JBoss Rich Faces SVN: r15814 - root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging.
by richfaces-svn-commits@lists.jboss.org
Author: Alex.Kolonitsky
Date: 2009-11-02 09:30:33 -0500 (Mon, 02 Nov 2009)
New Revision: 15814
Modified:
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcePath.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcePath.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcePath.java 2009-11-02 14:22:28 UTC (rev 15813)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcePath.java 2009-11-02 14:30:33 UTC (rev 15814)
@@ -12,13 +12,13 @@
*
*/
public class ServerResourcePath {
+ public static final Pattern SLASH = Pattern.compile("/");
+
public static final ServerResourcePath WEB_INF = new ServerResourcePath("/WEB-INF/");
public static final ServerResourcePath META_INF = new ServerResourcePath("/META-INF/");
public static final ServerResourcePath WEB_XML = new ServerResourcePath("/WEB-INF/web.xml");
public static final ServerResourcePath FACES_CONFIG = new ServerResourcePath("/WEB-INF/faces-config.xml");
- private static final Pattern SLASH = Pattern.compile("/");
-
private final String[] pathElements;
/**
15 years, 10 months
JBoss Rich Faces SVN: r15813 - in branches/community/3.3.X/samples/richfaces-demo/src/main: java/org/richfaces/demo/dataTableScroller and 2 other directories.
by richfaces-svn-commits@lists.jboss.org
Author: ilya_shaikovsky
Date: 2009-11-02 09:22:28 -0500 (Mon, 02 Nov 2009)
New Revision: 15813
Added:
branches/community/3.3.X/samples/richfaces-demo/src/main/java/org/richfaces/demo/dataTableScroller/DataScrollerBean.java
Modified:
branches/community/3.3.X/samples/richfaces-demo/src/main/java/org/richfaces/datatablescroller/DataTableScrollerBean.java
branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/WEB-INF/faces-config.xml
branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTableScroller/examples/customScroller.xhtml
branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTableScroller/examples/simpleScroller.xhtml
Log:
refactoring according to https://jira.jboss.org/jira/browse/RF-7934
Modified: branches/community/3.3.X/samples/richfaces-demo/src/main/java/org/richfaces/datatablescroller/DataTableScrollerBean.java
===================================================================
--- branches/community/3.3.X/samples/richfaces-demo/src/main/java/org/richfaces/datatablescroller/DataTableScrollerBean.java 2009-11-02 13:13:21 UTC (rev 15812)
+++ branches/community/3.3.X/samples/richfaces-demo/src/main/java/org/richfaces/datatablescroller/DataTableScrollerBean.java 2009-11-02 14:22:28 UTC (rev 15813)
@@ -14,7 +14,6 @@
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
-import javax.faces.model.SelectItem;
import org.richfaces.component.UIScrollableDataTable;
import org.richfaces.demo.datafilterslider.DemoInventoryItem;
@@ -30,16 +29,6 @@
private DemoInventoryItem currentItem = new DemoInventoryItem();
- private int rows = 10;
-
- public int getRows() {
- return rows;
- }
-
- public void setRows(int rows) {
- this.rows = rows;
- }
-
public void fetchCurrentRow(ActionEvent event) {
String vin=(FacesContext.getCurrentInstance().
getExternalContext().getRequestParameterMap().get("vin"));
@@ -63,7 +52,6 @@
private SortOrder order = new SortOrder();
- private int scrollerPage=1;
private ArrayList<DemoInventoryItem[]> model = null;
@@ -133,17 +121,6 @@
return allCars;
}
- public List<SelectItem> getPagesToScroll() {
- List<SelectItem> list = new ArrayList<SelectItem>();
- for (int i = 1; i <= allCars.size() / getRows()+1; i++) {
- if (Math.abs(i - scrollerPage) < 5) {
- SelectItem item = new SelectItem(i);
- list.add(item);
- }
- }
- return list;
- }
-
public List<DemoInventoryItem> getTenRandomCars() {
List<DemoInventoryItem> result = new ArrayList<DemoInventoryItem>();
int size = getAllCars().size() - 1;
@@ -314,14 +291,6 @@
return columns;
}
- public int getScrollerPage() {
- return scrollerPage;
- }
-
- public void setScrollerPage(int scrollerPage) {
- this.scrollerPage = scrollerPage;
- }
-
public SortOrder getOrder() {
return order;
}
Added: branches/community/3.3.X/samples/richfaces-demo/src/main/java/org/richfaces/demo/dataTableScroller/DataScrollerBean.java
===================================================================
--- branches/community/3.3.X/samples/richfaces-demo/src/main/java/org/richfaces/demo/dataTableScroller/DataScrollerBean.java (rev 0)
+++ branches/community/3.3.X/samples/richfaces-demo/src/main/java/org/richfaces/demo/dataTableScroller/DataScrollerBean.java 2009-11-02 14:22:28 UTC (rev 15813)
@@ -0,0 +1,49 @@
+package org.richfaces.demo.dataTableScroller;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.faces.model.SelectItem;
+
+public class DataScrollerBean {
+
+ private int rows = 10;
+ private int scrollerPage=1;
+ private int size;
+
+ public int getRows() {
+ return rows;
+ }
+
+ public void setRows(int rows) {
+ this.rows = rows;
+ }
+
+ public List<SelectItem> getPagesToScroll() {
+ List<SelectItem> list = new ArrayList<SelectItem>();
+ for (int i = 1; i <= size / getRows()+1; i++) {
+ if (Math.abs(i - scrollerPage) < 5) {
+ SelectItem item = new SelectItem(i);
+ list.add(item);
+ }
+ }
+ return list;
+ }
+
+ public int getScrollerPage() {
+ return scrollerPage;
+ }
+
+ public void setScrollerPage(int scrollerPage) {
+ this.scrollerPage = scrollerPage;
+ }
+
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+
+}
Modified: branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/WEB-INF/faces-config.xml
===================================================================
--- branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/WEB-INF/faces-config.xml 2009-11-02 13:13:21 UTC (rev 15812)
+++ branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/WEB-INF/faces-config.xml 2009-11-02 14:22:28 UTC (rev 15813)
@@ -130,6 +130,15 @@
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
+ <managed-bean-name>dataScrollerBean</managed-bean-name>
+ <managed-bean-class>org.richfaces.demo.dataTableScroller.DataScrollerBean</managed-bean-class>
+ <managed-bean-scope>request</managed-bean-scope>
+ <managed-property>
+ <property-name>size</property-name>
+ <value>#{dataTableScrollerBean.allCars.size()}</value>
+ </managed-property>
+ </managed-bean>
+ <managed-bean>
<managed-bean-name>toggleBean</managed-bean-name>
<managed-bean-class>org.richfaces.demo.togglePanel.ToggleBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
Modified: branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTableScroller/examples/customScroller.xhtml
===================================================================
--- branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTableScroller/examples/customScroller.xhtml 2009-11-02 13:13:21 UTC (rev 15812)
+++ branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTableScroller/examples/customScroller.xhtml 2009-11-02 14:22:28 UTC (rev 15813)
@@ -10,9 +10,10 @@
padding-left: 10px;
}
</style>
+ <a4j:keepAlive beanName="dataScrollerBean" ajaxOnly="true"/>
<h:form>
<rich:dataTable width="483" id="carList"
- rows="#{dataTableScrollerBean.rows}" columnClasses="col"
+ rows="#{dataScrollerBean.rows}" columnClasses="col"
value="#{dataTableScrollerBean.allCars}" var="category">
<f:facet name="header">
<rich:columnGroup>
@@ -44,7 +45,7 @@
</rich:column>
<f:facet name="footer">
<rich:datascroller maxPages="20" fastControls="hide"
- page="#{dataTableScrollerBean.scrollerPage}" pagesVar="pages"
+ page="#{dataScrollerBean.scrollerPage}" pagesVar="pages"
id="ds">
<f:facet name="first">
<h:outputText value="First" styleClass="scrollerCell" />
@@ -73,9 +74,9 @@
<f:facet name="pages">
<h:panelGroup>
<h:outputText value="Page "/>
- <h:selectOneMenu value="#{dataTableScrollerBean.scrollerPage}"
+ <h:selectOneMenu value="#{dataScrollerBean.scrollerPage}"
onchange="#{rich:component('ds')}.switchToPage(this.value)">
- <f:selectItems value="#{dataTableScrollerBean.pagesToScroll}" />
+ <f:selectItems value="#{dataScrollerBean.pagesToScroll}" />
</h:selectOneMenu>
<h:outputText value=" of #{pages}" />
</h:panelGroup>
Modified: branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTableScroller/examples/simpleScroller.xhtml
===================================================================
--- branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTableScroller/examples/simpleScroller.xhtml 2009-11-02 13:13:21 UTC (rev 15812)
+++ branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTableScroller/examples/simpleScroller.xhtml 2009-11-02 14:22:28 UTC (rev 15813)
@@ -10,10 +10,10 @@
width: 100px;
}
</style>
-
+ <a4j:keepAlive beanName="dataScrollerBean" ajaxOnly="true"/>
<h:form>
<rich:datascroller align="left" for="carList" maxPages="20"
- page="#{dataTableScrollerBean.scrollerPage}" reRender="sc2" id="sc1" />
+ page="#{dataScrollerBean.scrollerPage}" reRender="sc2" id="sc1" />
<rich:spacer height="30" />
<rich:dataTable width="483" id="carList" rows="10" columnClasses="col"
value="#{dataTableScrollerBean.allCars}" var="category">
@@ -51,7 +51,7 @@
</rich:dataTable>
<rich:datascroller align="left" for="carList" maxPages="20"
- page="#{dataTableScrollerBean.scrollerPage}" id="sc2" reRender="sc1" />
+ page="#{dataScrollerBean.scrollerPage}" id="sc2" reRender="sc1" />
</h:form>
</ui:composition>
\ No newline at end of file
15 years, 10 months
JBoss Rich Faces SVN: r15812 - branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTable.
by richfaces-svn-commits@lists.jboss.org
Author: ilya_shaikovsky
Date: 2009-11-02 08:13:21 -0500 (Mon, 02 Nov 2009)
New Revision: 15812
Modified:
branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTable/modifiableModel.xhtml
Log:
https://jira.jboss.org/jira/browse/RF-7978
Modified: branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTable/modifiableModel.xhtml
===================================================================
--- branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTable/modifiableModel.xhtml 2009-11-02 13:12:53 UTC (rev 15811)
+++ branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/dataTable/modifiableModel.xhtml 2009-11-02 13:13:21 UTC (rev 15812)
@@ -12,7 +12,7 @@
how to implement <b>sorting and filtering in your model</b>.
</p>
<p>
- Model class should extend <b>ExtendedDataTableModel</b> and additionally implement
+ Model class should extend <b>ExtendedDataModel</b> and additionally implement
<b>Modifiable interface</b>. This interface defines <b>modify</b> method. This
method is called with lists of sort and filter fields as parameters and should perform sorting and
filtering according to the fields.
15 years, 10 months
JBoss Rich Faces SVN: r15811 - root/framework/trunk/impl/src/main/java/org/richfaces/resource.
by richfaces-svn-commits@lists.jboss.org
Author: Alex.Kolonitsky
Date: 2009-11-02 08:12:53 -0500 (Mon, 02 Nov 2009)
New Revision: 15811
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource2.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource2.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource2.java 2009-11-02 13:05:00 UTC (rev 15810)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource2.java 2009-11-02 13:12:53 UTC (rev 15811)
@@ -40,60 +40,60 @@
private static final int MASK_FOR_COLOR_WITHOUT_ALPHA_CHANNEL = 0x00FFFFFF;
- private Color color;
-
+ private Color color;
+
private Dimension dimension = new Dimension(20, 150);
public TestResource2() {
- super(ImageType.PNG);
- FacesContext context = FacesContext.getCurrentInstance();
- Skin skin = SkinFactory.getInstance().getSkin(context);
- Object parameter = skin.getParameter(context, Skin.HEADER_GRADIENT_COLOR);
- this.color = HtmlColor.decode(parameter.toString());
- }
-
- @Override
- protected void paint(Graphics2D graphics2d, Dimension dim) {
- super.paint(graphics2d, dim);
-
- graphics2d.setPaint(new GradientPaint(0, 0, Color.WHITE, dim.width, dim.height, color));
- graphics2d.fillRect(0, 0, dim.width, dim.height);
- }
+ super(ImageType.PNG);
+ FacesContext context = FacesContext.getCurrentInstance();
+ Skin skin = SkinFactory.getInstance().getSkin(context);
+ Object parameter = skin.getParameter(context, Skin.HEADER_GRADIENT_COLOR);
+ this.color = HtmlColor.decode(parameter.toString());
+ }
- @Override
- protected void readState(FacesContext context, NumericDataInputStream stream) {
- super.readState(context, stream);
- this.color = stream.readColor();
- }
-
- @Override
- protected void writeState(FacesContext context,
- NumericDataOutputStream stream) {
- super.writeState(context, stream);
- stream.writeColor(this.color);
- }
-
- @Override
- public String getEntityTag(FacesContext context) {
- return ResourceUtils.formatWeakTag(getColorWitoutAlphaChanel());
- }
+ @Override
+ protected void paint(Graphics2D graphics2d, Dimension dim) {
+ super.paint(graphics2d, dim);
+ graphics2d.setPaint(new GradientPaint(0, 0, Color.WHITE, dim.width, dim.height, color));
+ graphics2d.fillRect(0, 0, dim.width, dim.height);
+ }
+
+ @Override
+ protected void readState(FacesContext context, NumericDataInputStream stream) {
+ super.readState(context, stream);
+ this.color = stream.readColor();
+ }
+
+ @Override
+ protected void writeState(FacesContext context,
+ NumericDataOutputStream stream) {
+ super.writeState(context, stream);
+ stream.writeColor(this.color);
+ }
+
+ @Override
+ public String getEntityTag(FacesContext context) {
+ return ResourceUtils.formatWeakTag(getColorWitoutAlphaChanel());
+ }
+
private String getColorWitoutAlphaChanel() {
return Integer.toHexString(color.getRGB() & MASK_FOR_COLOR_WITHOUT_ALPHA_CHANNEL);
}
@Override
- public String getVersion() {
- return VersionBean._version.getResourceVersion();
- }
+ public String getVersion() {
+ return VersionBean.VERSION.getResourceVersion();
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.resource.Java2Dresource#getDimension()
- */
- @Override
- public Dimension getDimension() {
- return dimension;
- }
+ /* (non-Javadoc)
+ * @see org.ajax4jsf.resource.Java2Dresource#getDimension()
+ */
+ @Override
+ public Dimension getDimension() {
+ return dimension;
+ }
public Color getColor() {
return color;
15 years, 10 months
JBoss Rich Faces SVN: r15810 - in branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push: examples and 1 other directory.
by richfaces-svn-commits@lists.jboss.org
Author: ilya_shaikovsky
Date: 2009-11-02 08:05:00 -0500 (Mon, 02 Nov 2009)
New Revision: 15810
Modified:
branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push/choices.xhtml
branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push/examples/choices.xhtml
Log:
https://jira.jboss.org/jira/browse/RF-7993
+ minor syntax correction.
Modified: branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push/choices.xhtml
===================================================================
--- branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push/choices.xhtml 2009-11-02 12:14:26 UTC (rev 15809)
+++ branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push/choices.xhtml 2009-11-02 13:05:00 UTC (rev 15810)
@@ -18,7 +18,7 @@
<div class="sample-container">
<ui:include src="/richfaces/push/examples/choices.xhtml"/>
<ui:include src="/templates/include/sourceview.xhtml">
- <ui:param name="sourcepath" value="/richfaces/dataTable/examples/choices.xhtml"/>
+ <ui:param name="sourcepath" value="/richfaces/push/examples/choices.xhtml"/>
</ui:include>
<ui:include src="/templates/include/sourceview.xhtml">
<ui:param name="sourcepath" value="/WEB-INF/src/org/richfaces/demo/datatable/Choice.java"/>
Modified: branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push/examples/choices.xhtml
===================================================================
--- branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push/examples/choices.xhtml 2009-11-02 12:14:26 UTC (rev 15809)
+++ branches/community/3.3.X/samples/richfaces-demo/src/main/webapp/richfaces/push/examples/choices.xhtml 2009-11-02 13:05:00 UTC (rev 15810)
@@ -14,14 +14,14 @@
background-image: none;
}
</style>
- <h:form id="choisesForm">
+ <h:form id="choicesForm">
<rich:jQuery selector=".votesClass"
query="each(function(key){
if (param[key].votesCount > 0) jQuery(this).addClass('highlight');
else jQuery(this).removeClass('highlight'); })"
name="jqhighlight" />
<rich:dataTable value="#{choicesBean.choices}" var="choice"
- rowKeyVar="row" ajaxKeys="#{choicesBean.keysSet}" id="choises">
+ rowKeyVar="row" ajaxKeys="#{choicesBean.keysSet}" id="choices">
<f:facet name="header">
<h:outputText value="Voting for favourite fruit" />
</f:facet>
15 years, 10 months
JBoss Rich Faces SVN: r15809 - in root/ui-sandbox/trunk/components: core/src/main/java/org/richfaces/renderkit/html/gradientimages and 1 other directories.
by richfaces-svn-commits@lists.jboss.org
Author: Alex.Kolonitsky
Date: 2009-11-02 07:14:26 -0500 (Mon, 02 Nov 2009)
New Revision: 15809
Modified:
root/ui-sandbox/trunk/components/common/src/main/java/org/richfaces/renderkit/html/images/ComboBoxButtonPressGradient.java
root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/HeaderGradientImage.java
root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/HeaderInverseGradientImage.java
root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/InputGradientImage.java
root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/TabGradientImage.java
root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/TabInverseGradientImage.java
root/ui-sandbox/trunk/components/tables/ui/src/main/java/org/richfaces/renderkit/AbstractRowsRenderer.java
root/ui-sandbox/trunk/components/tables/ui/src/main/java/org/richfaces/renderkit/SimpleDataTableRendererBase.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195
Modified: root/ui-sandbox/trunk/components/common/src/main/java/org/richfaces/renderkit/html/images/ComboBoxButtonPressGradient.java
===================================================================
--- root/ui-sandbox/trunk/components/common/src/main/java/org/richfaces/renderkit/html/images/ComboBoxButtonPressGradient.java 2009-11-02 12:12:01 UTC (rev 15808)
+++ root/ui-sandbox/trunk/components/common/src/main/java/org/richfaces/renderkit/html/images/ComboBoxButtonPressGradient.java 2009-11-02 12:14:26 UTC (rev 15809)
@@ -30,7 +30,7 @@
public class ComboBoxButtonPressGradient extends BaseGradient{
public ComboBoxButtonPressGradient() {
- super(7,15 , 9, Skin.headerBackgroundColor, "headerGradientColor");
+ super(7,15 , 9, Skin.HEADER_BACKGROUND_COLOR, "headerGradientColor");
}
}
Modified: root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/HeaderGradientImage.java
===================================================================
--- root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/HeaderGradientImage.java 2009-11-02 12:12:01 UTC (rev 15808)
+++ root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/HeaderGradientImage.java 2009-11-02 12:14:26 UTC (rev 15809)
@@ -27,7 +27,7 @@
public class HeaderGradientImage extends BaseControlBackgroundImage {
public HeaderGradientImage() {
- super(Skin.headerGradientColor, Skin.headerBackgroundColor, 8);
+ super(Skin.HEADER_GRADIENT_COLOR, Skin.HEADER_BACKGROUND_COLOR, 8);
}
}
Modified: root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/HeaderInverseGradientImage.java
===================================================================
--- root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/HeaderInverseGradientImage.java 2009-11-02 12:12:01 UTC (rev 15808)
+++ root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/HeaderInverseGradientImage.java 2009-11-02 12:14:26 UTC (rev 15809)
@@ -27,7 +27,7 @@
public class HeaderInverseGradientImage extends BaseControlBackgroundImage {
public HeaderInverseGradientImage() {
- super(Skin.headerBackgroundColor, Skin.headerGradientColor, 8);
+ super(Skin.HEADER_BACKGROUND_COLOR, Skin.HEADER_GRADIENT_COLOR, 8);
}
}
Modified: root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/InputGradientImage.java
===================================================================
--- root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/InputGradientImage.java 2009-11-02 12:12:01 UTC (rev 15808)
+++ root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/InputGradientImage.java 2009-11-02 12:14:26 UTC (rev 15809)
@@ -27,7 +27,7 @@
public class InputGradientImage extends BaseControlBackgroundImage {
public InputGradientImage() {
- super(Skin.additionalBackgroundColor, Skin.controlBackgroundColor, 8);
+ super(Skin.additionalBackgroundColor, Skin.CONTROL_BACKGROUND_COLOR, 8);
}
}
Modified: root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/TabGradientImage.java
===================================================================
--- root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/TabGradientImage.java 2009-11-02 12:12:01 UTC (rev 15808)
+++ root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/TabGradientImage.java 2009-11-02 12:14:26 UTC (rev 15809)
@@ -27,7 +27,7 @@
public class TabGradientImage extends BaseControlBackgroundImage {
public TabGradientImage() {
- super("tabBackgroundColor", Skin.generalBackgroundColor, 8);
+ super("tabBackgroundColor", Skin.GENERAL_BACKGROUND_COLOR, 8);
}
}
Modified: root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/TabInverseGradientImage.java
===================================================================
--- root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/TabInverseGradientImage.java 2009-11-02 12:12:01 UTC (rev 15808)
+++ root/ui-sandbox/trunk/components/core/src/main/java/org/richfaces/renderkit/html/gradientimages/TabInverseGradientImage.java 2009-11-02 12:14:26 UTC (rev 15809)
@@ -27,7 +27,7 @@
public class TabInverseGradientImage extends BaseControlBackgroundImage {
public TabInverseGradientImage() {
- super(Skin.generalBackgroundColor, "tabBackgroundColor", 8);
+ super(Skin.GENERAL_BACKGROUND_COLOR, "tabBackgroundColor", 8);
}
}
Modified: root/ui-sandbox/trunk/components/tables/ui/src/main/java/org/richfaces/renderkit/AbstractRowsRenderer.java
===================================================================
--- root/ui-sandbox/trunk/components/tables/ui/src/main/java/org/richfaces/renderkit/AbstractRowsRenderer.java 2009-11-02 12:12:01 UTC (rev 15808)
+++ root/ui-sandbox/trunk/components/tables/ui/src/main/java/org/richfaces/renderkit/AbstractRowsRenderer.java 2009-11-02 12:14:26 UTC (rev 15809)
@@ -182,7 +182,7 @@
styleClass.append(custom);
}
if (styleClass.length() > 0) {
- writer.writeAttribute(HTML.class_ATTRIBUTE, styleClass, "styleClass");
+ writer.writeAttribute(HTML.CLASS_ATTRIBUTE, styleClass, "styleClass");
}
}
Modified: root/ui-sandbox/trunk/components/tables/ui/src/main/java/org/richfaces/renderkit/SimpleDataTableRendererBase.java
===================================================================
--- root/ui-sandbox/trunk/components/tables/ui/src/main/java/org/richfaces/renderkit/SimpleDataTableRendererBase.java 2009-11-02 12:12:01 UTC (rev 15808)
+++ root/ui-sandbox/trunk/components/tables/ui/src/main/java/org/richfaces/renderkit/SimpleDataTableRendererBase.java 2009-11-02 12:14:26 UTC (rev 15809)
@@ -16,124 +16,124 @@
import org.richfaces.component.UISubTable;
@ResourceDependencies({
- @ResourceDependency(name = "simple-datatable.js"),
- @ResourceDependency(name = "simple-table.css")
+ @ResourceDependency(name = "simple-datatable.js"),
+ @ResourceDependency(name = "simple-table.css")
})
public abstract class SimpleDataTableRendererBase extends AbstractTableRenderer {
-
- public void encodeRowStart(RowEncodeEvent event) throws IOException {
- ResponseWriter writer = event.getContext().getResponseWriter();
- writer.startElement(HTML.TR_ELEMENT, event.getSource());
- }
-
- public void encodeRowEnd(RowEncodeEvent event) throws IOException {
- ResponseWriter writer = event.getContext().getResponseWriter();
- writer.endElement(HTML.TR_ELEMENT);
- }
-
- public void encodeFirstRow(RowEncodeEvent event)throws IOException {
- ResponseWriter writer = event.getContext().getResponseWriter();
- writer.startElement(HTML.TR_ELEMENT, event.getSource());
- }
-
- public void encodeCell(CellEncodeEvent event) throws IOException {
- ResponseWriter writer = event.getContext().getResponseWriter();
- FacesContext context = event.getContext();
- UIColumn column = event.getSource();
-
- writer.startElement(HTML.td_ELEM, column);
- getUtils().encodeId(context, column);
- getCellStyleClasses(context, column);
- renderChildren(context, column);
-
- writer.endElement(HTML.td_ELEM);
- }
-
- public void encodeHeaderCell(CellEncodeEvent event) throws IOException {
- ResponseWriter writer = event.getContext().getResponseWriter();
- FacesContext context = event.getContext();
- UIColumn column = event.getSource();
-
- writer.startElement(HTML.th_ELEM, column);
- //TODO --- move to the separate method
- getUtils().encodeId(context, column);
- getCellStyleClasses(context, column);
- renderChildren(context, column);
- //------
- writer.endElement(HTML.th_ELEM);
- }
-
- @Override
- public RowEncoder getRowEncoder(TableHolder holder) {
- RowEncoder encoder = new RowEncoder();
- encoder.setListener(this);
- return encoder;
- }
-
- public void encodeSubTable(FacesContext context, UISubTable subTable) throws IOException {
- encodeRows(context, subTable);
- }
-
- // ---------------------------------------------------------------------------------------
-
- public void encodeTableStructure(FacesContext context, UIDataTable table) throws IOException{
-
- Object key = table.getRowKey();
- table.captureOrigValue(context);
- table.setRowKey(context, null);
-
- encodeCaption(context, table);
-
- // Encode colgroup definition.
- ResponseWriter writer = context.getResponseWriter();
- writer.startElement("colgroup", table);
-
- int columns = getColumnsCount(table);
-
- writer.writeAttribute("span", String.valueOf(columns), null);
- String columnsWidth = (String) table.getAttributes().get("columnsWidth");
-
- if (null != columnsWidth) {
- String[] widths = columnsWidth.split(",");
- for (int i = 0; i < widths.length; i++) {
- writer.startElement("col", table);
- writer.writeAttribute("width", widths[i], null);
- writer.endElement("col");
- }
- }
- writer.endElement("colgroup");
- encodeHeader(context, table, columns);
- encodeFooter(context, table, columns);
-
- table.setRowKey(context,key);
- table.restoreOrigValue(context);
- }
-
- public void encodeCaption(FacesContext context, UIDataTable table) throws IOException {
-
- UIComponent caption = table.getCaption();
- if (caption == null) {
- return;
- }
+ public void encodeRowStart(RowEncodeEvent event) throws IOException {
+ ResponseWriter writer = event.getContext().getResponseWriter();
+ writer.startElement(HTML.TR_ELEMENT, event.getSource());
+ }
+ public void encodeRowEnd(RowEncodeEvent event) throws IOException {
+ ResponseWriter writer = event.getContext().getResponseWriter();
+ writer.endElement(HTML.TR_ELEMENT);
+ }
+
+ public void encodeFirstRow(RowEncodeEvent event) throws IOException {
+ ResponseWriter writer = event.getContext().getResponseWriter();
+ writer.startElement(HTML.TR_ELEMENT, event.getSource());
+ }
+
+ public void encodeCell(CellEncodeEvent event) throws IOException {
+ ResponseWriter writer = event.getContext().getResponseWriter();
+ FacesContext context = event.getContext();
+ UIColumn column = event.getSource();
+
+ writer.startElement(HTML.TD_ELEM, column);
+ getUtils().encodeId(context, column);
+ getCellStyleClasses(context, column);
+ renderChildren(context, column);
+
+ writer.endElement(HTML.TD_ELEM);
+ }
+
+ public void encodeHeaderCell(CellEncodeEvent event) throws IOException {
+ ResponseWriter writer = event.getContext().getResponseWriter();
+ FacesContext context = event.getContext();
+ UIColumn column = event.getSource();
+
+ writer.startElement(HTML.TH_ELEM, column);
+ //TODO --- move to the separate method
+ getUtils().encodeId(context, column);
+ getCellStyleClasses(context, column);
+ renderChildren(context, column);
+ //------
+ writer.endElement(HTML.TH_ELEM);
+ }
+
+ @Override
+ public RowEncoder getRowEncoder(TableHolder holder) {
+ RowEncoder encoder = new RowEncoder();
+ encoder.setListener(this);
+ return encoder;
+ }
+
+ public void encodeSubTable(FacesContext context, UISubTable subTable) throws IOException {
+ encodeRows(context, subTable);
+ }
+
+ // ---------------------------------------------------------------------------------------
+
+ public void encodeTableStructure(FacesContext context, UIDataTable table) throws IOException {
+
+ Object key = table.getRowKey();
+ table.captureOrigValue(context);
+ table.setRowKey(context, null);
+
+ encodeCaption(context, table);
+
+ // Encode colgroup definition.
ResponseWriter writer = context.getResponseWriter();
- writer.startElement("caption", table);
+ writer.startElement("colgroup", table);
- String captionClass = (String) table.getAttributes().get("captionClass");
- captionClass = captionClass != null ? "rich-table-caption " + captionClass : "rich-table-caption";
- writer.writeAttribute("class", captionClass, "captionClass");
-
+ int columns = getColumnsCount(table);
+
+ writer.writeAttribute("span", String.valueOf(columns), null);
+ String columnsWidth = (String) table.getAttributes().get("columnsWidth");
+
+ if (null != columnsWidth) {
+ String[] widths = columnsWidth.split(",");
+ for (int i = 0; i < widths.length; i++) {
+ writer.startElement("col", table);
+ writer.writeAttribute("width", widths[i], null);
+ writer.endElement("col");
+ }
+ }
+ writer.endElement("colgroup");
+
+ encodeHeader(context, table, columns);
+ encodeFooter(context, table, columns);
+
+ table.setRowKey(context, key);
+ table.restoreOrigValue(context);
+ }
+
+ public void encodeCaption(FacesContext context, UIDataTable table) throws IOException {
+
+ UIComponent caption = table.getCaption();
+ if (caption == null) {
+ return;
+ }
+
+ ResponseWriter writer = context.getResponseWriter();
+ writer.startElement("caption", table);
+
+ String captionClass = (String) table.getAttributes().get("captionClass");
+ captionClass = captionClass != null ? "rich-table-caption " + captionClass : "rich-table-caption";
+ writer.writeAttribute("class", captionClass, "captionClass");
+
String captionStyle = (String) table.getAttributes().get("captionStyle");
- if (captionStyle != null) {
- writer.writeAttribute("style", captionStyle, "captionStyle");
- }
-
- renderChild(context, caption);
-
- writer.endElement("caption");
-
- }
+ if (captionStyle != null) {
+ writer.writeAttribute("style", captionStyle, "captionStyle");
+ }
+
+ renderChild(context, caption);
+
+ writer.endElement("caption");
+
+ }
/*
@Override
public void encodeCell(FacesContext context, UIComponent component) throws IOException {
@@ -145,185 +145,191 @@
}
*/
-
- public void encodeHeader(FacesContext context, UIDataTable table, int columns) throws IOException {
- UIComponent header = table.getHeader();
- boolean isEncodeHeaders = isEncodeHeaders(table);
- if (header != null || isEncodeHeaders) {
-
- ResponseWriter writer = context.getResponseWriter();
- writer.startElement("thead", table);
- writer.writeAttribute(HTML.class_ATTRIBUTE, "rich-table-thead", null);
- String headerClass = (String) table.getAttributes().get("headerClass");
-
- if (header != null) {
- encodeTableHeaderFacet(context, columns, writer, header,
- "rich-table-header",
- "rich-table-header-continue",
- "rich-table-headercell",
- headerClass, "th");
- }
+ public void encodeHeader(FacesContext context, UIDataTable table, int columns) throws IOException {
+ UIComponent header = table.getHeader();
+ boolean isEncodeHeaders = isEncodeHeaders(table);
- if (isEncodeHeaders) {
- writer.startElement("tr", table);
- encodeStyleClass(writer, null, "rich-table-subheader", null, headerClass);
- encodeHeaderFacets(context, writer, table.columns(), "rich-table-subheadercell", headerClass, "header", "th", columns);
- writer.endElement("tr");
- }
-
- writer.endElement("thead");
- }
- }
-
- public void encodeFooter(FacesContext context, UIDataTable table, int columns) throws IOException {
- ResponseWriter writer = context.getResponseWriter();
- Iterator<UIComponent> tableColumns = table.columns();
+ if (header != null || isEncodeHeaders) {
- UIComponent footer = table.getFooter();
- boolean columnFacetPresent = isColumnFacetPresent(table,"footer");
-
- if (footer != null || columnFacetPresent) {
- writer.startElement("tfoot", table);
- String footerClass = (String) table.getAttributes().get("footerClass");
+ ResponseWriter writer = context.getResponseWriter();
+ writer.startElement("thead", table);
+ writer.writeAttribute(HTML.CLASS_ATTRIBUTE, "rich-table-thead", null);
+ String headerClass = (String) table.getAttributes().get("headerClass");
- if (columnFacetPresent) {
- writer.startElement("tr", table);
- encodeStyleClass(writer, null, "rich-table-subfooter", null, footerClass);
- encodeHeaderFacets(context, writer, tableColumns, "rich-table-subfootercell", footerClass, "footer", "td",columns);
- writer.endElement("tr");
- }
-
- if (footer != null) {
- encodeTableHeaderFacet(context, columns, writer, footer,
- "rich-table-footer",
- "rich-table-footer-continue",
- "rich-table-footercell",
- footerClass, "td");
- }
- writer.endElement("tfoot");
- }
- }
-
- protected void encodeTableHeaderFacet(FacesContext context, int columns, ResponseWriter writer, UIComponent footer, String skinFirstRowClass, String skinRowClass, String skinCellClass, String footerClass, String element) throws IOException {
- boolean isColgroup = footer instanceof Row;
-
- if (!isColgroup) {
- writer.startElement("tr", footer);
- encodeStyleClass(writer, null, skinFirstRowClass, footerClass, null);
- writer.startElement(element, footer);
- encodeStyleClass(writer, null, skinCellClass, footerClass, null);
-
- if (columns > 0) {
- writer.writeAttribute("colspan", String.valueOf(columns), null);
- }
-
- writer.writeAttribute("scope", "colgroup", null);
- }
-
- if(isColgroup) {
- RowEncoder encoder = getRowEncoder(null);
- encoder.setHeader(true);
- encoder.encodeRows(context, footer);
- } else {
- renderChild(context, footer);
- }
-
- if (!isColgroup) {
- writer.endElement(element);
- writer.endElement("tr");
- }
- }
-
- protected void encodeHeaderFacets(FacesContext context, ResponseWriter writer, Iterator<UIComponent> headers,
- String skinCellClass, String headerClass, String facetName, String element, int colCount) throws IOException {
- int t_colCount = 0;
+ if (header != null) {
+ encodeTableHeaderFacet(context, columns, writer, header,
+ "rich-table-header",
+ "rich-table-header-continue",
+ "rich-table-headercell",
+ headerClass, "th");
+ }
- // HeaderEncodeStrategy richEncodeStrategy = new
- // RichHeaderEncodeStrategy();
- // HeaderEncodeStrategy simpleEncodeStrategy = new
- // SimpleHeaderEncodeStrategy();
+ if (isEncodeHeaders) {
+ writer.startElement("tr", table);
+ encodeStyleClass(writer, null, "rich-table-subheader", null, headerClass);
+ encodeHeaderFacets(context, writer, table.columns(), "rich-table-subheadercell", headerClass, "header",
+ "th", columns);
+ writer.endElement("tr");
+ }
- while (headers.hasNext()) {
- UIComponent column = headers.next();
- if (!column.isRendered()) {
- continue;
- }
+ writer.endElement("thead");
+ }
+ }
- Integer colspan = (Integer) column.getAttributes().get("colspan");
- if (colspan != null && colspan.intValue() > 0) {
- t_colCount += colspan.intValue();
- } else {
- t_colCount++;
- }
+ public void encodeFooter(FacesContext context, UIDataTable table, int columns) throws IOException {
+ ResponseWriter writer = context.getResponseWriter();
+ Iterator<UIComponent> tableColumns = table.columns();
- if (t_colCount > colCount) {
- break;
- }
+ UIComponent footer = table.getFooter();
+ boolean columnFacetPresent = isColumnFacetPresent(table, "footer");
- String classAttribute = facetName + "Class";
- String columnHeaderClass = (String) column.getAttributes().get(classAttribute);
+ if (footer != null || columnFacetPresent) {
+ writer.startElement("tfoot", table);
+ String footerClass = (String) table.getAttributes().get("footerClass");
- writer.startElement(element, column);
- encodeStyleClass(writer, null, skinCellClass, headerClass,columnHeaderClass);
- writer.writeAttribute("scope", "col", null);
- getUtils().encodeAttribute(context, column, "colspan");
+ if (columnFacetPresent) {
+ writer.startElement("tr", table);
+ encodeStyleClass(writer, null, "rich-table-subfooter", null, footerClass);
+ encodeHeaderFacets(context, writer, tableColumns, "rich-table-subfootercell", footerClass, "footer",
+ "td", columns);
+ writer.endElement("tr");
+ }
- UIComponent facet = column.getFacet(facetName);
- if (facet != null && facet.isRendered()) {
- renderChild(context, facet);
- }
+ if (footer != null) {
+ encodeTableHeaderFacet(context, columns, writer, footer,
+ "rich-table-footer",
+ "rich-table-footer-continue",
+ "rich-table-footercell",
+ footerClass, "td");
+ }
+ writer.endElement("tfoot");
+ }
+ }
- writer.endElement(element);
- }
- }
-
- @Override
- public void encodeBodyBegin(FacesContext context, UIDataTable table) throws IOException {
- String clientId = table.getClientId(context);
- ResponseWriter writer = context.getResponseWriter();
- writer.startElement("tbody", table);
- writer.writeAttribute("id", clientId + ":tb", null);
- }
-
- @Override
- public void encodeBodyEnd(FacesContext context, UIDataTable table) throws IOException {
- ResponseWriter writer = context.getResponseWriter();
- writer.endElement("tbody");
- }
-
- protected String getRowSkinClasses(boolean firstColumn) {
- String rowSkinClass = getRowSkinClass();
- if (firstColumn) {
- String firstRowSkinClass = getFirstRowSkinClass();
- if (firstRowSkinClass != null && firstRowSkinClass.length() != 0) {
- rowSkinClass = (rowSkinClass != null && rowSkinClass.trim().length() != 0) ?
- rowSkinClass + " " + firstRowSkinClass : firstRowSkinClass;
- }
- }
-
- return rowSkinClass;
- }
+ protected void encodeTableHeaderFacet(FacesContext context, int columns, ResponseWriter writer, UIComponent footer,
+ String skinFirstRowClass, String skinRowClass, String skinCellClass, String footerClass, String element)
+ throws IOException {
+
+ boolean isColgroup = footer instanceof Row;
- /**
- * @return
- */
- protected String getRowSkinClass() {
- return "rich-table-row";
- }
+ if (!isColgroup) {
+ writer.startElement("tr", footer);
+ encodeStyleClass(writer, null, skinFirstRowClass, footerClass, null);
+ writer.startElement(element, footer);
+ encodeStyleClass(writer, null, skinCellClass, footerClass, null);
- /**
- * @return
- */
- protected String getFirstRowSkinClass() {
- return "rich-table-firstrow";
- }
+ if (columns > 0) {
+ writer.writeAttribute("colspan", String.valueOf(columns), null);
+ }
- /**
- * @return
- */
- protected String getCellSkinClass() {
- return "rich-table-cell";
- }
-
+ writer.writeAttribute("scope", "colgroup", null);
+ }
+
+ if (isColgroup) {
+ RowEncoder encoder = getRowEncoder(null);
+ encoder.setHeader(true);
+ encoder.encodeRows(context, footer);
+ } else {
+ renderChild(context, footer);
+ }
+
+ if (!isColgroup) {
+ writer.endElement(element);
+ writer.endElement("tr");
+ }
+ }
+
+ protected void encodeHeaderFacets(FacesContext context, ResponseWriter writer, Iterator<UIComponent> headers,
+ String skinCellClass, String headerClass, String facetName, String element, int colCount) throws IOException {
+
+ int tColCount = 0;
+
+ // HeaderEncodeStrategy richEncodeStrategy = new
+ // RichHeaderEncodeStrategy();
+ // HeaderEncodeStrategy simpleEncodeStrategy = new
+ // SimpleHeaderEncodeStrategy();
+
+ while (headers.hasNext()) {
+ UIComponent column = headers.next();
+ if (!column.isRendered()) {
+ continue;
+ }
+
+ Integer colspan = (Integer) column.getAttributes().get("colspan");
+ if (colspan != null && colspan.intValue() > 0) {
+ tColCount += colspan.intValue();
+ } else {
+ tColCount++;
+ }
+
+ if (tColCount > colCount) {
+ break;
+ }
+
+ String classAttribute = facetName + "Class";
+ String columnHeaderClass = (String) column.getAttributes().get(classAttribute);
+
+ writer.startElement(element, column);
+ encodeStyleClass(writer, null, skinCellClass, headerClass, columnHeaderClass);
+ writer.writeAttribute("scope", "col", null);
+ getUtils().encodeAttribute(context, column, "colspan");
+
+ UIComponent facet = column.getFacet(facetName);
+ if (facet != null && facet.isRendered()) {
+ renderChild(context, facet);
+ }
+
+ writer.endElement(element);
+ }
+ }
+
+ @Override
+ public void encodeBodyBegin(FacesContext context, UIDataTable table) throws IOException {
+ String clientId = table.getClientId(context);
+ ResponseWriter writer = context.getResponseWriter();
+ writer.startElement("tbody", table);
+ writer.writeAttribute("id", clientId + ":tb", null);
+ }
+
+ @Override
+ public void encodeBodyEnd(FacesContext context, UIDataTable table) throws IOException {
+ ResponseWriter writer = context.getResponseWriter();
+ writer.endElement("tbody");
+ }
+
+ protected String getRowSkinClasses(boolean firstColumn) {
+ String rowSkinClass = getRowSkinClass();
+ if (firstColumn) {
+ String firstRowSkinClass = getFirstRowSkinClass();
+ if (firstRowSkinClass != null && firstRowSkinClass.length() != 0) {
+ rowSkinClass = (rowSkinClass != null && rowSkinClass.trim().length() != 0)
+ ? rowSkinClass + " " + firstRowSkinClass : firstRowSkinClass;
+ }
+ }
+
+ return rowSkinClass;
+ }
+
+ /**
+ * @return
+ */
+ protected String getRowSkinClass() {
+ return "rich-table-row";
+ }
+
+ /**
+ * @return
+ */
+ protected String getFirstRowSkinClass() {
+ return "rich-table-firstrow";
+ }
+
+ /**
+ * @return
+ */
+ protected String getCellSkinClass() {
+ return "rich-table-cell";
+ }
+
}
15 years, 10 months
JBoss Rich Faces SVN: r15808 - in root/framework/trunk/test-base/src: main/java/org/richfaces/test/staging and 2 other directories.
by richfaces-svn-commits@lists.jboss.org
Author: Alex.Kolonitsky
Date: 2009-11-02 07:12:01 -0500 (Mon, 02 Nov 2009)
New Revision: 15808
Modified:
root/framework/trunk/test-base/src/main/java/org/richfaces/test/AbstractFacesTest.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/AbstractThreadedTest.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebClient.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebConnection.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebResponse.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/TestException.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/AbstractServerResource.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ClasspathServerResource.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/EventInvoker.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/FilterContainer.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/HttpMethod.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationErrorEvent.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationEvent.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationListener.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/NotImplementedException.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/PageContextExtension.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/RequestChain.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerLogger.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResource.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcePath.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcesDirectory.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServletContainer.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaggingJspApplicationContext.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaggingJspFactory.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingConnection.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpRequest.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpResponse.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpSession.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingInitialContextFactoryBuilder.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingServer.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingServletContext.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaticServlet.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/URLScanner.java
root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/UrlServerResource.java
root/framework/trunk/test-base/src/test/java/org/richfaces/test/FacesServerTest.java
root/framework/trunk/test-base/src/test/java/org/richfaces/test/HelloBean.java
root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServerResourcePathTest.java
root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServerResourceTest.java
root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServletTest.java
root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/UrlResourceLoadingTest.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/AbstractFacesTest.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/AbstractFacesTest.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/AbstractFacesTest.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,13 +1,16 @@
+
/**
- *
+ *
*/
package org.richfaces.test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+
import java.net.MalformedURLException;
import java.net.URL;
+
import java.util.EventListener;
import java.util.Locale;
import java.util.Properties;
@@ -27,310 +30,329 @@
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.webapp.FacesServlet;
+
import javax.servlet.Filter;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
+
import org.richfaces.test.staging.FilterContainer;
import org.richfaces.test.staging.ServletContainer;
import org.richfaces.test.staging.StagingConnection;
import org.richfaces.test.staging.StagingServer;
/**
- * Base class for all JSF test cases.
+ * Base class for all JSF test cases.
* @author asmirnov
- *
+ *
*/
public abstract class AbstractFacesTest extends TestCase {
- private ClassLoader contextClassLoader;
+ /**
+ * JSF {@link Application} instance. Populated by the default {@link #setUp()} method.
+ */
+ protected Application application;
- /**
- * Prepared test server instance. Populated by the default {@link #setUp()} method.
- */
- protected StagingServer facesServer;
+ /**
+ * Current virtual connection. This field populated by the {@link #setupWebContent()} method only.
+ */
+ protected StagingConnection connection;
+ private ClassLoader contextClassLoader;
- /**
- * Current virtual connection. This field populated by the {@link #setupWebContent()} method only.
- */
- protected StagingConnection connection;
+ /**
+ * Current {@link FacesContext} instance. This field populated by the {@link #setupWebContent()} method only.
+ */
+ protected FacesContext facesContext;
- /**
- * Current {@link FacesContext} instance. This field populated by the {@link #setupWebContent()} method only.
- */
- protected FacesContext facesContext;
+ /**
+ * Prepared test server instance. Populated by the default {@link #setUp()} method.
+ */
+ protected StagingServer facesServer;
- /**
- * JSF {@link Lifecycle} instance. Populated by the default {@link #setUp()} method.
- */
- protected Lifecycle lifecycle;
+ /**
+ * JSF {@link Lifecycle} instance. Populated by the default {@link #setUp()} method.
+ */
+ protected Lifecycle lifecycle;
- /**
- * JSF {@link Application} instance. Populated by the default {@link #setUp()} method.
- */
- protected Application application;
+ /**
+ * Setup staging server instance with JSF implementation. First, this method creates a local test instance
+ * and calls the other template method in the next sequence:
+ * <ol>
+ * <li>{@link #setupFacesServlet()}</li>
+ * <li>{@link #setupFacesListener()}</li>
+ * <li>{@link #setupJsfInitParameters()}</li>
+ * <li>{@link #setupWebContent()}</li>
+ * </ol>
+ * After them, test server is initialized as well as fields {@link #lifecycle} and {@link #application} populated.
+ * Also, if the resource "logging.properties" is exist in the test class package, The Java {@link LogManager} will
+ * be configured with its content.
+ * @throws java.lang.Exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ contextClassLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
- /**
- * Setup staging server instance with JSF implementation. First, this method creates a local test instance
- * and calls the other template method in the next sequence:
- * <ol>
- * <li>{@link #setupFacesServlet()}</li>
- * <li>{@link #setupFacesListener()}</li>
- * <li>{@link #setupJsfInitParameters()}</li>
- * <li>{@link #setupWebContent()}</li>
- * </ol>
- * After them, test server is initialized as well as fields {@link #lifecycle} and {@link #application} populated.
- * Also, if the resource "logging.properties" is exist in the test class package, The Java {@link LogManager} will be configured with its content.
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- contextClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(
- this.getClass().getClassLoader());
- InputStream stream = this.getClass().getResourceAsStream(
- "logging.properties");
- if (null != stream) {
- try {
- LogManager.getLogManager().readConfiguration(stream);
- } catch (Exception e) {
- // Ignore it.
- } finally {
- try {
- stream.close();
- } catch (IOException e) {
- // Ignore it.
- }
- }
- }
- facesServer = new StagingServer();
- setupFacesServlet();
- setupFacesListener();
- setupJsfInitParameters();
- setupWebContent();
- facesServer.init();
- ApplicationFactory applicationFactory = (ApplicationFactory) FactoryFinder
- .getFactory(FactoryFinder.APPLICATION_FACTORY);
- application = applicationFactory.getApplication();
- LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
- .getFactory(FactoryFinder.LIFECYCLE_FACTORY);
- lifecycle = lifecycleFactory
- .getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
- }
+ InputStream stream = this.getClass().getResourceAsStream("logging.properties");
- /**
- * This hook method called from the {@link #setUp()} should append JSF implementation
- * listener to the test server. Default version applends "com.sun.faces.config.ConfigureListener"
- * or "org.apache.myfaces.webapp.StartupServletContextListener" for the existed SUN RI or MyFaces implementation.
- * This metod also calls appropriate {@link #setupSunFaces()} or {@link #setupMyFaces()} methods.
- */
- protected void setupFacesListener() {
- EventListener listener = null;
- try {
- // Check Sun RI configuration listener class.
- Class<? extends EventListener> listenerClass = contextClassLoader
- .loadClass("com.sun.faces.config.ConfigureListener")
- .asSubclass(EventListener.class);
- listener = listenerClass.newInstance();
- setupSunFaces();
- } catch (ClassNotFoundException e) {
- // No JSF RI listener, check MyFaces.
- Class<? extends EventListener> listenerClass;
- try {
- listenerClass = contextClassLoader
- .loadClass(
- "org.apache.myfaces.webapp.StartupServletContextListener")
- .asSubclass(EventListener.class);
- listener = listenerClass.newInstance();
- setupMyFaces();
- } catch (ClassNotFoundException e1) {
- throw new TestException("No JSF listeners have been found", e1);
- } catch (Exception e2) {
- throw new TestException("Error instantiate MyFaces listener",
- e2);
- }
- } catch (Exception e) {
- throw new TestException("Error instantiate JSF RI listener", e);
- }
- facesServer.addWebListener(listener);
- }
+ if (null != stream) {
+ try {
+ LogManager.getLogManager().readConfiguration(stream);
+ } catch (Exception e) {
- /**
- * This template method called from {@link #setUp()} to create {@link FacesServlet} instance.
- * The default implementation also tests presense of the "org.ajax4jsf.Filter" class.
- * If this class is avalable, these instance appended to the Faces Servlet call chain.
- * Default mapping to the FacesServlet instance is "*.jsf"
- */
- protected void setupFacesServlet() {
- ServletContainer facesServletContainer = new ServletContainer("*.jsf",
- new FacesServlet());
- facesServletContainer.setName("Faces Servlet");
- try {
- // Check for an ajax4jsf filter.
- Class<? extends Filter> ajaxFilterClass = contextClassLoader
- .loadClass("org.ajax4jsf.Filter").asSubclass(Filter.class);
- Filter ajaxFilter = ajaxFilterClass.newInstance();
- FilterContainer filterContainer = new FilterContainer(ajaxFilter,
- facesServletContainer);
- filterContainer.setName("ajax4jsf");
- facesServer.addResource("/WEB-INF/web.xml",
- "org/richfaces/test/ajax-web.xml");
- facesServer.addServlet(filterContainer);
- } catch (ClassNotFoundException e) {
- // No Richfaces filter, uses servlet directly.
- facesServer.addResource("/WEB-INF/web.xml",
- "org/richfaces/test/web.xml");
- facesServer.addServlet(facesServletContainer);
- } catch (Exception e) {
- throw new TestException(e);
- }
- }
+ // Ignore it.
+ } finally {
+ try {
+ stream.close();
+ } catch (IOException e) {
- /**
- * This template method called from {@link #setUp()} to append appropriate init parameters to the test server.
- * The default implementation sets state saving method to the "server", default jsf page suffix to the ".xhtml"
- * and project stage to UnitTest
- */
- protected void setupJsfInitParameters() {
- facesServer.addInitParameter(
- StateManager.STATE_SAVING_METHOD_PARAM_NAME,
- StateManager.STATE_SAVING_METHOD_SERVER);
- facesServer.addInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME,
- ".xhtml");
-
- facesServer.addInitParameter(ProjectStage.PROJECT_STAGE_PARAM_NAME,
- ProjectStage.UnitTest.name());
- }
+ // Ignore it.
+ }
+ }
+ }
- /**
- * This template method called from the {@link #setupFacesListener()} if MyFaces implementation presents.
- * The default implementation does nothing.
- */
- protected void setupMyFaces() {
- // Do nothing by default.
- }
+ facesServer = new StagingServer();
+ setupFacesServlet();
+ setupFacesListener();
+ setupJsfInitParameters();
+ setupWebContent();
+ facesServer.init();
- /**
- * This template method called from the {@link #setupFacesListener()} if Sun JSF reference implementation presents.
- * The default implementation sets the "com.sun.faces.validateXml" "com.sun.faces.verifyObjects" init parameters to the "true"
- */
- protected void setupSunFaces() {
- facesServer.addInitParameter("com.sun.faces.validateXml", "true");
- facesServer.addInitParameter("com.sun.faces.verifyObjects", "true");
- }
+ ApplicationFactory applicationFactory =
+ (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
- /**
- * This template method called from the {@link #setUp()} to populate virtual server content.
- * The default implementation tries to load web content from directory pointed by the System property
- * "webroot" or same property from the "/webapp.properties" file.
- */
- protected void setupWebContent() {
- String webappDirectory = System.getProperty("webroot");
+ application = applicationFactory.getApplication();
+
+ LifecycleFactory lifecycleFactory =
+ (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
+
+ lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
+ }
+
+ /**
+ * This hook method called from the {@link #setUp()} should append JSF implementation
+ * listener to the test server. Default version applends "com.sun.faces.config.ConfigureListener"
+ * or "org.apache.myfaces.webapp.StartupServletContextListener" for the existed SUN RI or MyFaces implementation.
+ * This metod also calls appropriate {@link #setupSunFaces()} or {@link #setupMyFaces()} methods.
+ */
+ protected void setupFacesListener() {
+ EventListener listener = null;
+
+ try {
+
+ // Check Sun RI configuration listener class.
+ Class<? extends EventListener> listenerClass =
+ contextClassLoader.loadClass("com.sun.faces.config.ConfigureListener").asSubclass(EventListener.class);
+
+ listener = listenerClass.newInstance();
+ setupSunFaces();
+ } catch (ClassNotFoundException e) {
+
+ // No JSF RI listener, check MyFaces.
+ Class<? extends EventListener> listenerClass;
+
+ try {
+ listenerClass = contextClassLoader.loadClass(
+ "org.apache.myfaces.webapp.StartupServletContextListener").asSubclass(EventListener.class);
+ listener = listenerClass.newInstance();
+ setupMyFaces();
+ } catch (ClassNotFoundException e1) {
+ throw new TestException("No JSF listeners have been found", e1);
+ } catch (Exception e2) {
+ throw new TestException("Error instantiate MyFaces listener", e2);
+ }
+ } catch (Exception e) {
+ throw new TestException("Error instantiate JSF RI listener", e);
+ }
+
+ facesServer.addWebListener(listener);
+ }
+
+ /**
+ * This template method called from {@link #setUp()} to create {@link FacesServlet} instance.
+ * The default implementation also tests presense of the "org.ajax4jsf.Filter" class.
+ * If this class is avalable, these instance appended to the Faces Servlet call chain.
+ * Default mapping to the FacesServlet instance is "*.jsf"
+ */
+ protected void setupFacesServlet() {
+ ServletContainer facesServletContainer = new ServletContainer("*.jsf", new FacesServlet());
+
+ facesServletContainer.setName("Faces Servlet");
+
+ try {
+
+ // Check for an ajax4jsf filter.
+ Class<? extends Filter> ajaxFilterClass =
+ contextClassLoader.loadClass("org.ajax4jsf.Filter").asSubclass(Filter.class);
+ Filter ajaxFilter = ajaxFilterClass.newInstance();
+ FilterContainer filterContainer = new FilterContainer(ajaxFilter, facesServletContainer);
+
+ filterContainer.setName("ajax4jsf");
+ facesServer.addResource("/WEB-INF/web.xml", "org/richfaces/test/ajax-web.xml");
+ facesServer.addServlet(filterContainer);
+ } catch (ClassNotFoundException e) {
+
+ // No Richfaces filter, uses servlet directly.
+ facesServer.addResource("/WEB-INF/web.xml", "org/richfaces/test/web.xml");
+ facesServer.addServlet(facesServletContainer);
+ } catch (Exception e) {
+ throw new TestException(e);
+ }
+ }
+
+ /**
+ * This template method called from {@link #setUp()} to append appropriate init parameters to the test server.
+ * The default implementation sets state saving method to the "server", default jsf page suffix to the ".xhtml"
+ * and project stage to UnitTest
+ */
+ protected void setupJsfInitParameters() {
+ facesServer.addInitParameter(StateManager.STATE_SAVING_METHOD_PARAM_NAME,
+ StateManager.STATE_SAVING_METHOD_SERVER);
+ facesServer.addInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME, ".xhtml");
+ facesServer.addInitParameter(ProjectStage.PROJECT_STAGE_PARAM_NAME, ProjectStage.UnitTest.name());
+ }
+
+ /**
+ * This template method called from the {@link #setupFacesListener()} if MyFaces implementation presents.
+ * The default implementation does nothing.
+ */
+ protected void setupMyFaces() {
+
+ // Do nothing by default.
+ }
+
+ /**
+ * This template method called from the {@link #setupFacesListener()} if Sun JSF reference implementation presents.
+ * The default implementation sets the "com.sun.faces.validateXml" "com.sun.faces.verifyObjects" init parameters to
+ * the "true"
+ */
+ protected void setupSunFaces() {
+ facesServer.addInitParameter("com.sun.faces.validateXml", "true");
+ facesServer.addInitParameter("com.sun.faces.verifyObjects", "true");
+ }
+
+ /**
+ * This template method called from the {@link #setUp()} to populate virtual server content.
+ * The default implementation tries to load web content from directory pointed by the System property
+ * "webroot" or same property from the "/webapp.properties" file.
+ */
+ protected void setupWebContent() {
+ String webappDirectory = System.getProperty("webroot");
File webFile = null;
+
if (null == webappDirectory) {
- URL resource = this.getClass().getResource("/webapp.properties");
- if (null != resource && "file".equals(resource.getProtocol())) {
- Properties webProperties = new Properties();
- try {
- InputStream inputStream = resource.openStream();
- webProperties.load(inputStream);
- inputStream.close();
- webFile = new File(resource.getPath());
- webFile = new File(webFile.getParentFile(), webProperties.getProperty("webroot")).getAbsoluteFile();
- facesServer.addResourcesFromDirectory("/", webFile);
- } catch (IOException e) {
- throw new TestException(e);
- }
+ URL resource = this.getClass().getResource("/webapp.properties");
+
+ if (null != resource && "file".equals(resource.getProtocol())) {
+ Properties webProperties = new Properties();
+
+ try {
+ InputStream inputStream = resource.openStream();
+
+ webProperties.load(inputStream);
+ inputStream.close();
+ webFile = new File(resource.getPath());
+ webFile = new File(webFile.getParentFile(), webProperties.getProperty("webroot")).getAbsoluteFile();
+ facesServer.addResourcesFromDirectory("/", webFile);
+ } catch (IOException e) {
+ throw new TestException(e);
}
+ }
} else {
- webFile = new File(webappDirectory);
- facesServer.addResourcesFromDirectory("/", webFile);
+ webFile = new File(webappDirectory);
+ facesServer.addResourcesFromDirectory("/", webFile);
}
+ }
- }
+ /**
+ * Setup virtual server connection to run tests inside JSF lifecycle.
+ * The default implementation setups virtual request to the "http://localhost/test.jsf" URL and creates
+ * {@link FacesContext} instance.
+ * Two template methods are called :
+ * <ol>
+ * <li>{@link #setupConnection()} to prepare request method, parameters, headers and so</li>
+ * <li>{@link #setupView()} to create default view.</li>
+ * </ol>
+ * @throws Exception
+ */
+ protected void setupFacesRequest() throws Exception {
+ String url = "http://localhost/test.jsf";
- /**
- * Setup virtual server connection to run tests inside JSF lifecycle.
- * The default implementation setups virtual request to the "http://localhost/test.jsf" URL and creates {@link FacesContext} instance.
- * Two template methods are called :
- * <ol>
- * <li>{@link #setupConnection()} to prepare request method, parameters, headers and so</li>
- * <li>{@link #setupView()} to create default view.</li>
- * </ol>
- * @throws Exception
- */
- protected void setupFacesRequest() throws Exception {
- String url = "http://localhost/test.jsf";
- setupFacesRequest(url);
- UIViewRoot viewRoot = setupView();
- if (null != viewRoot) {
- facesContext.setViewRoot(viewRoot);
- }
- }
+ setupFacesRequest(url);
- /**
- * <p class="changed_added_2_0"></p>
- * @param url
- * @throws MalformedURLException
- * @throws FacesException
- */
- protected void setupFacesRequest(String url) throws MalformedURLException,
- FacesException {
- connection = facesServer.getConnection(new URL(
- url));
- setupConnection();
- connection.start();
- FacesContextFactory facesContextFactory = (FacesContextFactory) FactoryFinder
- .getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
- facesContext = facesContextFactory.getFacesContext(facesServer
- .getContext(), connection.getRequest(), connection
- .getResponse(), lifecycle);
- }
+ UIViewRoot viewRoot = setupView();
- /**
- * This template method called from the {@link #setupFacesRequest()} to create components view tree in the virtual request.
- * The default implementation is only creates {@link UIViewRoot} instance for view ID "/test.xhtml".
- * @return
- */
- protected UIViewRoot setupView() {
- UIViewRoot viewRoot = (UIViewRoot) application.createComponent(UIViewRoot.COMPONENT_TYPE);
- viewRoot.setViewId("/test.xhtml");
- viewRoot.setLocale(Locale.getDefault());
- viewRoot.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
- return viewRoot;
- }
+ if (null != viewRoot) {
+ facesContext.setViewRoot(viewRoot);
+ }
+ }
- /**
- * This template method called from the {@link #setupFacesRequest()} to setup additional virtual connection parameters.
- * The default implementation does nothing.
- */
- protected void setupConnection() {
+ /**
+ * <p class="changed_added_2_0"></p>
+ * @param url
+ * @throws MalformedURLException
+ * @throws FacesException
+ */
+ protected void setupFacesRequest(String url) throws MalformedURLException, FacesException {
+ connection = facesServer.getConnection(new URL(url));
+ setupConnection();
+ connection.start();
- }
+ FacesContextFactory facesContextFactory =
+ (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
- /**
- * Virtual server instance cleanup.
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws Exception {
- if (null != facesContext) {
- facesContext.release();
- facesContext = null;
- }
- if (null != connection) {
- if (!connection.isFinished()) {
- connection.finish();
- }
- connection = null;
- }
- facesServer.destroy();
- Thread.currentThread().setContextClassLoader(contextClassLoader);
- facesServer = null;
- application = null;
- lifecycle = null;
- }
+ facesContext = facesContextFactory.getFacesContext(facesServer.getContext(), connection.getRequest(),
+ connection.getResponse(), lifecycle);
+ }
+ /**
+ * This template method called from the {@link #setupFacesRequest()} to create components view tree in the virtual
+ * request.
+ * The default implementation is only creates {@link UIViewRoot} instance for view ID "/test.xhtml".
+ * @return
+ */
+ protected UIViewRoot setupView() {
+ UIViewRoot viewRoot = (UIViewRoot) application.createComponent(UIViewRoot.COMPONENT_TYPE);
+
+ viewRoot.setViewId("/test.xhtml");
+ viewRoot.setLocale(Locale.getDefault());
+ viewRoot.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
+
+ return viewRoot;
+ }
+
+ /**
+ * This template method called from the {@link #setupFacesRequest()} to setup additional virtual connection
+ * parameters.
+ * The default implementation does nothing.
+ */
+ protected void setupConnection() {}
+
+ /**
+ * Virtual server instance cleanup.
+ * @throws java.lang.Exception
+ */
+ @After
+ public void tearDown() throws Exception {
+ if (null != facesContext) {
+ facesContext.release();
+ facesContext = null;
+ }
+
+ if (null != connection) {
+ if (!connection.isFinished()) {
+ connection.finish();
+ }
+
+ connection = null;
+ }
+
+ facesServer.destroy();
+ Thread.currentThread().setContextClassLoader(contextClassLoader);
+ facesServer = null;
+ application = null;
+ lifecycle = null;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/AbstractThreadedTest.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/AbstractThreadedTest.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/AbstractThreadedTest.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test;
@@ -13,17 +14,19 @@
*/
public abstract class AbstractThreadedTest extends TestCase {
- /**
- * The threads that are executing.
+ /**
+ * The tests TestResult.
*/
- private Thread threads[] = null;
- /**
- * The tests TestResult.*/
private TestResult testResult = null;
+ /**
+ * The threads that are executing.
+ */
+ private Thread[] threads = null;
+
public void interruptThreads() {
- if(threads != null) {
- for(int i = 0;i < threads.length;i++) {
+ if (threads != null) {
+ for (int i = 0; i < threads.length; i++) {
threads[i].interrupt();
}
}
@@ -31,7 +34,7 @@
/**
* Override run so we can squirrel away the test result.
- *
+ *
*/
@Override
public void run(final TestResult result) {
@@ -47,82 +50,90 @@
* @throws InstantiationException
* @throws IllegalAccessException
*/
- protected void runTestCaseThreads(Class<?> clazz, int numThreads) {
- TestCaseRunnable[] runnables = new TestCaseRunnable[numThreads];
- for (int i = 0; i < runnables.length; i++) {
- try {
- runnables[i]= (TestCaseRunnable) clazz.newInstance();
- } catch (Exception e) {
- testResult.addError(this, e);
- return;
- }
- }
- runTestCaseRunnables(runnables);
+ protected void runTestCaseThreads(Class<?> clazz, int numThreads) {
+ TestCaseRunnable[] runnables = new TestCaseRunnable[numThreads];
+
+ for (int i = 0; i < runnables.length; i++) {
+ try {
+ runnables[i] = (TestCaseRunnable) clazz.newInstance();
+ } catch (Exception e) {
+ testResult.addError(this, e);
+
+ return;
+ }
+ }
+
+ runTestCaseRunnables(runnables);
}
+
/**
* Run the test case threads.
* @param runnables - array with instances of {@link TestCaseRunnable} with concrete tests
*/
- protected void runTestCaseRunnables (final TestCaseRunnable[] runnables) {
- if(runnables == null) {
+ protected void runTestCaseRunnables(final TestCaseRunnable[] runnables) {
+ if (runnables == null) {
throw new IllegalArgumentException("runnables is null");
}
+
threads = new Thread[runnables.length];
- for(int i = 0;i < threads.length;i++) {
+
+ for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(runnables[i]);
}
- for(int i = 0;i < threads.length;i++) {
+
+ for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
+
try {
- for(int i = 0;i < threads.length;i++) {
+ for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
- }
- catch(InterruptedException ignore) {
+ } catch (InterruptedException ignore) {
System.out.println("Thread join interrupted.");
}
+
threads = null;
}
-
+
/**
* Handle an exception. Since multiple threads won't have their
* exceptions caught the threads must manually catch them and call
* <code>handleException ()</code>.
- * @param t Exception to handle.*/
+ * @param t Exception to handle.
+ */
private void handleException(final Throwable t) {
- synchronized(testResult) {
- if(t instanceof AssertionFailedError) {
- testResult.addFailure(this, (AssertionFailedError)t);
- }
- else {
+ synchronized (testResult) {
+ if (t instanceof AssertionFailedError) {
+ testResult.addFailure(this, (AssertionFailedError) t);
+ } else {
testResult.addError(this, t);
}
}
}
-
+
/**
* A test case thread. Override runTestCase () and define
- * behaviour of test in there.*/
+ * behaviour of test in there.
+ */
public abstract class TestCaseRunnable implements Runnable {
+
/**
- * Override this to define the test*/
-
- public abstract void runTestCase()
- throws Throwable;
+ * Override this to define the test
+ */
+ public abstract void runTestCase() throws Throwable;
+
/**
* Run the test in an environment where
- * we can handle the exceptions generated by the test method.*/
-
+ * we can handle the exceptions generated by the test method.
+ */
public void run() {
try {
runTestCase();
- }
- catch(Throwable t) /* Any other exception we handle and then we interrupt the other threads.*/ {
+ } catch (Throwable t) /* Any other exception we handle and then we interrupt the other threads. */ {
handleException(t);
interruptThreads();
}
}
}
-
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebClient.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebClient.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebClient.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test;
@@ -14,57 +15,54 @@
* Modified version of the HtmlUnit {@link WebClient}. This subclass uses {@link LocalWebConnection} by default,
* to perform requests to the local saging server {@link StagingServer} instead of real network request.
* It is also setup synchonous ajax controller {@link WebClient#setAjaxController(com.gargoylesoftware.htmlunit.AjaxController)},
- * to avoid thread syncronisation problem.
+ * to avoid thread syncronisation problem.
* @author asmirnov
*
*/
@SuppressWarnings("serial")
public class LocalWebClient extends WebClient {
-
- private final StagingServer server;
-
- private transient WebConnection webConnection;
+ private final StagingServer server;
+ private transient WebConnection webConnection;
- /**
- * Create WebConnection instance for the given {@link StagingServer}
- * @param server test server instance.
- */
- public LocalWebClient(StagingServer server) {
- super();
- this.server = server;
- setAjaxController(new NicelyResynchronizingAjaxController());
- }
+ /**
+ * Create WebConnection instance for the given {@link StagingServer}
+ * @param server test server instance.
+ */
+ public LocalWebClient(StagingServer server) {
+ super();
+ this.server = server;
+ setAjaxController(new NicelyResynchronizingAjaxController());
+ }
- /**
- * Create WebConnection instance for the given {@link StagingServer} and browser version.
- * @param server test server instance.
- * @param browserVersion
- */
- public LocalWebClient(StagingServer server,BrowserVersion browserVersion) {
- super(browserVersion);
- this.server = server;
- setAjaxController(new NicelyResynchronizingAjaxController());
- }
+ /**
+ * Create WebConnection instance for the given {@link StagingServer} and browser version.
+ * @param server test server instance.
+ * @param browserVersion
+ */
+ public LocalWebClient(StagingServer server, BrowserVersion browserVersion) {
+ super(browserVersion);
+ this.server = server;
+ setAjaxController(new NicelyResynchronizingAjaxController());
+ }
- /**
- * Overwride default webConnection.
- * @return the webConnection
- */
- @Override
- public WebConnection getWebConnection() {
- if (this.webConnection == null) {
- this.webConnection = new LocalWebConnection(server);
- }
+ /**
+ * Overwride default webConnection.
+ * @return the webConnection
+ */
+ @Override
+ public WebConnection getWebConnection() {
+ if (this.webConnection == null) {
+ this.webConnection = new LocalWebConnection(server);
+ }
- return this.webConnection;
- }
+ return this.webConnection;
+ }
- /**
- * @param webConnection the webConnection to set
- */
- @Override
- public void setWebConnection(WebConnection webConnection) {
- this.webConnection = webConnection;
- }
-
+ /**
+ * @param webConnection the webConnection to set
+ */
+ @Override
+ public void setWebConnection(WebConnection webConnection) {
+ this.webConnection = webConnection;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebConnection.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebConnection.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebConnection.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,11 +1,13 @@
+
/**
- *
+ *
*/
package org.richfaces.test;
import java.io.IOException;
import org.apache.commons.httpclient.NameValuePair;
+
import org.richfaces.test.staging.HttpMethod;
import org.richfaces.test.staging.StagingConnection;
import org.richfaces.test.staging.StagingServer;
@@ -17,48 +19,58 @@
/**
* This implementation of the HtmlUnit {@link WebConnection} execute http requests on the local
- * staging server instead of the real network connection.
+ * staging server instead of the real network connection.
* @author asmirnov
*
*/
public final class LocalWebConnection implements WebConnection {
- /**
- * test server instance
- */
- private final StagingServer localServer;
- /**
- * @param localServer
- */
- public LocalWebConnection(StagingServer localServer) {
- this.localServer = localServer;
- }
+ /**
+ * test server instance
+ */
+ private final StagingServer localServer;
- /* (non-Javadoc)
- * @see com.gargoylesoftware.htmlunit.WebConnection#getResponse(com.gargoylesoftware.htmlunit.WebRequestSettings)
- */
- public WebResponse getResponse(WebRequestSettings settings)
- throws IOException {
- StagingConnection connection = localServer.getConnection(settings.getUrl());
- // Propagate web request settings to the local connection.
- for (NameValuePair param : settings.getRequestParameters()) {
- connection.addRequestParameter(param.getName(), param.getValue());
- }
- HttpMethod httpMethod = HttpMethod.valueOf(settings.getHttpMethod().toString());
- connection.setRequestMethod(httpMethod);
- connection.setRequestCharacterEncoding(settings.getCharset());
- String body = settings.getRequestBody();
- String contentType = settings.getEncodingType().getName();
- connection.setRequestBody(body);
- connection.setRequestContentType(contentType);
- connection.addRequestHeaders(settings.getAdditionalHeaders());
- // HtmlUnit uses request parameters map for the form submit, but does not parse
- // XMLHttpRequest content.
- if(null != body && FormEncodingType.URL_ENCODED.getName().equals(contentType)){
- connection.parseFormParameters(body);
- }
- long startTime = System.currentTimeMillis();
- connection.execute();
- return new LocalWebResponse(settings,connection,System.currentTimeMillis()-startTime);
- }
-}
\ No newline at end of file
+ /**
+ * @param localServer
+ */
+ public LocalWebConnection(StagingServer localServer) {
+ this.localServer = localServer;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see com.gargoylesoftware.htmlunit.WebConnection#getResponse(com.gargoylesoftware.htmlunit.WebRequestSettings)
+ */
+ public WebResponse getResponse(WebRequestSettings settings) throws IOException {
+ StagingConnection connection = localServer.getConnection(settings.getUrl());
+
+ // Propagate web request settings to the local connection.
+ for (NameValuePair param : settings.getRequestParameters()) {
+ connection.addRequestParameter(param.getName(), param.getValue());
+ }
+
+ HttpMethod httpMethod = HttpMethod.valueOf(settings.getHttpMethod().toString());
+
+ connection.setRequestMethod(httpMethod);
+ connection.setRequestCharacterEncoding(settings.getCharset());
+
+ String body = settings.getRequestBody();
+ String contentType = settings.getEncodingType().getName();
+
+ connection.setRequestBody(body);
+ connection.setRequestContentType(contentType);
+ connection.addRequestHeaders(settings.getAdditionalHeaders());
+
+ // HtmlUnit uses request parameters map for the form submit, but does not parse
+ // XMLHttpRequest content.
+ if (null != body && FormEncodingType.URL_ENCODED.getName().equals(contentType)) {
+ connection.parseFormParameters(body);
+ }
+
+ long startTime = System.currentTimeMillis();
+
+ connection.execute();
+
+ return new LocalWebResponse(settings, connection, System.currentTimeMillis() - startTime);
+ }
+}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebResponse.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebResponse.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/LocalWebResponse.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test;
@@ -7,12 +8,15 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
+
import java.net.URL;
+
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.apache.commons.httpclient.NameValuePair;
+
import org.richfaces.test.staging.StagingConnection;
import com.gargoylesoftware.htmlunit.WebRequestSettings;
@@ -23,7 +27,7 @@
* connection. This class is used by the {@link LocalWebClient}, but also can be used to analise response rendering:
* <pre>
* ............
- * @Test
+ * @Test
* public void testRender() {
* setupFacesRequest();
* // Prepare view etc
@@ -35,196 +39,204 @@
* assertTrue(....)
* }
* </pre>
- *
+ *
* @author asmirnov
- *
+ *
*/
public class LocalWebResponse implements WebResponse {
-
- private WebRequestSettings settings;
-
- private final StagingConnection serverConnection;
-
- private final long loadTime;
+ private final long loadTime;
+ private final StagingConnection serverConnection;
+ private WebRequestSettings settings;
- public LocalWebResponse(StagingConnection serverConnection,long l) {
- this.serverConnection = serverConnection;
- this.loadTime = l;
- }
+ public LocalWebResponse(StagingConnection serverConnection, long l) {
+ this.serverConnection = serverConnection;
+ this.loadTime = l;
+ }
- public LocalWebResponse(WebRequestSettings settings,
- StagingConnection connection, long l) {
- this(connection,l);
- this.settings = settings;
- }
+ public LocalWebResponse(WebRequestSettings settings, StagingConnection connection, long l) {
+ this(connection, l);
+ this.settings = settings;
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getContentAsStream()
- */
- public InputStream getContentAsStream() throws IOException {
- return new ByteArrayInputStream(getResponseBody());
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getContentAsStream()
+ */
+ public InputStream getContentAsStream() throws IOException {
+ return new ByteArrayInputStream(getResponseBody());
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getContentAsString()
- */
- public String getContentAsString() {
- return serverConnection.getContentAsString();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getContentAsString()
+ */
+ public String getContentAsString() {
+ return serverConnection.getContentAsString();
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getContentCharSet()
- */
- public String getContentCharSet() {
- return serverConnection.getResponseCharacterEncoding();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getContentCharSet()
+ */
+ public String getContentCharSet() {
+ return serverConnection.getResponseCharacterEncoding();
+ }
- public String getContentType() {
- return serverConnection.getResponseContentType();
- }
+ public String getContentType() {
+ return serverConnection.getResponseContentType();
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * com.gargoylesoftware.htmlunit.WebResponse#getLoadTimeInMilliSeconds()
- */
- public long getLoadTimeInMilliSeconds() {
- return loadTime;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.gargoylesoftware.htmlunit.WebResponse#getLoadTimeInMilliSeconds()
+ */
+ public long getLoadTimeInMilliSeconds() {
+ return loadTime;
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getRequestMethod()
- */
- public com.gargoylesoftware.htmlunit.HttpMethod getRequestMethod() {
- return com.gargoylesoftware.htmlunit.HttpMethod
- .valueOf(serverConnection.getRequestMethod().toString());
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getRequestMethod()
+ */
+ public com.gargoylesoftware.htmlunit.HttpMethod getRequestMethod() {
+ return com.gargoylesoftware.htmlunit.HttpMethod.valueOf(serverConnection.getRequestMethod().toString());
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getRequestSettings()
- */
- public WebRequestSettings getRequestSettings() {
- if (settings == null) {
- settings = new WebRequestSettings(this.getUrl(), getRequestMethod());
- }
- return settings;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getRequestSettings()
+ */
+ public WebRequestSettings getRequestSettings() {
+ if (settings == null) {
+ settings = new WebRequestSettings(this.getUrl(), getRequestMethod());
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getResponseBody()
- */
- public byte[] getResponseBody() {
- return serverConnection.getResponseBody();
- }
+ return settings;
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * com.gargoylesoftware.htmlunit.WebResponse#getResponseHeaderValue(java
- * .lang.String)
- */
- public String getResponseHeaderValue(String headerName) {
- String[] values = serverConnection.getResponseHeaders().get(headerName);
- if(null != values && values.length >0){
- return values[0];
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getResponseBody()
+ */
+ public byte[] getResponseBody() {
+ return serverConnection.getResponseBody();
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getStatusCode()
- */
- public int getStatusCode() {
- return serverConnection.getResponseStatus();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.gargoylesoftware.htmlunit.WebResponse#getResponseHeaderValue(java
+ * .lang.String)
+ */
+ public String getResponseHeaderValue(String headerName) {
+ String[] values = serverConnection.getResponseHeaders().get(headerName);
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getStatusMessage()
- */
- public String getStatusMessage() {
- return serverConnection.getErrorMessage();
- }
+ if (null != values && values.length > 0) {
+ return values[0];
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getUrl()
- */
- public URL getUrl() {
- return serverConnection.getUrl();
- }
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.gargoylesoftware.htmlunit.WebResponse#getResponseHeaders()
- */
- public List<NameValuePair> getResponseHeaders() {
- ArrayList<NameValuePair> headers = new ArrayList<NameValuePair>(10);
- for (Entry<String, String[]> entry : serverConnection
- .getResponseHeaders().entrySet()) {
- for (String value : entry.getValue()) {
- headers.add(new NameValuePair(entry.getKey(), value));
- }
- }
- int contentLength = serverConnection.getResponseContentLength();
- if(contentLength>=0){
- headers.add(new NameValuePair("Content-Length", String.valueOf(contentLength)));
- }
- return headers;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getStatusCode()
+ */
+ public int getStatusCode() {
+ return serverConnection.getResponseStatus();
+ }
- /* (non-Javadoc)
- * @see com.gargoylesoftware.htmlunit.WebResponse#getContentAsBytes()
- */
- public byte[] getContentAsBytes() {
- return serverConnection.getResponseBody();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getStatusMessage()
+ */
+ public String getStatusMessage() {
+ return serverConnection.getErrorMessage();
+ }
- /* (non-Javadoc)
- * @see com.gargoylesoftware.htmlunit.WebResponse#getContentAsString(java.lang.String)
- */
- public String getContentAsString(String encoding) {
- byte[] body = serverConnection.getResponseBody();
- String content;
- try {
- content = new String(body,encoding);
- } catch (UnsupportedEncodingException e) {
- content = new String(body);
- }
- return content;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getUrl()
+ */
+ public URL getUrl() {
+ return serverConnection.getUrl();
+ }
- /* (non-Javadoc)
- * @see com.gargoylesoftware.htmlunit.WebResponse#getLoadTime()
- */
- public long getLoadTime() {
- return loadTime;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getResponseHeaders()
+ */
+ public List<NameValuePair> getResponseHeaders() {
+ ArrayList<NameValuePair> headers = new ArrayList<NameValuePair>(10);
- /* (non-Javadoc)
- * @see com.gargoylesoftware.htmlunit.WebResponse#getRequestUrl()
- */
- public URL getRequestUrl() {
- // TODO Auto-generated method stub
- return serverConnection.getUrl();
- }
-}
\ No newline at end of file
+ for (Entry<String, String[]> entry : serverConnection.getResponseHeaders().entrySet()) {
+ for (String value : entry.getValue()) {
+ headers.add(new NameValuePair(entry.getKey(), value));
+ }
+ }
+
+ int contentLength = serverConnection.getResponseContentLength();
+
+ if (contentLength >= 0) {
+ headers.add(new NameValuePair("Content-Length", String.valueOf(contentLength)));
+ }
+
+ return headers;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getContentAsBytes()
+ */
+ public byte[] getContentAsBytes() {
+ return serverConnection.getResponseBody();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getContentAsString(java.lang.String)
+ */
+ public String getContentAsString(String encoding) {
+ byte[] body = serverConnection.getResponseBody();
+ String content;
+
+ try {
+ content = new String(body, encoding);
+ } catch (UnsupportedEncodingException e) {
+ content = new String(body);
+ }
+
+ return content;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getLoadTime()
+ */
+ public long getLoadTime() {
+ return loadTime;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see com.gargoylesoftware.htmlunit.WebResponse#getRequestUrl()
+ */
+ public URL getRequestUrl() {
+
+ // TODO Auto-generated method stub
+ return serverConnection.getUrl();
+ }
+}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/TestException.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/TestException.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/TestException.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,45 +1,43 @@
+
/**
- *
+ *
*/
package org.richfaces.test;
-import org.richfaces.test.staging.StagingServer;
-
/**
- * Internal runtame exception for the {@link StagingServer} engine.
+ * Internal runtame exception for the {@link org.richfaces.test.staging.StagingServer} engine.
* @author asmirnov
*
*/
@SuppressWarnings("serial")
public class TestException extends RuntimeException {
- /**
- * Default constructor.
- */
- public TestException() {
- super();
- }
+ /**
+ * Default constructor.
+ */
+ public TestException() {
+ super();
+ }
- /**
- * @param message
- */
- public TestException(String message) {
- super(message);
- }
+ /**
+ * @param message
+ */
+ public TestException(String message) {
+ super(message);
+ }
- /**
- * @param cause
- */
- public TestException(Throwable cause) {
- super(cause);
- }
+ /**
+ * @param cause
+ */
+ public TestException(Throwable cause) {
+ super(cause);
+ }
- /**
- * @param message
- * @param cause
- */
- public TestException(String message, Throwable cause) {
- super(message, cause);
- }
-
+ /**
+ * @param message
+ * @param cause
+ */
+ public TestException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/AbstractServerResource.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/AbstractServerResource.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/AbstractServerResource.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -2,71 +2,78 @@
import java.io.IOException;
import java.io.InputStream;
+
import java.net.URL;
import java.net.URLConnection;
+
import java.util.Set;
import java.util.logging.Logger;
-
/**
* Base abstract class for an all file references in the 'virtual' staging server directory.
* @author asmirnov
*
*/
public abstract class AbstractServerResource implements ServerResource {
+ private static final Logger LOG = ServerLogger.RESOURCE.getLogger();
- private static final Logger log = ServerLogger.RESOURCE.getLogger();
+ public AbstractServerResource() {}
- public AbstractServerResource() {
- }
+ /**
+ * This implementation creates stream from the resource URL. I also tries to disable
+ * url connection cache, to prevent jar file locking in the windows environment.
+ * @see org.richfaces.test.staging.ServerResource#getAsStream()
+ */
+ public InputStream getAsStream() throws IOException {
+ URL url = getURL();
- /** This implementation creates stream from the resource URL. I also tries to disable
- * url connection cache, to prevent jar file locking in the windows environment.
- * @see org.richfaces.test.staging.ServerResource#getAsStream()
- */
- public InputStream getAsStream() throws IOException {
- URL url = getURL();
- if (url != null) {
- URLConnection connection = url.openConnection();
- try {
- connection.setUseCaches(false);
- } catch (IllegalArgumentException e) {
- log.info("RESOURCE_NOT_CACHEABLE");
- }
- return connection.getInputStream();
- } else {
- return null;
- }
- }
+ if (url != null) {
+ URLConnection connection = url.openConnection();
- /**
- * File-like resources do not allows resources additions.
- * @throws UnsupportedOperationException
- * @see org.richfaces.test.staging.ServerResource#addResource(org.richfaces.test.staging.ServerResourcePath, org.richfaces.test.staging.ServerResource)
- */
- public void addResource(ServerResourcePath path, ServerResource resource) {
- throw new UnsupportedOperationException();
- }
+ try {
+ connection.setUseCaches(false);
+ } catch (IllegalArgumentException e) {
+ LOG.info("RESOURCE_NOT_CACHEABLE");
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.ServerResource#getResource(org.richfaces.test.staging.ServerResourcePath)
- */
- public ServerResource getResource(ServerResourcePath path) {
- if(null == path){
- throw new NullPointerException();
- }
- // If path points to the resource itself, returns this instance.
- if(path.isFile()){
- return this;
- }
- return null;
- }
+ return connection.getInputStream();
+ } else {
+ return null;
+ }
+ }
- /** File-like resources does not contain any other, so this method always returns null.
- * @see org.richfaces.test.staging.ServerResource#getPaths()
- */
- public Set<String> getPaths() {
- return null;//Collections.emptySet();
- }
+ /**
+ * File-like resources do not allows resources additions.
+ * @throws UnsupportedOperationException
+ * @see org.richfaces.test.staging.ServerResource#addResource(org.richfaces.test.staging.ServerResourcePath,
+ * org.richfaces.test.staging.ServerResource)
+ */
+ public void addResource(ServerResourcePath path, ServerResource resource) {
+ throw new UnsupportedOperationException();
+ }
-}
\ No newline at end of file
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.ServerResource#getResource(org.richfaces.test.staging.ServerResourcePath)
+ */
+ public ServerResource getResource(ServerResourcePath path) {
+ if (null == path) {
+ throw new NullPointerException();
+ }
+
+ // If path points to the resource itself, returns this instance.
+ if (path.isFile()) {
+ return this;
+ }
+
+ return null;
+ }
+
+ /**
+ * File-like resources does not contain any other, so this method always returns null.
+ * @see org.richfaces.test.staging.ServerResource#getPaths()
+ */
+ public Set<String> getPaths() {
+ return null; // Collections.emptySet();
+ }
+}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ClasspathServerResource.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ClasspathServerResource.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ClasspathServerResource.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,67 +1,64 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.net.URL;
+
import java.util.logging.Level;
import java.util.logging.Logger;
import org.richfaces.test.TestException;
-
/**
* This class represents file from classpath in the virtual web application
* content.
- *
+ *
* @author asmirnov
- *
+ *
*/
public class ClasspathServerResource extends AbstractServerResource {
+ private static final Logger LOG = ServerLogger.RESOURCE.getLogger();
+ private volatile URL url = null;
+ private final String classpath;
- /**
- *
- */
- private final String classpath;
+ /**
+ * @param classpath
+ */
+ public ClasspathServerResource(String classpath) {
+ this.classpath = classpath;
+ }
- private volatile URL url = null;
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.richfaces.test.staging.ServerResource#getURL()
+ */
+ public URL getURL() {
+ if (url == null) {
- private static final Logger log = ServerLogger.RESOURCE.getLogger();
+ // JDK-5 singleton-like synchronization.
+ // @see http://jeremymanson.blogspot.com/2008/05/double-checked-locking.html
+ synchronized (this) {
+ if (LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("get classpath resource from " + this.classpath);
+ }
- /**
- * @param name
- * @param classpath
- */
- public ClasspathServerResource(String classpath) {
- this.classpath = classpath;
- }
+ ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- /*
- * (non-Javadoc)
- *
- * @see org.richfaces.test.staging.ServerResource#getURL()
- */
- public URL getURL() {
- if (url == null) {
- // JDK-5 singleton-like synchronization.
- // @see http://jeremymanson.blogspot.com/2008/05/double-checked-locking.html
- synchronized (this) {
- if(log.isLoggable(Level.FINEST)){
- log.finest("get classpath resource from "+this.classpath);
- }
- ClassLoader classLoader = Thread.currentThread()
- .getContextClassLoader();
- if (null == classLoader) {
- classLoader = this.getClass().getClassLoader();
- }
- url = classLoader.getResource(classpath);
- if(null == url){
- throw new TestException("Virtual server resource can't be loaded from "+classpath);
- }
- }
- }
+ if (null == classLoader) {
+ classLoader = this.getClass().getClassLoader();
+ }
- return url;
- }
+ url = classLoader.getResource(classpath);
+ if (null == url) {
+ throw new TestException("Virtual server resource can't be loaded from " + classpath);
+ }
+ }
+ }
+
+ return url;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/EventInvoker.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/EventInvoker.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/EventInvoker.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -7,11 +8,11 @@
/**
* Internal interface, used to invoke listeners of different types.
-
+ *
* @author asmirnov
*
* @param <T> listener type.
*/
interface EventInvoker<T extends EventListener> {
- public void invoke(T listener);
-}
\ No newline at end of file
+ public void invoke(T listener);
+}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/FilterContainer.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/FilterContainer.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/FilterContainer.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,6 +1,7 @@
package org.richfaces.test.staging;
import java.io.IOException;
+
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
@@ -15,194 +16,194 @@
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
-
/**
* Holds a filter instance and reference to the next executable server object (
* filter or servlet ) in the chain.
- *
+ *
* @author asmirnov
- *
+ *
*/
public class FilterContainer implements RequestChain {
+ private static final Logger LOG = ServerLogger.SERVER.getLogger();
- private static final Logger log = ServerLogger.SERVER.getLogger();
+ /**
+ * Filter name.
+ */
+ private String name = "Default";
- /**
- * Servlet filter instance.
- */
- private final Filter filter;
+ /**
+ * Initialization flag to avoid double calls.
+ */
+ private boolean initialized = false;
- /**
- * Next object in the chain.
- */
- private final RequestChain next;
+ /**
+ * Servlet filter instance.
+ */
+ private final Filter filter;
- /**
- * Filter name.
- */
- private String name = "Default";
+ /**
+ * Filter initialization parameters.
+ */
+ private final Map<String, String> initParameters;
- /**
- * Filter initialization parameters.
- */
- private final Map<String, String> initParameters;
+ /**
+ * Next object in the chain.
+ */
+ private final RequestChain next;
- /**
- * Initialization flag to avoid double calls.
- */
- private boolean initialized = false;
+ /**
+ * @param filter
+ * instance of the web application filter.
+ * @param next
+ * next executable object in the filter chain.
+ * @throws NullPointerException if any of parameter is null.
+ */
+ public FilterContainer(Filter filter, RequestChain next) {
+ if (null == filter || null == next) {
+ throw new NullPointerException();
+ }
- /**
- * @param filter
- * instance of the web application filter.
- * @param next
- * next executable object in the filter chain.
- * @throws NullPointerException if any of parameter is null.
- */
- public FilterContainer(Filter filter, RequestChain next) {
- if(null == filter || null == next){
- throw new NullPointerException();
- }
- this.filter = filter;
- this.next = next;
- this.initParameters = new HashMap<String, String>();
- }
+ this.filter = filter;
+ this.next = next;
+ this.initParameters = new HashMap<String, String>();
+ }
- /**
- * @return filter name.
- */
- public String getName() {
- return name;
- }
+ /**
+ * @return filter name.
+ */
+ public String getName() {
+ return name;
+ }
- /**
- * @param name
- * new filter name.
- */
- public void setName(String name) {
- if (initialized) {
- throw new IllegalStateException(
- "Filter have already been initialized, name can't be changed");
- }
- this.name = name;
- }
+ /**
+ * @param name
+ * new filter name.
+ */
+ public void setName(String name) {
+ if (initialized) {
+ throw new IllegalStateException("Filter have already been initialized, name can't be changed");
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.RequestChain#execute(javax.servlet.ServletRequest
- * , javax.servlet.ServletResponse)
- */
- public void execute(ServletRequest request, ServletResponse response)
- throws ServletException, IOException {
- if (!initialized) {
- throw new IllegalStateException(
- "Filter "+getName()+" have not been initialized, could'n execute request");
- }
- log.finest("Request '"+request+"' executes by the '"+getName()+"' filter");
- FilterChain chain = new FilterChain() {
- // Execute next object in the chain.
- public void doFilter(ServletRequest request,
- ServletResponse response) throws IOException,
- ServletException {
- next.execute(request, response);
+ this.name = name;
+ }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.RequestChain#execute(javax.servlet.ServletRequest
+ * , javax.servlet.ServletResponse)
+ */
+ public void execute(ServletRequest request, ServletResponse response) throws ServletException, IOException {
+ if (!initialized) {
+ throw new IllegalStateException("Filter " + getName()
+ + " have not been initialized, could'n execute request");
+ }
- };
- filter.doFilter(request, response, chain);
+ LOG.finest("Request '" + request + "' executes by the '" + getName() + "' filter");
- }
+ FilterChain chain = new FilterChain() {
- /**
- * Append filter initialization parameter. Name and value are same as
- * defined in the web.xml
- *
- * <code>
- * <init-param>
- * <param-name>foo</param-name>
- * <param-value>bar</param-value>
- * </init-param>
- * </code>
- *
- * @param name
- * name of the parameter
- * @param value
- * its value
- */
- public void addInitParameter(String name, String value) {
- if (initialized) {
- throw new IllegalStateException(
- "Filter have already been initialized, init parameters can't be changed");
- }
- initParameters.put(name, value);
- }
+ // Execute next object in the chain.
+ public void doFilter(ServletRequest request, ServletResponse response)
+ throws IOException, ServletException {
+
+ next.execute(request, response);
+ }
+ };
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#isApplicable(java.lang.String)
- */
- public boolean isApplicable(String path) {
- // Delegate to the next object. Filter has a same mapping as target servlet.
- return next.isApplicable(path);
- }
+ filter.doFilter(request, response, chain);
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#destroy()
- */
- public void destroy() {
- if (initialized) {
- next.destroy();
- filter.destroy();
- initialized = false;
- }
- }
+ /**
+ * Append filter initialization parameter. Name and value are same as
+ * defined in the web.xml
+ *
+ * <code>
+ * <init-param>
+ * <param-name>foo</param-name>
+ * <param-value>bar</param-value>
+ * </init-param>
+ * </code>
+ *
+ * @param name
+ * name of the parameter
+ * @param value
+ * its value
+ */
+ public void addInitParameter(String name, String value) {
+ if (initialized) {
+ throw new IllegalStateException("Filter have already been initialized, init parameters can't be changed");
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#init(org.richfaces.test.staging.StagingServletContext)
- */
- public void init(final ServletContext context)
- throws ServletException {
- if (!initialized) {
- filter.init(new FilterConfig() {
+ initParameters.put(name, value);
+ }
- public String getFilterName() {
- return name;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#isApplicable(java.lang.String)
+ */
+ public boolean isApplicable(String path) {
- public String getInitParameter(String name) {
- return initParameters.get(name);
- }
+ // Delegate to the next object. Filter has a same mapping as target servlet.
+ return next.isApplicable(path);
+ }
- @SuppressWarnings("unchecked")
- public Enumeration getInitParameterNames() {
- return Collections.enumeration(initParameters.keySet());
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#destroy()
+ */
+ public void destroy() {
+ if (initialized) {
+ next.destroy();
+ filter.destroy();
+ initialized = false;
+ }
+ }
- public ServletContext getServletContext() {
- return context;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#init(org.richfaces.test.staging.StagingServletContext)
+ */
+ public void init(final ServletContext context) throws ServletException {
+ if (!initialized) {
+ filter.init(new FilterConfig() {
+ public String getFilterName() {
+ return name;
+ }
+ public String getInitParameter(String name) {
+ return initParameters.get(name);
+ }
+ @SuppressWarnings("unchecked")
+ public Enumeration getInitParameterNames() {
+ return Collections.enumeration(initParameters.keySet());
+ }
+ public ServletContext getServletContext() {
+ return context;
+ }
+ });
+ next.init(context);
+ initialized = true;
+ }
+ }
- });
- next.init(context);
- initialized = true;
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#getPathInfo(java.lang.String)
+ */
+ public String getPathInfo(String path) {
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#getPathInfo(java.lang.String)
- */
- public String getPathInfo(String path) {
- // Delegate to the next object. Filter has a same mapping as target servlet.
- return next.getPathInfo(path);
- }
+ // Delegate to the next object. Filter has a same mapping as target servlet.
+ return next.getPathInfo(path);
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#getServletPath(java.lang.String)
- */
- public String getServletPath(String path) {
- // Delegate to the next object. Filter has a same mapping as target servlet.
- return next.getServletPath(path);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#getServletPath(java.lang.String)
+ */
+ public String getServletPath(String path) {
+ // Delegate to the next object. Filter has a same mapping as target servlet.
+ return next.getServletPath(path);
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/HttpMethod.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/HttpMethod.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/HttpMethod.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -8,26 +9,19 @@
*
*/
public enum HttpMethod {
-
- GET("GET"),
- POST("POST"),
- HEAD("HEAD"),
- PUT("PUT"),
- OPTIONS("OPTIONS"),
- TRACE("TRACE"),
- DELETE("DELETE");
-
- /**
- * @param name
- */
- private HttpMethod(String name) {
- this.name = name;
- }
+ GET("GET"), POST("POST"), HEAD("HEAD"), PUT("PUT"), OPTIONS("OPTIONS"), TRACE("TRACE"), DELETE("DELETE");
- private String name;
+ private String name;
- @Override
- public String toString() {
- return name;
- }
+ /**
+ * @param name
+ */
+ private HttpMethod(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationErrorEvent.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationErrorEvent.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationErrorEvent.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,51 +1,49 @@
package org.richfaces.test.staging;
import java.lang.reflect.Method;
+
import java.util.EventObject;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
/**
* This event sent from the virtual server introspection method to the registered
- * {@link InvocationListener} instance after any exception thrown from calls to {@link HttpServletRequest} , {@link HttpServletResponse}, {@link HttpSession} and {@link ServletContext} objects.
-
+ * {@link InvocationListener} instance after any exception thrown from calls to
+ * {@link javax.servlet.http.HttpServletRequest} , {@link javax.servlet.http.HttpServletResponse},
+ * {@link javax.servlet.http.HttpSession} and {@link ServletContext} objects.
+ *
* @author asmirnov
*
*/
@SuppressWarnings("serial")
public class InvocationErrorEvent extends EventObject {
- private Object target;
- private Method method;
- private Object[] args;
- private Throwable e;
+ private Object[] args;
+ private Throwable e;
+ private Method method;
+ private Object target;
- public InvocationErrorEvent(Object target, Method method, Object[] args,
- Throwable e) {
- super(target);
- this.target = target;
- this.method = method;
- this.args = args;
- this.e = e;
- }
+ public InvocationErrorEvent(Object target, Method method, Object[] args, Throwable e) {
+ super(target);
+ this.target = target;
+ this.method = method;
+ this.args = args;
+ this.e = e;
+ }
- public Object getTarget() {
- return target;
- }
+ public Object getTarget() {
+ return target;
+ }
- public Method getMethod() {
- return method;
- }
+ public Method getMethod() {
+ return method;
+ }
- public Object[] getArgs() {
- return args;
- }
+ public Object[] getArgs() {
+ return args;
+ }
- /**
- * @return thrown exception.
- */
- public Throwable getE() {
- return e;
- }
-}
\ No newline at end of file
+ /**
+ * @return thrown exception.
+ */
+ public Throwable getE() {
+ return e;
+ }
+}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationEvent.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationEvent.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationEvent.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,59 +1,58 @@
package org.richfaces.test.staging;
import java.lang.reflect.Method;
+
import java.util.EventObject;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
/**
* This event sent from the staging server introspection method to the registered
- * {@link InvocationListener} instance after all calls to {@link HttpServletRequest} , {@link HttpServletResponse}, {@link HttpSession} and {@link ServletContext} objects.
+ * {@link InvocationListener} instance after all calls to {@link javax.servlet.http.HttpServletRequest} ,
+ * {@link javax.servlet.http.HttpServletResponse}, {@link javax.servlet.http.HttpSession}
+ * and {@link ServletContext} objects.
+ *
* @author asmirnov
*
*/
@SuppressWarnings("serial")
public class InvocationEvent extends EventObject {
- private Object target;
- private Method method;
- private Object[] args;
- private Object result;
+ private Object[] args;
+ private Method method;
+ private Object result;
+ private Object target;
- public InvocationEvent(Object target, Method method, Object[] args,
- Object result) {
- super(target);
- this.target = target;
- this.method = method;
- this.args = args;
- this.result = result;
- }
+ public InvocationEvent(Object target, Method method, Object[] args, Object result) {
+ super(target);
+ this.target = target;
+ this.method = method;
+ this.args = args;
+ this.result = result;
+ }
- /**
- * @return target object instance.
- */
- public Object getTarget() {
- return target;
- }
+ /**
+ * @return target object instance.
+ */
+ public Object getTarget() {
+ return target;
+ }
- /**
- * @return {@link Method} that was called.
- */
- public Method getMethod() {
- return method;
- }
+ /**
+ * @return {@link Method} that was called.
+ */
+ public Method getMethod() {
+ return method;
+ }
- /**
- * @return method arguments.
- */
- public Object[] getArgs() {
- return args;
- }
+ /**
+ * @return method arguments.
+ */
+ public Object[] getArgs() {
+ return args;
+ }
- /**
- * @return value returned from the invoked method.
- */
- public Object getResult() {
- return result;
- }
-}
\ No newline at end of file
+ /**
+ * @return value returned from the invoked method.
+ */
+ public Object getResult() {
+ return result;
+ }
+}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationListener.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationListener.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/InvocationListener.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,32 +1,30 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.util.EventListener;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-
/**
- * Listener interface to inspect all calls to {@link HttpServletRequest} , {@link HttpServletResponse}, {@link HttpSession} and {@link ServletContext} objects.
+ * Listener interface to inspect all calls to {@link javax.servlet.http.HttpServletRequest} ,
+ * {@link javax.servlet.http.HttpServletResponse}, {@link javax.servlet.http.HttpSession} and
+ * {@link ServletContext} objects.
+ *
* @author asmirnov
*
*/
-public interface InvocationListener extends EventListener{
+public interface InvocationListener extends EventListener {
- /**
- * This metod called after successful invocation on the target object.
- * @param invocationEvent
- */
- public void afterInvoke(InvocationEvent invocationEvent);
-
- /**
- * This method called after any {@link Throwable} thrown during method invocation.
- * @param invocationErrorEvent
- */
- public void processException(InvocationErrorEvent invocationErrorEvent);
-
+ /**
+ * This metod called after successful invocation on the target object.
+ * @param invocationEvent
+ */
+ public void afterInvoke(InvocationEvent invocationEvent);
+
+ /**
+ * This method called after any {@link Throwable} thrown during method invocation.
+ * @param invocationErrorEvent
+ */
+ public void processException(InvocationErrorEvent invocationErrorEvent);
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/NotImplementedException.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/NotImplementedException.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/NotImplementedException.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -11,36 +12,38 @@
@SuppressWarnings("serial")
public class NotImplementedException extends RuntimeException {
- /**
- *
- */
- public NotImplementedException() {
- super("This feature not yet implemented");
- }
+ /**
+ *
+ */
+ public NotImplementedException() {
+ super("This feature not yet implemented");
+ }
- /**
- * @param message
- */
- public NotImplementedException(String message) {
- super(message);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param message
+ */
+ public NotImplementedException(String message) {
+ super(message);
- /**
- * @param cause
- */
- public NotImplementedException(Throwable cause) {
- super(cause);
- // TODO Auto-generated constructor stub
- }
+ // TODO Auto-generated constructor stub
+ }
- /**
- * @param message
- * @param cause
- */
- public NotImplementedException(String message, Throwable cause) {
- super(message, cause);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param cause
+ */
+ public NotImplementedException(Throwable cause) {
+ super(cause);
+ // TODO Auto-generated constructor stub
+ }
+
+ /**
+ * @param message
+ * @param cause
+ */
+ public NotImplementedException(String message, Throwable cause) {
+ super(message, cause);
+
+ // TODO Auto-generated constructor stub
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/PageContextExtension.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/PageContextExtension.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/PageContextExtension.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,12 +1,15 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.io.IOException;
+
import java.util.Enumeration;
import javax.el.ELContext;
+
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
@@ -21,181 +24,183 @@
import javax.servlet.jsp.el.VariableResolver;
final class PageContextExtension extends PageContext {
- private ServletResponse response;
- private Servlet servlet;
- private ServletRequest request;
- private boolean needsSession;
- private int bufferSize;
- private boolean autoFlush;
+ private boolean autoFlush;
+ private int bufferSize;
+ private boolean needsSession;
+ private ServletRequest request;
+ private ServletResponse response;
+ private Servlet servlet;
+ @Override
+ public void forward(String relativeUrlPath) throws ServletException, IOException {
- @Override
- public void forward(String relativeUrlPath)
- throws ServletException, IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
- @Override
- public Exception getException() {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public Exception getException() {
- @Override
- public Object getPage() {
- return servlet;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- @Override
- public ServletRequest getRequest() {
- return request;
- }
+ @Override
+ public Object getPage() {
+ return servlet;
+ }
- @Override
- public ServletResponse getResponse() {
- return response;
- }
+ @Override
+ public ServletRequest getRequest() {
+ return request;
+ }
- @Override
- public ServletConfig getServletConfig() {
- return servlet.getServletConfig();
- }
+ @Override
+ public ServletResponse getResponse() {
+ return response;
+ }
- @Override
- public ServletContext getServletContext() {
- return servlet.getServletConfig().getServletContext();
- }
+ @Override
+ public ServletConfig getServletConfig() {
+ return servlet.getServletConfig();
+ }
- @Override
- public HttpSession getSession() {
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- return httpRequest.getSession(needsSession);
- }
+ @Override
+ public ServletContext getServletContext() {
+ return servlet.getServletConfig().getServletContext();
+ }
- @Override
- public void handlePageException(Exception e)
- throws ServletException, IOException {
- throw new ServletException(e);
-
- }
+ @Override
+ public HttpSession getSession() {
+ HttpServletRequest httpRequest = (HttpServletRequest) request;
- @Override
- public void handlePageException(Throwable t)
- throws ServletException, IOException {
- throw new ServletException(t);
-
- }
+ return httpRequest.getSession(needsSession);
+ }
- @Override
- public void include(String relativeUrlPath)
- throws ServletException, IOException {
- // TODO Auto-generated method stub
-
- }
+ @Override
+ public void handlePageException(Exception e) throws ServletException, IOException {
+ throw new ServletException(e);
+ }
- @Override
- public void include(String relativeUrlPath, boolean flush)
- throws ServletException, IOException {
- // TODO Auto-generated method stub
-
- }
+ @Override
+ public void handlePageException(Throwable t) throws ServletException, IOException {
+ throw new ServletException(t);
+ }
- @Override
- public void initialize(Servlet servlet, ServletRequest request,
- ServletResponse response, String errorPageURL,
- boolean needsSession, int bufferSize, boolean autoFlush)
- throws IOException, IllegalStateException,
- IllegalArgumentException {
- this.response = response;
- this.servlet = servlet;
- this.request = request;
- this.needsSession = needsSession;
- this.bufferSize = bufferSize;
- this.autoFlush = autoFlush;
- }
+ @Override
+ public void include(String relativeUrlPath) throws ServletException, IOException {
- @Override
- public void release() {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
- @Override
- public Object findAttribute(String name) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public void include(String relativeUrlPath, boolean flush) throws ServletException, IOException {
- @Override
- public Object getAttribute(String name) {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ }
- @Override
- public Object getAttribute(String name, int scope) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL,
+ boolean needsSession, int bufferSize, boolean autoFlush)
+ throws IOException, IllegalStateException, IllegalArgumentException {
+
+ this.response = response;
+ this.servlet = servlet;
+ this.request = request;
+ this.needsSession = needsSession;
+ this.bufferSize = bufferSize;
+ this.autoFlush = autoFlush;
+ }
- @Override
- public Enumeration<String> getAttributeNamesInScope(int scope) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public void release() {
- @Override
- public int getAttributesScope(String name) {
- // TODO Auto-generated method stub
- return 0;
- }
+ // TODO Auto-generated method stub
+ }
- @Override
- public ELContext getELContext() {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public Object findAttribute(String name) {
- @Override
- public ExpressionEvaluator getExpressionEvaluator() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- @Override
- public JspWriter getOut() {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public Object getAttribute(String name) {
- @Override
- public VariableResolver getVariableResolver() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- @Override
- public void removeAttribute(String name) {
- // TODO Auto-generated method stub
-
- }
+ @Override
+ public Object getAttribute(String name, int scope) {
- @Override
- public void removeAttribute(String name, int scope) {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- @Override
- public void setAttribute(String name, Object value) {
- // TODO Auto-generated method stub
-
- }
+ @Override
+ public Enumeration<String> getAttributeNamesInScope(int scope) {
- @Override
- public void setAttribute(String name, Object value, int scope) {
- // TODO Auto-generated method stub
-
- }
-}
\ No newline at end of file
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int getAttributesScope(String name) {
+
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public ELContext getELContext() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public ExpressionEvaluator getExpressionEvaluator() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public JspWriter getOut() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public VariableResolver getVariableResolver() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void removeAttribute(String name) {
+
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public void removeAttribute(String name, int scope) {
+
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public void setAttribute(String name, Object value) {
+
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public void setAttribute(String name, Object value, int scope) {
+
+ // TODO Auto-generated method stub
+ }
+}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/RequestChain.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/RequestChain.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/RequestChain.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -15,47 +15,45 @@
*/
public interface RequestChain {
- /**
- * Is this object applicable to process given path ?
- * @param path request path relative to web application context.
- * @return true if this object was configured to process given path.
- */
- public abstract boolean isApplicable(String path);
+ /**
+ * Is this object applicable to process given path ?
+ * @param path request path relative to web application context.
+ * @return true if this object was configured to process given path.
+ */
+ public abstract boolean isApplicable(String path);
- /**
- * Execute request with current object. Filter objects also delegate doFilter calls to the next object in the chain.
- * @param request
- * @param response
- * @throws ServletException
- * @throws IOException
- */
- public abstract void execute(ServletRequest request,
- ServletResponse response) throws ServletException, IOException;
+ /**
+ * Execute request with current object. Filter objects also delegate doFilter calls to the next object in the chain.
+ * @param request
+ * @param response
+ * @throws ServletException
+ * @throws IOException
+ */
+ public abstract void execute(ServletRequest request, ServletResponse response) throws ServletException, IOException;
- /**
- * Destroy containing web server objects.
- */
- public abstract void destroy();
+ /**
+ * Destroy containing web server objects.
+ */
+ public abstract void destroy();
- /**
- * Init containing objects ( filters or servlet ).
- * @param servletContext
- * @throws ServletException
- */
- public abstract void init(ServletContext servletContext) throws ServletException;
+ /**
+ * Init containing objects ( filters or servlet ).
+ * @param servletContext
+ * @throws ServletException
+ */
+ public abstract void init(ServletContext servletContext) throws ServletException;
- /**
- * Calculate path info for a request path.
- * @param path request path relative to the web application context.
- * @return part of the path after servlet path or null for a suffix-based mapping.
- */
- public abstract String getPathInfo(String path);
+ /**
+ * Calculate path info for a request path.
+ * @param path request path relative to the web application context.
+ * @return part of the path after servlet path or null for a suffix-based mapping.
+ */
+ public abstract String getPathInfo(String path);
- /**
- * Calculate servlet path for a given request.
- * @param path request path relative to the web application context.
- * @return prefix part from servlet mapping or {@code path} for a suffix-based mapping.
- */
- public abstract String getServletPath(String path);
-
-}
\ No newline at end of file
+ /**
+ * Calculate servlet path for a given request.
+ * @param path request path relative to the web application context.
+ * @return prefix part from servlet mapping or {@code path} for a suffix-based mapping.
+ */
+ public abstract String getServletPath(String path);
+}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerLogger.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerLogger.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerLogger.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -10,32 +11,27 @@
*
*/
public enum ServerLogger {
-
- RESOURCE("resource"),
- CONNECTION("connection"),
- SERVER("server");
-
- private static final String PREFIX="org.richfaces.test.";
-
- private static final String LOGGING_BUNDLE="org.richfaces.test.LogMessages";
- private final String name;
+ RESOURCE("resource"), CONNECTION("connection"), SERVER("server");
- /**
- * @param name
- */
- private ServerLogger(String name) {
- this.name = PREFIX+name;
- }
+ private static final String LOGGING_BUNDLE = "org.richfaces.test.LogMessages";
+ private static final String PREFIX = "org.richfaces.test.";
+ private final String name;
- /**
- * @return the name
- */
- public String getName() {
- return name;
- }
-
- public Logger getLogger(){
- return Logger.getLogger(name, LOGGING_BUNDLE);
- }
+ /**
+ * @param name
+ */
+ private ServerLogger(String name) {
+ this.name = PREFIX + name;
+ }
+ /**
+ * @return the name
+ */
+ public String getName() {
+ return name;
+ }
+
+ public Logger getLogger() {
+ return Logger.getLogger(name, LOGGING_BUNDLE);
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResource.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResource.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResource.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,11 +1,14 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.io.IOException;
import java.io.InputStream;
+
import java.net.URL;
+
import java.util.Set;
/**
@@ -13,38 +16,36 @@
*
*/
public interface ServerResource {
-
- /**
- * Get URL for a test server resource content. Directories should return null or "stub"
- * @return
- */
- public URL getURL();
-
- /**
- * Create input stream to read content. Directories returns {@code null}
- * @return
- * @throws IOException
- */
- public InputStream getAsStream() throws IOException;
-
- /**
- * @return strings representing directory content. File-like resources return null.
- */
- public Set<String> getPaths();
-
- /**
- * Append resource to the current directory-like structure.
- * @param path
- * @param resource
- */
- public void addResource(ServerResourcePath path, ServerResource resource);
-
- /**
- * Get resource from the current directory or its subdirectories.
- * @param path
- * @return
- */
- public ServerResource getResource(ServerResourcePath path);
+ /**
+ * Get URL for a test server resource content. Directories should return null or "stub"
+ * @return
+ */
+ public URL getURL();
+ /**
+ * Create input stream to read content. Directories returns {@code null}
+ * @return
+ * @throws IOException
+ */
+ public InputStream getAsStream() throws IOException;
+
+ /**
+ * @return strings representing directory content. File-like resources return null.
+ */
+ public Set<String> getPaths();
+
+ /**
+ * Append resource to the current directory-like structure.
+ * @param path
+ * @param resource
+ */
+ public void addResource(ServerResourcePath path, ServerResource resource);
+
+ /**
+ * Get resource from the current directory or its subdirectories.
+ * @param path
+ * @return
+ */
+ public ServerResource getResource(ServerResourcePath path);
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcePath.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcePath.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcePath.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,113 +1,120 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.util.regex.Pattern;
-import javax.servlet.ServletContext;
-
/**
* Class to represent web server resources directory path.
* @author asmirnov
- *
+ *
*/
public class ServerResourcePath {
-
- private static final Pattern SLASH = Pattern.compile("/");
+ public static final ServerResourcePath WEB_INF = new ServerResourcePath("/WEB-INF/");
+ public static final ServerResourcePath META_INF = new ServerResourcePath("/META-INF/");
+ public static final ServerResourcePath WEB_XML = new ServerResourcePath("/WEB-INF/web.xml");
+ public static final ServerResourcePath FACES_CONFIG = new ServerResourcePath("/WEB-INF/faces-config.xml");
- public static final ServerResourcePath WEB_INF=new ServerResourcePath("/WEB-INF/");
+ private static final Pattern SLASH = Pattern.compile("/");
+
+ private final String[] pathElements;
- public static final ServerResourcePath META_INF=new ServerResourcePath("/META-INF/");
- public static final ServerResourcePath WEB_XML=new ServerResourcePath("/WEB-INF/web.xml");
- public static final ServerResourcePath FACES_CONFIG=new ServerResourcePath("/WEB-INF/faces-config.xml");
+ /**
+ * Create path from string representation. Path have to started with training slash, as required for
+ * {@link javax.servlet.ServletContext#getResource(String)}
+ * @param path
+ */
+ public ServerResourcePath(String path) {
+ if (null == path) {
+ throw new NullPointerException();
+ }
+ if (!path.startsWith("/")) {
+ throw new IllegalArgumentException();
+ }
- private final String[] pathElements;
+ String[] split = SLASH.split(path);
- /**
- * Private constructor for next sub - path.
- * @param pathElements
- */
- private ServerResourcePath(String[] pathElements) {
- this.pathElements = pathElements;
- }
+ if (split.length > 1 && path.endsWith("/")) {
+ pathElements = new String[split.length + 1];
+ System.arraycopy(split, 0, pathElements, 0, split.length);
+ } else {
+ pathElements = split;
+ }
+ }
- /**
- * Create path from string representation. Path have to started with training slash, as required for
- * {@link ServletContext#getResource(String)}
- * @param path
- */
- public ServerResourcePath(String path) {
- if (null == path) {
- throw new NullPointerException();
- }
- if (!path.startsWith("/")) {
- throw new IllegalArgumentException();
- }
- String[] split = SLASH.split(path);
- if(split.length >1 && path.endsWith("/")){
- pathElements = new String[split.length+1];
- System.arraycopy(split, 0, pathElements, 0, split.length);
- } else {
- pathElements = split;
- }
- }
+ /**
+ * Private constructor for next sub - path.
+ * @param pathElements
+ */
+ private ServerResourcePath(String[] pathElements) {
+ this.pathElements = pathElements;
+ }
- /**
- * Method to detect last element in the path.
- * @return true for a last element in the path.
- */
- public boolean isFile() {
- return pathElements.length <= 1 || null == pathElements[1];
- }
+ /**
+ * Method to detect last element in the path.
+ * @return true for a last element in the path.
+ */
+ public boolean isFile() {
+ return pathElements.length <= 1 || null == pathElements[1];
+ }
- /**
- * Name of the next element ( directory or file ) name.
- * For the "/foo/bar/baz" it should be "foo/" , /bar/baz : "bar/" , "/" : null.
- * @return name of the next element or null if it is last element in the chain ( file ).
- */
- public String getNextElementName() {
- if (pathElements.length > 1) {
- String name = pathElements[1];
- if(pathElements.length>2){
- name+='/';
- }
- return name;
- } else {
- return null;
- }
- }
+ /**
+ * Name of the next element ( directory or file ) name.
+ * For the "/foo/bar/baz" it should be "foo/" , /bar/baz : "bar/" , "/" : null.
+ * @return name of the next element or null if it is last element in the chain ( file ).
+ */
+ public String getNextElementName() {
+ if (pathElements.length > 1) {
+ String name = pathElements[1];
- /**
- * Create next path of the path chain.
- * Path /foo/bar/baz should be converted to /bar/baz , /bar/baz -> /baz -> / ( empty path )
- * @return next subdirectory path or null.
- */
- public ServerResourcePath getNextPath() {
- if (pathElements.length > 1 && null != pathElements[1]) {
- String[] nextElenemts = new String[pathElements.length - 1];
- System.arraycopy(pathElements, 1, nextElenemts, 0, nextElenemts.length);
- return new ServerResourcePath(nextElenemts);
- } else {
- return null;
- }
- }
-
- @Override
- public String toString() {
- StringBuilder str = new StringBuilder();
- if (pathElements.length > 1) {
- for (int i = 1; i < pathElements.length; i++) {
- String element = pathElements[i];
- str.append("/");
- if(null != element){
- str.append(element);
- }
- }
- } else {
- str.append("/");
- }
- return str.toString();
- }
+ if (pathElements.length > 2) {
+ name += '/';
+ }
+
+ return name;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Create next path of the path chain.
+ * Path /foo/bar/baz should be converted to /bar/baz , /bar/baz -> /baz -> / ( empty path )
+ * @return next subdirectory path or null.
+ */
+ public ServerResourcePath getNextPath() {
+ if (pathElements.length > 1 && null != pathElements[1]) {
+ String[] nextElenemts = new String[pathElements.length - 1];
+
+ System.arraycopy(pathElements, 1, nextElenemts, 0, nextElenemts.length);
+
+ return new ServerResourcePath(nextElenemts);
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder str = new StringBuilder();
+
+ if (pathElements.length > 1) {
+ for (int i = 1; i < pathElements.length; i++) {
+ String element = pathElements[i];
+
+ str.append("/");
+
+ if (null != element) {
+ str.append(element);
+ }
+ }
+ } else {
+ str.append("/");
+ }
+
+ return str.toString();
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcesDirectory.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcesDirectory.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServerResourcesDirectory.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,10 +1,13 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.io.InputStream;
+
import java.net.URL;
+
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -15,79 +18,90 @@
*
*/
public class ServerResourcesDirectory implements ServerResource {
-
-
- /**
- * Directory content.
- */
- private final Map<String,ServerResource> children = new HashMap<String,ServerResource>();
+ /**
+ * Directory content.
+ */
+ private final Map<String, ServerResource> children = new HashMap<String, ServerResource>();
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.ServerResource#addResource(org.richfaces.test.staging.ServerResource)
- */
- public void addResource(ServerResourcePath path,ServerResource resource) {
-
- if(null == path || path.isFile()){
- throw new IllegalArgumentException();
- } else if(path.getNextPath().isFile()) {
- // This is a last part in the path - append resource to the directory content.
- children.put(path.getNextElementName(), resource);
- } else {
- // Create a next directory entry.
- ServerResource nextDirectory = children.get(path.getNextElementName());
- if(null == nextDirectory){
- nextDirectory = new ServerResourcesDirectory();
- children.put(path.getNextElementName(), nextDirectory);
- }
- nextDirectory.addResource(path.getNextPath(), resource);
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.ServerResource#addResource(org.richfaces.test.staging.ServerResource)
+ */
+ public void addResource(ServerResourcePath path, ServerResource resource) {
+ if (null == path || path.isFile()) {
+ throw new IllegalArgumentException();
+ } else if (path.getNextPath().isFile()) {
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.ServerResource#getResource(org.richfaces.test.staging.ServerResourcePath)
- */
- public ServerResource getResource(ServerResourcePath path) {
- if(null == path){
- throw new NullPointerException();
- }
- ServerResource resource = null; //children.get(path.getName());
- if(path.isFile()){
- // Path points to the resource itself.
- resource=this;
- } else {
- resource = children.get(path.getNextElementName());
- if(!path.getNextPath().isFile() && null!=resource){
- // Get next resource in the tree, if exists.
- resource = resource.getResource(path.getNextPath());
- }
- }
- return resource;
- }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.ServerResource#getAsStream()
- */
- public InputStream getAsStream() {
- // can't read directory.
- return null;
- }
+ // This is a last part in the path - append resource to the directory content.
+ children.put(path.getNextElementName(), resource);
+ } else {
+ // Create a next directory entry.
+ ServerResource nextDirectory = children.get(path.getNextElementName());
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.ServerResource#getPaths()
- */
- public Set<String> getPaths() {
- return children.keySet();
- }
+ if (null == nextDirectory) {
+ nextDirectory = new ServerResourcesDirectory();
+ children.put(path.getNextElementName(), nextDirectory);
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.ServerResource#getURL()
- */
- public URL getURL() {
- // Directory don't have url.
- return null;
- }
+ nextDirectory.addResource(path.getNextPath(), resource);
+ }
+ }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.ServerResource#getResource(org.richfaces.test.staging.ServerResourcePath)
+ */
+ public ServerResource getResource(ServerResourcePath path) {
+ if (null == path) {
+ throw new NullPointerException();
+ }
-
+ ServerResource resource = null; // children.get(path.getName());
+
+ if (path.isFile()) {
+
+ // Path points to the resource itself.
+ resource = this;
+ } else {
+ resource = children.get(path.getNextElementName());
+
+ if (!path.getNextPath().isFile() && null != resource) {
+
+ // Get next resource in the tree, if exists.
+ resource = resource.getResource(path.getNextPath());
+ }
+ }
+
+ return resource;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.ServerResource#getAsStream()
+ */
+ public InputStream getAsStream() {
+
+ // can't read directory.
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.ServerResource#getPaths()
+ */
+ public Set<String> getPaths() {
+ return children.keySet();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.ServerResource#getURL()
+ */
+ public URL getURL() {
+
+ // Directory don't have url.
+ return null;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServletContainer.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServletContainer.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/ServletContainer.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,9 +1,11 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.io.IOException;
+
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
@@ -17,197 +19,187 @@
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
-
/**
* This class represens Servlet in the web application.
* @author asmirnov
- *
+ *
*/
public class ServletContainer implements RequestChain {
+ private static final Logger LOG = ServerLogger.SERVER.getLogger();
+ private String name = "Default";
+ private boolean initialized = false;
+ private final Map<String, String> initParameters;
+ private final String mapping;
+ private final boolean prefixMapped;
+ private final Servlet servlet;
- private static final Logger log = ServerLogger.SERVER.getLogger();
+ /**
+ * @param mapping Servlet mapping pattern, as defined in the <servlet-mapping> element.
+ * @param servlet servlet instance. Can't be null.
+ * @throws NullPointerException if servlet parameter is null.
+ */
+ public ServletContainer(String mapping, Servlet servlet) {
+ if (null == servlet) {
+ throw new NullPointerException();
+ }
- private final Servlet servlet;
+ if (null == mapping) {
+ this.prefixMapped = true;
+ this.mapping = "";
+ } else if (mapping.startsWith("*")) {
+ this.prefixMapped = false;
+ this.mapping = mapping.substring(1);
+ } else if (mapping.endsWith("*")) {
+ this.prefixMapped = true;
+ this.mapping = mapping.substring(0, mapping.length() - 1);
+ } else {
+ throw new IllegalArgumentException("Invalid mapping " + mapping);
+ }
- private final boolean prefixMapped;
+ this.servlet = servlet;
+ this.initParameters = new HashMap<String, String>();
+ }
- private final String mapping;
+ /**
+ * Append filter initialization parameter. Name and value are same as
+ * defined in the web.xml
+ *
+ * <code>
+ * <init-param>
+ * <param-name>foo</param-name>
+ * <param-value>bar</param-value>
+ * </init-param>
+ * </code>
+ *
+ * @param name
+ * @param value
+ * @throws IllegalStateException if servlet was already initialized.
+ */
+ public void addInitParameter(String name, String value) {
+ if (initialized) {
+ throw new IllegalStateException("Servlet have already been initialized, init parameters can't be changed");
+ }
- private final Map<String, String> initParameters;
+ initParameters.put(name, value);
+ }
- private String name = "Default";
+ /**
+ * @return the name of servlet
+ */
+ public String getName() {
+ return name;
+ }
- private boolean initialized = false;
+ /**
+ * @param name
+ * the name to set
+ * @throws IllegalStateException if servlet was already initialized.
+ */
+ public void setName(String name) {
+ if (initialized) {
+ throw new IllegalStateException("Servlet have already been initialized, name can't be changed");
+ }
- /**
- * @param mapping Servlet mapping pattern, as defined in the <servlet-mapping> element.
- * @param servlet servlet instance. Can't be null.
- * @throws NullPointerException if servlet parameter is null.
- */
- public ServletContainer(String mapping, Servlet servlet) {
- if(null == servlet){
- throw new NullPointerException();
- }
- if (null == mapping) {
- this.prefixMapped = true;
- this.mapping = "";
- } else if (mapping.startsWith("*")) {
- this.prefixMapped = false;
- this.mapping = mapping.substring(1);
- } else if (mapping.endsWith("*")) {
- this.prefixMapped = true;
- this.mapping = mapping.substring(0, mapping.length() - 1);
- } else {
- throw new IllegalArgumentException("Invalid mapping " + mapping);
- }
- this.servlet = servlet;
- this.initParameters = new HashMap<String, String>();
- }
+ this.name = name;
+ }
- /**
- * Append filter initialization parameter. Name and value are same as
- * defined in the web.xml
- *
- * <code>
- * <init-param>
- * <param-name>foo</param-name>
- * <param-value>bar</param-value>
- * </init-param>
- * </code>
- *
- * @param name
- * @param value
- * @throws IllegalStateException if servlet was already initialized.
- */
- public void addInitParameter(String name, String value) {
- if (initialized) {
- throw new IllegalStateException(
- "Servlet have already been initialized, init parameters can't be changed");
- }
- initParameters.put(name, value);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.RequestChain#isApplicable(java.lang.String)
+ */
+ public boolean isApplicable(String path) {
+ if (prefixMapped && path.startsWith(mapping)) {
+ return true;
+ } else {
+ return !prefixMapped && path.endsWith(mapping);
+ }
+ }
- /**
- * @return the name of servlet
- */
- public String getName() {
- return name;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#getServletPath(java.lang.String)
+ */
+ public String getServletPath(String path) {
+ if (!isApplicable(path)) {
+ return null;
+ }
- /**
- * @param name
- * the name to set
- * @throws IllegalStateException if servlet was already initialized.
- */
- public void setName(String name) {
- if (initialized) {
- throw new IllegalStateException(
- "Servlet have already been initialized, name can't be changed");
- }
- this.name = name;
- }
+ if (prefixMapped) {
+ return mapping;
+ } else {
+ return path;
+ }
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.RequestChain#isApplicable(java.lang.String)
- */
- public boolean isApplicable(String path) {
- if (prefixMapped && path.startsWith(mapping)) {
- return true;
- } else if (!prefixMapped && path.endsWith(mapping)) {
- return true;
- } else {
- return false;
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#getPathInfo(java.lang.String)
+ */
+ public String getPathInfo(String path) {
+ if (!isApplicable(path)) {
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#getServletPath(java.lang.String)
- */
- public String getServletPath(String path) {
- if (!isApplicable(path)) {
- return null;
- }
- if (prefixMapped) {
- return mapping;
- } else {
- return path;
- }
- }
+ if (prefixMapped) {
+ return path.substring(mapping.length());
+ } else {
+ return null;
+ }
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#getPathInfo(java.lang.String)
- */
- public String getPathInfo(String path) {
- if (!isApplicable(path)) {
- return null;
- }
- if (prefixMapped) {
- return path.substring(mapping.length());
- } else {
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#init(org.richfaces.test.staging.StagingServletContext)
+ */
+ public void init(final ServletContext context) throws ServletException {
+ if (!initialized) {
+ LOG.finest("Initialize servlet " + getName());
+ servlet.init(new ServletConfig() {
+ public String getInitParameter(String name) {
+ return initParameters.get(name);
+ }
+ @SuppressWarnings("unchecked")
+ public Enumeration getInitParameterNames() {
+ return Collections.enumeration(initParameters.keySet());
+ }
+ public ServletContext getServletContext() {
+ return context;
+ }
+ public String getServletName() {
+ return name;
+ }
+ });
+ initialized = true;
+ }
+ }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.RequestChain#execute(javax.servlet.ServletRequest
+ * , javax.servlet.ServletResponse)
+ */
+ public void execute(ServletRequest request, ServletResponse response) throws ServletException, IOException {
+ if (!initialized) {
+ throw new IllegalStateException("Servlet " + getName()
+ + " have not been initialized, could'n execute request");
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#init(org.richfaces.test.staging.StagingServletContext)
- */
- public void init(final ServletContext context)
- throws ServletException {
- if (!initialized) {
- log.finest("Initialize servlet "+getName());
- servlet.init(new ServletConfig() {
+ LOG.finest("Request '" + request + "' executes by the '" + getName() + "' servlet");
+ this.servlet.service(request, response);
+ }
- public String getInitParameter(String name) {
- return initParameters.get(name);
- }
-
- @SuppressWarnings("unchecked")
- public Enumeration getInitParameterNames() {
- return Collections.enumeration(initParameters.keySet());
- }
-
- public ServletContext getServletContext() {
- return context;
- }
-
- public String getServletName() {
- return name;
- }
-
- });
- initialized = true;
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.RequestChain#execute(javax.servlet.ServletRequest
- * , javax.servlet.ServletResponse)
- */
- public void execute(ServletRequest request, ServletResponse response)
- throws ServletException, IOException {
- if (!initialized) {
- throw new IllegalStateException(
- "Servlet "+getName()+" have not been initialized, could'n execute request");
- }
- log.finest("Request '"+request+"' executes by the '"+getName()+"' servlet");
- this.servlet.service(request, response);
-
- }
-
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.RequestChain#destroy()
- */
- public void destroy() {
- if (initialized) {
- this.servlet.destroy();
- initialized = false;
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.RequestChain#destroy()
+ */
+ public void destroy() {
+ if (initialized) {
+ this.servlet.destroy();
+ initialized = false;
+ }
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaggingJspApplicationContext.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaggingJspApplicationContext.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaggingJspApplicationContext.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,63 +1,64 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import javax.el.ELContextListener;
import javax.el.ELResolver;
import javax.el.ExpressionFactory;
+
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspApplicationContext;
import org.richfaces.test.TestException;
-
/**
* @author asmirnov
*
*/
public class StaggingJspApplicationContext implements JspApplicationContext {
-
- private static final String DEFAULT_EXPRESSION_FACTORY="com.sun.el.ExpressionFactoryImpl";
-
- private final ExpressionFactory expressionFactory ;
- private final ServletContext servletContext;
-
+ private static final String DEFAULT_EXPRESSION_FACTORY = "com.sun.el.ExpressionFactoryImpl";
+ private final ExpressionFactory expressionFactory;
+ private final ServletContext servletContext;
- public StaggingJspApplicationContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- String elFactoryClass = servletContext.getInitParameter("com.sun.faces.expressionFactory");
- if(null == elFactoryClass){
- elFactoryClass = servletContext.getInitParameter("com.sun.el.ExpressionFactoryImpl");
- }
- if(null == elFactoryClass){
- elFactoryClass = DEFAULT_EXPRESSION_FACTORY;
- }
- try {
- expressionFactory = Class.forName(elFactoryClass).asSubclass(ExpressionFactory.class).newInstance();
- } catch (Exception e) {
- throw new TestException("Couldn't instantiate EL expression factory",e);
- }
- }
+ public StaggingJspApplicationContext(ServletContext servletContext) {
+ this.servletContext = servletContext;
- /* (non-Javadoc)
- * @see javax.servlet.jsp.JspApplicationContext#addELContextListener(javax.el.ELContextListener)
- */
- public void addELContextListener(ELContextListener listener) {
+ String elFactoryClass = servletContext.getInitParameter("com.sun.faces.expressionFactory");
- }
+ if (null == elFactoryClass) {
+ elFactoryClass = servletContext.getInitParameter("com.sun.el.ExpressionFactoryImpl");
+ }
- /* (non-Javadoc)
- * @see javax.servlet.jsp.JspApplicationContext#addELResolver(javax.el.ELResolver)
- */
- public void addELResolver(ELResolver resolver) {
- }
+ if (null == elFactoryClass) {
+ elFactoryClass = DEFAULT_EXPRESSION_FACTORY;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.jsp.JspApplicationContext#getExpressionFactory()
- */
- public ExpressionFactory getExpressionFactory() {
- return expressionFactory;
- }
+ try {
+ expressionFactory = Class.forName(elFactoryClass).asSubclass(ExpressionFactory.class).newInstance();
+ } catch (Exception e) {
+ throw new TestException("Couldn't instantiate EL expression factory", e);
+ }
+ }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.jsp.JspApplicationContext#addELContextListener(javax.el.ELContextListener)
+ */
+ public void addELContextListener(ELContextListener listener) {}
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.jsp.JspApplicationContext#addELResolver(javax.el.ELResolver)
+ */
+ public void addELResolver(ELResolver resolver) {}
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.jsp.JspApplicationContext#getExpressionFactory()
+ */
+ public ExpressionFactory getExpressionFactory() {
+ return expressionFactory;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaggingJspFactory.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaggingJspFactory.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaggingJspFactory.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -18,78 +19,75 @@
* Stagging implementation of the {@link JspFactory} to simulate JSP processing in the stagging server.
* TODO - implement JSP functionality.
* @author asmirnov
- *
+ *
*/
public class StaggingJspFactory extends JspFactory {
+ private static final JspEngineInfo ENGINE_INFO = new JspEngineInfo() {
+ @Override
+ public String getSpecificationVersion() {
+ return "2.1";
+ }
+ };
+ private final JspApplicationContext context;
- private static final JspEngineInfo engineInfo = new JspEngineInfo() {
+ public StaggingJspFactory(ServletContext servletContext) {
+ this.context = new StaggingJspApplicationContext(servletContext);
+ }
- @Override
- public String getSpecificationVersion() {
- return "2.1";
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.jsp.JspFactory#getEngineInfo()
+ */
+ @Override
+ public JspEngineInfo getEngineInfo() {
- };
+ // TODO Auto-generated method stub
+ return ENGINE_INFO;
+ }
- private final JspApplicationContext context;
+ /*
+ * (non-Javadoc)
+ *
+ * @seejavax.servlet.jsp.JspFactory#getJspApplicationContext(javax.servlet.
+ * ServletContext)
+ */
+ @Override
+ public JspApplicationContext getJspApplicationContext(ServletContext context) {
+ return this.context;
+ }
- public StaggingJspFactory(ServletContext servletContext) {
- this.context = new StaggingJspApplicationContext(servletContext);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.jsp.JspFactory#getPageContext(javax.servlet.Servlet,
+ * javax.servlet.ServletRequest, javax.servlet.ServletResponse,
+ * java.lang.String, boolean, int, boolean)
+ */
+ @Override
+ public PageContext getPageContext(final Servlet servlet, final ServletRequest request,
+ final ServletResponse response, String errorPageURL, final boolean needsSession,
+ int buffer, boolean autoflush) {
+ PageContextExtension pageContextExtension = new PageContextExtension();
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.jsp.JspFactory#getEngineInfo()
- */
- @Override
- public JspEngineInfo getEngineInfo() {
- // TODO Auto-generated method stub
- return engineInfo;
- }
+ try {
+ pageContextExtension.initialize(servlet, request, response, errorPageURL, needsSession, buffer, autoflush);
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
- /*
- * (non-Javadoc)
- *
- * @seejavax.servlet.jsp.JspFactory#getJspApplicationContext(javax.servlet.
- * ServletContext)
- */
- @Override
- public JspApplicationContext getJspApplicationContext(ServletContext context) {
- return this.context;
- }
+ return pageContextExtension;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.jsp.JspFactory#getPageContext(javax.servlet.Servlet,
- * javax.servlet.ServletRequest, javax.servlet.ServletResponse,
- * java.lang.String, boolean, int, boolean)
- */
- @Override
- public PageContext getPageContext(final Servlet servlet, final ServletRequest request,
- final ServletResponse response, String errorPageURL,
- final boolean needsSession, int buffer, boolean autoflush) {
- PageContextExtension pageContextExtension = new PageContextExtension();
- try {
- pageContextExtension.initialize(servlet, request, response, errorPageURL, needsSession, buffer, autoflush);
- } catch (IOException e) {
- throw new IllegalStateException(e);
- }
- return pageContextExtension;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.jsp.JspFactory#releasePageContext(javax.servlet.jsp.PageContext
- * )
- */
- @Override
- public void releasePageContext(PageContext pc) {
- pc.release();
-
- }
-
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.jsp.JspFactory#releasePageContext(javax.servlet.jsp.PageContext
+ * )
+ */
+ @Override
+ public void releasePageContext(PageContext pc) {
+ pc.release();
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingConnection.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingConnection.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingConnection.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,14 +1,18 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
+
import java.lang.reflect.Proxy;
+
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
@@ -29,596 +33,618 @@
import org.richfaces.test.TestException;
/**
- * This class represent single connection ( request ) to the virtual server. These instance should not be created directly, but by the {@link StagingServer#getConnection(URL)}.
- * method only.
+ * This class represent single connection ( request ) to the virtual server. These instance should not be created
+ * directly, but by the {@link StagingServer#getConnection(URL)}. method only.
* Since instance have been created, additional request parameters and headers can be set.
* @author asmirnov
- *
+ *
*/
public class StagingConnection {
+ private static final Logger LOG = ServerLogger.SERVER.getLogger();
+ private static final Cookie[] COOKIE = new Cookie[] {};
- private static final Logger log = ServerLogger.SERVER.getLogger();
+ final URL url;
- private final StagingServer server;
+ private HttpMethod method = HttpMethod.GET;
+ private List<Cookie> cookies = new ArrayList<Cookie>();
+ private Map<String, String[]> requestParameters = new HashMap<String, String[]>();
+ private boolean finished = false;
+ private boolean started = false;
+ private final String pathInfo;
+ private String queryString;
+ private ConnectionRequest request;
+ private HttpServletRequest requestProxy;
+ private ConnectionResponse response;
+ private HttpServletResponse responseProxy;
+ private final StagingServer server;
+ private final RequestChain servlet;
+ private final String servletPath;
- final URL url;
+ /**
+ * Create connection instance.
+ * @param localServer virtual server instance.
+ * @param url request URL.
+ */
+ StagingConnection(StagingServer localServer, URL url) {
+ this.server = localServer;
+ this.url = url;
- private ConnectionRequest request;
+ // TODO - context path support.
+ String path = url.getPath();
- private ConnectionResponse response;
+ servlet = localServer.getServlet(path);
- private final RequestChain servlet;
+ if (null == servlet) {
+ throw new IllegalArgumentException();
+ }
- private HttpMethod method = HttpMethod.GET;
+ this.pathInfo = servlet.getPathInfo(path);
+ this.servletPath = servlet.getServletPath(path);
+ this.request = new ConnectionRequest();
+ this.response = new ConnectionResponse();
+ this.request.setAttribute("javax.servlet.include.path_info", this.pathInfo);
+ this.request.setAttribute("javax.servlet.include.servlet_path", this.servletPath);
+ setQueryString(url.getQuery());
- private static final Cookie[] COOKIE = new Cookie[] {};
+ if (null != getQueryString()) {
+ parseFormParameters(queryString);
+ }
- private List<Cookie> cookies = new ArrayList<Cookie>();
+ // Create proxy objects.
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
- private Map<String, String[]> requestParameters = new HashMap<String, String[]>();
+ if (null == loader) {
+ loader = this.getClass().getClassLoader();
+ }
- private final String pathInfo;
+ requestProxy = (HttpServletRequest) Proxy.newProxyInstance(loader, new Class[] {HttpServletRequest.class},
+ server.getInvocationHandler(request));
+ responseProxy = (HttpServletResponse) Proxy.newProxyInstance(loader, new Class[] {HttpServletResponse.class},
+ server.getInvocationHandler(response));
+ }
- private final String servletPath;
+ /**
+ * Parse 'application/x-www-form-urlencoded' string with parameters name/value pairs,
+ * as it expected after a form submit.
+ * @param queryString URL query string or POST content.
+ */
+ public void parseFormParameters(String queryString) {
+ String[] queryParams = queryString.split("&");
- private boolean finished = false;
+ for (int i = 0; i < queryParams.length; i++) {
+ try {
+ String par = queryParams[i];
+ int eqIndex = par.indexOf('=');
- private boolean started = false;
+ if (eqIndex >= 0) {
- private String queryString;
+ // decode url-decoded values.
+ String name = URLDecoder.decode(par.substring(0, eqIndex), request.getCharacterEncoding());
+ String value = URLDecoder.decode(par.substring(eqIndex + 1), request.getCharacterEncoding());
- private HttpServletRequest requestProxy;
+ addRequestParameter(name, value);
+ } else {
+ addRequestParameter(URLDecoder.decode(par, request.getCharacterEncoding()), null);
+ }
+ } catch (UnsupportedEncodingException e) {
+ throw new TestException(e);
+ }
+ }
+ }
- private HttpServletResponse responseProxy;
+ /**
+ * @return the finished
+ */
+ public boolean isFinished() {
+ return finished;
+ }
- /**
- * Create connection instance.
- * @param localServer virtual server instance.
- * @param url request URL.
- */
- StagingConnection(StagingServer localServer, URL url) {
- this.server = localServer;
- this.url = url;
- // TODO - context path support.
- String path = url.getPath();
- servlet = localServer.getServlet(path);
- if (null == servlet) {
- throw new IllegalArgumentException();
- }
- this.pathInfo = servlet.getPathInfo(path);
- this.servletPath = servlet.getServletPath(path);
- this.request = new ConnectionRequest();
- this.response = new ConnectionResponse();
- this.request.setAttribute("javax.servlet.include.path_info",
- this.pathInfo);
- this.request.setAttribute("javax.servlet.include.servlet_path",
- this.servletPath);
- setQueryString(url.getQuery());
- if (null != getQueryString()) {
- parseFormParameters(queryString);
- }
-
- // Create proxy objects.
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- if(null == loader){
- loader = this.getClass().getClassLoader();
- }
- requestProxy = (HttpServletRequest) Proxy.newProxyInstance(loader, new Class[]{HttpServletRequest.class}, server.getInvocationHandler(request));
- responseProxy = (HttpServletResponse) Proxy.newProxyInstance(loader, new Class[]{HttpServletResponse.class}, server.getInvocationHandler(response));
- }
+ /**
+ * @return the started
+ */
+ public boolean isStarted() {
+ return started;
+ }
- /**
- * Parse 'application/x-www-form-urlencoded' string with parameters name/value pairs,
- * as it expected after a form submit.
- * @param queryString URL query string or POST content.
- */
- public void parseFormParameters(String queryString) {
- String[] queryParams = queryString.split("&");
- for (int i = 0; i < queryParams.length; i++) {
- try {
- String par = queryParams[i];
- int eqIndex = par.indexOf('=');
- if (eqIndex >= 0) {
- // decode url-decoded values.
- String name = URLDecoder.decode(par.substring(0, eqIndex),
- request.getCharacterEncoding());
- String value = URLDecoder.decode(
- par.substring(eqIndex + 1), request
- .getCharacterEncoding());
- addRequestParameter(name, value);
- } else {
- addRequestParameter(URLDecoder.decode(par, request
- .getCharacterEncoding()), null);
- }
- } catch (UnsupportedEncodingException e) {
- throw new TestException(e);
- }
- }
- }
+// private void checkStarted() {
+// if (!isFinished()) {
+// throw new TestException("request have not been started");
+// }
+// }
+// private void checkNotStarted() {
+// if (isStarted()) {
+// throw new TestException("request was started, no parameters changes allowed");
+// }
+// }
- /**
- * @return the finished
- */
- public boolean isFinished() {
- return finished;
- }
+ /**
+ * Execute this connection request on the associated servlet or filter chain.
+ * @throws TestException if any errors were during execution.
+ */
+ public void execute() {
+ if (isStarted() || isFinished()) {
+ throw new TestException("request have already been executed");
+ }
- /**
- * @return the started
- */
- public boolean isStarted() {
- return started;
- }
+ start();
-// private void checkStarted() {
-// if (!isFinished()) {
-// throw new TestException("request have not been started");
-// }
-// }
+ try {
+ this.servlet.execute(request, response);
+ } catch (ServletException e) {
+ throw new TestException("Error execute request ", e);
+ } catch (IOException e) {
+ throw new TestException("IO Error during request execution", e);
+ } finally {
+ finish();
+ }
+ }
-// private void checkNotStarted() {
-// if (isStarted()) {
-// throw new TestException("request was started, no parameters changes allowed");
-// }
-// }
+ /**
+ * Finish request to the this connection, inform server listeners about request status.
+ */
+ public void finish() {
+ server.requestFinished(request);
+ finished = true;
+ }
- /**
- * Execute this connection request on the associated servlet or filter chain.
- * @throws TestException if any errors were during execution.
- */
- public void execute() {
- if (isStarted() || isFinished()) {
- throw new TestException(
- "request have already been executed");
- }
- start();
- try {
- this.servlet.execute(request, response);
- } catch (ServletException e) {
- throw new TestException("Error execute request ",e);
- } catch (IOException e) {
- throw new TestException("IO Error during request execution",e);
- } finally {
- finish();
- }
- }
+ /**
+ * Start request to the this connection, inform server listeners about request status.
+ * No request parameters changes allowed after connection start.
+ */
+ public void start() {
+ LOG.fine("start " + getRequestMethod() + " request processing for file " + url.getFile());
+ LOG.fine("request parameters: " + requestParameters);
+ server.requestStarted(request);
+ started = true;
+ }
- /**
- * Finish request to the this connection, inform server listeners about request status.
- */
- public void finish() {
- server.requestFinished(request);
- finished = true;
- }
+ /**
+ * Get request HTTP methos ( GET, POST etc ).
+ * @return the method
+ */
+ public HttpMethod getRequestMethod() {
+ return method;
+ }
- /**
- * Start request to the this connection, inform server listeners about request status.
- * No request parameters changes allowed after connection start.
- */
- public void start() {
- log.fine("start " + getRequestMethod() + " request processing for file "
- + url.getFile());
- log.fine("request parameters: " + requestParameters);
- server.requestStarted(request);
- started = true;
- }
+ /**
+ * Set request HTTP methos ( GET, POST etc ).
+ * @param method
+ * the method to set
+ */
+ public void setRequestMethod(HttpMethod method) {
- /**
- * Get request HTTP methos ( GET, POST etc ).
- * @return the method
- */
- public HttpMethod getRequestMethod() {
- return method;
- }
+// checkNotStarted();
+ this.method = method;
+ }
- /**
- * Set request HTTP methos ( GET, POST etc ).
- * @param method
- * the method to set
- */
- public void setRequestMethod(HttpMethod method) {
-// checkNotStarted();
- this.method = method;
- }
+ /**
+ * Get request url.
+ * @return the url
+ */
+ public URL getUrl() {
+ return url;
+ }
- /**
- * Get request url.
- * @return the url
- */
- public URL getUrl() {
- return url;
- }
+ /**
+ * Append additional request parameter.
+ * @param name
+ * @param value
+ */
+ public void addRequestParameter(String name, String value) {
- /**
- * Append additional request parameter.
- * @param name
- * @param value
- */
- public void addRequestParameter(String name, String value) {
-// checkNotStarted();
- String[] values = requestParameters.get(name);
- if (null == values) {
- values = new String[1];
- } else {
- String[] newValues = new String[values.length + 1];
- System.arraycopy(values, 0, newValues, 0, values.length);
- values = newValues;
- }
- values[values.length - 1] = value;
- requestParameters.put(name, values);
- }
+// checkNotStarted();
+ String[] values = requestParameters.get(name);
- /**
- * Get content of the response as String.
- * @return content of the response writer or String created from the ServletOutputStream with current response encoding.
- * @throws TestException
- * if has an unsupported encoding.
- */
- public String getContentAsString() {
-// checkStarted();
- String content = response.getWriterContent();
- if (null == content) {
- byte[] streamContent = response.getStreamContent();
- if (null != streamContent) {
- String encoding = response.getCharacterEncoding();
- if (null != encoding) {
- try {
- content = new String(streamContent, encoding);
- } catch (UnsupportedEncodingException e) {
- throw new TestException(e);
- }
- } else {
- content = new String(streamContent);
- }
- }
- }
- return content;
- }
+ if (null == values) {
+ values = new String[1];
+ } else {
+ String[] newValues = new String[values.length + 1];
- /**
- * Get content of the response as byte array.
- * @return content of the ServletOutputStream or convert String, collected by response writer, with current response encoding.
- * @throws TestException
- * if response has unsupported encoding.
- */
- public byte[] getResponseBody() {
-// checkStarted();
- byte[] content = response.getStreamContent();
- if (null == content) {
- String writerContent = response.getWriterContent();
- if (null != writerContent) {
- try {
- content = writerContent.getBytes(response
- .getCharacterEncoding());
- } catch (UnsupportedEncodingException e) {
- content = writerContent.getBytes();
- }
- } else {
- content = new byte[0];
- }
- }
- return content;
- }
+ System.arraycopy(values, 0, newValues, 0, values.length);
+ values = newValues;
+ }
- /**
- * List of the {@link Cookie} used by the request or response ( There are same cookies for both request and response ).
- * @return the cookies
- */
- public List<Cookie> getCookies() {
- return cookies;
- }
+ values[values.length - 1] = value;
+ requestParameters.put(name, values);
+ }
- /**
- * request object for the this connection.
- * @return the request
- */
- public HttpServletRequest getRequest() {
- return requestProxy;
- }
+ /**
+ * Get content of the response as String.
+ * @return content of the response writer or String created from the ServletOutputStream with current response
+ * encoding.
+ *
+ * @throws TestException
+ * if has an unsupported encoding.
+ */
+ public String getContentAsString() {
- /**
- * response object for the this connection.
- * @return the response
- */
- public HttpServletResponse getResponse() {
- return responseProxy;
- }
+// checkStarted();
+ String content = response.getWriterContent();
- /**
- * @return encoding used to write response.
- */
- public String getResponseCharacterEncoding() {
-// checkStarted();
- return response.getCharacterEncoding();
- }
+ if (null == content) {
+ byte[] streamContent = response.getStreamContent();
- /**
- * @return content type ( eg 'text/html' ) of the response.
- */
- public String getResponseContentType() {
-// checkStarted();
- return response.getContentType();
- }
+ if (null != streamContent) {
+ String encoding = response.getCharacterEncoding();
- /**
- * @return HTTP status code of the response.
- */
- public int getResponseStatus() {
-// checkStarted();
- return response.getStatus();
- }
+ if (null != encoding) {
+ try {
+ content = new String(streamContent, encoding);
+ } catch (UnsupportedEncodingException e) {
+ throw new TestException(e);
+ }
+ } else {
+ content = new String(streamContent);
+ }
+ }
+ }
- /**
- * @return HTTP error message.
- */
- public String getErrorMessage() {
-// checkStarted();
- return response.getErrorMessage();
- }
+ return content;
+ }
- /**
- * Set request Query string. This method does not parse query string, {@link #parseFormParameters(String)} should be used.
- * @param queryString
- * the queryString to set
- */
- public void setQueryString(String queryString) {
-// checkNotStarted();
- this.queryString = queryString;
- }
+ /**
+ * Get content of the response as byte array.
+ * @return content of the ServletOutputStream or convert String, collected by response writer, with current
+ * response encoding.
+ *
+ * @throws TestException
+ * if response has unsupported encoding.
+ */
+ public byte[] getResponseBody() {
- /**
- * @return the queryString
- */
- public String getQueryString() {
- return queryString;
- }
+// checkStarted();
+ byte[] content = response.getStreamContent();
- /**
- * Get HTTP response headers.
- * @return headers name-values map.
- */
- public Map<String, String[]> getResponseHeaders() {
-// checkStarted();
- return response.getHeaders();
- }
+ if (null == content) {
+ String writerContent = response.getWriterContent();
- /**
- * Set charset for the request body.
- * @param charset
- * @throws UnsupportedEncodingException
- */
- public void setRequestCharacterEncoding(String charset) throws UnsupportedEncodingException {
-// checkNotStarted();
- request.setCharacterEncoding(charset);
- }
+ if (null != writerContent) {
+ try {
+ content = writerContent.getBytes(response.getCharacterEncoding());
+ } catch (UnsupportedEncodingException e) {
+ content = writerContent.getBytes();
+ }
+ } else {
+ content = new byte[0];
+ }
+ }
- /**
- * Set HTTP POST/PUT methods uploading content.
- * @param body
- */
- public void setRequestBody(String body) {
-// checkNotStarted();
- request.setRequestBody(body);
- }
+ return content;
+ }
- /**
- * Set HTTP request content type ( eg 'application/x-www-form-urlencoded' or 'text/xml' ).
- * @param contentType
- */
- public void setRequestContentType(String contentType) {
-// checkNotStarted();
- request.setContentType(contentType);
-
- }
+ /**
+ * List of the {@link Cookie} used by the request or response ( There are same cookies for both request and
+ * response ).
+ *
+ * @return the cookies
+ */
+ public List<Cookie> getCookies() {
+ return cookies;
+ }
- /**
- * Append additional HTTP request headers.
- * @param headers
- */
- public void addRequestHeaders(Map<String, String> headers) {
-// checkNotStarted();
- request.addHeaders(headers);
- }
+ /**
+ * request object for the this connection.
+ * @return the request
+ */
+ public HttpServletRequest getRequest() {
+ return requestProxy;
+ }
- private class ConnectionRequest extends StagingHttpRequest {
-
- public Cookie[] getCookies() {
- return cookies.toArray(COOKIE);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getMethod()
- */
- public String getMethod() {
- return method.toString();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getServletPath()
- */
- public String getServletPath() {
- return servletPath;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getPathInfo()
- */
- public String getPathInfo() {
- return pathInfo;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getQueryString()
- */
- public String getQueryString() {
- return queryString;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getRequestURI()
- */
- public String getRequestURI() {
- return url.getPath();
- }
-
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.StagingHttpRequest#getServerName()
- */
- @Override
- public String getServerName() {
- return url.getHost();
- }
-
-
- @Override
- public int getLocalPort() {
- int port = url.getPort();
- if(port < 0){
- port = super.getLocalPort();
- }
- return port;
- }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getParameter(java.lang.String)
- */
- public String getParameter(String name) {
- String[] values = requestParameters.get(name);
- if (null != values && values.length > 0) {
- return values[0];
- }
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getParameterMap()
- */
- @SuppressWarnings("unchecked")
- public Map getParameterMap() {
- return Collections.unmodifiableMap(requestParameters);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getParameterNames()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getParameterNames() {
- return Collections.enumeration(requestParameters.keySet());
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.ServletRequest#getParameterValues(java.lang.String)
- */
- public String[] getParameterValues(String name) {
- return requestParameters.get(name);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getSession()
- */
- public HttpSession getSession() {
- return server.getSession();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getSession(boolean)
- */
- public HttpSession getSession(boolean create) {
- return server.getSession(create);
- }
-
- @Override
- public RequestDispatcher getRequestDispatcher(String path) {
- RequestDispatcher dispatcher = null;
- if (!path.startsWith("/")) {
- try {
- URL absoluteUrl = new URL(url, path);
- path = absoluteUrl.getFile();
- } catch (MalformedURLException e) {
- return null;
- }
- }
- final RequestChain dispatchedServlet = server.getServlet(path);
- if (null != dispatchedServlet) {
- dispatcher = new RequestDispatcher() {
-
- public void forward(ServletRequest request,
- ServletResponse response) throws ServletException,
- IOException {
- response.reset();
- dispatchedServlet.execute(request, response);
- }
-
- public void include(ServletRequest request,
- ServletResponse response) throws ServletException,
- IOException {
- dispatchedServlet.execute(request, response);
- }
-
- };
- }
- return dispatcher;
- }
-
- @Override
- protected void attributeAdded(String name, Object o) {
- server.requestAttributeAdded(this, name, o);
-
- }
-
- @Override
- protected void attributeRemoved(String name, Object removed) {
- server.requestAttributeRemoved(this, name, removed);
-
- }
-
- @Override
- protected void attributeReplaced(String name, Object o) {
- server.requestAttributeReplaced(this, name, o);
-
- }
-
- }
+ /**
+ * response object for the this connection.
+ * @return the response
+ */
+ public HttpServletResponse getResponse() {
+ return responseProxy;
+ }
- private class ConnectionResponse extends StagingHttpResponse {
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#addCookie(javax.servlet.http
- * .Cookie )
- */
- public void addCookie(Cookie cookie) {
- cookies.add(cookie);
-
- }
-
- }
+ /**
+ * @return encoding used to write response.
+ */
+ public String getResponseCharacterEncoding() {
- public int getResponseContentLength() {
- return response.getContentLength();
- }
+// checkStarted();
+ return response.getCharacterEncoding();
+ }
+ /**
+ * @return content type ( eg 'text/html' ) of the response.
+ */
+ public String getResponseContentType() {
+
+// checkStarted();
+ return response.getContentType();
+ }
+
+ /**
+ * @return HTTP status code of the response.
+ */
+ public int getResponseStatus() {
+
+// checkStarted();
+ return response.getStatus();
+ }
+
+ /**
+ * @return HTTP error message.
+ */
+ public String getErrorMessage() {
+
+// checkStarted();
+ return response.getErrorMessage();
+ }
+
+ /**
+ * Set request Query string. This method does not parse query string, {@link #parseFormParameters(String)} should
+ * be used.
+ *
+ * @param queryString
+ * the queryString to set
+ */
+ public void setQueryString(String queryString) {
+
+// checkNotStarted();
+ this.queryString = queryString;
+ }
+
+ /**
+ * @return the queryString
+ */
+ public String getQueryString() {
+ return queryString;
+ }
+
+ /**
+ * Get HTTP response headers.
+ * @return headers name-values map.
+ */
+ public Map<String, String[]> getResponseHeaders() {
+
+// checkStarted();
+ return response.getHeaders();
+ }
+
+ /**
+ * Set charset for the request body.
+ * @param charset
+ * @throws UnsupportedEncodingException
+ */
+ public void setRequestCharacterEncoding(String charset) throws UnsupportedEncodingException {
+
+// checkNotStarted();
+ request.setCharacterEncoding(charset);
+ }
+
+ /**
+ * Set HTTP POST/PUT methods uploading content.
+ * @param body
+ */
+ public void setRequestBody(String body) {
+
+// checkNotStarted();
+ request.setRequestBody(body);
+ }
+
+ /**
+ * Set HTTP request content type ( eg 'application/x-www-form-urlencoded' or 'text/xml' ).
+ * @param contentType
+ */
+ public void setRequestContentType(String contentType) {
+
+// checkNotStarted();
+ request.setContentType(contentType);
+ }
+
+ /**
+ * Append additional HTTP request headers.
+ * @param headers
+ */
+ public void addRequestHeaders(Map<String, String> headers) {
+
+// checkNotStarted();
+ request.addHeaders(headers);
+ }
+
+ public int getResponseContentLength() {
+ return response.getContentLength();
+ }
+
+ private class ConnectionRequest extends StagingHttpRequest {
+ public Cookie[] getCookies() {
+ return cookies.toArray(COOKIE);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getMethod()
+ */
+ public String getMethod() {
+ return method.toString();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getServletPath()
+ */
+ public String getServletPath() {
+ return servletPath;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getPathInfo()
+ */
+ public String getPathInfo() {
+ return pathInfo;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getQueryString()
+ */
+ public String getQueryString() {
+ return queryString;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getRequestURI()
+ */
+ public String getRequestURI() {
+ return url.getPath();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.StagingHttpRequest#getServerName()
+ */
+ @Override
+ public String getServerName() {
+ return url.getHost();
+ }
+
+ @Override
+ public int getLocalPort() {
+ int port = url.getPort();
+
+ if (port < 0) {
+ port = super.getLocalPort();
+ }
+
+ return port;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getParameter(java.lang.String)
+ */
+ public String getParameter(String name) {
+ String[] values = requestParameters.get(name);
+
+ if (null != values && values.length > 0) {
+ return values[0];
+ }
+
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getParameterMap()
+ */
+ @SuppressWarnings("unchecked")
+ public Map getParameterMap() {
+ return Collections.unmodifiableMap(requestParameters);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getParameterNames()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getParameterNames() {
+ return Collections.enumeration(requestParameters.keySet());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.ServletRequest#getParameterValues(java.lang.String)
+ */
+ public String[] getParameterValues(String name) {
+ return requestParameters.get(name);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getSession()
+ */
+ public HttpSession getSession() {
+ return server.getSession();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getSession(boolean)
+ */
+ public HttpSession getSession(boolean create) {
+ return server.getSession(create);
+ }
+
+ @Override
+ public RequestDispatcher getRequestDispatcher(String path) {
+ RequestDispatcher dispatcher = null;
+
+ if (!path.startsWith("/")) {
+ try {
+ URL absoluteUrl = new URL(url, path);
+
+ path = absoluteUrl.getFile();
+ } catch (MalformedURLException e) {
+ return null;
+ }
+ }
+
+ final RequestChain dispatchedServlet = server.getServlet(path);
+
+ if (null != dispatchedServlet) {
+ dispatcher = new RequestDispatcher() {
+ public void forward(ServletRequest request, ServletResponse response)
+ throws ServletException, IOException {
+
+ response.reset();
+ dispatchedServlet.execute(request, response);
+ }
+ public void include(ServletRequest request, ServletResponse response)
+ throws ServletException, IOException {
+
+ dispatchedServlet.execute(request, response);
+ }
+ };
+ }
+
+ return dispatcher;
+ }
+
+ @Override
+ protected void attributeAdded(String name, Object o) {
+ server.requestAttributeAdded(this, name, o);
+ }
+
+ @Override
+ protected void attributeRemoved(String name, Object removed) {
+ server.requestAttributeRemoved(this, name, removed);
+ }
+
+ @Override
+ protected void attributeReplaced(String name, Object o) {
+ server.requestAttributeReplaced(this, name, o);
+ }
+ }
+
+
+ private class ConnectionResponse extends StagingHttpResponse {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#addCookie(javax.servlet.http
+ * .Cookie )
+ */
+ public void addCookie(Cookie cookie) {
+ cookies.add(cookie);
+ }
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpRequest.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpRequest.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpRequest.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -8,10 +9,14 @@
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
+
import java.nio.charset.Charset;
+
import java.security.Principal;
+
import java.text.DateFormat;
import java.text.ParseException;
+
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -26,525 +31,538 @@
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
-
/**
* @author asmirnov
- *
+ *
*/
abstract class StagingHttpRequest implements HttpServletRequest {
+ public static final String HTTP = "http";
+ public static final String LOCALHOST = "localhost";
+ public static final String LOCALHOST_IP = "127.0.0.1";
+ public static final String UTF8 = "UTF-8";
+ private static final Logger LOG = ServerLogger.CONNECTION.getLogger();
+ private String requestBody = null;
+ private Collection<Locale> locales = Arrays.asList(Locale.US, Locale.GERMANY);
+ private Map<String, String> headers = new HashMap<String, String>();
+ private String characterEncoding = UTF8;
+ private Map<String, Object> attributes = new HashMap<String, Object>();
+ private String contentType;
- private static final Logger log = ServerLogger.CONNECTION.getLogger();
+ /**
+ * @return the requestBody
+ */
+ String getRequestBody() {
+ return requestBody;
+ }
- public static final String LOCALHOST = "localhost";
- public static final String HTTP = "http";
- public static final String LOCALHOST_IP = "127.0.0.1";
- public static final String UTF8 = "UTF-8";
+ /**
+ * @param requestBody
+ * the requestBody to set
+ */
+ void setRequestBody(String requestBody) {
+ this.requestBody = requestBody;
+ }
- private String requestBody = null;
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getAuthType()
+ */
+ public String getAuthType() {
- private String contentType;
+ // TODO configure test auth.
+ LOG.info("unimplemented request method getAuthType");
- private Map<String, Object> attributes = new HashMap<String, Object>();
+ return null;
+ }
- private Map<String, String> headers = new HashMap<String, String>();
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getContextPath()
+ */
+ public String getContextPath() {
+ return StagingServletContext.CONTEXT_PATH;
+ }
- private Collection<Locale> locales = Arrays.asList(Locale.US,
- Locale.GERMANY);
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
+ */
+ public long getDateHeader(String name) {
+ String value = headers.get(name);
- private String characterEncoding = UTF8;
+ if (null != value) {
+ try {
+ return DateFormat.getDateInstance(DateFormat.FULL, getLocale()).parse(value).getTime();
+ } catch (ParseException e) {
+ throw new IllegalArgumentException(e.getMessage());
+ }
+ }
- /**
- * @return the requestBody
- */
- String getRequestBody() {
- return requestBody;
- }
+ return -1;
+ }
- /**
- * @param requestBody
- * the requestBody to set
- */
- void setRequestBody(String requestBody) {
- this.requestBody = requestBody;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
+ */
+ public String getHeader(String name) {
+ return headers.get(name);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getAuthType()
- */
- public String getAuthType() {
- // TODO configure test auth.
- log.info("unimplemented request method getAuthType");
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getHeaderNames()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getHeaderNames() {
+ return Collections.enumeration(headers.keySet());
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getContextPath()
- */
- public String getContextPath() {
- return StagingServletContext.CONTEXT_PATH;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getHeaders(String name) {
+ Set<String> values;
+ String value = headers.get(name);
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
- */
- public long getDateHeader(String name) {
- String value = headers.get(name);
- if(null != value){
- try {
- return DateFormat.getDateInstance(DateFormat.FULL, getLocale()).parse(value).getTime();
- } catch (ParseException e) {
- throw new IllegalArgumentException(e.getMessage());
- }
- }
- return -1;
- }
+ if (null != value) {
+ values = Collections.singleton(value);
+ } else {
+ values = Collections.emptySet();
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
- */
- public String getHeader(String name) {
- return headers.get(name);
- }
+ return Collections.enumeration(values);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getHeaderNames()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getHeaderNames() {
- return Collections.enumeration(headers.keySet());
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
+ */
+ public int getIntHeader(String name) {
+ String value = headers.get(name);
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
- */
- @SuppressWarnings("unchecked")
- public Enumeration getHeaders(String name) {
- Set<String> values;
- String value = headers.get(name);
- if (null != value) {
- values = Collections.singleton(value);
+ if (null != value) {
+ return Integer.parseInt(value);
+ }
- } else {
- values = Collections.emptySet();
- }
- return Collections.enumeration(values);
- }
+ return -1;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
- */
- public int getIntHeader(String name) {
- String value = headers.get(name);
- if(null != value){
- return Integer.parseInt(value);
- }
- return -1;
- }
+ void addHeader(String name, String value) {
+ headers.put(name, value);
+ }
- void addHeader(String name, String value) {
- headers.put(name, value);
- }
+ void addHeaders(Map<String, String> headers) {
+ this.headers.putAll(headers);
+ }
- void addHeaders(Map<String, String> headers) {
- this.headers.putAll(headers);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getPathTranslated()
+ */
+ public String getPathTranslated() {
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getPathTranslated()
- */
- public String getPathTranslated() {
- // we have only 'virtual' server.
- return null;
- }
+ // we have only 'virtual' server.
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getRemoteUser()
- */
- public String getRemoteUser() {
- // TODO configure test auth.
- log.info("unimplemented request method getRemoteUser");
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getRemoteUser()
+ */
+ public String getRemoteUser() {
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getRequestURL()
- */
- public StringBuffer getRequestURL() {
- StringBuffer requestURL = new StringBuffer(HTTP + "://" + LOCALHOST
- + getRequestURI());
- return requestURL;
- }
+ // TODO configure test auth.
+ LOG.info("unimplemented request method getRemoteUser");
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId()
- */
- public String getRequestedSessionId() {
- return StagingHttpSession.SESSION_ID;
- }
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#getUserPrincipal()
- */
- public Principal getUserPrincipal() {
- // TODO implement test auth.
- log.info("unimplemented request method getUserPrincipal");
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getRequestURL()
+ */
+ public StringBuffer getRequestURL() {
+ StringBuffer requestURL = new StringBuffer(HTTP + "://" + LOCALHOST + getRequestURI());
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie()
- */
- public boolean isRequestedSessionIdFromCookie() {
- // test do not supports cookie
- return false;
- }
+ return requestURL;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL()
- */
- public boolean isRequestedSessionIdFromURL() {
- return true;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId()
+ */
+ public String getRequestedSessionId() {
+ return StagingHttpSession.SESSION_ID;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl()
- */
- public boolean isRequestedSessionIdFromUrl() {
- return true;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#getUserPrincipal()
+ */
+ public Principal getUserPrincipal() {
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()
- */
- public boolean isRequestedSessionIdValid() {
- // TODO - check session.
- return false;
- }
+ // TODO implement test auth.
+ LOG.info("unimplemented request method getUserPrincipal");
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String)
- */
- public boolean isUserInRole(String role) {
- // TODO implement test auth.
- log.info("unimplemented request method isUserInRole");
- return false;
- }
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getAttribute(java.lang.String)
- */
- public Object getAttribute(String name) {
- return attributes.get(name);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie()
+ */
+ public boolean isRequestedSessionIdFromCookie() {
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getAttributeNames()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getAttributeNames() {
- return Collections.enumeration(attributes.keySet());
- }
+ // test do not supports cookie
+ return false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getCharacterEncoding()
- */
- public String getCharacterEncoding() {
- return characterEncoding;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL()
+ */
+ public boolean isRequestedSessionIdFromURL() {
+ return true;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getContentLength()
- */
- public int getContentLength() {
- String body = getRequestBody();
- return null == body ? -1 : body.length();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl()
+ */
+ public boolean isRequestedSessionIdFromUrl() {
+ return true;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getContentType()
- */
- public String getContentType() {
- return contentType;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()
+ */
+ public boolean isRequestedSessionIdValid() {
- /**
- * @param contentType
- * the contentType to set
- */
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
+ // TODO - check session.
+ return false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getInputStream()
- */
- public ServletInputStream getInputStream() throws IOException {
- String body = getRequestBody();
- if(null != body){
- final ByteArrayInputStream input = new ByteArrayInputStream(body.getBytes(getCharacterEncoding()));
- return new ServletInputStream(){
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String)
+ */
+ public boolean isUserInRole(String role) {
- @Override
- public int read() throws IOException {
- // TODO Auto-generated method stub
- return input.read();
- }
-
- };
- }
- return null;
- }
+ // TODO implement test auth.
+ LOG.info("unimplemented request method isUserInRole");
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getLocalAddr()
- */
- public String getLocalAddr() {
- return LOCALHOST_IP;
- }
+ return false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getLocalName()
- */
- public String getLocalName() {
- return LOCALHOST;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getAttribute(java.lang.String)
+ */
+ public Object getAttribute(String name) {
+ return attributes.get(name);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getLocalPort()
- */
- public int getLocalPort() {
- return 80;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getAttributeNames()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getAttributeNames() {
+ return Collections.enumeration(attributes.keySet());
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getLocale()
- */
- public Locale getLocale() {
- return Locale.US;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getCharacterEncoding()
+ */
+ public String getCharacterEncoding() {
+ return characterEncoding;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getLocales()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getLocales() {
- return Collections.enumeration(locales);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getContentLength()
+ */
+ public int getContentLength() {
+ String body = getRequestBody();
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getProtocol()
- */
- public String getProtocol() {
- return "HTTP/1.1";
- }
+ return null == body ? -1 : body.length();
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getReader()
- */
- public BufferedReader getReader() throws IOException {
- String body = getRequestBody();
- if(null != body){
- return new BufferedReader(new StringReader(body));
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getContentType()
+ */
+ public String getContentType() {
+ return contentType;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getRealPath(java.lang.String)
- */
- public String getRealPath(String path) {
- return null;
- }
+ /**
+ * @param contentType
+ * the contentType to set
+ */
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getRemoteAddr()
- */
- public String getRemoteAddr() {
- return LOCALHOST_IP;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getInputStream()
+ */
+ public ServletInputStream getInputStream() throws IOException {
+ String body = getRequestBody();
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getRemoteHost()
- */
- public String getRemoteHost() {
- return LOCALHOST;
- }
+ if (null != body) {
+ final ByteArrayInputStream input = new ByteArrayInputStream(body.getBytes(getCharacterEncoding()));
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getRemotePort()
- */
- public int getRemotePort() {
- return 1223340;
- }
+ return new ServletInputStream() {
+ @Override
+ public int read() throws IOException {
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String)
- */
- public RequestDispatcher getRequestDispatcher(String path) {
- // TODO Auto-generated method stub
- throw new NotImplementedException();
- // return null;
- }
+ // TODO Auto-generated method stub
+ return input.read();
+ }
+ };
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getScheme()
- */
- public String getScheme() {
- return HTTP;
- }
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getServerName()
- */
- public String getServerName() {
- return LOCALHOST;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getLocalAddr()
+ */
+ public String getLocalAddr() {
+ return LOCALHOST_IP;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#getServerPort()
- */
- public int getServerPort() {
- return 80;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getLocalName()
+ */
+ public String getLocalName() {
+ return LOCALHOST;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#isSecure()
- */
- public boolean isSecure() {
- return false;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getLocalPort()
+ */
+ public int getLocalPort() {
+ return 80;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String)
- */
- public void removeAttribute(String name) {
- // TODO - inform listeners
- Object removed = attributes.remove(name);
- if (null != removed) {
- attributeRemoved(name, removed);
- }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getLocale()
+ */
+ public Locale getLocale() {
+ return Locale.US;
+ }
- protected abstract void attributeRemoved(String name, Object removed);
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getLocales()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getLocales() {
+ return Collections.enumeration(locales);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#setAttribute(java.lang.String,
- * java.lang.Object)
- */
- public void setAttribute(String name, Object o) {
- if (null == o) {
- removeAttribute(name);
- } else {
- Object oldValue = attributes.put(name, o);
- if (null != oldValue) {
- attributeReplaced(name, o);
- } else {
- attributeAdded(name, o);
- }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getProtocol()
+ */
+ public String getProtocol() {
+ return "HTTP/1.1";
+ }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getReader()
+ */
+ public BufferedReader getReader() throws IOException {
+ String body = getRequestBody();
- protected abstract void attributeAdded(String name, Object o);
+ if (null != body) {
+ return new BufferedReader(new StringReader(body));
+ }
- protected abstract void attributeReplaced(String name, Object o);
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
- */
- public void setCharacterEncoding(String env)
- throws UnsupportedEncodingException {
- if (!Charset.isSupported(env)) {
- throw new UnsupportedEncodingException("Unknown charset "+env);
- }
- this.characterEncoding = env;
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getRealPath(java.lang.String)
+ */
+ public String getRealPath(String path) {
+ return null;
+ }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getRemoteAddr()
+ */
+ public String getRemoteAddr() {
+ return LOCALHOST_IP;
+ }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getRemoteHost()
+ */
+ public String getRemoteHost() {
+ return LOCALHOST;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getRemotePort()
+ */
+ public int getRemotePort() {
+ return 1223340;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String)
+ */
+ public RequestDispatcher getRequestDispatcher(String path) {
+
+ // TODO Auto-generated method stub
+ throw new NotImplementedException();
+
+ // return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getScheme()
+ */
+ public String getScheme() {
+ return HTTP;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getServerName()
+ */
+ public String getServerName() {
+ return LOCALHOST;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#getServerPort()
+ */
+ public int getServerPort() {
+ return 80;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#isSecure()
+ */
+ public boolean isSecure() {
+ return false;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String)
+ */
+ public void removeAttribute(String name) {
+
+ // TODO - inform listeners
+ Object removed = attributes.remove(name);
+
+ if (null != removed) {
+ attributeRemoved(name, removed);
+ }
+ }
+
+ protected abstract void attributeRemoved(String name, Object removed);
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#setAttribute(java.lang.String,
+ * java.lang.Object)
+ */
+ public void setAttribute(String name, Object o) {
+ if (null == o) {
+ removeAttribute(name);
+ } else {
+ Object oldValue = attributes.put(name, o);
+
+ if (null != oldValue) {
+ attributeReplaced(name, o);
+ } else {
+ attributeAdded(name, o);
+ }
+ }
+ }
+
+ protected abstract void attributeAdded(String name, Object o);
+
+ protected abstract void attributeReplaced(String name, Object o);
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
+ */
+ public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
+ if (!Charset.isSupported(env)) {
+ throw new UnsupportedEncodingException("Unknown charset " + env);
+ }
+
+ this.characterEncoding = env;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpResponse.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpResponse.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpResponse.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -7,6 +8,7 @@
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
+
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
@@ -18,449 +20,443 @@
/**
* @author asmirnov
- *
+ *
*/
abstract class StagingHttpResponse implements HttpServletResponse {
+ private static final Logger LOG = ServerLogger.CONNECTION.getLogger();
+ private int bufferSize = 8196;
+ private String contentType = "text";
+ private String errorMessage = null;
+ private String redirectLocation = null;
+ private int status = 200;
+ private Locale locale = Locale.US;
+ private final Map<String, String[]> headers = new HashMap<String, String[]>();
+ private String encoding = StagingHttpRequest.UTF8;
+ private int contentLength = Integer.MIN_VALUE;
+ private ByteArrayOutputStream outputStream;
+ private StringWriter outputWriter;
+ private PrintWriter printWriter;
+ private ServletOutputStream servletOutputStream;
+ /**
+ * @return the headers
+ */
+ Map<String, String[]> getHeaders() {
+ return headers;
+ }
- private static final Logger log = ServerLogger.CONNECTION.getLogger();
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#addDateHeader(java.lang.String,
+ * long)
+ */
+ public void addDateHeader(String name, long date) {
-
- private int status = 200;
+ // TODO - locale support ?
+ addHeader(name, new Date(date).toString());
+ }
- private String redirectLocation = null;
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String,
+ * java.lang.String)
+ */
+ public void addHeader(String name, String value) {
+ String[] values = headers.get(name);
- private String errorMessage = null;
+ if (null == values) {
+ values = new String[1];
+ } else {
+ String[] newValues = new String[values.length + 1];
- private int bufferSize = 8196;
+ System.arraycopy(values, 0, newValues, 0, values.length);
+ values = newValues;
+ }
- private StringWriter outputWriter;
+ values[values.length - 1] = value;
+ headers.put(name, values);
+ }
- private ByteArrayOutputStream outputStream;
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#addIntHeader(java.lang.String,
+ * int)
+ */
+ public void addIntHeader(String name, int value) {
+ addHeader(name, String.valueOf(value));
+ }
- private PrintWriter printWriter;
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#containsHeader(java.lang.String)
+ */
+ public boolean containsHeader(String name) {
+ return headers.containsKey(name);
+ }
- private ServletOutputStream servletOutputStream;
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#encodeRedirectURL(java.lang.String
+ * )
+ */
+ public String encodeRedirectURL(String url) {
+ return url;
+ }
- private Locale locale = Locale.US;
-
- private String contentType="text";
-
- private int contentLength = Integer.MIN_VALUE;
-
- private String encoding = StagingHttpRequest.UTF8;
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#encodeRedirectUrl(java.lang.String
+ * )
+ */
+ public String encodeRedirectUrl(String url) {
+ return encodeRedirectURL(url);
+ }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletResponse#encodeURL(java.lang.String)
+ */
+ public String encodeURL(String url) {
+ return url;
+ }
- private final Map<String, String[]> headers= new HashMap<String, String[]>();
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletResponse#encodeUrl(java.lang.String)
+ */
+ public String encodeUrl(String url) {
+ return encodeURL(url);
+ }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletResponse#sendError(int)
+ */
+ public void sendError(int sc) throws IOException {
+ status = sc;
+ }
- /**
- * @return the headers
- */
- Map<String, String[]> getHeaders() {
- return headers;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletResponse#sendError(int,
+ * java.lang.String)
+ */
+ public void sendError(int sc, String msg) throws IOException {
+ status = sc;
+ errorMessage = msg;
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#addDateHeader(java.lang.String,
- * long)
- */
- public void addDateHeader(String name, long date) {
- // TODO - locale support ?
- addHeader(name, new Date(date).toString());
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#sendRedirect(java.lang.String)
+ */
+ public void sendRedirect(String location) throws IOException {
+ redirectLocation = location;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String,
- * java.lang.String)
- */
- public void addHeader(String name, String value) {
- String[] values = headers.get(name);
- if (null == values) {
- values = new String[1];
- } else {
- String[] newValues = new String[values.length + 1];
- System.arraycopy(values, 0, newValues, 0, values.length);
- values = newValues;
- }
- values[values.length - 1] = value;
- headers.put(name, values);
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String,
+ * long)
+ */
+ public void setDateHeader(String name, long date) {
- }
+ // TODO - locale support ?
+ setHeader(name, new Date(date).toString());
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#addIntHeader(java.lang.String,
- * int)
- */
- public void addIntHeader(String name, int value) {
- addHeader(name, String.valueOf(value));
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletResponse#setHeader(java.lang.String,
+ * java.lang.String)
+ */
+ public void setHeader(String name, String value) {
+ headers.put(name, new String[] {value});
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#containsHeader(java.lang.String)
- */
- public boolean containsHeader(String name) {
- return headers.containsKey(name);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * javax.servlet.http.HttpServletResponse#setIntHeader(java.lang.String,
+ * int)
+ */
+ public void setIntHeader(String name, int value) {
+ setHeader(name, String.valueOf(value));
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#encodeRedirectURL(java.lang.String
- * )
- */
- public String encodeRedirectURL(String url) {
- return url;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletResponse#setStatus(int)
+ */
+ public void setStatus(int sc) {
+ status = sc;
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#encodeRedirectUrl(java.lang.String
- * )
- */
- public String encodeRedirectUrl(String url) {
- return encodeRedirectURL(url);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpServletResponse#setStatus(int,
+ * java.lang.String)
+ */
+ public void setStatus(int sc, String sm) {
+ status = sc;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletResponse#encodeURL(java.lang.String)
- */
- public String encodeURL(String url) {
- return url;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#flushBuffer()
+ */
+ public void flushBuffer() throws IOException {
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletResponse#encodeUrl(java.lang.String)
- */
- public String encodeUrl(String url) {
- return encodeURL(url);
- }
+ // do nothing
+ LOG.info("unimplemented response method flushBuffer");
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletResponse#sendError(int)
- */
- public void sendError(int sc) throws IOException {
- status = sc;
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#getBufferSize()
+ */
+ public int getBufferSize() {
+ return bufferSize;
+ }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#getCharacterEncoding()
+ */
+ public String getCharacterEncoding() {
+ return encoding;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletResponse#sendError(int,
- * java.lang.String)
- */
- public void sendError(int sc, String msg) throws IOException {
- status = sc;
- errorMessage = msg;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#getContentType()
+ */
+ public String getContentType() {
+ return contentType;
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#sendRedirect(java.lang.String)
- */
- public void sendRedirect(String location) throws IOException {
- redirectLocation = location;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#getLocale()
+ */
+ public Locale getLocale() {
+ return locale;
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String,
- * long)
- */
- public void setDateHeader(String name, long date) {
- // TODO - locale support ?
- setHeader(name, new Date(date).toString());
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#getOutputStream()
+ */
+ public ServletOutputStream getOutputStream() throws IOException {
+ if (null != this.outputWriter) {
+ throw new IllegalStateException();
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletResponse#setHeader(java.lang.String,
- * java.lang.String)
- */
- public void setHeader(String name, String value) {
- headers.put(name, new String[]{value});
- }
+ if (this.outputStream == null) {
+ this.outputStream = new ByteArrayOutputStream(getBufferSize());
+ servletOutputStream = new ServletOutputStream() {
+ @Override
+ public void write(int b) throws IOException {
+ StagingHttpResponse.this.outputStream.write(b);
+ }
+ };
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.servlet.http.HttpServletResponse#setIntHeader(java.lang.String,
- * int)
- */
- public void setIntHeader(String name, int value) {
- setHeader(name, String.valueOf(value));
- }
+ return servletOutputStream;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletResponse#setStatus(int)
- */
- public void setStatus(int sc) {
- status = sc;
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#getWriter()
+ */
+ public PrintWriter getWriter() throws IOException {
+ if (null != this.outputStream) {
+ throw new IllegalStateException();
+ }
- }
+ if (this.outputWriter == null) {
+ this.outputWriter = new StringWriter(getBufferSize());
+ printWriter = new PrintWriter(outputWriter);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpServletResponse#setStatus(int,
- * java.lang.String)
- */
- public void setStatus(int sc, String sm) {
- status = sc;
- }
+ return printWriter;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#flushBuffer()
- */
- public void flushBuffer() throws IOException {
- // do nothing
- log.info("unimplemented response method flushBuffer");
- }
+ public String getWriterContent() {
+ if (null != this.outputWriter) {
+ return this.outputWriter.toString();
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#getBufferSize()
- */
- public int getBufferSize() {
- return bufferSize;
- }
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#getCharacterEncoding()
- */
- public String getCharacterEncoding() {
- return encoding;
- }
+ public byte[] getStreamContent() {
+ if (null != outputStream) {
+ return outputStream.toByteArray();
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#getContentType()
- */
- public String getContentType() {
- return contentType;
- }
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#getLocale()
- */
- public Locale getLocale() {
- return locale;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#isCommitted()
+ */
+ public boolean isCommitted() {
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#getOutputStream()
- */
- public ServletOutputStream getOutputStream() throws IOException {
- if (null != this.outputWriter) {
- throw new IllegalStateException();
- }
- if (this.outputStream == null) {
- this.outputStream = new ByteArrayOutputStream(getBufferSize());
- servletOutputStream = new ServletOutputStream(){
+ // TODO Auto-generated method stub
+ LOG.info("unimplemented response method isCommited");
- @Override
- public void write(int b) throws IOException {
- StagingHttpResponse.this.outputStream.write(b);
- }
-
- };
- }
- return servletOutputStream;
- }
+ return false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#getWriter()
- */
- public PrintWriter getWriter() throws IOException {
- if (null != this.outputStream) {
- throw new IllegalStateException();
- }
- if (this.outputWriter == null) {
- this.outputWriter = new StringWriter(getBufferSize());
- printWriter = new PrintWriter(outputWriter);
- }
- return printWriter;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#reset()
+ */
+ public void reset() {
+ if (isCommitted()) {
+ throw new IllegalStateException();
+ }
-
- public String getWriterContent() {
- if(null != this.outputWriter){
- return this.outputWriter.toString();
- }
- return null;
- }
-
- public byte[] getStreamContent() {
- if(null!=outputStream){
- return outputStream.toByteArray();
- }
- return null;
- }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#isCommitted()
- */
- public boolean isCommitted() {
- // TODO Auto-generated method stub
- log.info("unimplemented response method isCommited");
- return false;
- }
+ resetBuffer();
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#reset()
- */
- public void reset() {
- if(isCommitted()){
- throw new IllegalStateException();
- }
- resetBuffer();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#resetBuffer()
+ */
+ public void resetBuffer() {
+ if (isCommitted()) {
+ throw new IllegalStateException();
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#resetBuffer()
- */
- public void resetBuffer() {
- if(isCommitted()){
- throw new IllegalStateException();
- }
- this.servletOutputStream = null;
- this.outputStream = null;
- this.printWriter = null;
- this.outputWriter = null;
- }
+ this.servletOutputStream = null;
+ this.outputStream = null;
+ this.printWriter = null;
+ this.outputWriter = null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#setBufferSize(int)
- */
- public void setBufferSize(int size) {
- this.bufferSize = size;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#setBufferSize(int)
+ */
+ public void setBufferSize(int size) {
+ this.bufferSize = size;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#setCharacterEncoding(java.lang.String)
- */
- public void setCharacterEncoding(String charset) {
- encoding = charset;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#setCharacterEncoding(java.lang.String)
+ */
+ public void setCharacterEncoding(String charset) {
+ encoding = charset;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#setContentLength(int)
- */
- public void setContentLength(int len) {
- this.contentLength = len;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#setContentLength(int)
+ */
+ public void setContentLength(int len) {
+ this.contentLength = len;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#setContentType(java.lang.String)
- */
- public void setContentType(String type) {
- if(null == type){
- throw new NullPointerException();
- }
- int i = type.indexOf(';');
- if(i>=0){
- setHeader("Content-Type", type);
- contentType = type.substring(0, i).trim();
- i=type.lastIndexOf('=');
- if(i>=0){
- setCharacterEncoding(type.substring(i+1).trim());
- }
- } else {
- setHeader("Content-Type", type+";charset="+getCharacterEncoding());
- contentType = type;
- }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#setContentType(java.lang.String)
+ */
+ public void setContentType(String type) {
+ if (null == type) {
+ throw new NullPointerException();
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletResponse#setLocale(java.util.Locale)
- */
- public void setLocale(Locale loc) {
- this.locale = loc;
+ int i = type.indexOf(';');
- }
+ if (i >= 0) {
+ setHeader("Content-Type", type);
+ contentType = type.substring(0, i).trim();
+ i = type.lastIndexOf('=');
- /**
- * @return the status
- */
- int getStatus() {
- return status;
- }
+ if (i >= 0) {
+ setCharacterEncoding(type.substring(i + 1).trim());
+ }
+ } else {
+ setHeader("Content-Type", type + ";charset=" + getCharacterEncoding());
+ contentType = type;
+ }
+ }
- /**
- * @return the contentLength
- */
- int getContentLength() {
- return contentLength;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletResponse#setLocale(java.util.Locale)
+ */
+ public void setLocale(Locale loc) {
+ this.locale = loc;
+ }
- /**
- * @return the redirectLocation
- */
- String getRedirectLocation() {
- return redirectLocation;
- }
+ /**
+ * @return the status
+ */
+ int getStatus() {
+ return status;
+ }
- /**
- * @return the errorMessage
- */
- String getErrorMessage() {
- return errorMessage;
- }
+ /**
+ * @return the contentLength
+ */
+ int getContentLength() {
+ return contentLength;
+ }
+ /**
+ * @return the redirectLocation
+ */
+ String getRedirectLocation() {
+ return redirectLocation;
+ }
+
+ /**
+ * @return the errorMessage
+ */
+ String getErrorMessage() {
+ return errorMessage;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpSession.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpSession.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingHttpSession.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -16,263 +17,270 @@
/**
* @author asmirnov
- *
+ *
*/
@SuppressWarnings("deprecation")
abstract class StagingHttpSession implements HttpSession {
+ private static final int DEFAULT_INACTIVE_TIME = 30;
+ public static final String SESSION_ID = "1234567890";
+ private final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();
+ private volatile int inactiveTime = DEFAULT_INACTIVE_TIME;
+ private final long creationTime;
+ private boolean valid;
- private static final int DEFAULT_INACTIVE_TIME = 30;
+ protected StagingHttpSession() {
+ this.creationTime = System.currentTimeMillis();
+ this.valid = true;
+ }
- public static final String SESSION_ID = "1234567890";
+ /**
+ *
+ */
+ void destroy() {
- private final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();
+ // Destroy all session attributes.
+ unboundAttributes();
+ }
- private final long creationTime;
+ private void unboundAttributes() {
+ for (String name : getValueNames()) {
+ removeAttribute(name);
+ }
+ }
- private volatile int inactiveTime = DEFAULT_INACTIVE_TIME;
-
- private boolean valid;
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getAttribute(java.lang.String)
+ */
+ public Object getAttribute(String name) {
+ checkValid();
- public StagingHttpSession() {
- this.creationTime = System.currentTimeMillis();
- this.valid = true;
- }
+ return attributes.get(name);
+ }
- /**
- *
- */
- void destroy() {
- // Destroy all session attributes.
- unboundAttributes();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getAttributeNames()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getAttributeNames() {
+ checkValid();
- private void unboundAttributes() {
- for (String name : getValueNames()) {
- removeAttribute(name);
- }
- }
+ return Collections.enumeration(attributes.keySet());
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getAttribute(java.lang.String)
- */
- public Object getAttribute(String name) {
- checkValid();
- return attributes.get(name);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getCreationTime()
+ */
+ public long getCreationTime() {
+ checkValid();
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getAttributeNames()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getAttributeNames() {
- checkValid();
- return Collections.enumeration(attributes.keySet());
- }
+ return creationTime;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getCreationTime()
- */
- public long getCreationTime() {
- checkValid();
- return creationTime;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getId()
+ */
+ public String getId() {
+ return SESSION_ID;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getId()
- */
- public String getId() {
- return SESSION_ID;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getLastAccessedTime()
+ */
+ public long getLastAccessedTime() {
+ checkValid();
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getLastAccessedTime()
- */
- public long getLastAccessedTime() {
- checkValid();
- // TODO fix accessing time
- return 0;
- }
+ // TODO fix accessing time
+ return 0;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getMaxInactiveInterval()
- */
- public int getMaxInactiveInterval() {
- return inactiveTime;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getMaxInactiveInterval()
+ */
+ public int getMaxInactiveInterval() {
+ return inactiveTime;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getSessionContext()
- */
- public HttpSessionContext getSessionContext() {
- throw new NotImplementedException("Session context is not implemented");
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getSessionContext()
+ */
+ public HttpSessionContext getSessionContext() {
+ throw new NotImplementedException("Session context is not implemented");
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getValue(java.lang.String)
- */
- public Object getValue(String name) {
- return getAttribute(name);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getValue(java.lang.String)
+ */
+ public Object getValue(String name) {
+ return getAttribute(name);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getValueNames()
- */
- public String[] getValueNames() {
- checkValid();
- ArrayList<String> names = new ArrayList<String>(attributes.keySet());
- return names.toArray(new String[names.size()]);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getValueNames()
+ */
+ public String[] getValueNames() {
+ checkValid();
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#invalidate()
- */
- public void invalidate() {
- checkValid();
- destroy();
- this.valid=false;
+ ArrayList<String> names = new ArrayList<String>(attributes.keySet());
- }
+ return names.toArray(new String[names.size()]);
+ }
- protected void checkValid(){
- if(!valid){
- throw new IllegalStateException("Session have been invalidated");
- }
- }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#isNew()
- */
- public boolean isNew() {
- checkValid();
- return false;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#invalidate()
+ */
+ public void invalidate() {
+ checkValid();
+ destroy();
+ this.valid = false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#putValue(java.lang.String,
- * java.lang.Object)
- */
- public void putValue(String name, Object value) {
- setAttribute(name, value);
+ protected void checkValid() {
+ if (!valid) {
+ throw new IllegalStateException("Session have been invalidated");
+ }
+ }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#isNew()
+ */
+ public boolean isNew() {
+ checkValid();
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#removeAttribute(java.lang.String)
- */
- public void removeAttribute(String name) {
- checkValid();
- Object removed = this.attributes.remove(name);
- if (null != removed) {
- removedFromSession(name, removed);
- }
+ return false;
+ }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#putValue(java.lang.String,
+ * java.lang.Object)
+ */
+ public void putValue(String name, Object value) {
+ setAttribute(name, value);
+ }
- protected void removedFromSession(String name, Object removed) {
- HttpSessionBindingEvent sessionBindingEvent = new HttpSessionBindingEvent(
- this, name, removed);
- if (removed instanceof HttpSessionBindingListener) {
- HttpSessionBindingListener listener = (HttpSessionBindingListener) removed;
- listener.valueUnbound(sessionBindingEvent);
- }
- valueUnbound(sessionBindingEvent);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#removeAttribute(java.lang.String)
+ */
+ public void removeAttribute(String name) {
+ checkValid();
- protected abstract void valueUnbound(
- HttpSessionBindingEvent sessionBindingEvent);
+ Object removed = this.attributes.remove(name);
- protected void boundToSession(String name, Object value) {
- HttpSessionBindingEvent sessionBindingEvent = new HttpSessionBindingEvent(
- this, name, value);
- if (value instanceof HttpSessionBindingListener) {
- HttpSessionBindingListener listener = (HttpSessionBindingListener) value;
- listener.valueBound(sessionBindingEvent);
- }
- valueBound(sessionBindingEvent);
- }
+ if (null != removed) {
+ removedFromSession(name, removed);
+ }
+ }
- protected abstract void valueBound(
- HttpSessionBindingEvent sessionBindingEvent);
+ protected void removedFromSession(String name, Object removed) {
+ HttpSessionBindingEvent sessionBindingEvent = new HttpSessionBindingEvent(this, name, removed);
- protected void replacedInSession(String name, Object oldValue, Object value) {
- HttpSessionBindingEvent sessionBindingEvent = new HttpSessionBindingEvent(
- this, name, value);
- if (oldValue instanceof HttpSessionBindingListener) {
- HttpSessionBindingListener listener = (HttpSessionBindingListener) oldValue;
- listener.valueUnbound(sessionBindingEvent);
- }
- if (value instanceof HttpSessionBindingListener) {
- HttpSessionBindingListener listener = (HttpSessionBindingListener) value;
- listener.valueBound(sessionBindingEvent);
- }
- valueReplaced(sessionBindingEvent);
- }
-
- protected abstract void valueReplaced(
- HttpSessionBindingEvent sessionBindingEvent);
+ if (removed instanceof HttpSessionBindingListener) {
+ HttpSessionBindingListener listener = (HttpSessionBindingListener) removed;
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#removeValue(java.lang.String)
- */
- public void removeValue(String name) {
- removeAttribute(name);
- }
+ listener.valueUnbound(sessionBindingEvent);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#setAttribute(java.lang.String,
- * java.lang.Object)
- */
- public void setAttribute(String name, Object value) {
- checkValid();
- if (null == value) {
- removeAttribute(name);
- } else {
- Object oldValue = attributes.put(name, value);
- if (null != oldValue) {
- replacedInSession(name, oldValue, value);
- } else {
- boundToSession(name, value);
- }
- }
- }
+ valueUnbound(sessionBindingEvent);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#setMaxInactiveInterval(int)
- */
- public void setMaxInactiveInterval(int interval) {
- this.inactiveTime = interval;
+ protected abstract void valueUnbound(HttpSessionBindingEvent sessionBindingEvent);
- }
+ protected void boundToSession(String name, Object value) {
+ HttpSessionBindingEvent sessionBindingEvent = new HttpSessionBindingEvent(this, name, value);
+ if (value instanceof HttpSessionBindingListener) {
+ HttpSessionBindingListener listener = (HttpSessionBindingListener) value;
+
+ listener.valueBound(sessionBindingEvent);
+ }
+
+ valueBound(sessionBindingEvent);
+ }
+
+ protected abstract void valueBound(HttpSessionBindingEvent sessionBindingEvent);
+
+ protected void replacedInSession(String name, Object oldValue, Object value) {
+ HttpSessionBindingEvent sessionBindingEvent = new HttpSessionBindingEvent(this, name, value);
+
+ if (oldValue instanceof HttpSessionBindingListener) {
+ HttpSessionBindingListener listener = (HttpSessionBindingListener) oldValue;
+
+ listener.valueUnbound(sessionBindingEvent);
+ }
+
+ if (value instanceof HttpSessionBindingListener) {
+ HttpSessionBindingListener listener = (HttpSessionBindingListener) value;
+
+ listener.valueBound(sessionBindingEvent);
+ }
+
+ valueReplaced(sessionBindingEvent);
+ }
+
+ protected abstract void valueReplaced(HttpSessionBindingEvent sessionBindingEvent);
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#removeValue(java.lang.String)
+ */
+ public void removeValue(String name) {
+ removeAttribute(name);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#setAttribute(java.lang.String,
+ * java.lang.Object)
+ */
+ public void setAttribute(String name, Object value) {
+ checkValid();
+
+ if (null == value) {
+ removeAttribute(name);
+ } else {
+ Object oldValue = attributes.put(name, value);
+
+ if (null != oldValue) {
+ replacedInSession(name, oldValue, value);
+ } else {
+ boundToSession(name, value);
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#setMaxInactiveInterval(int)
+ */
+ public void setMaxInactiveInterval(int interval) {
+ this.inactiveTime = interval;
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingInitialContextFactoryBuilder.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingInitialContextFactoryBuilder.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingInitialContextFactoryBuilder.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,12 +1,8 @@
/*
- * $Id$
- */
-
-/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
- *
+ *
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
- *
+ *
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
@@ -14,7 +10,7 @@
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
- *
+ *
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
@@ -23,9 +19,9 @@
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
- *
+ *
* Contributor(s):
- *
+ *
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
@@ -38,6 +34,11 @@
* holder.
*/
+
+
+/*
+* $Id$
+ */
package org.richfaces.test.staging;
import java.util.Hashtable;
@@ -57,193 +58,187 @@
* @author asmirnov(a)exadel.com
*
*/
-public class StagingInitialContextFactoryBuilder implements
- InitialContextFactoryBuilder {
+public class StagingInitialContextFactoryBuilder implements InitialContextFactoryBuilder {
- private static final class StagingInitialContext implements Context {
- public Object addToEnvironment(String propName,
- Object propVal) throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void bind(Name name, Object obj)
- throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public void bind(String name, Object obj)
- throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public void close() throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public Name composeName(Name name, Name prefix)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public String composeName(String name, String prefix)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Context createSubcontext(Name name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Context createSubcontext(String name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void destroySubcontext(Name name)
- throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public void destroySubcontext(String name)
- throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public Hashtable<?, ?> getEnvironment()
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public String getNameInNamespace() throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public NameParser getNameParser(Name name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public NameParser getNameParser(String name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public NamingEnumeration<NameClassPair> list(Name name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public NamingEnumeration<NameClassPair> list(String name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public NamingEnumeration<Binding> listBindings(Name name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public NamingEnumeration<Binding> listBindings(String name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Object lookup(Name name) throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Object lookup(String name) throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Object lookupLink(Name name) throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Object lookupLink(String name)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void rebind(Name name, Object obj)
- throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public void rebind(String name, Object obj)
- throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public Object removeFromEnvironment(String propName)
- throws NamingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void rename(Name oldName, Name newName)
- throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public void rename(String oldName, String newName)
- throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public void unbind(Name name) throws NamingException {
- // TODO Auto-generated method stub
-
- }
-
- public void unbind(String name) throws NamingException {
- // TODO Auto-generated method stub
-
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.naming.spi.InitialContextFactoryBuilder#createInitialContextFactory(java.util.Hashtable)
+ */
+ public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException {
+ return new StagingInitialContextFactory();
+ }
- public static final class StagingInitialContextFactory implements
- InitialContextFactory {
- public Context getInitialContext(Hashtable<?, ?> environment)
- throws NamingException {
- // TODO Auto-generated method stub
- return new StagingInitialContext();
- }
- }
+ private static final class StagingInitialContext implements Context {
+ public Object addToEnvironment(String propName, Object propVal) throws NamingException {
- /* (non-Javadoc)
- * @see javax.naming.spi.InitialContextFactoryBuilder#createInitialContextFactory(java.util.Hashtable)
- */
- public InitialContextFactory createInitialContextFactory(
- Hashtable<?, ?> environment) throws NamingException {
- return new StagingInitialContextFactory();
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
+ public void bind(Name name, Object obj) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public void bind(String name, Object obj) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public void close() throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public Name composeName(Name name, Name prefix) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String composeName(String name, String prefix) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Context createSubcontext(Name name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Context createSubcontext(String name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void destroySubcontext(Name name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public void destroySubcontext(String name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public Hashtable<?, ?> getEnvironment() throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String getNameInNamespace() throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public NameParser getNameParser(Name name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public NameParser getNameParser(String name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Object lookup(Name name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Object lookup(String name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Object lookupLink(Name name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Object lookupLink(String name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void rebind(Name name, Object obj) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public void rebind(String name, Object obj) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public Object removeFromEnvironment(String propName) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void rename(Name oldName, Name newName) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public void rename(String oldName, String newName) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public void unbind(Name name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+
+ public void unbind(String name) throws NamingException {
+
+ // TODO Auto-generated method stub
+ }
+ }
+
+
+ public static final class StagingInitialContextFactory implements InitialContextFactory {
+ public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
+
+ // TODO Auto-generated method stub
+ return new StagingInitialContext();
+ }
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingServer.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingServer.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingServer.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -2,13 +2,16 @@
import java.io.File;
import java.io.IOException;
+
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
+
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
+
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.EventListener;
@@ -22,7 +25,7 @@
import javax.naming.NamingException;
import javax.naming.spi.NamingManager;
-import javax.servlet.Filter;
+
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
@@ -35,8 +38,6 @@
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@@ -60,856 +61,868 @@
* <li>...</li>
* </ul>
* It is main part of the test framework.
- *
+ *
*/
public class StagingServer {
+ private static final Class<ServletRequestListener> REQUEST_LISTENER_CLASS = ServletRequestListener.class;
+ private static final Class<ServletRequestAttributeListener> REQUEST_ATTRIBUTE_LISTENER_CLASS =
+ ServletRequestAttributeListener.class;
+ private static final Class<ServletContextListener> CONTEXT_LISTENER_CLASS = ServletContextListener.class;
+ private static final Class<HttpSessionListener> SESSION_LISTENER_CLASS = HttpSessionListener.class;
+ private static final Class<HttpSessionAttributeListener> SESSION_ATTRIBUTE_LISTENER_CLASS =
+ HttpSessionAttributeListener.class;
+ private static final Logger LOG = ServerLogger.SERVER.getLogger();
+ private HttpSession currentSession = null;
+ private final List<RequestChain> servlets = new ArrayList<RequestChain>();
+ private final ServerResource serverRoot = new ServerResourcesDirectory();
+ private final Map<String, String> mimeTypes = new HashMap<String, String>();
+ private final Map<String, String> initParameters = new HashMap<String, String>();
+ private RequestChain defaultServlet = new ServletContainer(null, new StaticServlet());
+ private final List<EventListener> contextListeners = new ArrayList<EventListener>();
+ private final StagingServletContext context = new LocalContext();
+ private ThreadLocal<HttpSession> sessions = new ThreadLocal<HttpSession>();
+ private boolean sessionPerThread = false;
+ private List<ServerHttpSession> sessionInstances = new ArrayList<ServerHttpSession>();
+ private boolean initialised = false;
+ private ServletContext contextProxy;
+ private InvocationListener invocationListener;
- private static final Class<ServletRequestListener> REQUEST_LISTENER_CLASS = ServletRequestListener.class;
+ /**
+ *
+ */
+ @SuppressWarnings("unchecked")
+ private <T extends EventListener> void fireEvent(Class<T> listenerClass, EventInvoker<T> invoker) {
+ for (EventListener listener : contextListeners) {
+ if (listenerClass.isInstance(listener)) {
+ invoker.invoke((T) listener);
+ }
+ }
+ }
- private static final Class<ServletRequestAttributeListener> REQUEST_ATTRIBUTE_LISTENER_CLASS = ServletRequestAttributeListener.class;
+ /**
+ * Append executable server object ( {@link Filter} or {@link Servlet} to
+ * the server.
+ *
+ * @param servlet
+ */
+ public void addServlet(RequestChain servlet) {
+ servlets.add(servlet);
+ }
- private static final Class<ServletContextListener> CONTEXT_LISTENER_CLASS = ServletContextListener.class;
+ /**
+ * Add servlet to the server.
+ *
+ * @param mapping
+ * servlet mapping
+ * @param servlet
+ * {@link Servlet} instance.
+ */
+ public void addServlet(String mapping, Servlet servlet) {
+ servlets.add(new ServletContainer(mapping, servlet));
+ }
- private static final Class<HttpSessionListener> SESSION_LISTENER_CLASS = HttpSessionListener.class;
+ /**
+ * Get appropriate object ( Filter or Servlet ) for a given path.
+ *
+ * @param path
+ * request path relative to web application context.
+ * @return Appropriate Filter or Servlet executable object to serve given
+ * request. If no servlet was registered for the given path, try to
+ * send requested object directly.
+ */
+ public RequestChain getServlet(String path) {
+ RequestChain result = null;
- private static final Class<HttpSessionAttributeListener> SESSION_ATTRIBUTE_LISTENER_CLASS = HttpSessionAttributeListener.class;
+ for (RequestChain servlet : servlets) {
+ if (servlet.isApplicable(path)) {
+ result = servlet;
- private static final Logger log = ServerLogger.SERVER.getLogger();
+ break;
+ }
+ }
- private final List<RequestChain> servlets = new ArrayList<RequestChain>();
+ if (null == result) {
- private RequestChain defaultServlet = new ServletContainer(null,
- new StaticServlet());
+ // Is requested object exist in the virtual content ?
+ try {
+ URL resource = context.getResource(path);
- private final List<EventListener> contextListeners = new ArrayList<EventListener>();
+ if (null != resource) {
- private final Map<String, String> initParameters = new HashMap<String, String>();
+ // Serve it directly.
+ result = defaultServlet;
+ }
+ } catch (MalformedURLException e) {
+ LOG.warning("Mailformed request URL " + e.getMessage());
+ }
+ }
- private final ServerResource serverRoot = new ServerResourcesDirectory();
+ return result;
+ }
- private final Map<String, String> mimeTypes = new HashMap<String, String>();
+ /**
+ * Add web application init parameter.
+ *
+ * @param name
+ * @param value
+ */
+ public void addInitParameter(String name, String value) {
+ initParameters.put(name, value);
+ }
- private InvocationListener invocationListener;
+ /**
+ * Add default mime type for serve files with given extension.
+ *
+ * @param extension
+ * @param mimeType
+ */
+ public void addMimeType(String extension, String mimeType) {
+ mimeTypes.put(extension, mimeType);
+ }
- private final StagingServletContext context = new LocalContext();
+ /**
+ * Add java resource to the virtual web application content. This method
+ * makes all parent directories as needed.
+ *
+ * @param path
+ * path to the file in the virtual web server.
+ * @param resource
+ * path to the resource in the classpath, as required by the
+ * {@link ClassLoader#getResource(String)}.
+ */
+ public void addResource(String path, String resource) {
+ ServerResourcePath resourcePath = new ServerResourcePath(path);
- private ServletContext contextProxy;
+ serverRoot.addResource(resourcePath, new ClasspathServerResource(resource));
+ }
- private HttpSession currentSession = null;
-
- private ThreadLocal<HttpSession> sessions = new ThreadLocal<HttpSession>();
-
- private List<ServerHttpSession> sessionInstances = new ArrayList<ServerHttpSession>();
-
- private boolean sessionPerThread = false;
+ /**
+ * Add resource to the virtual veb application content. This method makes
+ * all parent directories as needed.
+ *
+ * @param path
+ * path to the file in the virtual web server.
+ * @param resource
+ * {@code URL} to the file content.
+ */
+ public void addResource(String path, URL resource) {
+ serverRoot.addResource(new ServerResourcePath(path), new UrlServerResource(resource));
+ }
+ /**
+ * Add all resources from the directory to the virtual web application
+ * content.
+ *
+ * @param path
+ * name of the target directory in the virtual web application.
+ * If no such directory exists, it will be created, as well as
+ * all parent directories as needed.
+ * @param resource
+ * {@code URL} to the source directory or any file in the source
+ * directory. Only 'file' or 'jar' protocols are supported. If
+ * this parameter points to a file, it will be converted to a
+ * enclosing directory.
+ */
+ public void addResourcesFromDirectory(String path, URL resource) {
+ ServerResourcePath resourcePath = new ServerResourcePath(path);
+ ServerResource baseDirectory = serverRoot.getResource(resourcePath);
- private boolean initialised = false;
+ if (null == baseDirectory) {
- /**
- * This inner class links ServletContext calls to the server instance.
- *
- * @author asmirnov
- *
- */
- private class LocalContext extends StagingServletContext {
+ // Create target directory.
+ baseDirectory = new ServerResourcesDirectory();
+ serverRoot.addResource(resourcePath, baseDirectory);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.ServletContext#getMimeType(java.lang.String)
- */
- public String getMimeType(String file) {
- int indexOfDot = file.lastIndexOf('.');
- // get extension.
- if (indexOfDot >= 0) {
- file = file.substring(indexOfDot);
- }
- return mimeTypes.get(file);
- }
+ String protocol = resource.getProtocol();
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.StagingServletContext#valueBound(javax
- * .servlet.ServletContextAttributeEvent)
- */
- @Override
- protected void valueBound(ServletContextAttributeEvent event) {
- // inform listeners.
- for (EventListener listener : contextListeners) {
- if (listener instanceof ServletContextAttributeListener) {
- ServletContextAttributeListener contextListener = (ServletContextAttributeListener) listener;
- contextListener.attributeAdded(event);
- }
- }
- }
+ if ("jar".equals(protocol)) {
+ addResourcesFromJar(resource, baseDirectory);
+ } else if ("file".equals(protocol)) {
+ addResourcesFromFile(resource, baseDirectory);
+ } else {
+ throw new TestException("Unsupported protocol " + protocol);
+ }
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.StagingServletContext#valueReplaced(javax
- * .servlet.ServletContextAttributeEvent)
- */
- @Override
- protected void valueReplaced(ServletContextAttributeEvent event) {
- // inform listeners.
- for (EventListener listener : contextListeners) {
- if (listener instanceof ServletContextAttributeListener) {
- ServletContextAttributeListener contextListener = (ServletContextAttributeListener) listener;
- contextListener.attributeReplaced(event);
- }
- }
- }
+ /**
+ * Add all files from the directory to the virtual web application
+ * content.
+ *
+ * @param path
+ * name of the target directory in the virtual web application.
+ * If no such directory exists, it will be created, as well as
+ * all parent directories as needed.
+ * @param resource
+ * {@code File} of the source directory or any file in the source
+ * directory. If this parameter points to a file, it will be converted to a
+ * enclosing directory.
+ */
+ public void addResourcesFromDirectory(String path, File directory) {
+ ServerResourcePath resourcePath = new ServerResourcePath(path);
+ ServerResource baseDirectory = serverRoot.getResource(resourcePath);
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.StagingServletContext#valueUnbound(javax
- * .servlet.ServletContextAttributeEvent)
- */
- @Override
- protected void valueUnbound(ServletContextAttributeEvent event) {
- // inform listeners.
- for (EventListener listener : contextListeners) {
- if (listener instanceof ServletContextAttributeListener) {
- ServletContextAttributeListener contextListener = (ServletContextAttributeListener) listener;
- contextListener.attributeRemoved(event);
- }
- }
- }
+ if (null == baseDirectory) {
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.StagingServletContext#getServerResource
- * (java.lang.String)
- */
- @Override
- protected ServerResource getServerResource(String path) {
- return serverRoot.getResource(new ServerResourcePath(path));
- }
+ // Create target directory.
+ baseDirectory = new ServerResourcesDirectory();
+ serverRoot.addResource(resourcePath, baseDirectory);
+ }
- }
+ if (!directory.isDirectory()) {
+ directory = directory.getParentFile();
+ }
- /**
- * This inner class links session object calls to the server instance.
- *
- * @author asmirnov
- *
- */
- private class ServerHttpSession extends StagingHttpSession {
+ if (!directory.exists()) {
+ throw new TestException("directory does not exist:" + directory.getAbsolutePath());
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.http.HttpSession#getServletContext()
- */
- public ServletContext getServletContext() {
- return context;
- }
+ try {
+ addFiles(baseDirectory, directory);
+ } catch (MalformedURLException e) {
+ throw new TestException(e);
+ }
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.StagingHttpSession#valueBound(javax.servlet
- * .http.HttpSessionBindingEvent)
- */
- @Override
- protected void valueBound(
- final HttpSessionBindingEvent sessionBindingEvent) {
- // inform session listeners.
- fireEvent(SESSION_ATTRIBUTE_LISTENER_CLASS,
- new EventInvoker<HttpSessionAttributeListener>() {
- public void invoke(HttpSessionAttributeListener listener) {
- listener.attributeAdded(sessionBindingEvent);
- }
- });
- }
+ /**
+ * Internal method used by the
+ * {@link #addResourcesFromDirectory(String, URL)} to process 'file'
+ * protocol.
+ *
+ * @param resource
+ * source directory.
+ * @param baseDirectory
+ * target virtual directory.
+ */
+ protected void addResourcesFromFile(URL resource, ServerResource baseDirectory) {
+ File file = new File(resource.getPath());
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.StagingHttpSession#valueUnbound(javax.
- * servlet.http.HttpSessionBindingEvent)
- */
- @Override
- protected void valueUnbound(
- final HttpSessionBindingEvent sessionBindingEvent) {
- // inform session listeners.
- fireEvent(SESSION_ATTRIBUTE_LISTENER_CLASS,
- new EventInvoker<HttpSessionAttributeListener>() {
- public void invoke(HttpSessionAttributeListener listener) {
- listener.attributeRemoved(sessionBindingEvent);
- }
- });
- }
+ if (!file.isDirectory()) {
+ file = file.getParentFile();
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.richfaces.test.staging.StagingHttpSession#valueReplaced(javax
- * .servlet.http.HttpSessionBindingEvent)
- */
- @Override
- protected void valueReplaced(
- final HttpSessionBindingEvent sessionBindingEvent) {
- // inform session listeners.
- fireEvent(SESSION_ATTRIBUTE_LISTENER_CLASS,
- new EventInvoker<HttpSessionAttributeListener>() {
- public void invoke(HttpSessionAttributeListener listener) {
- listener.attributeReplaced(sessionBindingEvent);
- }
- });
- }
-
- @Override
- public void invalidate() {
- super.invalidate();
- setCurrentSession(null);
- }
- }
+ try {
+ addFiles(baseDirectory, file);
+ } catch (MalformedURLException e) {
+ throw new TestException(e);
+ }
+ }
- /**
- *
- */
- @SuppressWarnings("unchecked")
- private <T extends EventListener> void fireEvent(Class<T> listenerClass,
- EventInvoker<T> invoker) {
- for (EventListener listener : contextListeners) {
- if (listenerClass.isInstance(listener)) {
- invoker.invoke((T) listener);
- }
- }
-
-
- }
+ /**
+ * Internal method used by the
+ * {@link #addResourcesFromDirectory(String, URL)} to process 'jar'
+ * protocol.
+ *
+ * @param resource
+ * URL to the any object in the source directory.
+ * @param baseDirectory
+ * target virtual directory.
+ */
+ protected void addResourcesFromJar(URL resource, ServerResource baseDirectory) {
+ try {
+ String jarPath = resource.getPath();
+ String entry = jarPath.substring(jarPath.indexOf('!') + 2);
- /**
- * Append executable server object ( {@link Filter} or {@link Servlet} to
- * the server.
- *
- * @param servlet
- */
- public void addServlet(RequestChain servlet) {
- servlets.add(servlet);
- }
+ jarPath = jarPath.substring(0, jarPath.indexOf('!'));
- /**
- * Add servlet to the server.
- *
- * @param mapping
- * servlet mapping
- * @param servlet
- * {@link Servlet} instance.
- */
- public void addServlet(String mapping, Servlet servlet) {
- servlets.add(new ServletContainer(mapping, servlet));
- }
+ File file = new File(new URI(jarPath));
+ ZipFile zip = new ZipFile(file);
+ Enumeration<? extends ZipEntry> entries = zip.entries();
- /**
- * Get appropriate object ( Filter or Servlet ) for a given path.
- *
- * @param path
- * request path relative to web application context.
- * @return Appropriate Filter or Servlet executable object to serve given
- * request. If no servlet was registered for the given path, try to
- * send requested object directly.
- */
- public RequestChain getServlet(String path) {
- RequestChain result = null;
- for (RequestChain servlet : servlets) {
- if (servlet.isApplicable(path)) {
- result = servlet;
- break;
- }
- }
- if (null == result) {
- // Is requested object exist in the virtual content ?
- try {
- URL resource = context.getResource(path);
- if (null != resource) {
- // Serve it directly.
- result = defaultServlet;
- }
- } catch (MalformedURLException e) {
- log.warning("Mailformed request URL " + e.getMessage());
- }
- }
- return result;
- }
+ entry = entry.substring(0, entry.lastIndexOf('/') + 1);
- /**
- * Add web application init parameter.
- *
- * @param name
- * @param value
- */
- public void addInitParameter(String name, String value) {
- initParameters.put(name, value);
- }
+ while (entries.hasMoreElements()) {
+ ZipEntry zzz = (ZipEntry) entries.nextElement();
- /**
- * Add default mime type for serve files with given extension.
- *
- * @param extension
- * @param mimeType
- */
- public void addMimeType(String extension, String mimeType) {
- mimeTypes.put(extension, mimeType);
- }
+ if (zzz.getName().startsWith(entry) && !zzz.isDirectory()) {
+ String relativePath = zzz.getName().substring(entry.length());
+ URL relativeResource = new URL(resource, relativePath);
- /**
- * Add java resource to the virtual web application content. This method
- * makes all parent directories as needed.
- *
- * @param path
- * path to the file in the virtual web server.
- * @param resource
- * path to the resource in the classpath, as required by the
- * {@link ClassLoader#getResource(String)}.
- */
- public void addResource(String path, String resource) {
- ServerResourcePath resourcePath = new ServerResourcePath(path);
- serverRoot.addResource(resourcePath, new ClasspathServerResource(
- resource));
- }
+ baseDirectory.addResource(new ServerResourcePath("/" + relativePath),
+ new UrlServerResource(relativeResource));
+ }
+ }
+ } catch (IOException e) {
+ throw new TestException("Error read Jar content", e);
+ } catch (URISyntaxException e) {
+ throw new TestException(e);
+ }
+ }
- /**
- * Add resource to the virtual veb application content. This method makes
- * all parent directories as needed.
- *
- * @param path
- * path to the file in the virtual web server.
- * @param resource
- * {@code URL} to the file content.
- */
- public void addResource(String path, URL resource) {
- serverRoot.addResource(new ServerResourcePath(path),
- new UrlServerResource(resource));
- }
+ /**
+ * Internal reccursive method process directory content and all
+ * subdirectories.
+ *
+ * @param baseDirectory
+ * @param file
+ * @throws MalformedURLException
+ */
+ protected void addFiles(ServerResource baseDirectory, File file) throws MalformedURLException {
+ File[] files = file.listFiles();
- /**
- * Add all resources from the directory to the virtual web application
- * content.
- *
- * @param path
- * name of the target directory in the virtual web application.
- * If no such directory exists, it will be created, as well as
- * all parent directories as needed.
- * @param resource
- * {@code URL} to the source directory or any file in the source
- * directory. Only 'file' or 'jar' protocols are supported. If
- * this parameter points to a file, it will be converted to a
- * enclosing directory.
- */
- public void addResourcesFromDirectory(String path, URL resource) {
- ServerResourcePath resourcePath = new ServerResourcePath(path);
- ServerResource baseDirectory = serverRoot.getResource(resourcePath);
- if (null == baseDirectory) {
- // Create target directory.
- baseDirectory = new ServerResourcesDirectory();
- serverRoot.addResource(resourcePath, baseDirectory);
- }
- String protocol = resource.getProtocol();
- if ("jar".equals(protocol)) {
- addResourcesFromJar(resource, baseDirectory);
- } else if ("file".equals(protocol)) {
- addResourcesFromFile(resource, baseDirectory);
- } else {
- throw new TestException("Unsupported protocol " + protocol);
- }
- }
+ for (File subfile : files) {
+ if (subfile.isDirectory()) {
+ ServerResourcePath serverResourcePath = new ServerResourcePath("/" + subfile.getName() + "/");
+ ServerResourcesDirectory subDir = new ServerResourcesDirectory();
- /**
- * Add all files from the directory to the virtual web application
- * content.
- *
- * @param path
- * name of the target directory in the virtual web application.
- * If no such directory exists, it will be created, as well as
- * all parent directories as needed.
- * @param resource
- * {@code File} of the source directory or any file in the source
- * directory. If this parameter points to a file, it will be converted to a
- * enclosing directory.
- */
- public void addResourcesFromDirectory(String path, File directory) {
- ServerResourcePath resourcePath = new ServerResourcePath(path);
- ServerResource baseDirectory = serverRoot.getResource(resourcePath);
- if (null == baseDirectory) {
- // Create target directory.
- baseDirectory = new ServerResourcesDirectory();
- serverRoot.addResource(resourcePath, baseDirectory);
- }
- if (!directory.isDirectory()) {
- directory = directory.getParentFile();
- }
- if(!directory.exists()){
- throw new TestException("directory does not exist:"+directory.getAbsolutePath());
- }
- try {
- addFiles(baseDirectory, directory);
- } catch (MalformedURLException e) {
- throw new TestException(e);
- }
- }
+ baseDirectory.addResource(serverResourcePath, subDir);
+ addFiles(subDir, subfile);
+ } else {
+ ServerResourcePath serverResourcePath = new ServerResourcePath("/" + subfile.getName());
+ UrlServerResource resource = new UrlServerResource(subfile.toURL());
- /**
- * Internal method used by the
- * {@link #addResourcesFromDirectory(String, URL)} to process 'file'
- * protocol.
- *
- * @param resource
- * source directory.
- * @param baseDirectory
- * target virtual directory.
- */
- protected void addResourcesFromFile(URL resource,
- ServerResource baseDirectory) {
- File file = new File(resource.getPath());
- if (!file.isDirectory()) {
- file = file.getParentFile();
- }
- try {
- addFiles(baseDirectory, file);
- } catch (MalformedURLException e) {
- throw new TestException(e);
- }
- }
+ baseDirectory.addResource(serverResourcePath, resource);
+ }
+ }
+ }
- /**
- * Internal method used by the
- * {@link #addResourcesFromDirectory(String, URL)} to process 'jar'
- * protocol.
- *
- * @param resource
- * URL to the any object in the source directory.
- * @param baseDirectory
- * target virtual directory.
- */
- protected void addResourcesFromJar(URL resource,
- ServerResource baseDirectory) {
- try {
- String jarPath = resource.getPath();
- String entry = jarPath.substring(jarPath.indexOf('!') + 2);
- jarPath = jarPath.substring(0, jarPath.indexOf('!'));
- File file = new File(new URI(jarPath));
- ZipFile zip = new ZipFile(file);
- Enumeration<? extends ZipEntry> entries = zip.entries();
- entry = entry.substring(0, entry.lastIndexOf('/') + 1);
- while (entries.hasMoreElements()) {
- ZipEntry zzz = (ZipEntry) entries.nextElement();
- if (zzz.getName().startsWith(entry) && !zzz.isDirectory()) {
- String relativePath = zzz.getName().substring(
- entry.length());
- URL relativeResource = new URL(resource, relativePath);
- baseDirectory.addResource(new ServerResourcePath("/"
- + relativePath), new UrlServerResource(
- relativeResource));
- }
- }
+ /**
+ * Add web-application wide listenes, same as it is defined by the
+ * <listener> element in the web.xml file for a real server. Supported
+ * listener types:
+ * <ul>
+ * <li>{@link ServletContextListener}</li>
+ * <li>{@link ServletContextAttributeListener}</li>
+ * <li>{@link HttpSessionListener}</li>
+ * <li>{@link HttpSessionAttributeListener}</li>
+ * <li>{@link ServletRequestListener}</li>
+ * <li>{@link ServletRequestAttributeListener}</li>
+ * </ul>
+ *
+ * @param listener
+ * web listener instance.
+ */
+ public void addWebListener(EventListener listener) {
+ contextListeners.add(listener);
+ }
- } catch (IOException e) {
- throw new TestException("Error read Jar content", e);
- } catch (URISyntaxException e) {
- throw new TestException(e);
- }
- }
+ /**
+ * Getter method for 'interceptor' events listener.
+ *
+ * @return the invocationListener
+ */
+ public InvocationListener getInvocationListener() {
+ return invocationListener;
+ }
- /**
- * Internal reccursive method process directory content and all
- * subdirectories.
- *
- * @param baseDirectory
- * @param file
- * @throws MalformedURLException
- */
- protected void addFiles(ServerResource baseDirectory, File file)
- throws MalformedURLException {
- File[] files = file.listFiles();
- for (File subfile : files) {
- if (subfile.isDirectory()) {
- ServerResourcePath serverResourcePath = new ServerResourcePath("/"
- + subfile.getName()+"/");
- ServerResourcesDirectory subDir = new ServerResourcesDirectory();
- baseDirectory.addResource(serverResourcePath, subDir);
- addFiles(subDir, subfile);
- } else {
- ServerResourcePath serverResourcePath = new ServerResourcePath("/"
- + subfile.getName());
- UrlServerResource resource = new UrlServerResource(subfile
- .toURL());
- baseDirectory.addResource(serverResourcePath, resource);
+ /**
+ * Set listener which gets events on all calls to any methods of the
+ * {@link ServletContext}, {@link HttpSession}, {@link javax.servlet.http.HttpServletRequest},
+ * {@link javax.servlet.http.HttpServletResponse} instances in the virtual server. this
+ * interceptor can be used to check internal calls in the tests .
+ *
+ * @param invocationListener
+ * the invocationListener to set
+ */
+ public void setInvocationListener(InvocationListener invocationListener) {
+ this.invocationListener = invocationListener;
+ }
- }
- }
- }
+ /**
+ * Create instance of the {@link InvocationHandler} for the proxy objects.
+ * This handler fire events to the registered {@link InvocationListener} (
+ * if present ) after target object method call.
+ *
+ * @return the invocationHandler
+ */
+ InvocationHandler getInvocationHandler(final Object target) {
+ return new InvocationHandler() {
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ InvocationListener listener = getInvocationListener();
- /**
- * Add web-application wide listenes, same as it is defined by the
- * <listener> element in the web.xml file for a real server. Supported
- * listener types:
- * <ul>
- * <li>{@link ServletContextListener}</li>
- * <li>{@link ServletContextAttributeListener}</li>
- * <li>{@link HttpSessionListener}</li>
- * <li>{@link HttpSessionAttributeListener}</li>
- * <li>{@link ServletRequestListener}</li>
- * <li>{@link ServletRequestAttributeListener}</li>
- * </ul>
- *
- * @param listener
- * web listener instance.
- */
- public void addWebListener(EventListener listener) {
- contextListeners.add(listener);
- }
+ try {
+ Object result = method.invoke(target, args);
- /**
- * Getter method for 'interceptor' events listener.
- *
- * @return the invocationListener
- */
- public InvocationListener getInvocationListener() {
- return invocationListener;
- }
+ if (null != listener) {
+ listener.afterInvoke(new InvocationEvent(target, method, args, result));
+ }
- /**
- * Set listener which gets events on all calls to any methods of the
- * {@link ServletContext}, {@link HttpSession}, {@link HttpServletRequest},
- * {@link HttpServletResponse} instances in the virtual server. this
- * interceptor can be used to check internal calls in the tests .
- *
- * @param invocationListener
- * the invocationListener to set
- */
- public void setInvocationListener(InvocationListener invocationListener) {
- this.invocationListener = invocationListener;
- }
+ return result;
+ } catch (Throwable e) {
+ if (null != listener) {
+ listener.processException(new InvocationErrorEvent(target, method, args, e));
+ }
- /**
- * Create instance of the {@link InvocationHandler} for the proxy objects.
- * This handler fire events to the registered {@link InvocationListener} (
- * if present ) after target object method call.
- *
- * @return the invocationHandler
- */
- InvocationHandler getInvocationHandler(final Object target) {
- return new InvocationHandler() {
+ throw e;
+ }
+ }
+ };
+ }
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- InvocationListener listener = getInvocationListener();
- try {
- Object result = method.invoke(target, args);
- if (null != listener) {
- listener.afterInvoke(new InvocationEvent(target,
- method, args, result));
- }
- return result;
- } catch (Throwable e) {
- if (null != listener) {
- listener.processException(new InvocationErrorEvent(
- target, method, args, e));
- }
- throw e;
- }
- }
+ public boolean isSessionPerThread() {
+ return sessionPerThread;
+ }
- };
+ public void setSessionPerThread(boolean sessionPerThread) {
+ this.sessionPerThread = sessionPerThread;
+ }
- }
+ HttpSession getCurrentSession() {
+ if (isSessionPerThread()) {
+ return sessions.get();
+ } else {
+ return currentSession;
+ }
+ }
- public boolean isSessionPerThread() {
- return sessionPerThread;
- }
+ void setCurrentSession(HttpSession session) {
+ if (isSessionPerThread()) {
+ sessions.set(session);
+ } else {
+ this.currentSession = session;
+ }
+ }
- public void setSessionPerThread(boolean sessionPerThread) {
- this.sessionPerThread = sessionPerThread;
- }
-
-
- HttpSession getCurrentSession() {
- if (isSessionPerThread()) {
- return sessions.get();
- } else {
- return currentSession;
- }
- }
-
- void setCurrentSession(HttpSession session) {
- if (isSessionPerThread()) {
- sessions.set(session);
- } else {
- this.currentSession=session;
- }
-
- }
+ /**
+ * Get virtual server session object. Create new one if necessary.
+ *
+ * @return instance of the virtual server session.
+ */
+ public HttpSession getSession() {
+ return getSession(true);
+ }
- /**
- * Get virtual server session object. Create new one if necessary.
- *
- * @return instance of the virtual server session.
- */
- public HttpSession getSession() {
- return getSession(true);
- }
+ /**
+ *
+ * Returns the current <code>HttpSession</code> associated with this server
+ * or, if there is no current session and <code>create</code> is true,
+ * returns a new session. Staging server supports only one session per
+ * instance, different clients for the same server instance does not
+ * supported.
+ *
+ * <p>
+ * If <code>create</code> is <code>false</code> and the request has no valid
+ * <code>HttpSession</code>, this method returns <code>null</code>.
+ *
+ *
+ * @param create
+ * <code>true</code> to create a new session for this request if
+ * necessary; <code>false</code> to return <code>null</code> if
+ * there's no current session
+ *
+ *
+ * @return the <code>HttpSession</code> associated with this server instance
+ * or <code>null</code> if <code>create</code> is <code>false</code>
+ * and the server has no session
+ *
+ */
+ public synchronized HttpSession getSession(boolean create) {
+ if (!initialised) {
+ throw new TestException("Staging server have not been initialised");
+ }
- /**
- *
- * Returns the current <code>HttpSession</code> associated with this server
- * or, if there is no current session and <code>create</code> is true,
- * returns a new session. Staging server supports only one session per
- * instance, different clients for the same server instance does not
- * supported.
- *
- * <p>
- * If <code>create</code> is <code>false</code> and the request has no valid
- * <code>HttpSession</code>, this method returns <code>null</code>.
- *
- *
- * @param create
- * <code>true</code> to create a new session for this request if
- * necessary; <code>false</code> to return <code>null</code> if
- * there's no current session
- *
- *
- * @return the <code>HttpSession</code> associated with this server instance
- * or <code>null</code> if <code>create</code> is <code>false</code>
- * and the server has no session
- *
- */
- public synchronized HttpSession getSession(boolean create) {
- if (!initialised) {
- throw new TestException("Staging server have not been initialised");
- }
- HttpSession httpSession = this.getCurrentSession();
- if (null == httpSession && create) {
- ServerHttpSession sessionImpl = new ServerHttpSession();
- // Create proxy objects.
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- if (null == loader) {
- loader = this.getClass().getClassLoader();
- }
- httpSession = (HttpSession) Proxy.newProxyInstance(loader,
- new Class[] { HttpSession.class },
- getInvocationHandler(sessionImpl));
- setCurrentSession(httpSession);
- // inform session listeners.
- final HttpSessionEvent event = new HttpSessionEvent(httpSession);
- fireEvent(SESSION_LISTENER_CLASS,
- new EventInvoker<HttpSessionListener>() {
- public void invoke(HttpSessionListener listener) {
- listener.sessionCreated(event);
- }
- });
- sessionInstances.add(sessionImpl);
- }
- return httpSession;
- }
+ HttpSession httpSession = this.getCurrentSession();
- /**
- * Virtual server initialization. This method creates instances of the
- * {@link ServletContext}, {@link JspFactory}, informs
- * {@link ServletContextListener} ind inits all {@link Filter} and
- * {@link Servlet} instances. It should be called from test setUp method to
- * prepare testing environment.
- */
- public void init() {
- log.info("Init staging server");
- // Create Jsp factory
- JspFactory.setDefaultFactory(new StaggingJspFactory(this.context));
- // Create init parameters
- context.addInitParameters(initParameters);
- // Inform listeners
- // Create proxy objects.
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- if (null == loader) {
- loader = this.getClass().getClassLoader();
- }
- this.contextProxy = (ServletContext) Proxy.newProxyInstance(loader,
- new Class[] { ServletContext.class },
- getInvocationHandler(context));
- // Create default servlet
- final ServletContextEvent event = new ServletContextEvent(context);
- fireEvent(CONTEXT_LISTENER_CLASS,
- new EventInvoker<ServletContextListener>() {
- public void invoke(ServletContextListener listener) {
- listener.contextInitialized(event);
- }
- });
- // Init servlets
- try {
- for (RequestChain servlet : servlets) {
- // init servlet
- servlet.init(context);
- }
- defaultServlet.init(context);
- } catch (ServletException e) {
- throw new TestException("Servlet initialisation error ", e);
- }
- try {
- NamingManager.setInitialContextFactoryBuilder(new StagingInitialContextFactoryBuilder());
- } catch (NamingException e) {
- log.warning("Error set initial context factory builder.");
- } catch (IllegalStateException e) {
- log.warning("Initial context factory builder already set.");
- }
- this.initialised = true;
- }
+ if (null == httpSession && create) {
+ ServerHttpSession sessionImpl = new ServerHttpSession();
- /**
- * Stop wirtual server. This method informs {@link ServletContextListener}
- * ind inits all {@link Filter} and {@link Servlet} instances, as well
- * remove all internal objects. It should be called from the testt thearDown
- * method to clean up testing environment.
- *
- */
- public void destroy() {
- if (!initialised) {
- throw new TestException("Staging server have not been initialised");
- }
- this.initialised = false;
- // Destroy session
- // TODO - destroy all threads.
- for (Iterator<ServerHttpSession> sessionIterator = sessionInstances.iterator(); sessionIterator.hasNext();) {
- ServerHttpSession session = sessionIterator.next();
- // inform session listeners.
- final HttpSessionEvent event = new HttpSessionEvent(session);
- fireEvent(SESSION_LISTENER_CLASS,
- new EventInvoker<HttpSessionListener>() {
- public void invoke(HttpSessionListener listener) {
- listener.sessionDestroyed(event);
- }
- });
- session.invalidate();
- sessionIterator.remove();
- }
- setCurrentSession(null);
- // Inform listeners
- final ServletContextEvent event = new ServletContextEvent(context);
- fireEvent(CONTEXT_LISTENER_CLASS,
- new EventInvoker<ServletContextListener>() {
- public void invoke(ServletContextListener listener) {
- listener.contextDestroyed(event);
- }
- });
- // Destroy servlets
- for (RequestChain servlet : servlets) {
- servlet.destroy();
- }
- defaultServlet.destroy();
- // Create Jsp factory
- JspFactory.setDefaultFactory(null);
- this.contextProxy = null;
- log.info("Staging server have been destroyed");
- }
+ // Create proxy objects.
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
- /**
- * Get virtual connection to the given URL. Even thought for an http request
- * to the external servers, only local connection to the virtual server will
- * be created.
- *
- * @param url
- * request url.
- * @return local connection to the appropriate servlet in the virtual
- * server.
- * @throws {@link TestException} if no servlet found to process given URL.
- */
- public StagingConnection getConnection(URL url) {
- if (!initialised) {
- throw new TestException("Staging server have not been initialised");
- }
- return new StagingConnection(this, url);
- }
+ if (null == loader) {
+ loader = this.getClass().getClassLoader();
+ }
- /**
- * Get instance of virtual web application context.
- *
- * @return context instance.
- */
- public ServletContext getContext() {
- if (!initialised) {
- throw new TestException("Staging server have not been initialised");
- }
- return contextProxy;
- }
+ httpSession = (HttpSession) Proxy.newProxyInstance(loader, new Class[] {HttpSession.class},
+ getInvocationHandler(sessionImpl));
+ setCurrentSession(httpSession);
- /**
- * Inform {@link ServletRequestListener} instances. For internal use only.
- *
- * @param request
- * started request.
- */
- void requestStarted(ServletRequest request) {
- final ServletRequestEvent event = new ServletRequestEvent(context,
- request);
- fireEvent(REQUEST_LISTENER_CLASS,
- new EventInvoker<ServletRequestListener>() {
- public void invoke(ServletRequestListener listener) {
- listener.requestInitialized(event);
+ // inform session listeners.
+ final HttpSessionEvent event = new HttpSessionEvent(httpSession);
- }
- });
- }
+ fireEvent(SESSION_LISTENER_CLASS, new EventInvoker<HttpSessionListener>() {
+ public void invoke(HttpSessionListener listener) {
+ listener.sessionCreated(event);
+ }
+ });
+ sessionInstances.add(sessionImpl);
+ }
- /**
- * Inform {@link ServletRequestListener} instances. For internal use only.
- *
- * @param request
- * finished request.
- */
- void requestFinished(ServletRequest request) {
- final ServletRequestEvent event = new ServletRequestEvent(context,
- request);
- fireEvent(REQUEST_LISTENER_CLASS,
- new EventInvoker<ServletRequestListener>() {
- public void invoke(ServletRequestListener listener) {
- listener.requestDestroyed(event);
- }
- });
- }
+ return httpSession;
+ }
- void requestAttributeAdded(ServletRequest request, String name, Object o) {
- final ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(
- context, request, name, o);
- fireEvent(REQUEST_ATTRIBUTE_LISTENER_CLASS,
- new EventInvoker<ServletRequestAttributeListener>() {
- public void invoke(ServletRequestAttributeListener listener) {
- listener.attributeAdded(event);
- }
- });
- }
+ /**
+ * Virtual server initialization. This method creates instances of the
+ * {@link ServletContext}, {@link JspFactory}, informs
+ * {@link ServletContextListener} ind inits all {@link Filter} and
+ * {@link Servlet} instances. It should be called from test setUp method to
+ * prepare testing environment.
+ */
+ public void init() {
+ LOG.info("Init staging server");
- void requestAttributeRemoved(ServletRequest request, String name,
- Object removed) {
- final ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(
- context, request, name, removed);
- fireEvent(REQUEST_ATTRIBUTE_LISTENER_CLASS,
- new EventInvoker<ServletRequestAttributeListener>() {
- public void invoke(ServletRequestAttributeListener listener) {
- listener.attributeRemoved(event);
- }
- });
- }
+ // Create Jsp factory
+ JspFactory.setDefaultFactory(new StaggingJspFactory(this.context));
- void requestAttributeReplaced(ServletRequest request, String name,
- Object value) {
- final ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(
- context, request, name, value);
- fireEvent(REQUEST_ATTRIBUTE_LISTENER_CLASS,
- new EventInvoker<ServletRequestAttributeListener>() {
- public void invoke(ServletRequestAttributeListener listener) {
- listener.attributeReplaced(event);
- }
- });
- }
+ // Create init parameters
+ context.addInitParameters(initParameters);
+
+ // Inform listeners
+ // Create proxy objects.
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+
+ if (null == loader) {
+ loader = this.getClass().getClassLoader();
+ }
+
+ this.contextProxy = (ServletContext) Proxy.newProxyInstance(loader, new Class[] {ServletContext.class},
+ getInvocationHandler(context));
+
+ // Create default servlet
+ final ServletContextEvent event = new ServletContextEvent(context);
+
+ fireEvent(CONTEXT_LISTENER_CLASS, new EventInvoker<ServletContextListener>() {
+ public void invoke(ServletContextListener listener) {
+ listener.contextInitialized(event);
+ }
+ });
+
+ // Init servlets
+ try {
+ for (RequestChain servlet : servlets) {
+
+ // init servlet
+ servlet.init(context);
+ }
+
+ defaultServlet.init(context);
+ } catch (ServletException e) {
+ throw new TestException("Servlet initialisation error ", e);
+ }
+
+ try {
+ NamingManager.setInitialContextFactoryBuilder(new StagingInitialContextFactoryBuilder());
+ } catch (NamingException e) {
+ LOG.warning("Error set initial context factory builder.");
+ } catch (IllegalStateException e) {
+ LOG.warning("Initial context factory builder already set.");
+ }
+
+ this.initialised = true;
+ }
+
+ /**
+ * Stop wirtual server. This method informs {@link ServletContextListener}
+ * ind inits all {@link Filter} and {@link Servlet} instances, as well
+ * remove all internal objects. It should be called from the testt thearDown
+ * method to clean up testing environment.
+ *
+ */
+ public void destroy() {
+ if (!initialised) {
+ throw new TestException("Staging server have not been initialised");
+ }
+
+ this.initialised = false;
+
+ // Destroy session
+ // TODO - destroy all threads.
+ for (Iterator<ServerHttpSession> sessionIterator = sessionInstances.iterator(); sessionIterator.hasNext(); ) {
+ ServerHttpSession session = sessionIterator.next();
+
+ // inform session listeners.
+ final HttpSessionEvent event = new HttpSessionEvent(session);
+
+ fireEvent(SESSION_LISTENER_CLASS, new EventInvoker<HttpSessionListener>() {
+ public void invoke(HttpSessionListener listener) {
+ listener.sessionDestroyed(event);
+ }
+ });
+ session.invalidate();
+ sessionIterator.remove();
+ }
+
+ setCurrentSession(null);
+
+ // Inform listeners
+ final ServletContextEvent event = new ServletContextEvent(context);
+
+ fireEvent(CONTEXT_LISTENER_CLASS, new EventInvoker<ServletContextListener>() {
+ public void invoke(ServletContextListener listener) {
+ listener.contextDestroyed(event);
+ }
+ });
+
+ // Destroy servlets
+ for (RequestChain servlet : servlets) {
+ servlet.destroy();
+ }
+
+ defaultServlet.destroy();
+
+ // Create Jsp factory
+ JspFactory.setDefaultFactory(null);
+ this.contextProxy = null;
+ LOG.info("Staging server have been destroyed");
+ }
+
+ /**
+ * Get virtual connection to the given URL. Even thought for an http request
+ * to the external servers, only local connection to the virtual server will
+ * be created.
+ *
+ * @param url
+ * request url.
+ * @return local connection to the appropriate servlet in the virtual
+ * server.
+ * @throws {@link TestException} if no servlet found to process given URL.
+ */
+ public StagingConnection getConnection(URL url) {
+ if (!initialised) {
+ throw new TestException("Staging server have not been initialised");
+ }
+
+ return new StagingConnection(this, url);
+ }
+
+ /**
+ * Get instance of virtual web application context.
+ *
+ * @return context instance.
+ */
+ public ServletContext getContext() {
+ if (!initialised) {
+ throw new TestException("Staging server have not been initialised");
+ }
+
+ return contextProxy;
+ }
+
+ /**
+ * Inform {@link ServletRequestListener} instances. For internal use only.
+ *
+ * @param request
+ * started request.
+ */
+ void requestStarted(ServletRequest request) {
+ final ServletRequestEvent event = new ServletRequestEvent(context, request);
+
+ fireEvent(REQUEST_LISTENER_CLASS, new EventInvoker<ServletRequestListener>() {
+ public void invoke(ServletRequestListener listener) {
+ listener.requestInitialized(event);
+ }
+ });
+ }
+
+ /**
+ * Inform {@link ServletRequestListener} instances. For internal use only.
+ *
+ * @param request
+ * finished request.
+ */
+ void requestFinished(ServletRequest request) {
+ final ServletRequestEvent event = new ServletRequestEvent(context, request);
+
+ fireEvent(REQUEST_LISTENER_CLASS, new EventInvoker<ServletRequestListener>() {
+ public void invoke(ServletRequestListener listener) {
+ listener.requestDestroyed(event);
+ }
+ });
+ }
+
+ void requestAttributeAdded(ServletRequest request, String name, Object o) {
+ final ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(context, request, name, o);
+
+ fireEvent(REQUEST_ATTRIBUTE_LISTENER_CLASS, new EventInvoker<ServletRequestAttributeListener>() {
+ public void invoke(ServletRequestAttributeListener listener) {
+ listener.attributeAdded(event);
+ }
+ });
+ }
+
+ void requestAttributeRemoved(ServletRequest request, String name, Object removed) {
+ final ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(context, request, name, removed);
+
+ fireEvent(REQUEST_ATTRIBUTE_LISTENER_CLASS, new EventInvoker<ServletRequestAttributeListener>() {
+ public void invoke(ServletRequestAttributeListener listener) {
+ listener.attributeRemoved(event);
+ }
+ });
+ }
+
+ void requestAttributeReplaced(ServletRequest request, String name, Object value) {
+ final ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(context, request, name, value);
+
+ fireEvent(REQUEST_ATTRIBUTE_LISTENER_CLASS, new EventInvoker<ServletRequestAttributeListener>() {
+ public void invoke(ServletRequestAttributeListener listener) {
+ listener.attributeReplaced(event);
+ }
+ });
+ }
+
+ /**
+ * This inner class links ServletContext calls to the server instance.
+ *
+ * @author asmirnov
+ *
+ */
+ private class LocalContext extends StagingServletContext {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.ServletContext#getMimeType(java.lang.String)
+ */
+ public String getMimeType(String file) {
+ int indexOfDot = file.lastIndexOf('.');
+
+ // get extension.
+ if (indexOfDot >= 0) {
+ file = file.substring(indexOfDot);
+ }
+
+ return mimeTypes.get(file);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.StagingServletContext#valueBound(javax
+ * .servlet.ServletContextAttributeEvent)
+ */
+ @Override
+ protected void valueBound(ServletContextAttributeEvent event) {
+
+ // inform listeners.
+ for (EventListener listener : contextListeners) {
+ if (listener instanceof ServletContextAttributeListener) {
+ ServletContextAttributeListener contextListener = (ServletContextAttributeListener) listener;
+
+ contextListener.attributeAdded(event);
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.StagingServletContext#valueReplaced(javax
+ * .servlet.ServletContextAttributeEvent)
+ */
+ @Override
+ protected void valueReplaced(ServletContextAttributeEvent event) {
+
+ // inform listeners.
+ for (EventListener listener : contextListeners) {
+ if (listener instanceof ServletContextAttributeListener) {
+ ServletContextAttributeListener contextListener = (ServletContextAttributeListener) listener;
+
+ contextListener.attributeReplaced(event);
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.StagingServletContext#valueUnbound(javax
+ * .servlet.ServletContextAttributeEvent)
+ */
+ @Override
+ protected void valueUnbound(ServletContextAttributeEvent event) {
+
+ // inform listeners.
+ for (EventListener listener : contextListeners) {
+ if (listener instanceof ServletContextAttributeListener) {
+ ServletContextAttributeListener contextListener = (ServletContextAttributeListener) listener;
+
+ contextListener.attributeRemoved(event);
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.StagingServletContext#getServerResource
+ * (java.lang.String)
+ */
+ @Override
+ protected ServerResource getServerResource(String path) {
+ return serverRoot.getResource(new ServerResourcePath(path));
+ }
+ }
+
+
+ /**
+ * This inner class links session object calls to the server instance.
+ *
+ * @author asmirnov
+ *
+ */
+ private class ServerHttpSession extends StagingHttpSession {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.servlet.http.HttpSession#getServletContext()
+ */
+ public ServletContext getServletContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.StagingHttpSession#valueBound(javax.servlet
+ * .http.HttpSessionBindingEvent)
+ */
+ @Override
+ protected void valueBound(final HttpSessionBindingEvent sessionBindingEvent) {
+
+ // inform session listeners.
+ fireEvent(SESSION_ATTRIBUTE_LISTENER_CLASS, new EventInvoker<HttpSessionAttributeListener>() {
+ public void invoke(HttpSessionAttributeListener listener) {
+ listener.attributeAdded(sessionBindingEvent);
+ }
+ });
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.StagingHttpSession#valueUnbound(javax.
+ * servlet.http.HttpSessionBindingEvent)
+ */
+ @Override
+ protected void valueUnbound(final HttpSessionBindingEvent sessionBindingEvent) {
+
+ // inform session listeners.
+ fireEvent(SESSION_ATTRIBUTE_LISTENER_CLASS, new EventInvoker<HttpSessionAttributeListener>() {
+ public void invoke(HttpSessionAttributeListener listener) {
+ listener.attributeRemoved(sessionBindingEvent);
+ }
+ });
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.test.staging.StagingHttpSession#valueReplaced(javax
+ * .servlet.http.HttpSessionBindingEvent)
+ */
+ @Override
+ protected void valueReplaced(final HttpSessionBindingEvent sessionBindingEvent) {
+
+ // inform session listeners.
+ fireEvent(SESSION_ATTRIBUTE_LISTENER_CLASS, new EventInvoker<HttpSessionAttributeListener>() {
+ public void invoke(HttpSessionAttributeListener listener) {
+ listener.attributeReplaced(sessionBindingEvent);
+ }
+ });
+ }
+
+ @Override
+ public void invalidate() {
+ super.invalidate();
+ setCurrentSession(null);
+ }
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingServletContext.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingServletContext.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StagingServletContext.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,12 +1,15 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.io.IOException;
import java.io.InputStream;
+
import java.net.MalformedURLException;
import java.net.URL;
+
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
@@ -23,277 +26,318 @@
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletException;
-
/**
* @author asmirnov
*
*/
abstract class StagingServletContext implements ServletContext {
-
- private static final Logger log = ServerLogger.SERVER.getLogger();
+ private static final String APPLICATION_NAME = "stub";
+ public static final String CONTEXT_PATH = "";
+ private static final Logger LOG = ServerLogger.SERVER.getLogger();
+ private final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();
+ private final Map<String, String> initParameters = new HashMap<String, String>();
- public static final String CONTEXT_PATH = "";
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getAttribute(java.lang.String)
+ */
+ public Object getAttribute(String name) {
+ return attributes.get(name);
+ }
- private static final String APPLICATION_NAME = "stub";
- private final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();
- private final Map<String,String> initParameters = new HashMap<String, String>();
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getAttributeNames()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getAttributeNames() {
+ return Collections.enumeration(attributes.keySet());
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getAttribute(java.lang.String)
- */
- public Object getAttribute(String name) {
- return attributes.get(name);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getContext(java.lang.String)
+ */
+ public ServletContext getContext(String uripath) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getAttributeNames()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getAttributeNames() {
- return Collections.enumeration(attributes.keySet());
- }
+ // stub server has only one context.
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getContext(java.lang.String)
- */
- public ServletContext getContext(String uripath) {
- // stub server has only one context.
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getContextPath()
+ */
+ public String getContextPath() {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getContextPath()
- */
- public String getContextPath() {
- // Test always run in the root context.
- return CONTEXT_PATH;
- }
+ // Test always run in the root context.
+ return CONTEXT_PATH;
+ }
- public void addInitParameters(Map<String,String>parameters) {
- initParameters.putAll(parameters);
- }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getInitParameter(java.lang.String)
- */
- public String getInitParameter(String name) {
- return initParameters.get(name);
- }
+ public void addInitParameters(Map<String, String> parameters) {
+ initParameters.putAll(parameters);
+ }
-
- /**
- * Put new init parameter to the Map.
- * @param name
- * @param value
- */
- public void setInitParameter(String name, String value) {
- initParameters.put(name, value);
- }
-
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getInitParameterNames()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getInitParameterNames() {
- return Collections.enumeration(initParameters.keySet());
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getInitParameter(java.lang.String)
+ */
+ public String getInitParameter(String name) {
+ return initParameters.get(name);
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getMajorVersion()
- */
- public int getMajorVersion() {
- return 2;
- }
+ /**
+ * Put new init parameter to the Map.
+ * @param name
+ * @param value
+ */
+ public void setInitParameter(String name, String value) {
+ initParameters.put(name, value);
+ }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getInitParameterNames()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getInitParameterNames() {
+ return Collections.enumeration(initParameters.keySet());
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getMinorVersion()
- */
- public int getMinorVersion() {
- return 5;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getMajorVersion()
+ */
+ public int getMajorVersion() {
+ return 2;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getNamedDispatcher(java.lang.String)
- */
- public RequestDispatcher getNamedDispatcher(String name) {
- // TODO create stub dispatcher.
- log.info("unimplemented response method getNamedDispatcher");
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getMinorVersion()
+ */
+ public int getMinorVersion() {
+ return 5;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getRealPath(java.lang.String)
- */
- public String getRealPath(String path) {
- // we always use 'virtual' configuration.
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getNamedDispatcher(java.lang.String)
+ */
+ public RequestDispatcher getNamedDispatcher(String name) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getRequestDispatcher(java.lang.String)
- */
- public RequestDispatcher getRequestDispatcher(String path) {
- // TODO implement stub dispatcher.
- log.info("unimplemented response method getRequestDispatcher");
- return null;
- }
+ // TODO create stub dispatcher.
+ LOG.info("unimplemented response method getNamedDispatcher");
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getResource(java.lang.String)
- */
- public URL getResource(String path) throws MalformedURLException {
- URL url = null;
- ServerResource resource = getServerResource(path);
- if(null != resource){
- url = resource.getURL();
- }
- return url;
- }
+ return null;
+ }
- /**
- * @param path
- * @return
- */
- protected abstract ServerResource getServerResource(String path);
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getRealPath(java.lang.String)
+ */
+ public String getRealPath(String path) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getResourceAsStream(java.lang.String)
- */
- public InputStream getResourceAsStream(String path) {
- ServerResource resource = getServerResource(path);
- if(null != resource){
- try {
- return resource.getAsStream();
- } catch (IOException e) {
- return null;
- }
- }
- return null;
- }
+ // we always use 'virtual' configuration.
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String)
- */
- @SuppressWarnings("unchecked")
- public Set getResourcePaths(String path) {
- HashSet result=null;
- ServerResource resource = getServerResource(path);
- if(null == resource && !path.endsWith("/")){
- path+="/";
- resource = getServerResource(path);
- }
- if(null != resource){
- Set<String> paths = resource.getPaths();
- if(null != paths && paths.size()>0){
- result = new HashSet(paths.size());
- for (String resourcePath : paths) {
- result.add(path+resourcePath);
- }
- }
- }
- return result;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getRequestDispatcher(java.lang.String)
+ */
+ public RequestDispatcher getRequestDispatcher(String path) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServerInfo()
- */
- public String getServerInfo() {
- return "Stub test server";
- }
+ // TODO implement stub dispatcher.
+ LOG.info("unimplemented response method getRequestDispatcher");
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServlet(java.lang.String)
- */
- public Servlet getServlet(String name) throws ServletException {
- // always return null.
- log.info("unimplemented response method getServlet");
- return null;
- }
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServletContextName()
- */
- public String getServletContextName() {
- // Stub server has no declared name.
- return APPLICATION_NAME;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getResource(java.lang.String)
+ */
+ public URL getResource(String path) throws MalformedURLException {
+ URL url = null;
+ ServerResource resource = getServerResource(path);
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServletNames()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getServletNames() {
- log.info("unimplemented response method getServletNames");
- return Collections.enumeration(Collections.EMPTY_LIST);
- }
+ if (null != resource) {
+ url = resource.getURL();
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServlets()
- */
- @SuppressWarnings("unchecked")
- public Enumeration getServlets() {
- log.info("unimplemented response method getServlets");
- return Collections.enumeration(Collections.EMPTY_LIST);
- }
+ return url;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#log(java.lang.String)
- */
- public void log(String msg) {
- log.finest(msg);
+ /**
+ * @param path
+ * @return
+ */
+ protected abstract ServerResource getServerResource(String path);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getResourceAsStream(java.lang.String)
+ */
+ public InputStream getResourceAsStream(String path) {
+ ServerResource resource = getServerResource(path);
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#log(java.lang.Exception, java.lang.String)
- */
- public void log(Exception exception, String msg) {
- log.log(Level.FINEST, msg, exception);
+ if (null != resource) {
+ try {
+ return resource.getAsStream();
+ } catch (IOException e) {
+ return null;
+ }
+ }
- }
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#log(java.lang.String, java.lang.Throwable)
- */
- public void log(String message, Throwable throwable) {
- log.log(Level.FINEST, message, throwable);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String)
+ */
+ @SuppressWarnings("unchecked")
+ public Set getResourcePaths(String path) {
+ String tmpPath = path;
+ ServerResource resource = getServerResource(tmpPath);
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#removeAttribute(java.lang.String)
- */
- public void removeAttribute(String name) {
- // TODO - inform listeners
- Object removed = attributes.remove(name);
- if(null != removed){
- valueUnbound(new ServletContextAttributeEvent(this,name,removed));
- }
- }
+ if (null == resource && !tmpPath.endsWith("/")) {
+ tmpPath += "/";
+ resource = getServerResource(tmpPath);
+ }
+ Set<String> result = null;
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#setAttribute(java.lang.String, java.lang.Object)
- */
- public void setAttribute(String name, Object object) {
- // TODO - inform listeners
- if (null == object) {
- removeAttribute(name);
- } else {
- Object oldValue = attributes.put(name, object);
- ServletContextAttributeEvent event = new ServletContextAttributeEvent(this,name,object);
- if(null != oldValue){
- valueReplaced(event);
- } else {
- valueBound(event);
- }
- }
- }
+ if (null != resource) {
+ Set<String> paths = resource.getPaths();
- protected abstract void valueBound(ServletContextAttributeEvent event);
+ if (null != paths && paths.size() > 0) {
+ result = new HashSet(paths.size());
- protected abstract void valueReplaced(ServletContextAttributeEvent event);
+ for (String resourcePath : paths) {
+ result.add(tmpPath + resourcePath);
+ }
+ }
+ }
- protected abstract void valueUnbound(
- ServletContextAttributeEvent servletContextAttributeEvent);
+ return result;
+ }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServerInfo()
+ */
+ public String getServerInfo() {
+ return "Stub test server";
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServlet(java.lang.String)
+ */
+ public Servlet getServlet(String name) throws ServletException {
+
+ // always return null.
+ LOG.info("unimplemented response method getServlet");
+
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServletContextName()
+ */
+ public String getServletContextName() {
+
+ // Stub server has no declared name.
+ return APPLICATION_NAME;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServletNames()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getServletNames() {
+ LOG.info("unimplemented response method getServletNames");
+
+ return Collections.enumeration(Collections.EMPTY_LIST);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServlets()
+ */
+ @SuppressWarnings("unchecked")
+ public Enumeration getServlets() {
+ LOG.info("unimplemented response method getServlets");
+
+ return Collections.enumeration(Collections.EMPTY_LIST);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#log(java.lang.String)
+ */
+ public void log(String msg) {
+ LOG.finest(msg);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#log(java.lang.Exception, java.lang.String)
+ */
+ public void log(Exception exception, String msg) {
+ LOG.log(Level.FINEST, msg, exception);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#log(java.lang.String, java.lang.Throwable)
+ */
+ public void log(String message, Throwable throwable) {
+ LOG.log(Level.FINEST, message, throwable);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#removeAttribute(java.lang.String)
+ */
+ public void removeAttribute(String name) {
+
+ // TODO - inform listeners
+ Object removed = attributes.remove(name);
+
+ if (null != removed) {
+ valueUnbound(new ServletContextAttributeEvent(this, name, removed));
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#setAttribute(java.lang.String, java.lang.Object)
+ */
+ public void setAttribute(String name, Object object) {
+
+ // TODO - inform listeners
+ if (null == object) {
+ removeAttribute(name);
+ } else {
+ Object oldValue = attributes.put(name, object);
+ ServletContextAttributeEvent event = new ServletContextAttributeEvent(this, name, object);
+
+ if (null != oldValue) {
+ valueReplaced(event);
+ } else {
+ valueBound(event);
+ }
+ }
+ }
+
+ protected abstract void valueBound(ServletContextAttributeEvent event);
+
+ protected abstract void valueReplaced(ServletContextAttributeEvent event);
+
+ protected abstract void valueUnbound(ServletContextAttributeEvent servletContextAttributeEvent);
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaticServlet.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaticServlet.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/StaticServlet.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -18,33 +19,36 @@
*/
@SuppressWarnings("serial")
public class StaticServlet extends HttpServlet {
+ @Override
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ InputStream inputStream = getServletContext().getResourceAsStream(req.getServletPath());
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- InputStream inputStream = getServletContext().getResourceAsStream(req.getServletPath());
- if(null != inputStream){
- String fileName = req.getServletPath();
- String mimeType = getServletContext().getMimeType(fileName);
- if(null == mimeType){
- mimeType = "text/plain";
- }
- resp.setContentType(mimeType);
- ServletOutputStream outputStream = resp.getOutputStream();
- int c;
- while((c = inputStream.read())>0){
- outputStream.write(c);
- }
- inputStream.close();
- outputStream.close();
- } else {
- resp.sendError(404, "not found");
- }
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- doGet(req, resp);
- }
+ if (null != inputStream) {
+ String fileName = req.getServletPath();
+ String mimeType = getServletContext().getMimeType(fileName);
+
+ if (null == mimeType) {
+ mimeType = "text/plain";
+ }
+
+ resp.setContentType(mimeType);
+
+ ServletOutputStream outputStream = resp.getOutputStream();
+ int c;
+
+ while ((c = inputStream.read()) > 0) {
+ outputStream.write(c);
+ }
+
+ inputStream.close();
+ outputStream.close();
+ } else {
+ resp.sendError(404, "not found");
+ }
+ }
+
+ @Override
+ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ doGet(req, resp);
+ }
}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/URLScanner.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/URLScanner.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/URLScanner.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -7,6 +8,4 @@
* @author asmirnov
*
*/
-public class URLScanner {
-
-}
+public class URLScanner {}
Modified: root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/UrlServerResource.java
===================================================================
--- root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/UrlServerResource.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/main/java/org/richfaces/test/staging/UrlServerResource.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,38 +1,38 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import java.net.URL;
+
import java.util.logging.Logger;
-
/**
* This class represent file-like virtual web application object, loaded from the any URL.
* @author asmirnov
*
*/
public class UrlServerResource extends AbstractServerResource {
+ static final Logger LOG = ServerLogger.RESOURCE.getLogger();
- /**
- * Resource target URL
- */
- private final URL resource;
-
- static final Logger log = ServerLogger.RESOURCE.getLogger();
+ /**
+ * Resource target URL
+ */
+ private final URL resource;
- /**
- * @param resource url to the resource content.
- */
- public UrlServerResource(URL resource) {
- this.resource = resource;
- }
+ /**
+ * @param resource url to the resource content.
+ */
+ public UrlServerResource(URL resource) {
+ this.resource = resource;
+ }
- /* (non-Javadoc)
- * @see org.richfaces.test.staging.ServerResource#getURL()
- */
- public URL getURL() {
- return resource;
- }
-
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.staging.ServerResource#getURL()
+ */
+ public URL getURL() {
+ return resource;
+ }
}
Modified: root/framework/trunk/test-base/src/test/java/org/richfaces/test/FacesServerTest.java
===================================================================
--- root/framework/trunk/test-base/src/test/java/org/richfaces/test/FacesServerTest.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/test/java/org/richfaces/test/FacesServerTest.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,9 +1,11 @@
+
/**
- *
+ *
*/
package org.richfaces.test;
import java.io.IOException;
+
import java.net.MalformedURLException;
import javax.servlet.http.HttpSession;
@@ -11,6 +13,7 @@
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+
import org.w3c.dom.Element;
import com.gargoylesoftware.htmlunit.WebClient;
@@ -21,73 +24,84 @@
/**
* @author asmirnov
- *
+ *
*/
public class FacesServerTest extends AbstractFacesTest {
+ /**
+ * @throws java.lang.Exception
+ */
+ @Before
+ public void setUpTest() throws Exception {}
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUpTest() throws Exception {
- }
+ @Override
+ protected void setupWebContent() {
+ facesServer.addResource("/WEB-INF/faces-config.xml", "org/richfaces/test/WEB-INF/faces-config.xml");
+ facesServer.addResource("/hello.xhtml", "org/richfaces/test/hello.xhtml");
+ facesServer.addResource("/response.xhtml", "org/richfaces/test/response.xhtml");
+ facesServer.addResource("/wave.med.gif", "org/richfaces/test/wave.med.gif");
+ }
- @Override
- protected void setupWebContent() {
- facesServer.addResource("/WEB-INF/faces-config.xml", "org/richfaces/test/WEB-INF/faces-config.xml");
- facesServer.addResource("/hello.xhtml", "org/richfaces/test/hello.xhtml");
- facesServer.addResource("/response.xhtml", "org/richfaces/test/response.xhtml");
- facesServer.addResource("/wave.med.gif", "org/richfaces/test/wave.med.gif");
- }
- /**
- * @throws java.lang.Exception
- */
- @After
- public void tearDownTest() throws Exception {
- }
+ /**
+ * @throws java.lang.Exception
+ */
+ @After
+ public void tearDownTest() throws Exception {}
- /**
- * Test method for
- * {@link org.richfaces.test.staging.StagingServer#getConnection(java.net.URL)}.
- *
- * @throws Exception
- */
- @Test
- public void testHelloFacelets() throws Exception {
- HtmlPage page = getPage("/hello.jsf");
- System.out.println(page.asXml());
- Element submitElement = page.getElementById("helloForm:submit");
- HtmlForm htmlForm = page.getFormByName("helloForm");
- htmlForm.getInputByName("helloForm:username");
- assertNotNull(htmlForm);
- HtmlInput input = htmlForm.getInputByName("helloForm:username");
- assertNotNull(input);
- input.setValueAttribute("foo");
- HtmlPage responsePage = (HtmlPage) htmlForm.submit((SubmittableElement) submitElement);
- assertNotNull(responsePage);
- System.out.println(responsePage.asXml());
- HttpSession session = facesServer.getSession(false);
- assertNotNull(session);
- HelloBean bean = (HelloBean) session.getAttribute("HelloBean");
- assertNotNull(bean);
- assertEquals("foo", bean.getName());
- Element span = responsePage.getElementById("responseform:userLabel");
- assertNotNull(span);
- assertEquals("foo", span.getTextContent().trim());
- }
+ /**
+ * Test method for
+ * {@link org.richfaces.test.staging.StagingServer#getConnection(java.net.URL)}.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testHelloFacelets() throws Exception {
+ HtmlPage page = getPage("/hello.jsf");
- /**
- * <p class="changed_added_2_0"></p>
- * @param url TODO
- * @return
- * @throws IOException
- * @throws MalformedURLException
- */
- protected HtmlPage getPage(String url) throws Exception {
- WebClient webClient = new LocalWebClient(facesServer);
- HtmlPage page = webClient.getPage("http://localhost"+url);
- return page;
- }
+ System.out.println(page.asXml());
+ Element submitElement = page.getElementById("helloForm:submit");
+ HtmlForm htmlForm = page.getFormByName("helloForm");
+
+ htmlForm.getInputByName("helloForm:username");
+ assertNotNull(htmlForm);
+
+ HtmlInput input = htmlForm.getInputByName("helloForm:username");
+
+ assertNotNull(input);
+ input.setValueAttribute("foo");
+
+ HtmlPage responsePage = (HtmlPage) htmlForm.submit((SubmittableElement) submitElement);
+
+ assertNotNull(responsePage);
+ System.out.println(responsePage.asXml());
+
+ HttpSession session = facesServer.getSession(false);
+
+ assertNotNull(session);
+
+ HelloBean bean = (HelloBean) session.getAttribute("HelloBean");
+
+ assertNotNull(bean);
+ assertEquals("foo", bean.getName());
+
+ Element span = responsePage.getElementById("responseform:userLabel");
+
+ assertNotNull(span);
+ assertEquals("foo", span.getTextContent().trim());
+ }
+
+ /**
+ * <p class="changed_added_2_0"></p>
+ * @param url TODO
+ * @return
+ * @throws IOException
+ * @throws MalformedURLException
+ */
+ protected HtmlPage getPage(String url) throws Exception {
+ WebClient webClient = new LocalWebClient(facesServer);
+ HtmlPage page = webClient.getPage("http://localhost" + url);
+
+ return page;
+ }
}
Modified: root/framework/trunk/test-base/src/test/java/org/richfaces/test/HelloBean.java
===================================================================
--- root/framework/trunk/test-base/src/test/java/org/richfaces/test/HelloBean.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/test/java/org/richfaces/test/HelloBean.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -3,13 +3,15 @@
import java.io.Serializable;
public class HelloBean implements Serializable {
+ private String name;
- private String name;
-
- public HelloBean() {}
-
- public String getName() { return name;}
-
- public void setName(String name) { this.name = name; }
-
+ public HelloBean() {}
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
}
Modified: root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServerResourcePathTest.java
===================================================================
--- root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServerResourcePathTest.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServerResourcePathTest.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,11 +1,13 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
import static org.junit.Assert.*;
import org.junit.Test;
+
import org.richfaces.test.staging.ServerResourcePath;
/**
@@ -14,81 +16,84 @@
*/
public class ServerResourcePathTest {
- /**
- * Test method for {@link org.richfaces.test.staging.ServerResourcePath#ServerResourcePath(java.lang.String)}.
- */
- @Test
- public void testRootPath() {
- ServerResourcePath path = new ServerResourcePath("/");
- assertNull(path.getNextPath());
- assertNull(path.getNextElementName());
- assertTrue(path.isFile());
- assertEquals("/", path.toString());
- }
+ /**
+ * Test method for {@link org.richfaces.test.staging.ServerResourcePath#ServerResourcePath(java.lang.String)}.
+ */
+ @Test
+ public void testRootPath() {
+ ServerResourcePath path = new ServerResourcePath("/");
- /**
- * Test method for {@link org.richfaces.test.staging.ServerResourcePath#ServerResourcePath(java.lang.String)}.
- */
- @Test
- public void testWebInfPath() {
- ServerResourcePath path = ServerResourcePath.WEB_INF;
- assertNotNull(path.getNextPath());
- assertNotNull(path.getNextElementName());
- assertFalse(path.isFile());
- assertEquals("WEB-INF/", path.getNextElementName());
- assertEquals("/WEB-INF/", path.toString());
- path = path.getNextPath();
- assertNotNull(path);
- assertTrue(path.isFile());
- path = path.getNextPath();
- assertNull(path);
- }
+ assertNull(path.getNextPath());
+ assertNull(path.getNextElementName());
+ assertTrue(path.isFile());
+ assertEquals("/", path.toString());
+ }
- /**
- * Test method for {@link org.richfaces.test.staging.ServerResourcePath#ServerResourcePath(java.lang.String)}.
- */
- @Test
- public void testWebInfTrainingSlashPath() {
- ServerResourcePath path = new ServerResourcePath("/WEB-INF/");
- assertNotNull(path.getNextPath());
- assertNotNull(path.getNextElementName());
- assertFalse(path.isFile());
- assertEquals("WEB-INF/", path.getNextElementName());
- assertEquals("/WEB-INF/", path.toString());
- path = path.getNextPath();
- assertNotNull(path);
- assertTrue(path.isFile());
- path = path.getNextPath();
- assertNull(path);
- }
+ /**
+ * Test method for {@link org.richfaces.test.staging.ServerResourcePath#ServerResourcePath(java.lang.String)}.
+ */
+ @Test
+ public void testWebInfPath() {
+ ServerResourcePath path = ServerResourcePath.WEB_INF;
-
- /**
- * Test method for {@link org.richfaces.test.staging.ServerResourcePath#ServerResourcePath(java.lang.String)}.
- */
- @Test
- public void testWebXmlPath() {
- ServerResourcePath path = ServerResourcePath.WEB_XML;
- assertFalse(path.isFile());
- assertEquals("WEB-INF/", path.getNextElementName());
- assertEquals("/WEB-INF/web.xml", path.toString());
- path = path.getNextPath();
- assertNotNull(path.getNextElementName());
- assertFalse(path.isFile());
- assertEquals("web.xml", path.getNextElementName());
- assertEquals("/web.xml", path.toString());
- path = path.getNextPath();
- assertNotNull(path);
- assertTrue(path.isFile());
- path = path.getNextPath();
- assertNull(path);
- }
+ assertNotNull(path.getNextPath());
+ assertNotNull(path.getNextElementName());
+ assertFalse(path.isFile());
+ assertEquals("WEB-INF/", path.getNextElementName());
+ assertEquals("/WEB-INF/", path.toString());
+ path = path.getNextPath();
+ assertNotNull(path);
+ assertTrue(path.isFile());
+ path = path.getNextPath();
+ assertNull(path);
+ }
- @Test
- public void testDirPath() throws Exception {
- ServerResourcePath path = new ServerResourcePath("/foo/bar");
- assertEquals("foo/", path.getNextElementName());
- assertEquals("bar", path.getNextPath().getNextElementName());
- }
+ /**
+ * Test method for {@link org.richfaces.test.staging.ServerResourcePath#ServerResourcePath(java.lang.String)}.
+ */
+ @Test
+ public void testWebInfTrainingSlashPath() {
+ ServerResourcePath path = new ServerResourcePath("/WEB-INF/");
+ assertNotNull(path.getNextPath());
+ assertNotNull(path.getNextElementName());
+ assertFalse(path.isFile());
+ assertEquals("WEB-INF/", path.getNextElementName());
+ assertEquals("/WEB-INF/", path.toString());
+ path = path.getNextPath();
+ assertNotNull(path);
+ assertTrue(path.isFile());
+ path = path.getNextPath();
+ assertNull(path);
+ }
+
+ /**
+ * Test method for {@link org.richfaces.test.staging.ServerResourcePath#ServerResourcePath(java.lang.String)}.
+ */
+ @Test
+ public void testWebXmlPath() {
+ ServerResourcePath path = ServerResourcePath.WEB_XML;
+
+ assertFalse(path.isFile());
+ assertEquals("WEB-INF/", path.getNextElementName());
+ assertEquals("/WEB-INF/web.xml", path.toString());
+ path = path.getNextPath();
+ assertNotNull(path.getNextElementName());
+ assertFalse(path.isFile());
+ assertEquals("web.xml", path.getNextElementName());
+ assertEquals("/web.xml", path.toString());
+ path = path.getNextPath();
+ assertNotNull(path);
+ assertTrue(path.isFile());
+ path = path.getNextPath();
+ assertNull(path);
+ }
+
+ @Test
+ public void testDirPath() throws Exception {
+ ServerResourcePath path = new ServerResourcePath("/foo/bar");
+
+ assertEquals("foo/", path.getNextElementName());
+ assertEquals("bar", path.getNextPath().getNextElementName());
+ }
}
Modified: root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServerResourceTest.java
===================================================================
--- root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServerResourceTest.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServerResourceTest.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.test.staging;
@@ -7,10 +8,13 @@
import java.io.IOException;
import java.io.InputStream;
+
import java.net.URL;
+
import java.util.Set;
import org.junit.Test;
+
import org.richfaces.test.staging.ClasspathServerResource;
import org.richfaces.test.staging.ServerResource;
import org.richfaces.test.staging.ServerResourcePath;
@@ -18,128 +22,132 @@
/**
* @author asmirnov
- *
+ *
*/
public class ServerResourceTest {
- private class MockResource implements ServerResource {
+ /**
+ * Test method for
+ * {@link org.richfaces.test.staging.ServerResourcesDirectory#addResource(org.richfaces.test.staging.ServerResourcePath, org.richfaces.test.staging.ServerResource)}
+ * .
+ */
+ @Test
+ public void testAddResource() {
+ ServerResourcesDirectory root = new ServerResourcesDirectory();
+ MockResource webXml = new MockResource();
- public void addResource(ServerResourcePath path, ServerResource resource) {
- }
+ root.addResource(ServerResourcePath.WEB_XML, webXml);
+ assertEquals(1, root.getPaths().size());
- public InputStream getAsStream() throws IOException {
- return null;
- }
+ MockResource facesConfig = new MockResource();
- public Set<String> getPaths() {
- return null;
- }
+ root.addResource(ServerResourcePath.FACES_CONFIG, facesConfig);
+ assertEquals(1, root.getPaths().size());
- public ServerResource getResource(ServerResourcePath path) {
- if (null != path && path.isFile()) {
- return this;
- }
- return null;
- }
+ ServerResource webInf = root.getResource(ServerResourcePath.WEB_INF);
- public URL getURL() {
- return null;
- }
+ assertNotNull(webInf);
+ assertEquals(2, webInf.getPaths().size());
+ assertSame(webXml, webInf.getResource(new ServerResourcePath("/web.xml")));
+ assertSame(facesConfig, webInf.getResource(new ServerResourcePath("/faces-config.xml")));
+ }
- }
+ /**
+ * Test method for
+ * {@link org.richfaces.test.staging.ServerResourcesDirectory#getResource(org.richfaces.test.staging.ServerResourcePath)}
+ * .
+ */
+ @Test
+ public void testGetResource() {
+ ServerResourcesDirectory root = new ServerResourcesDirectory();
+ MockResource webXml = new MockResource();
- /**
- * Test method for
- * {@link org.richfaces.test.staging.ServerResourcesDirectory#addResource(org.richfaces.test.staging.ServerResourcePath, org.richfaces.test.staging.ServerResource)}
- * .
- */
- @Test
- public void testAddResource() {
- ServerResourcesDirectory root = new ServerResourcesDirectory();
- MockResource webXml = new MockResource();
- root.addResource(ServerResourcePath.WEB_XML, webXml);
- assertEquals(1, root.getPaths().size());
- MockResource facesConfig = new MockResource();
- root.addResource(ServerResourcePath.FACES_CONFIG, facesConfig);
- assertEquals(1, root.getPaths().size());
- ServerResource webInf = root.getResource(ServerResourcePath.WEB_INF);
- assertNotNull(webInf);
- assertEquals(2, webInf.getPaths().size());
- assertSame(webXml, webInf
- .getResource(new ServerResourcePath("/web.xml")));
- assertSame(facesConfig, webInf.getResource(new ServerResourcePath(
- "/faces-config.xml")));
- }
+ root.addResource(ServerResourcePath.WEB_XML, webXml);
- /**
- * Test method for
- * {@link org.richfaces.test.staging.ServerResourcesDirectory#getResource(org.richfaces.test.staging.ServerResourcePath)}
- * .
- */
- @Test
- public void testGetResource() {
- ServerResourcesDirectory root = new ServerResourcesDirectory();
- MockResource webXml = new MockResource();
- root.addResource(ServerResourcePath.WEB_XML, webXml);
- ServerResource webInf = root.getResource(ServerResourcePath.WEB_INF);
- assertNotNull(webInf);
- assertNull(root.getResource(new ServerResourcePath("/foo")));
- assertNull(root.getResource(new ServerResourcePath("/foo/baz")));
- assertEquals(1, root.getPaths().size());
- assertNull(root.getResource(new ServerResourcePath(
- "/WEB-INF/web.xml/foo")));
- assertSame(webXml, webInf.getResource(new ServerResourcePath(
- "/web.xml")));
- }
+ ServerResource webInf = root.getResource(ServerResourcePath.WEB_INF);
- /**
- * Test method for
- * {@link org.richfaces.test.staging.ServerResourcesDirectory#getResource(org.richfaces.test.staging.ServerResourcePath)}
- * .
- */
- @Test
- public void testGetResourceRoot() {
- ServerResourcesDirectory root = new ServerResourcesDirectory();
- MockResource indexXhtml = new MockResource();
- root.addResource(new ServerResourcePath("/index.xhtml"), indexXhtml);
- ServerResource index = root.getResource(new ServerResourcePath("/index.xhtml"));
- assertNotNull(index);
- assertNull(root.getResource(new ServerResourcePath("/foo")));
- assertNull(root.getResource(new ServerResourcePath("/foo/baz")));
- assertEquals(1, root.getPaths().size());
- }
-
- /**
- * Test method for
- * {@link org.richfaces.test.staging.ServerResourcesDirectory#getAsStream()}.
- *
- * @throws IOException
- */
- @Test
- public void testGetAsStream() throws IOException {
- ClasspathServerResource resource = new ClasspathServerResource(
- "org/richfaces/test/resource.txt");
- InputStream inputStream = resource.getAsStream();
- assertNotNull(inputStream);
- try {
- byte[] buff = new byte[20];
- assertEquals(3, inputStream.read(buff));
+ assertNotNull(webInf);
+ assertNull(root.getResource(new ServerResourcePath("/foo")));
+ assertNull(root.getResource(new ServerResourcePath("/foo/baz")));
+ assertEquals(1, root.getPaths().size());
+ assertNull(root.getResource(new ServerResourcePath("/WEB-INF/web.xml/foo")));
+ assertSame(webXml, webInf.getResource(new ServerResourcePath("/web.xml")));
+ }
- } finally {
- inputStream.close();
- }
- }
+ /**
+ * Test method for
+ * {@link org.richfaces.test.staging.ServerResourcesDirectory#getResource(org.richfaces.test.staging.ServerResourcePath)}
+ * .
+ */
+ @Test
+ public void testGetResourceRoot() {
+ ServerResourcesDirectory root = new ServerResourcesDirectory();
+ MockResource indexXhtml = new MockResource();
+ root.addResource(new ServerResourcePath("/index.xhtml"), indexXhtml);
- /**
- * Test method for
- * {@link org.richfaces.test.staging.ServerResourcesDirectory#getURL()}.
- */
- @Test
- public void testGetURL() {
- ClasspathServerResource resource = new ClasspathServerResource(
- "org/richfaces/test/resource.txt");
- assertNotNull(resource.getURL());
- }
+ ServerResource index = root.getResource(new ServerResourcePath("/index.xhtml"));
+ assertNotNull(index);
+ assertNull(root.getResource(new ServerResourcePath("/foo")));
+ assertNull(root.getResource(new ServerResourcePath("/foo/baz")));
+ assertEquals(1, root.getPaths().size());
+ }
+
+ /**
+ * Test method for
+ * {@link org.richfaces.test.staging.ServerResourcesDirectory#getAsStream()}.
+ *
+ * @throws IOException
+ */
+ @Test
+ public void testGetAsStream() throws IOException {
+ ClasspathServerResource resource = new ClasspathServerResource("org/richfaces/test/resource.txt");
+ InputStream inputStream = resource.getAsStream();
+
+ assertNotNull(inputStream);
+
+ try {
+ byte[] buff = new byte[20];
+
+ assertEquals(3, inputStream.read(buff));
+ } finally {
+ inputStream.close();
+ }
+ }
+
+ /**
+ * Test method for
+ * {@link org.richfaces.test.staging.ServerResourcesDirectory#getURL()}.
+ */
+ @Test
+ public void testGetURL() {
+ ClasspathServerResource resource = new ClasspathServerResource("org/richfaces/test/resource.txt");
+
+ assertNotNull(resource.getURL());
+ }
+
+ private class MockResource implements ServerResource {
+ public void addResource(ServerResourcePath path, ServerResource resource) {}
+
+ public InputStream getAsStream() throws IOException {
+ return null;
+ }
+
+ public Set<String> getPaths() {
+ return null;
+ }
+
+ public ServerResource getResource(ServerResourcePath path) {
+ if (null != path && path.isFile()) {
+ return this;
+ }
+
+ return null;
+ }
+
+ public URL getURL() {
+ return null;
+ }
+ }
}
Modified: root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServletTest.java
===================================================================
--- root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServletTest.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/ServletTest.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -6,6 +6,7 @@
import javax.servlet.ServletException;
import org.junit.Test;
+
import org.richfaces.test.staging.RequestChain;
import org.richfaces.test.staging.ServerResource;
import org.richfaces.test.staging.ServletContainer;
@@ -13,85 +14,83 @@
import org.richfaces.test.staging.StagingServletContext;
public class ServletTest {
+ @Test
+ public void testIsApplicable() {
+ StaticServlet staticServlet = new StaticServlet();
+ RequestChain servlet = new ServletContainer("/foo/*", staticServlet);
- @Test
- public void testIsApplicable() {
- StaticServlet staticServlet = new StaticServlet();
- RequestChain servlet = new ServletContainer("/foo/*",staticServlet);
- assertTrue(servlet.isApplicable("/foo/bar.jsf"));
- assertFalse(servlet.isApplicable("/foz/bar.jsf"));
- assertFalse(servlet.isApplicable("bar"));
- servlet = new ServletContainer("*.jsf",staticServlet);
- assertTrue(servlet.isApplicable("/foo/bar.jsf"));
- assertFalse(servlet.isApplicable("bar"));
- try {
- servlet = new ServletContainer(".jsf",staticServlet);
- } catch (IllegalArgumentException e) {
- return;
- }
- assertFalse(true);
- }
+ assertTrue(servlet.isApplicable("/foo/bar.jsf"));
+ assertFalse(servlet.isApplicable("/foz/bar.jsf"));
+ assertFalse(servlet.isApplicable("bar"));
+ servlet = new ServletContainer("*.jsf", staticServlet);
+ assertTrue(servlet.isApplicable("/foo/bar.jsf"));
+ assertFalse(servlet.isApplicable("bar"));
- @Test
- public void testGetServletPath() {
- StaticServlet staticServlet = new StaticServlet();
- RequestChain servlet = new ServletContainer("/foo/*",staticServlet);
- assertEquals("/foo/", servlet.getServletPath("/foo/bar.jsf"));
- assertNull(servlet.getServletPath("/foz/bar.jsf"));
- servlet = new ServletContainer("*.jsf",staticServlet);
- assertEquals("/foo/bar.jsf", servlet.getServletPath("/foo/bar.jsf"));
- }
+ try {
+ servlet = new ServletContainer(".jsf", staticServlet);
+ } catch (IllegalArgumentException e) {
+ return;
+ }
- @Test
- public void testGetPathInfo() {
- StaticServlet staticServlet = new StaticServlet();
- RequestChain servlet = new ServletContainer("/foo/*",staticServlet);
- assertEquals("bar.jsf", servlet.getPathInfo("/foo/bar.jsf"));
- assertNull(servlet.getPathInfo("/foz/bar.jsf"));
- servlet = new ServletContainer("*.jsf",staticServlet);
- assertNull(servlet.getPathInfo("/foo/bar.jsf"));
+ assertFalse(true);
+ }
- }
+ @Test
+ public void testGetServletPath() {
+ StaticServlet staticServlet = new StaticServlet();
+ RequestChain servlet = new ServletContainer("/foo/*", staticServlet);
- @Test
- public void testInit() throws ServletException {
- StaticServlet staticServlet = new StaticServlet();
- RequestChain servlet = new ServletContainer("/foo/*",staticServlet);
- StagingServletContext context = new StagingServletContext(){
+ assertEquals("/foo/", servlet.getServletPath("/foo/bar.jsf"));
+ assertNull(servlet.getServletPath("/foz/bar.jsf"));
+ servlet = new ServletContainer("*.jsf", staticServlet);
+ assertEquals("/foo/bar.jsf", servlet.getServletPath("/foo/bar.jsf"));
+ }
- @Override
- protected ServerResource getServerResource(String path) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Test
+ public void testGetPathInfo() {
+ StaticServlet staticServlet = new StaticServlet();
+ RequestChain servlet = new ServletContainer("/foo/*", staticServlet);
- @Override
- protected void valueBound(ServletContextAttributeEvent event) {
- // TODO Auto-generated method stub
-
- }
+ assertEquals("bar.jsf", servlet.getPathInfo("/foo/bar.jsf"));
+ assertNull(servlet.getPathInfo("/foz/bar.jsf"));
+ servlet = new ServletContainer("*.jsf", staticServlet);
+ assertNull(servlet.getPathInfo("/foo/bar.jsf"));
+ }
- @Override
- protected void valueReplaced(ServletContextAttributeEvent event) {
- // TODO Auto-generated method stub
-
- }
+ @Test
+ public void testInit() throws ServletException {
+ StaticServlet staticServlet = new StaticServlet();
+ RequestChain servlet = new ServletContainer("/foo/*", staticServlet);
+ StagingServletContext context = new StagingServletContext() {
+ @Override
+ protected ServerResource getServerResource(String path) {
- @Override
- protected void valueUnbound(
- ServletContextAttributeEvent servletContextAttributeEvent) {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
+ @Override
+ protected void valueBound(ServletContextAttributeEvent event) {
- public String getMimeType(String file) {
- // TODO Auto-generated method stub
- return null;
- }
-
- };
- servlet.init(context);
- assertSame(context,staticServlet.getServletContext());
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ protected void valueReplaced(ServletContextAttributeEvent event) {
+ // TODO Auto-generated method stub
+ }
+ @Override
+ protected void valueUnbound(ServletContextAttributeEvent servletContextAttributeEvent) {
+
+ // TODO Auto-generated method stub
+ }
+ public String getMimeType(String file) {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+ };
+
+ servlet.init(context);
+ assertSame(context, staticServlet.getServletContext());
+ }
}
Modified: root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/UrlResourceLoadingTest.java
===================================================================
--- root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/UrlResourceLoadingTest.java 2009-11-02 12:03:55 UTC (rev 15807)
+++ root/framework/trunk/test-base/src/test/java/org/richfaces/test/staging/UrlResourceLoadingTest.java 2009-11-02 12:12:01 UTC (rev 15808)
@@ -3,8 +3,10 @@
import static org.junit.Assert.*;
import java.io.File;
+
import java.net.URI;
import java.net.URL;
+
import java.util.Enumeration;
import java.util.Iterator;
import java.util.zip.ZipEntry;
@@ -13,43 +15,49 @@
import org.junit.Test;
public class UrlResourceLoadingTest {
+ @Test
+ public void testAddFromJar() throws Exception {
+ URL resource = this.getClass().getClassLoader().getResource("java/util/Set.class");
- @Test
- public void testAddFromJar() throws Exception {
- URL resource = this.getClass().getClassLoader().getResource("java/util/Set.class");
- assertNotNull(resource);
- StagingServer server = new StagingServer();
- ServerResourcesDirectory baseDir = new ServerResourcesDirectory();
- server.addResourcesFromJar(resource, baseDir);
- assertNotNull(baseDir.getResource(new ServerResourcePath("/Map.class")));
- assertNotNull(baseDir.getResource(new ServerResourcePath("/concurrent/atomic/AtomicBoolean.class")));
- }
+ assertNotNull(resource);
- @Test
- public void testAddFromFile() throws Exception {
- URL resource = this.getClass().getClassLoader().getResource("org/richfaces/test/resource.txt");
- assertNotNull(resource);
- StagingServer server = new StagingServer();
- ServerResourcesDirectory baseDir = new ServerResourcesDirectory();
- server.addResourcesFromFile(resource, baseDir);
- assertNotNull(baseDir.getResource(new ServerResourcePath("/logging.properties")));
- assertNotNull(baseDir.getResource(new ServerResourcePath("/WEB-INF/faces-config.xml")));
- }
+ StagingServer server = new StagingServer();
+ ServerResourcesDirectory baseDir = new ServerResourcesDirectory();
-
- @Test
- public void testGetDirectory() throws Exception {
- URL resource = this.getClass().getClassLoader().getResource("java/util/Set.class");
- assertNotNull(resource);
- StagingServer server = new StagingServer();
- server.addResourcesFromDirectory("/WEB-INF/classes/java/util/", resource);
- try {
- server.init();
- assertNotNull(server.getContext().getResource("/WEB-INF/classes/java/util/Map.class"));
- } finally {
- server.destroy();
- }
-
- }
+ server.addResourcesFromJar(resource, baseDir);
+ assertNotNull(baseDir.getResource(new ServerResourcePath("/Map.class")));
+ assertNotNull(baseDir.getResource(new ServerResourcePath("/concurrent/atomic/AtomicBoolean.class")));
+ }
+ @Test
+ public void testAddFromFile() throws Exception {
+ URL resource = this.getClass().getClassLoader().getResource("org/richfaces/test/resource.txt");
+
+ assertNotNull(resource);
+
+ StagingServer server = new StagingServer();
+ ServerResourcesDirectory baseDir = new ServerResourcesDirectory();
+
+ server.addResourcesFromFile(resource, baseDir);
+ assertNotNull(baseDir.getResource(new ServerResourcePath("/logging.properties")));
+ assertNotNull(baseDir.getResource(new ServerResourcePath("/WEB-INF/faces-config.xml")));
+ }
+
+ @Test
+ public void testGetDirectory() throws Exception {
+ URL resource = this.getClass().getClassLoader().getResource("java/util/Set.class");
+
+ assertNotNull(resource);
+
+ StagingServer server = new StagingServer();
+
+ server.addResourcesFromDirectory("/WEB-INF/classes/java/util/", resource);
+
+ try {
+ server.init();
+ assertNotNull(server.getContext().getResource("/WEB-INF/classes/java/util/Map.class"));
+ } finally {
+ server.destroy();
+ }
+ }
}
15 years, 10 months
JBoss Rich Faces SVN: r15807 - in root/framework/trunk/legacy-tests/src: main/java/org/ajax4jsf/tests/org/apache/shale/test/config and 9 other directories.
by richfaces-svn-commits@lists.jboss.org
Author: Alex.Kolonitsky
Date: 2009-11-02 07:03:55 -0500 (Mon, 02 Nov 2009)
New Revision: 15807
Modified:
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractAjax4JsfTestCase.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractJspTestCase.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractThreadedAjax4JsfTestCase.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/Condition.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/ConstantlyFailingLiteralValueExpression.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/DummyScriptEngine.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/EnumSupportExpressionFactoryWrapper.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/HtmlTestUtils.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/JsfMock.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/LiteralValueExpression.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockAjax4JsfLifecycle.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockApplication.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockComponentState.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockDataModel.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockDataModelListener.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockELContext.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockELContext2.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockExternalContext.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockFaceletContext.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockFacesResourceContext.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockMethodBinding.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockMethodExpression.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockPageContext.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockRange.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockSerializableDataModel.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockUIComponent.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockUIInputRenderer.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockValueBinding.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockValueExpression.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockViewHandler.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockViewRoot.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/org/apache/shale/test/config/ConfigParser.java
root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/xml/FacesEntityResolver.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/AjaxStateHolderTest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/AjaxStateManagerTest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/ComponentLoaderTest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/component/AjaxViewRootTest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/AjaxContextImplTest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/AjaxContextTest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/MockAjaxContext.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/AllTests.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/CacheContentTest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/NekkoParserTest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/BeforeRendererListenerTestCase.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitImplTestCase.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/RenderTests.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/AllResourcesTests.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/CSSTemplateTestCase.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/InternetResourceServiceTestCase.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockCacheableResource.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockFilterConfig.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockResourceRequest.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/ParametersEncodingTestCase.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/ResourceServiceThreadsTestCase.java
root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/webapp/WebXmlTest.java
root/framework/trunk/legacy-tests/src/test/java/org/richfaces/util/RenderPhaseComponentVisitorUtilsTest.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractAjax4JsfTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractAjax4JsfTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractAjax4JsfTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import java.io.ByteArrayInputStream;
@@ -28,8 +30,11 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+
import java.lang.reflect.Field;
+
import java.net.URL;
+
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
@@ -41,6 +46,7 @@
import javax.el.ELContext;
import javax.el.ExpressionFactory;
+
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.component.UIComponent;
@@ -48,6 +54,7 @@
import javax.faces.context.FacesContext;
import javax.faces.render.RenderKitFactory;
import javax.faces.render.Renderer;
+
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
@@ -69,11 +76,13 @@
import org.ajax4jsf.webapp.BaseXMLFilter;
import org.ajax4jsf.webapp.HtmlParser;
import org.ajax4jsf.webapp.WebXml;
+
import org.apache.shale.test.base.AbstractJsfTestCase;
import org.apache.shale.test.mock.MockApplication;
import org.apache.shale.test.mock.MockPrintWriter;
import org.apache.shale.test.mock.MockResponseWriter;
import org.apache.shale.test.mock.MockServletOutputStream;
+
import org.richfaces.VersionBean;
import org.richfaces.skin.SkinBean;
import org.richfaces.skin.SkinFactory;
@@ -98,614 +107,664 @@
*
*/
public class AbstractAjax4JsfTestCase extends AbstractJsfTestCase {
+ private static final String HTTP_PREFIX = "http:";
+ private static final String IMAGE_NOT_FOUND_OR_UNAVAILABLE_MESSAGE = "Image not found or unavailable";
+ private static final String RESOURCE_NOT_FOUND_MESSAGE = "Resource not found";
+ @Deprecated
+ protected final static String SLASHED_RESOURCE_URI_PREFIX = "/" + WebXml.RESOURCE_URI_PREFIX;
+ protected AjaxContext ajaxContext = null;
- private static final String IMAGE_NOT_FOUND_OR_UNAVAILABLE_MESSAGE = "Image not found or unavailable";
+ // Thread context class loader saved and restored after each test
+ private ClassLoader threadContextClassLoader = null;
+ private File tmpRoot = null;
- private static final String RESOURCE_NOT_FOUND_MESSAGE = "Resource not found";
+ /**
+ * Initialised instance of VCP render kit.
+ */
+ protected ChameleonRenderKitImpl vcpRenderKit = null;
- private static final String HTTP_PREFIX = "http:";
+ /**
+ * <p>The htmlunit web client for this test case. </p>
+ *
+ */
+ protected WebClient webClient = null;
- @Deprecated
- protected final static String SLASHED_RESOURCE_URI_PREFIX = "/" + WebXml.RESOURCE_URI_PREFIX;
+ /**
+ * Mock web connection for accept stored content of JSF encoding. For testing JavaScript code, all URL's for scripts must be
+ * rregistered by {@link MockWebConnection#setResponse(java.net.URL, byte[], int, java.lang.String, java.lang.String, java.util.List)} method
+ * By default, for unregistered pages return 404 - not found.
+ */
+ protected MockWebConnection webConnection = null;
+ protected ELContext elContext;
+ protected ExpressionFactory expressionFactory;
+ protected WebXml webXml;
- private File tmpRoot = null;
+ /**
+ * Instance of Mock {@link javax.faces.context.ResponseWriter} , created by setupResponseWriter
+ */
+ protected MockResponseWriter writer;
- protected ELContext elContext;
-
- protected ExpressionFactory expressionFactory;
-
- public static final void evaluate(Condition condition) {
- String message = condition.getMessage();
- assertTrue(message, condition.isConditionTrue());
- }
- /**
- * @param name
- */
- public AbstractAjax4JsfTestCase(String name) {
- super(name);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param name
+ */
+ public AbstractAjax4JsfTestCase(String name) {
+ super(name);
- /* (non-Javadoc)
- * @see org.apache.shale.test.base.AbstractJsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- // This method MUST BE OVERRIDEN in any subclasses - since Junit see for it in class for call
- super.setUp();
+ // TODO Auto-generated constructor stub
+ }
- //Try to override default expression factory with our wrapper that supports enums (like Sun's)
- try {
- ExpressionFactory exprFact =
- new EnumSupportExpressionFactoryWrapper(application.getExpressionFactory());
-
- Class<? extends MockApplication> applicationClass = application.getClass();
- Field field = applicationClass.getDeclaredField("expressionFactory");
- field.setAccessible(true);
- field.set(application, exprFact);
- expressionFactory = application.getExpressionFactory();
- } catch(Exception e) {
- //e.printStackTrace();
- //We cannot set private field
- }
-
- // Setup FacesContext with necessary init parameters.
- this.servletContext.addInitParameter(SkinFactory.SKIN_PARAMETER, getSkinName());
-
- this.servletContext.addInitParameter("com.sun.faces.externalizeJavaScript", "true");
-
-
- // setup VCP renderKit, create renderers.
- RenderKitFactory vcpRenderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
- vcpRenderKit = new ChameleonRenderKitImpl();
- vcpRenderKitFactory.addRenderKit("HTML_CHAMELEON", vcpRenderKit);
- renderKit.addRenderer(UIViewRoot.COMPONENT_FAMILY, UIViewRoot.COMPONENT_TYPE, new AjaxViewRootRenderer());
- // setup nessesary components.
- application.addComponent("javax.faces.ViewRoot", MockViewRoot.class.getName());
- // setup AjaxContext.
- ajaxContext = new AjaxContextImpl();
- request.setAttribute(AjaxContext.AJAX_CONTEXT_KEY, ajaxContext);
- // Setup ViewHandler / ViewRoot.
- application.setViewHandler(new MockViewHandler(application.getViewHandler()));
-
- UIViewRoot root = new MockViewRoot();
+ public static final void evaluate(Condition condition) {
+ String message = condition.getMessage();
+
+ assertTrue(message, condition.isConditionTrue());
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.apache.shale.test.base.AbstractJsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+
+ // This method MUST BE OVERRIDEN in any subclasses - since Junit see for it in class for call
+ super.setUp();
+
+ // Try to override default expression factory with our wrapper that supports enums (like Sun's)
+ try {
+ ExpressionFactory exprFact = new EnumSupportExpressionFactoryWrapper(application.getExpressionFactory());
+ Class<? extends MockApplication> applicationClass = application.getClass();
+ Field field = applicationClass.getDeclaredField("expressionFactory");
+
+ field.setAccessible(true);
+ field.set(application, exprFact);
+ expressionFactory = application.getExpressionFactory();
+ } catch (Exception e) {
+
+ // e.printStackTrace();
+ // We cannot set private field
+ }
+
+ // Setup FacesContext with necessary init parameters.
+ this.servletContext.addInitParameter(SkinFactory.SKIN_PARAMETER, getSkinName());
+ this.servletContext.addInitParameter("com.sun.faces.externalizeJavaScript", "true");
+
+ // setup VCP renderKit, create renderers.
+ RenderKitFactory vcpRenderKitFactory =
+ (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
+
+ vcpRenderKit = new ChameleonRenderKitImpl();
+ vcpRenderKitFactory.addRenderKit("HTML_CHAMELEON", vcpRenderKit);
+ renderKit.addRenderer(UIViewRoot.COMPONENT_FAMILY, UIViewRoot.COMPONENT_TYPE, new AjaxViewRootRenderer());
+
+ // setup nessesary components.
+ application.addComponent("javax.faces.ViewRoot", MockViewRoot.class.getName());
+
+ // setup AjaxContext.
+ ajaxContext = new AjaxContextImpl();
+ request.setAttribute(AjaxContext.AJAX_CONTEXT_KEY, ajaxContext);
+
+ // Setup ViewHandler / ViewRoot.
+ application.setViewHandler(new MockViewHandler(application.getViewHandler()));
+
+ UIViewRoot root = new MockViewRoot();
+
root.setViewId("/viewId");
root.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
facesContext.setViewRoot(root);
- // Setup Skin avd version variables.
- servletContext.setAttribute("a4j", new VersionBean());
- servletContext.setAttribute("a4jSkin", new SkinBean());
- // Setup servlet context and testing web.xml
- request.setPathElements("/testContext","/faces","/vievId.jsf","");
- File webRoot = new File(getClass().getResource("/WEB-INF/web.xml").getFile()).getParentFile().getParentFile();
- if (webRoot.exists()) {
- servletContext.setDocumentRoot(webRoot);
- } else {
- // Prepare WEB-ROOT in temp folder
- tmpRoot = File.createTempFile("TmpTestRoot" + new Random().nextInt(), null);
- tmpRoot.delete();
- tmpRoot.mkdir();
- servletContext.setDocumentRoot(tmpRoot);
+ // Setup Skin avd version variables.
+ servletContext.setAttribute("a4j", new VersionBean());
+ servletContext.setAttribute("a4jSkin", new SkinBean());
- URL jarUrl = AbstractAjax4JsfTestCase.class.getProtectionDomain().getCodeSource().getLocation();
- ZipInputStream zis = new ZipInputStream(jarUrl.openStream());
- try {
- ZipEntry entry;
- byte[] buffer = new byte[8192];
- while ((entry = zis.getNextEntry()) != null) {
- String name = entry.getName();
- if (name.startsWith("WEB-INF/")) {
- File out = new File(tmpRoot, name);
- if (entry.isDirectory()) {
- out.mkdirs();
- } else {
- out.getParentFile().mkdirs();
- OutputStream os = new FileOutputStream(out);
- try {
- int count;
- while ((count = zis.read(buffer)) > 0) {
- os.write(buffer, 0, count);
- }
- } finally {
- os.close();
- }
- zis.closeEntry();
- }
- }
- }
- } catch (IOException e) {
- deleteRecursively(tmpRoot);
- throw e;
- }
- servletContext.setDocumentRoot(tmpRoot);
- }
+ // Setup servlet context and testing web.xml
+ request.setPathElements("/testContext", "/faces", "/vievId.jsf", "");
- try {
- InternetResourceBuilder.getInstance().init();
- } catch (FacesException e) {
- InternetResourceBuilder.setInstance(null);
- }
- webXml = new WebXml();
- webXml.init(servletContext, "A4J");
+ File webRoot = new File(getClass().getResource("/WEB-INF/web.xml").getFile()).getParentFile().getParentFile();
- ConfigParser parser = new ConfigParser();
- parser.parse(parser.getPlatformURLs());
+ if (webRoot.exists()) {
+ servletContext.setDocumentRoot(webRoot);
+ } else {
- Enumeration<URL> resources = getClass().getClassLoader().getResources("META-INF/faces-config.xml");
- while (resources.hasMoreElements()) {
- parser.parse((URL) resources.nextElement());
- }
-
- externalContext = new MockExternalContext(externalContext);
- facesContext.setExternalContext(externalContext);
- elContext = facesContext.getELContext();
- expressionFactory = application.getExpressionFactory();
- }
+ // Prepare WEB-ROOT in temp folder
+ tmpRoot = File.createTempFile("TmpTestRoot" + new Random().nextInt(), null);
+ tmpRoot.delete();
+ tmpRoot.mkdir();
+ servletContext.setDocumentRoot(tmpRoot);
- protected WebClient createWebClient() {
- WebClient client = new WebClient();
- // disable javascript for now as HtmlUnit doesn't treat prototype.js
- // well
- client.setJavaScriptEnabled(true);
- // Set dummy script engine to prevent NPEs from default HtmlUnit engine
- client.setJavaScriptEngine(new DummyScriptEngine(client));
- return client;
- }
+ URL jarUrl = AbstractAjax4JsfTestCase.class.getProtectionDomain().getCodeSource().getLocation();
+ ZipInputStream zis = new ZipInputStream(jarUrl.openStream());
- /**
- * This function checks is resource present. If so, resource returned in the form of InputStream, otherwise IOException throwed.
- *
- * @param path - path to specified resource
- *
- * @return InputStream of the resource, if resource present
- *
- * @throws IOException - if resource not available
- */
- protected InputStream getResourceIfPresent(String path) throws IOException {
- InternetResourceBuilder builder = ResourceBuilderImpl.getInstance();
- InternetResource resource = builder.getResource(path);
- if (resource != null) {
- String uri = HTTP_PREFIX + resource.getUri(facesContext, null);
- Page page = webClient.getPage(uri);
- if (page.getWebResponse().getStatusCode() == HttpServletResponse.SC_OK) {
- return page.getWebResponse().getContentAsStream();
- }
- }
- throw new IOException(RESOURCE_NOT_FOUND_MESSAGE + path);
- }
+ try {
+ ZipEntry entry;
+ byte[] buffer = new byte[8192];
- /**
- * This function checks is image resource present. If so, image returned, otherwise IOException throwed.
- *
- * @param path - path to specified image resource
- *
- * @return ImageInfo of the image, if image resource present or null if method ImageInfo.check() return false;
- *
- * @throws IOException - if image not available or not exist
- */
- protected ImageInfo getImageResource(String path) throws IOException {
- ImageInfo info = new ImageInfo();
- try {
- info.setInput(getResourceIfPresent(path));
- } catch(IOException e){
- throw new IOException(IMAGE_NOT_FOUND_OR_UNAVAILABLE_MESSAGE + path);
- }
- return info.check() ? info : null;
- }
-
- /**
- * This function return count of <script> elements on page and validate - if this script contains in Set of predefined attribute for this component
- *
- * @param view - page to validate
- * @param predefinedScripts - set of predefined scripts, should be presented on component
- *
- * @return count of valid <script> element
- * @throws Exception if script not available on page
- */
- protected Integer getCountValidScripts(HtmlPage view, Set<String> predefinedScripts, boolean isPageAvailabilityCheck)
- throws Exception {
- /*List<HtmlScript> scripts = view.getDocumentHtmlElement()
- .getHtmlElementsByTagName(HTML.SCRIPT_ELEM);
- int foundCount = 0;
- for (Iterator<HtmlScript> it = scripts.iterator(); it.hasNext();) {
- HtmlScript item = it.next();
- String srcAttr = item.getSrcAttribute();
+ while ((entry = zis.getNextEntry()) != null) {
+ String name = entry.getName();
- if (StringUtils.isNotBlank(srcAttr)) {
- boolean found = false;
- for (Iterator<String> srcIt = predefinedScripts.iterator(); srcIt
- .hasNext();) {
- String src = (String) srcIt.next();
+ if (name.startsWith("WEB-INF/")) {
+ File out = new File(tmpRoot, name);
- found = srcAttr.contains(src);
- if (found) {
- foundCount++;
+ if (entry.isDirectory()) {
+ out.mkdirs();
+ } else {
+ out.getParentFile().mkdirs();
- String uri = "http:" + srcAttr;
- Page page = webClient.getPage(uri);
- if (!(page != null && page.getWebResponse()
- .getStatusCode() == HttpServletResponse.SC_OK)) {
- throw new Exception("Page is not available " + uri);
+ OutputStream os = new FileOutputStream(out);
- }
- break;
- }
- }
- }
- }
- return foundCount;*/
- int foundCount = 0;
- List<String> scriptSources = HtmlTestUtils.extractScriptSources(view);
- for (String javascript : predefinedScripts) {
- for (String script : scriptSources) {
- if (script.indexOf(javascript) >= 0) {
- foundCount++;
+ try {
+ int count;
- String uri = HTTP_PREFIX + script;
- Page page = webClient.getPage(uri);
- if(isPageAvailabilityCheck){
- if (!(page != null && page.getWebResponse()
- .getStatusCode() == HttpServletResponse.SC_OK)) {
- throw new Exception("Component script " + javascript + " is not found in the response");
- }
- }
- break;
- }
- }
- }
- return foundCount;
- }
-
- /**
- *
- */
- protected void setupWebClient() {
- ajaxContext = null;
- // setup webClient for got response content.
- webClient = createWebClient();
- webConnection = new MockWebConnection(webClient) {
- public WebResponse getResponse(WebRequestSettings settings)
- throws IOException {
- String resourceKey = WebXml.getInstance(facesContext).getFacesResourceKey(settings.getURL().getFile().substring(
- request.getContextPath().length()));
- if (resourceKey != null) {
- InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
-
- InternetResource resource = resourceBuilder.getResourceForKey(resourceKey);
- Object resourceData = resourceBuilder.getResourceDataForKey(resourceKey);
+ while ((count = zis.read(buffer)) > 0) {
+ os.write(buffer, 0, count);
+ }
+ } finally {
+ os.close();
+ }
- final MockFacesResourceContext resourceContext = new MockFacesResourceContext(facesContext);
- resourceContext.setResourceData(resourceData);
+ zis.closeEntry();
+ }
+ }
+ }
+ } catch (IOException e) {
+ deleteRecursively(tmpRoot);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- response.setOutputStream(new MockServletOutputStream(baos));
-
- resource.sendHeaders(resourceContext);
- resource.send(resourceContext);
-
- return new WebResponseImpl(
- new WebResponseData(
- new ByteArrayInputStream(baos.toByteArray()),
- HttpServletResponse.SC_OK,
- "OK",
- resourceContext.getHeaders()),
- settings.getURL(),
- settings.getSubmitMethod(),
- 0) {
+ throw e;
+ }
- public String getContentType() {
- return resourceContext.getContentType();
- }
- };
+ servletContext.setDocumentRoot(tmpRoot);
+ }
- } else {
- return super.getResponse(settings);
- }
- }
- };
- webClient.setWebConnection(webConnection);
- webConnection.setDefaultResponse("<html><body>not found</body></html>",404,"NOT FOUND","text/html");
- webClient.setThrowExceptionOnFailingStatusCode(false);
- webClient.setThrowExceptionOnScriptError(false);
- }
+ try {
+ InternetResourceBuilder.getInstance().init();
+ } catch (FacesException e) {
+ InternetResourceBuilder.setInstance(null);
+ }
- private void deleteRecursively(File file) {
- if (file != null) {
+ webXml = new WebXml();
+ webXml.init(servletContext, "A4J");
- String[] list = file.list();
- if (list != null) {
- for (int i = 0; i < list.length; i++) {
- String name = list[i];
- File f = new File(file, name);
- if (f.isDirectory()) {
- deleteRecursively(f);
- } else {
- f.delete();
- }
- }
- }
+ ConfigParser parser = new ConfigParser();
- file.delete();
- }
- }
+ parser.parse(parser.getPlatformURLs());
+ Enumeration<URL> resources = getClass().getClassLoader().getResources("META-INF/faces-config.xml");
- /* (non-Javadoc)
- * @see org.apache.shale.test.base.AbstractJsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- // This method MUST BE OVERRIDEN in any subclasses - since Junit see for it in class for call
- expressionFactory = null;
- elContext = null;
- super.tearDown();
- vcpRenderKit = null;
-// Thread.currentThread().setContextClassLoader(threadContextClassLoader);
-// threadContextClassLoader = null;
- webClient = null;
- webConnection = null;
- writer = null;
- SkinFactory.reset();
- InternetResourceBuilder.setInstance(null);
+ while (resources.hasMoreElements()) {
+ parser.parse((URL) resources.nextElement());
+ }
- deleteRecursively(tmpRoot);
-
- }
+ externalContext = new MockExternalContext(externalContext);
+ facesContext.setExternalContext(externalContext);
+ elContext = facesContext.getELContext();
+ expressionFactory = application.getExpressionFactory();
+ }
- // Protected configurations URL's
- /**
- * Hook method for setup current VCP skin name for test. default use "classic"
- * @return
- */
- protected String getSkinName() {
- return "DEFAULT";
- }
+ protected WebClient createWebClient() {
+ WebClient client = new WebClient();
- /**
- * Hook method for load diffrernt frameworks for this test.
- * Can return URL's for jars with tested implementation.
- * @return
- */
- protected URL[] getImplementationUrls() {
- return new URL[0];
- }
+ // disable javascript for now as HtmlUnit doesn't treat prototype.js
+ // well
+ client.setJavaScriptEnabled(true);
- /**
- * Create component with given render kit and unique Id from ViewRoot.
- * @param type - component type.
- * @param clazz - class of component.
- * @param rendererType - name for renderer type ( can be null ).
- * @param rendererClazz - class of renderer in HTMP_BASIC renderkit. If not null, renderer will created and registered.
- * @param skinRendererClazz - class of renderer in Skin render-kit.
- * @return component instance.
- * @throws Exception
- */
- protected UIComponent createComponent(String type, String className, String rendererType, Class rendererClazz,Class skinRendererClazz) {
- UIComponent comp;
- try {
- comp = application.createComponent(type);
- } catch (FacesException e) {
- application.addComponent(type, className);
- comp = application.createComponent(type);
- }
- comp.setRendererType(rendererType);
- String family = comp.getFamily();
- if (null != rendererClazz) {
- Renderer renderer = renderKit.getRenderer(family, rendererType);
- if (null == renderer) {
- try {
- renderer = (Renderer) rendererClazz.newInstance();
- } catch (InstantiationException e) {
- assertTrue("Instantiation exception for create renderer "+rendererClazz.getName(),false);
- } catch (IllegalAccessException e) {
- assertTrue("ILEGAL access exception for create renderer "+rendererClazz.getName(),false);
- }
- renderKit.addRenderer(family, rendererType, renderer);
- }
- }
- if(null != skinRendererClazz) {
- Renderer renderer = renderKit.getRenderer(family, rendererType);
- if (null == renderer) {
- try {
- renderer = (Renderer) skinRendererClazz.newInstance();
- } catch (InstantiationException e) {
- assertTrue("Instantiation exception for create renderer "+skinRendererClazz.getName(),false);
- } catch (IllegalAccessException e) {
- assertTrue("ILEGAL access exception for create renderer "+skinRendererClazz.getName(),false);
- }
- vcpRenderKit.addRenderer(family, rendererType, renderer);
- }
- }
- comp.setId(facesContext.getViewRoot().createUniqueId());
- return comp;
- }
+ // Set dummy script engine to prevent NPEs from default HtmlUnit engine
+ client.setJavaScriptEngine(new DummyScriptEngine(client));
+ return client;
+ }
- /**
- * Render all children for given component.
- * @param component
- * @throws IOException
- */
- protected void renderChildren(FacesContext context,
- UIComponent component) throws IOException {
- if (component.getChildCount() > 0) {
- for (Iterator it = component.getChildren().iterator(); it.hasNext();) {
- UIComponent child = (UIComponent) it.next();
- renderChild(context,child);
- }
- }
- }
+ /**
+ * This function checks is resource present. If so, resource returned in the form of InputStream, otherwise IOException throwed.
+ *
+ * @param path - path to specified resource
+ *
+ * @return InputStream of the resource, if resource present
+ *
+ * @throws IOException - if resource not available
+ */
+ protected InputStream getResourceIfPresent(String path) throws IOException {
+ InternetResourceBuilder builder = ResourceBuilderImpl.getInstance();
+ InternetResource resource = builder.getResource(path);
+ if (resource != null) {
+ String uri = HTTP_PREFIX + resource.getUri(facesContext, null);
+ Page page = webClient.getPage(uri);
- /**
- * Render one component and it childrens
- * @param child
- * @throws IOException
- */
- protected void renderChild(FacesContext context, UIComponent child)
- throws IOException {
- if (!child.isRendered()) {
- return;
- }
+ if (page.getWebResponse().getStatusCode() == HttpServletResponse.SC_OK) {
+ return page.getWebResponse().getContentAsStream();
+ }
+ }
- child.encodeBegin(context);
- if (child.getRendersChildren()) {
- child.encodeChildren(context);
- } else {
- renderChildren(context, child);
- }
- child.encodeEnd(context);
- }
+ throw new IOException(RESOURCE_NOT_FOUND_MESSAGE + path);
+ }
- /**
- * Render test view and parse to htmlunit page structure.
- * @return
- * @throws Exception
- */
- protected HtmlPage renderView() throws Exception {
- setupResponseWriter();
-
- // Emulate A4J web filter chaining like in real web application.
- TestXMLFilter filter = new TestXMLFilter();
- try {
- filter.processFilter(new FilterChain() {
- public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
- response.setContentType("text/html");
- facesContext.setResponseWriter((MockResponseWriter) renderKit.createResponseWriter(response.getWriter(),"text/html",null));
-
- ViewResources viewResources = new ViewResources();
- viewResources.initialize(facesContext);
- //viewResources.setStyleStrategy(InternetResourceBuilder.LOAD_ALL);
- //viewResources.setScriptStrategy(InternetResourceBuilder.LOAD_ALL);
- viewResources.setUseStdControlsSkinning(false);
- viewResources.setUseStdControlsSkinningClasses(false);
-
- renderChild(facesContext, facesContext.getViewRoot());
-
- viewResources.processHeadResources(facesContext);
- Object[] headEvents = (Object[]) viewResources.getHeadEvents();
- request.setAttribute(AjaxContext.HEAD_EVENTS_PARAMETER, headEvents);
-
- facesContext.setResponseWriter(writer);
- }
- }, request, response);
- } catch (Exception e) {
- throw e;
- }
-
- return processResponseWriter();
- }
+ /**
+ * This function checks is image resource present. If so, image returned, otherwise IOException throwed.
+ *
+ * @param path - path to specified image resource
+ *
+ * @return ImageInfo of the image, if image resource present or null if method ImageInfo.check() return false;
+ *
+ * @throws IOException - if image not available or not exist
+ */
+ protected ImageInfo getImageResource(String path) throws IOException {
+ ImageInfo info = new ImageInfo();
- /**
- * Implements default XML filter to emulate A4J filter that invoked while
- * http request in web application.
- *
- * Needed to make sure that all processed (web page generation) like in real
- * web application. Additionally now all RF components styles and scripts generated
- * by A4J filter only, so we need the same in out unit tests.
- * Fast filter used now by default.
- * TODO: we can make it configurable like org.ajax4jsf.webapp.ConfigurableXMLFilter
- *
- * @author dmorozov
- */
- private class TestXMLFilter extends BaseXMLFilter {
- private HtmlParser parser = null;
- public TestXMLFilter() {}
+ try {
+ info.setInput(getResourceIfPresent(path));
+ } catch (IOException e) {
+ throw new IOException(IMAGE_NOT_FOUND_OR_UNAVAILABLE_MESSAGE + path);
+ }
- public void processFilter(FilterChain chain, HttpServletRequest request,
- final HttpServletResponse response) throws IOException,
- ServletException {
- super.doXmlFilter(chain, request, response);
- }
-
- @Override
- protected HtmlParser getParser(String mimetype, boolean isAjax, String viewId) {
- HtmlParser parser = this.parser;
- if (parser == null) {
- parser = new FastHtmlParser();
- }
- return parser;
- }
-
- /**
- * Peturn parser to pool
- * @param parser
- */
- @Override
- protected void reuseParser(HtmlParser parser) {
- this.parser = parser;
- }
- }
-
- /**
- * Finish response processing by call {@link javax.faces.context.ResponseWriter#endDocument()} and parse
- * result to htmlunit {@link HtmlPage}
- * @return
- * @throws IOException
- * @throws Exception
- */
- protected HtmlPage processResponseWriter() throws IOException, Exception {
- writer.endDocument();
- return (HtmlPage) processResponse();
- }
+ return info.check() ? info : null;
+ }
- /**
- * Setup Faces {@link javax.faces.context.ResponseWriter} and prepare rendering ( startDocument ).
- * after this method, any jsf rendering methods can be performed, and results can be checked by {@link #processResponseWriter()}
- * @throws IOException
- */
- protected void setupResponseWriter() throws IOException {
- writer = (MockResponseWriter) renderKit.createResponseWriter(response.getWriter(),"text/html",null);
- facesContext.setResponseWriter(writer);
- writer.startDocument();
- }
+ /**
+ * This function return count of <script> elements on page and validate - if this script contains in Set of predefined attribute for this component
+ *
+ * @param view - page to validate
+ * @param predefinedScripts - set of predefined scripts, should be presented on component
+ *
+ * @return count of valid <script> element
+ * @throws Exception if script not available on page
+ */
+ protected Integer getCountValidScripts(HtmlPage view, Set<String> predefinedScripts,
+ boolean isPageAvailabilityCheck)
+ throws Exception {
- /**
- * Parse collected content of mock response to Page instance, used for check rendered html.
- * @return
- * @throws Exception
- */
- protected Page processResponse() throws Exception {
- setupWebClient();
- URL page = new URL( HTTP_PREFIX+ facesContext.getExternalContext().getRequestContextPath() + facesContext.getViewRoot().getViewId());
- try {
- char[] content = ((MockPrintWriter) response.getWriter()).content();
- webConnection.setResponse(page,String.valueOf(content),response.getStatus(), "OK", response.getContentType(), Collections.EMPTY_LIST);
- } catch (IllegalStateException e) {
- byte[] content = ((MockServletOutputStream)response.getOutputStream()).content();
- webConnection.setResponse(page,content, response.getStatus(), "OK", response.getContentType(), Collections.EMPTY_LIST);
- }
- return webClient.getPage(page);
- }
+ /*
+ * List<HtmlScript> scripts = view.getDocumentHtmlElement()
+ * .getHtmlElementsByTagName(HTML.SCRIPT_ELEM);
+ * int foundCount = 0;
+ * for (Iterator<HtmlScript> it = scripts.iterator(); it.hasNext();) {
+ * HtmlScript item = it.next();
+ * String srcAttr = item.getSrcAttribute();
+ *
+ * if (StringUtils.isNotBlank(srcAttr)) {
+ * boolean found = false;
+ * for (Iterator<String> srcIt = predefinedScripts.iterator(); srcIt
+ * .hasNext();) {
+ * String src = (String) srcIt.next();
+ *
+ * found = srcAttr.contains(src);
+ * if (found) {
+ * foundCount++;
+ *
+ * String uri = "http:" + srcAttr;
+ * Page page = webClient.getPage(uri);
+ * if (!(page != null && page.getWebResponse()
+ * .getStatusCode() == HttpServletResponse.SC_OK)) {
+ * throw new Exception("Page is not available " + uri);
+ *
+ * }
+ * break;
+ * }
+ * }
+ * }
+ * }
+ * return foundCount;
+ */
+ int foundCount = 0;
+ List<String> scriptSources = HtmlTestUtils.extractScriptSources(view);
- protected AjaxContext ajaxContext = null;
+ for (String javascript : predefinedScripts) {
+ for (String script : scriptSources) {
+ if (script.indexOf(javascript) >= 0) {
+ foundCount++;
- /**
- * Initialised instance of VCP render kit.
- */
- protected ChameleonRenderKitImpl vcpRenderKit = null;
+ String uri = HTTP_PREFIX + script;
+ Page page = webClient.getPage(uri);
- /**
- * Instance of Mock {@link javax.faces.context.ResponseWriter} , created by setupResponseWriter
- */
- protected MockResponseWriter writer;
+ if (isPageAvailabilityCheck) {
+ if (!(page != null && page.getWebResponse().getStatusCode() == HttpServletResponse.SC_OK)) {
+ throw new Exception("Component script " + javascript + " is not found in the response");
+ }
+ }
- /**
- * <p>The htmlunit web client for this test case. </p>
- *
- */
- protected WebClient webClient = null;
+ break;
+ }
+ }
+ }
- /**
- * Mock web connection for accept stored content of JSF encoding. For testing JavaScript code, all URL's for scripts must be
- * rregistered by {@link MockWebConnection#setResponse(java.net.URL, byte[], int, java.lang.String, java.lang.String, java.util.List)} method
- * By default, for unregistered pages return 404 - not found.
- */
- protected MockWebConnection webConnection = null;
+ return foundCount;
+ }
+ /**
+ *
+ */
+ protected void setupWebClient() {
+ ajaxContext = null;
- // Thread context class loader saved and restored after each test
- private ClassLoader threadContextClassLoader = null;
+ // setup webClient for got response content.
+ webClient = createWebClient();
+ webConnection = new MockWebConnection(webClient) {
+ public WebResponse getResponse(WebRequestSettings settings) throws IOException {
+ String resourceKey = WebXml.getInstance(facesContext).getFacesResourceKey(
+ settings.getURL().getFile().substring(request.getContextPath().length()));
- protected WebXml webXml;
+ if (resourceKey != null) {
+ InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
+ InternetResource resource = resourceBuilder.getResourceForKey(resourceKey);
+ Object resourceData = resourceBuilder.getResourceDataForKey(resourceKey);
+ final MockFacesResourceContext resourceContext = new MockFacesResourceContext(facesContext);
+ resourceContext.setResourceData(resourceData);
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ response.setOutputStream(new MockServletOutputStream(baos));
+ resource.sendHeaders(resourceContext);
+ resource.send(resourceContext);
+
+ return new WebResponseImpl(new WebResponseData(new ByteArrayInputStream(baos.toByteArray()),
+ HttpServletResponse.SC_OK, "OK", resourceContext.getHeaders()), settings.getURL(),
+ settings.getSubmitMethod(), 0) {
+ public String getContentType() {
+ return resourceContext.getContentType();
+ }
+ };
+ } else {
+ return super.getResponse(settings);
+ }
+ }
+ };
+ webClient.setWebConnection(webConnection);
+ webConnection.setDefaultResponse("<html><body>not found</body></html>", 404, "NOT FOUND", "text/html");
+ webClient.setThrowExceptionOnFailingStatusCode(false);
+ webClient.setThrowExceptionOnScriptError(false);
+ }
+
+ private void deleteRecursively(File file) {
+ if (file != null) {
+ String[] list = file.list();
+
+ if (list != null) {
+ for (int i = 0; i < list.length; i++) {
+ String name = list[i];
+ File f = new File(file, name);
+
+ if (f.isDirectory()) {
+ deleteRecursively(f);
+ } else {
+ f.delete();
+ }
+ }
+ }
+
+ file.delete();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.apache.shale.test.base.AbstractJsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+
+ // This method MUST BE OVERRIDEN in any subclasses - since Junit see for it in class for call
+ expressionFactory = null;
+ elContext = null;
+ super.tearDown();
+ vcpRenderKit = null;
+
+// Thread.currentThread().setContextClassLoader(threadContextClassLoader);
+// threadContextClassLoader = null;
+ webClient = null;
+ webConnection = null;
+ writer = null;
+ SkinFactory.reset();
+ InternetResourceBuilder.setInstance(null);
+ deleteRecursively(tmpRoot);
+ }
+
+ // Protected configurations URL's
+
+ /**
+ * Hook method for setup current VCP skin name for test. default use "classic"
+ * @return
+ */
+ protected String getSkinName() {
+ return "DEFAULT";
+ }
+
+ /**
+ * Hook method for load diffrernt frameworks for this test.
+ * Can return URL's for jars with tested implementation.
+ * @return
+ */
+ protected URL[] getImplementationUrls() {
+ return new URL[0];
+ }
+
+ /**
+ * Create component with given render kit and unique Id from ViewRoot.
+ * @param type - component type.
+ * @param clazz - class of component.
+ * @param rendererType - name for renderer type ( can be null ).
+ * @param rendererClazz - class of renderer in HTMP_BASIC renderkit. If not null, renderer will created and registered.
+ * @param skinRendererClazz - class of renderer in Skin render-kit.
+ * @return component instance.
+ * @throws Exception
+ */
+ protected UIComponent createComponent(String type, String className, String rendererType, Class rendererClazz,
+ Class skinRendererClazz) {
+ UIComponent comp;
+
+ try {
+ comp = application.createComponent(type);
+ } catch (FacesException e) {
+ application.addComponent(type, className);
+ comp = application.createComponent(type);
+ }
+
+ comp.setRendererType(rendererType);
+
+ String family = comp.getFamily();
+
+ if (null != rendererClazz) {
+ Renderer renderer = renderKit.getRenderer(family, rendererType);
+
+ if (null == renderer) {
+ try {
+ renderer = (Renderer) rendererClazz.newInstance();
+ } catch (InstantiationException e) {
+ assertTrue("Instantiation exception for create renderer " + rendererClazz.getName(), false);
+ } catch (IllegalAccessException e) {
+ assertTrue("ILEGAL access exception for create renderer " + rendererClazz.getName(), false);
+ }
+
+ renderKit.addRenderer(family, rendererType, renderer);
+ }
+ }
+
+ if (null != skinRendererClazz) {
+ Renderer renderer = renderKit.getRenderer(family, rendererType);
+
+ if (null == renderer) {
+ try {
+ renderer = (Renderer) skinRendererClazz.newInstance();
+ } catch (InstantiationException e) {
+ assertTrue("Instantiation exception for create renderer " + skinRendererClazz.getName(), false);
+ } catch (IllegalAccessException e) {
+ assertTrue("ILEGAL access exception for create renderer " + skinRendererClazz.getName(), false);
+ }
+
+ vcpRenderKit.addRenderer(family, rendererType, renderer);
+ }
+ }
+
+ comp.setId(facesContext.getViewRoot().createUniqueId());
+
+ return comp;
+ }
+
+ /**
+ * Render all children for given component.
+ * @param component
+ * @throws IOException
+ */
+ protected void renderChildren(FacesContext context, UIComponent component) throws IOException {
+ if (component.getChildCount() > 0) {
+ for (Iterator it = component.getChildren().iterator(); it.hasNext(); ) {
+ UIComponent child = (UIComponent) it.next();
+
+ renderChild(context, child);
+ }
+ }
+ }
+
+ /**
+ * Render one component and it childrens
+ * @param child
+ * @throws IOException
+ */
+ protected void renderChild(FacesContext context, UIComponent child) throws IOException {
+ if (!child.isRendered()) {
+ return;
+ }
+
+ child.encodeBegin(context);
+
+ if (child.getRendersChildren()) {
+ child.encodeChildren(context);
+ } else {
+ renderChildren(context, child);
+ }
+
+ child.encodeEnd(context);
+ }
+
+ /**
+ * Render test view and parse to htmlunit page structure.
+ * @return
+ * @throws Exception
+ */
+ protected HtmlPage renderView() throws Exception {
+ setupResponseWriter();
+
+ // Emulate A4J web filter chaining like in real web application.
+ TestXMLFilter filter = new TestXMLFilter();
+
+ try {
+ filter.processFilter(new FilterChain() {
+ public void doFilter(ServletRequest request, ServletResponse response)
+ throws IOException, ServletException {
+ response.setContentType("text/html");
+ facesContext.setResponseWriter(
+ (MockResponseWriter) renderKit.createResponseWriter(response.getWriter(), "text/html", null));
+
+ ViewResources viewResources = new ViewResources();
+
+ viewResources.initialize(facesContext);
+
+ // viewResources.setStyleStrategy(InternetResourceBuilder.LOAD_ALL);
+ // viewResources.setScriptStrategy(InternetResourceBuilder.LOAD_ALL);
+ viewResources.setUseStdControlsSkinning(false);
+ viewResources.setUseStdControlsSkinningClasses(false);
+ renderChild(facesContext, facesContext.getViewRoot());
+ viewResources.processHeadResources(facesContext);
+
+ Object[] headEvents = (Object[]) viewResources.getHeadEvents();
+
+ request.setAttribute(AjaxContext.HEAD_EVENTS_PARAMETER, headEvents);
+ facesContext.setResponseWriter(writer);
+ }
+ }, request, response);
+ } catch (Exception e) {
+ throw e;
+ }
+
+ return processResponseWriter();
+ }
+
+ /**
+ * Finish response processing by call {@link javax.faces.context.ResponseWriter#endDocument()} and parse
+ * result to htmlunit {@link HtmlPage}
+ * @return
+ * @throws IOException
+ * @throws Exception
+ */
+ protected HtmlPage processResponseWriter() throws IOException, Exception {
+ writer.endDocument();
+
+ return (HtmlPage) processResponse();
+ }
+
+ /**
+ * Setup Faces {@link javax.faces.context.ResponseWriter} and prepare rendering ( startDocument ).
+ * after this method, any jsf rendering methods can be performed, and results can be checked by {@link #processResponseWriter()}
+ * @throws IOException
+ */
+ protected void setupResponseWriter() throws IOException {
+ writer = (MockResponseWriter) renderKit.createResponseWriter(response.getWriter(), "text/html", null);
+ facesContext.setResponseWriter(writer);
+ writer.startDocument();
+ }
+
+ /**
+ * Parse collected content of mock response to Page instance, used for check rendered html.
+ * @return
+ * @throws Exception
+ */
+ protected Page processResponse() throws Exception {
+ setupWebClient();
+
+ URL page = new URL(HTTP_PREFIX + facesContext.getExternalContext().getRequestContextPath()
+ + facesContext.getViewRoot().getViewId());
+
+ try {
+ char[] content = ((MockPrintWriter) response.getWriter()).content();
+
+ webConnection.setResponse(page, String.valueOf(content), response.getStatus(), "OK",
+ response.getContentType(), Collections.EMPTY_LIST);
+ } catch (IllegalStateException e) {
+ byte[] content = ((MockServletOutputStream) response.getOutputStream()).content();
+
+ webConnection.setResponse(page, content, response.getStatus(), "OK", response.getContentType(),
+ Collections.EMPTY_LIST);
+ }
+
+ return webClient.getPage(page);
+ }
+
+ /**
+ * Implements default XML filter to emulate A4J filter that invoked while
+ * http request in web application.
+ *
+ * Needed to make sure that all processed (web page generation) like in real
+ * web application. Additionally now all RF components styles and scripts generated
+ * by A4J filter only, so we need the same in out unit tests.
+ * Fast filter used now by default.
+ * TODO: we can make it configurable like org.ajax4jsf.webapp.ConfigurableXMLFilter
+ *
+ * @author dmorozov
+ */
+ private class TestXMLFilter extends BaseXMLFilter {
+ private HtmlParser parser = null;
+
+ public TestXMLFilter() {}
+
+ public void processFilter(FilterChain chain, HttpServletRequest request, final HttpServletResponse response)
+ throws IOException, ServletException {
+ super.doXmlFilter(chain, request, response);
+ }
+
+ @Override
+ protected HtmlParser getParser(String mimetype, boolean isAjax, String viewId) {
+ HtmlParser parser = this.parser;
+
+ if (parser == null) {
+ parser = new FastHtmlParser();
+ }
+
+ return parser;
+ }
+
+ /**
+ * Peturn parser to pool
+ * @param parser
+ */
+ @Override
+ protected void reuseParser(HtmlParser parser) {
+ this.parser = parser;
+ }
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractJspTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractJspTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractJspTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,17 +1,21 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
import java.io.IOException;
+
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.el.ELContext;
+
import javax.faces.component.UIOutput;
import javax.faces.webapp.UIComponentELTag;
+
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.PageContext;
@@ -21,117 +25,112 @@
*
*/
public abstract class AbstractJspTestCase extends AbstractAjax4JsfTestCase {
+ protected PageContext pageContext = null;
+ protected UIComponentELTag rootTag;
- protected PageContext pageContext = null;
-
- protected UIComponentELTag rootTag;
- /**
- * @param name
- */
- public AbstractJspTestCase(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public AbstractJspTestCase(String name) {
+ super(name);
+ }
- @Override
- public void setUp() throws Exception {
- super.setUp();
- pageContext = new MockPageContext() {
-
- private final int[] SCOPE_ORDER = {PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, APPLICATION_SCOPE};
-
- private Map<String, Object> attributes =
- new HashMap<String, Object>();
-
- @Override
- public ELContext getELContext() {
- return elContext;
- }
-
- @Override
- public Object findAttribute(String name) {
- Object value = null;
- for(int i = 0; i < SCOPE_ORDER.length && value == null; i++) {
- value = getScope(SCOPE_ORDER[i]).get(name);
- }
- return value;
- }
-
- @Override
- public int getAttributesScope(String name) {
- Object value = null;
- int i = 0;
- for(; i < SCOPE_ORDER.length && value == null; i++) {
- value = getScope(SCOPE_ORDER[i]).get(name);
- }
- return value == null ? 0 :SCOPE_ORDER[i];
- }
-
-
- @Override
- public Enumeration<String> getAttributeNamesInScope(int scope) {
- Map<String, Object> scopeMap = getScope(scope);
- final Iterator<String> iterator = scopeMap.keySet().iterator();
- return new Enumeration<String>() {
- public boolean hasMoreElements() {
- return iterator.hasNext();
- }
- public String nextElement() {
- // TODO Auto-generated method stub
- return iterator.next();
- }
- };
- }
-
- @Override
- public ServletRequest getRequest() {
- return request;
- }
- @Override
- public Object getAttribute(String name) {
- return getScope(PAGE_SCOPE).get(name);
- }
-
- @Override
- public Object getAttribute(String name, int scope) {
- return getScope(scope).get(name);
- }
-
- @SuppressWarnings("unchecked")
- private Map<String, Object> getScope(int scopeName) {
- switch(scopeName) {
- case APPLICATION_SCOPE: return externalContext.getApplicationMap();
- case SESSION_SCOPE: return externalContext.getSessionMap();
- case REQUEST_SCOPE: return externalContext.getRequestMap();
- default: return attributes;
- }
- }
- };
-
-
- rootTag = new UIComponentELTag() {
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ pageContext = new MockPageContext() {
+ private final int[] SCOPE_ORDER = {PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, APPLICATION_SCOPE};
+ private Map<String, Object> attributes = new HashMap<String, Object>();
+ @Override
+ public ELContext getELContext() {
+ return elContext;
+ }
+ @Override
+ public Object findAttribute(String name) {
+ Object value = null;
- @Override
- public String getComponentType() {
- // TODO Auto-generated method stub
- return UIOutput.COMPONENT_TYPE;
- }
+ for (int i = 0; i < SCOPE_ORDER.length && value == null; i++) {
+ value = getScope(SCOPE_ORDER[i]).get(name);
+ }
- @Override
- public String getRendererType() {
- return null;
- }
-
- };
-
- rootTag.setPageContext(pageContext);
- rootTag.doStartTag();
- }
-
-
- @Override
- public void tearDown() throws Exception {
- pageContext = null;
- rootTag = null;
- super.tearDown();
- }
+ return value;
+ }
+ @Override
+ public int getAttributesScope(String name) {
+ Object value = null;
+ int i = 0;
+
+ for (; i < SCOPE_ORDER.length && value == null; i++) {
+ value = getScope(SCOPE_ORDER[i]).get(name);
+ }
+
+ return value == null ? 0 : SCOPE_ORDER[i];
+ }
+ @Override
+ public Enumeration<String> getAttributeNamesInScope(int scope) {
+ Map<String, Object> scopeMap = getScope(scope);
+ final Iterator<String> iterator = scopeMap.keySet().iterator();
+
+ return new Enumeration<String>() {
+ public boolean hasMoreElements() {
+ return iterator.hasNext();
+ }
+ public String nextElement() {
+
+ // TODO Auto-generated method stub
+ return iterator.next();
+ }
+ };
+ }
+ @Override
+ public ServletRequest getRequest() {
+ return request;
+ }
+ @Override
+ public Object getAttribute(String name) {
+ return getScope(PAGE_SCOPE).get(name);
+ }
+ @Override
+ public Object getAttribute(String name, int scope) {
+ return getScope(scope).get(name);
+ }
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> getScope(int scopeName) {
+ switch (scopeName) {
+ case APPLICATION_SCOPE :
+ return externalContext.getApplicationMap();
+
+ case SESSION_SCOPE :
+ return externalContext.getSessionMap();
+
+ case REQUEST_SCOPE :
+ return externalContext.getRequestMap();
+
+ default :
+ return attributes;
+ }
+ }
+ };
+ rootTag = new UIComponentELTag() {
+ @Override
+ public String getComponentType() {
+
+ // TODO Auto-generated method stub
+ return UIOutput.COMPONENT_TYPE;
+ }
+ @Override
+ public String getRendererType() {
+ return null;
+ }
+ };
+ rootTag.setPageContext(pageContext);
+ rootTag.doStartTag();
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ pageContext = null;
+ rootTag = null;
+ super.tearDown();
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractThreadedAjax4JsfTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractThreadedAjax4JsfTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/AbstractThreadedAjax4JsfTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import javax.faces.context.FacesContext;
@@ -28,6 +30,7 @@
import org.ajax4jsf.context.AjaxContext;
import org.ajax4jsf.context.AjaxContextImpl;
+
import org.apache.shale.test.mock.MockFacesContext;
import org.apache.shale.test.mock.MockHttpServletRequest;
import org.apache.shale.test.mock.MockHttpServletResponse;
@@ -37,8 +40,8 @@
* @author asmirnov(a)exadel.com (latest modification by $Author: ishabalov $)
* @version $Revision: 1.1.2.3 $ $Date: 2007/02/20 20:58:08 $
*
-/**
- * A multi-threaded JUnit test case, with setup faces environment.
+ *
+ * A multi-threaded JUnit test case, with setup faces environment.
* To perform test cases that spin off threads to do tests: <p>
* <UL>
* <LI>Extend <code>MultiThreadedTestCase</code>
@@ -76,53 +79,56 @@
* public void test1 ()
* {
* TestCaseRunnable tct [] = new TestCaseRunnable [5];
- * for (int i = 0; i < 5; i++)
+ * for (int i = 0; i < 5; i++)
* {
* tct[i] = new CounterThread ();
* }
* runTestCaseRunnables (tct);
* }
* }
- * </PRE>
+ * </PRE>
* <BR><STRONG>Category: Test</STRONG>
* <BR><STRONG>Not guaranteed to be thread safe.</STRONG>
-*/
+ */
public class AbstractThreadedAjax4JsfTestCase extends AbstractAjax4JsfTestCase {
- /**
+ /**
+ * The tests TestResult.
+ */
+ private TestResult testResult = null;
+
+ /**
* The threads that are executing.
*/
private Thread threads[] = null;
+
/**
- * The tests TestResult.*/
- private TestResult testResult = null;
- /**
- * Simple constructor.
+ * Simple constructor.
*/
-
public AbstractThreadedAjax4JsfTestCase(String s) {
super(s);
}
+
/**
* Interrupt the running threads.
*/
-
public void interruptThreads() {
- if(threads != null) {
- for(int i = 0;i < threads.length;i++) {
+ if (threads != null) {
+ for (int i = 0; i < threads.length; i++) {
threads[i].interrupt();
}
}
}
+
/**
- * Override run so we can squirrel away the test result.*/
-
+ * Override run so we can squirrel away the test result.
+ */
public void run(final TestResult result) {
testResult = result;
super.run(result);
testResult = null;
}
-
+
/**
* Create instances of classes and run threads with it.
* @param clazz - class of test thread implementation.
@@ -130,106 +136,118 @@
* @throws InstantiationException
* @throws IllegalAccessException
*/
- protected void runTestCaseThreads(Class clazz, int numThreads) {
- TestCaseRunnable[] runnables = new TestCaseRunnable[numThreads];
- for (int i = 0; i < runnables.length; i++) {
- try {
- runnables[i]= (TestCaseRunnable) clazz.newInstance();
- } catch (Exception e) {
- testResult.addError(this, e);
- return;
- }
- }
- runTestCaseRunnables(runnables);
+ protected void runTestCaseThreads(Class clazz, int numThreads) {
+ TestCaseRunnable[] runnables = new TestCaseRunnable[numThreads];
+
+ for (int i = 0; i < runnables.length; i++) {
+ try {
+ runnables[i] = (TestCaseRunnable) clazz.newInstance();
+ } catch (Exception e) {
+ testResult.addError(this, e);
+
+ return;
+ }
+ }
+
+ runTestCaseRunnables(runnables);
}
+
/**
* Run the test case threads.
* @param runnables - array with instances of {@link TestCaseRunnable} with concrete tests
*/
- protected void runTestCaseRunnables (final TestCaseRunnable[] runnables) {
- if(runnables == null) {
+ protected void runTestCaseRunnables(final TestCaseRunnable[] runnables) {
+ if (runnables == null) {
throw new IllegalArgumentException("runnables is null");
}
+
threads = new Thread[runnables.length];
- for(int i = 0;i < threads.length;i++) {
+
+ for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(runnables[i]);
}
- for(int i = 0;i < threads.length;i++) {
+
+ for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
+
try {
- for(int i = 0;i < threads.length;i++) {
+ for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
- }
- catch(InterruptedException ignore) {
+ } catch (InterruptedException ignore) {
System.out.println("Thread join interrupted.");
}
+
threads = null;
}
+
/**
* Handle an exception. Since multiple threads won't have their
* exceptions caught the threads must manually catch them and call
* <code>handleException ()</code>.
- * @param t Exception to handle.*/
-
+ * @param t Exception to handle.
+ */
private void handleException(final Throwable t) {
- synchronized(testResult) {
- if(t instanceof AssertionFailedError) {
- testResult.addFailure(this, (AssertionFailedError)t);
- }
- else {
+ synchronized (testResult) {
+ if (t instanceof AssertionFailedError) {
+ testResult.addFailure(this, (AssertionFailedError) t);
+ } else {
testResult.addError(this, t);
}
}
}
-
+
/**
+ * Create instance of faces context for current thread.
+ * @return
+ */
+ protected FacesContext createFacesContext() {
+ MockHttpSession tsession = new MockHttpSession();
+ MockHttpServletRequest trequest = new MockHttpServletRequest(tsession);
+
+ trequest.setAttribute(AjaxContext.AJAX_CONTEXT_KEY, new AjaxContextImpl());
+
+ MockHttpServletResponse tresponse = new MockHttpServletResponse();
+ MockFacesContext tfacesContext = (MockFacesContext) facesContextFactory.getFacesContext(servletContext,
+ trequest, tresponse, lifecycle);
+
+ tfacesContext.setApplication(application);
+ tfacesContext.setViewRoot(application.getViewHandler().createView(facesContext,
+ facesContext.getViewRoot().getViewId()));
+
+ return tfacesContext;
+ }
+
+ /**
* A test case thread. Override runTestCase () and define
- * behaviour of test in there.*/
+ * behaviour of test in there.
+ */
public abstract class TestCaseRunnable implements Runnable {
+
/**
- * Override this to define the test*/
-
- public abstract void runTestCase(FacesContext context)
- throws Throwable;
+ * Override this to define the test
+ */
+ public abstract void runTestCase(FacesContext context) throws Throwable;
+
/**
* Run the test in an environment where
- * we can handle the exceptions generated by the test method.*/
-
+ * we can handle the exceptions generated by the test method.
+ */
public void run() {
- FacesContext context = null;
+ FacesContext context = null;
+
try {
- context = createFacesContext();
+ context = createFacesContext();
runTestCase(context);
- }
- catch(Throwable t) /* Any other exception we handle and then we interrupt the other threads.*/ {
+ } catch (Throwable t) /* Any other exception we handle and then we interrupt the other threads. */ {
handleException(t);
interruptThreads();
} finally {
- if(null != context) {
- context.release();
- }
+ if (null != context) {
+ context.release();
+ }
}
}
}
-
- /**
- * Create instance of faces context for current thread.
- * @return
- */
- protected FacesContext createFacesContext() {
- MockHttpSession tsession = new MockHttpSession();
- MockHttpServletRequest trequest = new MockHttpServletRequest(tsession);
- trequest.setAttribute(AjaxContext.AJAX_CONTEXT_KEY, new AjaxContextImpl());
- MockHttpServletResponse tresponse = new MockHttpServletResponse();
- MockFacesContext tfacesContext = (MockFacesContext)
- facesContextFactory.getFacesContext(servletContext,
- trequest,
- tresponse,
- lifecycle);
- tfacesContext.setApplication(application);
- tfacesContext.setViewRoot(application.getViewHandler().createView(facesContext, facesContext.getViewRoot().getViewId()));
- return tfacesContext;
- }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/Condition.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/Condition.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/Condition.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -8,38 +9,35 @@
*
*/
public class Condition {
- private boolean conditionTrue;
+ private boolean conditionTrue;
+ private String message;
- private String message;
-
- public Condition(String message) {
- super();
- this.message = message;
- }
+ public Condition(String message) {
+ super();
+ this.message = message;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public boolean isConditionTrue() {
- return conditionTrue;
- }
+ public boolean isConditionTrue() {
+ return conditionTrue;
+ }
- public void setTrue() {
- setCondition(true);
- }
-
- public void setFalse(){
- setCondition(false);
- }
- public void setCondition(boolean conditionTrue) {
- this.conditionTrue = conditionTrue;
- }
+ public void setTrue() {
+ setCondition(true);
+ }
-
-
+ public void setFalse() {
+ setCondition(false);
+ }
+
+ public void setCondition(boolean conditionTrue) {
+ this.conditionTrue = conditionTrue;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/ConstantlyFailingLiteralValueExpression.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/ConstantlyFailingLiteralValueExpression.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/ConstantlyFailingLiteralValueExpression.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -8,7 +9,7 @@
import javax.el.ValueExpression;
/**
- * Value expression failing when trying
+ * Value expression failing when trying
* to coerce its expression string to any type
* Needed to test tags throw FacesException in that case
* @author Maksim Kaszynski
@@ -17,76 +18,84 @@
@SuppressWarnings("serial")
public class ConstantlyFailingLiteralValueExpression extends ValueExpression {
- /* (non-Javadoc)
- * @see javax.el.ValueExpression#getExpectedType()
- */
- @Override
- public Class<?> getExpectedType() {
- throw new ELException("Everything is a stub here");
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ValueExpression#getExpectedType()
+ */
+ @Override
+ public Class<?> getExpectedType() {
+ throw new ELException("Everything is a stub here");
+ }
- /* (non-Javadoc)
- * @see javax.el.ValueExpression#getType(javax.el.ELContext)
- */
- @Override
- public Class<?> getType(ELContext context) {
- throw new ELException("Everything is a stub here");
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ValueExpression#getType(javax.el.ELContext)
+ */
+ @Override
+ public Class<?> getType(ELContext context) {
+ throw new ELException("Everything is a stub here");
+ }
- /* (non-Javadoc)
- * @see javax.el.ValueExpression#getValue(javax.el.ELContext)
- */
- @Override
- public Object getValue(ELContext context) {
- throw new ELException("Everything is a stub here");
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ValueExpression#getValue(javax.el.ELContext)
+ */
+ @Override
+ public Object getValue(ELContext context) {
+ throw new ELException("Everything is a stub here");
+ }
- /* (non-Javadoc)
- * @see javax.el.ValueExpression#isReadOnly(javax.el.ELContext)
- */
- @Override
- public boolean isReadOnly(ELContext context) {
- throw new ELException("Everything is a stub here");
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ValueExpression#isReadOnly(javax.el.ELContext)
+ */
+ @Override
+ public boolean isReadOnly(ELContext context) {
+ throw new ELException("Everything is a stub here");
+ }
- /* (non-Javadoc)
- * @see javax.el.ValueExpression#setValue(javax.el.ELContext, java.lang.Object)
- */
- @Override
- public void setValue(ELContext context, Object value) {
- throw new ELException("Everything is a stub here");
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ValueExpression#setValue(javax.el.ELContext, java.lang.Object)
+ */
+ @Override
+ public void setValue(ELContext context, Object value) {
+ throw new ELException("Everything is a stub here");
+ }
- /* (non-Javadoc)
- * @see javax.el.Expression#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- throw new ELException("Everything is a stub here");
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.Expression#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ throw new ELException("Everything is a stub here");
+ }
- /* (non-Javadoc)
- * @see javax.el.Expression#getExpressionString()
- */
- @Override
- public String getExpressionString() {
- throw new ELException("Everything is a stub here");
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.Expression#getExpressionString()
+ */
+ @Override
+ public String getExpressionString() {
+ throw new ELException("Everything is a stub here");
+ }
- /* (non-Javadoc)
- * @see javax.el.Expression#hashCode()
- */
- @Override
- public int hashCode() {
- throw new ELException("Everything is a stub here");
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.Expression#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ throw new ELException("Everything is a stub here");
+ }
- /* (non-Javadoc)
- * @see javax.el.Expression#isLiteralText()
- */
- @Override
- public boolean isLiteralText() {
- return true;
- }
-
+ /*
+ * (non-Javadoc)
+ * @see javax.el.Expression#isLiteralText()
+ */
+ @Override
+ public boolean isLiteralText() {
+ return true;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/DummyScriptEngine.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/DummyScriptEngine.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/DummyScriptEngine.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,9 +1,11 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
import org.apache.commons.logging.Log;
+
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Script;
@@ -24,56 +26,47 @@
*/
@SuppressWarnings("serial")
public class DummyScriptEngine extends JavaScriptEngine {
+ public DummyScriptEngine(WebClient webClient) {
+ super(webClient);
+ }
- public DummyScriptEngine(WebClient webClient) {
- super(webClient);
- }
+ @Override
+ public Object callFunction(HtmlPage htmlPage, Function function, Context context, Scriptable scope,
+ Scriptable thisObject, Object[] args) {
+ return false;
+ }
- @Override
- public Object callFunction(HtmlPage htmlPage, Function function,
- Context context, Scriptable scope, Scriptable thisObject,
- Object[] args) {
- return false;
- }
+ @Override
+ public Script compile(HtmlPage htmlPage, String sourceCode, String sourceName, int startLine) {
+ return new Script() {
+ public Object exec(Context arg0, Scriptable arg1) {
+ return false;
+ }
+ };
+ }
- @Override
- public Script compile(HtmlPage htmlPage, String sourceCode,
- String sourceName, int startLine) {
- return new Script() {
- public Object exec(Context arg0, Scriptable arg1) {
- return false;
- }
- };
- }
+ @Override
+ public Script getCachedScript(WebResponse webResponse) {
+ return null;
+ }
-
- @Override
- public Script getCachedScript(WebResponse webResponse) {
- return null;
- }
+ @Override
+ protected Log getLog() {
+ return null;
+ }
- @Override
- protected Log getLog() {
- return null;
- }
+ @Override
+ public void initialize(WebWindow webWindow) {
+ super.initialize(webWindow);
+ }
- @Override
- public void initialize(WebWindow webWindow) {
- super.initialize(webWindow);
- }
+ @Override
+ public boolean isScriptRunning() {
+ return false;
+ }
- @Override
- public boolean isScriptRunning() {
- return false;
- }
-
- @Override
- public String preProcess(HtmlPage htmlPage, String sourceCode,
- String sourceName, HtmlElement htmlElement) {
- return "";
- }
-
-
-
-
+ @Override
+ public String preProcess(HtmlPage htmlPage, String sourceCode, String sourceName, HtmlElement htmlElement) {
+ return "";
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/EnumSupportExpressionFactoryWrapper.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/EnumSupportExpressionFactoryWrapper.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/EnumSupportExpressionFactoryWrapper.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -13,69 +14,70 @@
*
*/
public class EnumSupportExpressionFactoryWrapper extends ExpressionFactory {
+ private ExpressionFactory factory;
- private ExpressionFactory factory;
- /**
- *
- */
- public EnumSupportExpressionFactoryWrapper(ExpressionFactory factory) {
- this.factory = factory;
- }
+ /**
+ *
+ */
+ public EnumSupportExpressionFactoryWrapper(ExpressionFactory factory) {
+ this.factory = factory;
+ }
- /* (non-Javadoc)
- * @see javax.el.ExpressionFactory#coerceToType(java.lang.Object, java.lang.Class)
- */
- @Override
- public Object coerceToType(Object obj, Class<?> targetType) {
- if (targetType != null && targetType.isEnum()) {
- return coerceToEnum(obj, (Class<?>) targetType);
- }
- return factory.coerceToType(obj, targetType);
- }
-
- @SuppressWarnings("unchecked")
- private Enum<?> coerceToEnum(Object o, Class clazz) {
- if (o == null || "".equals(o)) {
- return null;
- }
-
- if (clazz.isInstance(o)) {
- return (Enum<?>) o;
- }
-
- if (o instanceof String) {
- return Enum.valueOf(clazz, (String) o);
- }
-
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ExpressionFactory#coerceToType(java.lang.Object, java.lang.Class)
+ */
+ @Override
+ public Object coerceToType(Object obj, Class<?> targetType) {
+ if (targetType != null && targetType.isEnum()) {
+ return coerceToEnum(obj, (Class<?>) targetType);
+ }
+
+ return factory.coerceToType(obj, targetType);
+ }
+
+ @SuppressWarnings("unchecked")
+ private Enum<?> coerceToEnum(Object o, Class clazz) {
+ if (o == null || "".equals(o)) {
+ return null;
+ }
+
+ if (clazz.isInstance(o)) {
+ return (Enum<?>) o;
+ }
+
+ if (o instanceof String) {
+ return Enum.valueOf(clazz, (String) o);
+ }
+
throw new IllegalArgumentException("Cannot convert " + o + " of class " + o.getClass() + " to type " + clazz);
- }
+ }
- /* (non-Javadoc)
- * @see javax.el.ExpressionFactory#createMethodExpression(javax.el.ELContext, java.lang.String, java.lang.Class, java.lang.Class<?>[])
- */
- @Override
- public MethodExpression createMethodExpression(ELContext context,
- String expression, Class<?> expectedReturnType,
- Class<?>[] expectedParamTypes) {
- return factory.createMethodExpression(context, expression, expectedReturnType, expectedParamTypes);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ExpressionFactory#createMethodExpression(javax.el.ELContext, java.lang.String, java.lang.Class, java.lang.Class<?>[])
+ */
+ @Override
+ public MethodExpression createMethodExpression(ELContext context, String expression, Class<?> expectedReturnType,
+ Class<?>[] expectedParamTypes) {
+ return factory.createMethodExpression(context, expression, expectedReturnType, expectedParamTypes);
+ }
- /* (non-Javadoc)
- * @see javax.el.ExpressionFactory#createValueExpression(java.lang.Object, java.lang.Class)
- */
- @Override
- public ValueExpression createValueExpression(Object instance,
- Class<?> expectedType) {
- return factory.createValueExpression(instance, expectedType);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ExpressionFactory#createValueExpression(java.lang.Object, java.lang.Class)
+ */
+ @Override
+ public ValueExpression createValueExpression(Object instance, Class<?> expectedType) {
+ return factory.createValueExpression(instance, expectedType);
+ }
- /* (non-Javadoc)
- * @see javax.el.ExpressionFactory#createValueExpression(javax.el.ELContext, java.lang.String, java.lang.Class)
- */
- @Override
- public ValueExpression createValueExpression(ELContext context,
- String expression, Class<?> expectedType) {
- return factory.createValueExpression(context, expression, expectedType);
- }
-
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ExpressionFactory#createValueExpression(javax.el.ELContext, java.lang.String, java.lang.Class)
+ */
+ @Override
+ public ValueExpression createValueExpression(ELContext context, String expression, Class<?> expectedType) {
+ return factory.createValueExpression(context, expression, expectedType);
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/HtmlTestUtils.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/HtmlTestUtils.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/HtmlTestUtils.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -7,6 +8,7 @@
import java.util.List;
import org.ajax4jsf.renderkit.RendererUtils.HTML;
+
import org.apache.commons.lang.StringUtils;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
@@ -17,27 +19,26 @@
*
*/
public final class HtmlTestUtils {
- private HtmlTestUtils() {
- }
-
- /**
- * Extract list of all <script> elements' src attributes
- * @param page
- * @return
- */
+ private HtmlTestUtils() {}
+
+ /**
+ * Extract list of all <script> elements' src attributes
+ * @param page
+ * @return
+ */
@SuppressWarnings("unchecked")
public static List<String> extractScriptSources(HtmlPage page) {
- List<HtmlScript> list =
- page.getDocumentHtmlElement().getHtmlElementsByTagName(HTML.SCRIPT_ELEM);
- List<String> sources = new ArrayList<String>();
- for (HtmlScript htmlScript : list) {
- String srcAttribute = htmlScript.getSrcAttribute();
- if (StringUtils.isNotBlank(srcAttribute)) {
- sources.add(srcAttribute);
- }
- }
- return sources;
- }
+ List<HtmlScript> list = page.getDocumentHtmlElement().getHtmlElementsByTagName(HTML.SCRIPT_ELEM);
+ List<String> sources = new ArrayList<String>();
+ for (HtmlScript htmlScript : list) {
+ String srcAttribute = htmlScript.getSrcAttribute();
+ if (StringUtils.isNotBlank(srcAttribute)) {
+ sources.add(srcAttribute);
+ }
+ }
+
+ return sources;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/JsfMock.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/JsfMock.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/JsfMock.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,11 +1,13 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
import javax.el.Expression;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
+
import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
@@ -27,146 +29,168 @@
*/
@SuppressWarnings("deprecation")
public class JsfMock {
-
- public static <T extends Expression> T expressionStringEq(T t) {
- EasyMock.reportMatcher(new ExpressionEq(t){});
- return null;
- }
-
-
- public static ValueBinding vbEqToVe(ValueExpression expression) {
- EasyMock.reportMatcher(new ExpressionEq(expression){});
- return null;
- }
+ public static <T extends Expression> T expressionStringEq(T t) {
+ EasyMock.reportMatcher(new ExpressionEq(t) {}
+ );
- public static MethodBinding mbEqToMe(MethodExpression expression) {
- EasyMock.reportMatcher(new ExpressionEq(expression){});
- return null;
- }
-
- public static MethodExpression meEqToMe(MethodExpression expression) {
- EasyMock.reportMatcher(new ExpressionEq(expression){});
- return null;
- }
-
- public static Validator meValidator(MockMethodExpression expression) {
- EasyMock.reportMatcher(new MethodValidatorMatcher(expression));
- return null;
- }
-
- public static ActionListener meActionListener(MockMethodExpression expression) {
- EasyMock.reportMatcher(new MethodActionListenerMatcher(expression));
- return null;
- }
+ return null;
+ }
- public static ValueChangeListener meValueChangeListener(MockMethodExpression expression) {
- EasyMock.reportMatcher(new MethodValueChangeListenerMatcher(expression));
- return null;
- }
+ public static ValueBinding vbEqToVe(ValueExpression expression) {
+ EasyMock.reportMatcher(new ExpressionEq(expression) {}
+ );
-// public static ValueExpression expressionStringEq(ValueExpression expression) {
-// EasyMock.reportMatcher(new ExpressionEq(expression) {});
-// return null;
-// }
-
- public abstract static class ExpressionEq implements IArgumentMatcher{
- private Expression expression;
+ return null;
+ }
- public ExpressionEq(Expression expression) {
- super();
- this.expression = expression;
- }
-
- public void appendTo(StringBuffer buffer) {
- buffer.append("Expression expected to have expression string ")
- .append(expression.getExpressionString());
- }
- public boolean matches(Object argument) {
- if (argument instanceof Expression) {
- Expression e2 = (Expression) argument;
- return e2.getExpressionString().equals(expression.getExpressionString());
- } else if (argument instanceof ValueBinding) {
- ValueBinding binding = (ValueBinding) argument;
- return binding.getExpressionString().equals(expression.getExpressionString());
- } else if (argument instanceof MethodBinding) {
- MethodBinding binding = (MethodBinding) argument;
- return binding.getExpressionString().equals(expression.getExpressionString());
- }
- return false;
- }
- }
-
-
-
- public static class MethodActionListenerMatcher implements IArgumentMatcher{
- private MockMethodExpression expression;
-
- public MethodActionListenerMatcher(MockMethodExpression expression) {
- super();
- this.expression = expression;
- }
- public void appendTo(StringBuffer buffer) {
- buffer
- .append("Action Listener is supposed to evaluate method")
- .append(expression.getExpressionString());
- }
- public boolean matches(Object argument) {
- if (argument instanceof ActionListener) {
- ActionListener listener = (ActionListener) argument;
- ActionEvent event = new ActionEvent(new UICommand());
- listener.processAction(event);
- return expression.lastInvocationMatched(event);
- }
- return false;
- }
- }
-
- public static class MethodValueChangeListenerMatcher implements IArgumentMatcher{
- private MockMethodExpression expression;
-
- public MethodValueChangeListenerMatcher(MockMethodExpression expression) {
- super();
- this.expression = expression;
- }
- public void appendTo(StringBuffer buffer) {
- buffer
- .append("ValueChangeListener Listener is supposed to evaluate method")
- .append(expression.getExpressionString());
- }
- public boolean matches(Object argument) {
- if (argument instanceof ValueChangeListener) {
- ValueChangeListener listener = (ValueChangeListener) argument;
- ValueChangeEvent event = new ValueChangeEvent(new UIInput(), new Object(), new Object());
- listener.processValueChange(event);
- return expression.lastInvocationMatched(event);
- }
- return false;
- }
- }
-
- public static class MethodValidatorMatcher implements IArgumentMatcher{
- private MockMethodExpression expression;
-
- public MethodValidatorMatcher(MockMethodExpression expression) {
- super();
- this.expression = expression;
- }
- public void appendTo(StringBuffer buffer) {
- buffer
- .append("Validator is supposed to evaluate method")
- .append(expression.getExpressionString());
- }
- public boolean matches(Object argument) {
- if (argument instanceof Validator) {
- Validator validator = (Validator) argument;
- FacesContext context = FacesContext.getCurrentInstance();
- UIComponent component = new UIInput();
- Object value = new Object();
- validator.validate(context, component, value);
- return expression.lastInvocationMatched(context, component, value);
- }
- return false;
- }
- }
-
+ public static MethodBinding mbEqToMe(MethodExpression expression) {
+ EasyMock.reportMatcher(new ExpressionEq(expression) {}
+ );
+
+ return null;
+ }
+
+ public static MethodExpression meEqToMe(MethodExpression expression) {
+ EasyMock.reportMatcher(new ExpressionEq(expression) {}
+ );
+
+ return null;
+ }
+
+ public static Validator meValidator(MockMethodExpression expression) {
+ EasyMock.reportMatcher(new MethodValidatorMatcher(expression));
+
+ return null;
+ }
+
+ public static ActionListener meActionListener(MockMethodExpression expression) {
+ EasyMock.reportMatcher(new MethodActionListenerMatcher(expression));
+
+ return null;
+ }
+
+ public static ValueChangeListener meValueChangeListener(MockMethodExpression expression) {
+ EasyMock.reportMatcher(new MethodValueChangeListenerMatcher(expression));
+
+ return null;
+ }
+
+// public static ValueExpression expressionStringEq(ValueExpression expression) {
+// EasyMock.reportMatcher(new ExpressionEq(expression) {});
+// return null;
+// }
+ public abstract static class ExpressionEq implements IArgumentMatcher {
+ private Expression expression;
+
+ public ExpressionEq(Expression expression) {
+ super();
+ this.expression = expression;
+ }
+
+ public void appendTo(StringBuffer buffer) {
+ buffer.append("Expression expected to have expression string ").append(expression.getExpressionString());
+ }
+
+ public boolean matches(Object argument) {
+ if (argument instanceof Expression) {
+ Expression e2 = (Expression) argument;
+
+ return e2.getExpressionString().equals(expression.getExpressionString());
+ } else if (argument instanceof ValueBinding) {
+ ValueBinding binding = (ValueBinding) argument;
+
+ return binding.getExpressionString().equals(expression.getExpressionString());
+ } else if (argument instanceof MethodBinding) {
+ MethodBinding binding = (MethodBinding) argument;
+
+ return binding.getExpressionString().equals(expression.getExpressionString());
+ }
+
+ return false;
+ }
+ }
+
+
+ public static class MethodActionListenerMatcher implements IArgumentMatcher {
+ private MockMethodExpression expression;
+
+ public MethodActionListenerMatcher(MockMethodExpression expression) {
+ super();
+ this.expression = expression;
+ }
+
+ public void appendTo(StringBuffer buffer) {
+ buffer.append("Action Listener is supposed to evaluate method").append(expression.getExpressionString());
+ }
+
+ public boolean matches(Object argument) {
+ if (argument instanceof ActionListener) {
+ ActionListener listener = (ActionListener) argument;
+ ActionEvent event = new ActionEvent(new UICommand());
+
+ listener.processAction(event);
+
+ return expression.lastInvocationMatched(event);
+ }
+
+ return false;
+ }
+ }
+
+
+ public static class MethodValidatorMatcher implements IArgumentMatcher {
+ private MockMethodExpression expression;
+
+ public MethodValidatorMatcher(MockMethodExpression expression) {
+ super();
+ this.expression = expression;
+ }
+
+ public void appendTo(StringBuffer buffer) {
+ buffer.append("Validator is supposed to evaluate method").append(expression.getExpressionString());
+ }
+
+ public boolean matches(Object argument) {
+ if (argument instanceof Validator) {
+ Validator validator = (Validator) argument;
+ FacesContext context = FacesContext.getCurrentInstance();
+ UIComponent component = new UIInput();
+ Object value = new Object();
+
+ validator.validate(context, component, value);
+
+ return expression.lastInvocationMatched(context, component, value);
+ }
+
+ return false;
+ }
+ }
+
+
+ public static class MethodValueChangeListenerMatcher implements IArgumentMatcher {
+ private MockMethodExpression expression;
+
+ public MethodValueChangeListenerMatcher(MockMethodExpression expression) {
+ super();
+ this.expression = expression;
+ }
+
+ public void appendTo(StringBuffer buffer) {
+ buffer.append("ValueChangeListener Listener is supposed to evaluate method").append(
+ expression.getExpressionString());
+ }
+
+ public boolean matches(Object argument) {
+ if (argument instanceof ValueChangeListener) {
+ ValueChangeListener listener = (ValueChangeListener) argument;
+ ValueChangeEvent event = new ValueChangeEvent(new UIInput(), new Object(), new Object());
+
+ listener.processValueChange(event);
+
+ return expression.lastInvocationMatched(event);
+ }
+
+ return false;
+ }
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/LiteralValueExpression.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/LiteralValueExpression.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/LiteralValueExpression.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -9,15 +10,16 @@
*/
@SuppressWarnings("serial")
public class LiteralValueExpression extends MockValueExpression {
+ public LiteralValueExpression(Object o) {
+ super(o);
- public LiteralValueExpression(Object o) {
- super(o);
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public boolean isLiteralText() {
- // TODO Auto-generated method stub
- return true;
- }
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public boolean isLiteralText() {
+
+ // TODO Auto-generated method stub
+ return true;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockAjax4JsfLifecycle.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockAjax4JsfLifecycle.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockAjax4JsfLifecycle.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import javax.faces.context.FacesContext;
@@ -31,9 +33,5 @@
*
*/
public class MockAjax4JsfLifecycle extends MockLifecycle {
-
- public void processAll(FacesContext context) {
-
- }
-
+ public void processAll(FacesContext context) {}
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockApplication.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockApplication.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockApplication.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -13,16 +14,14 @@
*
*/
public class MockApplication extends MockApplication12 {
+ private ExpressionFactory expressionFactory;
- private ExpressionFactory expressionFactory;
-
- public MockApplication() {
- expressionFactory =
- new EnumSupportExpressionFactoryWrapper(new MockExpressionFactory());
- }
-
- @Override
- public ExpressionFactory getExpressionFactory() {
- return expressionFactory;
- }
+ public MockApplication() {
+ expressionFactory = new EnumSupportExpressionFactoryWrapper(new MockExpressionFactory());
+ }
+
+ @Override
+ public ExpressionFactory getExpressionFactory() {
+ return expressionFactory;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockComponentState.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockComponentState.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockComponentState.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import java.io.Serializable;
@@ -32,65 +34,72 @@
* @author shura
*
*/
-public class MockComponentState implements DataComponentState,Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = -4278697745017092414L;
- private int _count = 2;
+public class MockComponentState implements DataComponentState, Serializable {
- /* (non-Javadoc)
- * @see org.ajax4jsf.ajax.repeat.DataComponentState#getRange()
- */
- public Range getRange() {
- // TODO Auto-generated method stub
- return new MockRange(_count);
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4278697745017092414L;
+ private int _count = 2;
- /* (non-Javadoc)
- * @see javax.faces.component.StateHolder#isTransient()
- */
- public boolean isTransient() {
- // TODO Auto-generated method stub
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.ajax.repeat.DataComponentState#getRange()
+ */
+ public Range getRange() {
- /* (non-Javadoc)
- * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object)
- */
- public void restoreState(FacesContext context, Object state) {
- _count = ((Integer)state).intValue();
- }
+ // TODO Auto-generated method stub
+ return new MockRange(_count);
+ }
- /* (non-Javadoc)
- * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext)
- */
- public Object saveState(FacesContext context) {
- // TODO Auto-generated method stub
- return new Integer(_count);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.component.StateHolder#isTransient()
+ */
+ public boolean isTransient() {
- /* (non-Javadoc)
- * @see javax.faces.component.StateHolder#setTransient(boolean)
- */
- public void setTransient(boolean newTransientValue) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ return false;
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object)
+ */
+ public void restoreState(FacesContext context, Object state) {
+ _count = ((Integer) state).intValue();
+ }
- /**
- * @return the count
- */
- public int getCount() {
- return _count;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext)
+ */
+ public Object saveState(FacesContext context) {
- /**
- * @param count the count to set
- */
- public void setCount(int count) {
- _count = count;
- }
+ // TODO Auto-generated method stub
+ return new Integer(_count);
+ }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.component.StateHolder#setTransient(boolean)
+ */
+ public void setTransient(boolean newTransientValue) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /**
+ * @return the count
+ */
+ public int getCount() {
+ return _count;
+ }
+
+ /**
+ * @param count the count to set
+ */
+ public void setCount(int count) {
+ _count = count;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockDataModel.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockDataModel.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockDataModel.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import java.io.IOException;
@@ -35,136 +37,150 @@
*
*/
public class MockDataModel extends ExtendedDataModel {
-
- public static final int ROWS = 10;
-
- private int rowIndex = 0;
-
- private int minRow = 0;
-
- private int maxRow = ROWS;
+ public static final int ROWS = 10;
+ private int minRow = 0;
+ private int rowIndex = 0;
+ private int maxRow = ROWS;
+ private Object wrappedData;
- private Object wrappedData;
- /**
- * @return the maxRow
- */
- public int getMaxRow() {
- return maxRow;
- }
+ /**
+ * @return the maxRow
+ */
+ public int getMaxRow() {
+ return maxRow;
+ }
- /**
- * @param maxRow the maxRow to set
- */
- public void setMaxRow(int maxRow) {
- this.maxRow = maxRow;
- }
+ /**
+ * @param maxRow the maxRow to set
+ */
+ public void setMaxRow(int maxRow) {
+ this.maxRow = maxRow;
+ }
- /**
- * @return the minRow
- */
- public int getMinRow() {
- return minRow;
- }
+ /**
+ * @return the minRow
+ */
+ public int getMinRow() {
+ return minRow;
+ }
- /**
- * @param minRow the minRow to set
- */
- public void setMinRow(int minRow) {
- this.minRow = minRow;
- }
+ /**
+ * @param minRow the minRow to set
+ */
+ public void setMinRow(int minRow) {
+ this.minRow = minRow;
+ }
-
- public void walk(FacesContext context, DataVisitor visitor, Range range, Object argument) throws IOException {
- int first=0;
- int count=ROWS;
- if (range instanceof MockRange) {
- MockRange mockRange = (MockRange) range;
- count = mockRange.getCount();
- } else if (range instanceof SequenceRange) {
- SequenceRange seqRange = (SequenceRange) range;
- first = seqRange.getFirstRow();
- int rows = seqRange.getRows();
- if(rows>0){
- count = rows+first;
- }
- }
- for(int row = first; row < count && row < ROWS;row++){
- visitor.process(context, new Integer(row), argument);
- }
-
- }
+ public void walk(FacesContext context, DataVisitor visitor, Range range, Object argument) throws IOException {
+ int first = 0;
+ int count = ROWS;
- /* (non-Javadoc)
- * @see org.ajax4jsf.ajax.repeat.ExtendedDataModel#getRowKey()
- */
- public Object getRowKey() {
- // TODO Auto-generated method stub
- return rowIndex<0?null:new Integer(rowIndex);
- }
+ if (range instanceof MockRange) {
+ MockRange mockRange = (MockRange) range;
- /* (non-Javadoc)
- * @see org.ajax4jsf.ajax.repeat.ExtendedDataModel#setRowKey(java.lang.Object)
- */
- public void setRowKey(Object key) {
- if(null == key){
- rowIndex = -1;
- } else {
- rowIndex = ((Integer) key).intValue();
- }
- }
+ count = mockRange.getCount();
+ } else if (range instanceof SequenceRange) {
+ SequenceRange seqRange = (SequenceRange) range;
- /* (non-Javadoc)
- * @see javax.faces.model.DataModel#getRowCount()
- */
- public int getRowCount() {
- // TODO Auto-generated method stub
- return getMaxRow();
- }
+ first = seqRange.getFirstRow();
- /* (non-Javadoc)
- * @see javax.faces.model.DataModel#getRowData()
- */
- public Object getRowData() {
- // TODO Auto-generated method stub
- return isRowAvailable()?String.valueOf(rowIndex):null;
- }
+ int rows = seqRange.getRows();
- /* (non-Javadoc)
- * @see javax.faces.model.DataModel#getRowIndex()
- */
- public int getRowIndex() {
- // TODO Auto-generated method stub
- return rowIndex;
- }
+ if (rows > 0) {
+ count = rows + first;
+ }
+ }
- /* (non-Javadoc)
- * @see javax.faces.model.DataModel#getWrappedData()
- */
- public Object getWrappedData() {
- // TODO Auto-generated method stub
- return wrappedData;
- }
+ for (int row = first; row < count && row < ROWS; row++) {
+ visitor.process(context, new Integer(row), argument);
+ }
+ }
- /* (non-Javadoc)
- * @see javax.faces.model.DataModel#isRowAvailable()
- */
- public boolean isRowAvailable() {
- // TODO Auto-generated method stub
- return rowIndex>=getMinRow() && rowIndex<getMaxRow();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.ajax.repeat.ExtendedDataModel#getRowKey()
+ */
+ public Object getRowKey() {
- /* (non-Javadoc)
- * @see javax.faces.model.DataModel#setRowIndex(int)
- */
- public void setRowIndex(int rowIndex) {
- this.rowIndex = rowIndex;
- }
+ // TODO Auto-generated method stub
+ return rowIndex < 0 ? null : new Integer(rowIndex);
+ }
- /* (non-Javadoc)
- * @see javax.faces.model.DataModel#setWrappedData(java.lang.Object)
- */
- public void setWrappedData(Object data) {
- wrappedData = data;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.ajax.repeat.ExtendedDataModel#setRowKey(java.lang.Object)
+ */
+ public void setRowKey(Object key) {
+ if (null == key) {
+ rowIndex = -1;
+ } else {
+ rowIndex = ((Integer) key).intValue();
+ }
+ }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.model.DataModel#getRowCount()
+ */
+ public int getRowCount() {
+
+ // TODO Auto-generated method stub
+ return getMaxRow();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.model.DataModel#getRowData()
+ */
+ public Object getRowData() {
+
+ // TODO Auto-generated method stub
+ return isRowAvailable() ? String.valueOf(rowIndex) : null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.model.DataModel#getRowIndex()
+ */
+ public int getRowIndex() {
+
+ // TODO Auto-generated method stub
+ return rowIndex;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.model.DataModel#getWrappedData()
+ */
+ public Object getWrappedData() {
+
+ // TODO Auto-generated method stub
+ return wrappedData;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.model.DataModel#isRowAvailable()
+ */
+ public boolean isRowAvailable() {
+
+ // TODO Auto-generated method stub
+ return rowIndex >= getMinRow() && rowIndex < getMaxRow();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.model.DataModel#setRowIndex(int)
+ */
+ public void setRowIndex(int rowIndex) {
+ this.rowIndex = rowIndex;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.model.DataModel#setWrappedData(java.lang.Object)
+ */
+ public void setWrappedData(Object data) {
+ wrappedData = data;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockDataModelListener.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockDataModelListener.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockDataModelListener.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -12,12 +13,12 @@
*/
public class MockDataModelListener implements DataModelListener {
- /* (non-Javadoc)
- * @see javax.faces.model.DataModelListener#rowSelected(javax.faces.model.DataModelEvent)
- */
- public void rowSelected(DataModelEvent event) {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.model.DataModelListener#rowSelected(javax.faces.model.DataModelEvent)
+ */
+ public void rowSelected(DataModelEvent event) {
- }
-
+ // TODO Auto-generated method stub
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockELContext.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockELContext.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockELContext.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,9 +1,9 @@
+
/*
- * ELContextMock.java Date created: 14.12.2007
- * Last modified by: $Author$
- * $Revision$ $Date$
+* ELContextMock.java Date created: 14.12.2007
+* Last modified by: $Author$
+* $Revision$ $Date$
*/
-
package org.ajax4jsf.tests;
import javax.el.ELContext;
@@ -18,31 +18,36 @@
*/
public class MockELContext extends ELContext {
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.ELContext#getELResolver()
*/
@Override
public ELResolver getELResolver() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.ELContext#getFunctionMapper()
*/
@Override
public FunctionMapper getFunctionMapper() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.ELContext#getVariableMapper()
*/
@Override
public VariableMapper getVariableMapper() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
-
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockELContext2.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockELContext2.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockELContext2.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -7,6 +8,7 @@
import javax.el.ELResolver;
import javax.el.FunctionMapper;
import javax.el.VariableMapper;
+
import javax.faces.context.FacesContext;
import com.sun.facelets.FaceletContext;
@@ -16,40 +18,45 @@
*
*/
public class MockELContext2 extends ELContext {
+ private FacesContext faces;
- private FacesContext faces;
- /**
- *
- */
- public MockELContext2(FacesContext context) {
- faces = context;
- }
+ /**
+ *
+ */
+ public MockELContext2(FacesContext context) {
+ faces = context;
+ }
- /* (non-Javadoc)
- * @see javax.el.ELContext#getELResolver()
- */
- @Override
- public ELResolver getELResolver() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ELContext#getELResolver()
+ */
+ @Override
+ public ELResolver getELResolver() {
- /* (non-Javadoc)
- * @see javax.el.ELContext#getFunctionMapper()
- */
- @Override
- public FunctionMapper getFunctionMapper() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.el.ELContext#getVariableMapper()
- */
- @Override
- public VariableMapper getVariableMapper() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ELContext#getFunctionMapper()
+ */
+ @Override
+ public FunctionMapper getFunctionMapper() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.el.ELContext#getVariableMapper()
+ */
+ @Override
+ public VariableMapper getVariableMapper() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockExternalContext.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockExternalContext.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockExternalContext.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import java.io.IOException;
+
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
@@ -33,6 +36,7 @@
import java.util.TreeMap;
import javax.faces.FacesException;
+
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -45,112 +49,127 @@
*
*/
public class MockExternalContext extends MockExternalContext12 {
- /*
- * Realizes methods unimplemented by org.apache.shale.test.mock.MockExternalContext operations.
- *
- */
-
- private Map requestParameterValuesMap = null;
- private Map requestHeaderMap = null;
- private Map requestHeaderValuesMap = null;
- private Iterator requestParameterNamesIterator = null;
- private Set resourcePathsSet = null;
-
- public MockExternalContext(org.apache.shale.test.mock.MockExternalContext baseContext) {
- super((ServletContext)baseContext.getContext(),
- (HttpServletRequest)baseContext.getRequest(), (HttpServletResponse)baseContext.getResponse());
- }
-
- public Map getRequestParameterValuesMap() {
- if (null == requestParameterValuesMap) {
- requestParameterValuesMap = new HashMap();
- HttpServletRequest request = (HttpServletRequest)getRequest();
- for ( Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
- String name = (String) e.nextElement();
- requestParameterValuesMap.put(name, request.getParameterValues(name));
- }
- }
- return Collections.unmodifiableMap(requestParameterValuesMap);
- }
-
- public void dispatch(String requestURI)
- throws IOException, FacesException {
- //TODO hans, should be implemented
- super.dispatch(requestURI);
- }
-
- public Map getRequestHeaderMap() {
- if (null == requestHeaderMap) {
- requestHeaderMap = new TreeMap(CASE_INSENSITIVE_COMPARATOR);
-
- HttpServletRequest request = (HttpServletRequest)getRequest();
- for ( Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
- String name = (String) e.nextElement();
- requestHeaderMap.put(name, request.getHeader(name));
- }
- }
- return Collections.unmodifiableMap(requestHeaderMap);
- }
-
- public Map getRequestHeaderValuesMap() {
- if (null == requestHeaderValuesMap) {
- requestHeaderValuesMap = new TreeMap(CASE_INSENSITIVE_COMPARATOR);
-
- HttpServletRequest request = (HttpServletRequest)getRequest();
- for ( Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
- String name = (String) e.nextElement();
- requestHeaderValuesMap.put(name, EnumerationUtils.toList(request.getHeaders(name)).toArray());
- }
- }
- return Collections.unmodifiableMap(requestHeaderValuesMap);
- }
-
- public Iterator getRequestParameterNames() {
- if (null == requestParameterNamesIterator) {
- requestParameterNamesIterator = getRequestParameterValuesMap().keySet().iterator();
- }
- return requestParameterNamesIterator;
- }
-
- /**
- * <p>Add the specified request parameter for this request.</p>
- *
- * @param key Parameter name
- * @param value Parameter value
- */
- public void addRequestParameterMap(String key, String value) {
- super.addRequestParameterMap(key, value);
-
- String [] currentValue = (String[]) getRequestParameterValuesMap().get(key);
- if (null == currentValue) {
- requestParameterValuesMap.put(key, new String[] { value });
- } else {
- String [] newArray = new String [currentValue.length + 1];
- System.arraycopy(currentValue, 0, newArray, 0, currentValue.length);
- newArray[currentValue.length] = value;
- requestParameterValuesMap.put(key, newArray);
- }
- }
-
- public Set getResourcePaths(String path) {
- // TODO hans, should be implemented
- if (null == resourcePathsSet) {
- resourcePathsSet = new HashSet();
- }
- return resourcePathsSet;
- }
-
- public void redirect(String requestURI) throws IOException {
- // TODO hans, should be implemented
- super.redirect(requestURI);
- }
-
- protected final static Comparator CASE_INSENSITIVE_COMPARATOR = new Comparator() {
- public int compare(Object arg0, Object arg1) {
- String s0 = ( String ) arg0;
- String s1 = ( String ) arg1;
- return s0.toUpperCase().compareTo(s1.toUpperCase());
- }
- };
-
+ protected final static Comparator CASE_INSENSITIVE_COMPARATOR = new Comparator() {
+ public int compare(Object arg0, Object arg1) {
+ String s0 = (String) arg0;
+ String s1 = (String) arg1;
+
+ return s0.toUpperCase().compareTo(s1.toUpperCase());
+ }
+ };
+ private Map requestHeaderMap = null;
+ private Map requestHeaderValuesMap = null;
+ private Iterator requestParameterNamesIterator = null;
+
+ /*
+ * Realizes methods unimplemented by org.apache.shale.test.mock.MockExternalContext operations.
+ *
+ */
+ private Map requestParameterValuesMap = null;
+ private Set resourcePathsSet = null;
+
+ public MockExternalContext(org.apache.shale.test.mock.MockExternalContext baseContext) {
+ super((ServletContext) baseContext.getContext(), (HttpServletRequest) baseContext.getRequest(),
+ (HttpServletResponse) baseContext.getResponse());
+ }
+
+ public Map getRequestParameterValuesMap() {
+ if (null == requestParameterValuesMap) {
+ requestParameterValuesMap = new HashMap();
+
+ HttpServletRequest request = (HttpServletRequest) getRequest();
+
+ for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
+ String name = (String) e.nextElement();
+
+ requestParameterValuesMap.put(name, request.getParameterValues(name));
+ }
+ }
+
+ return Collections.unmodifiableMap(requestParameterValuesMap);
+ }
+
+ public void dispatch(String requestURI) throws IOException, FacesException {
+
+ // TODO hans, should be implemented
+ super.dispatch(requestURI);
+ }
+
+ public Map getRequestHeaderMap() {
+ if (null == requestHeaderMap) {
+ requestHeaderMap = new TreeMap(CASE_INSENSITIVE_COMPARATOR);
+
+ HttpServletRequest request = (HttpServletRequest) getRequest();
+
+ for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
+ String name = (String) e.nextElement();
+
+ requestHeaderMap.put(name, request.getHeader(name));
+ }
+ }
+
+ return Collections.unmodifiableMap(requestHeaderMap);
+ }
+
+ public Map getRequestHeaderValuesMap() {
+ if (null == requestHeaderValuesMap) {
+ requestHeaderValuesMap = new TreeMap(CASE_INSENSITIVE_COMPARATOR);
+
+ HttpServletRequest request = (HttpServletRequest) getRequest();
+
+ for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
+ String name = (String) e.nextElement();
+
+ requestHeaderValuesMap.put(name, EnumerationUtils.toList(request.getHeaders(name)).toArray());
+ }
+ }
+
+ return Collections.unmodifiableMap(requestHeaderValuesMap);
+ }
+
+ public Iterator getRequestParameterNames() {
+ if (null == requestParameterNamesIterator) {
+ requestParameterNamesIterator = getRequestParameterValuesMap().keySet().iterator();
+ }
+
+ return requestParameterNamesIterator;
+ }
+
+ /**
+ * <p>Add the specified request parameter for this request.</p>
+ *
+ * @param key Parameter name
+ * @param value Parameter value
+ */
+ public void addRequestParameterMap(String key, String value) {
+ super.addRequestParameterMap(key, value);
+
+ String[] currentValue = (String[]) getRequestParameterValuesMap().get(key);
+
+ if (null == currentValue) {
+ requestParameterValuesMap.put(key, new String[] {value});
+ } else {
+ String[] newArray = new String[currentValue.length + 1];
+
+ System.arraycopy(currentValue, 0, newArray, 0, currentValue.length);
+ newArray[currentValue.length] = value;
+ requestParameterValuesMap.put(key, newArray);
+ }
+ }
+
+ public Set getResourcePaths(String path) {
+
+ // TODO hans, should be implemented
+ if (null == resourcePathsSet) {
+ resourcePathsSet = new HashSet();
+ }
+
+ return resourcePathsSet;
+ }
+
+ public void redirect(String requestURI) throws IOException {
+
+ // TODO hans, should be implemented
+ super.redirect(requestURI);
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockFaceletContext.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockFaceletContext.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockFaceletContext.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,10 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import java.io.IOException;
+
import java.net.URL;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -35,6 +39,7 @@
import javax.el.FunctionMapper;
import javax.el.ValueExpression;
import javax.el.VariableMapper;
+
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
@@ -47,145 +52,151 @@
* @author Nick Belaevski
* @since 3.2.2
*/
-
public class MockFaceletContext extends FaceletContext {
+ private Map<String, Integer> ids = new HashMap<String, Integer>();
+ private FacesContext context;
+ private ELResolver elResolver;
+ private FunctionMapper functionMapper;
+ private List<TemplateClient> templateClients;
+ private VariableMapper variableMapper;
- private FacesContext context;
- private FunctionMapper functionMapper;
- private VariableMapper variableMapper;
- private ELResolver elResolver;
-
- private List<TemplateClient> templateClients;
- private Map<String, Integer> ids = new HashMap<String, Integer>();
-
- public List<TemplateClient> getTemplateClients() {
- return templateClients;
- }
+ public MockFaceletContext(FacesContext context) {
+ super();
+ this.context = context;
+ this.templateClients = new ArrayList<TemplateClient>();
- public void setTemplateClients(List<TemplateClient> templateClients) {
- this.templateClients = templateClients;
- }
+ ELContext elContext = context.getELContext();
- public MockFaceletContext(FacesContext context) {
- super();
- this.context = context;
- this.templateClients = new ArrayList<TemplateClient>();
+ this.elResolver = elContext.getELResolver();
+ this.functionMapper = elContext.getFunctionMapper();
+ this.variableMapper = elContext.getVariableMapper();
+ }
- ELContext elContext = context.getELContext();
- this.elResolver = elContext.getELResolver();
- this.functionMapper = elContext.getFunctionMapper();
- this.variableMapper = elContext.getVariableMapper();
- }
+ public List<TemplateClient> getTemplateClients() {
+ return templateClients;
+ }
- @Override
- public String generateUniqueId(String base) {
- Integer cnt = (Integer) this.ids .get(base);
+ public void setTemplateClients(List<TemplateClient> templateClients) {
+ this.templateClients = templateClients;
+ }
+
+ @Override
+ public String generateUniqueId(String base) {
+ Integer cnt = (Integer) this.ids.get(base);
+
if (cnt == null) {
this.ids.put(base, new Integer(0));
+
return base;
} else {
int i = cnt.intValue() + 1;
+
this.ids.put(base, new Integer(i));
+
return base + "_" + i;
}
- }
+ }
- @Override
- public ExpressionFactory getExpressionFactory() {
- return context.getApplication().getExpressionFactory();
- }
+ @Override
+ public ExpressionFactory getExpressionFactory() {
+ return context.getApplication().getExpressionFactory();
+ }
- @Override
- public FacesContext getFacesContext() {
- return context;
- }
+ @Override
+ public FacesContext getFacesContext() {
+ return context;
+ }
- @Override
- public boolean includeDefinition(UIComponent parent, String name)
- throws IOException, FaceletException, FacesException, ELException {
- // TODO Auto-generated method stub
- throw new UnsupportedOperationException();
- }
+ @Override
+ public boolean includeDefinition(UIComponent parent, String name)
+ throws IOException, FaceletException, FacesException, ELException {
- @Override
- public void includeFacelet(UIComponent parent, String relativePath)
- throws IOException, FaceletException, FacesException, ELException {
- // TODO Auto-generated method stub
- throw new UnsupportedOperationException();
- }
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException();
+ }
- @Override
- public void includeFacelet(UIComponent parent, URL absolutePath)
- throws IOException, FaceletException, FacesException, ELException {
- // TODO Auto-generated method stub
- throw new UnsupportedOperationException();
- }
+ @Override
+ public void includeFacelet(UIComponent parent, String relativePath)
+ throws IOException, FaceletException, FacesException, ELException {
- @Override
- public void popClient(TemplateClient client) {
- if (this.templateClients.isEmpty()) {
- throw new IllegalArgumentException();
- }
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException();
+ }
- this.templateClients.remove(client);
- }
+ @Override
+ public void includeFacelet(UIComponent parent, URL absolutePath)
+ throws IOException, FaceletException, FacesException, ELException {
- @Override
- public void pushClient(TemplateClient client) {
- this.templateClients.add(0, client);
- }
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException();
+ }
- @Override
- public void extendClient(TemplateClient client) {
- this.templateClients.add(client);
- }
+ @Override
+ public void popClient(TemplateClient client) {
+ if (this.templateClients.isEmpty()) {
+ throw new IllegalArgumentException();
+ }
- @Override
- public Object getAttribute(String name) {
+ this.templateClients.remove(client);
+ }
+
+ @Override
+ public void pushClient(TemplateClient client) {
+ this.templateClients.add(0, client);
+ }
+
+ @Override
+ public void extendClient(TemplateClient client) {
+ this.templateClients.add(client);
+ }
+
+ @Override
+ public Object getAttribute(String name) {
if (this.variableMapper != null) {
ValueExpression ve = this.variableMapper.resolveVariable(name);
+
if (ve != null) {
return ve.getValue(this);
}
}
+
return null;
- }
+ }
- @Override
- public void setAttribute(String name, Object value) {
+ @Override
+ public void setAttribute(String name, Object value) {
if (this.variableMapper != null) {
if (value == null) {
this.variableMapper.setVariable(name, null);
} else {
- this.variableMapper.setVariable(name, this.getExpressionFactory()
- .createValueExpression(value, Object.class));
+ this.variableMapper.setVariable(name,
+ this.getExpressionFactory().createValueExpression(value, Object.class));
}
}
- }
+ }
- @Override
- public void setFunctionMapper(FunctionMapper fnMapper) {
- this.functionMapper = fnMapper;
- }
+ @Override
+ public void setFunctionMapper(FunctionMapper fnMapper) {
+ this.functionMapper = fnMapper;
+ }
- @Override
- public void setVariableMapper(VariableMapper varMapper) {
- this.variableMapper = varMapper;
- }
+ @Override
+ public void setVariableMapper(VariableMapper varMapper) {
+ this.variableMapper = varMapper;
+ }
- @Override
- public ELResolver getELResolver() {
- return this.elResolver;
- }
+ @Override
+ public ELResolver getELResolver() {
+ return this.elResolver;
+ }
- @Override
- public FunctionMapper getFunctionMapper() {
- return this.functionMapper;
- }
+ @Override
+ public FunctionMapper getFunctionMapper() {
+ return this.functionMapper;
+ }
- @Override
- public VariableMapper getVariableMapper() {
- return this.variableMapper;
- }
-
+ @Override
+ public VariableMapper getVariableMapper() {
+ return this.variableMapper;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockFacesResourceContext.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockFacesResourceContext.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockFacesResourceContext.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -18,6 +18,9 @@
* 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.tests;
import java.util.ArrayList;
@@ -29,6 +32,7 @@
import javax.faces.context.FacesContext;
import org.ajax4jsf.resource.FacesResourceContext;
+
import org.apache.shale.test.mock.MockHttpServletResponse;
import com.gargoylesoftware.htmlunit.KeyValuePair;
@@ -36,68 +40,67 @@
/**
* @author Nick - mailto:nbelaevski@exadel.com
* created 03.04.2007
- *
+ *
*/
public class MockFacesResourceContext extends FacesResourceContext {
- private String contentType;
- //used to encode headers properly
- private MockHttpServletResponse mockResponse = new MockHttpServletResponse();
- private Set headerSet = new LinkedHashSet();
- private Integer contentLength;
-
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
+ // used to encode headers properly
+ private MockHttpServletResponse mockResponse = new MockHttpServletResponse();
+ private Set headerSet = new LinkedHashSet();
+ private Integer contentLength;
+ private String contentType;
- public String getContentType() {
- return contentType;
- }
-
- public void setContentLength(int contentLength) {
- this.contentLength = contentLength;
- }
-
- public int getContentLength() {
- if (contentLength == null) {
- throw new IllegalStateException("Content length hasn't been set yet!");
- }
-
- return contentLength.intValue();
- }
-
- public void setDateHeader(String name, long value) {
- headerSet.add(name);
- mockResponse.setDateHeader(name, value);
- }
+ public MockFacesResourceContext(FacesContext facesContext) {
+ super(facesContext);
+ }
- public void setHeader(String name, String value) {
- headerSet.add(name);
- mockResponse.setHeader(name, value);
- }
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+ }
- public void setIntHeader(String name, int value) {
- headerSet.add(name);
- mockResponse.setIntHeader(name, value);
- }
+ public String getContentType() {
+ return contentType;
+ }
- public List getHeaders() {
- List headers = new ArrayList();
- for (Iterator iterator = headerSet.iterator(); iterator
- .hasNext();) {
- String headerName = (String) iterator.next();
-
- String headerValue = mockResponse.getHeader(headerName);
- if (headerValue != null) {
- headers.add(new KeyValuePair(headerName, headerValue));
- }
- }
+ public void setContentLength(int contentLength) {
+ this.contentLength = contentLength;
+ }
- return headers;
- }
-
- public MockFacesResourceContext(FacesContext facesContext) {
- super(facesContext);
- }
+ public int getContentLength() {
+ if (contentLength == null) {
+ throw new IllegalStateException("Content length hasn't been set yet!");
+ }
+ return contentLength.intValue();
+ }
+
+ public void setDateHeader(String name, long value) {
+ headerSet.add(name);
+ mockResponse.setDateHeader(name, value);
+ }
+
+ public void setHeader(String name, String value) {
+ headerSet.add(name);
+ mockResponse.setHeader(name, value);
+ }
+
+ public void setIntHeader(String name, int value) {
+ headerSet.add(name);
+ mockResponse.setIntHeader(name, value);
+ }
+
+ public List getHeaders() {
+ List headers = new ArrayList();
+
+ for (Iterator iterator = headerSet.iterator(); iterator.hasNext(); ) {
+ String headerName = (String) iterator.next();
+ String headerValue = mockResponse.getHeader(headerName);
+
+ if (headerValue != null) {
+ headers.add(new KeyValuePair(headerName, headerValue));
+ }
+ }
+
+ return headers;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockMethodBinding.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockMethodBinding.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockMethodBinding.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import java.util.ArrayList;
@@ -32,56 +34,54 @@
/**
* @author Nick - mailto:nbelaevski@exadel.com
* created 09.04.2007
- *
+ *
*/
public class MockMethodBinding extends MethodBinding {
+ private List invocationArgs = new ArrayList();
+ private MethodResult result;
+ private Class returnType;
- private Class returnType;
- private MethodResult result;
-
- private List invocationArgs = new ArrayList();
+ public MockMethodBinding() {
+ this(null, null);
+ }
- public static interface MethodResult {
- public Object invoke(FacesContext facesContext, Object[] args, Class returnType);
- }
-
- public MockMethodBinding() {
- this(null, null);
- }
-
- public MockMethodBinding(Class returnType, MethodResult result) {
- super();
- this.returnType = returnType;
- this.result = result;
- }
+ public MockMethodBinding(Class returnType, MethodResult result) {
+ super();
+ this.returnType = returnType;
+ this.result = result;
+ }
- public Class getType(FacesContext context) throws MethodNotFoundException {
- if (context == null) {
- throw new NullPointerException();
- }
-
- return returnType;
- }
+ public Class getType(FacesContext context) throws MethodNotFoundException {
+ if (context == null) {
+ throw new NullPointerException();
+ }
- public Object invoke(FacesContext context, Object[] params)
- throws EvaluationException, MethodNotFoundException {
- if (context == null) {
- throw new NullPointerException();
- }
-
- invocationArgs.add(params);
- if (result != null) {
- return result.invoke(context, params, returnType);
- }
-
- return null;
- }
+ return returnType;
+ }
- public void clear() {
- invocationArgs.clear();
- }
-
- public Object[][] getInvocationArgs() {
- return (Object[][]) invocationArgs.toArray(new Object[invocationArgs.size()][]);
- }
+ public Object invoke(FacesContext context, Object[] params) throws EvaluationException, MethodNotFoundException {
+ if (context == null) {
+ throw new NullPointerException();
+ }
+
+ invocationArgs.add(params);
+
+ if (result != null) {
+ return result.invoke(context, params, returnType);
+ }
+
+ return null;
+ }
+
+ public void clear() {
+ invocationArgs.clear();
+ }
+
+ public Object[][] getInvocationArgs() {
+ return (Object[][]) invocationArgs.toArray(new Object[invocationArgs.size()][]);
+ }
+
+ public static interface MethodResult {
+ public Object invoke(FacesContext facesContext, Object[] args, Class returnType);
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockMethodExpression.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockMethodExpression.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockMethodExpression.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -17,98 +18,110 @@
*/
@SuppressWarnings("serial")
public class MockMethodExpression extends MethodExpression {
+ private List<Object[]> invocationArgs = new ArrayList<Object[]>();
+ private String expressionString;
- public static interface MethodExpressionInvocationResult {
- public Object invoke(ELContext context, Object ... arguments);
- }
-
- //private Class<?> returnType;
- private MethodExpressionInvocationResult result;
- private String expressionString;
- private List<Object[]> invocationArgs = new ArrayList<Object[]>();
+ // private Class<?> returnType;
+ private MethodExpressionInvocationResult result;
-
-
-
- public MockMethodExpression(String expressionString, Class<?> returnType,
- MethodExpressionInvocationResult result) {
- super();
- this.expressionString = expressionString;
- //this.returnType = returnType;
- this.result = result;
- }
+ public MockMethodExpression(String expressionString, Class<?> returnType, MethodExpressionInvocationResult result) {
+ super();
+ this.expressionString = expressionString;
- /* (non-Javadoc)
- * @see javax.el.MethodExpression#getMethodInfo(javax.el.ELContext)
- */
- @Override
- public MethodInfo getMethodInfo(ELContext context) {
- return null;
- }
+ // this.returnType = returnType;
+ this.result = result;
+ }
- /* (non-Javadoc)
- * @see javax.el.MethodExpression#invoke(javax.el.ELContext, java.lang.Object[])
- */
- @Override
- public Object invoke(ELContext context, Object[] params) {
- invocationArgs.add(params);
- Object returnValue = null;
- if (result != null) {
- returnValue = result.invoke(context, params);
- }
- return returnValue;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.MethodExpression#getMethodInfo(javax.el.ELContext)
+ */
+ @Override
+ public MethodInfo getMethodInfo(ELContext context) {
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.el.Expression#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof MethodExpression) {
- MethodExpression expression = (MethodExpression) obj;
- return expressionString != null && expression.getExpressionString() != null && expressionString.equals(expression.getExpressionString());
- }
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.MethodExpression#invoke(javax.el.ELContext, java.lang.Object[])
+ */
+ @Override
+ public Object invoke(ELContext context, Object[] params) {
+ invocationArgs.add(params);
- /* (non-Javadoc)
- * @see javax.el.Expression#getExpressionString()
- */
- @Override
- public String getExpressionString() {
- return expressionString;
- }
+ Object returnValue = null;
- /* (non-Javadoc)
- * @see javax.el.Expression#hashCode()
- */
- @Override
- public int hashCode() {
- return expressionString == null ? 0 : expressionString.hashCode();
- }
+ if (result != null) {
+ returnValue = result.invoke(context, params);
+ }
- /* (non-Javadoc)
- * @see javax.el.Expression#isLiteralText()
- */
- @Override
- public boolean isLiteralText() {
- // TODO Auto-generated method stub
- return expressionString != null && !(expressionString.contains("${") || expressionString.contains("#{"));
- }
+ return returnValue;
+ }
- public List<Object[]> getInvocationArgs() {
- return invocationArgs;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.el.Expression#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof MethodExpression) {
+ MethodExpression expression = (MethodExpression) obj;
- public void reset() {
- invocationArgs.clear();
- }
-
- public boolean lastInvocationMatched(Object ...objects) {
- if (!invocationArgs.isEmpty()) {
- Object[] argz = invocationArgs.get(invocationArgs.size() - 1);
- return Arrays.equals(objects, argz);
- }
- return false;
- }
+ return expressionString != null && expression.getExpressionString() != null
+ && expressionString.equals(expression.getExpressionString());
+ }
+
+ return false;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.el.Expression#getExpressionString()
+ */
+ @Override
+ public String getExpressionString() {
+ return expressionString;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.el.Expression#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ return expressionString == null ? 0 : expressionString.hashCode();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.el.Expression#isLiteralText()
+ */
+ @Override
+ public boolean isLiteralText() {
+
+ // TODO Auto-generated method stub
+ return expressionString != null && !(expressionString.contains("${") || expressionString.contains("#{"));
+ }
+
+ public List<Object[]> getInvocationArgs() {
+ return invocationArgs;
+ }
+
+ public void reset() {
+ invocationArgs.clear();
+ }
+
+ public boolean lastInvocationMatched(Object... objects) {
+ if (!invocationArgs.isEmpty()) {
+ Object[] argz = invocationArgs.get(invocationArgs.size() - 1);
+
+ return Arrays.equals(objects, argz);
+ }
+
+ return false;
+ }
+
+ public static interface MethodExpressionInvocationResult {
+ public Object invoke(ELContext context, Object... arguments);
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockPageContext.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockPageContext.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockPageContext.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,15 +1,17 @@
+
/*
- * PageContextMock.java Date created: 14.12.2007
- * Last modified by: $Author$
- * $Revision$ $Date$
+* PageContextMock.java Date created: 14.12.2007
+* Last modified by: $Author$
+* $Revision$ $Date$
*/
-
package org.ajax4jsf.tests;
import java.io.IOException;
+
import java.util.Enumeration;
import javax.el.ELContext;
+
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
@@ -28,428 +30,435 @@
*
*/
public class MockPageContext extends PageContext {
+ private ELContext ELContext;
-
- private ELContext ELContext;
-
-
-
/**
* TODO Description goes here.
*/
public MockPageContext() {
- super();
- ELContext = new MockELContext();
- // TODO Auto-generated constructor stub
+ super();
+ ELContext = new MockELContext();
+
+ // TODO Auto-generated constructor stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#forward(java.lang.String)
*/
@Override
- public void forward(String relativeUrlPath) throws ServletException,
- IOException {
- // TODO Auto-generated method stub
+ public void forward(String relativeUrlPath) throws ServletException, IOException {
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#getException()
*/
@Override
public Exception getException() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#getPage()
*/
@Override
public Object getPage() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#getRequest()
*/
@Override
public ServletRequest getRequest() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#getResponse()
*/
@Override
public ServletResponse getResponse() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#getServletConfig()
*/
@Override
public ServletConfig getServletConfig() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#getServletContext()
*/
@Override
public ServletContext getServletContext() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#getSession()
*/
@Override
public HttpSession getSession() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#handlePageException(java.lang.Exception)
*/
@Override
- public void handlePageException(Exception e) throws ServletException,
- IOException {
- // TODO Auto-generated method stub
+ public void handlePageException(Exception e) throws ServletException, IOException {
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#handlePageException(java.lang.Throwable)
*/
@Override
- public void handlePageException(Throwable t) throws ServletException,
- IOException {
- // TODO Auto-generated method stub
+ public void handlePageException(Throwable t) throws ServletException, IOException {
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#include(java.lang.String)
*/
@Override
- public void include(String relativeUrlPath) throws ServletException,
- IOException {
- // TODO Auto-generated method stub
+ public void include(String relativeUrlPath) throws ServletException, IOException {
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#include(java.lang.String, boolean)
*/
@Override
- public void include(String relativeUrlPath, boolean flush)
- throws ServletException, IOException {
- // TODO Auto-generated method stub
+ public void include(String relativeUrlPath, boolean flush) throws ServletException, IOException {
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#initialize(javax.servlet.Servlet, javax.servlet.ServletRequest, javax.servlet.ServletResponse, java.lang.String, boolean, int, boolean)
*/
@Override
- public void initialize(Servlet servlet, ServletRequest request,
- ServletResponse response, String errorPageURL,
- boolean needsSession, int bufferSize, boolean autoFlush)
- throws IOException, IllegalStateException, IllegalArgumentException {
- // TODO Auto-generated method stub
+ public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL,
+ boolean needsSession, int bufferSize, boolean autoFlush)
+ throws IOException, IllegalStateException, IllegalArgumentException {
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.PageContext#release()
*/
@Override
public void release() {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#findAttribute(java.lang.String)
*/
@Override
public Object findAttribute(String name) {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#getAttribute(java.lang.String)
*/
@Override
public Object getAttribute(String name) {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#getAttribute(java.lang.String, int)
*/
@Override
public Object getAttribute(String name, int scope) {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#getAttributeNamesInScope(int)
*/
@Override
public Enumeration<String> getAttributeNamesInScope(int scope) {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#getAttributesScope(java.lang.String)
*/
@Override
public int getAttributesScope(String name) {
- // TODO Auto-generated method stub
- return 0;
+
+ // TODO Auto-generated method stub
+ return 0;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#getELContext()
*/
@Override
public ELContext getELContext() {
- // TODO Auto-generated method stub
- return this.ELContext;
+
+ // TODO Auto-generated method stub
+ return this.ELContext;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#getExpressionEvaluator()
*/
@Override
public ExpressionEvaluator getExpressionEvaluator() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#getOut()
*/
@Override
public JspWriter getOut() {
- // TODO Auto-generated method stub
- return new JspWriter(0, false) {
- @Override
- public void clear() throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ return new JspWriter(0, false) {
+ @Override
+ public void clear() throws IOException {
- @Override
- public void clearBuffer() throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void clearBuffer() throws IOException {
- @Override
- public void close() throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void close() throws IOException {
- @Override
- public void flush() throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void flush() throws IOException {
- @Override
- public int getRemaining() {
- // TODO Auto-generated method stub
- return 0;
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public int getRemaining() {
- @Override
- public void newLine() throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ return 0;
+ }
+ @Override
+ public void newLine() throws IOException {
- @Override
- public void print(boolean b) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(boolean b) throws IOException {
- @Override
- public void print(char c) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(char c) throws IOException {
- @Override
- public void print(int i) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(int i) throws IOException {
- @Override
- public void print(long l) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(long l) throws IOException {
- @Override
- public void print(float f) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(float f) throws IOException {
- @Override
- public void print(double d) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(double d) throws IOException {
- @Override
- public void print(char[] s) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(char[] s) throws IOException {
- @Override
- public void print(String s) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(String s) throws IOException {
- @Override
- public void print(Object obj) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void print(Object obj) throws IOException {
- @Override
- public void println() throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println() throws IOException {
- @Override
- public void println(boolean x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(boolean x) throws IOException {
- @Override
- public void println(char x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(char x) throws IOException {
- @Override
- public void println(int x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(int x) throws IOException {
- @Override
- public void println(long x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(long x) throws IOException {
- @Override
- public void println(float x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(float x) throws IOException {
- @Override
- public void println(double x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(double x) throws IOException {
- @Override
- public void println(char[] x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(char[] x) throws IOException {
- @Override
- public void println(String x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(String x) throws IOException {
- @Override
- public void println(Object x) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void println(Object x) throws IOException {
- @Override
- public void write(char[] cbuf, int off, int len) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- };
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void write(char[] cbuf, int off, int len) throws IOException {
+
+ // TODO Auto-generated method stub
+ }
+ };
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#getVariableResolver()
*/
@Override
public VariableResolver getVariableResolver() {
- // TODO Auto-generated method stub
- return null;
+
+ // TODO Auto-generated method stub
+ return null;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#removeAttribute(java.lang.String)
*/
@Override
public void removeAttribute(String name) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#removeAttribute(java.lang.String, int)
*/
@Override
public void removeAttribute(String name, int scope) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#setAttribute(java.lang.String, java.lang.Object)
*/
@Override
public void setAttribute(String name, Object value) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.servlet.jsp.JspContext#setAttribute(java.lang.String, java.lang.Object, int)
*/
@Override
public void setAttribute(String name, Object value, int scope) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
-
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockRange.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockRange.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockRange.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import org.ajax4jsf.model.Range;
@@ -28,14 +30,13 @@
*
*/
public class MockRange implements Range {
-
- private int count;
+ private int count;
- public MockRange(int count) {
- this.count = count;
- }
+ public MockRange(int count) {
+ this.count = count;
+ }
- public int getCount(){
- return count;
- }
+ public int getCount() {
+ return count;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockSerializableDataModel.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockSerializableDataModel.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockSerializableDataModel.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import java.io.IOException;
@@ -34,67 +36,62 @@
*
*/
public class MockSerializableDataModel extends MockDataModel {
+ public SerializableDataModel getSerializableModel(Range range) {
+ MockRange mockRange = (MockRange) range;
+ SerializableDataModel model = new SerializableDataModel() {
+ public void update() {
- public SerializableDataModel getSerializableModel(Range range) {
- MockRange mockRange = (MockRange) range;
- SerializableDataModel model = new SerializableDataModel(){
+ // TODO Auto-generated method stub
+ }
+ public Object getRowKey() {
- public void update() {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
+ public void setRowKey(Object key) {
- public Object getRowKey() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ }
+ public void walk(FacesContext context, DataVisitor visitor, Range range, Object argument)
+ throws IOException {
- public void setRowKey(Object key) {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ public int getRowCount() {
- public void walk(FacesContext context, DataVisitor visitor, Range range, Object argument) throws IOException {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ return 0;
+ }
+ public Object getRowData() {
- public int getRowCount() {
- // TODO Auto-generated method stub
- return 0;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
+ public int getRowIndex() {
- public Object getRowData() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return 0;
+ }
+ public Object getWrappedData() {
- public int getRowIndex() {
- // TODO Auto-generated method stub
- return 0;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
+ public boolean isRowAvailable() {
- public Object getWrappedData() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return false;
+ }
+ public void setRowIndex(int arg0) {
- public boolean isRowAvailable() {
- // TODO Auto-generated method stub
- return false;
- }
+ // TODO Auto-generated method stub
+ }
+ public void setWrappedData(Object arg0) {
- public void setRowIndex(int arg0) {
- // TODO Auto-generated method stub
-
- }
+ // TODO Auto-generated method stub
+ }
+ };
- public void setWrappedData(Object arg0) {
- // TODO Auto-generated method stub
-
- }
-
- };
- return model;
- }
+ return model;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockUIComponent.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockUIComponent.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockUIComponent.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.tests;
@@ -16,99 +17,101 @@
*
*/
public class MockUIComponent extends UIComponentBase {
+ private int runsBroadcast = 0;
+ private int runsDecode = 0;
+ private int runsInvokeOnComponent = 0;
+ private int runsProcessDecodes = 0;
+ private int runsProcessUpdates = 0;
+ private int runsProcessValidators = 0;
- private int runsProcessDecodes = 0;
- private int runsDecode = 0;
- private int runsBroadcast=0;
- private int runsInvokeOnComponent=0;
- private int runsProcessUpdates=0;
- private int runsProcessValidators=0;
-
- /**
- * @return the runsProcessDecodes
- */
- public int getRunsProcessDecodes() {
- return runsProcessDecodes;
- }
+ /**
+ * @return the runsProcessDecodes
+ */
+ public int getRunsProcessDecodes() {
+ return runsProcessDecodes;
+ }
- /**
- * @return the runsDecode
- */
- public int getRunsDecode() {
- return runsDecode;
- }
+ /**
+ * @return the runsDecode
+ */
+ public int getRunsDecode() {
+ return runsDecode;
+ }
- /**
- * @return the runsBroadcast
- */
- public int getRunsBroadcast() {
- return runsBroadcast;
- }
+ /**
+ * @return the runsBroadcast
+ */
+ public int getRunsBroadcast() {
+ return runsBroadcast;
+ }
- /**
- * @return the runsInvokeOnComponent
- */
- public int getRunsInvokeOnComponent() {
- return runsInvokeOnComponent;
- }
+ /**
+ * @return the runsInvokeOnComponent
+ */
+ public int getRunsInvokeOnComponent() {
+ return runsInvokeOnComponent;
+ }
- /**
- * @return the runsProcessUpdates
- */
- public int getRunsProcessUpdates() {
- return runsProcessUpdates;
- }
+ /**
+ * @return the runsProcessUpdates
+ */
+ public int getRunsProcessUpdates() {
+ return runsProcessUpdates;
+ }
- /**
- * @return the runsProcessValidators
- */
- public int getRunsProcessValidators() {
- return runsProcessValidators;
- }
+ /**
+ * @return the runsProcessValidators
+ */
+ public int getRunsProcessValidators() {
+ return runsProcessValidators;
+ }
- /* (non-Javadoc)
- * @see javax.faces.component.UIComponent#getFamily()
- */
- @Override
- public String getFamily() {
- // TODO Auto-generated method stub
- return "org.ajax4jsf.test";
- }
-
- @Override
- public void processDecodes(FacesContext context) {
- runsProcessDecodes++;
- super.processDecodes(context);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.component.UIComponent#getFamily()
+ */
+ @Override
+ public String getFamily() {
- @Override
- public void decode(FacesContext context) {
- runsDecode++;
- super.decode(context);
- }
-
- @Override
- public void broadcast(FacesEvent event) throws AbortProcessingException {
- runsBroadcast++;
- super.broadcast(event);
- }
-
- @Override
- public boolean invokeOnComponent(FacesContext context, String clientId,
- ContextCallback callback) throws FacesException {
- runsInvokeOnComponent++;
- return super.invokeOnComponent(context, clientId, callback);
- }
-
- @Override
- public void processUpdates(FacesContext context) {
- runsProcessUpdates++;
- super.processUpdates(context);
- }
-
- @Override
- public void processValidators(FacesContext context) {
- runsProcessValidators++;
- super.processValidators(context);
- }
+ // TODO Auto-generated method stub
+ return "org.ajax4jsf.test";
+ }
+
+ @Override
+ public void processDecodes(FacesContext context) {
+ runsProcessDecodes++;
+ super.processDecodes(context);
+ }
+
+ @Override
+ public void decode(FacesContext context) {
+ runsDecode++;
+ super.decode(context);
+ }
+
+ @Override
+ public void broadcast(FacesEvent event) throws AbortProcessingException {
+ runsBroadcast++;
+ super.broadcast(event);
+ }
+
+ @Override
+ public boolean invokeOnComponent(FacesContext context, String clientId, ContextCallback callback)
+ throws FacesException {
+ runsInvokeOnComponent++;
+
+ return super.invokeOnComponent(context, clientId, callback);
+ }
+
+ @Override
+ public void processUpdates(FacesContext context) {
+ runsProcessUpdates++;
+ super.processUpdates(context);
+ }
+
+ @Override
+ public void processValidators(FacesContext context) {
+ runsProcessValidators++;
+ super.processValidators(context);
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockUIInputRenderer.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockUIInputRenderer.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockUIInputRenderer.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import javax.faces.render.Renderer;
@@ -27,6 +29,4 @@
* @author shura
*
*/
-public class MockUIInputRenderer extends Renderer {
-
-}
+public class MockUIInputRenderer extends Renderer {}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockValueBinding.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockValueBinding.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockValueBinding.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import javax.faces.context.FacesContext;
@@ -29,46 +31,39 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 13.04.2007
- *
+ *
*/
public class MockValueBinding extends ValueBinding {
+ private Class clazz;
+ private Object value;
- private Class clazz;
- private Object value;
-
- public MockValueBinding(Object value, Class clazz) {
- super();
- this.clazz = clazz;
- this.value = value;
- }
+ public MockValueBinding(Object value, Class clazz) {
+ super();
+ this.clazz = clazz;
+ this.value = value;
+ }
- public Class getType(FacesContext context) throws EvaluationException,
- PropertyNotFoundException {
- return clazz;
- }
+ public Class getType(FacesContext context) throws EvaluationException, PropertyNotFoundException {
+ return clazz;
+ }
- public Object getValue(FacesContext context) throws EvaluationException,
- PropertyNotFoundException {
- if (context == null) {
- throw new NullPointerException();
- }
-
- return value;
- }
+ public Object getValue(FacesContext context) throws EvaluationException, PropertyNotFoundException {
+ if (context == null) {
+ throw new NullPointerException();
+ }
- public boolean isReadOnly(FacesContext context) throws EvaluationException,
- PropertyNotFoundException {
- return false;
- }
+ return value;
+ }
- public void setValue(FacesContext context, Object value)
- throws EvaluationException, PropertyNotFoundException {
+ public boolean isReadOnly(FacesContext context) throws EvaluationException, PropertyNotFoundException {
+ return false;
+ }
- if (context == null) {
- throw new NullPointerException();
- }
-
- this.value = value;
- }
+ public void setValue(FacesContext context, Object value) throws EvaluationException, PropertyNotFoundException {
+ if (context == null) {
+ throw new NullPointerException();
+ }
+ this.value = value;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockValueExpression.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockValueExpression.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockValueExpression.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,9 +1,9 @@
+
/*
- * ValueExpressionMock.java Date created: 14.12.2007
- * Last modified by: $Author$
- * $Revision$ $Date$
+* ValueExpressionMock.java Date created: 14.12.2007
+* Last modified by: $Author$
+* $Revision$ $Date$
*/
-
package org.ajax4jsf.tests;
import javax.el.ELContext;
@@ -18,98 +18,121 @@
/** Object to returned by getValue method */
private Object o;
-
+
/**
* TODO Description goes here.
*/
public MockValueExpression(Object o) {
- this.o = o;
+ this.o = o;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.ValueExpression#getExpectedType()
*/
@Override
public Class<?> getExpectedType() {
- // TODO Auto-generated method stub
- return Object.class;
+
+ // TODO Auto-generated method stub
+ return Object.class;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.ValueExpression#getType(javax.el.ELContext)
*/
@Override
public Class<?> getType(ELContext context) {
- // TODO Auto-generated method stub
- return Object.class;
+
+ // TODO Auto-generated method stub
+ return Object.class;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.ValueExpression#getValue(javax.el.ELContext)
*/
@Override
public Object getValue(ELContext context) {
- // TODO Auto-generated method stub
- return o;
+
+ // TODO Auto-generated method stub
+ return o;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.ValueExpression#isReadOnly(javax.el.ELContext)
*/
@Override
public boolean isReadOnly(ELContext context) {
- // TODO Auto-generated method stub
- return false;
+
+ // TODO Auto-generated method stub
+ return false;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.ValueExpression#setValue(javax.el.ELContext, java.lang.Object)
*/
@Override
public void setValue(ELContext context, Object value) {
- o = value;
-
+ o = value;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see javax.el.Expression#getExpressionString()
*/
@Override
public String getExpressionString() {
- // TODO Auto-generated method stub
- return o.toString();
+
+ // TODO Auto-generated method stub
+ return o.toString();
}
@Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((o == null) ? 0 : o.hashCode());
- return result;
- }
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- MockValueExpression other = (MockValueExpression) obj;
- if (o == null) {
- if (other.o != null)
- return false;
- } else if (!o.equals(other.o))
- return false;
- return true;
- }
+ result = prime * result + ((o == null) ? 0 : o.hashCode());
- /* (non-Javadoc)
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+
+ if (obj == null) {
+ return false;
+ }
+
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+
+ MockValueExpression other = (MockValueExpression) obj;
+
+ if (o == null) {
+ if (other.o != null) {
+ return false;
+ }
+ } else if (!o.equals(other.o)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /*
+ * (non-Javadoc)
* @see javax.el.Expression#isLiteralText()
*/
@Override
public boolean isLiteralText() {
- return false;
+ return false;
}
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockViewHandler.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockViewHandler.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockViewHandler.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import java.io.IOException;
@@ -29,13 +31,12 @@
import org.ajax4jsf.application.AjaxViewHandler;
public class MockViewHandler extends AjaxViewHandler {
+ public MockViewHandler(ViewHandler parent) {
+ super(parent);
+ }
- public MockViewHandler(ViewHandler parent) {
- super(parent);
- }
-
- public void writeState(FacesContext context) throws IOException {
- //System.out.println(".writeState()");
- }
+ public void writeState(FacesContext context) throws IOException {
-}
\ No newline at end of file
+ // System.out.println(".writeState()");
+ }
+}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockViewRoot.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockViewRoot.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/MockViewRoot.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests;
import javax.faces.event.PhaseId;
@@ -29,20 +31,18 @@
/**
* @author Nick - mailto:nbelaevski@exadel.com
* created 08.04.2007
- *
+ *
*/
public class MockViewRoot extends AjaxViewRoot {
+ public EventsQueue getAjaxEventsQueue() {
+ return super.getAjaxEventsQueue();
+ }
- public EventsQueue getAjaxEventsQueue() {
- return super.getAjaxEventsQueue();
- }
+ public EventsQueue[] getEvents() {
+ return super.getEvents();
+ }
- public EventsQueue[] getEvents() {
- return super.getEvents();
- }
-
- public EventsQueue getEventsQueue(PhaseId phase) {
- return super.getEventsQueue(phase);
- }
-
+ public EventsQueue getEventsQueue(PhaseId phase) {
+ return super.getEventsQueue(phase);
+ }
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/org/apache/shale/test/config/ConfigParser.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/org/apache/shale/test/config/ConfigParser.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/org/apache/shale/test/config/ConfigParser.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,27 +19,30 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements. See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to you under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
*/
-
package org.ajax4jsf.tests.org.apache.shale.test.config;
import java.io.IOException;
+
import java.net.URL;
+
import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
@@ -48,9 +51,11 @@
import javax.faces.render.Renderer;
import org.ajax4jsf.tests.xml.FacesEntityResolver;
+
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.Rule;
import org.apache.shale.test.mock.MockRenderKit;
+
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
@@ -80,47 +85,33 @@
* @since 1.1
*/
public final class ConfigParser {
-
- // ------------------------------------------------------------ Constructors
-
-
- /** Creates a new instance of ConfigParser */
- public ConfigParser() {
- }
-
-
// ------------------------------------------------------ Manifest Constants
-
/**
* <p>Configuration resource URLs for the JSF RI.</p>
*/
- private static final String[] JSFRI_RESOURCES =
- { "/com/sun/faces/jsf-ri-runtime.xml",
- };
+ private static final String[] JSFRI_RESOURCES = {"/com/sun/faces/jsf-ri-runtime.xml", };
-
/**
* <p>Configuration resource URLs for Apache MyFaces.</p>
*/
- private static final String[] MYFACES_RESOURCES =
- { "/org/apache/myfaces/resource/standard-faces-config.xml",
- };
+ private static final String[] MYFACES_RESOURCES = {"/org/apache/myfaces/resource/standard-faces-config.xml", };
-
// ------------------------------------------------------ Instance Variables
-
/**
* <p>The <code>Digester</code> instance we will use for parsing.</p>
*/
private Digester digester = null;
+ // ------------------------------------------------------------ Constructors
+ /** Creates a new instance of ConfigParser */
+ public ConfigParser() {}
+
// ------------------------------------------------------- Public Properties
-
/**
* <p>Return the URLs of the platform configuration resources for this
* application. The following platforms are currently supported:</p>
@@ -133,19 +124,17 @@
* the name of the configuration resource, it will be supported as well.</p>
*/
public URL[] getPlatformURLs() {
-
URL[] urls = translate(JSFRI_RESOURCES);
+
if (urls[0] == null) {
urls = translate(MYFACES_RESOURCES);
}
- return urls;
+ return urls;
}
-
// ---------------------------------------------------------- Public Methods
-
/**
* <p>Parse the specified JavaServer Faces configuration resource, causing
* the appropriate JSF artifacts to be registered with the mock object
@@ -160,9 +149,9 @@
// Acquire and configure the Digester instance we will use
Digester digester = digester();
- ApplicationFactory factory = (ApplicationFactory)
- FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
+ ApplicationFactory factory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
Application application = factory.getApplication();
+
digester.push(application);
// Perform the required parsing
@@ -171,10 +160,8 @@
} finally {
digester.clear();
}
-
}
-
/**
* <p>Parse the specified set of JavaServer Faces configuration resources,
* in the listed order, causing the appropriate JSF artifacts to be registered
@@ -186,100 +173,82 @@
* @exception SAXException if a parsing error occurs
*/
public void parse(URL[] urls) throws IOException, SAXException {
-
for (int i = 0; i < urls.length; i++) {
parse(urls[i]);
}
-
}
-
// --------------------------------------------------------- Private Methods
-
/**
* <p>Return the <code>Digester</code> instance we will use for parsing,
* creating and configuring a new instance if necessary.</p>
*/
private Digester digester() {
-
if (this.digester == null) {
this.digester = new Digester();
digester.addRule("faces-config/component", new ComponentRule());
- digester.addCallMethod
- ("faces-config/component/component-type", "setComponentType", 0);
- digester.addCallMethod
- ("faces-config/component/component-class", "setComponentClass", 0);
+ digester.addCallMethod("faces-config/component/component-type", "setComponentType", 0);
+ digester.addCallMethod("faces-config/component/component-class", "setComponentClass", 0);
digester.addRule("faces-config/converter", new ConverterRule());
- digester.addCallMethod
- ("faces-config/converter/converter-id", "setConverterId", 0);
- digester.addCallMethod
- ("faces-config/converter/converter-class", "setConverterClass", 0);
- digester.addCallMethod
- ("faces-config/converter/converter-for-class", "setConverterForClass", 0);
+ digester.addCallMethod("faces-config/converter/converter-id", "setConverterId", 0);
+ digester.addCallMethod("faces-config/converter/converter-class", "setConverterClass", 0);
+ digester.addCallMethod("faces-config/converter/converter-for-class", "setConverterForClass", 0);
digester.addRule("faces-config/render-kit", new RenderKitRule());
digester.addRule("faces-config/render-kit/render-kit-id", new RenderKitIdRule());
digester.addRule("faces-config/render-kit/renderer", new RendererRule());
- digester.addCallMethod
- ("faces-config/render-kit/renderer/component-family", "setComponentFamily", 0);
- digester.addCallMethod
- ("faces-config/render-kit/renderer/renderer-class", "setRendererClass", 0);
- digester.addCallMethod
- ("faces-config/render-kit/renderer/renderer-type", "setRendererType", 0);
+ digester.addCallMethod("faces-config/render-kit/renderer/component-family", "setComponentFamily", 0);
+ digester.addCallMethod("faces-config/render-kit/renderer/renderer-class", "setRendererClass", 0);
+ digester.addCallMethod("faces-config/render-kit/renderer/renderer-type", "setRendererType", 0);
digester.addRule("faces-config/validator", new ValidatorRule());
- digester.addCallMethod
- ("faces-config/validator/validator-id", "setValidatorId", 0);
- digester.addCallMethod
- ("faces-config/validator/validator-class", "setValidatorClass", 0);
+ digester.addCallMethod("faces-config/validator/validator-id", "setValidatorId", 0);
+ digester.addCallMethod("faces-config/validator/validator-class", "setValidatorClass", 0);
}
-
+
digester.setEntityResolver(new FacesEntityResolver());
-
- return this.digester;
+ return this.digester;
}
-
/**
* <p>Translate an array of resource names into an array of resource URLs.</p>
*
* @param names Resource names to translate
*/
private URL[] translate(String[] names) {
-
URL[] results = new URL[names.length];
+
for (int i = 0; i < names.length; i++) {
results[i] = this.getClass().getResource(names[i]);
}
+
return results;
-
}
-
// --------------------------------------------------------- Private Classes
-
/**
* <p>Data bean that stores information related to a component.</p>
*/
class ComponentBean {
-
private String componentClass;
+ private String componentType;
+
public String getComponentClass() {
return this.componentClass;
}
+
public void setComponentClass(String componentClass) {
this.componentClass = componentClass;
}
- private String componentType;
public String getComponentType() {
return this.componentType;
}
+
public void setComponentType(String componentType) {
this.componentType = componentType;
}
-
}
@@ -287,7 +256,6 @@
* <p>Digester <code>Rule</code> for processing components.</p>
*/
class ComponentRule extends Rule {
-
public void begin(String namespace, String name, Attributes attributes) {
getDigester().push(new ComponentBean());
}
@@ -295,9 +263,9 @@
public void end(String namespace, String name) {
ComponentBean bean = (ComponentBean) getDigester().pop();
Application application = (Application) getDigester().peek();
+
application.addComponent(bean.getComponentType(), bean.getComponentClass());
}
-
}
@@ -305,31 +273,33 @@
* <p>Data bean that stores information related to a converter.</p>
*/
class ConverterBean {
-
private String converterClass;
+ private String converterForClass;
+ private String converterId;
+
public String getConverterClass() {
return this.converterClass;
}
+
public void setConverterClass(String converterClass) {
this.converterClass = converterClass;
}
- private String converterForClass;
public String getConverterForClass() {
return this.converterForClass;
}
+
public void setConverterForClass(String converterForClass) {
this.converterForClass = converterForClass;
}
- private String converterId;
public String getConverterId() {
return this.converterId;
}
+
public void setConverterId(String converterId) {
this.converterId = converterId;
}
-
}
@@ -337,7 +307,6 @@
* <p>Digester <code>Rule</code> for processing converers.</p>
*/
class ConverterRule extends Rule {
-
public void begin(String namespace, String name, Attributes attributes) {
getDigester().push(new ConverterBean());
}
@@ -345,59 +314,58 @@
public void end(String namespace, String name) {
ConverterBean bean = (ConverterBean) getDigester().pop();
Application application = (Application) getDigester().peek();
+
if (bean.getConverterId() != null) {
application.addConverter(bean.getConverterId(), bean.getConverterClass());
} else {
Class clazz = null;
+
try {
clazz = this.getClass().getClassLoader().loadClass(bean.getConverterForClass());
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("java.lang.ClassNotFoundException: "
- + bean.getConverterForClass());
+ + bean.getConverterForClass());
}
+
application.addConverter(clazz, bean.getConverterClass());
}
}
-
}
/**
- * <p>Digester <code>Rule</code> for processing render kits.</p>
- */
- class RenderKitRule extends Rule {
-
- public void begin(String namespace, String name, Attributes attributes) {
- RenderKitFactory factory = (RenderKitFactory)
- FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
- getDigester().push(factory.getRenderKit(null, RenderKitFactory.HTML_BASIC_RENDER_KIT));
- }
-
- public void end(String namespace, String name) {
- getDigester().pop();
- }
-
- }
-
-
- /**
* <p>Digester <code>Rule</code> for processing render kit identifiers.</p>
*/
class RenderKitIdRule extends Rule {
-
public void body(String namespace, String name, String text) {
String renderKitId = text.trim();
- RenderKitFactory factory = (RenderKitFactory)
- FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
+ RenderKitFactory factory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
RenderKit renderKit = factory.getRenderKit(null, renderKitId);
+
if (renderKit == null) {
renderKit = new MockRenderKit();
factory.addRenderKit(renderKitId, renderKit);
}
+
digester.pop();
digester.push(renderKit);
}
+ }
+
+ /**
+ * <p>Digester <code>Rule</code> for processing render kits.</p>
+ */
+ class RenderKitRule extends Rule {
+ public void begin(String namespace, String name, Attributes attributes) {
+ RenderKitFactory factory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
+
+ getDigester().push(factory.getRenderKit(null, RenderKitFactory.HTML_BASIC_RENDER_KIT));
+ }
+
+ public void end(String namespace, String name) {
+ getDigester().pop();
+ }
}
@@ -405,31 +373,33 @@
* <p>Data bean that stores information related to a renderer.</p>
*/
class RendererBean {
-
private String componentFamily;
+ private String rendererClass;
+ private String rendererType;
+
public String getComponentFamily() {
return this.componentFamily;
}
+
public void setComponentFamily(String componentFamily) {
this.componentFamily = componentFamily;
}
- private String rendererClass;
public String getRendererClass() {
return this.rendererClass;
}
+
public void setRendererClass(String rendererClass) {
this.rendererClass = rendererClass;
}
- private String rendererType;
public String getRendererType() {
return this.rendererType;
}
+
public void setRendererType(String rendererType) {
this.rendererType = rendererType;
}
-
}
@@ -437,7 +407,6 @@
* <p>Digester <code>Rule</code> for processing renderers.</p>
*/
class RendererRule extends Rule {
-
public void begin(String namespace, String name, Attributes attributes) {
getDigester().push(new RendererBean());
}
@@ -447,18 +416,17 @@
RenderKit kit = (RenderKit) getDigester().peek();
Renderer renderer = null;
Class clazz = null;
+
try {
clazz = this.getClass().getClassLoader().loadClass(bean.getRendererClass());
renderer = (Renderer) clazz.newInstance();
} catch (Exception e) {
- throw new IllegalArgumentException("Exception while trying to instantiate"
- + " renderer class '" + bean.getRendererClass() + "' : "
- + e.getMessage());
+ throw new IllegalArgumentException("Exception while trying to instantiate" + " renderer class '"
+ + bean.getRendererClass() + "' : " + e.getMessage());
}
- kit.addRenderer(bean.getComponentFamily(), bean.getRendererType(),
- renderer);
- }
+ kit.addRenderer(bean.getComponentFamily(), bean.getRendererType(), renderer);
+ }
}
@@ -466,23 +434,24 @@
* <p>Data bean that stores information related to a validator.</p>
*/
class ValidatorBean {
-
private String validatorClass;
+ private String validatorId;
+
public String getValidatorClass() {
return this.validatorClass;
}
+
public void setValidatorClass(String validatorClass) {
this.validatorClass = validatorClass;
}
- private String validatorId;
public String getValidatorId() {
return this.validatorId;
}
+
public void setValidatorId(String validatorId) {
this.validatorId = validatorId;
}
-
}
@@ -490,7 +459,6 @@
* <p>Digester <code>Rule</code> for processing validators.</p>
*/
class ValidatorRule extends Rule {
-
public void begin(String namespace, String name, Attributes attributes) {
getDigester().push(new ValidatorBean());
}
@@ -498,10 +466,8 @@
public void end(String namespace, String name) {
ValidatorBean bean = (ValidatorBean) getDigester().pop();
Application application = (Application) getDigester().peek();
+
application.addValidator(bean.getValidatorId(), bean.getValidatorClass());
}
-
}
-
-
}
Modified: root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/xml/FacesEntityResolver.java
===================================================================
--- root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/xml/FacesEntityResolver.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/main/java/org/ajax4jsf/tests/xml/FacesEntityResolver.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.tests.xml;
import java.io.IOException;
+
import java.net.URL;
import org.xml.sax.EntityResolver;
@@ -31,43 +34,38 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 09.04.2007
- *
+ *
*/
public class FacesEntityResolver implements EntityResolver {
+ private static final String[] PREFIXES = new String[] {"/com/sun/faces/", "/org/apache/myfaces/resource/"};
- private static final String[] PREFIXES = new String[] {
- "/com/sun/faces/", "/org/apache/myfaces/resource/"
- };
-
- /* (non-Javadoc)
- * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
- */
- public InputSource resolveEntity(String publicId, String systemId)
- throws SAXException, IOException {
+ /*
+ * (non-Javadoc)
+ * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
+ */
+ public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
+ if (systemId == null) {
+ return null;
+ }
- if (systemId == null) {
- return null;
- }
+ String fileName;
+ int idx = systemId.lastIndexOf('/');
- String fileName;
-
- int idx = systemId.lastIndexOf('/');
- if (idx == -1) {
- fileName = systemId;
- } else {
- fileName = systemId.substring(idx + 1);
- }
-
- for (int i = 0; i < PREFIXES.length; i++) {
- String prefix = PREFIXES[i];
-
- URL url = getClass().getResource(prefix + fileName);
- if (url != null) {
- return new InputSource(url.openStream());
- }
- }
-
- return null;
- }
+ if (idx == -1) {
+ fileName = systemId;
+ } else {
+ fileName = systemId.substring(idx + 1);
+ }
+ for (int i = 0; i < PREFIXES.length; i++) {
+ String prefix = PREFIXES[i];
+ URL url = getClass().getResource(prefix + fileName);
+
+ if (url != null) {
+ return new InputSource(url.openStream());
+ }
+ }
+
+ return null;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/AjaxStateHolderTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/AjaxStateHolderTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/AjaxStateHolderTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.application;
@@ -11,58 +12,64 @@
*/
public class AjaxStateHolderTest extends AbstractAjax4JsfTestCase {
- /**
- * @param name
- */
- public AjaxStateHolderTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public AjaxStateHolderTest(String name) {
+ super(name);
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.ajax4jsf.application.AjaxStateHolder#getInstance(javax.faces.context.FacesContext)}.
- */
- public void testGetInstance() {
- StateHolder ajaxStateHolder = AjaxStateHolder.getInstance(facesContext);
- assertNotNull(ajaxStateHolder);
- StateHolder ajaxStateHolder2 = AjaxStateHolder.getInstance(facesContext);
- assertSame(ajaxStateHolder, ajaxStateHolder2);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.application.AjaxStateHolder#getInstance(javax.faces.context.FacesContext)}.
+ */
+ public void testGetInstance() {
+ StateHolder ajaxStateHolder = AjaxStateHolder.getInstance(facesContext);
- /**
- * Test method for {@link org.ajax4jsf.application.AjaxStateHolder#getState(java.lang.String, String)}.
- */
- public void testGetState() {
- Object state = new Object();
- Object state2 = new Object();
- StateHolder ajaxStateHolder = AjaxStateHolder.getInstance(facesContext);
- assertNull(ajaxStateHolder.getState("foo", "_id1"));
- ajaxStateHolder.saveState("foo", "_id1", new Object[]{state});
- ajaxStateHolder.saveState("foo", "_id2", new Object[]{state2});
- assertNull(ajaxStateHolder.getState("bar", "_id1"));
- assertSame(state2,ajaxStateHolder.getState("foo",null));
- assertSame(state,ajaxStateHolder.getState("foo","_id1"));
- assertSame(state,ajaxStateHolder.getState("foo","_id3"));
- Object state3 = new Object();
- Object state4 = new Object();
- ajaxStateHolder.saveState("bar", "_id1", new Object[]{state3});
- ajaxStateHolder.saveState("bar", "_id2", new Object[]{state4});
- assertSame(state3,ajaxStateHolder.getState("bar","_id1"));
- assertSame(state,ajaxStateHolder.getState("foo","_id3"));
- }
+ assertNotNull(ajaxStateHolder);
+ StateHolder ajaxStateHolder2 = AjaxStateHolder.getInstance(facesContext);
+ assertSame(ajaxStateHolder, ajaxStateHolder2);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.application.AjaxStateHolder#getState(java.lang.String, String)}.
+ */
+ public void testGetState() {
+ Object state = new Object();
+ Object state2 = new Object();
+ StateHolder ajaxStateHolder = AjaxStateHolder.getInstance(facesContext);
+
+ assertNull(ajaxStateHolder.getState("foo", "_id1"));
+ ajaxStateHolder.saveState("foo", "_id1", new Object[] {state});
+ ajaxStateHolder.saveState("foo", "_id2", new Object[] {state2});
+ assertNull(ajaxStateHolder.getState("bar", "_id1"));
+ assertSame(state2, ajaxStateHolder.getState("foo", null));
+ assertSame(state, ajaxStateHolder.getState("foo", "_id1"));
+ assertSame(state, ajaxStateHolder.getState("foo", "_id3"));
+
+ Object state3 = new Object();
+ Object state4 = new Object();
+
+ ajaxStateHolder.saveState("bar", "_id1", new Object[] {state3});
+ ajaxStateHolder.saveState("bar", "_id2", new Object[] {state4});
+ assertSame(state3, ajaxStateHolder.getState("bar", "_id1"));
+ assertSame(state, ajaxStateHolder.getState("foo", "_id3"));
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/AjaxStateManagerTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/AjaxStateManagerTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/AjaxStateManagerTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.application;
@@ -8,6 +9,7 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
+
import java.util.HashSet;
import javax.faces.FactoryFinder;
@@ -26,174 +28,192 @@
import javax.faces.render.ResponseStateManager;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.apache.shale.test.mock.MockRenderKit;
-
/**
* @author asmirnov
*
*/
public class AjaxStateManagerTest extends AbstractAjax4JsfTestCase {
+ private static final String AJAX_RENDER_KIT = "AJAX";
+ private static final String FACET_A = "facetA";
+ private static final String FACET_B = "facetB";
+ private AjaxStateManager ajaxStateManager;
+ private Object state;
+ private Object treeStructure;
- private static final String FACET_B = "facetB";
- private static final String FACET_A = "facetA";
- private static final String AJAX_RENDER_KIT = "AJAX";
- private AjaxStateManager ajaxStateManager;
-
- private Object treeStructure;
+ /**
+ * @param name
+ */
+ public AjaxStateManagerTest(String name) {
+ super(name);
+ }
- private Object state;
- /**
- * @param name
- */
- public AjaxStateManagerTest(String name) {
- super(name);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- RenderKitFactory renderKitFactory = (RenderKitFactory)
- FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
- renderKit = new MockRenderKit(){
- public ResponseStateManager getResponseStateManager() {
- return new ResponseStateManager(){
+ RenderKitFactory renderKitFactory =
+ (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
- public Object getComponentStateToRestore(FacesContext arg0) {
- return state;
- }
-
- public Object getTreeStructureToRestore(FacesContext arg0,
- String arg1) {
- return treeStructure;
- }
-
- public void writeState(FacesContext context,
- SerializedView serializedView) throws IOException {
- treeStructure = serializedView.getStructure();
- state = serializedView.getState();
- }
-
- };
- }
- };
+ renderKit = new MockRenderKit() {
+ public ResponseStateManager getResponseStateManager() {
+ return new ResponseStateManager() {
+ public Object getComponentStateToRestore(FacesContext arg0) {
+ return state;
+ }
+ public Object getTreeStructureToRestore(FacesContext arg0, String arg1) {
+ return treeStructure;
+ }
+ public void writeState(FacesContext context, SerializedView serializedView) throws IOException {
+ treeStructure = serializedView.getStructure();
+ state = serializedView.getState();
+ }
+ };
+ }
+ };
renderKitFactory.addRenderKit(AJAX_RENDER_KIT, renderKit);
facesContext.getViewRoot().setRenderKitId(AJAX_RENDER_KIT);
- ajaxStateManager = new AjaxStateManager(application.getStateManager());
- application.setStateManager(ajaxStateManager);
- }
+ ajaxStateManager = new AjaxStateManager(application.getStateManager());
+ application.setStateManager(ajaxStateManager);
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- ajaxStateManager = null;
- treeStructure = null;
- state = null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ ajaxStateManager = null;
+ treeStructure = null;
+ state = null;
+ }
- /**
- * Test method for {@link org.ajax4jsf.application.AjaxStateManager#restoreStateFromSession(javax.faces.context.FacesContext, java.lang.String, java.lang.String)}.
- */
- public void testRestoreStateFromSession() {
- Object structure = new Object();
- Object treeState = new Object();
- ajaxStateManager.saveStateInSession(facesContext, structure, treeState);
- treeStructure = UIViewRoot.UNIQUE_ID_PREFIX+"1";
- Object[] stateFromSession = ajaxStateManager.restoreStateFromSession(facesContext, facesContext.getViewRoot().getViewId(), AJAX_RENDER_KIT);
- assertSame(structure, stateFromSession[0]);
- assertSame(treeState, stateFromSession[1]);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.application.AjaxStateManager#restoreStateFromSession(javax.faces.context.FacesContext, java.lang.String, java.lang.String)}.
+ */
+ public void testRestoreStateFromSession() {
+ Object structure = new Object();
+ Object treeState = new Object();
- /**
- * Test method for {@link org.ajax4jsf.application.AjaxStateManager#getLogicalViewId(javax.faces.context.FacesContext)}.
- */
- public void testGetNextViewId() {
- Object nextViewId = ajaxStateManager.getLogicalViewId(facesContext);
- Object expected = ajaxStateManager.getLogicalViewId(facesContext);
- assertTrue(expected.equals(nextViewId));
- ajaxContext.setAjaxRequest(true);
- request.setAttribute(AjaxStateManager.AJAX_VIEW_SEQUENCE, expected);
- nextViewId = ajaxStateManager.getLogicalViewId(facesContext);
- assertEquals(expected, nextViewId);
- }
+ ajaxStateManager.saveStateInSession(facesContext, structure, treeState);
+ treeStructure = UIViewRoot.UNIQUE_ID_PREFIX + "1";
+ Object[] stateFromSession = ajaxStateManager.restoreStateFromSession(facesContext,
+ facesContext.getViewRoot().getViewId(), AJAX_RENDER_KIT);
- /**
- * Test method for {@link org.ajax4jsf.application.AjaxStateManager#getRenderKit(javax.faces.context.FacesContext, java.lang.String)}.
- */
- public void testGetRenderKit() {
- AjaxStateManager stateManager = getAjaxStateManager();
- RenderKit kit = stateManager.getRenderKit(facesContext, AJAX_RENDER_KIT);
- assertSame(renderKit, kit);
- }
-
- public void testTreeNodeApply() throws Exception {
- buildTestTree();
- TreeStructureNode node = new TreeStructureNode();
- node.apply(facesContext, facesContext.getViewRoot(), new HashSet());
- assertEquals(2, node.getChildren().size());
- assertEquals(1, node.getFacets().size());
- TreeStructureNode nodeA = (TreeStructureNode) node.getFacets().get(FACET_A);
- assertNotNull(nodeA);
- assertEquals(1, nodeA.getChildren().size());
- assertEquals(1, nodeA.getFacets().size());
- }
+ assertSame(structure, stateFromSession[0]);
+ assertSame(treeState, stateFromSession[1]);
+ }
- public void testTreeNodeCheckUniqueId() throws Exception {
- buildTestTree();
- TreeStructureNode node = new TreeStructureNode();
- UIViewRoot viewRoot = facesContext.getViewRoot();
- ((UIComponent)viewRoot.getChildren().get(0)).setId(FACET_A);
- ((UIComponent)viewRoot.getChildren().get(1)).setId(FACET_A);
- try {
- node.apply(facesContext, facesContext.getViewRoot(), new HashSet());
- } catch (IllegalStateException e) {
- assertTrue(e.getMessage().startsWith("duplicate"));
- return;
- }
- assertTrue("Duplicate components Id's not detected ",false);
- }
-
-
- public void testTreeNodeSerialisation() throws Exception {
- buildTestTree();
- TreeStructureNode node = new TreeStructureNode();
- node.apply(facesContext, facesContext.getViewRoot(), new HashSet());
- ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
- ObjectOutputStream out = new ObjectOutputStream(byteOut);
- out.writeObject(node);
- ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
- ObjectInputStream in = new ObjectInputStream(byteIn);
- TreeStructureNode nodeIn = (TreeStructureNode) in.readObject();
- assertEquals(2, nodeIn.getChildren().size());
- assertEquals(1, nodeIn.getFacets().size());
- TreeStructureNode nodeA = (TreeStructureNode) nodeIn.getFacets().get(FACET_A);
- assertNotNull(nodeA);
- assertEquals(1, nodeA.getChildren().size());
- assertEquals(1, nodeA.getFacets().size());
-
- }
- /**
- *
- */
- private void buildTestTree() {
- facesContext.getViewRoot().getChildren().add(new UIInput());
- facesContext.getViewRoot().getChildren().add(new UIOutput());
- UIData data = new UIData();
- facesContext.getViewRoot().getFacets().put(FACET_A, data);
- data.getChildren().add(new UIColumn());
- data.getFacets().put(FACET_B, new UIOutput());
- }
+ /**
+ * Test method for {@link org.ajax4jsf.application.AjaxStateManager#getLogicalViewId(javax.faces.context.FacesContext)}.
+ */
+ public void testGetNextViewId() {
+ Object nextViewId = ajaxStateManager.getLogicalViewId(facesContext);
+ Object expected = ajaxStateManager.getLogicalViewId(facesContext);
- /**
- * @return
- */
- private AjaxStateManager getAjaxStateManager() {
- return ajaxStateManager;
- }
+ assertTrue(expected.equals(nextViewId));
+ ajaxContext.setAjaxRequest(true);
+ request.setAttribute(AjaxStateManager.AJAX_VIEW_SEQUENCE, expected);
+ nextViewId = ajaxStateManager.getLogicalViewId(facesContext);
+ assertEquals(expected, nextViewId);
+ }
+ /**
+ * Test method for {@link org.ajax4jsf.application.AjaxStateManager#getRenderKit(javax.faces.context.FacesContext, java.lang.String)}.
+ */
+ public void testGetRenderKit() {
+ AjaxStateManager stateManager = getAjaxStateManager();
+ RenderKit kit = stateManager.getRenderKit(facesContext, AJAX_RENDER_KIT);
+
+ assertSame(renderKit, kit);
+ }
+
+ public void testTreeNodeApply() throws Exception {
+ buildTestTree();
+
+ TreeStructureNode node = new TreeStructureNode();
+
+ node.apply(facesContext, facesContext.getViewRoot(), new HashSet());
+ assertEquals(2, node.getChildren().size());
+ assertEquals(1, node.getFacets().size());
+
+ TreeStructureNode nodeA = (TreeStructureNode) node.getFacets().get(FACET_A);
+
+ assertNotNull(nodeA);
+ assertEquals(1, nodeA.getChildren().size());
+ assertEquals(1, nodeA.getFacets().size());
+ }
+
+ public void testTreeNodeCheckUniqueId() throws Exception {
+ buildTestTree();
+
+ TreeStructureNode node = new TreeStructureNode();
+ UIViewRoot viewRoot = facesContext.getViewRoot();
+
+ ((UIComponent) viewRoot.getChildren().get(0)).setId(FACET_A);
+ ((UIComponent) viewRoot.getChildren().get(1)).setId(FACET_A);
+
+ try {
+ node.apply(facesContext, facesContext.getViewRoot(), new HashSet());
+ } catch (IllegalStateException e) {
+ assertTrue(e.getMessage().startsWith("duplicate"));
+
+ return;
+ }
+
+ assertTrue("Duplicate components Id's not detected ", false);
+ }
+
+ public void testTreeNodeSerialisation() throws Exception {
+ buildTestTree();
+
+ TreeStructureNode node = new TreeStructureNode();
+
+ node.apply(facesContext, facesContext.getViewRoot(), new HashSet());
+
+ ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
+ ObjectOutputStream out = new ObjectOutputStream(byteOut);
+
+ out.writeObject(node);
+
+ ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
+ ObjectInputStream in = new ObjectInputStream(byteIn);
+ TreeStructureNode nodeIn = (TreeStructureNode) in.readObject();
+
+ assertEquals(2, nodeIn.getChildren().size());
+ assertEquals(1, nodeIn.getFacets().size());
+
+ TreeStructureNode nodeA = (TreeStructureNode) nodeIn.getFacets().get(FACET_A);
+
+ assertNotNull(nodeA);
+ assertEquals(1, nodeA.getChildren().size());
+ assertEquals(1, nodeA.getFacets().size());
+ }
+
+ /**
+ *
+ */
+ private void buildTestTree() {
+ facesContext.getViewRoot().getChildren().add(new UIInput());
+ facesContext.getViewRoot().getChildren().add(new UIOutput());
+
+ UIData data = new UIData();
+
+ facesContext.getViewRoot().getFacets().put(FACET_A, data);
+ data.getChildren().add(new UIColumn());
+ data.getFacets().put(FACET_B, new UIOutput());
+ }
+
+ /**
+ * @return
+ */
+ private AjaxStateManager getAjaxStateManager() {
+ return ajaxStateManager;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/ComponentLoaderTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/ComponentLoaderTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/application/ComponentLoaderTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.application;
@@ -16,52 +17,53 @@
*
*/
public class ComponentLoaderTest extends TestCase {
+ private URLClassLoader classLoader;
+ private ClassLoader contextClassLoader;
+ private ComponentsLoaderImpl loader;
- private ComponentsLoaderImpl loader;
- private ClassLoader contextClassLoader;
- private URLClassLoader classLoader;
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ contextClassLoader = Thread.currentThread().getContextClassLoader();
+ classLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader());
+ Thread.currentThread().setContextClassLoader(classLoader);
+ loader = new ComponentsLoaderImpl();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- contextClassLoader = Thread.currentThread().getContextClassLoader();
- classLoader = new URLClassLoader(new URL[0],
- this.getClass().getClassLoader());
- Thread.currentThread().setContextClassLoader(classLoader);
- loader = new ComponentsLoaderImpl();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ loader = null;
+ Thread.currentThread().setContextClassLoader(contextClassLoader);
+ contextClassLoader = null;
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- loader = null;
- Thread.currentThread().setContextClassLoader(contextClassLoader);
- contextClassLoader = null;
- }
+ /**
+ * Test method for {@link org.ajax4jsf.application.ComponentsLoaderImpl#createComponent(java.lang.String)}.
+ */
+ public void testCreateComponent() {
+ UIComponent input = loader.createComponent(UIInput.class.getName());
- /**
- * Test method for {@link org.ajax4jsf.application.ComponentsLoaderImpl#createComponent(java.lang.String)}.
- */
- public void testCreateComponent() {
- UIComponent input = loader.createComponent(UIInput.class.getName());
- assertNotNull(input);
- assertEquals(UIInput.class, input.getClass());
- }
+ assertNotNull(input);
+ assertEquals(UIInput.class, input.getClass());
+ }
- /**
- * Test method for {@link org.ajax4jsf.application.ComponentsLoaderImpl#transform(java.lang.Object)}.
- */
- public void testTransform() {
- Object componentClass = loader.transform(UIInput.class.getName());
- assertSame(UIInput.class, componentClass);
-
- }
+ /**
+ * Test method for {@link org.ajax4jsf.application.ComponentsLoaderImpl#transform(java.lang.Object)}.
+ */
+ public void testTransform() {
+ Object componentClass = loader.transform(UIInput.class.getName());
- public void testGetLoader() throws Exception {
- assertSame(classLoader,loader.getClassLoader());
- }
+ assertSame(UIInput.class, componentClass);
+ }
+
+ public void testGetLoader() throws Exception {
+ assertSame(classLoader, loader.getClassLoader());
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/component/AjaxViewRootTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/component/AjaxViewRootTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/component/AjaxViewRootTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -4,6 +4,7 @@
import java.util.List;
import javax.el.MethodExpression;
+
import javax.faces.component.UIComponent;
import javax.faces.component.UIPanel;
import javax.faces.context.FacesContext;
@@ -19,271 +20,289 @@
import org.ajax4jsf.tests.MockUIComponent;
public class AjaxViewRootTest extends AbstractAjax4JsfTestCase {
+ private AjaxViewRoot _ajaxRoot;
+ private MockUIComponent _mockComponent;
+ private MockUIComponent _panel;
+ private PhaseListenerImplementation _phaseListener;
+ private PhaseListenerImplementation _testListener;
- /**
- * @author asmirnov
- *
- */
- public static class InvokerCallbackImpl implements InvokerCallback {
-
- private int runsRoot = 0;
-
- private List<UIComponent> callbackComponents = new ArrayList<UIComponent>();
-
+ public AjaxViewRootTest(String name) {
+ super(name);
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.InvokerCallback#invokeContextCallback(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
- */
- public void invokeContextCallback(FacesContext context,
- UIComponent component) {
- callbackComponents.add(component);
- }
+ public void setUp() throws Exception {
+ super.setUp();
+ _ajaxRoot = new AjaxViewRoot();
+ _ajaxRoot.setViewId("/viewId");
+ _ajaxRoot.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
+ _testListener = new PhaseListenerImplementation();
+ externalContext.getRequestMap().put("listener", _testListener);
+ facesContext.setViewRoot(_ajaxRoot);
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.InvokerCallback#invokeRoot(javax.faces.context.FacesContext)
- */
- public void invokeRoot(FacesContext context) {
- runsRoot++;
+ public void tearDown() throws Exception {
+ _ajaxRoot = null;
+ _testListener = null;
+ super.tearDown();
+ }
- }
+ public final void testProcessPhaseListeners() {
+ MethodExpression beforeExpression = application.getExpressionFactory().createMethodExpression(elContext,
+ "#{listener.beforePhase}", null, new Class<?>[] {PhaseEvent.class});
+ MethodExpression afterExpression = application.getExpressionFactory().createMethodExpression(elContext,
+ "#{listener.afterPhase}", null, new Class<?>[] {PhaseEvent.class});
- }
+ _ajaxRoot.setBeforePhaseListener(beforeExpression);
+ _ajaxRoot.setAfterPhaseListener(afterExpression);
- public static final class PhaseListenerImplementation implements PhaseListener {
- private int runsBefore = 0;
- private int runsAfter = 0;
- private PhaseId phase = PhaseId.ANY_PHASE;
+ PhaseListenerImplementation phaseListener = new PhaseListenerImplementation();
- public void afterPhase(PhaseEvent event) {
- runsAfter++;
- }
+ _ajaxRoot.addPhaseListener(phaseListener);
+ _ajaxRoot.processPhaseListeners(facesContext, PhaseId.RESTORE_VIEW, true);
+ assertEquals(1, this._testListener.runsBefore);
+ assertEquals(0, this._testListener.runsAfter);
+ assertEquals(1, phaseListener.runsBefore);
+ assertEquals(0, phaseListener.runsAfter);
+ phaseListener.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
+ _ajaxRoot.processPhaseListeners(facesContext, PhaseId.RESTORE_VIEW, false);
+ assertEquals(1, this._testListener.runsBefore);
+ assertEquals(1, this._testListener.runsAfter);
+ assertEquals(1, phaseListener.runsBefore);
+ assertEquals(0, phaseListener.runsAfter);
+ }
- public void beforePhase(PhaseEvent event) {
- runsBefore++;
-
- }
+ public final void testCreatePhaseEvent() {
+ PhaseEvent phaseEvent = _ajaxRoot.createPhaseEvent(facesContext, PhaseId.APPLY_REQUEST_VALUES);
- public PhaseId getPhaseId() {
-
- return phase;
- }
+ assertSame(facesContext, phaseEvent.getFacesContext());
+ assertSame(PhaseId.APPLY_REQUEST_VALUES, phaseEvent.getPhaseId());
+ assertSame(lifecycle, phaseEvent.getSource());
+ }
- /**
- * @return the runsBefore
- */
- int getRunsBefore() {
- return runsBefore;
- }
+ public final void testProcessPhase() {
+ prepareView(PhaseId.APPLY_REQUEST_VALUES);
- /**
- * @return the runsAfter
- */
- int getRunsAfter() {
- return runsAfter;
- }
+ InvokerCallbackImpl callback = new InvokerCallbackImpl() {
+ @Override
+ public void invokeContextCallback(FacesContext context, UIComponent component) {
+ super.invokeContextCallback(context, component);
+ component.processDecodes(context);
+ }
+ };
- /**
- * @param phase the phase to set
- */
- void setPhaseId(PhaseId phase) {
- this.phase = phase;
- }
- }
+ _ajaxRoot.processPhase(facesContext, PhaseId.APPLY_REQUEST_VALUES, callback);
- private AjaxViewRoot _ajaxRoot;
- private PhaseListenerImplementation _testListener;
- private PhaseListenerImplementation _phaseListener;
- private MockUIComponent _panel;
- private MockUIComponent _mockComponent;
+ // Check phase listeners calls.
+ assertEquals(1, this._testListener.runsBefore);
+ assertEquals(1, this._testListener.runsAfter);
+ assertEquals(1, _phaseListener.runsBefore);
+ assertEquals(1, _phaseListener.runsAfter);
- public AjaxViewRootTest(String name) {
- super(name);
- }
+ // Check callbacks runs.
+ assertEquals(1, callback.runsRoot);
+ assertEquals(1, callback.callbackComponents.size());
+ assertSame(_panel, callback.callbackComponents.get(0));
+ assertEquals(1, _mockComponent.getRunsDecode());
+ }
- public void setUp() throws Exception {
- super.setUp();
- _ajaxRoot = new AjaxViewRoot();
- _ajaxRoot.setViewId("/viewId");
- _ajaxRoot.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
- _testListener = new PhaseListenerImplementation();
- externalContext.getRequestMap().put("listener", _testListener);
- facesContext.setViewRoot(_ajaxRoot);
- }
+ public final void testProcessAjaxPhase() {
+ externalContext.addRequestParameterMap(AjaxContext.AJAX_CONTEXT_KEY, _ajaxRoot.getClientId(facesContext));
+ ajaxContext.decode(facesContext);
+ prepareView(PhaseId.APPLY_REQUEST_VALUES);
- public void tearDown() throws Exception {
- _ajaxRoot = null;
- _testListener = null;
- super.tearDown();
- }
+ InvokerCallbackImpl callback = new InvokerCallbackImpl() {
+ @Override
+ public void invokeContextCallback(FacesContext context, UIComponent component) {
+ super.invokeContextCallback(context, component);
+ component.processDecodes(context);
+ }
+ };
- public final void testProcessPhaseListeners() {
- MethodExpression beforeExpression = application.getExpressionFactory().createMethodExpression(elContext, "#{listener.beforePhase}", null, new Class<?>[]{PhaseEvent.class});
- MethodExpression afterExpression = application.getExpressionFactory().createMethodExpression(elContext, "#{listener.afterPhase}", null, new Class<?>[]{PhaseEvent.class});
- _ajaxRoot.setBeforePhaseListener(beforeExpression);
- _ajaxRoot.setAfterPhaseListener(afterExpression);
- PhaseListenerImplementation phaseListener = new PhaseListenerImplementation();
- _ajaxRoot.addPhaseListener(phaseListener);
- _ajaxRoot.processPhaseListeners(facesContext, PhaseId.RESTORE_VIEW, true);
- assertEquals(1, this._testListener.runsBefore);
- assertEquals(0, this._testListener.runsAfter);
- assertEquals(1, phaseListener.runsBefore);
- assertEquals(0, phaseListener.runsAfter);
- phaseListener.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
- _ajaxRoot.processPhaseListeners(facesContext, PhaseId.RESTORE_VIEW, false);
- assertEquals(1, this._testListener.runsBefore);
- assertEquals(1, this._testListener.runsAfter);
- assertEquals(1, phaseListener.runsBefore);
- assertEquals(0, phaseListener.runsAfter);
- }
+ _ajaxRoot.processPhase(facesContext, PhaseId.APPLY_REQUEST_VALUES, callback);
- public final void testCreatePhaseEvent() {
- PhaseEvent phaseEvent = _ajaxRoot.createPhaseEvent(facesContext, PhaseId.APPLY_REQUEST_VALUES);
- assertSame(facesContext, phaseEvent.getFacesContext());
- assertSame(PhaseId.APPLY_REQUEST_VALUES, phaseEvent.getPhaseId());
- assertSame(lifecycle, phaseEvent.getSource());
- }
+ // Check phase listeners calls.
+ assertEquals(1, this._testListener.runsBefore);
+ assertEquals(1, this._testListener.runsAfter);
+ assertEquals(1, _phaseListener.runsBefore);
+ assertEquals(1, _phaseListener.runsAfter);
- public final void testProcessPhase() {
- prepareView(PhaseId.APPLY_REQUEST_VALUES);
- InvokerCallbackImpl callback = new InvokerCallbackImpl(){
- @Override
- public void invokeContextCallback(FacesContext context,
- UIComponent component) {
- super.invokeContextCallback(context, component);
- component.processDecodes(context);
- }
- };
- _ajaxRoot.processPhase(facesContext, PhaseId.APPLY_REQUEST_VALUES, callback);
- // Check phase listeners calls.
- assertEquals(1, this._testListener.runsBefore);
- assertEquals(1, this._testListener.runsAfter);
- assertEquals(1, _phaseListener.runsBefore);
- assertEquals(1, _phaseListener.runsAfter);
- // Check callbacks runs.
- assertEquals(1, callback.runsRoot);
- assertEquals(1, callback.callbackComponents.size());
- assertSame(_panel,callback.callbackComponents.get(0));
- assertEquals(1, _mockComponent.getRunsDecode());
+ // Check callbacks runs.
+ assertEquals(1, callback.runsRoot);
+ assertEquals(1, callback.callbackComponents.size());
+ assertSame(_panel, callback.callbackComponents.get(0));
+ assertEquals(1, _mockComponent.getRunsDecode());
+ }
- }
+ public final void testProcessAjaxRegionPhase() {
+ prepareView(PhaseId.APPLY_REQUEST_VALUES);
+ externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME,
+ _mockComponent.getClientId(facesContext));
+ ajaxContext.decode(facesContext);
- public final void testProcessAjaxPhase() {
- externalContext.addRequestParameterMap(AjaxContext.AJAX_CONTEXT_KEY, _ajaxRoot.getClientId(facesContext));
- ajaxContext.decode(facesContext);
- prepareView(PhaseId.APPLY_REQUEST_VALUES);
- InvokerCallbackImpl callback = new InvokerCallbackImpl(){
- @Override
- public void invokeContextCallback(FacesContext context,
- UIComponent component) {
- super.invokeContextCallback(context, component);
- component.processDecodes(context);
- }
- };
- _ajaxRoot.processPhase(facesContext, PhaseId.APPLY_REQUEST_VALUES, callback);
- // Check phase listeners calls.
- assertEquals(1, this._testListener.runsBefore);
- assertEquals(1, this._testListener.runsAfter);
- assertEquals(1, _phaseListener.runsBefore);
- assertEquals(1, _phaseListener.runsAfter);
- // Check callbacks runs.
- assertEquals(1, callback.runsRoot);
- assertEquals(1, callback.callbackComponents.size());
- assertSame(_panel,callback.callbackComponents.get(0));
- assertEquals(1, _mockComponent.getRunsDecode());
+ InvokerCallbackImpl callback = new InvokerCallbackImpl() {
+ @Override
+ public void invokeContextCallback(FacesContext context, UIComponent component) {
+ super.invokeContextCallback(context, component);
+ component.processDecodes(context);
+ }
+ };
- }
+ _ajaxRoot.processPhase(facesContext, PhaseId.APPLY_REQUEST_VALUES, callback);
- public final void testProcessAjaxRegionPhase() {
- prepareView(PhaseId.APPLY_REQUEST_VALUES);
- externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME, _mockComponent.getClientId(facesContext));
- ajaxContext.decode(facesContext);
- InvokerCallbackImpl callback = new InvokerCallbackImpl(){
- @Override
- public void invokeContextCallback(FacesContext context,
- UIComponent component) {
- super.invokeContextCallback(context, component);
- component.processDecodes(context);
- }
- };
- _ajaxRoot.processPhase(facesContext, PhaseId.APPLY_REQUEST_VALUES, callback);
- // Check phase listeners calls.
- assertEquals(1, this._testListener.runsBefore);
- assertEquals(1, this._testListener.runsAfter);
- assertEquals(1, _phaseListener.runsBefore);
- assertEquals(1, _phaseListener.runsAfter);
- // Check callbacks runs.
- assertEquals(0, callback.runsRoot);
- assertEquals(1, callback.callbackComponents.size());
- assertSame(_mockComponent,callback.callbackComponents.get(0));
- assertEquals(1, _mockComponent.getRunsDecode());
+ // Check phase listeners calls.
+ assertEquals(1, this._testListener.runsBefore);
+ assertEquals(1, this._testListener.runsAfter);
+ assertEquals(1, _phaseListener.runsBefore);
+ assertEquals(1, _phaseListener.runsAfter);
- }
- /**
- * @param phaseId TODO
- *
- */
- private void prepareView(PhaseId phaseId) {
- MethodExpression beforeExpression = application.getExpressionFactory().createMethodExpression(elContext, "#{listener.beforePhase}", null, new Class<?>[]{PhaseEvent.class});
- MethodExpression afterExpression = application.getExpressionFactory().createMethodExpression(elContext, "#{listener.afterPhase}", null, new Class<?>[]{PhaseEvent.class});
- _ajaxRoot.setBeforePhaseListener(beforeExpression);
- _ajaxRoot.setAfterPhaseListener(afterExpression);
- _phaseListener = new PhaseListenerImplementation();
- _phaseListener.setPhaseId(phaseId);
- _ajaxRoot.addPhaseListener(_phaseListener);
- _panel = new MockUIComponent();
- _panel.setId("panel");
- _mockComponent = new MockUIComponent();
- _mockComponent.setId("component");
- _panel.getChildren().add(_mockComponent);
- _ajaxRoot.getChildren().add(_panel);
- }
+ // Check callbacks runs.
+ assertEquals(0, callback.runsRoot);
+ assertEquals(1, callback.callbackComponents.size());
+ assertSame(_mockComponent, callback.callbackComponents.get(0));
+ assertEquals(1, _mockComponent.getRunsDecode());
+ }
+ /**
+ * @param phaseId TODO
+ *
+ */
+ private void prepareView(PhaseId phaseId) {
+ MethodExpression beforeExpression = application.getExpressionFactory().createMethodExpression(elContext,
+ "#{listener.beforePhase}", null, new Class<?>[] {PhaseEvent.class});
+ MethodExpression afterExpression = application.getExpressionFactory().createMethodExpression(elContext,
+ "#{listener.afterPhase}", null, new Class<?>[] {PhaseEvent.class});
-
- public final void testProcessDecodes() {
- prepareView(PhaseId.APPLY_REQUEST_VALUES);
- externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME, _mockComponent.getClientId(facesContext));
- ajaxContext.decode(facesContext);
- _ajaxRoot.processDecodes(facesContext);
- // Check phase listeners calls.
- assertEquals(1, this._testListener.runsBefore);
- assertEquals(1, this._testListener.runsAfter);
- assertEquals(1, _phaseListener.runsBefore);
- assertEquals(1, _phaseListener.runsAfter);
- assertEquals(0, _panel.getRunsDecode());
- assertEquals(1, _mockComponent.getRunsDecode());
- }
-
- public final void testQueueEventFacesEvent() {
- // fail("Not yet implemented");
- }
+ _ajaxRoot.setBeforePhaseListener(beforeExpression);
+ _ajaxRoot.setAfterPhaseListener(afterExpression);
+ _phaseListener = new PhaseListenerImplementation();
+ _phaseListener.setPhaseId(phaseId);
+ _ajaxRoot.addPhaseListener(_phaseListener);
+ _panel = new MockUIComponent();
+ _panel.setId("panel");
+ _mockComponent = new MockUIComponent();
+ _mockComponent.setId("component");
+ _panel.getChildren().add(_mockComponent);
+ _ajaxRoot.getChildren().add(_panel);
+ }
- public final void testBroadcastEvents() {
- // fail("Not yet implemented");
- }
+ public final void testProcessDecodes() {
+ prepareView(PhaseId.APPLY_REQUEST_VALUES);
+ externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME,
+ _mockComponent.getClientId(facesContext));
+ ajaxContext.decode(facesContext);
+ _ajaxRoot.processDecodes(facesContext);
- public final void testProcessEvents() {
- // fail("Not yet implemented");
- }
+ // Check phase listeners calls.
+ assertEquals(1, this._testListener.runsBefore);
+ assertEquals(1, this._testListener.runsAfter);
+ assertEquals(1, _phaseListener.runsBefore);
+ assertEquals(1, _phaseListener.runsAfter);
+ assertEquals(0, _panel.getRunsDecode());
+ assertEquals(1, _mockComponent.getRunsDecode());
+ }
- public final void testBroadcastAjaxEvents() {
- // fail("Not yet implemented");
- }
+ public final void testQueueEventFacesEvent() {
- public final void testGetEventsQueue() {
- // fail("Not yet implemented");
- }
+ // fail("Not yet implemented");
+ }
- public final void testGetEvents() {
- // fail("Not yet implemented");
- }
+ public final void testBroadcastEvents() {
- public final void testGetAjaxEventsQueue() {
- // fail("Not yet implemented");
- }
+ // fail("Not yet implemented");
+ }
- public final void testClearEvents() {
- // fail("Not yet implemented");
- }
+ public final void testProcessEvents() {
+ // fail("Not yet implemented");
+ }
+
+ public final void testBroadcastAjaxEvents() {
+
+ // fail("Not yet implemented");
+ }
+
+ public final void testGetEventsQueue() {
+
+ // fail("Not yet implemented");
+ }
+
+ public final void testGetEvents() {
+
+ // fail("Not yet implemented");
+ }
+
+ public final void testGetAjaxEventsQueue() {
+
+ // fail("Not yet implemented");
+ }
+
+ public final void testClearEvents() {
+
+ // fail("Not yet implemented");
+ }
+
+ /**
+ * @author asmirnov
+ *
+ */
+ public static class InvokerCallbackImpl implements InvokerCallback {
+ private int runsRoot = 0;
+ private List<UIComponent> callbackComponents = new ArrayList<UIComponent>();
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.InvokerCallback#invokeContextCallback(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+ */
+ public void invokeContextCallback(FacesContext context, UIComponent component) {
+ callbackComponents.add(component);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.InvokerCallback#invokeRoot(javax.faces.context.FacesContext)
+ */
+ public void invokeRoot(FacesContext context) {
+ runsRoot++;
+ }
+ }
+
+
+ public static final class PhaseListenerImplementation implements PhaseListener {
+ private int runsAfter = 0;
+ private int runsBefore = 0;
+ private PhaseId phase = PhaseId.ANY_PHASE;
+
+ public void afterPhase(PhaseEvent event) {
+ runsAfter++;
+ }
+
+ public void beforePhase(PhaseEvent event) {
+ runsBefore++;
+ }
+
+ public PhaseId getPhaseId() {
+ return phase;
+ }
+
+ /**
+ * @return the runsBefore
+ */
+ int getRunsBefore() {
+ return runsBefore;
+ }
+
+ /**
+ * @return the runsAfter
+ */
+ int getRunsAfter() {
+ return runsAfter;
+ }
+
+ /**
+ * @param phase the phase to set
+ */
+ void setPhaseId(PhaseId phase) {
+ this.phase = phase;
+ }
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/AjaxContextImplTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/AjaxContextImplTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/AjaxContextImplTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.context;
@@ -13,77 +14,76 @@
*
*/
public class AjaxContextImplTest extends AbstractAjax4JsfTestCase {
+ private static final String FOO_BAR = "foo:bar";
- private static final String FOO_BAR = "foo:bar";
+ /**
+ * @param name
+ */
+ public AjaxContextImplTest(String name) {
+ super(name);
+ }
- /**
- * @param name
- */
- public AjaxContextImplTest(String name) {
- super(name);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ /**
+ * Test method for {@link org.ajax4jsf.context.AjaxContextImpl#decode(javax.faces.context.FacesContext)}.
+ */
+ public void testDecode0() {
+ ajaxContext.decode(facesContext);
+ assertFalse(ajaxContext.isAjaxRequest());
+ assertNull(ajaxContext.getSubmittedRegionClientId());
+ assertNull(ajaxContext.getAjaxSingleClientId());
+ }
- /**
- * Test method for {@link org.ajax4jsf.context.AjaxContextImpl#decode(javax.faces.context.FacesContext)}.
- */
- public void testDecode0() {
- ajaxContext.decode(facesContext);
- assertFalse(ajaxContext.isAjaxRequest());
- assertNull(ajaxContext.getSubmittedRegionClientId());
- assertNull(ajaxContext.getAjaxSingleClientId());
- }
+ /**
+ * Test method for {@link org.ajax4jsf.context.AjaxContextImpl#decode(javax.faces.context.FacesContext)}.
+ */
+ public void testDecode1() {
+ request.addParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME, FOO_BAR);
+ externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME, FOO_BAR);
+ ajaxContext.decode(facesContext);
+ assertTrue(ajaxContext.isAjaxRequest());
+ assertEquals(FOO_BAR, ajaxContext.getSubmittedRegionClientId());
+ assertNull(ajaxContext.getAjaxSingleClientId());
+ }
- /**
- * Test method for {@link org.ajax4jsf.context.AjaxContextImpl#decode(javax.faces.context.FacesContext)}.
- */
- public void testDecode1() {
- request.addParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME, FOO_BAR);
- externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME, FOO_BAR);
- ajaxContext.decode(facesContext);
- assertTrue(ajaxContext.isAjaxRequest());
- assertEquals(FOO_BAR, ajaxContext.getSubmittedRegionClientId());
- assertNull(ajaxContext.getAjaxSingleClientId());
- }
+ /**
+ * Test method for {@link org.ajax4jsf.context.AjaxContextImpl#decode(javax.faces.context.FacesContext)}.
+ */
+ public void testDecode2() {
+ externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME, FOO_BAR);
+ externalContext.addRequestParameterMap(AjaxRendererUtils.AJAX_SINGLE_PARAMETER_NAME, FOO_BAR);
+ ajaxContext.decode(facesContext);
+ assertTrue(ajaxContext.isAjaxRequest());
+ assertEquals(FOO_BAR, ajaxContext.getSubmittedRegionClientId());
+ assertEquals(FOO_BAR, ajaxContext.getAjaxSingleClientId());
+ }
- /**
- * Test method for {@link org.ajax4jsf.context.AjaxContextImpl#decode(javax.faces.context.FacesContext)}.
- */
- public void testDecode2() {
- externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME, FOO_BAR);
- externalContext.addRequestParameterMap(AjaxRendererUtils.AJAX_SINGLE_PARAMETER_NAME, FOO_BAR);
- ajaxContext.decode(facesContext);
- assertTrue(ajaxContext.isAjaxRequest());
- assertEquals(FOO_BAR, ajaxContext.getSubmittedRegionClientId());
- assertEquals(FOO_BAR, ajaxContext.getAjaxSingleClientId());
- }
- /**
- * Test method for {@link org.ajax4jsf.context.AjaxContextImpl#release()}.
- */
- public void testRelease() {
-
- }
+ /**
+ * Test method for {@link org.ajax4jsf.context.AjaxContextImpl#release()}.
+ */
+ public void testRelease() {}
- public void testGetCurrentInstance() throws Exception {
- this.ajaxContext = null;
- request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY);
- externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME, FOO_BAR);
- ajaxContext = AjaxContext.getCurrentInstance(facesContext);
- assertTrue(ajaxContext.isAjaxRequest());
- assertEquals(FOO_BAR, ajaxContext.getSubmittedRegionClientId());
-
- }
+ public void testGetCurrentInstance() throws Exception {
+ this.ajaxContext = null;
+ request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY);
+ externalContext.addRequestParameterMap(AjaxContainerRenderer.AJAX_PARAMETER_NAME, FOO_BAR);
+ ajaxContext = AjaxContext.getCurrentInstance(facesContext);
+ assertTrue(ajaxContext.isAjaxRequest());
+ assertEquals(FOO_BAR, ajaxContext.getSubmittedRegionClientId());
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/AjaxContextTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/AjaxContextTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/AjaxContextTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -5,41 +5,44 @@
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
public class AjaxContextTest extends AbstractAjax4JsfTestCase {
+ public AjaxContextTest(String name) {
+ super(name);
+ }
- public AjaxContextTest(String name) {
- super(name);
- }
+ public void setUp() throws Exception {
+ super.setUp();
+ }
- public void setUp() throws Exception {
- super.setUp();
- }
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ public void testGetCurrentInstance() {
+ AjaxContext ajaxContext2 = AjaxContext.getCurrentInstance();
- public void testGetCurrentInstance() {
- AjaxContext ajaxContext2 = AjaxContext.getCurrentInstance();
- assertSame(ajaxContext, ajaxContext2);
- }
+ assertSame(ajaxContext, ajaxContext2);
+ }
- public void testGetCurrentInstanceFacesContext() {
- this.ajaxContext = null;
- request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY);
- ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- ClassLoader loader = new ClassLoader(contextClassLoader){
- @Override
- public URL getResource(String name) {
- if(AjaxContext.SERVICE_RESOURCE.equals(name)){
- return super.getResource("META-INF/ajaxContext.txt");
- } else {
- return super.getResource(name);
- }
- }
- };
- Thread.currentThread().setContextClassLoader(loader);
- AjaxContext ajaxContext2 = AjaxContext.getCurrentInstance(facesContext);
- assertSame(MockAjaxContext.class,ajaxContext2.getClass());
- }
+ public void testGetCurrentInstanceFacesContext() {
+ this.ajaxContext = null;
+ request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY);
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ ClassLoader loader = new ClassLoader(contextClassLoader) {
+ @Override
+ public URL getResource(String name) {
+ if (AjaxContext.SERVICE_RESOURCE.equals(name)) {
+ return super.getResource("META-INF/ajaxContext.txt");
+ } else {
+ return super.getResource(name);
+ }
+ }
+ };
+
+ Thread.currentThread().setContextClassLoader(loader);
+
+ AjaxContext ajaxContext2 = AjaxContext.getCurrentInstance(facesContext);
+
+ assertSame(MockAjaxContext.class, ajaxContext2.getClass());
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/MockAjaxContext.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/MockAjaxContext.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/context/MockAjaxContext.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,9 +1,11 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.context;
import java.io.IOException;
+
import java.util.Map;
import java.util.Set;
@@ -16,295 +18,335 @@
*/
public class MockAjaxContext extends AjaxContext {
- /**
- *
- */
- public MockAjaxContext() {
- // TODO Auto-generated constructor stub
- }
+ /**
+ *
+ */
+ public MockAjaxContext() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#addComponentToAjaxRender(javax.faces.component.UIComponent, java.lang.String)
- */
- @Override
- public void addComponentToAjaxRender(UIComponent base, String id) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated constructor stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#addComponentToAjaxRender(javax.faces.component.UIComponent, java.lang.String)
+ */
+ @Override
+ public void addComponentToAjaxRender(UIComponent base, String id) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#addComponentToAjaxRender(javax.faces.component.UIComponent)
- */
- @Override
- public void addComponentToAjaxRender(UIComponent component) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#addComponentToAjaxRender(javax.faces.component.UIComponent)
+ */
+ @Override
+ public void addComponentToAjaxRender(UIComponent component) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#addRegionsFromComponent(javax.faces.component.UIComponent)
- */
- @Override
- public void addRegionsFromComponent(UIComponent component) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#addRegionsFromComponent(javax.faces.component.UIComponent)
+ */
+ @Override
+ public void addRegionsFromComponent(UIComponent component) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#addRenderedArea(java.lang.String)
- */
- @Override
- public void addRenderedArea(String id) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#addRenderedArea(java.lang.String)
+ */
+ @Override
+ public void addRenderedArea(String id) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#decode(javax.faces.context.FacesContext)
- */
- @Override
- public void decode(FacesContext context) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#decode(javax.faces.context.FacesContext)
+ */
+ @Override
+ public void decode(FacesContext context) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#encodeAjaxBegin(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
- */
- @Override
- public void encodeAjaxBegin(FacesContext context)
- throws IOException {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#encodeAjaxBegin(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+ */
+ @Override
+ public void encodeAjaxBegin(FacesContext context) throws IOException {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#encodeAjaxEnd(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
- */
- @Override
- public void encodeAjaxEnd(FacesContext context)
- throws IOException {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#encodeAjaxEnd(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+ */
+ @Override
+ public void encodeAjaxEnd(FacesContext context) throws IOException {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getAjaxActionURL(javax.faces.context.FacesContext)
- */
- @Override
- public String getAjaxActionURL(FacesContext context) {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getAjaxActionURL()
- */
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getAjaxActionURL(javax.faces.context.FacesContext)
+ */
+ @Override
+ public String getAjaxActionURL(FacesContext context) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getAjaxAreasToRender()
- */
- @Override
- public Set<String> getAjaxAreasToRender() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getAjaxRenderedAreas()
- */
- @Override
- public Set<String> getAjaxRenderedAreas() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getAjaxActionURL()
+ */
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getAjaxSingleClientId()
- */
- @Override
- public String getAjaxSingleClientId() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getAjaxAreasToRender()
+ */
+ @Override
+ public Set<String> getAjaxAreasToRender() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getCommonAjaxParameters()
- */
- @Override
- public Map<String, Object> getCommonAjaxParameters() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getOncomplete()
- */
- @Override
- public Object getOncomplete() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getAjaxRenderedAreas()
+ */
+ @Override
+ public Set<String> getAjaxRenderedAreas() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getResponseData()
- */
- @Override
- public Object getResponseData() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getResponseDataMap()
- */
- @Override
- public Map<String, Object> getResponseDataMap() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getAjaxSingleClientId()
+ */
+ @Override
+ public String getAjaxSingleClientId() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getSubmittedRegionClientId(javax.faces.context.FacesContext)
- */
- @Override
- public String getSubmittedRegionClientId() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#getViewIdHolder()
- */
- @Override
- public ViewIdHolder getViewIdHolder() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getCommonAjaxParameters()
+ */
+ @Override
+ public Map<String, Object> getCommonAjaxParameters() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#isAjaxRequest(javax.faces.context.FacesContext)
- */
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#isAjaxRequest()
- */
- @Override
- public boolean isAjaxRequest() {
- // TODO Auto-generated method stub
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getOncomplete()
+ */
+ @Override
+ public Object getOncomplete() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#isSelfRender()
- */
- @Override
- public boolean isSelfRender() {
- // TODO Auto-generated method stub
- return false;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#release()
- */
- @Override
- public void release() {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getResponseData()
+ */
+ @Override
+ public Object getResponseData() {
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#removeRenderedArea(java.lang.String)
- */
- @Override
- public boolean removeRenderedArea(String id) {
- // TODO Auto-generated method stub
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getResponseDataMap()
+ */
+ @Override
+ public Map<String, Object> getResponseDataMap() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#renderSubmittedAjaxRegion(javax.faces.context.FacesContext)
- */
- @Override
- public void renderAjax(FacesContext context) {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getSubmittedRegionClientId(javax.faces.context.FacesContext)
+ */
+ @Override
+ public String getSubmittedRegionClientId() {
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#saveViewState(javax.faces.context.FacesContext)
- */
- @Override
- public void saveViewState(FacesContext context) throws IOException {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#getViewIdHolder()
+ */
+ @Override
+ public ViewIdHolder getViewIdHolder() {
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#setAjaxRequest(boolean)
- */
- @Override
- public void setAjaxRequest(boolean b) {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#isAjaxRequest(javax.faces.context.FacesContext)
+ */
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#isAjaxRequest()
+ */
+ @Override
+ public boolean isAjaxRequest() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#setAjaxSingleClientId(java.lang.String)
- */
- @Override
- public void setAjaxSingleClientId(String ajaxSingleClientId) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ return false;
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#isSelfRender()
+ */
+ @Override
+ public boolean isSelfRender() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#setOncomplete(java.lang.Object)
- */
- @Override
- public void setOncomplete(Object oncompleteFunction) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ return false;
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#release()
+ */
+ @Override
+ public void release() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#setResponseData(java.lang.Object)
- */
- @Override
- public void setResponseData(Object responseData) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#removeRenderedArea(java.lang.String)
+ */
+ @Override
+ public boolean removeRenderedArea(String id) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#setSelfRender(boolean)
- */
- @Override
- public void setSelfRender(boolean b) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ return false;
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#renderSubmittedAjaxRegion(javax.faces.context.FacesContext)
+ */
+ @Override
+ public void renderAjax(FacesContext context) {
- /* (non-Javadoc)
- * @see org.ajax4jsf.context.AjaxContext#setViewIdHolder(org.ajax4jsf.context.ViewIdHolder)
- */
- @Override
- public void setViewIdHolder(ViewIdHolder viewIdHolder) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#saveViewState(javax.faces.context.FacesContext)
+ */
+ @Override
+ public void saveViewState(FacesContext context) throws IOException {
- public void setAjaxAreasToProcess(Set<String> ajaxAreasToProcess) {
- }
+ // TODO Auto-generated method stub
+ }
- @Override
- public Set<String> getAjaxAreasToProcess() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#setAjaxRequest(boolean)
+ */
+ @Override
+ public void setAjaxRequest(boolean b) {
- public void setSubmittedRegionClientId(String submittedClientId) {
- }
+ // TODO Auto-generated method stub
+ }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#setAjaxSingleClientId(java.lang.String)
+ */
+ @Override
+ public void setAjaxSingleClientId(String ajaxSingleClientId) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#setOncomplete(java.lang.Object)
+ */
+ @Override
+ public void setOncomplete(Object oncompleteFunction) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#setResponseData(java.lang.Object)
+ */
+ @Override
+ public void setResponseData(Object responseData) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#setSelfRender(boolean)
+ */
+ @Override
+ public void setSelfRender(boolean b) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.context.AjaxContext#setViewIdHolder(org.ajax4jsf.context.ViewIdHolder)
+ */
+ @Override
+ public void setViewIdHolder(ViewIdHolder viewIdHolder) {
+
+ // TODO Auto-generated method stub
+ }
+
+ public void setAjaxAreasToProcess(Set<String> ajaxAreasToProcess) {}
+
+ @Override
+ public Set<String> getAjaxAreasToProcess() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void setSubmittedRegionClientId(String submittedClientId) {}
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/AllTests.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/AllTests.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/AllTests.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,21 +19,22 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.framework.ajax.xmlfilter;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
+ public static Test suite() {
+ TestSuite suite = new TestSuite("Test for org.ajax4jsf.webapp");
- public static Test suite() {
- TestSuite suite = new TestSuite(
- "Test for org.ajax4jsf.webapp");
- //$JUnit-BEGIN$
- suite.addTestSuite(CacheContentTest.class);
- suite.addTestSuite(NekkoParserTest.class);
- //$JUnit-END$
- return suite;
- }
+ // $JUnit-BEGIN$
+ suite.addTestSuite(CacheContentTest.class);
+ suite.addTestSuite(NekkoParserTest.class);
+ // $JUnit-END$
+ return suite;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/CacheContentTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/CacheContentTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/CacheContentTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.framework.ajax.xmlfilter;
import java.io.ByteArrayInputStream;
@@ -31,6 +33,7 @@
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
import org.ajax4jsf.webapp.CacheContent;
+
import org.apache.shale.test.mock.MockPrintWriter;
import org.apache.shale.test.mock.MockServletOutputStream;
@@ -39,86 +42,104 @@
*
*/
public class CacheContentTest extends AbstractAjax4JsfTestCase {
+ public CacheContentTest(String name) {
+ super(name);
- public CacheContentTest(String name) {
- super(name);
- // TODO Auto-generated constructor stub
- }
+ // TODO Auto-generated constructor stub
+ }
-
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- // TODO Auto-generated method stub
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ // TODO Auto-generated method stub
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- // TODO Auto-generated method stub
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ // TODO Auto-generated method stub
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.ajax4jsf.webapp.CacheContent#getOutputStream(java.io.OutputStream)}.
- * @throws IOException
- */
- public void testGetOutputStream() throws IOException {
- CacheContent content = new CacheContent();
- OutputStream outputStream = content.getOutputStream();
- byte[] bytes = "Test".getBytes();
- outputStream.write(bytes);
- outputStream.flush();
- outputStream.close();
- ByteArrayOutputStream ser = new ByteArrayOutputStream(1024);
- ObjectOutputStream objStream = new ObjectOutputStream(ser);
- objStream.writeObject(content);
- objStream.flush();
- ByteArrayInputStream in = new ByteArrayInputStream(ser.toByteArray());
- ObjectInputStream objInput = new ObjectInputStream(in);
- try {
- content = (CacheContent) objInput.readObject();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- content.send(this.response);
- MockServletOutputStream mockStream = (MockServletOutputStream) response.getOutputStream();
- byte[] bs = mockStream.content();
- assertEquals("Test", new String(bs));
- }
+ /**
+ * Test method for {@link org.ajax4jsf.webapp.CacheContent#getOutputStream(java.io.OutputStream)}.
+ * @throws IOException
+ */
+ public void testGetOutputStream() throws IOException {
+ CacheContent content = new CacheContent();
+ OutputStream outputStream = content.getOutputStream();
+ byte[] bytes = "Test".getBytes();
- /**
- * Test method for {@link org.ajax4jsf.webapp.CacheContent#getWriter(java.io.Writer)}.
- * @throws IOException
- */
- public void testGetWriter() throws IOException {
- CacheContent content = new CacheContent();
- PrintWriter outputStream = content.getWriter();
- outputStream.write("Test");
- outputStream.flush();
- outputStream.close();
- ByteArrayOutputStream ser = new ByteArrayOutputStream(1024);
- ObjectOutputStream objStream = new ObjectOutputStream(ser);
- objStream.writeObject(content);
- objStream.flush();
- ByteArrayInputStream in = new ByteArrayInputStream(ser.toByteArray());
- ObjectInputStream objInput = new ObjectInputStream(in);
- try {
- content = (CacheContent) objInput.readObject();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- content.send(this.response);
- MockPrintWriter writer = (MockPrintWriter) response.getWriter();
- char[] cs = writer.content();
- assertEquals("Test", new String(cs));
- }
+ outputStream.write(bytes);
+ outputStream.flush();
+ outputStream.close();
+ ByteArrayOutputStream ser = new ByteArrayOutputStream(1024);
+ ObjectOutputStream objStream = new ObjectOutputStream(ser);
+
+ objStream.writeObject(content);
+ objStream.flush();
+
+ ByteArrayInputStream in = new ByteArrayInputStream(ser.toByteArray());
+ ObjectInputStream objInput = new ObjectInputStream(in);
+
+ try {
+ content = (CacheContent) objInput.readObject();
+ } catch (ClassNotFoundException e) {
+
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ content.send(this.response);
+
+ MockServletOutputStream mockStream = (MockServletOutputStream) response.getOutputStream();
+ byte[] bs = mockStream.content();
+
+ assertEquals("Test", new String(bs));
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.webapp.CacheContent#getWriter(java.io.Writer)}.
+ * @throws IOException
+ */
+ public void testGetWriter() throws IOException {
+ CacheContent content = new CacheContent();
+ PrintWriter outputStream = content.getWriter();
+
+ outputStream.write("Test");
+ outputStream.flush();
+ outputStream.close();
+
+ ByteArrayOutputStream ser = new ByteArrayOutputStream(1024);
+ ObjectOutputStream objStream = new ObjectOutputStream(ser);
+
+ objStream.writeObject(content);
+ objStream.flush();
+
+ ByteArrayInputStream in = new ByteArrayInputStream(ser.toByteArray());
+ ObjectInputStream objInput = new ObjectInputStream(in);
+
+ try {
+ content = (CacheContent) objInput.readObject();
+ } catch (ClassNotFoundException e) {
+
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ content.send(this.response);
+
+ MockPrintWriter writer = (MockPrintWriter) response.getWriter();
+ char[] cs = writer.content();
+
+ assertEquals("Test", new String(cs));
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/NekkoParserTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/NekkoParserTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/ajax/xmlfilter/NekkoParserTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.framework.ajax.xmlfilter;
import java.io.IOException;
@@ -31,62 +33,77 @@
import org.ajax4jsf.webapp.nekko.NekkoParser;
public class NekkoParserTest extends TestCase {
-
- private NekkoParser parser;
+ private NekkoParser parser;
- protected void setUp() throws Exception {
- parser = new NekkoParser();
- parser.setInputEncoding("UTF-8");
- parser.setOutputEncoding("UTF-8");
- parser.init();
- super.setUp();
- }
+ protected void setUp() throws Exception {
+ parser = new NekkoParser();
+ parser.setInputEncoding("UTF-8");
+ parser.setOutputEncoding("UTF-8");
+ parser.init();
+ super.setUp();
+ }
- protected void tearDown() throws Exception {
- parser = null;
- super.tearDown();
- }
+ protected void tearDown() throws Exception {
+ parser = null;
+ super.tearDown();
+ }
- /*
- * Test method for 'org.ajax4jsf.webapp.NekkoParser.parseHtml(Reader, Writer)'
- */
- public void testParseHtmlReaderWriter() {
- String html = "<html><body><table><tr><td>xxx</td></tr></table></body></html>";
- ParseString(html);
- }
+ /*
+ * Test method for 'org.ajax4jsf.webapp.NekkoParser.parseHtml(Reader, Writer)'
+ */
+ public void testParseHtmlReaderWriter() {
+ String html = "<html><body><table><tr><td>xxx</td></tr></table></body></html>";
- public void testParseHtmlReaderWriter1() {
- String html = "<html><body><table><tr><td>xxx</td></tr><tr><td>xxx</td></tr></table></body></html>";
- ParseString(html);
- }
- public void testParseHtmlReaderWriter2() {
- String html = "<html><body><table><tbody><tr><td>xxx</td></tr><tr><td>xxx</td></tr></tbody></table></body></html>";
- ParseString(html);
- }
- public void testParseHtmlReaderWriter3() {
- String html = "<html><body><table><thead><tr><td>xxx</td></tr></thead><tr><td>xxx</td></tr></table></body></html>";
- ParseString(html);
- }
- public void testParseHtmlReaderWriter4() {
- String html = "<html><body><table><span><tr><td>xxx</td></tr><tr><td>xxx</td></tr></span></table></body></html>";
- ParseString(html);
- }
- /**
- * @param html
- */
- private String ParseString(String html) {
- Reader in = new StringReader(html);
- StringWriter out = new StringWriter();
- try {
- parser.parseHtml(in,out);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- assertTrue("Io error in parser ",false);
- }
- String toString = out.toString();
- System.out.println(toString);
- return toString;
- }
+ ParseString(html);
+ }
+ public void testParseHtmlReaderWriter1() {
+ String html = "<html><body><table><tr><td>xxx</td></tr><tr><td>xxx</td></tr></table></body></html>";
+
+ ParseString(html);
+ }
+
+ public void testParseHtmlReaderWriter2() {
+ String html =
+ "<html><body><table><tbody><tr><td>xxx</td></tr><tr><td>xxx</td></tr></tbody></table></body></html>";
+
+ ParseString(html);
+ }
+
+ public void testParseHtmlReaderWriter3() {
+ String html =
+ "<html><body><table><thead><tr><td>xxx</td></tr></thead><tr><td>xxx</td></tr></table></body></html>";
+
+ ParseString(html);
+ }
+
+ public void testParseHtmlReaderWriter4() {
+ String html =
+ "<html><body><table><span><tr><td>xxx</td></tr><tr><td>xxx</td></tr></span></table></body></html>";
+
+ ParseString(html);
+ }
+
+ /**
+ * @param html
+ */
+ private String ParseString(String html) {
+ Reader in = new StringReader(html);
+ StringWriter out = new StringWriter();
+
+ try {
+ parser.parseHtml(in, out);
+ } catch (IOException e) {
+
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ assertTrue("Io error in parser ", false);
+ }
+
+ String toString = out.toString();
+
+ System.out.println(toString);
+
+ return toString;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/BeforeRendererListenerTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/BeforeRendererListenerTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/BeforeRendererListenerTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.framework.renderer;
import javax.faces.event.PhaseEvent;
@@ -38,56 +40,55 @@
*/
public class BeforeRendererListenerTestCase extends AbstractAjax4JsfTestCase {
- /**
- * @param name
- */
- public BeforeRendererListenerTestCase(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public BeforeRendererListenerTestCase(String name) {
+ super(name);
+ }
- /*
- * @see VcpJsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- FilterServletResponseWrapper responseWrapper = new FilterServletResponseWrapper(response);
- request.setAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE, responseWrapper );
- }
+ /*
+ * @see VcpJsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
- /*
- * @see VcpJsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ FilterServletResponseWrapper responseWrapper = new FilterServletResponseWrapper(response);
- /*
- * Test method for 'org.ajax4jsf.renderkit.BeforeRenderListener.afterPhase(PhaseEvent)'
- */
- public void testAfterPhase() throws Exception {
- PhaseListener listener = new AjaxPhaseListener();
- PhaseEvent event = new PhaseEvent(facesContext,PhaseId.RENDER_RESPONSE,lifecycle);
-// UIComponent ajaxButton = createComponent("org.ajax4jsf.ajax.AjaxButton", "org.ajax4jsf.ajax.html.HtmlAjaxCommandButton", "org.ajax4jsf.ajax.AjaxButton", CommandButtonRenderer.class, null);
-// facesContext.getViewRoot().getChildren().add(ajaxButton);
- AjaxContext.getCurrentInstance(facesContext).setAjaxRequest(true);
- // TODO Must be used different StateManager !
-// listener.afterPhase(event);
-// assertNotNull(externalContext.getRequestMap().get(AjaxPhaseListener.VIEW_STATE_SAVED_PARAM));
-// assertNull(externalContext.getRequestMap().get(AjaxContext.STYLES_PARAMETER));
- }
+ request.setAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE, responseWrapper);
+ }
- /*
- * Test method for 'org.ajax4jsf.renderkit.BeforeRenderListener.beforePhase(PhaseEvent)'
- */
- public void testBeforePhase() {
+ /*
+ * @see VcpJsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- }
+ /*
+ * Test method for 'org.ajax4jsf.renderkit.BeforeRenderListener.afterPhase(PhaseEvent)'
+ */
+ public void testAfterPhase() throws Exception {
+ PhaseListener listener = new AjaxPhaseListener();
+ PhaseEvent event = new PhaseEvent(facesContext, PhaseId.RENDER_RESPONSE, lifecycle);
- /*
- * Test method for 'org.ajax4jsf.renderkit.BeforeRenderListener.isValueReference(String)'
- */
- public void testIsValueReference() {
+// UIComponent ajaxButton = createComponent("org.ajax4jsf.ajax.AjaxButton", "org.ajax4jsf.ajax.html.HtmlAjaxCommandButton", "org.ajax4jsf.ajax.AjaxButton", CommandButtonRenderer.class, null);
+// facesContext.getViewRoot().getChildren().add(ajaxButton);
+ AjaxContext.getCurrentInstance(facesContext).setAjaxRequest(true);
- }
+ // TODO Must be used different StateManager !
+// listener.afterPhase(event);
+// assertNotNull(externalContext.getRequestMap().get(AjaxPhaseListener.VIEW_STATE_SAVED_PARAM));
+// assertNull(externalContext.getRequestMap().get(AjaxContext.STYLES_PARAMETER));
+ }
+ /*
+ * Test method for 'org.ajax4jsf.renderkit.BeforeRenderListener.beforePhase(PhaseEvent)'
+ */
+ public void testBeforePhase() {}
+
+ /*
+ * Test method for 'org.ajax4jsf.renderkit.BeforeRenderListener.isValueReference(String)'
+ */
+ public void testIsValueReference() {}
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitImplTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitImplTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitImplTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.framework.renderer;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
@@ -30,46 +32,39 @@
*/
public class ChameleonRenderKitImplTestCase extends AbstractAjax4JsfTestCase {
- /**
- * @param name
- */
- public ChameleonRenderKitImplTestCase(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public ChameleonRenderKitImplTestCase(String name) {
+ super(name);
+ }
- /*
- * @see VcpJsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * @see VcpJsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
+ }
- /*
- * @see VcpJsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * @see VcpJsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- /*
- * Test method for 'org.ajax4jsf.renderkit.ChameleonRenderKitImpl.addRenderer(String, String, Renderer)'
- */
- public void testAddRendererStringStringRenderer() {
+ /*
+ * Test method for 'org.ajax4jsf.renderkit.ChameleonRenderKitImpl.addRenderer(String, String, Renderer)'
+ */
+ public void testAddRendererStringStringRenderer() {}
- }
+ /*
+ * Test method for 'org.ajax4jsf.renderkit.ChameleonRenderKitImpl.getRenderer(String, String)'
+ */
+ public void testGetRendererStringString() {}
- /*
- * Test method for 'org.ajax4jsf.renderkit.ChameleonRenderKitImpl.getRenderer(String, String)'
- */
- public void testGetRendererStringString() {
-
- }
-
- /*
- * Test method for 'org.ajax4jsf.renderkit.ChameleonRenderKitImpl.getDefaultRenderKit()'
- */
- public void testGetDefaultRenderKit() {
-
- }
-
+ /*
+ * Test method for 'org.ajax4jsf.renderkit.ChameleonRenderKitImpl.getDefaultRenderKit()'
+ */
+ public void testGetDefaultRenderKit() {}
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/RenderTests.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/RenderTests.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/framework/renderer/RenderTests.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.framework.renderer;
import junit.framework.Test;
@@ -30,15 +32,14 @@
*
*/
public class RenderTests {
+ public static Test suite() {
+ TestSuite suite = new TestSuite("Test for org.ajax4jsf.renderkit");
- public static Test suite() {
- TestSuite suite = new TestSuite(
- "Test for org.ajax4jsf.renderkit");
- //$JUnit-BEGIN$
- suite.addTestSuite(ChameleonRenderKitImplTestCase.class);
- suite.addTestSuite(BeforeRendererListenerTestCase.class);
- //$JUnit-END$
- return suite;
- }
+ // $JUnit-BEGIN$
+ suite.addTestSuite(ChameleonRenderKitImplTestCase.class);
+ suite.addTestSuite(BeforeRendererListenerTestCase.class);
+ // $JUnit-END$
+ return suite;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/AllResourcesTests.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/AllResourcesTests.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/AllResourcesTests.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.resource;
import junit.framework.Test;
@@ -30,16 +32,15 @@
*
*/
public class AllResourcesTests {
+ public static Test suite() {
+ TestSuite suite = new TestSuite("Test for org.ajax4jsf.resource");
- public static Test suite() {
- TestSuite suite = new TestSuite(
- "Test for org.ajax4jsf.resource");
- //$JUnit-BEGIN$
- suite.addTestSuite(ResourceServiceThreadsTestCase.class);
- suite.addTestSuite(InternetResourceServiceTestCase.class);
- suite.addTestSuite(CSSTemplateTestCase.class);
- //$JUnit-END$
- return suite;
- }
+ // $JUnit-BEGIN$
+ suite.addTestSuite(ResourceServiceThreadsTestCase.class);
+ suite.addTestSuite(InternetResourceServiceTestCase.class);
+ suite.addTestSuite(CSSTemplateTestCase.class);
+ // $JUnit-END$
+ return suite;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/CSSTemplateTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/CSSTemplateTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/CSSTemplateTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.resource;
import java.io.IOException;
@@ -27,6 +29,7 @@
import org.ajax4jsf.renderkit.compiler.TemplateContext;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
import org.ajax4jsf.webapp.WebXml;
+
import org.apache.shale.test.mock.MockPrintWriter;
/**
@@ -35,150 +38,160 @@
*
*/
public class CSSTemplateTestCase extends AbstractAjax4JsfTestCase {
+ private static boolean methodCalled = false;
+ private static boolean methodParamOk = false;
- private static boolean methodCalled=false;
+ /**
+ * Constructor for CSSTemplateTestCase.
+ * @param name
+ */
+ public CSSTemplateTestCase(String name) {
+ super(name);
+ }
- private static boolean methodParamOk=false;
+ /*
+ * @see VcpJsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
+ CSSTemplateTestCase.methodCalled = false;
+ CSSTemplateTestCase.methodParamOk = false;
+ }
- /**
- * Constructor for CSSTemplateTestCase.
- * @param name
- */
- public CSSTemplateTestCase(String name) {
- super(name);
- }
+ /*
+ * @see VcpJsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- /*
- * @see VcpJsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- CSSTemplateTestCase.methodCalled=false;
- CSSTemplateTestCase.methodParamOk=false;
- }
+ public void testCallWithContext() throws Exception {
+ String templatePath = "org/ajax4jsf/resource/call.xml";
+ TemplateCSSResource resource = new TemplateCSSResource(templatePath);
+ ResourceContext context = new FacesResourceContext(facesContext);
- /*
- * @see VcpJsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ try {
+ resource.send(context);
+ } catch (IOException e) {
+ assertTrue("error send style", false);
+ }
- public void testCallWithContext() throws Exception {
- String templatePath = "org/ajax4jsf/resource/call.xml";
- TemplateCSSResource resource = new TemplateCSSResource(templatePath);
+ assertTrue(methodCalled);
+ }
+
+ public static void contextCallWithParam(TemplateContext context, String param) {
+ methodCalled = true;
+ methodParamOk = "Test".equals(param);
+ }
+
+ public void testCallWithContextAndParam() throws Exception {
+ String templatePath = "org/ajax4jsf/resource/callWithParam.xml";
+ TemplateCSSResource resource = new TemplateCSSResource(templatePath);
ResourceContext context = new FacesResourceContext(facesContext);
+
try {
- resource.send(context);
- } catch (IOException e) {
- assertTrue("error send style",false);
- }
- assertTrue(methodCalled);
- }
-
- public static void contextCallWithParam(TemplateContext context,String param) {
- methodCalled = true;
- methodParamOk = "Test".equals(param);
- }
+ resource.send(context);
+ } catch (IOException e) {
+ assertTrue("error send style", false);
+ }
- public void testCallWithContextAndParam() throws Exception {
- String templatePath = "org/ajax4jsf/resource/callWithParam.xml";
- TemplateCSSResource resource = new TemplateCSSResource(templatePath);
+ assertTrue(methodCalled);
+ }
+
+ public static void contextCall(TemplateContext context) {
+ methodCalled = true;
+ }
+
+ /*
+ * Test method for 'org.ajax4jsf.resource.TemplateCSSResource.send(ResourceContext)'
+ */
+ public void testSend() throws IOException {
+ String templatePath = "org/ajax4jsf/resource/styles.xml";
+ TemplateCSSResource resource = new TemplateCSSResource(templatePath);
ResourceContext context = new FacesResourceContext(facesContext);
+
try {
- resource.send(context);
- } catch (IOException e) {
- assertTrue("error send style",false);
- }
- assertTrue(methodCalled);
- }
-
- public static void contextCall(TemplateContext context) {
- methodCalled = true;
- }
- /*
- * Test method for 'org.ajax4jsf.resource.TemplateCSSResource.send(ResourceContext)'
- */
- public void testSend() throws IOException {
- String templatePath = "org/ajax4jsf/resource/styles.xml";
- TemplateCSSResource resource = new TemplateCSSResource(templatePath);
- ResourceContext context = new FacesResourceContext(facesContext);
- try {
- resource.send(context);
- } catch (IOException e) {
- assertTrue("error send style",false);
- }
- MockPrintWriter printWriter = (MockPrintWriter) response.getWriter();
- String content = String.valueOf(printWriter.content());
- System.out.println(content);
- }
+ resource.send(context);
+ } catch (IOException e) {
+ assertTrue("error send style", false);
+ }
- /*
- * Test method for 'org.ajax4jsf.resource.TemplateCSSResource.TemplateCSSResource(String)'
- */
- public void testTemplateCSSResource() throws IOException {
- String templatePath = "org/ajax4jsf/resource/styles.xml";
- TemplateCSSResource resource = new TemplateCSSResource(templatePath);
- assertEquals(templatePath,resource.getKey());
- InternetResource resource2 = InternetResourceBuilder.getInstance().createResource(this,resource.getKey());
- ResourceContext ctx = new FacesResourceContext(this.facesContext);
- InputStream stream = resource.getResourceAsStream(ctx);
- byte[] resourceContent = new byte[8196];
- int length = stream.read(resourceContent);
- InputStream stream2 = resource2.getResourceAsStream(ctx);
- byte[] resource2Content = new byte[8196];
- int length2 = stream2.read(resource2Content);
- assertEquals(length, length2);
+ MockPrintWriter printWriter = (MockPrintWriter) response.getWriter();
+ String content = String.valueOf(printWriter.content());
- }
+ System.out.println(content);
+ }
- /*
- * Test method for 'org.ajax4jsf.resource.InternetResourceBase.isCacheable()'
- */
- public void testIsCacheable() {
+ /*
+ * Test method for 'org.ajax4jsf.resource.TemplateCSSResource.TemplateCSSResource(String)'
+ */
+ public void testTemplateCSSResource() throws IOException {
+ String templatePath = "org/ajax4jsf/resource/styles.xml";
+ TemplateCSSResource resource = new TemplateCSSResource(templatePath);
- }
+ assertEquals(templatePath, resource.getKey());
- /*
- * Test method for 'org.ajax4jsf.resource.InternetResourceBase.getContentType()'
- */
- public void testGetContentType() {
+ InternetResource resource2 = InternetResourceBuilder.getInstance().createResource(this, resource.getKey());
+ ResourceContext ctx = new FacesResourceContext(this.facesContext);
+ InputStream stream = resource.getResourceAsStream(ctx);
+ byte[] resourceContent = new byte[8196];
+ int length = stream.read(resourceContent);
+ InputStream stream2 = resource2.getResourceAsStream(ctx);
+ byte[] resource2Content = new byte[8196];
+ int length2 = stream2.read(resource2Content);
- String templatePath = "org/ajax4jsf/resource/styles.xml";
- TemplateCSSResource resource = new TemplateCSSResource(templatePath);
- assertEquals("text/css",resource.getContentType(null));
-}
+ assertEquals(length, length2);
+ }
- /*
- * Test method for 'org.ajax4jsf.resource.InternetResourceBase.getUri(FacesContext, Object)'
- */
- public void testGetUri() {
- String templatePath = "org/ajax4jsf/resource/styles.xml";
- TemplateCSSResource resource = new TemplateCSSResource(templatePath);
-// System.out.println(resource.getUri(facesContext,null));
-// System.out.println(expextedUri);
- String uri = resource.getUri(facesContext,null);
- assertTrue(uri.startsWith(request.getContextPath()+"/"+WebXml.RESOURCE_URI_PREFIX));
- assertTrue(uri.startsWith(request.getContextPath()+"/"+WebXml.SESSION_RESOURCE_URI_PREFIX_VERSIONED + resource.getKey()));
- }
+ /*
+ * Test method for 'org.ajax4jsf.resource.InternetResourceBase.isCacheable()'
+ */
+ public void testIsCacheable() {}
- /*
- * Test method for 'org.ajax4jsf.resource.InternetResourceBase.getResourceAsStream(ResourceContext)'
- */
- public void testGetResourceAsStream() {
+ /*
+ * Test method for 'org.ajax4jsf.resource.InternetResourceBase.getContentType()'
+ */
+ public void testGetContentType() {
+ String templatePath = "org/ajax4jsf/resource/styles.xml";
+ TemplateCSSResource resource = new TemplateCSSResource(templatePath);
- }
+ assertEquals("text/css", resource.getContentType(null));
+ }
- /*
- * Test method for 'org.ajax4jsf.resource.InternetResourceBase.sendHeaders(ResourceContext)'
- */
- public void testSendHeaders() {
- String templatePath = "org/ajax4jsf/resource/styles.xml";
- TemplateCSSResource resource = new TemplateCSSResource(templatePath);
+ /*
+ * Test method for 'org.ajax4jsf.resource.InternetResourceBase.getUri(FacesContext, Object)'
+ */
+ public void testGetUri() {
+ String templatePath = "org/ajax4jsf/resource/styles.xml";
+ TemplateCSSResource resource = new TemplateCSSResource(templatePath);
+
+// System.out.println(resource.getUri(facesContext,null));
+// System.out.println(expextedUri);
+ String uri = resource.getUri(facesContext, null);
+
+ assertTrue(uri.startsWith(request.getContextPath() + "/" + WebXml.RESOURCE_URI_PREFIX));
+ assertTrue(uri.startsWith(request.getContextPath() + "/" + WebXml.SESSION_RESOURCE_URI_PREFIX_VERSIONED
+ + resource.getKey()));
+ }
+
+ /*
+ * Test method for 'org.ajax4jsf.resource.InternetResourceBase.getResourceAsStream(ResourceContext)'
+ */
+ public void testGetResourceAsStream() {}
+
+ /*
+ * Test method for 'org.ajax4jsf.resource.InternetResourceBase.sendHeaders(ResourceContext)'
+ */
+ public void testSendHeaders() {
+ String templatePath = "org/ajax4jsf/resource/styles.xml";
+ TemplateCSSResource resource = new TemplateCSSResource(templatePath);
ResourceContext context = new FacesResourceContext(facesContext);
+
resource.sendHeaders(context);
+
String header = response.getContentType();
+
assertNotNull(header);
assertTrue(header.startsWith("text/css"));
- }
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/InternetResourceServiceTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/InternetResourceServiceTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/InternetResourceServiceTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,11 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.resource;
import java.io.IOException;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.apache.shale.test.mock.MockHttpServletResponse;
import org.apache.shale.test.mock.MockServletOutputStream;
@@ -33,138 +36,158 @@
*/
public class InternetResourceServiceTestCase extends AbstractAjax4JsfTestCase {
- /**
- * @param name
- */
- public InternetResourceServiceTestCase(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public InternetResourceServiceTestCase(String name) {
+ super(name);
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
-
- //TODO fix when setContentLength in shale-test will start function
- // https://issues.apache.org/struts/browse/SHALE-495
- this.response = new MockHttpServletResponse() {
-
- public int getContentLength() {
- return Integer.parseInt(getHeader("Content-Length"));
- }
-
- public void setContentLength(int length) {
- addIntHeader("Content-Length", length);
- }
- };
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- InternetResourceBuilder.setInstance(null);
- }
+ // TODO fix when setContentLength in shale-test will start function
+ // https://issues.apache.org/struts/browse/SHALE-495
+ this.response = new MockHttpServletResponse() {
+ public int getContentLength() {
+ return Integer.parseInt(getHeader("Content-Length"));
+ }
+ public void setContentLength(int length) {
+ addIntHeader("Content-Length", length);
+ }
+ };
+ }
- /**
- * Test method for {@link org.ajax4jsf.resource.InternetResourceService#init(javax.servlet.FilterConfig)}.
- * @throws Exception
- */
- public void testInit() throws Exception {
- InternetResourceService service = new InternetResourceService();
- MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
- mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
- service.init(mockFilterConfig);
- assertSame(servletContext, service.getServletContext());
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ InternetResourceBuilder.setInstance(null);
+ }
- /**
- * Test method for {@link org.ajax4jsf.resource.InternetResourceService#serviceResource(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
- * @throws IOException
- * @throws Exception
- */
- public void testServiceResource() throws Exception, IOException {
- InternetResourceService service = new InternetResourceService();
- MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
- mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
- service.init(mockFilterConfig);
- InternetResourceBuilder builder = InternetResourceBuilder.getInstance();
- InternetResource resource = builder.createResource(this, "test.js");
- MockResourceRequest resourceRequest = new MockResourceRequest(request);
- String key = resource.getKey();
- service.serviceResource(key,resourceRequest,response);
- byte[] content = ((MockServletOutputStream)response.getOutputStream()).content();
- String strContent = new String(content);
- assertEquals(strContent, "\nfunction Test(){};");
- response.setOutputStream(null);
- response.setWriter(null);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.resource.InternetResourceService#init(javax.servlet.FilterConfig)}.
+ * @throws Exception
+ */
+ public void testInit() throws Exception {
+ InternetResourceService service = new InternetResourceService();
+ MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
- /**
- * Test method for {@link org.ajax4jsf.resource.InternetResourceService#serviceResource(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
- * @throws IOException
- * @throws Exception
- */
- public void testCachedServiceResource() throws Exception, IOException {
- InternetResourceService service = new InternetResourceService();
- MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
- mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
- service.init(mockFilterConfig);
- InternetResourceBuilder builder = InternetResourceBuilder.getInstance();
- InternetResource resource = builder.createResource(this, MockCacheableResource.class.getName());
- MockResourceRequest resourceRequest = new MockResourceRequest(request);
- String key = resource.getKey();
- for(int i=1;i<=10;i++){
- service.serviceResource(key,resourceRequest,response);
- byte[] content = ((MockServletOutputStream)response.getOutputStream()).content();
- String strContent = new String(content);
- assertEquals(strContent, "test");
- assertEquals(((MockCacheableResource) resource).getCounter(), 1);
- response.setOutputStream(null);
- response.setWriter(null);
- }
- }
+ mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
+ service.init(mockFilterConfig);
+ assertSame(servletContext, service.getServletContext());
+ }
- /**
- * Test method for {@link org.ajax4jsf.resource.InternetResourceService#serviceResource(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
- * @throws IOException
- * @throws Exception
- */
- public void testCachedServiceExpiration() throws Exception, IOException {
- InternetResourceService service = new InternetResourceService();
- MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
- mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
- service.init(mockFilterConfig);
- InternetResourceBuilder builder = InternetResourceBuilder.getInstance();
- InternetResource resource = builder.createResource(this, MockCacheableResource.class.getName());
- MockResourceRequest resourceRequest = new MockResourceRequest(request);
- String key = resource.getKey();
- for(int j=1;j<=10;j++){
- for(int i=1;i<=10;i++){
- request.setPathElements(request.getContextPath(), request.getServletPath(), request.getPathInfo(), String.valueOf(i));
- service.serviceResource(key,resourceRequest,response);
- byte[] content = ((MockServletOutputStream)response.getOutputStream()).content();
- String strContent = new String(content);
- assertEquals(strContent, "test");
- response.setOutputStream(null);
- response.setWriter(null);
- }
- }
- int counter = ((MockCacheableResource) resource).getCounter();
- assertTrue("Resource was generated "+counter+" times", counter<= 10);
- }
-
- public void testSendResource() {
-// fail("Not yet implemented");
- }
+ /**
+ * Test method for {@link org.ajax4jsf.resource.InternetResourceService#serviceResource(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
+ * @throws IOException
+ * @throws Exception
+ */
+ public void testServiceResource() throws Exception, IOException {
+ InternetResourceService service = new InternetResourceService();
+ MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
- /**
- * Test method for {@link org.ajax4jsf.resource.InternetResourceService#getProperties(java.lang.String)}.
- */
- public void testGetProperties() {
-// fail("Not yet implemented");
- }
+ mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
+ service.init(mockFilterConfig);
+ InternetResourceBuilder builder = InternetResourceBuilder.getInstance();
+ InternetResource resource = builder.createResource(this, "test.js");
+ MockResourceRequest resourceRequest = new MockResourceRequest(request);
+ String key = resource.getKey();
+
+ service.serviceResource(key, resourceRequest, response);
+
+ byte[] content = ((MockServletOutputStream) response.getOutputStream()).content();
+ String strContent = new String(content);
+
+ assertEquals(strContent, "\nfunction Test(){};");
+ response.setOutputStream(null);
+ response.setWriter(null);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.resource.InternetResourceService#serviceResource(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
+ * @throws IOException
+ * @throws Exception
+ */
+ public void testCachedServiceResource() throws Exception, IOException {
+ InternetResourceService service = new InternetResourceService();
+ MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
+
+ mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
+ service.init(mockFilterConfig);
+
+ InternetResourceBuilder builder = InternetResourceBuilder.getInstance();
+ InternetResource resource = builder.createResource(this, MockCacheableResource.class.getName());
+ MockResourceRequest resourceRequest = new MockResourceRequest(request);
+ String key = resource.getKey();
+
+ for (int i = 1; i <= 10; i++) {
+ service.serviceResource(key, resourceRequest, response);
+
+ byte[] content = ((MockServletOutputStream) response.getOutputStream()).content();
+ String strContent = new String(content);
+
+ assertEquals(strContent, "test");
+ assertEquals(((MockCacheableResource) resource).getCounter(), 1);
+ response.setOutputStream(null);
+ response.setWriter(null);
+ }
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.resource.InternetResourceService#serviceResource(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
+ * @throws IOException
+ * @throws Exception
+ */
+ public void testCachedServiceExpiration() throws Exception, IOException {
+ InternetResourceService service = new InternetResourceService();
+ MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
+
+ mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
+ service.init(mockFilterConfig);
+
+ InternetResourceBuilder builder = InternetResourceBuilder.getInstance();
+ InternetResource resource = builder.createResource(this, MockCacheableResource.class.getName());
+ MockResourceRequest resourceRequest = new MockResourceRequest(request);
+ String key = resource.getKey();
+
+ for (int j = 1; j <= 10; j++) {
+ for (int i = 1; i <= 10; i++) {
+ request.setPathElements(request.getContextPath(), request.getServletPath(), request.getPathInfo(),
+ String.valueOf(i));
+ service.serviceResource(key, resourceRequest, response);
+
+ byte[] content = ((MockServletOutputStream) response.getOutputStream()).content();
+ String strContent = new String(content);
+
+ assertEquals(strContent, "test");
+ response.setOutputStream(null);
+ response.setWriter(null);
+ }
+ }
+
+ int counter = ((MockCacheableResource) resource).getCounter();
+
+ assertTrue("Resource was generated " + counter + " times", counter <= 10);
+ }
+
+ public void testSendResource() {
+
+// fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.resource.InternetResourceService#getProperties(java.lang.String)}.
+ */
+ public void testGetProperties() {
+
+// fail("Not yet implemented");
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockCacheableResource.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockCacheableResource.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockCacheableResource.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.resource;
import java.io.ByteArrayInputStream;
@@ -29,31 +31,32 @@
*
*/
public class MockCacheableResource extends InternetResourceBase {
-
- private int counter = 0;
+ private int counter = 0;
- public int getCounter() {
- return counter;
- }
+ /**
+ *
+ */
+ public MockCacheableResource() {
+ super();
+ setRenderer(new LogfileRenderer());
+ setCacheable(true);
+ }
- /**
- *
- */
- public MockCacheableResource() {
- super();
- setRenderer(new LogfileRenderer());
- setCacheable(true);
- }
+ public int getCounter() {
+ return counter;
+ }
- public InputStream getResourceAsStream(ResourceContext context) {
- counter++;
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return new ByteArrayInputStream("test".getBytes());
- }
-
+ public InputStream getResourceAsStream(ResourceContext context) {
+ counter++;
+
+ try {
+ Thread.sleep(3000);
+ } catch (InterruptedException e) {
+
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return new ByteArrayInputStream("test".getBytes());
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockFilterConfig.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockFilterConfig.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockFilterConfig.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.resource;
import java.util.Enumeration;
@@ -34,65 +36,69 @@
*
*/
public class MockFilterConfig implements FilterConfig {
-
- private ServletContext servletContext;
-
- private Map initParameters = new HashMap();
+ private Map initParameters = new HashMap();
+ private ServletContext servletContext;
- /**
- * @param servletContext
- */
- public MockFilterConfig(ServletContext servletContext) {
- super();
- this.servletContext = servletContext;
- }
+ /**
+ * @param servletContext
+ */
+ public MockFilterConfig(ServletContext servletContext) {
+ super();
+ this.servletContext = servletContext;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.FilterConfig#getFilterName()
- */
- public String getFilterName() {
- // TODO Auto-generated method stub
- return "A4J";
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.FilterConfig#getFilterName()
+ */
+ public String getFilterName() {
- /* (non-Javadoc)
- * @see javax.servlet.FilterConfig#getInitParameter(java.lang.String)
- */
- public String getInitParameter(String arg0) {
- // TODO Auto-generated method stub
- return (String) initParameters.get(arg0);
- }
+ // TODO Auto-generated method stub
+ return "A4J";
+ }
- public void setInitParameter(String name, String value) {
- initParameters.put(name, value);
- }
-
- /* (non-Javadoc)
- * @see javax.servlet.FilterConfig#getInitParameterNames()
- */
- public Enumeration getInitParameterNames() {
- final Iterator parametersIterator = initParameters.keySet().iterator();
- return new Enumeration(){
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.FilterConfig#getInitParameter(java.lang.String)
+ */
+ public String getInitParameter(String arg0) {
- public boolean hasMoreElements() {
- // TODO Auto-generated method stub
- return parametersIterator.hasNext();
- }
+ // TODO Auto-generated method stub
+ return (String) initParameters.get(arg0);
+ }
- public Object nextElement() {
- // TODO Auto-generated method stub
- return parametersIterator.next();
- }
-
- };
- }
+ public void setInitParameter(String name, String value) {
+ initParameters.put(name, value);
+ }
- /* (non-Javadoc)
- * @see javax.servlet.FilterConfig#getServletContext()
- */
- public ServletContext getServletContext() {
- // TODO Auto-generated method stub
- return servletContext;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.FilterConfig#getInitParameterNames()
+ */
+ public Enumeration getInitParameterNames() {
+ final Iterator parametersIterator = initParameters.keySet().iterator();
+ return new Enumeration() {
+ public boolean hasMoreElements() {
+
+ // TODO Auto-generated method stub
+ return parametersIterator.hasNext();
+ }
+ public Object nextElement() {
+
+ // TODO Auto-generated method stub
+ return parametersIterator.next();
+ }
+ };
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.FilterConfig#getServletContext()
+ */
+ public ServletContext getServletContext() {
+
+ // TODO Auto-generated method stub
+ return servletContext;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockResourceRequest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockResourceRequest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/MockResourceRequest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.resource;
import javax.servlet.http.HttpServletRequest;
@@ -29,20 +31,18 @@
*
*/
public class MockResourceRequest extends HttpServletRequestWrapper {
-
- private String method;
+ private String method;
- public MockResourceRequest(HttpServletRequest mockRequest) {
- super(mockRequest);
- method = "GET";
- }
+ public MockResourceRequest(HttpServletRequest mockRequest) {
+ super(mockRequest);
+ method = "GET";
+ }
- public String getMethod() {
- return method;
- }
+ public String getMethod() {
+ return method;
+ }
- public void setMethod(String method) {
- this.method = method;
- }
-
+ public void setMethod(String method) {
+ this.method = method;
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/ParametersEncodingTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/ParametersEncodingTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/ParametersEncodingTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -5,43 +5,45 @@
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
public class ParametersEncodingTestCase extends AbstractAjax4JsfTestCase {
-
+ private byte[] data = {
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
+ };
private ResourceBuilderImpl builder;
- private byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
-
public ParametersEncodingTestCase(String arg0) {
- super(arg0);
+ super(arg0);
}
public void setUp() throws Exception {
- super.setUp();
- builder = new ResourceBuilderImpl();
+ super.setUp();
+ builder = new ResourceBuilderImpl();
}
public void tearDown() throws Exception {
- builder = null;
- super.tearDown();
+ builder = null;
+ super.tearDown();
}
public final void testEncrypt() {
- byte[] bs = builder.encrypt(data);
- byte[] bs2 = builder.decrypt(bs);
- assertTrue(Arrays.equals(data, bs2));
+ byte[] bs = builder.encrypt(data);
+ byte[] bs2 = builder.decrypt(bs);
+
+ assertTrue(Arrays.equals(data, bs2));
}
public final void testDecryptLeak() {
- byte[] bs = {};
- for (int i = 0; i < 10000; i++) {
- bs = builder.encrypt(data);
+ byte[] bs = {};
- }
- byte[] bs2={};
- for (int i = 0; i < 10000; i++) {
- bs2 = builder.decrypt(bs);
+ for (int i = 0; i < 10000; i++) {
+ bs = builder.encrypt(data);
+ }
- }
- assertTrue(Arrays.equals(data, bs2));
+ byte[] bs2 = {};
+
+ for (int i = 0; i < 10000; i++) {
+ bs2 = builder.decrypt(bs);
+ }
+
+ assertTrue(Arrays.equals(data, bs2));
}
-
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/ResourceServiceThreadsTestCase.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/ResourceServiceThreadsTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/resource/ResourceServiceThreadsTestCase.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,120 +19,126 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.resource;
import java.text.SimpleDateFormat;
+
import java.util.Date;
import java.util.TimeZone;
import javax.faces.context.FacesContext;
import org.ajax4jsf.tests.AbstractThreadedAjax4JsfTestCase;
+
import org.apache.shale.test.mock.MockHttpServletRequest;
import org.apache.shale.test.mock.MockHttpServletResponse;
import org.apache.shale.test.mock.MockServletOutputStream;
/**
* @author shura
- *
+ *
*/
-public class ResourceServiceThreadsTestCase extends
- AbstractThreadedAjax4JsfTestCase {
+public class ResourceServiceThreadsTestCase extends AbstractThreadedAjax4JsfTestCase {
+ String key;
+ InternetResource resource;
+ InternetResourceService service;
- /**
- * @param s
- */
- public ResourceServiceThreadsTestCase(String s) {
- super(s);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param s
+ */
+ public ResourceServiceThreadsTestCase(String s) {
+ super(s);
- InternetResourceService service;
- String key;
- InternetResource resource;
+ // TODO Auto-generated constructor stub
+ }
- public void setUp() throws Exception {
- super.setUp();
- service = new InternetResourceService();
- MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
- mockFilterConfig.setInitParameter(
- InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
- service.init(mockFilterConfig);
- InternetResourceBuilder builder = InternetResourceBuilder.getInstance();
- resource = builder.createResource(this, MockCacheableResource.class
- .getName());
- key = resource.getKey();
- }
+ public void setUp() throws Exception {
+ super.setUp();
+ service = new InternetResourceService();
- public void tearDown() throws Exception {
- super.tearDown();
- InternetResourceBuilder.setInstance(null);
- resource = null;
- service = null;
- key = null;
- }
+ MockFilterConfig mockFilterConfig = new MockFilterConfig(servletContext);
- public class ResourceRunner extends TestCaseRunnable {
+ mockFilterConfig.setInitParameter(InternetResourceService.ENABLE_CACHING_PARAMETER, "true");
+ service.init(mockFilterConfig);
- private String data;
+ InternetResourceBuilder builder = InternetResourceBuilder.getInstance();
- /**
- * @param data
- */
- public ResourceRunner(String data) {
- super();
- this.data = data;
- }
+ resource = builder.createResource(this, MockCacheableResource.class.getName());
+ key = resource.getKey();
+ }
- public void runTestCase(FacesContext context) throws Throwable {
- MockHttpServletResponse response = new MockHttpServletResponse() {
- /* (non-Javadoc)
- * @see org.apache.shale.test.mock.MockHttpServletResponse#addDateHeader(java.lang.String, long)
- * Default shale implementation is not thread-safe.
- */
- public void addDateHeader(String name, long value) {
- SimpleDateFormat format = new SimpleDateFormat(
- "EEE, dd MMM yyyy HH:mm:ss zzz");
- format.setTimeZone(TimeZone.getTimeZone("GMT"));
- addHeader(name, format.format(new Date(value)));
- }
-
- //TODO fix when setContentLength in shale-test will start function
- // https://issues.apache.org/struts/browse/SHALE-495
- public int getContentLength() {
- return Integer.parseInt(getHeader("Content-Length"));
- }
-
- public void setContentLength(int length) {
- addIntHeader("Content-Length", length);
- }
+ public void tearDown() throws Exception {
+ super.tearDown();
+ InternetResourceBuilder.setInstance(null);
+ resource = null;
+ service = null;
+ key = null;
+ }
- };
- MockHttpServletRequest req = new MockHttpServletRequest(session);
- req.setServletContext(servletContext);
- req.setPathElements(request.getContextPath(), request
- .getServletPath(), request.getPathInfo(), data);
- MockResourceRequest resourceRequest = new MockResourceRequest(req);
- service.serviceResource(key, resourceRequest, response);
- byte[] content = ((MockServletOutputStream) response
- .getOutputStream()).content();
- String strContent = new String(content);
- assertEquals(strContent, "test");
+ public void testTreadServiceResource() {
+ TestCaseRunnable[] runnables = new TestCaseRunnable[1000];
- }
+ for (int i = 0; i < runnables.length; i++) {
+ runnables[i] = new ResourceRunner(String.valueOf(i % 10));
+ }
- }
+ this.runTestCaseRunnables(runnables);
- public void testTreadServiceResource() {
- TestCaseRunnable[] runnables = new TestCaseRunnable[1000];
- for (int i = 0; i < runnables.length; i++) {
- runnables[i] = new ResourceRunner(String.valueOf(i % 10));
+ int counter = ((MockCacheableResource) resource).getCounter();
- }
- this.runTestCaseRunnables(runnables);
- int counter = ((MockCacheableResource) resource).getCounter();
- assertTrue("Resource was generated " + counter + " times",
- counter <= 10);
+ assertTrue("Resource was generated " + counter + " times", counter <= 10);
+ }
- }
+ public class ResourceRunner extends TestCaseRunnable {
+ private String data;
+
+ /**
+ * @param data
+ */
+ public ResourceRunner(String data) {
+ super();
+ this.data = data;
+ }
+
+ public void runTestCase(FacesContext context) throws Throwable {
+ MockHttpServletResponse response = new MockHttpServletResponse() {
+
+ /*
+ * (non-Javadoc)
+ * @see org.apache.shale.test.mock.MockHttpServletResponse#addDateHeader(java.lang.String, long)
+ * Default shale implementation is not thread-safe.
+ */
+ public void addDateHeader(String name, long value) {
+ SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
+
+ format.setTimeZone(TimeZone.getTimeZone("GMT"));
+ addHeader(name, format.format(new Date(value)));
+ }
+
+ // TODO fix when setContentLength in shale-test will start function
+ // https://issues.apache.org/struts/browse/SHALE-495
+ public int getContentLength() {
+ return Integer.parseInt(getHeader("Content-Length"));
+ }
+ public void setContentLength(int length) {
+ addIntHeader("Content-Length", length);
+ }
+ };
+ MockHttpServletRequest req = new MockHttpServletRequest(session);
+
+ req.setServletContext(servletContext);
+ req.setPathElements(request.getContextPath(), request.getServletPath(), request.getPathInfo(), data);
+
+ MockResourceRequest resourceRequest = new MockResourceRequest(req);
+
+ service.serviceResource(key, resourceRequest, response);
+
+ byte[] content = ((MockServletOutputStream) response.getOutputStream()).content();
+ String strContent = new String(content);
+
+ assertEquals(strContent, "test");
+ }
+ }
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/webapp/WebXmlTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/webapp/WebXmlTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/ajax4jsf/webapp/WebXmlTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.webapp;
import java.io.InputStream;
@@ -26,187 +28,188 @@
import javax.servlet.ServletException;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.apache.shale.test.mock.MockServletContext;
public class WebXmlTest extends AbstractAjax4JsfTestCase {
+ MockServletContext context;
- MockServletContext context;
+ public WebXmlTest(String arg0) {
+ super(arg0);
+ }
- public WebXmlTest(String arg0) {
- super(arg0);
- }
+ public void setUp() throws Exception {
+ super.setUp();
+ context = new MockServletContext() {
- public void setUp() throws Exception {
- super.setUp();
- context = new MockServletContext(){
+ /*
+ * (non-Javadoc)
+ * @see org.apache.shale.test.mock.MockServletContext#getResourceAsStream(java.lang.String)
+ */
+ public InputStream getResourceAsStream(String uri) {
+ if (uri.equals(WebXml.WEB_XML)) {
+ return this.getClass().getResourceAsStream("/WEB-INF/complex-web.xml");
+ } else {
+ return super.getResourceAsStream(uri);
+ }
+ }
+ };
+ }
- /* (non-Javadoc)
- * @see org.apache.shale.test.mock.MockServletContext#getResourceAsStream(java.lang.String)
- */
- public InputStream getResourceAsStream(String uri) {
- if(uri.equals(WebXml.WEB_XML)){
- return this.getClass().getResourceAsStream("/WEB-INF/complex-web.xml");
- } else {
- return super.getResourceAsStream(uri);
- }
- }
-
- };
- }
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * Test method for 'org.ajax4jsf.webapp.WebXml.reset()'
+ */
+ public void testReset() {}
- /*
- * Test method for 'org.ajax4jsf.webapp.WebXml.reset()'
- */
- public void testReset() {
+ /*
+ * Test method for 'org.ajax4jsf.webapp.WebXml.init(ServletContext, String)'
+ */
+ public void testInit() throws ServletException {
+ WebXml webXml = new WebXml();
- }
+ webXml.init(context, "ajax4jsf");
+ assertFalse(webXml.isPrefixMapping());
+ assertNull(webXml.getFacesFilterPrefix());
+ assertNotNull(webXml.getFacesFilterSuffix());
+ assertEquals(".jsf", webXml.getFacesFilterSuffix());
+ }
- /*
- * Test method for 'org.ajax4jsf.webapp.WebXml.init(ServletContext, String)'
- */
- public void testInit() throws ServletException {
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
- assertFalse(webXml.isPrefixMapping());
- assertNull(webXml.getFacesFilterPrefix());
- assertNotNull(webXml.getFacesFilterSuffix());
- assertEquals(".jsf",webXml.getFacesFilterSuffix());
- }
+ /*
+ * Test method for 'org.ajax4jsf.webapp.WebXml.getInstance()'
+ */
+ public void testGetInstance() {}
- /*
- * Test method for 'org.ajax4jsf.webapp.WebXml.getInstance()'
- */
- public void testGetInstance() {
+ public void testDefaultResourcePrefix() throws Exception {
+ WebXml webXml = new WebXml();
- }
-
- public void testDefaultResourcePrefix() throws Exception {
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
+ webXml.init(context, "ajax4jsf");
+ assertEquals('/' + WebXml.RESOURCE_URI_PREFIX_VERSIONED, webXml.getResourcePrefix());
+ assertEquals('/' + WebXml.GLOBAL_RESOURCE_URI_PREFIX_VERSIONED, webXml.getGlobalResourcePrefix());
+ assertEquals('/' + WebXml.SESSION_RESOURCE_URI_PREFIX_VERSIONED, webXml.getSessionResourcePrefix());
+ }
- assertEquals('/' + WebXml.RESOURCE_URI_PREFIX_VERSIONED, webXml.getResourcePrefix());
- assertEquals('/' + WebXml.GLOBAL_RESOURCE_URI_PREFIX_VERSIONED, webXml.getGlobalResourcePrefix());
- assertEquals('/' + WebXml.SESSION_RESOURCE_URI_PREFIX_VERSIONED, webXml.getSessionResourcePrefix());
- }
-
- public void testOverrideResourcePrefix() throws Exception {
- context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "rich-rsrc/");
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
+ public void testOverrideResourcePrefix() throws Exception {
+ context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "rich-rsrc/");
- assertEquals("/rich-rsrc/", webXml.getResourcePrefix());
- assertEquals(webXml.getResourcePrefix(), webXml.getGlobalResourcePrefix());
- assertEquals(webXml.getResourcePrefix(), webXml.getSessionResourcePrefix());
- }
+ WebXml webXml = new WebXml();
- public void testCustomizedResourcePrefixes() throws Exception {
- context.addInitParameter(WebXml.SESSION_RESOURCE_URI_PREFIX_PARAM, "sess/");
- context.addInitParameter(WebXml.GLOBAL_RESOURCE_URI_PREFIX_PARAM, "glb/");
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
+ webXml.init(context, "ajax4jsf");
+ assertEquals("/rich-rsrc/", webXml.getResourcePrefix());
+ assertEquals(webXml.getResourcePrefix(), webXml.getGlobalResourcePrefix());
+ assertEquals(webXml.getResourcePrefix(), webXml.getSessionResourcePrefix());
+ }
- assertTrue(webXml.getResourcePrefix().startsWith("/a4j/"));
- assertTrue(webXml.getGlobalResourcePrefix().startsWith("/glb/"));
- assertTrue(webXml.getSessionResourcePrefix().startsWith("/sess/"));
- }
-
- public void testOverrideGlobalResourcePrefix() throws Exception {
- context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "j4a/");
- context.addInitParameter(WebXml.GLOBAL_RESOURCE_URI_PREFIX_PARAM, "glb/");
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
-
- assertTrue(webXml.getResourcePrefix().startsWith("/j4a/"));
- assertTrue(webXml.getGlobalResourcePrefix().startsWith("/glb/"));
- assertEquals(webXml.getResourcePrefix(), webXml.getSessionResourcePrefix());
- }
-
- public void testOverrideSessionResourcePrefix() throws Exception {
- context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "j4a/");
- context.addInitParameter(WebXml.SESSION_RESOURCE_URI_PREFIX_PARAM, "ssn/");
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
-
- assertTrue(webXml.getResourcePrefix().startsWith("/j4a/"));
- assertTrue(webXml.getSessionResourcePrefix().startsWith("/ssn/"));
- assertEquals(webXml.getResourcePrefix(), webXml.getGlobalResourcePrefix());
- }
+ public void testCustomizedResourcePrefixes() throws Exception {
+ context.addInitParameter(WebXml.SESSION_RESOURCE_URI_PREFIX_PARAM, "sess/");
+ context.addInitParameter(WebXml.GLOBAL_RESOURCE_URI_PREFIX_PARAM, "glb/");
- public void testOverrideAll() throws Exception {
- context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "j4a/");
- context.addInitParameter(WebXml.GLOBAL_RESOURCE_URI_PREFIX_PARAM, "glb/");
- context.addInitParameter(WebXml.SESSION_RESOURCE_URI_PREFIX_PARAM, "ssn/");
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
-
- assertTrue(webXml.getResourcePrefix().startsWith("/j4a/"));
- assertTrue(webXml.getSessionResourcePrefix().startsWith("/ssn/"));
- assertTrue(webXml.getGlobalResourcePrefix().startsWith("/glb/"));
- }
-
- /*
- * Test method for 'org.ajax4jsf.webapp.WebXml.getFacesResourceURL(FacesContext, String)'
- */
- public void testGetFacesResourceURL() throws ServletException {
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
- String resourceURL = webXml.getFacesResourceURL(facesContext,"foo.Bar", false);
- System.out.println(resourceURL);
- assertEquals("/testContext/"+WebXml.SESSION_RESOURCE_URI_PREFIX_VERSIONED+"foo.Bar.jsf",resourceURL);
-
- resourceURL = webXml.getFacesResourceURL(facesContext,"rich.Tree", true);
- System.out.println(resourceURL);
- assertEquals("/testContext/"+WebXml.GLOBAL_RESOURCE_URI_PREFIX_VERSIONED+"rich.Tree.jsf",resourceURL);
- }
+ WebXml webXml = new WebXml();
- public void testOverridenLegacyGetFacesResourceURL() throws ServletException {
- context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "j4a/");
-
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
- String resourceURL = webXml.getFacesResourceURL(facesContext,"foo.Bar", false);
- assertEquals("/testContext/j4a/foo.Bar.jsf",resourceURL);
-
- resourceURL = webXml.getFacesResourceURL(facesContext,"rich.Tree", true);
- assertEquals("/testContext/j4a/rich.Tree.jsf",resourceURL);
- }
-
- public void testOverridenGetFacesResourceURL() throws ServletException {
- context.addInitParameter(WebXml.GLOBAL_RESOURCE_URI_PREFIX_PARAM, "glb/");
- context.addInitParameter(WebXml.SESSION_RESOURCE_URI_PREFIX_PARAM, "ssn/");
-
- WebXml webXml = new WebXml();
- webXml.init(context,"ajax4jsf");
- String resourceURL = webXml.getFacesResourceURL(facesContext,"foo.Bar", false);
- assertEquals("/testContext/ssn/foo.Bar.jsf",resourceURL);
-
- resourceURL = webXml.getFacesResourceURL(facesContext,"rich.Tree", true);
- assertEquals("/testContext/glb/rich.Tree.jsf",resourceURL);
- }
-
- /*
- * Test method for 'org.ajax4jsf.webapp.WebXml.getFacesResourceKey(HttpServletRequest)'
- */
- public void testGetFacesResourceKey() {
+ webXml.init(context, "ajax4jsf");
+ assertTrue(webXml.getResourcePrefix().startsWith("/a4j/"));
+ assertTrue(webXml.getGlobalResourcePrefix().startsWith("/glb/"));
+ assertTrue(webXml.getSessionResourcePrefix().startsWith("/sess/"));
+ }
- }
+ public void testOverrideGlobalResourcePrefix() throws Exception {
+ context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "j4a/");
+ context.addInitParameter(WebXml.GLOBAL_RESOURCE_URI_PREFIX_PARAM, "glb/");
- /*
- * Test method for 'org.ajax4jsf.webapp.WebXml.isFacesRequest(HttpServletRequest)'
- */
- public void testIsFacesRequest() {
+ WebXml webXml = new WebXml();
- }
+ webXml.init(context, "ajax4jsf");
+ assertTrue(webXml.getResourcePrefix().startsWith("/j4a/"));
+ assertTrue(webXml.getGlobalResourcePrefix().startsWith("/glb/"));
+ assertEquals(webXml.getResourcePrefix(), webXml.getSessionResourcePrefix());
+ }
- /*
- * Test method for 'org.ajax4jsf.webapp.WebXml.setFilterName(String)'
- */
- public void testSetFilterName() {
+ public void testOverrideSessionResourcePrefix() throws Exception {
+ context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "j4a/");
+ context.addInitParameter(WebXml.SESSION_RESOURCE_URI_PREFIX_PARAM, "ssn/");
- }
+ WebXml webXml = new WebXml();
+ webXml.init(context, "ajax4jsf");
+ assertTrue(webXml.getResourcePrefix().startsWith("/j4a/"));
+ assertTrue(webXml.getSessionResourcePrefix().startsWith("/ssn/"));
+ assertEquals(webXml.getResourcePrefix(), webXml.getGlobalResourcePrefix());
+ }
+
+ public void testOverrideAll() throws Exception {
+ context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "j4a/");
+ context.addInitParameter(WebXml.GLOBAL_RESOURCE_URI_PREFIX_PARAM, "glb/");
+ context.addInitParameter(WebXml.SESSION_RESOURCE_URI_PREFIX_PARAM, "ssn/");
+
+ WebXml webXml = new WebXml();
+
+ webXml.init(context, "ajax4jsf");
+ assertTrue(webXml.getResourcePrefix().startsWith("/j4a/"));
+ assertTrue(webXml.getSessionResourcePrefix().startsWith("/ssn/"));
+ assertTrue(webXml.getGlobalResourcePrefix().startsWith("/glb/"));
+ }
+
+ /*
+ * Test method for 'org.ajax4jsf.webapp.WebXml.getFacesResourceURL(FacesContext, String)'
+ */
+ public void testGetFacesResourceURL() throws ServletException {
+ WebXml webXml = new WebXml();
+
+ webXml.init(context, "ajax4jsf");
+
+ String resourceURL = webXml.getFacesResourceURL(facesContext, "foo.Bar", false);
+
+ System.out.println(resourceURL);
+ assertEquals("/testContext/" + WebXml.SESSION_RESOURCE_URI_PREFIX_VERSIONED + "foo.Bar.jsf", resourceURL);
+ resourceURL = webXml.getFacesResourceURL(facesContext, "rich.Tree", true);
+ System.out.println(resourceURL);
+ assertEquals("/testContext/" + WebXml.GLOBAL_RESOURCE_URI_PREFIX_VERSIONED + "rich.Tree.jsf", resourceURL);
+ }
+
+ public void testOverridenLegacyGetFacesResourceURL() throws ServletException {
+ context.addInitParameter(WebXml.RESOURCE_URI_PREFIX_PARAM, "j4a/");
+
+ WebXml webXml = new WebXml();
+
+ webXml.init(context, "ajax4jsf");
+
+ String resourceURL = webXml.getFacesResourceURL(facesContext, "foo.Bar", false);
+
+ assertEquals("/testContext/j4a/foo.Bar.jsf", resourceURL);
+ resourceURL = webXml.getFacesResourceURL(facesContext, "rich.Tree", true);
+ assertEquals("/testContext/j4a/rich.Tree.jsf", resourceURL);
+ }
+
+ public void testOverridenGetFacesResourceURL() throws ServletException {
+ context.addInitParameter(WebXml.GLOBAL_RESOURCE_URI_PREFIX_PARAM, "glb/");
+ context.addInitParameter(WebXml.SESSION_RESOURCE_URI_PREFIX_PARAM, "ssn/");
+
+ WebXml webXml = new WebXml();
+
+ webXml.init(context, "ajax4jsf");
+
+ String resourceURL = webXml.getFacesResourceURL(facesContext, "foo.Bar", false);
+
+ assertEquals("/testContext/ssn/foo.Bar.jsf", resourceURL);
+ resourceURL = webXml.getFacesResourceURL(facesContext, "rich.Tree", true);
+ assertEquals("/testContext/glb/rich.Tree.jsf", resourceURL);
+ }
+
+ /*
+ * Test method for 'org.ajax4jsf.webapp.WebXml.getFacesResourceKey(HttpServletRequest)'
+ */
+ public void testGetFacesResourceKey() {}
+
+ /*
+ * Test method for 'org.ajax4jsf.webapp.WebXml.isFacesRequest(HttpServletRequest)'
+ */
+ public void testIsFacesRequest() {}
+
+ /*
+ * Test method for 'org.ajax4jsf.webapp.WebXml.setFilterName(String)'
+ */
+ public void testSetFilterName() {}
}
Modified: root/framework/trunk/legacy-tests/src/test/java/org/richfaces/util/RenderPhaseComponentVisitorUtilsTest.java
===================================================================
--- root/framework/trunk/legacy-tests/src/test/java/org/richfaces/util/RenderPhaseComponentVisitorUtilsTest.java 2009-11-02 11:33:49 UTC (rev 15806)
+++ root/framework/trunk/legacy-tests/src/test/java/org/richfaces/util/RenderPhaseComponentVisitorUtilsTest.java 2009-11-02 12:03:55 UTC (rev 15807)
@@ -1,24 +1,25 @@
+
/**
- *
+ *
*/
package org.richfaces.util;
import org.apache.shale.test.base.AbstractJsfTestCase;
+
import org.richfaces.event.RenderPhaseComponentVisitor;
public class RenderPhaseComponentVisitorUtilsTest extends AbstractJsfTestCase {
+ public RenderPhaseComponentVisitorUtilsTest(String name) {
+ super(name);
+ }
- public RenderPhaseComponentVisitorUtilsTest(String name) {
- super(name);
- }
+ /**
+ * Test method for {@link org.richfaces.util.ComponentPhaseEventHandlerUtils#getHandlers()}.
+ */
+ public void testGetHandlers() {
+ RenderPhaseComponentVisitor[] handlers = RenderPhaseComponentVisitorUtils.getVisitors(facesContext);
- /**
- * Test method for {@link org.richfaces.util.ComponentPhaseEventHandlerUtils#getHandlers()}.
- */
- public void testGetHandlers() {
- RenderPhaseComponentVisitor[] handlers = RenderPhaseComponentVisitorUtils.getVisitors(facesContext);
- assertNotNull(handlers);
- assertTrue(handlers.length > 0);
- }
-
+ assertNotNull(handlers);
+ assertTrue(handlers.length > 0);
+ }
}
15 years, 10 months
JBoss Rich Faces SVN: r15806 - in root/framework/trunk/impl/src: main/java/org/richfaces/renderkit/html and 25 other directories.
by richfaces-svn-commits@lists.jboss.org
Author: Alex.Kolonitsky
Date: 2009-11-02 06:33:49 -0500 (Mon, 02 Nov 2009)
New Revision: 15806
Added:
root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/Test.java
root/framework/trunk/impl/src/test/java/org/richfaces/json/Test.java
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/AttributeParametersEncoder.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/CompositeRenderer.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/Expression.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/InputRendererBase.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/MacroDefinitionJSContentHandler.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/RendererContributor.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/ScriptOptions.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/ScriptOptionsContributor.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/TemplateEncoderRendererBase.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/Base2WayGradient.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/GradientA.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/ButtonDisabledBackgroundImage.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/GradientAlignment.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/GradientType.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/StandardButtonBgImage.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/StandardButtonPressedBgImage.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/package-info.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/package-info.java
root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/package-info.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractBaseResource.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractCacheableResource.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AnimatedTestResource.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/CachedResourceImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/DefaultResourceCodec.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceCodec.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceUtils.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/AbstractChainableSkinImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/BasicSkinImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/DefaultSkinImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/DummySkinConfiguration.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinBean.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinFactoryImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinPropertyResolver.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinVariableResolver.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/ThemeImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/skin/package-info.java
root/framework/trunk/impl/src/main/java/org/richfaces/util/CollectionsUtils.java
root/framework/trunk/impl/src/main/java/org/richfaces/util/ReferenceMap.java
root/framework/trunk/impl/src/main/java/org/richfaces/util/RequestStateManager.java
root/framework/trunk/impl/src/main/java/org/richfaces/util/Util.java
root/framework/trunk/impl/src/main/java/org/richfaces/util/package-info.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/BaseCacheTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/EhCacheTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/JBossCacheTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/OsCacheTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/codec/CodecTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/FacesConfigTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/FrameworkConfigurationTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/MockServletContext.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/MockXmlReader.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/StateHandlerTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/WebXMLTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/WebappHandlerTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/context/InitParametersTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/css/CssCompressorTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/event/EventsQueueTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/parser/FastBufferOutputStreamTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/parser/FastBufferWriterTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/javascript/JSMinTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/renderkit/RendererUtilsTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/resource/cached/DualLRUMapTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/util/LRUMapTest.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/util/NumericStreamsTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/component/UIRangedNumberInputTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/component/nsutils/NSUtilsTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/component/util/ComponentUtilTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/component/util/FormUtilTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/component/util/HtmlUtilTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/javascript/QUnitTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/json/JsonTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/json/SerializationTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/CompositeRendererTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/TemplateEncoderRendererBaseTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/TemplateUtilTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/html/images/GradientEnumsTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractBaseResourceTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractCacheableResourceTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/CacheableResourceImpl.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/CachedResourceImplTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/EmptyStreamResource.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/MarkerFileResourceImpl.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/NoMarkerFileResourceImpl.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/NonCacheableResourceImpl.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceHandlerImplTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceUtilsTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/StateHolderResourceImpl.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/VersionedResourceImpl.java
root/framework/trunk/impl/src/test/java/org/richfaces/skin/Bean.java
root/framework/trunk/impl/src/test/java/org/richfaces/skin/SkinTestCase.java
root/framework/trunk/impl/src/test/java/org/richfaces/skin/SkinThreadsTestCase.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/AttributeParametersEncoder.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/AttributeParametersEncoder.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/AttributeParametersEncoder.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import java.io.IOException;
@@ -29,8 +31,8 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 30.01.2007
- *
+ *
*/
public interface AttributeParametersEncoder {
- public void doEncode(FacesContext context, UIComponent component) throws IOException;
+ public void doEncode(FacesContext context, UIComponent component) throws IOException;
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/CompositeRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/CompositeRenderer.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/CompositeRenderer.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,9 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
+import org.ajax4jsf.renderkit.AjaxChildrenRenderer;
+
import java.io.IOException;
+
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -29,132 +34,120 @@
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
-import org.ajax4jsf.renderkit.AjaxChildrenRenderer;
-
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 18.12.2006
- *
+ *
*/
public abstract class CompositeRenderer extends AjaxChildrenRenderer {
- private List<RendererContributor> renderers = new ArrayList<RendererContributor>();
+ private static final Command MERGE_OPTIONS_COMMAND = new Command() {
+ @Override
+ protected void execute(RendererContributor renderer, FacesContext context, UIComponent component,
+ Object argument) {
+ ScriptOptions initialOptions = (ScriptOptions) argument;
+ ScriptOptions builtOptions = renderer.buildOptions(context, component);
- private List<AttributeParametersEncoder> parameterEncoders = new ArrayList<AttributeParametersEncoder>();
-
- private abstract static class Command {
- protected final void execute(Iterator<?> renderers,
- FacesContext facesContext,
- UIComponent component,
- Object argument,
- Class<?> clazz) {
+ if (builtOptions != null) {
+ initialOptions.merge(builtOptions);
+ }
+ }
+ };
+ private static final Command GET_SCRIPT_CONTRIBUTIONS = new Command() {
+ @Override
+ protected void execute(RendererContributor renderer, FacesContext context, UIComponent component,
+ Object argument) {
+ String contribution = renderer.getScriptContribution(context, component);
- while (renderers.hasNext()) {
- RendererContributor contributor = (RendererContributor) renderers.next();
- Class<?> acceptableClass = contributor.getAcceptableClass();
- if (clazz == null || acceptableClass == null || acceptableClass.isAssignableFrom(clazz)) {
- execute(contributor, facesContext, component, argument);
- }
- }
- }
+ if (contribution != null) {
+ ((List<String>) argument).add(contribution);
+ }
+ }
+ };
+ private List<RendererContributor> renderers = new ArrayList<RendererContributor>();
+ private List<AttributeParametersEncoder> parameterEncoders = new ArrayList<AttributeParametersEncoder>();
+ private final Command decodeCommand = new Command() {
+ @Override
+ protected void execute(RendererContributor renderer, FacesContext context, UIComponent component,
+ Object argument) {
+ renderer.decode(context, component, CompositeRenderer.this);
+ }
+ };
- protected abstract void execute(RendererContributor renderer,
- FacesContext facesContext,
- UIComponent component,
- Object argument);
- }
+ @Override
+ protected void doDecode(FacesContext context, UIComponent component) {
+ super.doDecode(context, component);
+ decodeCommand.execute(renderers.iterator(), context, component, null, component.getClass());
+ }
- private final Command DECODE_COMMAND = new Command() {
+ protected void mergeScriptOptions(ScriptOptions scriptOptions, FacesContext context, UIComponent component) {
+ mergeScriptOptions(scriptOptions, context, component, null);
+ }
- protected void execute(RendererContributor renderer, FacesContext context,
- UIComponent component, Object argument) {
+ protected void mergeScriptOptions(ScriptOptions scriptOptions, FacesContext context, UIComponent component,
+ Class<?> acceptableClass) {
+ MERGE_OPTIONS_COMMAND.execute(renderers.iterator(), context, component, scriptOptions, acceptableClass);
+ }
- renderer.decode(context, component, CompositeRenderer.this);
- }
- };
+ protected String getScriptContributions(String varString, FacesContext context, UIComponent component) {
+ return getScriptContributions(varString, context, component, component.getClass());
+ }
- private static final Command MERGE_OPTIONS_COMMAND = new Command() {
+ protected String getScriptContributions(String varString, FacesContext context, UIComponent component,
+ Class<?> acceptableClass) {
+ List<String> scriptContributions = new ArrayList<String>();
- protected void execute(RendererContributor renderer, FacesContext context,
- UIComponent component, Object argument) {
+ GET_SCRIPT_CONTRIBUTIONS.execute(renderers.iterator(), context, component, scriptContributions,
+ acceptableClass);
- ScriptOptions initialOptions = (ScriptOptions) argument;
+ StringBuffer result = new StringBuffer();
- ScriptOptions builtOptions = renderer.buildOptions(context, component);
- if (builtOptions != null) {
- initialOptions.merge(builtOptions);
- }
- }
+ for (Iterator<String> itr = scriptContributions.iterator(); itr.hasNext(); ) {
+ result.append(varString);
+ result.append(itr.next());
+ }
- };
+ return result.toString();
+ }
- private static final Command GET_SCRIPT_CONTRIBUTIONS = new Command() {
+ protected void addContributor(RendererContributor renderer) {
+ renderers.add(renderer);
+ }
- protected void execute(RendererContributor renderer,
- FacesContext context, UIComponent component,
- Object argument) {
+ protected RendererContributor[] getContributors() {
+ return (RendererContributor[]) renderers.toArray(new RendererContributor[renderers.size()]);
+ }
- String contribution = renderer.getScriptContribution(context, component);
- if (contribution != null) {
- ((List<String>) argument).add(contribution);
- }
- }
-
- };
+ protected void addParameterEncoder(AttributeParametersEncoder encoder) {
+ parameterEncoders.add(encoder);
+ }
- protected void doDecode(FacesContext context, UIComponent component) {
- super.doDecode(context, component);
+ protected AttributeParametersEncoder[] getParameterEncoders() {
+ return (AttributeParametersEncoder[]) parameterEncoders.toArray(
+ new AttributeParametersEncoder[renderers.size()]);
+ }
- DECODE_COMMAND.execute(renderers.iterator(), context, component, null, component.getClass());
- }
+ public void encodeAttributeParameters(FacesContext context, UIComponent component) throws IOException {
+ for (Iterator<AttributeParametersEncoder> iterator = parameterEncoders.iterator(); iterator.hasNext(); ) {
+ AttributeParametersEncoder encoder = iterator.next();
- protected void mergeScriptOptions(ScriptOptions scriptOptions, FacesContext context, UIComponent component) {
- mergeScriptOptions(scriptOptions, context, component, null);
- }
-
- protected void mergeScriptOptions(ScriptOptions scriptOptions, FacesContext context, UIComponent component, Class<?> acceptableClass) {
- MERGE_OPTIONS_COMMAND.execute(renderers.iterator(), context, component, scriptOptions, acceptableClass);
- }
+ encoder.doEncode(context, component);
+ }
+ }
- protected String getScriptContributions(String varString, FacesContext context, UIComponent component) {
- return getScriptContributions(varString, context, component, component.getClass());
- }
-
- protected String getScriptContributions(String varString, FacesContext context, UIComponent component, Class<?> acceptableClass) {
- List<String> scriptContributions = new ArrayList<String>();
-
- GET_SCRIPT_CONTRIBUTIONS.execute(renderers.iterator(), context, component, scriptContributions, acceptableClass);
-
- StringBuffer result = new StringBuffer();
- for (Iterator<String> itr = scriptContributions.iterator(); itr.hasNext(); ) {
- result.append(varString);
- result.append(itr.next());
- }
-
- return result.toString();
- }
-
- protected void addContributor(RendererContributor renderer) {
- renderers.add(renderer);
- }
-
- protected RendererContributor[] getContributors() {
- return (RendererContributor[]) renderers.toArray(new RendererContributor[renderers.size()]);
- }
-
- protected void addParameterEncoder(AttributeParametersEncoder encoder) {
- parameterEncoders.add(encoder);
- }
-
- protected AttributeParametersEncoder[] getParameterEncoders() {
- return (AttributeParametersEncoder[]) parameterEncoders.toArray(new AttributeParametersEncoder[renderers.size()]);
- }
+ private abstract static class Command {
+ protected final void execute(Iterator<?> renderers, FacesContext facesContext, UIComponent component,
+ Object argument, Class<?> clazz) {
+ while (renderers.hasNext()) {
+ RendererContributor contributor = (RendererContributor) renderers.next();
+ Class<?> acceptableClass = contributor.getAcceptableClass();
- public void encodeAttributeParameters(FacesContext context, UIComponent component) throws IOException {
- for (Iterator<AttributeParametersEncoder> iterator = parameterEncoders.iterator(); iterator.hasNext();) {
- AttributeParametersEncoder encoder = iterator.next();
-
- encoder.doEncode(context, component);
- }
- }
-
+ if ((clazz == null) || (acceptableClass == null) || acceptableClass.isAssignableFrom(clazz)) {
+ execute(contributor, facesContext, component, argument);
+ }
+ }
+ }
+
+ protected abstract void execute(RendererContributor renderer, FacesContext facesContext, UIComponent component,
+ Object argument);
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/Expression.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/Expression.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/Expression.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,6 +18,9 @@
* 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.richfaces.renderkit;
/**
@@ -26,42 +29,53 @@
*
*/
public class Expression {
- private Object expression;
+ private Object expression;
- public Expression(Object expression) {
- super();
- this.expression = expression;
- }
+ public Expression(Object expression) {
+ super();
+ this.expression = expression;
+ }
- public Object getExpression() {
- return expression;
- }
-
- public String toString() {
- return super.toString() + "[" + expression + "]";
- }
+ public Object getExpression() {
+ return expression;
+ }
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((expression == null) ? 0 : expression.hashCode());
- return result;
- }
+ public String toString() {
+ return super.toString() + "[" + expression + "]";
+ }
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- final Expression other = (Expression) obj;
- if (expression == null) {
- if (other.expression != null)
- return false;
- } else if (!expression.equals(other.expression))
- return false;
- return true;
- }
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+
+ result = prime * result + ((expression == null) ? 0 : expression.hashCode());
+
+ return result;
+ }
+
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+
+ if (obj == null) {
+ return false;
+ }
+
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+
+ final Expression other = (Expression) obj;
+
+ if (expression == null) {
+ if (other.expression != null) {
+ return false;
+ }
+ } else if (!expression.equals(other.expression)) {
+ return false;
+ }
+
+ return true;
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/InputRendererBase.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/InputRendererBase.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/InputRendererBase.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,8 +19,13 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
+import org.ajax4jsf.renderkit.AjaxComponentRendererBase;
+import org.ajax4jsf.util.SelectUtils;
+
import java.util.Map;
import javax.faces.component.UIComponent;
@@ -29,54 +34,55 @@
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
-import org.ajax4jsf.renderkit.AjaxComponentRendererBase;
-import org.ajax4jsf.util.SelectUtils;
-
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 23.01.2007
- *
+ *
*/
public class InputRendererBase extends AjaxComponentRendererBase {
+ protected Class getComponentClass() {
+ return UIInput.class;
+ }
- protected Class getComponentClass() {
- return UIInput.class;
- }
-
- protected void doDecode(FacesContext context, UIComponent component) {
- String clientId = component.getClientId(context);
+ protected void doDecode(FacesContext context, UIComponent component) {
+ String clientId = component.getClientId(context);
Map requestParameterMap = context.getExternalContext().getRequestParameterMap();
String newValue = (String) requestParameterMap.get(clientId);
+
if (null != newValue) {
- UIInput input = (UIInput) component;
+ UIInput input = (UIInput) component;
+
input.setSubmittedValue(newValue);
}
- }
-
- public Object getConvertedValue(FacesContext context, UIComponent component, Object val) throws ConverterException {
- return SelectUtils.getConvertedUIInputValue(context, (UIInput) component, (String) val);
- }
-
- public String getInputValue(FacesContext context, UIInput component){
- UIInput input = (UIInput) component;
- String value = (String) input.getSubmittedValue();
- if(value == null){
- Object curVal = input.getValue();
- Converter converter = SelectUtils.getConverterForProperty(context, input, "value");
- if(converter != null){
- value = converter.getAsString(context, input, curVal);
- } else {
- if(curVal == null){
- value = "";
- } else {
- value = curVal.toString();
- }
- }
- }
- if(value == null){
- value = "";
- }
- return value;
- }
+ }
+ public Object getConvertedValue(FacesContext context, UIComponent component, Object val) throws ConverterException {
+ return SelectUtils.getConvertedUIInputValue(context, (UIInput) component, (String) val);
+ }
+
+ public String getInputValue(FacesContext context, UIInput component) {
+ UIInput input = (UIInput) component;
+ String value = (String) input.getSubmittedValue();
+
+ if (value == null) {
+ Object curVal = input.getValue();
+ Converter converter = SelectUtils.getConverterForProperty(context, input, "value");
+
+ if (converter != null) {
+ value = converter.getAsString(context, input, curVal);
+ } else {
+ if (curVal == null) {
+ value = "";
+ } else {
+ value = curVal.toString();
+ }
+ }
+ }
+
+ if (value == null) {
+ value = "";
+ }
+
+ return value;
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/MacroDefinitionJSContentHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/MacroDefinitionJSContentHandler.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/MacroDefinitionJSContentHandler.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,232 +18,229 @@
* 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.richfaces.renderkit;
+import org.richfaces.javacc.RichMacroDefinition;
+import org.richfaces.json.JSContentHandler;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
import java.io.FilterWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.Writer;
+
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import org.richfaces.javacc.RichMacroDefinition;
-import org.richfaces.json.JSContentHandler;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-
/**
* @author Nick Belaevski - mailto:nbelaevski@exadel.com created 21.06.2007
- *
+ *
*/
public class MacroDefinitionJSContentHandler extends JSContentHandler {
- private String prolog;
- private String epilog;
+ private String epilog;
+ private String prolog;
- /**
- * Writer will not output duplicate commas
- * @author Maksim Kaszynski
- *
- */
- static class WellFormedWriter extends FilterWriter {
-
- private char lastChar;
-
- public WellFormedWriter(Writer out) {
- super(out);
- }
-
- public void write(char[] cbuf, int off, int len) throws IOException {
-
-
- //Skip comma
- while (cbuf[off] == lastChar && lastChar == ',' && len > 0) {
- off++;
- len--;
- }
-
- while(len > 1 && cbuf[off] == cbuf[off+1] && cbuf[off] == ','){
- len--;
- off++;
- }
-
-
- super.write(cbuf, off, len);
-
- lastChar = cbuf[off + len - 1];
-
- }
+ public MacroDefinitionJSContentHandler(Writer writer, String prolog, String epilog) {
+ super(writer);
+ this.prolog = prolog;
+ this.epilog = epilog;
+ }
- public void write(int c) throws IOException {
- if (c != lastChar || lastChar != ',') {
- super.write(c);
- lastChar = (char) c;
- }
- }
-
- }
-
- public MacroDefinitionJSContentHandler(Writer writer, String prolog,
- String epilog) {
- super(writer);
- this.prolog = prolog;
- this.epilog = epilog;
- }
+ protected List<?> parseExpressiion(String expressionString) throws SAXException {
+ try {
+ if (expressionString.length() != 0) {
+ List<?> result = new RichMacroDefinition(new StringReader(expressionString)).expression();
- protected List<?> parseExpressiion(String expressionString) throws SAXException {
- try {
- if (expressionString.length() != 0) {
- List<?> result = new RichMacroDefinition(new StringReader(expressionString)).expression();
+ return result;
+ } else {
+ List<Object> list = new ArrayList<Object>(1);
- return result;
- } else {
- List<Object> list = new ArrayList<Object>(1);
- list.add("");
-
- return list;
- }
- } catch (Exception e) {
- throw new SAXException(e.getMessage(), e);
- }
- }
+ list.add("");
- private void encodeExpressionString(String string) throws IOException,
- SAXException {
-
- /*if (string.length() == 0) {
- this.outputWriter.write("\'\'");
- }*/
-
- List<?> parsedExpressiion = parseExpressiion(string);
+ return list;
+ }
+ } catch (Exception e) {
+ throw new SAXException(e.getMessage(), e);
+ }
+ }
- boolean isExpression = false;
- for (Iterator<?> iterator = parsedExpressiion.iterator(); iterator
- .hasNext();) {
- Object next = (Object) iterator.next();
- if (next instanceof Expression) {
- isExpression = true;
- break;
- }
- }
+ private void encodeExpressionString(String string) throws IOException, SAXException {
- if (isExpression) {
- this.outputWriter.write("function (context) { return ");
- }
+ /*
+ * if (string.length() == 0) {
+ * this.outputWriter.write("\'\'");
+ * }
+ */
+ List<?> parsedExpressiion = parseExpressiion(string);
+ boolean isExpression = false;
- boolean first = true;
- for (Iterator<?> iterator = parsedExpressiion.iterator(); iterator
- .hasNext();) {
- Object next = (Object) iterator.next();
+ for (Iterator<?> iterator = parsedExpressiion.iterator(); iterator.hasNext(); ) {
+ Object next = (Object) iterator.next();
- if (next == null) {
- continue;
- }
+ if (next instanceof Expression) {
+ isExpression = true;
- if (!first) {
- this.outputWriter.write('+');
- }
+ break;
+ }
+ }
- if (next instanceof Expression) {
- Expression macroExpression = (Expression) next;
+ if (isExpression) {
+ this.outputWriter.write("function (context) { return ");
+ }
- this.outputWriter.write(prolog);
- this.encode(macroExpression.getExpression().toString());
- this.outputWriter.write(epilog);
- } else {
- this.outputWriter.write('\'');
- this.encode(next.toString());
- this.outputWriter.write('\'');
- }
+ boolean first = true;
- first = false;
- }
+ for (Iterator<?> iterator = parsedExpressiion.iterator(); iterator.hasNext(); ) {
+ Object next = (Object) iterator.next();
- if (isExpression) {
- this.outputWriter.write(";}");
- }
- }
+ if (next == null) {
+ continue;
+ }
- protected void encodeAttributeValue(Attributes attributes, int idx)
- throws SAXException, IOException {
+ if (!first) {
+ this.outputWriter.write('+');
+ }
- String value = attributes.getValue(idx);
- encodeExpressionString(value);
- }
+ if (next instanceof Expression) {
+ Expression macroExpression = (Expression) next;
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- if (isProcessingCdata()) {
- super.characters(ch, start, length);
- } else {
- Writer oldWriter = outputWriter;
- outputWriter = new WellFormedWriter(oldWriter);
-
- try {
- List<?> parsedExpression = parseExpressiion(new String(ch, start,
- length));
- for (Iterator<?> iterator = parsedExpression.iterator(); iterator
- .hasNext();) {
+ this.outputWriter.write(prolog);
+ this.encode(macroExpression.getExpression().toString());
+ this.outputWriter.write(epilog);
+ } else {
+ this.outputWriter.write('\'');
+ this.encode(next.toString());
+ this.outputWriter.write('\'');
+ }
- Object next = iterator.next();
+ first = false;
+ }
- if (next instanceof Expression) {
- Expression expression = (Expression) next;
+ if (isExpression) {
+ this.outputWriter.write(";}");
+ }
+ }
- if (this.isBeforeDocumentStart() || level < 0)
- return;
- try {
- if (level != 0 && !this.closeElement(false)
- && this.isProcessingCdata() == false) {
- this.outputWriter.write(',');
- }
+ protected void encodeAttributeValue(Attributes attributes, int idx) throws SAXException, IOException {
+ String value = attributes.getValue(idx);
- if (this.isProcessingCdata() == false) {
- this.outputWriter.write("new ET(");
- }
+ encodeExpressionString(value);
+ }
- this.outputWriter
- .write("function (context) { return ");
- this.outputWriter.write(prolog);
- this.encode(expression.getExpression().toString());
- this.outputWriter.write(epilog);
- this.outputWriter.write("}");
+ public void characters(char[] ch, int start, int length) throws SAXException {
+ if (isProcessingCdata()) {
+ super.characters(ch, start, length);
+ } else {
+ Writer oldWriter = outputWriter;
- if (this.isProcessingCdata() == false) {
- this.outputWriter.write(")");
- }
- } catch (IOException e) {
- throw new SAXException("Write error", e);
- }
+ outputWriter = new WellFormedWriter(oldWriter);
- } else {
- char[] cs = next.toString().toCharArray();
- super.characters(cs, 0, cs.length);
- }
+ try {
+ List<?> parsedExpression = parseExpressiion(new String(ch, start, length));
- if (iterator.hasNext()) {
- try {
- this.outputWriter.write(',');
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- } finally {
- outputWriter = oldWriter;
- }
- }
- }
+ for (Iterator<?> iterator = parsedExpression.iterator(); iterator.hasNext(); ) {
+ Object next = iterator.next();
- protected void encodeText(char[] chars, int start, int length)
- throws SAXException, IOException {
- if (!isProcessingCdata()) {
- String str = new String(chars, start, length);
- encodeExpressionString(str);
- } else {
- super.encodeText(chars, start, length);
- }
- }
+ if (next instanceof Expression) {
+ Expression expression = (Expression) next;
+ if (this.isBeforeDocumentStart() || (level < 0)) {
+ return;
+ }
+
+ try {
+ if ((level != 0) && !this.closeElement(false) && !this.isProcessingCdata()) {
+ this.outputWriter.write(',');
+ }
+
+ if (!this.isProcessingCdata()) {
+ this.outputWriter.write("new ET(");
+ }
+
+ this.outputWriter.write("function (context) { return ");
+ this.outputWriter.write(prolog);
+ this.encode(expression.getExpression().toString());
+ this.outputWriter.write(epilog);
+ this.outputWriter.write("}");
+
+ if (!this.isProcessingCdata()) {
+ this.outputWriter.write(")");
+ }
+ } catch (IOException e) {
+ throw new SAXException("Write error", e);
+ }
+ } else {
+ char[] cs = next.toString().toCharArray();
+
+ super.characters(cs, 0, cs.length);
+ }
+
+ if (iterator.hasNext()) {
+ try {
+ this.outputWriter.write(',');
+ } catch (IOException e) {
+
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+ } finally {
+ outputWriter = oldWriter;
+ }
+ }
+ }
+
+ protected void encodeText(char[] chars, int start, int length) throws SAXException, IOException {
+ if (!isProcessingCdata()) {
+ String str = new String(chars, start, length);
+
+ encodeExpressionString(str);
+ } else {
+ super.encodeText(chars, start, length);
+ }
+ }
+
+ /**
+ * Writer will not output duplicate commas
+ * @author Maksim Kaszynski
+ *
+ */
+ static class WellFormedWriter extends FilterWriter {
+ private char lastChar;
+
+ public WellFormedWriter(Writer out) {
+ super(out);
+ }
+
+ public void write(char[] cbuf, int off, int len) throws IOException {
+
+ // Skip comma
+ while ((cbuf[off] == lastChar) && (lastChar == ',') && (len > 0)) {
+ off++;
+ len--;
+ }
+
+ while ((len > 1) && (cbuf[off] == cbuf[off + 1]) && (cbuf[off] == ',')) {
+ len--;
+ off++;
+ }
+
+ super.write(cbuf, off, len);
+ lastChar = cbuf[off + len - 1];
+ }
+
+ public void write(int c) throws IOException {
+ if ((c != lastChar) || (lastChar != ',')) {
+ super.write(c);
+ lastChar = (char) c;
+ }
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/RendererContributor.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/RendererContributor.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/RendererContributor.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import javax.faces.component.UIComponent;
@@ -27,13 +29,16 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 18.12.2006
- *
+ *
*/
public interface RendererContributor extends ScriptOptionsContributor {
- public String getScriptContribution(FacesContext context, UIComponent component);
-
- public void decode(FacesContext context, UIComponent component, CompositeRenderer compositeRenderer);
- public String[] getScriptDependencies();
- public String[] getStyleDependencies();
- public Class<?> getAcceptableClass();
+ public String getScriptContribution(FacesContext context, UIComponent component);
+
+ public void decode(FacesContext context, UIComponent component, CompositeRenderer compositeRenderer);
+
+ public String[] getScriptDependencies();
+
+ public String[] getStyleDependencies();
+
+ public Class<?> getAcceptableClass();
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/ScriptOptions.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/ScriptOptions.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/ScriptOptions.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,8 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
+import org.ajax4jsf.javascript.JSFunctionDefinition;
+import org.ajax4jsf.javascript.ScriptStringBase;
+import org.ajax4jsf.javascript.ScriptUtils;
+
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@@ -28,79 +34,78 @@
import javax.faces.component.UIComponent;
-import org.ajax4jsf.javascript.JSFunctionDefinition;
-import org.ajax4jsf.javascript.ScriptStringBase;
-import org.ajax4jsf.javascript.ScriptUtils;
-
/**
* @author Maksim Kaszynski
*
*/
public class ScriptOptions extends ScriptStringBase {
+ protected Map<String, Object> opts = new HashMap<String, Object>();
+ private UIComponent component;
- private UIComponent component;
- protected Map<String, Object> opts = new HashMap<String, Object>();
-
- public ScriptOptions(UIComponent component) {
- this.component = component;
- }
- public void appendScript(StringBuffer functionString) {
- functionString.append(ScriptUtils.toScript(opts));
- }
-
- public void addOption(String name) {
- if (name != null) {
- Object value = component.getAttributes().get(name);
- addOption(name, value);
- }
- }
-
- @SuppressWarnings("unchecked")
- public void addOption(String name, Object value) {
- if (value != null) {
- Object object = opts.get(name);
- if (object instanceof Map && value instanceof Map) {
- ((Map) object).putAll((Map) value);
- } else {
- opts.put(name, value);
- }
- }
- }
- public void addEventHandler(String event, String handler) {
- if (event != null && handler != null) {
- JSFunctionDefinition functionDefinition =
- new JSFunctionDefinition("event");
-
- functionDefinition.addToBody(handler);
- functionDefinition.addToBody(";return true;");
- addEventHandler(event, functionDefinition);
- }
- }
-
- public void addEventHandler(String event) {
- if (event != null) {
- String handler = (String) component.getAttributes().get(event);
- addEventHandler(event, handler);
- }
- }
-
- public void addEventHandler(String event, JSFunctionDefinition definition) {
- if (event != null && definition != null) {
- opts.put(event, definition);
- }
- }
- public Map<String,Object> getMap() {
- return opts;
- }
+ public ScriptOptions(UIComponent component) {
+ this.component = component;
+ }
- public void merge(ScriptOptions anotherOptions) {
- Iterator<Entry<String, Object>> entrySetIterator = anotherOptions.opts.entrySet().iterator();
- while (entrySetIterator.hasNext()) {
- Entry<String, Object> entry = entrySetIterator.next();
-
- addOption(entry.getKey(), entry.getValue());
- }
- }
+ public void appendScript(StringBuffer functionString) {
+ functionString.append(ScriptUtils.toScript(opts));
+ }
+ public void addOption(String name) {
+ if (name != null) {
+ Object value = component.getAttributes().get(name);
+ addOption(name, value);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public void addOption(String name, Object value) {
+ if (value != null) {
+ Object object = opts.get(name);
+
+ if ((object instanceof Map) && (value instanceof Map)) {
+ ((Map) object).putAll((Map) value);
+ } else {
+ opts.put(name, value);
+ }
+ }
+ }
+
+ public void addEventHandler(String event, String handler) {
+ if ((event != null) && (handler != null)) {
+ JSFunctionDefinition functionDefinition = new JSFunctionDefinition("event");
+
+ functionDefinition.addToBody(handler);
+ functionDefinition.addToBody(";return true;");
+ addEventHandler(event, functionDefinition);
+ }
+ }
+
+ public void addEventHandler(String event) {
+ if (event != null) {
+ String handler = (String) component.getAttributes().get(event);
+
+ addEventHandler(event, handler);
+ }
+ }
+
+ public void addEventHandler(String event, JSFunctionDefinition definition) {
+ if ((event != null) && (definition != null)) {
+ opts.put(event, definition);
+ }
+ }
+
+ public Map<String, Object> getMap() {
+ return opts;
+ }
+
+ public void merge(ScriptOptions anotherOptions) {
+ Iterator<Entry<String, Object>> entrySetIterator = anotherOptions.opts.entrySet().iterator();
+
+ while (entrySetIterator.hasNext()) {
+ Entry<String, Object> entry = entrySetIterator.next();
+
+ addOption(entry.getKey(), entry.getValue());
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/ScriptOptionsContributor.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/ScriptOptionsContributor.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/ScriptOptionsContributor.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import javax.faces.component.UIComponent;
@@ -27,14 +29,15 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 18.12.2006
- *
+ *
*/
public interface ScriptOptionsContributor {
- /**
- * Create script options if component class is known for renderer to contribute
- * @param context
- * @param component
- * @return Built {@link ScriptOptions} instance or null if component is not acceptable
- */
- public ScriptOptions buildOptions(FacesContext context, UIComponent component);
+
+ /**
+ * Create script options if component class is known for renderer to contribute
+ * @param context
+ * @param component
+ * @return Built {@link ScriptOptions} instance or null if component is not acceptable
+ */
+ public ScriptOptions buildOptions(FacesContext context, UIComponent component);
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/TemplateEncoderRendererBase.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/TemplateEncoderRendererBase.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/TemplateEncoderRendererBase.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,8 +18,18 @@
* 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.richfaces.renderkit;
+import org.ajax4jsf.io.SAXResponseWriter;
+import org.ajax4jsf.renderkit.RendererBase;
+
+import org.richfaces.component.TemplateComponent;
+
+import org.xml.sax.ContentHandler;
+
import java.io.IOException;
import java.io.Writer;
@@ -27,73 +37,68 @@
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
-import org.ajax4jsf.io.SAXResponseWriter;
-import org.ajax4jsf.renderkit.RendererBase;
-import org.richfaces.component.TemplateComponent;
-import org.xml.sax.ContentHandler;
-
/**
* @author Nick Belaevski - mailto:nbelaevski@exadel.com
* created 22.06.2007
*
*/
public abstract class TemplateEncoderRendererBase extends RendererBase {
-
- public final boolean getRendersChildren() {
- return true;
- }
+ public final boolean getRendersChildren() {
+ return true;
+ }
- protected void writeScriptBody(FacesContext context, UIComponent component, boolean children)
- throws IOException {
- ResponseWriter writer = context.getResponseWriter();
- ContentHandler handler = createContentHandler(writer);
- SAXResponseWriter saxResponseWriter = new SAXResponseWriter(handler);
- context.setResponseWriter(saxResponseWriter);
-
- TemplateComponent templateComponent = null;
- if (component instanceof TemplateComponent) {
- templateComponent = (TemplateComponent) component;
- }
-
- try {
- if (templateComponent != null) {
- templateComponent.startTemplateEncode();
- }
- saxResponseWriter.startDocument();
-
- //TODO - how to handle extra "root" element?
- saxResponseWriter.startElement("root", component);
+ protected void writeScriptBody(FacesContext context, UIComponent component, boolean children) throws IOException {
+ ResponseWriter writer = context.getResponseWriter();
+ ContentHandler handler = createContentHandler(writer);
+ SAXResponseWriter saxResponseWriter = new SAXResponseWriter(handler);
- if (children) {
- this.renderChildren(context, component);
- } else {
- this.renderChild(context, component);
- }
-
- saxResponseWriter.endElement("root");
- saxResponseWriter.endDocument();
- } finally {
- if (templateComponent != null) {
- templateComponent.endTemplateEncode();
- }
+ context.setResponseWriter(saxResponseWriter);
- context.setResponseWriter(writer);
- }
- }
-
- public void encodeChildren(FacesContext context, UIComponent component)
- throws IOException {
- ResponseWriter writer = context.getResponseWriter();
- writer.startElement("script", component);
- writer.write("var evaluator = ");
- writeScriptBody(context, component, true);
- writer.write(";\n new Insertion.Top($('" + component.getClientId(context) + "'), evaluator.invoke('getContent', window).join(''));");
- writer.endElement("script");
- }
-
-
- protected ContentHandler createContentHandler(Writer writer) {
- return new MacroDefinitionJSContentHandler(writer, "Richfaces.evalMacro(\"", "\", context)");
- }
+ TemplateComponent templateComponent = null;
+ if (component instanceof TemplateComponent) {
+ templateComponent = (TemplateComponent) component;
+ }
+
+ try {
+ if (templateComponent != null) {
+ templateComponent.startTemplateEncode();
+ }
+
+ saxResponseWriter.startDocument();
+
+ // TODO - how to handle extra "root" element?
+ saxResponseWriter.startElement("root", component);
+
+ if (children) {
+ this.renderChildren(context, component);
+ } else {
+ this.renderChild(context, component);
+ }
+
+ saxResponseWriter.endElement("root");
+ saxResponseWriter.endDocument();
+ } finally {
+ if (templateComponent != null) {
+ templateComponent.endTemplateEncode();
+ }
+
+ context.setResponseWriter(writer);
+ }
+ }
+
+ public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
+ ResponseWriter writer = context.getResponseWriter();
+
+ writer.startElement("script", component);
+ writer.write("var evaluator = ");
+ writeScriptBody(context, component, true);
+ writer.write(";\n new Insertion.Top($('" + component.getClientId(context)
+ + "'), evaluator.invoke('getContent', window).join(''));");
+ writer.endElement("script");
+ }
+
+ protected ContentHandler createContentHandler(Writer writer) {
+ return new MacroDefinitionJSContentHandler(writer, "Richfaces.evalMacro(\"", "\", context)");
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/Base2WayGradient.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/Base2WayGradient.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/Base2WayGradient.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,211 +1,192 @@
+
/**
- *
+ *
*/
package org.richfaces.renderkit.html;
-import java.awt.Dimension;
-import java.awt.GradientPaint;
-import java.awt.Graphics2D;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Rectangle2D;
-
-import org.richfaces.renderkit.html.BaseGradient;
import org.richfaces.renderkit.html.images.GradientType;
import org.richfaces.renderkit.html.images.GradientType.BiColor;
+import java.awt.*;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Rectangle2D;
+
/**
* @author asmirnov
*
*/
public class Base2WayGradient extends BaseGradient {
+ /**
+ * @param horizontal
+ */
+ public Base2WayGradient(boolean horizontal) {
+ super(horizontal);
+ // TODO Auto-generated constructor stub
+ }
+ /**
+ * @param width
+ * @param height
+ */
+ public Base2WayGradient(int width, int height) {
+ super(width, height);
- /**
- * @param horizontal
- */
- public Base2WayGradient(boolean horizontal) {
- super(horizontal);
- // TODO Auto-generated constructor stub
- }
+ // TODO Auto-generated constructor stub
+ }
- /**
- * @param width
- * @param height
- * @param horizontal
- */
- public Base2WayGradient(int width, int height, boolean horizontal) {
- super(width, height, horizontal);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param baseColor
+ * @param gradientColor
+ */
+ public Base2WayGradient(String baseColor, String gradientColor) {
+ super(baseColor, gradientColor);
- /**
- * @param width
- * @param height
- * @param gradientHeight
- * @param horizontal
- */
- public Base2WayGradient(int width, int height, int gradientHeight,
- boolean horizontal) {
- super(width, height, gradientHeight, horizontal);
- // TODO Auto-generated constructor stub
- }
+ // TODO Auto-generated constructor stub
+ }
- /**
- * @param width
- * @param height
- * @param gradientHeight
- * @param baseColor
- * @param gradientColor
- * @param horizontal
- */
- public Base2WayGradient(int width, int height, int gradientHeight,
- String baseColor, String gradientColor, boolean horizontal) {
- super(width, height, gradientHeight, baseColor, gradientColor, horizontal);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param width
+ * @param height
+ * @param horizontal
+ */
+ public Base2WayGradient(int width, int height, boolean horizontal) {
+ super(width, height, horizontal);
- /**
- * @param width
- * @param height
- * @param gradientHeight
- * @param baseColor
- * @param gradientColor
- */
- public Base2WayGradient(int width, int height, int gradientHeight,
- String baseColor, String gradientColor) {
- super(width, height, gradientHeight, baseColor, gradientColor);
- // TODO Auto-generated constructor stub
- }
+ // TODO Auto-generated constructor stub
+ }
- /**
- * @param width
- * @param height
- * @param gradientHeight
- */
- public Base2WayGradient(int width, int height, int gradientHeight) {
- super(width, height, gradientHeight);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param width
+ * @param height
+ * @param gradientHeight
+ */
+ public Base2WayGradient(int width, int height, int gradientHeight) {
+ super(width, height, gradientHeight);
- /**
- * @param width
- * @param height
- * @param baseColor
- * @param gradientColor
- * @param horizontal
- */
- public Base2WayGradient(int width, int height, String baseColor,
- String gradientColor, boolean horizontal) {
- super(width, height, baseColor, gradientColor, horizontal);
- // TODO Auto-generated constructor stub
- }
+ // TODO Auto-generated constructor stub
+ }
- /**
- * @param width
- * @param height
- * @param baseColor
- * @param gradientColor
- */
- public Base2WayGradient(int width, int height, String baseColor,
- String gradientColor) {
- super(width, height, baseColor, gradientColor);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param baseColor
+ * @param gradientColor
+ * @param horizontal
+ */
+ public Base2WayGradient(String baseColor, String gradientColor, boolean horizontal) {
+ super(baseColor, gradientColor, horizontal);
- /**
- * @param width
- * @param height
- */
- public Base2WayGradient(int width, int height) {
- super(width, height);
- // TODO Auto-generated constructor stub
- }
+ // TODO Auto-generated constructor stub
+ }
- /**
- * @param baseColor
- * @param gradientColor
- * @param horizontal
- */
- public Base2WayGradient(String baseColor, String gradientColor,
- boolean horizontal) {
- super(baseColor, gradientColor, horizontal);
- // TODO Auto-generated constructor stub
- }
+ /**
+ * @param width
+ * @param height
+ * @param gradientHeight
+ * @param horizontal
+ */
+ public Base2WayGradient(int width, int height, int gradientHeight, boolean horizontal) {
+ super(width, height, gradientHeight, horizontal);
- /**
- * @param baseColor
- * @param gradientColor
- */
- public Base2WayGradient(String baseColor, String gradientColor) {
- super(baseColor, gradientColor);
- // TODO Auto-generated constructor stub
- }
+ // TODO Auto-generated constructor stub
+ }
+ /**
+ * @param width
+ * @param height
+ * @param baseColor
+ * @param gradientColor
+ */
+ public Base2WayGradient(int width, int height, String baseColor, String gradientColor) {
+ super(width, height, baseColor, gradientColor);
- protected void drawBackGradient(Graphics2D g2d, Rectangle2D rectangle, BiColor colors, int height) {
- if (colors != null) {
- GradientPaint gragient = new GradientPaint(0, (float)(rectangle.getHeight()-height), colors.getBottomColor(), 0, (float) rectangle.getHeight(), colors.getTopColor());
- g2d.setPaint(gragient);
- g2d.fill(rectangle);
- }
- }
+ // TODO Auto-generated constructor stub
+ }
+ /**
+ * @param width
+ * @param height
+ * @param gradientHeight
+ * @param baseColor
+ * @param gradientColor
+ */
+ public Base2WayGradient(int width, int height, int gradientHeight, String baseColor, String gradientColor) {
+ super(width, height, gradientHeight, baseColor, gradientColor);
- @Override
- protected void paintGradient(Graphics2D g2d, Dimension dim) {
- if (headerBackgroundColor != null && headerGradientColor != null) {
- BiColor biColor = new GradientType.BiColor(headerBackgroundColor, headerGradientColor);
- BiColor firstLayer = gradientType.getFirstLayerColors(biColor);
- BiColor secondLayer = gradientType.getSecondLayerColors(biColor);
+ // TODO Auto-generated constructor stub
+ }
- if (isHorizontal()) {
- //x -> y, y -> x
- g2d.transform(new AffineTransform(0, 1, 1, 0, 0, 0));
- dim.setSize(dim.height, dim.width);
- }
+ /**
+ * @param width
+ * @param height
+ * @param baseColor
+ * @param gradientColor
+ * @param horizontal
+ */
+ public Base2WayGradient(int width, int height, String baseColor, String gradientColor, boolean horizontal) {
+ super(width, height, baseColor, gradientColor, horizontal);
- int localGradientHeight = getGradientHeight();
- if (localGradientHeight < 0) {
- localGradientHeight = dim.height/2;
- }
+ // TODO Auto-generated constructor stub
+ }
- Rectangle2D rect = new Rectangle2D.Float(
- 0,
- 0,
- dim.width,
- localGradientHeight);
+ /**
+ * @param width
+ * @param height
+ * @param gradientHeight
+ * @param baseColor
+ * @param gradientColor
+ * @param horizontal
+ */
+ public Base2WayGradient(int width, int height, int gradientHeight, String baseColor, String gradientColor,
+ boolean horizontal) {
+ super(width, height, gradientHeight, baseColor, gradientColor, horizontal);
- drawGradient(g2d, rect, firstLayer, localGradientHeight);
+ // TODO Auto-generated constructor stub
+ }
- rect = new Rectangle2D.Float(
- 0,
- localGradientHeight,
- dim.width,
- dim.height);
+ protected void drawBackGradient(Graphics2D g2d, Rectangle2D rectangle, BiColor colors, int height) {
+ if (colors != null) {
+ GradientPaint gragient = new GradientPaint(0, (float) (rectangle.getHeight() - height),
+ colors.getBottomColor(), 0, (float) rectangle.getHeight(),
+ colors.getTopColor());
- drawBackGradient(g2d, rect, firstLayer, localGradientHeight);
+ g2d.setPaint(gragient);
+ g2d.fill(rectangle);
+ }
+ }
- int smallGradientHeight = localGradientHeight / 2;
+ @Override
+ protected void paintGradient(Graphics2D g2d, Dimension dim) {
+ if ((headerBackgroundColor != null) && (headerGradientColor != null)) {
+ BiColor biColor = new GradientType.BiColor(headerBackgroundColor, headerGradientColor);
+ BiColor firstLayer = gradientType.getFirstLayerColors(biColor);
+ BiColor secondLayer = gradientType.getSecondLayerColors(biColor);
- rect = new Rectangle2D.Float(
- 0,
- 0,
- dim.width,
- smallGradientHeight);
+ if (isHorizontal()) {
- drawGradient(g2d, rect, secondLayer, smallGradientHeight);
+ // x -> y, y -> x
+ g2d.transform(new AffineTransform(0, 1, 1, 0, 0, 0));
+ dim.setSize(dim.height, dim.width);
+ }
- rect = new Rectangle2D.Float(
- 0,
- dim.height-smallGradientHeight,
- dim.width,
- dim.height);
+ int localGradientHeight = getGradientHeight();
- drawBackGradient(g2d, rect, secondLayer, smallGradientHeight);
- }
- }
+ if (localGradientHeight < 0) {
+ localGradientHeight = dim.height / 2;
+ }
+ Rectangle2D rect = new Rectangle2D.Float(0, 0, dim.width, localGradientHeight);
+ drawGradient(g2d, rect, firstLayer, localGradientHeight);
+ rect = new Rectangle2D.Float(0, localGradientHeight, dim.width, dim.height);
+ drawBackGradient(g2d, rect, firstLayer, localGradientHeight);
+
+ int smallGradientHeight = localGradientHeight / 2;
+
+ rect = new Rectangle2D.Float(0, 0, dim.width, smallGradientHeight);
+ drawGradient(g2d, rect, secondLayer, smallGradientHeight);
+ rect = new Rectangle2D.Float(0, dim.height - smallGradientHeight, dim.width, dim.height);
+ drawBackGradient(g2d, rect, secondLayer, smallGradientHeight);
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/GradientA.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/GradientA.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/GradientA.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,10 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit.html;
public class GradientA extends BaseGradient {
- public GradientA() {
- super(30, 50, 20, "headerGradientColor", "headerBackgroundColor");
- }
-}
\ No newline at end of file
+ public GradientA() {
+ super(30, 50, 20, "headerGradientColor", "headerBackgroundColor");
+ }
+}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/ButtonDisabledBackgroundImage.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/ButtonDisabledBackgroundImage.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/ButtonDisabledBackgroundImage.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,16 +19,16 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit.html.images;
-
/**
* @author Nick Belaevski
* @since 3.2
*/
-
public class ButtonDisabledBackgroundImage extends BaseControlBackgroundImage {
- public ButtonDisabledBackgroundImage() {
- super("tableSubfooterBackgroundColor", "tableFooterBackgroundColor", 1);
- }
+ public ButtonDisabledBackgroundImage() {
+ super("tableSubfooterBackgroundColor", "tableFooterBackgroundColor", 1);
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/GradientAlignment.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/GradientAlignment.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/GradientAlignment.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,67 +19,60 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-package org.richfaces.renderkit.html.images;
-import static java.lang.Math.max;
+package org.richfaces.renderkit.html.images;
+
import java.util.Locale;
+import static java.lang.Math.max;
/**
* Created 22.04.2008
* @author Nick Belaevski
* @since 3.2
*/
-
public enum GradientAlignment {
TOP {
- @Override
- public int getBottomRectangleHeight(int imageHeight, int gradientHeight) {
- return max(imageHeight - gradientHeight, 0);
- }
-
- @Override
- public int getTopRectangleHeight(int imageHeight, int gradientHeight) {
- return 0;
- }
+ @Override
+ public int getBottomRectangleHeight(int imageHeight, int gradientHeight) {
+ return max(imageHeight - gradientHeight, 0);
+ }
+ @Override
+ public int getTopRectangleHeight(int imageHeight, int gradientHeight) {
+ return 0;
+ }
},
-
MIDDLE {
- @Override
- public int getBottomRectangleHeight(int imageHeight, int gradientHeight) {
- return max((imageHeight - gradientHeight) / 2, 0);
- }
-
- @Override
- public int getTopRectangleHeight(int imageHeight, int gradientHeight) {
- return getBottomRectangleHeight(imageHeight, gradientHeight);
- }
+ @Override
+ public int getBottomRectangleHeight(int imageHeight, int gradientHeight) {
+ return max((imageHeight - gradientHeight) / 2, 0);
+ }
+ @Override
+ public int getTopRectangleHeight(int imageHeight, int gradientHeight) {
+ return getBottomRectangleHeight(imageHeight, gradientHeight);
+ }
},
-
BOTTOM {
- @Override
- public int getBottomRectangleHeight(int imageHeight, int gradientHeight) {
- return 0;
- }
-
- @Override
- public int getTopRectangleHeight(int imageHeight, int gradientHeight) {
- return max(imageHeight - gradientHeight, 0);
- }
+ @Override
+ public int getBottomRectangleHeight(int imageHeight, int gradientHeight) {
+ return 0;
+ }
+ @Override
+ public int getTopRectangleHeight(int imageHeight, int gradientHeight) {
+ return max(imageHeight - gradientHeight, 0);
+ }
};
public static final GradientAlignment getByParameter(String string) {
- if (string == null || string.length() == 0) {
- return MIDDLE;
- }
- return GradientAlignment.valueOf(string.toUpperCase(Locale.US));
+ if ((string == null) || (string.length() == 0)) {
+ return MIDDLE;
+ }
+
+ return GradientAlignment.valueOf(string.toUpperCase(Locale.US));
}
-
+
public abstract int getTopRectangleHeight(int imageHeight, int gradientHeight);
-
+
public abstract int getBottomRectangleHeight(int imageHeight, int gradientHeight);
-
-
-
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/GradientType.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/GradientType.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/GradientType.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,9 +18,13 @@
* 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.richfaces.renderkit.html.images;
import java.awt.Color;
+
import java.util.Locale;
/**
@@ -30,129 +34,117 @@
*
*/
public enum GradientType {
-
GLASS {
+ @Override
+ public BiColor getFirstLayerColors(BiColor biColor) {
+ Color bottomColor = biColor.getBottomColor();
- @Override
- public BiColor getFirstLayerColors(BiColor biColor) {
- Color bottomColor = biColor.getBottomColor();
- if (bottomColor != null) {
- float[] hsb = Color.RGBtoHSB(bottomColor.getRed(), bottomColor.getGreen(), bottomColor.getBlue(), null);
+ if (bottomColor != null) {
+ float[] hsb = Color.RGBtoHSB(bottomColor.getRed(), bottomColor.getGreen(), bottomColor.getBlue(), null);
- hsb[2] = 0.2f * hsb[2] + 0.80f; //(hsb[2] * 2) / 10 + 80;
- hsb[1] = 0.5f * hsb[1];
+ hsb[2] = 0.2f * hsb[2] + 0.80f; // (hsb[2] * 2) / 10 + 80;
+ hsb[1] = 0.5f * hsb[1];
- Color topColor = new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]));
+ Color topColor = new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]));
- return new BiColor(bottomColor, topColor);
- } else {
- return null;
- }
- }
-
- @Override
- public BiColor getSecondLayerColors(BiColor biColor) {
- if (biColor.getBottomColor() != null) {
- return WHITE;
- } else {
- return null;
- }
- }
-
+ return new BiColor(bottomColor, topColor);
+ } else {
+ return null;
+ }
+ }
+ @Override
+ public BiColor getSecondLayerColors(BiColor biColor) {
+ if (biColor.getBottomColor() != null) {
+ return WHITE;
+ } else {
+ return null;
+ }
+ }
},
-
PLASTIC {
+ @Override
+ public BiColor getFirstLayerColors(BiColor biColor) {
+ Color bottomColor = biColor.getBottomColor();
- @Override
- public BiColor getFirstLayerColors(BiColor biColor) {
- Color bottomColor = biColor.getBottomColor();
- if (bottomColor != null) {
- float[] hsb = Color.RGBtoHSB(bottomColor.getRed(), bottomColor.getGreen(), bottomColor.getBlue(), null);
+ if (bottomColor != null) {
+ float[] hsb = Color.RGBtoHSB(bottomColor.getRed(), bottomColor.getGreen(), bottomColor.getBlue(), null);
- hsb[2] = 0.25f * hsb[2] + 0.75f; //(100 - hsb[2]) * 0.75f + hsb[2];
- hsb[1] = 0.75f * hsb[1];
+ hsb[2] = 0.25f * hsb[2] + 0.75f; // (100 - hsb[2]) * 0.75f + hsb[2];
+ hsb[1] = 0.75f * hsb[1];
- Color topColor = new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]));
+ Color topColor = new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]));
- return new BiColor(topColor, bottomColor);
- } else {
- return null;
- }
- }
-
- @Override
- public BiColor getSecondLayerColors(BiColor biColor) {
- if (biColor.getBottomColor() != null) {
- return WHITE;
- } else {
- return null;
- }
- }
-
+ return new BiColor(topColor, bottomColor);
+ } else {
+ return null;
+ }
+ }
+ @Override
+ public BiColor getSecondLayerColors(BiColor biColor) {
+ if (biColor.getBottomColor() != null) {
+ return WHITE;
+ } else {
+ return null;
+ }
+ }
},
-
PLAIN {
+ @Override
+ public BiColor getFirstLayerColors(BiColor biColor) {
+ if ((biColor.getBottomColor() != null) && (biColor.getTopColor() != null)) {
+ return biColor;
+ } else {
+ return null;
+ }
+ }
+ @Override
+ public BiColor getSecondLayerColors(BiColor biColor) {
+ return null;
+ }
+ };
- @Override
- public BiColor getFirstLayerColors(BiColor biColor) {
- if (biColor.getBottomColor() != null && biColor.getTopColor() != null) {
- return biColor;
- } else {
- return null;
- }
- }
+ private static final BiColor WHITE = new BiColor(new Color(0xff, 0xff, 0xff, (int) (0.65f * 0xff)),
+ new Color(0xff, 0xff, 0xff, (int) (0.20f * 0xff)));
- @Override
- public BiColor getSecondLayerColors(BiColor biColor) {
- return null;
- }
-
- };
-
public static final GradientType getByParameter(String string) {
- if (string == null || string.length() == 0) {
- return PLAIN;
- }
-
- return GradientType.valueOf(string.toUpperCase(Locale.US));
+ if ((string == null) || (string.length() == 0)) {
+ return PLAIN;
+ }
+
+ return GradientType.valueOf(string.toUpperCase(Locale.US));
}
-
+
public abstract BiColor getFirstLayerColors(BiColor biColor);
+
public abstract BiColor getSecondLayerColors(BiColor biColor);
-
- private static final BiColor WHITE = new BiColor(new Color(0xff, 0xff, 0xff, (int) (0.65f * 0xff)),
- new Color(0xff, 0xff, 0xff, (int) (0.20f * 0xff)));
-
+
public static class BiColor {
- private Color topColor;
- private Color bottomColor;
+ private Color bottomColor;
+ private Color topColor;
- public BiColor(Color topColor, Color bottomColor) {
- super();
+ public BiColor(Color topColor, Color bottomColor) {
+ super();
+ this.topColor = topColor;
+ this.bottomColor = bottomColor;
+ }
- this.topColor = topColor;
- this.bottomColor = bottomColor;
- }
+ public BiColor(Integer topColor, Integer bottomColor) {
+ super();
+ this.topColor = (topColor != null) ? new Color(topColor.intValue()) : null;
+ this.bottomColor = (bottomColor != null) ? new Color(bottomColor.intValue()) : null;
+ }
- public BiColor(Integer topColor, Integer bottomColor) {
- super();
+ public Color getTopColor() {
+ return topColor;
+ }
- this.topColor = topColor != null ? new Color(topColor.intValue()) : null;
- this.bottomColor = bottomColor != null ? new Color(bottomColor.intValue()) : null;
- }
-
- public Color getTopColor() {
- return topColor;
- }
+ public Color getBottomColor() {
+ return bottomColor;
+ }
- public Color getBottomColor() {
- return bottomColor;
- }
-
- @Override
- public String toString() {
- return "BiColor: [" + topColor + " -> " + bottomColor + "]";
- }
- };
-
+ @Override
+ public String toString() {
+ return "BiColor: [" + topColor + " -> " + bottomColor + "]";
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/StandardButtonBgImage.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/StandardButtonBgImage.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/StandardButtonBgImage.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,14 +19,15 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit.html.images;
+import org.richfaces.skin.Skin;
+
import javax.faces.context.FacesContext;
-import org.richfaces.skin.Skin;
-
public class StandardButtonBgImage extends BaseControlBackgroundImage {
-
public StandardButtonBgImage() {
super(Skin.ADDITIONAL_BACKGROUND_COLOR, "trimColor", 9);
}
@@ -34,5 +35,4 @@
protected Integer getHeight(FacesContext context) {
return (int) (1.7 * super.getHeight(context, Skin.BUTTON_SIZE_FONT));
}
-
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/StandardButtonPressedBgImage.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/StandardButtonPressedBgImage.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/StandardButtonPressedBgImage.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,14 +19,15 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit.html.images;
+import org.richfaces.skin.Skin;
+
import javax.faces.context.FacesContext;
-import org.richfaces.skin.Skin;
-
public class StandardButtonPressedBgImage extends BaseControlBackgroundImage {
-
public StandardButtonPressedBgImage() {
super("trimColor", Skin.ADDITIONAL_BACKGROUND_COLOR, 9);
}
@@ -34,5 +35,4 @@
protected Integer getHeight(FacesContext context) {
return (int) (1.7 * super.getHeight(context, Skin.BUTTON_SIZE_FONT));
}
-
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/images/package-info.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,3 +1,4 @@
+
/**
* Control and background images
*/
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/html/package-info.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,3 +1,4 @@
+
/**
* HTML-specific renderer classes
*/
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/renderkit/package-info.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,3 +1,4 @@
+
/**
* Classes participating in components rendering
*/
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractBaseResource.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractBaseResource.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractBaseResource.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,15 +19,30 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
+import org.ajax4jsf.resource.InternetResource;
+
+import org.richfaces.context.SingletonsContext;
+import org.richfaces.log.RichfacesLogger;
+import org.richfaces.util.Util;
+
+import org.slf4j.Logger;
+
+import static org.richfaces.resource.ResourceUtils.*;
+
import java.io.IOException;
import java.io.InputStream;
+
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
+
import java.text.MessageFormat;
+
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@@ -37,52 +52,38 @@
import javax.faces.component.StateHolder;
import javax.faces.context.FacesContext;
-import org.ajax4jsf.resource.InternetResource;
-import org.richfaces.context.SingletonsContext;
-import org.richfaces.log.RichfacesLogger;
-import org.richfaces.util.Util;
-import org.slf4j.Logger;
-
-import static org.richfaces.resource.ResourceUtils.*;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public abstract class AbstractBaseResource extends AbstractCacheableResource implements VersionedResource {
+ public static final String URL_PROTOCOL = "jsfresource";
+ private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
+ private boolean cacheable = true;
+ private Date lastModified = null;
+ private String version;
- private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
+ protected AbstractBaseResource() {
+ super();
+ this.setResourceName(getClass().getName());
+ }
- public static final String URL_PROTOCOL = "jsfresource";
-
- private boolean cacheable = true;
-
- private String version;
-
- private Date lastModified = null;
+ // TODO remove FacesContext argument?
+ protected int getContentLength(FacesContext context) {
+ return -1;
+ }
- protected AbstractBaseResource() {
- super();
-
- this.setResourceName(getClass().getName());
- }
-
- //TODO remove FacesContext argument?
- protected int getContentLength(FacesContext context) {
- return -1;
- }
-
- /**
- * <b>IMPORTANT:</b> this method returned TTL in RF 3.x, now it returns expiration time
+ /**
+ * <b>IMPORTANT:</b> this method returned TTL in RF 3.x, now it returns expiration time
* @return Returns the expired.
- */
- protected Date getExpires(FacesContext context) {
- return null;
- }
+ */
+ protected Date getExpires(FacesContext context) {
+ return null;
+ }
- protected int getTimeToLive(FacesContext context) {
- return 0;
- }
+ protected int getTimeToLive(FacesContext context) {
+ return 0;
+ }
/**
* TODO optimize/review?
@@ -94,14 +95,17 @@
lastModified = getLastModifiedBySource();
}
- //TODO - originally lastModified was set during resource creation.
- //as resources can be managed beans this approach does not seem good
+ // TODO - originally lastModified was set during resource creation.
+ // as resources can be managed beans this approach does not seem good
if (lastModified == null) {
- lastModified = (Date) SingletonsContext.APPLICATION.get(context).
- getAttribute(ResourceHandlerImpl.HANDLER_START_TIME_ATTRIBUTE);
+ lastModified = (Date) SingletonsContext.APPLICATION.get(context).getAttribute(
+ ResourceHandlerImpl.HANDLER_START_TIME_ATTRIBUTE);
if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(MessageFormat.format("Using resource handler start time as last modified date: {0,date,dd MMM yyyy HH:mm:ss zzz}", lastModified));
+ LOGGER.debug(
+ MessageFormat.format(
+ "Using resource handler start time as last modified date: {0,date,dd MMM yyyy HH:mm:ss zzz}",
+ lastModified));
}
}
@@ -110,11 +114,13 @@
private Date getLastModifiedBySource() {
ClassLoader classLoader = getClassLoader();
+
if (classLoader == null) {
return null;
}
URL classResource = classLoader.getResource(getClass().getName().replace('.', '/') + ".class");
+
if (classResource != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(MessageFormat.format("Located source for the resource class: {0}", classResource));
@@ -122,8 +128,11 @@
try {
URLConnection connection = classResource.openConnection();
+
connection.setUseCaches(false);
+
long classLastModifiedDate = connection.getLastModified();
+
if (classLastModifiedDate > 0) {
lastModified = new Date(classLastModifiedDate);
@@ -132,6 +141,7 @@
}
}
} catch (IOException e) {
+
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -147,30 +157,32 @@
private ClassLoader getClassLoader() {
Class<? extends AbstractBaseResource> thisClass = getClass();
ClassLoader classLoader = thisClass.getClassLoader();
+
if (classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
+
return classLoader;
}
/**
- * @return Returns the cacheable.
- */
- @Override
+ * @return Returns the cacheable.
+ */
+ @Override
public boolean isCacheable(FacesContext context) {
- return cacheable;
- }
-
- protected void setCacheable(boolean cacheable) {
- this.cacheable = cacheable;
- }
+ return cacheable;
+ }
+ protected void setCacheable(boolean cacheable) {
+ this.cacheable = cacheable;
+ }
+
@Override
protected String getEntityTag(FacesContext context) {
int contentLength = getContentLength(context);
Date lastModified = getLastModified(context);
- if (contentLength < 0 || lastModified == null) {
+ if ((contentLength < 0) || (lastModified == null)) {
return null;
}
@@ -178,128 +190,136 @@
}
@Override
- public abstract InputStream getInputStream();
+ public abstract InputStream getInputStream();
- @Override
- public String getRequestPath() {
- //TODO - cache resource request path in request scope
-
- FacesContext context = FacesContext.getCurrentInstance();
- ResourceCodec resourceCodec = ResourceHandlerImpl.getResourceCodec(context);
+ @Override
+ public String getRequestPath() {
- String resourceName = getResourceName();
- Object resourceData = null;
- if (this instanceof StateHolder) {
- StateHolder stateHolder = (StateHolder) this;
- if (!stateHolder.isTransient()) {
- resourceData = stateHolder.saveState(context);
- }
- }
+ // TODO - cache resource request path in request scope
+ FacesContext context = FacesContext.getCurrentInstance();
+ ResourceCodec resourceCodec = ResourceHandlerImpl.getResourceCodec(context);
+ String resourceName = getResourceName();
+ Object resourceData = null;
- String resourceVersion = getVersion();
-
- String resourceUri = ResourceHandlerImpl.RICHFACES_RESOURCE_IDENTIFIER +
- resourceCodec.encodeResource(resourceName, resourceData, resourceVersion);
-
- resourceUri = Util.encodeResourceURL(context, resourceUri);
+ if (this instanceof StateHolder) {
+ StateHolder stateHolder = (StateHolder) this;
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(MessageFormat.format("Request path for {0} resource is: {1}",
- String.valueOf(resourceName), String.valueOf(resourceUri)));
- }
-
- return resourceUri;
- }
+ if (!stateHolder.isTransient()) {
+ resourceData = stateHolder.saveState(context);
+ }
+ }
- public String getVersion() {
- return version;
- }
-
- protected void setVersion(String version) {
- this.version = version;
- }
-
+ String resourceVersion = getVersion();
+ String resourceUri = ResourceHandlerImpl.RICHFACES_RESOURCE_IDENTIFIER
+ + resourceCodec.encodeResource(resourceName, resourceData, resourceVersion);
+
+ resourceUri = Util.encodeResourceURL(context, resourceUri);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(MessageFormat.format("Request path for {0} resource is: {1}", String.valueOf(resourceName),
+ String.valueOf(resourceUri)));
+ }
+
+ return resourceUri;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ protected void setVersion(String version) {
+ this.version = version;
+ }
+
boolean isResourceRequest() {
FacesContext facesContext = FacesContext.getCurrentInstance();
- return (facesContext.getApplication().getResourceHandler().isResourceRequest(facesContext));
+
+ return facesContext.getApplication().getResourceHandler().isResourceRequest(facesContext);
}
long getCurrentTime() {
- return System.currentTimeMillis();
+ return System.currentTimeMillis();
}
-
- @Override
- public Map<String, String> getResponseHeaders() {
- Map<String, String> headers = new HashMap<String, String>();
+
+ @Override
+ public Map<String, String> getResponseHeaders() {
+ Map<String, String> headers = new HashMap<String, String>();
FacesContext facesContext = FacesContext.getCurrentInstance();
-
- if (isResourceRequest()) {
- int contentLength = getContentLength(facesContext);
- if (contentLength >= 0) {
- headers.put("Content-Length", String.valueOf(contentLength));
- }
-
- String contentType = getContentType();
- if (contentType != null) {
- //TODO add content-encoding?
- headers.put("Content-Type", contentType);
- }
-
- Date lastModified = getLastModified(facesContext);
- if (lastModified != null) {
- headers.put("Last-Modified", Util.formatHttpDate(lastModified));
- }
- if (isCacheable(facesContext)) {
- long currentTime = getCurrentTime();
+ if (isResourceRequest()) {
+ int contentLength = getContentLength(facesContext);
- String formattedExpireDate;
- long maxAge = getTimeToLive(facesContext);
-
- if (maxAge > 0) {
- formattedExpireDate = Util.formatHttpDate(currentTime + secondToMillis(maxAge));
- } else {
- Date expired = getExpires(facesContext);
- if (expired != null) {
- formattedExpireDate = Util.formatHttpDate(expired);
- maxAge = millisToSecond(expired.getTime() - currentTime);
- } else {
- maxAge = InternetResource.DEFAULT_TTL;
- formattedExpireDate = Util.formatHttpDate(currentTime + secondToMillis(maxAge));
- }
- }
-
- if (formattedExpireDate != null) {
- headers.put("Expires", formattedExpireDate);
- }
- if (maxAge > 0) {
- headers.put("Cache-Control", "max-age=" + maxAge);
- }
-
- String entityTag = getEntityTag(facesContext);
- if (entityTag != null) {
- headers.put("ETag", entityTag);
- }
- } else {
- headers.put("Expires", "0");
- headers.put("Cache-Control", "max-age=0, no-store, no-cache");
- headers.put("Pragma", "no-cache");
- }
-
- headers.put("Date", Util.formatHttpDate(getCurrentTime()));
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Created set of response headers");
- //TODO - security - can we log header values?
- for (Entry<String, String> entry : headers.entrySet()) {
- LOGGER.debug(MessageFormat.format("\t{0}={1}", entry.getKey(), entry.getValue()));
- }
- }
- }
-
- return headers;
- }
+ if (contentLength >= 0) {
+ headers.put("Content-Length", String.valueOf(contentLength));
+ }
+ String contentType = getContentType();
+
+ if (contentType != null) {
+
+ // TODO add content-encoding?
+ headers.put("Content-Type", contentType);
+ }
+
+ Date lastModified = getLastModified(facesContext);
+
+ if (lastModified != null) {
+ headers.put("Last-Modified", Util.formatHttpDate(lastModified));
+ }
+
+ if (isCacheable(facesContext)) {
+ long currentTime = getCurrentTime();
+ String formattedExpireDate;
+ long maxAge = getTimeToLive(facesContext);
+
+ if (maxAge > 0) {
+ formattedExpireDate = Util.formatHttpDate(currentTime + secondToMillis(maxAge));
+ } else {
+ Date expired = getExpires(facesContext);
+
+ if (expired != null) {
+ formattedExpireDate = Util.formatHttpDate(expired);
+ maxAge = millisToSecond(expired.getTime() - currentTime);
+ } else {
+ maxAge = InternetResource.DEFAULT_TTL;
+ formattedExpireDate = Util.formatHttpDate(currentTime + secondToMillis(maxAge));
+ }
+ }
+
+ if (formattedExpireDate != null) {
+ headers.put("Expires", formattedExpireDate);
+ }
+
+ if (maxAge > 0) {
+ headers.put("Cache-Control", "max-age=" + maxAge);
+ }
+
+ String entityTag = getEntityTag(facesContext);
+
+ if (entityTag != null) {
+ headers.put("ETag", entityTag);
+ }
+ } else {
+ headers.put("Expires", "0");
+ headers.put("Cache-Control", "max-age=0, no-store, no-cache");
+ headers.put("Pragma", "no-cache");
+ }
+
+ headers.put("Date", Util.formatHttpDate(getCurrentTime()));
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Created set of response headers");
+
+ // TODO - security - can we log header values?
+ for (Entry<String, String> entry : headers.entrySet()) {
+ LOGGER.debug(MessageFormat.format("\t{0}={1}", entry.getKey(), entry.getValue()));
+ }
+ }
+ }
+
+ return headers;
+ }
+
@Override
public URL getURL() {
try {
@@ -309,26 +329,18 @@
}
}
- private class MyURLStreamHandler extends URLStreamHandler {
-
- @Override
- protected URLConnection openConnection(URL u) throws IOException {
- return new MyURLConnection(u);
- }
- }
-
private class MyURLConnection extends URLConnection {
MyURLConnection(URL u) {
super(u);
}
@Override
- public void connect() throws IOException {
- }
+ public void connect() throws IOException {}
@Override
public int getContentLength() {
FacesContext facesContext = FacesContext.getCurrentInstance();
+
return AbstractBaseResource.this.getContentLength(facesContext);
}
@@ -341,11 +353,13 @@
public long getExpiration() {
FacesContext facesContext = FacesContext.getCurrentInstance();
long ttl = AbstractBaseResource.this.getTimeToLive(facesContext);
+
if (ttl > 0) {
return System.currentTimeMillis() + secondToMillis(ttl);
}
Date date = AbstractBaseResource.this.getExpires(facesContext);
+
if (date != null) {
return date.getTime();
}
@@ -357,6 +371,7 @@
public long getLastModified() {
FacesContext facesContext = FacesContext.getCurrentInstance();
Date date = AbstractBaseResource.this.getLastModified(facesContext);
+
if (date != null) {
return date.getTime();
}
@@ -369,4 +384,12 @@
return AbstractBaseResource.this.getInputStream();
}
}
+
+
+ private class MyURLStreamHandler extends URLStreamHandler {
+ @Override
+ protected URLConnection openConnection(URL u) throws IOException {
+ return new MyURLConnection(u);
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractCacheableResource.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractCacheableResource.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractCacheableResource.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,8 +18,16 @@
* 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.richfaces.resource;
+import org.richfaces.log.RichfacesLogger;
+import org.richfaces.util.Util;
+
+import org.slf4j.Logger;
+
import java.util.Date;
import java.util.Map;
@@ -27,16 +35,11 @@
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
-import org.richfaces.log.RichfacesLogger;
-import org.richfaces.util.Util;
-import org.slf4j.Logger;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public abstract class AbstractCacheableResource extends Resource {
-
private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
protected abstract Date getLastModified(FacesContext context);
@@ -45,9 +48,9 @@
protected abstract String getEntityTag(FacesContext context);
- //TODO add getExpired(FacesContext) for HTTP matching headers?
+ // TODO add getExpired(FacesContext) for HTTP matching headers?
+ private static boolean isUserCopyActual(Date lastModified, Date modifiedCondition) {
- private static boolean isUserCopyActual(Date lastModified, Date modifiedCondition) {
// 1000 ms due to round modification time to seconds.
return (lastModified.getTime() - modifiedCondition.getTime()) <= 1000;
}
@@ -67,6 +70,7 @@
protected boolean isMatchesLastModified(FacesContext context, String modifiedCondition) {
Date lastModified = getLastModified(context);
+
if (lastModified == null) {
return false;
}
@@ -86,8 +90,10 @@
return isMatchesEntityTag(context, matchHeaderValue);
}
+
protected boolean isMatchesEntityTag(FacesContext context, String matchHeaderValue) {
String resourceEntityTag = getEntityTag(context);
+
if (resourceEntityTag == null) {
return false;
}
@@ -110,14 +116,15 @@
String modifiedCondition = requestHeaderMap.get("If-Modified-Since");
String matchHeaderValue = requestHeaderMap.get("If-None-Match");
- if (modifiedCondition == null && matchHeaderValue == null) {
+ if ((modifiedCondition == null) && (matchHeaderValue == null)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("User agent cache check: no cache information was provided in request");
}
+
return true;
}
- if (matchHeaderValue != null && !isMatchesEntityTag(context, matchHeaderValue)) {
+ if ((matchHeaderValue != null) && !isMatchesEntityTag(context, matchHeaderValue)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("User agent cache check: entity tags don't match");
}
@@ -125,14 +132,14 @@
return true;
}
- if (modifiedCondition != null && !isMatchesLastModified(context, modifiedCondition)) {
+ if ((modifiedCondition != null) && !isMatchesLastModified(context, modifiedCondition)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("User agent cache check: resource was modified since the last request");
}
+
return true;
}
return false;
}
-
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/AnimatedTestResource.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/AnimatedTestResource.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/AnimatedTestResource.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,15 +19,21 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
+import org.w3c.dom.Node;
+
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+
import java.util.Iterator;
import javax.imageio.IIOImage;
@@ -39,32 +45,29 @@
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageOutputStream;
-import org.w3c.dom.Node;
-
public class AnimatedTestResource extends TestResource2 {
+ private static final int DELAY_TIME = 50;
+ private static final int FRAMES_COUNT = 10;
- private static final int FRAMES_COUNT = 10;
+ private static ImageWriter getImageWriter() {
+ ImageWriter result = null;
+ Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("gif");
- private static final int DELAY_TIME = 50;
+ while (imageWriters.hasNext() && (result == null)) {
+ ImageWriter imageWriter = imageWriters.next();
- private static ImageWriter getImageWriter() {
- ImageWriter result = null;
-
- Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("gif");
- while (imageWriters.hasNext() && result == null) {
- ImageWriter imageWriter = imageWriters.next();
- if (imageWriter.canWriteSequence()) {
- result = imageWriter;
- }
- }
-
- return result;
- }
+ if (imageWriter.canWriteSequence()) {
+ result = imageWriter;
+ }
+ }
+ return result;
+ }
+
private static Node getOrCreateChild(Node root, String name) {
Node result = null;
- for (Node node = root.getFirstChild(); node != null && result == null; node = node.getNextSibling()) {
+ for (Node node = root.getFirstChild(); (node != null) && (result == null); node = node.getNextSibling()) {
if (name.equals(node.getNodeName())) {
result = node;
}
@@ -77,88 +80,89 @@
return result;
}
-
- @Override
- public String getContentType() {
- return "image/gif";
- }
- @Override
- public InputStream getInputStream() {
- GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ @Override
+ public String getContentType() {
+ return "image/gif";
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
Dimension dimension = getDimension();
BufferedImage image = new BufferedImage(dimension.width, dimension.height, ColorSpace.TYPE_RGB);
- Graphics2D g2d = environment.createGraphics(image);
+ Graphics2D g2d = environment.createGraphics(image);
+ ImageWriter sequenceCapableImageWriter = getImageWriter();
- ImageWriter sequenceCapableImageWriter = getImageWriter();
- if (sequenceCapableImageWriter == null) {
- throw new IllegalStateException("No sequence-capable image writers exit");
- }
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ImageOutputStream imageOutputStream = null;
-
- try {
- imageOutputStream = ImageIO.createImageOutputStream(baos);
- sequenceCapableImageWriter.setOutput(imageOutputStream);
- ImageWriteParam defaultImageWriteParam = sequenceCapableImageWriter.getDefaultWriteParam();
- ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(image.getType());
- IIOMetadata imageMetaData = sequenceCapableImageWriter.
- getDefaultImageMetadata(imageTypeSpecifier, defaultImageWriteParam);
-
- String metaFormatName = imageMetaData.getNativeMetadataFormatName();
- Node root = imageMetaData.getAsTree(metaFormatName);
- IIOMetadataNode graphicsControlExtensionNode = (IIOMetadataNode) getOrCreateChild(root, "GraphicControlExtension");
+ if (sequenceCapableImageWriter == null) {
+ throw new IllegalStateException("No sequence-capable image writers exit");
+ }
- // http://java.sun.com/javase/6/docs/api/javax/imageio/metadata/doc-files/gi...
- graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
- graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
- graphicsControlExtensionNode.setAttribute("transparentColorFlag", "FALSE");
- graphicsControlExtensionNode.setAttribute("delayTime", Integer.toString(DELAY_TIME));
- graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0");
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ImageOutputStream imageOutputStream = null;
- boolean loopContinuously = false;
- Node applicationExtensionsNode = getOrCreateChild(root, "ApplicationExtensions");
- IIOMetadataNode netscapeExtension = new IIOMetadataNode("ApplicationExtension");
+ try {
+ imageOutputStream = ImageIO.createImageOutputStream(baos);
+ sequenceCapableImageWriter.setOutput(imageOutputStream);
- netscapeExtension.setAttribute("applicationID", "NETSCAPE");
- netscapeExtension.setAttribute("authenticationCode", "2.0");
+ ImageWriteParam defaultImageWriteParam = sequenceCapableImageWriter.getDefaultWriteParam();
+ ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(image.getType());
+ IIOMetadata imageMetaData = sequenceCapableImageWriter.getDefaultImageMetadata(imageTypeSpecifier,
+ defaultImageWriteParam);
+ String metaFormatName = imageMetaData.getNativeMetadataFormatName();
+ Node root = imageMetaData.getAsTree(metaFormatName);
+ IIOMetadataNode graphicsControlExtensionNode = (IIOMetadataNode) getOrCreateChild(root,
+ "GraphicControlExtension");
- byte numLoops = (byte) (loopContinuously ? 0x0 : 0x1);
+ // http://java.sun.com/javase/6/docs/api/javax/imageio/metadata/doc-files/gi...
+ graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
+ graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
+ graphicsControlExtensionNode.setAttribute("transparentColorFlag", "FALSE");
+ graphicsControlExtensionNode.setAttribute("delayTime", Integer.toString(DELAY_TIME));
+ graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0");
+
+ boolean loopContinuously = false;
+ Node applicationExtensionsNode = getOrCreateChild(root, "ApplicationExtensions");
+ IIOMetadataNode netscapeExtension = new IIOMetadataNode("ApplicationExtension");
+
+ netscapeExtension.setAttribute("applicationID", "NETSCAPE");
+ netscapeExtension.setAttribute("authenticationCode", "2.0");
+
+ byte numLoops = (byte) (loopContinuously ? 0x0 : 0x1);
+
netscapeExtension.setUserObject(new byte[] {0x1, numLoops, 0x0});
- applicationExtensionsNode.appendChild(netscapeExtension);
-
- imageMetaData.setFromTree(metaFormatName, root);
-
- sequenceCapableImageWriter.prepareWriteSequence(null);
+ applicationExtensionsNode.appendChild(netscapeExtension);
+ imageMetaData.setFromTree(metaFormatName, root);
+ sequenceCapableImageWriter.prepareWriteSequence(null);
for (int i = 1; i <= FRAMES_COUNT; i++) {
- g2d.setPaint(new GradientPaint(0, i * dimension.height / FRAMES_COUNT, Color.WHITE, 0, dimension.height, getColor()));
- g2d.fillRect(0, 0, dimension.width, dimension.height);
-
- sequenceCapableImageWriter.writeToSequence(new IIOImage(image, null, imageMetaData),
- defaultImageWriteParam);
- }
-
- sequenceCapableImageWriter.endWriteSequence();
-
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if (imageOutputStream != null) {
- try {
- imageOutputStream.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- g2d.dispose();
- sequenceCapableImageWriter.dispose();
- }
+ g2d.setPaint(new GradientPaint(0, i * dimension.height / FRAMES_COUNT, Color.WHITE, 0,
+ dimension.height, getColor()));
+ g2d.fillRect(0, 0, dimension.width, dimension.height);
+ sequenceCapableImageWriter.writeToSequence(new IIOImage(image, null, imageMetaData),
+ defaultImageWriteParam);
+ }
- return new ByteArrayInputStream(baos.toByteArray());
- }
+ sequenceCapableImageWriter.endWriteSequence();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } finally {
+ if (imageOutputStream != null) {
+ try {
+ imageOutputStream.close();
+ } catch (IOException e) {
+
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ g2d.dispose();
+ sequenceCapableImageWriter.dispose();
+ }
+
+ return new ByteArrayInputStream(baos.toByteArray());
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/CachedResourceImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/CachedResourceImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/CachedResourceImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,12 +18,18 @@
* 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.richfaces.resource;
import java.io.IOException;
import java.io.InputStream;
+
import java.net.URL;
+
import java.text.MessageFormat;
+
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
@@ -38,8 +44,10 @@
import org.ajax4jsf.io.ByteBuffer;
import org.ajax4jsf.io.FastBufferInputStream;
import org.ajax4jsf.io.FastBufferOutputStream;
+
import org.richfaces.log.RichfacesLogger;
import org.richfaces.util.Util;
+
import org.slf4j.Logger;
import static org.richfaces.resource.ResourceUtils.*;
@@ -50,173 +58,174 @@
*/
class CachedResourceImpl extends AbstractCacheableResource {
- //[0..1]
- private static final float CACHE_EXPIRATION_COEFFICIENT = 0.9f;
-
- private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
-
- private static final int SMAX_AGE_GROUP = 1;
+ // [0..1]
+ private static final float CACHE_EXPIRATION_COEFFICIENT = 0.9f;
+ private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
+ private static final int MAX_AGE_VALUE_GROUP = 2;
+ private static final int SMAX_AGE_GROUP = 1;
+ private static final Pattern MAX_AGE = Pattern.compile("^(?:(s-maxage)|max-age)=(\\d+)$", Pattern.CASE_INSENSITIVE);
+ private ByteBuffer content;
+ private String entityTag;
- private static final int MAX_AGE_VALUE_GROUP = 2;
-
- private static final Pattern MAX_AGE = Pattern.compile("^(?:(s-maxage)|max-age)=(\\d+)$",
- Pattern.CASE_INSENSITIVE);
-
- private Map<String, String> headers;
-
- private ByteBuffer content;
-
- private String entityTag;
-
- private Date lastModified;
-
- /***
+ /**
* serves only to define server cache entry expiration time only
* browser cache expiration is controlled by stored HTTP headers value
*/
- private Date expired;
-
- private void initializeFromHeaders() {
- this.entityTag = null;
- this.lastModified = null;
- this.expired = null;
-
- Date expiredFromHeader = null;
- //TODO what if maxAge = 0 in header?
- int maxAge = 0;
+ private Date expired;
+ private Map<String, String> headers;
+ private Date lastModified;
- for (Entry<String, String> headerEntry: headers.entrySet()) {
- String headerKey = headerEntry.getKey().toLowerCase(Locale.US);
- if ("etag".equals(headerKey)) {
- this.entityTag = headerEntry.getValue();
- }
+ private void initializeFromHeaders() {
+ this.entityTag = null;
+ this.lastModified = null;
+ this.expired = null;
+ Date expiredFromHeader = null;
+
+ // TODO what if maxAge = 0 in header?
+ int maxAge = 0;
+
+ for (Entry<String, String> headerEntry : headers.entrySet()) {
+ String headerKey = headerEntry.getKey().toLowerCase(Locale.US);
+
+ if ("etag".equals(headerKey)) {
+ this.entityTag = headerEntry.getValue();
+ }
+
if ("last-modified".equals(headerKey)) {
- this.lastModified = Util.parseHttpDate(headerEntry.getValue());
- }
+ this.lastModified = Util.parseHttpDate(headerEntry.getValue());
+ }
if ("expires".equals(headerKey)) {
- expiredFromHeader = Util.parseHttpDate(headerEntry.getValue());
- }
+ expiredFromHeader = Util.parseHttpDate(headerEntry.getValue());
+ }
if ("cache-control".equals(headerKey)) {
- String[] values = headerEntry.getValue().split(",");
+ String[] values = headerEntry.getValue().split(",");
- for (String value : values) {
- Matcher matcher = MAX_AGE.matcher(value.trim());
- if (matcher.find()) {
- boolean isSMaxAge = matcher.group(SMAX_AGE_GROUP) != null;
- if (maxAge <= 0 || isSMaxAge) { // s-maxage overrides max-age
- try {
- maxAge = (int) secondToMillis(Integer.parseInt(matcher.group(MAX_AGE_VALUE_GROUP)));
- } catch (NumberFormatException e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
+ for (String value : values) {
+ Matcher matcher = MAX_AGE.matcher(value.trim());
- long currentTime = getCurrentTime();
- if (maxAge > 0) {
- this.expired = new Date((long) (currentTime + CACHE_EXPIRATION_COEFFICIENT * maxAge));
- } else if (expiredFromHeader != null) {
- // ttl = expireTime - currentTime
- // CACHE_EXPIRATION_COEFFICIENT * ttl + currentTime
- this.expired = new Date((long) (CACHE_EXPIRATION_COEFFICIENT * expiredFromHeader.getTime() +
- (1 - CACHE_EXPIRATION_COEFFICIENT) * currentTime));
- } else {
- //TODO throw exception or modify headers?
- }
- }
-
- long getCurrentTime() {
- return System.currentTimeMillis();
- }
-
- private static ByteBuffer readContent(InputStream is) throws IOException {
- if (is == null) {
- throw new NullPointerException("Resource input stream is null");
- }
-
- FastBufferOutputStream os = new FastBufferOutputStream();
- try {
- Util.copyStreamContent(is, os);
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(e.getMessage(), e);
- }
- }
+ if (matcher.find()) {
+ boolean isSMaxAge = matcher.group(SMAX_AGE_GROUP) != null;
- try {
- os.close();
- } catch (IOException e) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(e.getMessage(), e);
- }
- }
- }
-
- ByteBuffer buffer = os.getFirstBuffer();
- buffer.compact();
- return buffer;
- }
-
- public void initialize(Resource resource) throws IOException {
- setResourceName(resource.getResourceName());
- setContentType(resource.getContentType());
- this.headers = resource.getResponseHeaders();
+ if (maxAge <= 0 || isSMaxAge) { // s-maxage overrides max-age
+ try {
+ maxAge = (int) secondToMillis(Integer.parseInt(matcher.group(MAX_AGE_VALUE_GROUP)));
+ } catch (NumberFormatException e) {
- initializeFromHeaders();
- this.content = readContent(resource.getInputStream());
- }
-
- @Override
- public InputStream getInputStream() {
- return new FastBufferInputStream(content);
- }
+ // TODO: handle exception
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+ }
- @Override
- public String getRequestPath() {
- throw new UnsupportedOperationException();
- }
+ long currentTime = getCurrentTime();
- @Override
- public Map<String, String> getResponseHeaders() {
- return new HashMap<String, String>(headers);
- }
+ if (maxAge > 0) {
+ this.expired = new Date((long) (currentTime + CACHE_EXPIRATION_COEFFICIENT * maxAge));
+ } else if (expiredFromHeader != null) {
- @Override
- public URL getURL() {
- throw new UnsupportedOperationException();
- }
+ // ttl = expireTime - currentTime
+ // CACHE_EXPIRATION_COEFFICIENT * ttl + currentTime
+ this.expired = new Date((long) (CACHE_EXPIRATION_COEFFICIENT * expiredFromHeader.getTime()
+ + (1 - CACHE_EXPIRATION_COEFFICIENT) * currentTime));
+ } else {
- @Override
- public boolean isCacheable(FacesContext context) {
- return true;
- }
-
- @Override
- protected String getEntityTag(FacesContext context) {
- return entityTag;
- }
-
- @Override
- protected Date getLastModified(FacesContext context) {
- return lastModified;
- }
-
- public Date getExpired(FacesContext context) {
- return expired;
- }
-
- @Override
- public String toString() {
- return MessageFormat.format("Cached resource: {0}", getResourceName());
- }
+ // TODO throw exception or modify headers?
+ }
+ }
+
+ long getCurrentTime() {
+ return System.currentTimeMillis();
+ }
+
+ private static ByteBuffer readContent(InputStream is) throws IOException {
+ if (is == null) {
+ throw new NullPointerException("Resource input stream is null");
+ }
+
+ FastBufferOutputStream os = new FastBufferOutputStream();
+
+ try {
+ Util.copyStreamContent(is, os);
+ } finally {
+ try {
+ is.close();
+ } catch (IOException e) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(e.getMessage(), e);
+ }
+ }
+
+ try {
+ os.close();
+ } catch (IOException e) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(e.getMessage(), e);
+ }
+ }
+ }
+
+ ByteBuffer buffer = os.getFirstBuffer();
+
+ buffer.compact();
+
+ return buffer;
+ }
+
+ public void initialize(Resource resource) throws IOException {
+ setResourceName(resource.getResourceName());
+ setContentType(resource.getContentType());
+ this.headers = resource.getResponseHeaders();
+ initializeFromHeaders();
+ this.content = readContent(resource.getInputStream());
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ return new FastBufferInputStream(content);
+ }
+
+ @Override
+ public String getRequestPath() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Map<String, String> getResponseHeaders() {
+ return new HashMap<String, String>(headers);
+ }
+
+ @Override
+ public URL getURL() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean isCacheable(FacesContext context) {
+ return true;
+ }
+
+ @Override
+ protected String getEntityTag(FacesContext context) {
+ return entityTag;
+ }
+
+ @Override
+ protected Date getLastModified(FacesContext context) {
+ return lastModified;
+ }
+
+ public Date getExpired(FacesContext context) {
+ return expired;
+ }
+
+ @Override
+ public String toString() {
+ return MessageFormat.format("Cached resource: {0}", getResourceName());
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/DefaultResourceCodec.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/DefaultResourceCodec.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/DefaultResourceCodec.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,37 +19,34 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import org.richfaces.util.Util;
final class DefaultResourceCodec implements ResourceCodec {
+ private static final ResourceCodec CODEC = new DefaultResourceCodec();
- private static final ResourceCodec CODEC = new DefaultResourceCodec();
+ private DefaultResourceCodec() {}
- private DefaultResourceCodec() {
-
- }
-
- public String decodeResourceName(String resourceKey) {
- return Util.getResourceName(resourceKey);
- }
+ public String decodeResourceName(String resourceKey) {
+ return Util.getResourceName(resourceKey);
+ }
- public Object decodeResourceData(String resourceKey) {
- return Util.getResourceData(resourceKey);
- }
+ public Object decodeResourceData(String resourceKey) {
+ return Util.getResourceData(resourceKey);
+ }
- public static ResourceCodec getInstance() {
- return CODEC;
- }
+ public static ResourceCodec getInstance() {
+ return CODEC;
+ }
- public String decodeResourceVersion(String resourceKey) {
- return Util.getResourceVersion(resourceKey);
- }
+ public String decodeResourceVersion(String resourceKey) {
+ return Util.getResourceVersion(resourceKey);
+ }
- public String encodeResource(String resourceName, Object resourceData,
- String resourceVersion) {
- return Util.encodeResourceData(resourceName, resourceData, resourceVersion);
- }
-
-}
\ No newline at end of file
+ public String encodeResource(String resourceName, Object resourceData, String resourceVersion) {
+ return Util.encodeResourceData(resourceName, resourceData, resourceVersion);
+ }
+}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceCodec.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceCodec.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceCodec.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.resource;
@@ -8,12 +9,11 @@
* @since 4.0
*/
public interface ResourceCodec {
+ public String encodeResource(String resourceName, Object resourceData, String resourceVersion);
- public String encodeResource(String resourceName, Object resourceData, String resourceVersion);
-
- public String decodeResourceName(String resourceKey);
+ public String decodeResourceName(String resourceKey);
- public Object decodeResourceData(String resourceKey);
+ public Object decodeResourceData(String resourceKey);
- public String decodeResourceVersion(String resourceKey);
+ public String decodeResourceVersion(String resourceKey);
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,13 +19,29 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
+import org.ajax4jsf.cache.Cache;
+import org.ajax4jsf.cache.CacheManager;
+
+import org.richfaces.context.AttributesContext;
+import org.richfaces.context.SingletonsContext;
+import org.richfaces.log.RichfacesLogger;
+import org.richfaces.util.RequestStateManager.BooleanRequestStateVariable;
+import org.richfaces.util.Util;
+
+import org.slf4j.Logger;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+
import java.net.URL;
+
import java.text.MessageFormat;
+
import java.util.Date;
import java.util.Locale;
import java.util.Map;
@@ -37,437 +53,447 @@
import javax.faces.component.StateHolder;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
+
import javax.imageio.ImageIO;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.ajax4jsf.cache.Cache;
-import org.ajax4jsf.cache.CacheManager;
-import org.richfaces.context.AttributesContext;
-import org.richfaces.context.SingletonsContext;
-import org.richfaces.log.RichfacesLogger;
-import org.richfaces.util.Util;
-import org.richfaces.util.RequestStateManager.BooleanRequestStateVariable;
-import org.slf4j.Logger;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class ResourceHandlerImpl extends ResourceHandler {
+ public static final String RICHFACES_RESOURCE_IDENTIFIER = "/rfRes/";
+ public static final String RESOURCE_CACHE_NAME = ResourceHandlerImpl.class.getName() + ":CACHE";
+ public static final String HANDLER_START_TIME_ATTRIBUTE = ResourceHandlerImpl.class.getName() + ":StartTime";
- public static final String RICHFACES_RESOURCE_IDENTIFIER = "/rfRes/";
+ private static final String RESOURCE_CODEC_ATTRIBUTE_NAME = ResourceHandlerImpl.class.getName() + ":ResourceCodec";
+ private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
- public static final String HANDLER_START_TIME_ATTRIBUTE = ResourceHandlerImpl.class.getName() +
- ":StartTime";
-
- public static final String RESOURCE_CACHE_NAME = ResourceHandlerImpl.class.getName() + ":CACHE";
-
- private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
+ // TODO - review - do we need this?
+ static {
- //TODO - review - do we need this?
- static {
- // set in-memory caching ImageIO
- Thread thread = Thread.currentThread();
- ClassLoader initialTCCL = thread.getContextClassLoader();
-
- try {
- ClassLoader systemCL = ClassLoader.getSystemClassLoader();
- thread.setContextClassLoader(systemCL);
- ImageIO.setUseCache(false);
- } finally {
- thread.setContextClassLoader(initialTCCL);
- }
- }
+ // set in-memory caching ImageIO
+ Thread thread = Thread.currentThread();
+ ClassLoader initialTCCL = thread.getContextClassLoader();
-
- private ResourceHandler defaultHandler;
+ try {
+ ClassLoader systemCL = ClassLoader.getSystemClassLoader();
- private Cache cache;
-
- public ResourceHandlerImpl(ResourceHandler defaultHandler) {
- this.defaultHandler = defaultHandler;
+ thread.setContextClassLoader(systemCL);
+ ImageIO.setUseCache(false);
+ } finally {
+ thread.setContextClassLoader(initialTCCL);
+ }
+ }
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(MessageFormat.format("Instance of {0} resource handler created",
- getClass().getName()));
- }
-
- FacesContext facesContext = FacesContext.getCurrentInstance();
- initializeCache(facesContext);
- markStartTime(facesContext);
- }
+ private Cache cache;
+ private ResourceHandler defaultHandler;
- private void initializeCache(FacesContext facesContext) {
- Map<?,?> envMap = facesContext.getExternalContext().getInitParameterMap();
- cache = CacheManager.getInstance().getNewCache(RESOURCE_CACHE_NAME, envMap);
- }
+ public ResourceHandlerImpl(ResourceHandler defaultHandler) {
+ this.defaultHandler = defaultHandler;
- private static void markStartTime(FacesContext facesContext) {
- AttributesContext applicationContext = SingletonsContext.APPLICATION.get(facesContext);
- applicationContext.setAttribute(HANDLER_START_TIME_ATTRIBUTE, new Date());
- }
-
- private static final String RESOURCE_CODEC_ATTRIBUTE_NAME =
- ResourceHandlerImpl.class.getName() + ":ResourceCodec";
-
- protected static void setResourceCodec(ResourceCodec codec) {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- Map<String, Object> applicationMap = facesContext.getExternalContext().getApplicationMap();
- Object oldCodec = applicationMap.put(RESOURCE_CODEC_ATTRIBUTE_NAME, codec);
-
- if (oldCodec != null && codec != null && !oldCodec.equals(codec) &&
- facesContext.isProjectStage(ProjectStage.Development)) {
-
- LOGGER.warn("Resource codec should be typically set once per application lifetime");
- }
- }
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(MessageFormat.format("Instance of {0} resource handler created", getClass().getName()));
+ }
- public static ResourceCodec getResourceCodec(FacesContext context) {
- Map<String, Object> applicationMap = context.getExternalContext().getApplicationMap();
- ResourceCodec resourceCodec = (ResourceCodec) applicationMap.get(RESOURCE_CODEC_ATTRIBUTE_NAME);
- if (resourceCodec == null) {
- resourceCodec = DefaultResourceCodec.getInstance();
- }
- return resourceCodec;
- }
-
- protected static String getResourceKey(FacesContext context) {
- String resourceName = Util.decodeResourceURL(context);
- if (resourceName != null) {
- if (resourceName.startsWith(RICHFACES_RESOURCE_IDENTIFIER)) {
- return resourceName.substring(RICHFACES_RESOURCE_IDENTIFIER.length());
- } else {
- return null;
- }
- } else {
- //TODO log
- return null;
- }
- }
+ FacesContext facesContext = FacesContext.getCurrentInstance();
- protected boolean isThisHandlerResourceRequest(FacesContext context) {
- Boolean resourceRequest = BooleanRequestStateVariable.ResourceRequest.get(context);
- if (resourceRequest == null) {
- String resourceKey = getResourceKey(context);
- //TODO handle exclusions
- resourceRequest = resourceKey != null && resourceKey.length() > 0;
- BooleanRequestStateVariable.ResourceRequest.set(context, resourceRequest);
+ initializeCache(facesContext);
+ markStartTime(facesContext);
+ }
- if (LOGGER.isDebugEnabled() && resourceRequest) {
- LOGGER.debug(MessageFormat.format("Resource request detected: {0}", resourceKey));
- }
- }
+ private void initializeCache(FacesContext facesContext) {
+ Map<?, ?> envMap = facesContext.getExternalContext().getInitParameterMap();
- return resourceRequest;
- }
-
- @Override
+ cache = CacheManager.getInstance().getNewCache(RESOURCE_CACHE_NAME, envMap);
+ }
+
+ private static void markStartTime(FacesContext facesContext) {
+ AttributesContext applicationContext = SingletonsContext.APPLICATION.get(facesContext);
+
+ applicationContext.setAttribute(HANDLER_START_TIME_ATTRIBUTE, new Date());
+ }
+
+ protected static void setResourceCodec(ResourceCodec codec) {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ Map<String, Object> applicationMap = facesContext.getExternalContext().getApplicationMap();
+ Object oldCodec = applicationMap.put(RESOURCE_CODEC_ATTRIBUTE_NAME, codec);
+
+ if ((oldCodec != null) && (codec != null) && !oldCodec.equals(codec)
+ && facesContext.isProjectStage(ProjectStage.Development)) {
+ LOGGER.warn("Resource codec should be typically set once per application lifetime");
+ }
+ }
+
+ public static ResourceCodec getResourceCodec(FacesContext context) {
+ Map<String, Object> applicationMap = context.getExternalContext().getApplicationMap();
+ ResourceCodec resourceCodec = (ResourceCodec) applicationMap.get(RESOURCE_CODEC_ATTRIBUTE_NAME);
+
+ if (resourceCodec == null) {
+ resourceCodec = DefaultResourceCodec.getInstance();
+ }
+
+ return resourceCodec;
+ }
+
+ protected static String getResourceKey(FacesContext context) {
+ String resourceName = Util.decodeResourceURL(context);
+
+ if (resourceName != null) {
+ if (resourceName.startsWith(RICHFACES_RESOURCE_IDENTIFIER)) {
+ return resourceName.substring(RICHFACES_RESOURCE_IDENTIFIER.length());
+ } else {
+ return null;
+ }
+ } else {
+
+ // TODO log
+ return null;
+ }
+ }
+
+ protected boolean isThisHandlerResourceRequest(FacesContext context) {
+ Boolean resourceRequest = BooleanRequestStateVariable.ResourceRequest.get(context);
+
+ if (resourceRequest == null) {
+ String resourceKey = getResourceKey(context);
+
+ // TODO handle exclusions
+ resourceRequest = (resourceKey != null) && (resourceKey.length() > 0);
+ BooleanRequestStateVariable.ResourceRequest.set(context, resourceRequest);
+
+ if (LOGGER.isDebugEnabled() && resourceRequest) {
+ LOGGER.debug(MessageFormat.format("Resource request detected: {0}", resourceKey));
+ }
+ }
+
+ return resourceRequest;
+ }
+
+ @Override
public boolean isResourceRequest(FacesContext context) {
- return isThisHandlerResourceRequest(context) || defaultHandler.isResourceRequest(context);
- }
+ return isThisHandlerResourceRequest(context) || defaultHandler.isResourceRequest(context);
+ }
- private Resource lookupInCache(FacesContext context, String resourceKey) {
- Resource resource = (Resource) cache.get(resourceKey);
+ private Resource lookupInCache(FacesContext context, String resourceKey) {
+ Resource resource = (Resource) cache.get(resourceKey);
- if (LOGGER.isDebugEnabled()) {
- if (resource == null) {
- LOGGER.debug("Resource was not located in cache");
- } else {
- LOGGER.debug("Resource was located in cache");
- }
- }
+ if (LOGGER.isDebugEnabled()) {
+ if (resource == null) {
+ LOGGER.debug("Resource was not located in cache");
+ } else {
+ LOGGER.debug("Resource was located in cache");
+ }
+ }
- return resource;
- }
-
- private static void sendNotModified(FacesContext context) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("User agent has actual resource copy - sending 304 status code");
- }
-
- //TODO send cacheable resource headers (ETag + LastModified)?
- context.getExternalContext().setResponseStatus(HttpServletResponse.SC_NOT_MODIFIED);
- }
+ return resource;
+ }
- private void logResourceProblem(FacesContext context, Throwable throwable, String messagePattern, Object... arguments) {
- boolean isProductionStage = context.isProjectStage(ProjectStage.Production);
- if (LOGGER.isWarnEnabled() || (!isProductionStage && LOGGER.isInfoEnabled())) {
- String formattedMessage = MessageFormat.format(messagePattern, arguments);
+ private static void sendNotModified(FacesContext context) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("User agent has actual resource copy - sending 304 status code");
+ }
- if (throwable != null) {
- LOGGER.warn(formattedMessage, throwable);
- } else {
- if (isProductionStage) {
- LOGGER.info(formattedMessage);
- } else {
- LOGGER.warn(formattedMessage);
- }
- }
- }
- }
-
- private void logMissingResource(FacesContext context, String resourceData) {
- logResourceProblem(context, null, "Resource {0} was not found", resourceData);
- }
-
- private static void sendResourceNotFound(FacesContext context) {
- context.getExternalContext().setResponseStatus(HttpServletResponse.SC_NOT_FOUND);
- }
-
- @Override
+ // TODO send cacheable resource headers (ETag + LastModified)?
+ context.getExternalContext().setResponseStatus(HttpServletResponse.SC_NOT_MODIFIED);
+ }
+
+ private void logResourceProblem(FacesContext context, Throwable throwable, String messagePattern,
+ Object... arguments) {
+ boolean isProductionStage = context.isProjectStage(ProjectStage.Production);
+
+ if (LOGGER.isWarnEnabled() || (!isProductionStage && LOGGER.isInfoEnabled())) {
+ String formattedMessage = MessageFormat.format(messagePattern, arguments);
+
+ if (throwable != null) {
+ LOGGER.warn(formattedMessage, throwable);
+ } else {
+ if (isProductionStage) {
+ LOGGER.info(formattedMessage);
+ } else {
+ LOGGER.warn(formattedMessage);
+ }
+ }
+ }
+ }
+
+ private void logMissingResource(FacesContext context, String resourceData) {
+ logResourceProblem(context, null, "Resource {0} was not found", resourceData);
+ }
+
+ private static void sendResourceNotFound(FacesContext context) {
+ context.getExternalContext().setResponseStatus(HttpServletResponse.SC_NOT_FOUND);
+ }
+
+ @Override
public void handleResourceRequest(FacesContext context) throws IOException {
- if (isThisHandlerResourceRequest(context)) {
- String resourceKey = getResourceKey(context);
-
- assert (resourceKey != null && resourceKey.length() != 0);
-
- Resource resource = lookupInCache(context, resourceKey);
- if (resource == null) {
- ResourceCodec resourceCodec = ResourceHandlerImpl.getResourceCodec(context);
- String resourceName = resourceCodec.decodeResourceName(resourceKey);
- if (resourceName == null || resourceName.length() == 0) {
- logMissingResource(context, resourceKey);
- sendResourceNotFound(context);
- return;
- }
-
- if (isResourceExists(resourceName)) {
- resource = createHandlerDependentResource(resourceName);
- }
+ if (isThisHandlerResourceRequest(context)) {
+ String resourceKey = getResourceKey(context);
- if (resource == null) {
- logMissingResource(context, resourceName);
- sendResourceNotFound(context);
- return;
- }
-
- if (resource instanceof VersionedResource) {
- VersionedResource versionedResource = (VersionedResource) resource;
- String existingVersion = versionedResource.getVersion();
- String requestedVersion = resourceCodec.decodeResourceVersion(resourceKey);
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(MessageFormat.format("Client requested {0} version of resource, server has {1} version",
- String.valueOf(requestedVersion), String.valueOf(existingVersion)));
- }
-
- if (existingVersion != null && requestedVersion != null &&
- !existingVersion.equals(requestedVersion)) {
-
- logResourceProblem(context, null, "Resource {0} of version {1} was not found",
- resourceName, requestedVersion);
-
- sendResourceNotFound(context);
- return;
- }
- }
-
- if (resource instanceof StateHolder) {
- StateHolder stateHolder = (StateHolder) resource;
- Object decodedData = resourceCodec.decodeResourceData(resourceKey);
+ assert (resourceKey != null) && (resourceKey.length() != 0);
- if (LOGGER.isDebugEnabled()) {
- if (decodedData != null) {
- LOGGER.debug("Resource state data succesfully decoded");
- } else {
- LOGGER.debug("Resource state data decoded as null");
- }
- }
-
- if (decodedData != null) {
- stateHolder.restoreState(context, decodedData);
- } else {
- //resource was transient and didn't store data
- }
- }
-
- if (resource instanceof AbstractCacheableResource) {
- AbstractCacheableResource cacheableResource = (AbstractCacheableResource) resource;
-
- if (cacheableResource.isCacheable(context)) {
- //TODO - we could move this part of code to ConcurrentMap so that
- //only single thread does resource put
- CachedResourceImpl cachedResource = new CachedResourceImpl();
- cachedResource.initialize(resource);
+ Resource resource = lookupInCache(context, resourceKey);
- //someone may provided this resource for us
- //while we were reading it, check once again
- resource = lookupInCache(context, resourceKey);
- if (resource == null) {
- Date cacheExpirationDate = cachedResource.getExpired(context);
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(new MessageFormat("Storing {0} resource in cache until {1,date,dd MMM yyyy HH:mm:ss zzz}",
- Locale.US).format(new Object[]{resourceKey, cacheExpirationDate}));
- }
-
- cache.put(resourceKey, cachedResource, cacheExpirationDate);
- resource = cachedResource;
- }
- }
- }
- }
-
- if (resource.userAgentNeedsUpdate(context)) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("User agent needs resource update, encoding resource");
- }
-
- ExternalContext externalContext = context.getExternalContext();
- Map<String, String> headers = resource.getResponseHeaders();
- for (Entry<String, String> headerEntry : headers.entrySet()) {
- String headerName = headerEntry.getKey();
- String headerValue = headerEntry.getValue();
-
- //TODO should external context handles this itself?
- if ("content-length".equals(headerName.toLowerCase(Locale.US))) {
- try {
- externalContext.setResponseContentLength(Integer.parseInt(headerValue));
- } catch (NumberFormatException e) {
- // TODO: handle exception
- }
- }/* else if ("content-type".equals(headerName.toLowerCase(Locale.US))) {
- externalContext.setResponseContentType(headerValue);
- }*/ else {
- externalContext.setResponseHeader(headerName, headerValue);
- }
- }
+ if (resource == null) {
+ ResourceCodec resourceCodec = ResourceHandlerImpl.getResourceCodec(context);
+ String resourceName = resourceCodec.decodeResourceName(resourceKey);
- //TODO null content type?
- String contentType = resource.getContentType();
- if (contentType != null) {
- externalContext.setResponseContentType(contentType);
- }
-
- //TODO - portlets
- HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
- if (!"HEAD".equals(httpServletRequest.getMethod())) {
- //TODO 'HEAD' HTTP method resources - ?
- //TODO setup output buffer size according to configuration parameter
- InputStream is = resource.getInputStream();
- OutputStream os = externalContext.getResponseOutputStream();
+ if ((resourceName == null) || (resourceName.length() == 0)) {
+ logMissingResource(context, resourceKey);
+ sendResourceNotFound(context);
- try {
- Util.copyStreamContent(is, os);
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(e.getMessage(), e);
- }
- }
- }
- //TODO flush resource
- //TODO dispose resource
- }
- }
+ return;
+ }
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Resource succesfully encoded");
- }
-
- } else {
- sendNotModified(context);
- }
- } else {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Passing request to the next resource handler in chain");
- }
- defaultHandler.handleResourceRequest(context);
- }
- }
+ if (isResourceExists(resourceName)) {
+ resource = createHandlerDependentResource(resourceName);
+ }
- protected static boolean isResourceExists(String resourceName) {
- boolean result = false;
- ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- if (contextClassLoader != null) {
- //TODO resource marker extension name?
- URL resourceMarkerUrl = contextClassLoader.getResource("META-INF/" + resourceName + ".resource.properties");
- result = (resourceMarkerUrl != null);
-
- if (LOGGER.isDebugEnabled()) {
- if (result) {
- LOGGER.debug(MessageFormat.format("Marker file for {0} resource found in classpath", resourceName));
- } else {
- LOGGER.debug(MessageFormat.format("Marker file for {0} resource does not exist", resourceName));
- }
- }
- }
-
- return result;
- }
-
- /**
- * Should be called only if {@link #isResourceExists(String)} returns <code>true</code>
- * @param resourceName
- * @return
- */
- protected Resource createHandlerDependentResource(String resourceName) {
-
- Resource resource = null;
-
- ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- if (contextClassLoader != null) {
- try {
- Class<?> resourceClass = Class.forName(resourceName, false, contextClassLoader);
- if (Resource.class.isAssignableFrom(resourceClass)) {
- resource = (Resource) resourceClass.newInstance();
- resource.setResourceName(resourceName);
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(MessageFormat.format(
- "Successfully created instance of {0} resource", resourceName));
- }
- } else {
- throw new ClassCastException(resourceClass.getName());
- }
- } catch (Throwable t) {
- logResourceProblem(FacesContext.getCurrentInstance(), t,
- "Error creating resource {0}", resourceName);
- }
- }
-
- return resource;
- }
-
- @Override
- public Resource createResource(String resourceName, String libraryName,
- String contentType) {
+ if (resource == null) {
+ logMissingResource(context, resourceName);
+ sendResourceNotFound(context);
- Resource result;
+ return;
+ }
- if (resourceName != null && (libraryName == null || libraryName.length() == 0)
- && isResourceExists(resourceName)) {
+ if (resource instanceof VersionedResource) {
+ VersionedResource versionedResource = (VersionedResource) resource;
+ String existingVersion = versionedResource.getVersion();
+ String requestedVersion = resourceCodec.decodeResourceVersion(resourceKey);
- result = createHandlerDependentResource(resourceName);
- } else {
- result = defaultHandler.createResource(resourceName, libraryName, contentType);
- }
-
- return result;
- }
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(
+ MessageFormat.format(
+ "Client requested {0} version of resource, server has {1} version",
+ String.valueOf(requestedVersion), String.valueOf(existingVersion)));
+ }
- @Override
+ if ((existingVersion != null) && (requestedVersion != null)
+ && !existingVersion.equals(requestedVersion)) {
+ logResourceProblem(context, null, "Resource {0} of version {1} was not found", resourceName,
+ requestedVersion);
+ sendResourceNotFound(context);
+
+ return;
+ }
+ }
+
+ if (resource instanceof StateHolder) {
+ StateHolder stateHolder = (StateHolder) resource;
+ Object decodedData = resourceCodec.decodeResourceData(resourceKey);
+
+ if (LOGGER.isDebugEnabled()) {
+ if (decodedData != null) {
+ LOGGER.debug("Resource state data succesfully decoded");
+ } else {
+ LOGGER.debug("Resource state data decoded as null");
+ }
+ }
+
+ if (decodedData != null) {
+ stateHolder.restoreState(context, decodedData);
+ } else {
+
+ // resource was transient and didn't store data
+ }
+ }
+
+ if (resource instanceof AbstractCacheableResource) {
+ AbstractCacheableResource cacheableResource = (AbstractCacheableResource) resource;
+
+ if (cacheableResource.isCacheable(context)) {
+
+ // TODO - we could move this part of code to ConcurrentMap so that
+ // only single thread does resource put
+ CachedResourceImpl cachedResource = new CachedResourceImpl();
+
+ cachedResource.initialize(resource);
+
+ // someone may provided this resource for us
+ // while we were reading it, check once again
+ resource = lookupInCache(context, resourceKey);
+
+ if (resource == null) {
+ Date cacheExpirationDate = cachedResource.getExpired(context);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(new MessageFormat(
+ "Storing {0} resource in cache until {1,date,dd MMM yyyy HH:mm:ss zzz}", Locale.US).
+ format(new Object[] {resourceKey, cacheExpirationDate}));
+ }
+
+ cache.put(resourceKey, cachedResource, cacheExpirationDate);
+ resource = cachedResource;
+ }
+ }
+ }
+ }
+
+ if (resource.userAgentNeedsUpdate(context)) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("User agent needs resource update, encoding resource");
+ }
+
+ ExternalContext externalContext = context.getExternalContext();
+ Map<String, String> headers = resource.getResponseHeaders();
+
+ for (Entry<String, String> headerEntry : headers.entrySet()) {
+ String headerName = headerEntry.getKey();
+ String headerValue = headerEntry.getValue();
+
+ // TODO should external context handles this itself?
+ if ("content-length".equals(headerName.toLowerCase(Locale.US))) {
+ try {
+ externalContext.setResponseContentLength(Integer.parseInt(headerValue));
+ } catch (NumberFormatException e) {
+
+ // TODO: handle exception
+ }
+ } else {
+ externalContext.setResponseHeader(headerName, headerValue);
+ }
+ }
+
+ // TODO null content type?
+ String contentType = resource.getContentType();
+
+ if (contentType != null) {
+ externalContext.setResponseContentType(contentType);
+ }
+
+ // TODO - portlets
+ HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
+
+ if (!"HEAD".equals(httpServletRequest.getMethod())) {
+
+ // TODO 'HEAD' HTTP method resources - ?
+ // TODO setup output buffer size according to configuration parameter
+ InputStream is = resource.getInputStream();
+ OutputStream os = externalContext.getResponseOutputStream();
+
+ try {
+ Util.copyStreamContent(is, os);
+ } finally {
+ if (is != null) {
+ try {
+ is.close();
+ } catch (IOException e) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(e.getMessage(), e);
+ }
+ }
+ }
+
+ // TODO flush resource
+ // TODO dispose resource
+ }
+ }
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Resource succesfully encoded");
+ }
+ } else {
+ sendNotModified(context);
+ }
+ } else {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Passing request to the next resource handler in chain");
+ }
+
+ defaultHandler.handleResourceRequest(context);
+ }
+ }
+
+ protected static boolean isResourceExists(String resourceName) {
+ boolean result = false;
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+
+ if (contextClassLoader != null) {
+
+ // TODO resource marker extension name?
+ URL resourceMarkerUrl = contextClassLoader.getResource("META-INF/" + resourceName + ".resource.properties");
+
+ result = resourceMarkerUrl != null;
+
+ if (LOGGER.isDebugEnabled()) {
+ if (result) {
+ LOGGER.debug(MessageFormat.format("Marker file for {0} resource found in classpath", resourceName));
+ } else {
+ LOGGER.debug(MessageFormat.format("Marker file for {0} resource does not exist", resourceName));
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Should be called only if {@link #isResourceExists(String)} returns <code>true</code>
+ * @param resourceName
+ * @return
+ */
+ protected Resource createHandlerDependentResource(String resourceName) {
+ Resource resource = null;
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+
+ if (contextClassLoader != null) {
+ try {
+ Class<?> resourceClass = Class.forName(resourceName, false, contextClassLoader);
+
+ if (Resource.class.isAssignableFrom(resourceClass)) {
+ resource = (Resource) resourceClass.newInstance();
+ resource.setResourceName(resourceName);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(MessageFormat.format("Successfully created instance of {0} resource",
+ resourceName));
+ }
+ } else {
+ throw new ClassCastException(resourceClass.getName());
+ }
+ } catch (Throwable t) {
+ logResourceProblem(FacesContext.getCurrentInstance(), t, "Error creating resource {0}", resourceName);
+ }
+ }
+
+ return resource;
+ }
+
+ @Override
+ public Resource createResource(String resourceName, String libraryName, String contentType) {
+ Resource result;
+
+ if ((resourceName != null) && ((libraryName == null) || (libraryName.length() == 0))
+ && isResourceExists(resourceName)) {
+ result = createHandlerDependentResource(resourceName);
+ } else {
+ result = defaultHandler.createResource(resourceName, libraryName, contentType);
+ }
+
+ return result;
+ }
+
+ @Override
public Resource createResource(String resourceName, String libraryName) {
- return createResource(resourceName, libraryName, null);
- }
+ return createResource(resourceName, libraryName, null);
+ }
- @Override
+ @Override
public Resource createResource(String resourceName) {
- return createResource(resourceName, null, null);
- }
+ return createResource(resourceName, null, null);
+ }
- @Override
+ @Override
public String getRendererTypeForResourceName(String resourceName) {
- //TODO add support for dynamic resources
- return defaultHandler.getRendererTypeForResourceName(resourceName);
- }
- @Override
+ // TODO add support for dynamic resources
+ return defaultHandler.getRendererTypeForResourceName(resourceName);
+ }
+
+ @Override
public boolean libraryExists(String libraryName) {
- return defaultHandler.libraryExists(libraryName);
- }
+ return defaultHandler.libraryExists(libraryName);
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceUtils.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceUtils.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceUtils.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,75 +19,74 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public final class ResourceUtils {
-
- private ResourceUtils() {}
-
- private static final String QUOTED_STRING_REGEX = "(?:\\\\[\\x00-\\x7F]|[^\"\\\\])+";
-
- private static final Pattern ETAG_PATTERN = Pattern.compile("(?:W/)?\"(" + QUOTED_STRING_REGEX + ")\"(?:,\\s*)?");
-
private static final long MILLISECOND_IN_SECOND = 1000L;
+ private static final String QUOTED_STRING_REGEX = "(?:\\\\[\\x00-\\x7F]|[^\"\\\\])+";
+ private static final Pattern ETAG_PATTERN = Pattern.compile("(?:W/)?\"(" + QUOTED_STRING_REGEX + ")\"(?:,\\s*)?");
- public static String formatWeakTag(String eTag) {
- String formattedTag = formatTag(eTag);
- if (formattedTag == null) {
- return null;
- }
-
- return "W/" + formattedTag;
- }
+ private ResourceUtils() {}
- public static String formatTag(String eTag) {
- if (eTag == null) {
- return null;
- }
-
- if (!eTag.matches(QUOTED_STRING_REGEX)) {
- throw new IllegalArgumentException("tag must matches to regexp '" + QUOTED_STRING_REGEX + '\'');
- }
+ public static String formatWeakTag(String eTag) {
+ String formattedTag = formatTag(eTag);
- return '\"' + eTag + '\"';
- }
-
- public static boolean matchTag(String eTag, String eTagHeaderValue) {
- if (eTag == null || eTagHeaderValue == null) {
- throw new IllegalArgumentException("tag and tagHeaderValue must be not null");
- }
+ if (formattedTag == null) {
+ return null;
+ }
- Matcher eTagMatcher = ETAG_PATTERN.matcher(eTag);
- if (!eTagMatcher.find()) {
- throw new IllegalArgumentException();
- }
+ return "W/" + formattedTag;
+ }
+ public static String formatTag(String eTag) {
+ if (eTag == null) {
+ return null;
+ }
+
+ if (!eTag.matches(QUOTED_STRING_REGEX)) {
+ throw new IllegalArgumentException("tag must matches to regexp '" + QUOTED_STRING_REGEX + '\'');
+ }
+
+ return '\"' + eTag + '\"';
+ }
+
+ public static boolean matchTag(String eTag, String eTagHeaderValue) {
+ if ((eTag == null) || (eTagHeaderValue == null)) {
+ throw new IllegalArgumentException("tag and tagHeaderValue must be not null");
+ }
+
+ Matcher eTagMatcher = ETAG_PATTERN.matcher(eTag);
+
+ if (!eTagMatcher.find()) {
+ throw new IllegalArgumentException();
+ }
+
String tag = eTagMatcher.group(1);
+ Matcher eTagHeaderMatcher = ETAG_PATTERN.matcher(eTagHeaderValue);
+ while (eTagHeaderMatcher.find()) {
+ if (tag.equals(eTagHeaderMatcher.group(1))) {
+ return true;
+ }
+ }
- Matcher eTagHeaderMatcher = ETAG_PATTERN.matcher(eTagHeaderValue);
- while (eTagHeaderMatcher.find()) {
- if (tag.equals(eTagHeaderMatcher.group(1))) {
- return true;
- }
- }
-
- return false;
- }
+ return false;
+ }
public static long millisToSecond(long millisecond) {
- return millisecond / MILLISECOND_IN_SECOND;
+ return millisecond / MILLISECOND_IN_SECOND;
}
public static long secondToMillis(long second) {
- return second * MILLISECOND_IN_SECOND;
+ return second * MILLISECOND_IN_SECOND;
}
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/AbstractChainableSkinImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/AbstractChainableSkinImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/AbstractChainableSkinImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,141 +19,140 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
+import org.ajax4jsf.Messages;
+
import java.util.Map;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
-import org.ajax4jsf.Messages;
-
/**
* @author nick belaevski
* @since 3.2
*/
-
public abstract class AbstractChainableSkinImpl extends BasicSkinImpl {
+ private static final Operation RESOLVE = new Operation() {
+ public Object doExternalCall(FacesContext context, Skin impl, String name) {
+ // TODO add warning because substitution can work incorrect and cyclic references
+ // won't be caught
+ return impl.getParameter(context, name);
+ }
+ public Object doLocalCall(FacesContext context, AbstractChainableSkinImpl impl, String name) {
+ return impl.localResolveSkinParameter(context, name);
+ }
+ };
+ private static final Operation CONTAINS = new Operation() {
+ private Object wrapBoolean(boolean value) {
+ return value ? Boolean.TRUE : null;
+ }
+ public Object doExternalCall(FacesContext context, Skin impl, String name) {
+ return wrapBoolean(impl.containsProperty(name));
+ }
+ public Object doLocalCall(FacesContext context, AbstractChainableSkinImpl impl, String name) {
+ return wrapBoolean(impl.localContainsProperty(context, name));
+ }
+ };
+
AbstractChainableSkinImpl(Map properties) {
- super(properties);
+ super(properties);
}
protected abstract Skin getBaseSkin(FacesContext context);
-
+
protected Object localResolveSkinParameter(FacesContext context, String name) {
- return getSkinParams().get(name);
+ return getSkinParams().get(name);
}
-
+
protected boolean localContainsProperty(FacesContext context, String name) {
- return getSkinParams().containsKey(name);
+ return getSkinParams().containsKey(name);
}
- private static abstract class Operation {
- public Object doChainedCall(FacesContext context, AbstractChainableSkinImpl impl, String name, int[] singleInt) {
- return impl.executeOperation(context, this, name, singleInt);
- }
-
- public abstract Object doLocalCall(FacesContext context, AbstractChainableSkinImpl impl, String name);
+ protected Object executeOperation(FacesContext context, Operation operation, String name, int[] singleInt) {
+ if (singleInt[0]++ > 1000) {
+ throw new FacesException(Messages.getMessage(Messages.SKIN_CYCLIC_REFERENCE, name));
+ }
- public abstract Object doExternalCall(FacesContext context, Skin impl, String name);
- }
+ Object object = operation.doLocalCall(context, this, name);
- private static final Operation RESOLVE = new Operation() {
+ if (object == null) {
+ Skin baseSkin = getBaseSkin(context);
- public Object doExternalCall(FacesContext context, Skin impl, String name) {
- //TODO add warning because substitution can work incorrect and cyclic references
- //won't be caught
- return impl.getParameter(context, name);
- }
+ if (baseSkin != null) {
+ if (baseSkin instanceof AbstractChainableSkinImpl) {
+ AbstractChainableSkinImpl skinImpl = (AbstractChainableSkinImpl) baseSkin;
- public Object doLocalCall(FacesContext context, AbstractChainableSkinImpl impl, String name) {
- return impl.localResolveSkinParameter(context, name);
- }
-
- };
-
- private static final Operation CONTAINS = new Operation() {
+ object = operation.doChainedCall(context, skinImpl, name, singleInt);
+ } else {
+ object = operation.doExternalCall(context, baseSkin, name);
+ }
+ }
+ }
- private Object wrapBoolean(boolean value) {
- return value ? Boolean.TRUE : null;
- }
-
- public Object doExternalCall(FacesContext context, Skin impl, String name) {
- return wrapBoolean(impl.containsProperty(name));
- }
-
- public Object doLocalCall(FacesContext context, AbstractChainableSkinImpl impl, String name) {
- return wrapBoolean(impl.localContainsProperty(context, name));
- }
-
- };
-
- protected Object executeOperation(FacesContext context, Operation operation, String name, int[] singleInt) {
- if (singleInt[0]++ > 1000) {
- throw new FacesException(Messages.getMessage(
- Messages.SKIN_CYCLIC_REFERENCE, name));
- }
-
- Object object = operation.doLocalCall(context, this, name);
- if (object == null) {
- Skin baseSkin = getBaseSkin(context);
- if (baseSkin != null) {
- if (baseSkin instanceof AbstractChainableSkinImpl) {
- AbstractChainableSkinImpl skinImpl = (AbstractChainableSkinImpl) baseSkin;
- object = operation.doChainedCall(context, skinImpl, name, singleInt);
- } else {
- object = operation.doExternalCall(context, baseSkin, name);
- }
- }
- }
-
- return object;
+ return object;
}
-
+
protected Object resolveSkinParameter(FacesContext context, String name, int[] singleInt) {
- return executeOperation(context, RESOLVE, name, singleInt);
+ return executeOperation(context, RESOLVE, name, singleInt);
}
-
+
protected boolean containsProperty(FacesContext context, String name, int[] singleInt) {
- return Boolean.TRUE.equals(executeOperation(context, CONTAINS, name, singleInt));
+ return Boolean.TRUE.equals(executeOperation(context, CONTAINS, name, singleInt));
}
protected Object resolveSkinParameter(FacesContext context, String name) {
- int[] singleInt = new int[] {0};
- Object resolvedParameter = resolveSkinParameter(context, name, singleInt);
-
- while (resolvedParameter instanceof String) {
- String string = (String) resolvedParameter;
- if (string.length() > 0 && string.charAt(0) == '&') {
- resolvedParameter = resolveSkinParameter(context, string.substring(1), singleInt);
- if (resolvedParameter == null) {
- throw new FacesException(Messages.getMessage(
- Messages.SKIN_ILLEGAL_REFERENCE, name));
- }
- } else {
- break;
- }
- }
-
- return resolvedParameter;
+ int[] singleInt = new int[] {0};
+ Object resolvedParameter = resolveSkinParameter(context, name, singleInt);
+
+ while (resolvedParameter instanceof String) {
+ String string = (String) resolvedParameter;
+
+ if ((string.length() > 0) && (string.charAt(0) == '&')) {
+ resolvedParameter = resolveSkinParameter(context, string.substring(1), singleInt);
+
+ if (resolvedParameter == null) {
+ throw new FacesException(Messages.getMessage(Messages.SKIN_ILLEGAL_REFERENCE, name));
+ }
+ } else {
+ break;
+ }
+ }
+
+ return resolvedParameter;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.richfaces.skin.Skin#containsProperty(java.lang.String)
*/
public boolean containsProperty(String name) {
- return containsProperty(FacesContext.getCurrentInstance(), name, new int[] {0});
+ return containsProperty(FacesContext.getCurrentInstance(), name, new int[] {0});
}
+ @Override
protected int computeHashCode(FacesContext context) {
- int hash = super.computeHashCode(context);
- Skin baseSkin = getBaseSkin(context);
- if (baseSkin != null) {
- hash = 31*hash + baseSkin.hashCode(context);
- }
+ int hash = super.computeHashCode(context);
+ Skin baseSkin = getBaseSkin(context);
+ if (baseSkin != null) {
+ hash = 31 * hash + baseSkin.hashCode(context);
+ }
+
return hash;
}
-
+
+ private abstract static class Operation {
+ public Object doChainedCall(FacesContext context, AbstractChainableSkinImpl impl, String name,
+ int[] singleInt) {
+ return impl.executeOperation(context, this, name, singleInt);
+ }
+
+ public abstract Object doLocalCall(FacesContext context, AbstractChainableSkinImpl impl, String name);
+
+ public abstract Object doExternalCall(FacesContext context, Skin impl, String name);
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/BasicSkinImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/BasicSkinImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/BasicSkinImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
import java.util.HashMap;
@@ -28,67 +30,70 @@
import java.util.concurrent.ConcurrentMap;
import javax.el.ValueExpression;
+
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
/**
* Singleton ( in respect as collection of different skins ) for produce
* instances properties for all used skins.
- *
+ *
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:59:41 $
- *
+ *
*/
public abstract class BasicSkinImpl implements Skin {
-
public static final String RENDER_KIT_PARAMETER = "render.kit";
-
- public static final String REQUEST_HASH_CODES_MAP_PARAMETER = "org.ajax4jsf.skin.HASH_CODES_MAP";
-
+ public static final String REQUEST_HASH_CODES_MAP_PARAMETER = "org.ajax4jsf.skin.HASH_CODES_MAP";
private Map<String, Object> skinParams = new HashMap<String, Object>();
/**
* Skin can instantiate only by factory method.
- *
+ *
* @param skinName
*/
BasicSkinImpl(Map properties) {
- this.skinParams = properties;
+ this.skinParams = properties;
}
-
+
protected Map<String, Object> getSkinParams() {
- return skinParams;
+ return skinParams;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.richfaces.skin.Skin#getRenderKitId(javax.faces.context.FacesContext)
*/
public String getRenderKitId(FacesContext context) {
- return (String) getValueReference(context, resolveSkinParameter(context, RENDER_KIT_PARAMETER));
+ return (String) getValueReference(context, resolveSkinParameter(context, RENDER_KIT_PARAMETER));
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.richfaces.skin.Skin#getParameter(javax.faces.context.FacesContext, java.lang.String)
*/
public Object getParameter(FacesContext context, String name) {
- return getValueReference(context, resolveSkinParameter(context, name));
+ return getValueReference(context, resolveSkinParameter(context, name));
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.richfaces.skin.Skin#getParameter(javax.faces.context.FacesContext, java.lang.String, java.lang.String, java.lang.Object)
*/
- public Object getParameter(FacesContext context, String name, Object defaultValue) {
- Object value = getValueReference(context, resolveSkinParameter(context, name));
- if(null == value){
- value = defaultValue;
- }
- return value;
+ public Object getParameter(FacesContext context, String name, Object defaultValue) {
+ Object value = getValueReference(context, resolveSkinParameter(context, name));
+
+ if (null == value) {
+ value = defaultValue;
+ }
+
+ return value;
}
protected Object getLocalParameter(FacesContext context, String name) {
- return getValueReference(context, skinParams.get(name));
+ return getValueReference(context, skinParams.get(name));
}
-
+
protected abstract Object resolveSkinParameter(FacesContext context, String name);
/**
@@ -99,52 +104,60 @@
* @return
*/
protected Object getValueReference(FacesContext context, Object property) {
- if (property instanceof ValueExpression) {
- ValueExpression value = (ValueExpression) property;
- return value.getValue(context.getELContext());
- }
- return property;
+ if (property instanceof ValueExpression) {
+ ValueExpression value = (ValueExpression) property;
+
+ return value.getValue(context.getELContext());
+ }
+
+ return property;
}
-
public String toString() {
- return this.getClass().getSimpleName() + ": " + skinParams.toString();
+ return this.getClass().getSimpleName() + ": " + skinParams.toString();
}
-
+
protected int computeHashCode(FacesContext context) {
- int hash = 0;
- for (Iterator iter = skinParams.keySet().iterator(); iter.hasNext();) {
- String key = (String) iter.next();
- Object parameter = getLocalParameter(context, key);
- hash = 31*hash + key.hashCode();
- hash = 31*hash + (parameter != null ? parameter.hashCode() : 0);
- }
+ int hash = 0;
- return hash;
+ for (Iterator iter = skinParams.keySet().iterator(); iter.hasNext(); ) {
+ String key = (String) iter.next();
+ Object parameter = getLocalParameter(context, key);
+
+ hash = 31 * hash + key.hashCode();
+ hash = 31 * hash + ((parameter != null) ? parameter.hashCode() : 0);
+ }
+
+ return hash;
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see org.richfaces.skin.Skin#hashCode(javax.faces.context.FacesContext)
*/
public int hashCode(FacesContext context) {
- ExternalContext externalContext = context.getExternalContext();
- Map<String, Object> requestMap = externalContext.getRequestMap();
- ConcurrentMap<Skin, Integer> map;
- synchronized (requestMap) {
- map = (ConcurrentMap<Skin, Integer>) requestMap.get(REQUEST_HASH_CODES_MAP_PARAMETER);
- if (map == null) {
- map = new ConcurrentHashMap<Skin, Integer>();
- requestMap.put(REQUEST_HASH_CODES_MAP_PARAMETER, map);
- }
- }
+ ExternalContext externalContext = context.getExternalContext();
+ Map<String, Object> requestMap = externalContext.getRequestMap();
+ ConcurrentMap<Skin, Integer> map;
- Integer requestCode = (Integer) map.get(this);
- if(null == requestCode){
- requestCode = new Integer(computeHashCode(context));
- // store hash for this skin as request-skope parameter - not calculate on next calls for same request
- map.putIfAbsent(this, requestCode);
- }
- return requestCode.intValue();
+ synchronized (requestMap) {
+ map = (ConcurrentMap<Skin, Integer>) requestMap.get(REQUEST_HASH_CODES_MAP_PARAMETER);
+
+ if (map == null) {
+ map = new ConcurrentHashMap<Skin, Integer>();
+ requestMap.put(REQUEST_HASH_CODES_MAP_PARAMETER, map);
+ }
+ }
+
+ Integer requestCode = (Integer) map.get(this);
+
+ if (null == requestCode) {
+ requestCode = new Integer(computeHashCode(context));
+
+ // store hash for this skin as request-skope parameter - not calculate on next calls for same request
+ map.putIfAbsent(this, requestCode);
+ }
+
+ return requestCode.intValue();
}
-
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/DefaultSkinImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/DefaultSkinImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/DefaultSkinImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
import java.util.Map;
@@ -29,11 +31,9 @@
* @author nick belaevski
* @since 3.2
*/
-
public class DefaultSkinImpl extends AbstractChainableSkinImpl {
-
DefaultSkinImpl(Map properties) {
- super(properties);
+ super(properties);
}
protected Skin getBaseSkin(FacesContext context) {
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/DummySkinConfiguration.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/DummySkinConfiguration.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/DummySkinConfiguration.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,53 +19,54 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
import javax.faces.context.FacesContext;
-import org.richfaces.skin.Skin;
-import org.richfaces.skin.SkinConfiguration;
-
/**
* @author shura
*
*/
public class DummySkinConfiguration implements SkinConfiguration {
-
- private Skin _skin;
+ private Skin skin;
- /**
- * @param skin
- */
- public DummySkinConfiguration(Skin skin) {
- super();
- _skin = skin;
- }
+ /**
+ * @param skin
+ */
+ public DummySkinConfiguration(Skin skin) {
+ super();
+ this.skin = skin;
+ }
- /* (non-Javadoc)
- * @see org.richfaces.skin.SkinConfiguration#containsParameter(java.lang.String)
- */
- public boolean containsParameter(String name) {
- return _skin.containsProperty(name);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.SkinConfiguration#containsParameter(java.lang.String)
+ */
+ public boolean containsParameter(String name) {
+ return skin.containsProperty(name);
+ }
- /* (non-Javadoc)
- * @see org.richfaces.skin.SkinConfiguration#getParameter(javax.faces.context.FacesContext, java.lang.String)
- */
- public Object getParameter(FacesContext context, String name) {
- return _skin.getParameter(context, name);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.SkinConfiguration#getParameter(javax.faces.context.FacesContext, java.lang.String)
+ */
+ public Object getParameter(FacesContext context, String name) {
+ return skin.getParameter(context, name);
+ }
- /* (non-Javadoc)
- * @see org.richfaces.skin.SkinConfiguration#getParameter(javax.faces.context.FacesContext, java.lang.String, java.lang.String, java.lang.Object)
- */
- public Object getParameter(FacesContext context, String name,
- String skinName, Object defaultValue) {
- Object parameter = _skin.getParameter(context, name);
- if(null == parameter){
- parameter = defaultValue;
- }
- return parameter;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.SkinConfiguration#getParameter(javax.faces.context.FacesContext, String, String, Object)
+ */
+ public Object getParameter(FacesContext context, String name, String skinName, Object defaultValue) {
+ Object parameter = skin.getParameter(context, name);
+ if (null == parameter) {
+ parameter = defaultValue;
+ }
+
+ return parameter;
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinBean.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinBean.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinBean.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,18 +19,18 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
+import javax.faces.context.FacesContext;
+
import java.nio.ByteBuffer;
+
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Set;
-import javax.faces.context.FacesContext;
-
-import org.richfaces.skin.Skin;
-import org.richfaces.skin.SkinFactory;
-
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:59:40 $
@@ -38,102 +38,113 @@
*/
public class SkinBean extends AbstractMap implements Skin {
- /* (non-Javadoc)
- * @see org.richfaces.skin.Skin#hashCode(javax.faces.context.FacesContext)
- */
- public int hashCode(FacesContext context) {
- // TODO Auto-generated method stub
- return getSkin().hashCode(context);
- }
-
-
-
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.Skin#hashCode(javax.faces.context.FacesContext)
+ */
+ public int hashCode(FacesContext context) {
- /* (non-Javadoc)
- * @see java.util.AbstractMap#entrySet()
- */
- public Set entrySet() {
- // TODO Auto-generated method stub
- return Collections.EMPTY_SET;
- }
+ // TODO Auto-generated method stub
+ return getSkin().hashCode(context);
+ }
- /* (non-Javadoc)
- * @see java.util.AbstractMap#containsKey(java.lang.Object)
- */
- public boolean containsKey(Object key) {
- if(null == key) {
- return false;
- }
- return getSkin().containsProperty(key.toString());
- }
+ /*
+ * (non-Javadoc)
+ * @see java.util.AbstractMap#entrySet()
+ */
+ @Override
+ public Set entrySet() {
- /* (non-Javadoc)
- * @see java.util.AbstractMap#get(java.lang.Object)
- */
- public Object get(Object key) {
- if(null == key) {
- return null;
- }
- return getSkin().getParameter(FacesContext.getCurrentInstance(),key.toString());
- }
+ // TODO Auto-generated method stub
+ return Collections.EMPTY_SET;
+ }
- private Skin getSkin() {
- FacesContext context = FacesContext.getCurrentInstance();
- return SkinFactory.getInstance().getSkin(context);
- }
+ /*
+ * (non-Javadoc)
+ * @see java.util.AbstractMap#containsKey(java.lang.Object)
+ */
+ @Override
+ public boolean containsKey(Object key) {
+ if (null == key) {
+ return false;
+ }
- /* (non-Javadoc)
- * @see java.util.AbstractMap#toString()
- */
- public String toString() {
- return getSkin().toString();
- }
+ return getSkin().containsProperty(key.toString());
+ }
- /* (non-Javadoc)
- * @see java.util.AbstractMap#isEmpty()
- */
- public boolean isEmpty() {
- // TODO Auto-generated method stub
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see java.util.AbstractMap#get(java.lang.Object)
+ */
+ @Override
+ public Object get(Object key) {
+ if (null == key) {
+ return null;
+ }
- /* (non-Javadoc)
- * @see org.richfaces.skin.Skin#getRenderKitId(javax.faces.context.FacesContext)
- */
- public String getRenderKitId(FacesContext context) {
- return getSkin().getRenderKitId(context);
- }
+ return getSkin().getParameter(FacesContext.getCurrentInstance(), key.toString());
+ }
- /* (non-Javadoc)
- * @see org.richfaces.skin.Skin#getParameter(javax.faces.context.FacesContext, java.lang.String)
- */
- public Object getParameter(FacesContext context, String name) {
- return getSkin().getParameter(context,name);
- }
+ private Skin getSkin() {
+ FacesContext context = FacesContext.getCurrentInstance();
-
- public Object getParameter(FacesContext context, String name, Object defaultValue) {
-
- return getSkin().getParameter(context, name, defaultValue);
- }
+ return SkinFactory.getInstance().getSkin(context);
+ }
+ /*
+ * (non-Javadoc)
+ * @see java.util.AbstractMap#toString()
+ */
+ @Override
+ public String toString() {
+ return getSkin().toString();
+ }
+ /*
+ * (non-Javadoc)
+ * @see java.util.AbstractMap#isEmpty()
+ */
+ @Override
+ public boolean isEmpty() {
+ // TODO Auto-generated method stub
+ return false;
+ }
- /* (non-Javadoc)
- * @see org.richfaces.skin.Skin#containsProperty(java.lang.String)
- */
- public boolean containsProperty(String name) {
- return getSkin().containsProperty(name);
- }
-
- /* Static methods for manipulate skins */
-
- public static Object skinHashCode(){
- FacesContext context = FacesContext.getCurrentInstance();
- int hashCode = SkinFactory.getInstance().getSkin(context).hashCode(context);
- byte[] bs = ByteBuffer.allocate(4).putInt(hashCode).array();
- return bs;
- }
-
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.Skin#getRenderKitId(javax.faces.context.FacesContext)
+ */
+ public String getRenderKitId(FacesContext context) {
+ return getSkin().getRenderKitId(context);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.Skin#getParameter(javax.faces.context.FacesContext, java.lang.String)
+ */
+ public Object getParameter(FacesContext context, String name) {
+ return getSkin().getParameter(context, name);
+ }
+
+ public Object getParameter(FacesContext context, String name, Object defaultValue) {
+ return getSkin().getParameter(context, name, defaultValue);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.Skin#containsProperty(java.lang.String)
+ */
+ public boolean containsProperty(String name) {
+ return getSkin().containsProperty(name);
+ }
+
+ /* Static methods for manipulate skins */
+ public static Object skinHashCode() {
+ FacesContext context = FacesContext.getCurrentInstance();
+ int hashCode = SkinFactory.getInstance().getSkin(context).hashCode(context);
+ byte[] bs = ByteBuffer.allocate(4).putInt(hashCode).array();
+
+ return bs;
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinFactoryImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinFactoryImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinFactoryImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,365 +19,393 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Map.Entry;
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.resource.util.URLToStreamHelper;
+import org.ajax4jsf.util.ELUtils;
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
-import javax.faces.FacesException;
+
import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.context.FacesContext;
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.resource.util.URLToStreamHelper;
-import org.ajax4jsf.util.ELUtils;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Properties;
+
/**
* Implementation of {@link SkinFactory} with building skins from properties
* files.
- *
+ *
* @author shura
- *
+ *
*/
public class SkinFactoryImpl extends SkinFactory {
+ private static final String A4J_BASE_SKIN_PARAMETER = "org.ajax4jsf.BASE_SKIN";
+ private static final String A4J_SKIN_PARAMETER = "org.ajax4jsf.SKIN";
+ // private static final String DEFAULT_CONFIGURATION_RESOURCE = "META-INF/skins/DEFAULT.configuration.properties";
- /**
- * Name of web application init parameter for current default
- * {@link javax.faces.render.RenderKit } interaction. by default -
- * org.exadel.chameleon.RENDERKIT_DEFINITION . TODO Possible Values
- */
- public static final String RENDER_KIT_PARAMETER = "org.ajax4jsf.RENDERKIT_DEFINITION";
+ /**
+ * Name of default skin . "DEFAULT" in this realisation.
+ */
+ private static final String DEFAULT_SKIN_NAME = "DEFAULT";
- /**
- * Resource Uri for properties file with default values of skin parameters.
- */
- private static final String DEFAULT_SKIN_PATH = "META-INF/skins/%s.skin.properties";
+ /**
+ * Resource Uri for properties file with default values of skin parameters.
+ */
+ private static final String DEFAULT_SKIN_PATH = "META-INF/skins/%s.skin.properties";
- private static final String USER_SKIN_PATH = "%s.skin.properties";
+ /**
+ * Name of web application init parameter for current default
+ * {@link javax.faces.render.RenderKit } interaction. by default -
+ * org.exadel.chameleon.RENDERKIT_DEFINITION . TODO Possible Values
+ */
+ public static final String RENDER_KIT_PARAMETER = "org.ajax4jsf.RENDERKIT_DEFINITION";
+ private static final String[] THEME_PATHS = {"META-INF/themes/%s.theme.properties", "%s.theme.properties"};
- // private static final String DEFAULT_CONFIGURATION_RESOURCE = "META-INF/skins/DEFAULT.configuration.properties";
- /**
- * Name of default skin . "DEFAULT" in this realisation.
- */
- private static final String DEFAULT_SKIN_NAME = "DEFAULT";
+// private static final String[] DEFAULT_SKIN_PATHS = { DEFAULT_SKIN_PATH };
+ private static final String USER_SKIN_PATH = "%s.skin.properties";
- /**
- * Path in jar to pre-defined vendor and custom user-defined skins
- * definitions. in this realisation "META-INF/skins/" for vendor , "" -
- * user-defined.
- */
- private static final String[] SKINS_PATHS = {
- DEFAULT_SKIN_PATH, USER_SKIN_PATH };
- private static final String[] THEME_PATHS = {
- "META-INF/themes/%s.theme.properties", "%s.theme.properties" };
-// private static final String[] DEFAULT_SKIN_PATHS = { DEFAULT_SKIN_PATH };
+ /**
+ * Path in jar to pre-defined vendor and custom user-defined skins
+ * definitions. in this realisation "META-INF/skins/" for vendor , "" -
+ * user-defined.
+ */
+ private static final String[] SKINS_PATHS = {DEFAULT_SKIN_PATH, USER_SKIN_PATH};
+ private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
+ private ValueExpression baseSkinBinding = null;
+ private String baseSkinName = null;
+ private ValueExpression skinBinding = null;
-// private static final String[] CONFIGURATIONS_PATHS = {
-// "META-INF/skins/%s.configuration.properties",
-// "%s.configuration.properties" };
-// private static final String[] DEFAULT_CONFIGURATION_PATHS = { "META-INF/skins/DEFAULT.configuration.properties" };
+// private Properties defaultSkinProperties = null;
+ private String skinName = null;
- private Map<String,Skin> skins = new HashMap<String,Skin>();
- private Map<String,Skin> baseSkins = new HashMap<String,Skin>();
- private Map<String,Properties> sourceProperties = new HashMap<String,Properties>();
- private Map<String,Theme> themes = new HashMap<String,Theme>();
+// private static final String[] CONFIGURATIONS_PATHS = {
+// "META-INF/skins/%s.configuration.properties",
+// "%s.configuration.properties" };
+// private static final String[] DEFAULT_CONFIGURATION_PATHS = { "META-INF/skins/DEFAULT.configuration.properties" };
+ private Map<String, Skin> skins = new HashMap<String, Skin>();
+ private Map<String, Skin> baseSkins = new HashMap<String, Skin>();
+ private Map<String, Properties> sourceProperties = new HashMap<String, Properties>();
+ private Map<String, Theme> themes = new HashMap<String, Theme>();
-// private Properties defaultSkinProperties = null;
- private String skinName = null;
- private ValueExpression skinBinding = null;
- private String baseSkinName = null;
- private ValueExpression baseSkinBinding = null;
- private static final Logger log = RichfacesLogger.APPLICATION.getLogger();
+ protected Skin getSkinByName(FacesContext facesContext, Object currentSkinOrName, boolean isBase) {
+ if (null == currentSkinOrName) {
+ throw new SkinNotFoundException(Messages.getMessage(Messages.NULL_SKIN_NAME_ERROR));
+ }
- private static final String A4J_BASE_SKIN_PARAMETER = "org.ajax4jsf.BASE_SKIN";
+ Skin currentSkin = null;
- private static final String A4J_SKIN_PARAMETER = "org.ajax4jsf.SKIN";
+ // user binding return skin instance.
+ if (currentSkinOrName instanceof Skin) {
+ currentSkin = (Skin) currentSkinOrName;
+ } else {
+ String currentSkinName = currentSkinOrName.toString();
+ Map<String, Skin> skinsMap = isBase ? baseSkins : skins;
- protected Skin getSkinByName(FacesContext facesContext, Object currentSkinOrName, boolean isBase) {
- if (null == currentSkinOrName) {
- throw new SkinNotFoundException(Messages
- .getMessage(Messages.NULL_SKIN_NAME_ERROR));
- }
- Skin currentSkin = null;
- // user binding return skin instance.
- if (currentSkinOrName instanceof Skin) {
- currentSkin = (Skin) currentSkinOrName;
- } else {
- String currentSkinName = currentSkinOrName.toString();
+ synchronized (skinsMap) {
+ currentSkin = skinsMap.get(currentSkinName);
- Map<String, Skin> skinsMap = (isBase ? baseSkins : skins);
- synchronized (skinsMap) {
- currentSkin = (Skin) skinsMap.get(currentSkinName);
- // LAZY creation for skins, since, in case of EL expressions
- // for skin name, we don't can know all names of existing skins.
- if (currentSkin == null) {
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(
- Messages.CREATE_SKIN_INFO, currentSkinName));
- }
- currentSkin = buildSkin(facesContext, currentSkinName,
- isBase);
- skinsMap.put(currentSkinName, currentSkin);
- }
- }
- }
- return currentSkin;
- }
+ // LAZY creation for skins, since, in case of EL expressions
+ // for skin name, we don't can know all names of existing skins.
+ if (currentSkin == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(Messages.getMessage(Messages.CREATE_SKIN_INFO, currentSkinName));
+ }
- public Skin getDefaultSkin(FacesContext context) {
- return getSkinByName(context, DEFAULT_SKIN_NAME, false);
- }
+ currentSkin = buildSkin(facesContext, currentSkinName, isBase);
+ skinsMap.put(currentSkinName, currentSkin);
+ }
+ }
+ }
- public Skin getSkin(FacesContext context) {
- // TODO - cache skin for current thread ? or for current Faces Lifecycle
- // Phase ?
- Object currentSkinOrName = getSkinOrName(context, false);
- return getSkinByName(context, currentSkinOrName, false);
- }
+ return currentSkin;
+ }
- public Skin getBaseSkin(FacesContext context) {
- Object currentSkinOrName = getSkinOrName(context, true);
- return getSkinByName(context, currentSkinOrName, true);
- }
+ public Skin getDefaultSkin(FacesContext context) {
+ return getSkinByName(context, DEFAULT_SKIN_NAME, false);
+ }
-// protected Properties getDefaultSkinProperties() {
-// if (defaultSkinProperties == null) {
-// defaultSkinProperties = loadProperties(DEFAULT_SKIN_NAME,DEFAULT_SKIN_PATHS);
-// }
-// return defaultSkinProperties;
-// }
+ public Skin getSkin(FacesContext context) {
- /**
- * Calculate name for current skin. For EL init parameter store value
- * binding for speed calculations.
- *
- * @param context
- * @param useBase
- * @return name of currens skin from init parameter ( "DEFAULT" if no
- * parameter ) or {@link Skin } as result of evaluation EL
- * expression.
- */
- protected Object getSkinOrName(FacesContext context, boolean useBase) {
- // Detect skin name
- ValueExpression binding;
- String skin;
+ // TODO - cache skin for current thread ? or for current Faces Lifecycle
+ // Phase ?
+ Object currentSkinOrName = getSkinOrName(context, false);
- synchronized (this) {
- if (useBase) {
- binding = baseSkinBinding;
- skin = baseSkinName;
- } else {
- binding = skinBinding;
- skin = skinName;
- }
+ return getSkinByName(context, currentSkinOrName, false);
+ }
- if (binding == null && skin == null) {
- String currentSkinName = context.getExternalContext()
- .getInitParameter(
- useBase ? BASE_SKIN_PARAMETER : SKIN_PARAMETER);
- if (null == currentSkinName) {
- // Check for a old ( deprecated ) parameter name.
- currentSkinName = context.getExternalContext()
- .getInitParameter(
- useBase ? A4J_BASE_SKIN_PARAMETER
- : A4J_SKIN_PARAMETER);
- if (null != currentSkinName) {
- log.warn("Init parameter for a skin name changed to "+ (useBase ? BASE_SKIN_PARAMETER
- : SKIN_PARAMETER));
- }
+ public Skin getBaseSkin(FacesContext context) {
+ Object currentSkinOrName = getSkinOrName(context, true);
- }
- if (currentSkinName == null) {
- // not set - usr default.
- return DEFAULT_SKIN_NAME;
- }
- if (ELUtils.isValueReference(currentSkinName)) {
- // For EL expression as skin name
- binding = context.getApplication().getExpressionFactory().
- createValueExpression(context.getELContext(),
- currentSkinName, Object.class);
- } else {
- skin = currentSkinName;
- }
+ return getSkinByName(context, currentSkinOrName, true);
+ }
- if (useBase) {
- baseSkinBinding = binding;
- baseSkinName = skin;
- } else {
- skinBinding = binding;
- skinName = skin;
- }
- }
+// protected Properties getDefaultSkinProperties() {
+// if (defaultSkinProperties == null) {
+// defaultSkinProperties = loadProperties(DEFAULT_SKIN_NAME,DEFAULT_SKIN_PATHS);
+// }
+// return defaultSkinProperties;
+// }
- // }
- }
- if (binding != null) {
- return binding.getValue(context.getELContext());
- } else {
- return skin;
- }
- }
+ /**
+ * Calculate name for current skin. For EL init parameter store value
+ * binding for speed calculations.
+ *
+ * @param context
+ * @param useBase
+ * @return name of currens skin from init parameter ( "DEFAULT" if no
+ * parameter ) or {@link Skin } as result of evaluation EL
+ * expression.
+ */
+ protected Object getSkinOrName(FacesContext context, boolean useBase) {
- private void processProperties(FacesContext context, Map<Object, Object> properties) {
- ELContext elContext = context.getELContext();
- // replace all EL-expressions by prepared ValueBinding ?
- ApplicationFactory factory = (ApplicationFactory) FactoryFinder
- .getFactory(FactoryFinder.APPLICATION_FACTORY);
- Application app = factory.getApplication();
-
- for (Entry<Object, Object> entry : properties.entrySet()) {
- Object propertyObject = entry.getValue();
- if (propertyObject instanceof String) {
- String property = (String) propertyObject;
- if (ELUtils.isValueReference(property)) {
- ExpressionFactory expressionFactory = app.getExpressionFactory();
- entry.setValue(expressionFactory.createValueExpression(elContext, property, Object.class));
- } else {
- entry.setValue(property);
- }
- }
- }
- }
-
- /**
- * Factory method for build skin from properties files. for given skin name,
- * search in classpath all resources with name 'name'.skin.properties and
- * append in content to default properties. First, get it from
- * META-INF/skins/ , next - from root package. for any place search order
- * determined by {@link java.lang.ClassLoader } realisation.
- * @param name
- * name for builded skin.
- * @param defaultProperties
- *
- * @return skin instance for current name
- * @throws SkinNotFoundException -
- * if no skin properies found for name.
- */
- protected Skin buildSkin(FacesContext context, String name, boolean isBase)
- throws SkinNotFoundException {
- Properties skinParams;
- synchronized (sourceProperties) {
- skinParams = sourceProperties.get(name);
- if (skinParams == null) {
- skinParams = loadProperties(name, SKINS_PATHS);
- processProperties(context, skinParams);
- // skinParams = Collections.unmodifiableMap(skinParams);
- sourceProperties.put(name, skinParams);
- }
- }
- BasicSkinImpl skinImpl;
- if (DEFAULT_SKIN_NAME.equals(name)) {
- skinImpl = new DefaultSkinImpl(skinParams);
- } else if (isBase) {
- skinImpl = new BaseSkinImpl(skinParams, this);
- } else {
- skinImpl = new SkinImpl(skinParams, this);
- }
+ // Detect skin name
+ ValueExpression binding;
+ String skin;
- return skinImpl;
- }
+ synchronized (this) {
+ if (useBase) {
+ binding = baseSkinBinding;
+ skin = baseSkinName;
+ } else {
+ binding = skinBinding;
+ skin = skinName;
+ }
- /**
- * @param name
- * @param defaultProperties
- * @return
- * @throws SkinNotFoundException
- * @throws FacesException
- */
- protected Properties loadProperties(String name, String[] paths) throws SkinNotFoundException, FacesException {
- ClassLoader loader = getClassLoader();
- // Get properties for concrete skin.
- Properties skinProperties = new Properties();
- int loadedPropertiesCount = 0;
- for (int i = 0; i < paths.length; i++) {
- String skinPropertiesLocation = paths[i].replaceAll("%s", name);
- if(loadProperties(loader, skinProperties, skinPropertiesLocation)){
- loadedPropertiesCount++;
- }
- }
- if (loadedPropertiesCount == 0) {
- throw new SkinNotFoundException(Messages.getMessage(
- Messages.SKIN_NOT_FOUND_ERROR, name));
- }
- return skinProperties;
- }
+ if ((binding == null) && (skin == null)) {
+ String currentSkinName = context.getExternalContext().getInitParameter(useBase
+ ? BASE_SKIN_PARAMETER : SKIN_PARAMETER);
- /**
- * @return
- */
- protected ClassLoader getClassLoader() {
- return Thread.currentThread().getContextClassLoader();
- }
+ if (null == currentSkinName) {
- /**
- * @param loader
- * @param properties
- * @param location
- */
- protected boolean loadProperties(ClassLoader loader, Properties properties,
- String location) {
- boolean loaded = false;
- try {
- Enumeration<URL> resources = loader
- .getResources(location);
- while (resources.hasMoreElements()) {
- URL url = (URL) resources.nextElement();
- InputStream propertyStream = null;
- try {
- propertyStream = URLToStreamHelper.urlToStream(url);
- properties.load(propertyStream);
- loaded=true;
- } catch (IOException e) {
- log.warn(Messages
- .getMessage(Messages.SKIN_PROPERTIES_IO_ERROR),
- e);
- continue;
- } finally {
- if (null != propertyStream) {
- propertyStream.close();
- }
- }
- }
- } catch (IOException e) {
- // Do nothing - we can only log error, and continue to load next
- // property.
- if (log.isInfoEnabled()) {
- log.info(Messages
- .getMessage(Messages.SKIN_PROPERTIES_IO_ERROR), e);
- }
- }
- return loaded;
- }
+ // Check for a old ( deprecated ) parameter name.
+ currentSkinName = context.getExternalContext().getInitParameter(useBase
+ ? A4J_BASE_SKIN_PARAMETER : A4J_SKIN_PARAMETER);
- @Override
- public Theme getTheme(FacesContext facesContext, String name) {
- Theme theme = themes.get(name);
- if(null == theme){
- Properties properties;
- try {
- properties = loadProperties(name, THEME_PATHS);
- } catch (SkinNotFoundException e) {
- throw new ThemeNotFoundException(Messages.getMessage(
- Messages.THEME_NOT_FOUND_ERROR, name), e.getCause());
- }
- processProperties(facesContext, properties);
- theme = new ThemeImpl(properties);
- themes.put(name, theme);
- }
- return theme;
- }
+ if (null != currentSkinName) {
+ LOG.warn("Init parameter for a skin name changed to "
+ + (useBase ? BASE_SKIN_PARAMETER : SKIN_PARAMETER));
+ }
+ }
+
+ if (currentSkinName == null) {
+
+ // not set - usr default.
+ return DEFAULT_SKIN_NAME;
+ }
+
+ if (ELUtils.isValueReference(currentSkinName)) {
+
+ // For EL expression as skin name
+ binding =
+ context.getApplication().getExpressionFactory().createValueExpression(context.getELContext(),
+ currentSkinName, Object.class);
+ } else {
+ skin = currentSkinName;
+ }
+
+ if (useBase) {
+ baseSkinBinding = binding;
+ baseSkinName = skin;
+ } else {
+ skinBinding = binding;
+ skinName = skin;
+ }
+ }
+
+ // }
+ }
+
+ if (binding != null) {
+ return binding.getValue(context.getELContext());
+ } else {
+ return skin;
+ }
+ }
+
+ private void processProperties(FacesContext context, Map<Object, Object> properties) {
+ ELContext elContext = context.getELContext();
+
+ // replace all EL-expressions by prepared ValueBinding ?
+ ApplicationFactory factory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
+ Application app = factory.getApplication();
+
+ for (Entry<Object, Object> entry : properties.entrySet()) {
+ Object propertyObject = entry.getValue();
+
+ if (propertyObject instanceof String) {
+ String property = (String) propertyObject;
+
+ if (ELUtils.isValueReference(property)) {
+ ExpressionFactory expressionFactory = app.getExpressionFactory();
+
+ entry.setValue(expressionFactory.createValueExpression(elContext, property, Object.class));
+ } else {
+ entry.setValue(property);
+ }
+ }
+ }
+ }
+
+ /**
+ * Factory method for build skin from properties files. for given skin name,
+ * search in classpath all resources with name 'name'.skin.properties and
+ * append in content to default properties. First, get it from
+ * META-INF/skins/ , next - from root package. for any place search order
+ * determined by {@link java.lang.ClassLoader } realisation.
+ * @param name
+ * name for builded skin.
+ * @param defaultProperties
+ *
+ * @return skin instance for current name
+ * @throws SkinNotFoundException -
+ * if no skin properies found for name.
+ */
+ protected Skin buildSkin(FacesContext context, String name, boolean isBase) throws SkinNotFoundException {
+ Properties skinParams;
+
+ synchronized (sourceProperties) {
+ skinParams = sourceProperties.get(name);
+
+ if (skinParams == null) {
+ skinParams = loadProperties(name, SKINS_PATHS);
+ processProperties(context, skinParams);
+
+ // skinParams = Collections.unmodifiableMap(skinParams);
+ sourceProperties.put(name, skinParams);
+ }
+ }
+
+ BasicSkinImpl skinImpl;
+
+ if (DEFAULT_SKIN_NAME.equals(name)) {
+ skinImpl = new DefaultSkinImpl(skinParams);
+ } else if (isBase) {
+ skinImpl = new BaseSkinImpl(skinParams, this);
+ } else {
+ skinImpl = new SkinImpl(skinParams, this);
+ }
+
+ return skinImpl;
+ }
+
+ /**
+ * @param name
+ * @param paths
+ *
+ * @return
+ *
+ * @throws SkinNotFoundException
+ */
+ protected Properties loadProperties(String name, String[] paths) throws SkinNotFoundException {
+ ClassLoader loader = getClassLoader();
+
+ // Get properties for concrete skin.
+ Properties skinProperties = new Properties();
+ int loadedPropertiesCount = 0;
+
+ for (int i = 0; i < paths.length; i++) {
+ String skinPropertiesLocation = paths[i].replaceAll("%s", name);
+
+ if (loadProperties(loader, skinProperties, skinPropertiesLocation)) {
+ loadedPropertiesCount++;
+ }
+ }
+
+ if (loadedPropertiesCount == 0) {
+ throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR, name));
+ }
+
+ return skinProperties;
+ }
+
+ /**
+ * @return
+ */
+ protected ClassLoader getClassLoader() {
+ return Thread.currentThread().getContextClassLoader();
+ }
+
+ /**
+ * @param loader
+ * @param properties
+ * @param location
+ */
+ protected boolean loadProperties(ClassLoader loader, Properties properties, String location) {
+ boolean loaded = false;
+
+ try {
+ Enumeration<URL> resources = loader.getResources(location);
+
+ while (resources.hasMoreElements()) {
+ URL url = (URL) resources.nextElement();
+ InputStream propertyStream = null;
+
+ try {
+ propertyStream = URLToStreamHelper.urlToStream(url);
+ properties.load(propertyStream);
+ loaded = true;
+ } catch (IOException e) {
+ LOG.warn(Messages.getMessage(Messages.SKIN_PROPERTIES_IO_ERROR), e);
+
+ continue;
+ } finally {
+ if (null != propertyStream) {
+ propertyStream.close();
+ }
+ }
+ }
+ } catch (IOException e) {
+
+ // Do nothing - we can only log error, and continue to load next
+ // property.
+ if (LOG.isInfoEnabled()) {
+ LOG.info(Messages.getMessage(Messages.SKIN_PROPERTIES_IO_ERROR), e);
+ }
+ }
+
+ return loaded;
+ }
+
+ @Override
+ public Theme getTheme(FacesContext facesContext, String name) {
+ Theme theme = themes.get(name);
+
+ if (null == theme) {
+ Properties properties;
+
+ try {
+ properties = loadProperties(name, THEME_PATHS);
+ } catch (SkinNotFoundException e) {
+ throw new ThemeNotFoundException(Messages.getMessage(Messages.THEME_NOT_FOUND_ERROR, name),
+ e.getCause());
+ }
+
+ processProperties(facesContext, properties);
+ theme = new ThemeImpl(properties);
+ themes.put(name, theme);
+ }
+
+ return theme;
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinPropertyResolver.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinPropertyResolver.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinPropertyResolver.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,17 +19,20 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
+import org.ajax4jsf.Messages;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
-import javax.faces.el.PropertyNotFoundException;
import javax.faces.el.PropertyResolver;
-import org.ajax4jsf.Messages;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
/**
* Resolve Skin propertyes.
* @author asmirnov(a)exadel.com (latest modification by $Author: alexsmirnov $)
@@ -37,116 +40,145 @@
*
*/
public class SkinPropertyResolver extends PropertyResolver {
-
- private static final Logger log = RichfacesLogger.APPLICATION.getLogger();
- private PropertyResolver parent = null;
+ private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
+ private PropertyResolver parent = null;
- /**
- * @param parent
- */
- public SkinPropertyResolver(PropertyResolver parent) {
- this.parent = parent;
- }
+ /**
+ * @param parent
+ */
+ public SkinPropertyResolver(PropertyResolver parent) {
+ this.parent = parent;
+ }
- /* (non-Javadoc)
- * @see javax.faces.el.PropertyResolver#getType(java.lang.Object, int)
- */
- public Class getType(Object base, int index) throws EvaluationException, PropertyNotFoundException {
- if (base instanceof Skin) {
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.ACESSING_SKIN_PROPERTY_AS_ARRAY_ERROR));
- }
- return null;
- }
- return parent.getType(base, index);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.PropertyResolver#getType(java.lang.Object, int)
+ */
+ @Override
+ public Class getType(Object base, int index) {
+ if (base instanceof Skin) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(Messages.getMessage(Messages.ACESSING_SKIN_PROPERTY_AS_ARRAY_ERROR));
+ }
- /* (non-Javadoc)
- * @see javax.faces.el.PropertyResolver#getType(java.lang.Object, java.lang.Object)
- */
- public Class getType(Object base, Object property) throws EvaluationException, PropertyNotFoundException {
- if (base instanceof Skin) {
- Skin skin = (Skin) base;
- if(property instanceof String){
- return skin.getParameter(FacesContext.getCurrentInstance(),(String) property).getClass();
- }
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.ACESSING_SKIN_PROPERTY_ERROR));
- }
- return null;
- }
- return parent.getType(base, property);
- }
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.faces.el.PropertyResolver#getValue(java.lang.Object, int)
- */
- public Object getValue(Object base, int index) throws EvaluationException, PropertyNotFoundException {
- if (base instanceof Skin) {
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.ACESSING_SKIN_PROPERTY_AS_ARRAY_ERROR));
- }
- return null;
- }
- return parent.getValue(base, index);
- }
+ return parent.getType(base, index);
+ }
- /* (non-Javadoc)
- * @see javax.faces.el.PropertyResolver#getValue(java.lang.Object, java.lang.Object)
- */
- public Object getValue(Object base, Object property) throws EvaluationException, PropertyNotFoundException {
- if (base instanceof Skin) {
- Skin skin = (Skin) base;
- if(property instanceof String){
- return skin.getParameter(FacesContext.getCurrentInstance(),(String) property);
- }
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.ACESSING_SKIN_PROPERTY_ERROR));
- }
- return null;
- }
- return parent.getValue(base, property);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.PropertyResolver#getType(java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public Class getType(Object base, Object property) {
+ if (base instanceof Skin) {
+ Skin skin = (Skin) base;
- /* (non-Javadoc)
- * @see javax.faces.el.PropertyResolver#isReadOnly(java.lang.Object, int)
- */
- public boolean isReadOnly(Object base, int arg1) throws EvaluationException, PropertyNotFoundException {
- if (base instanceof Skin) {
- return true;
- }
- return parent.isReadOnly(base, arg1);
- }
+ if (property instanceof String) {
+ return skin.getParameter(FacesContext.getCurrentInstance(), (String) property).getClass();
+ }
- /* (non-Javadoc)
- * @see javax.faces.el.PropertyResolver#isReadOnly(java.lang.Object, java.lang.Object)
- */
- public boolean isReadOnly(Object base, Object arg1) throws EvaluationException, PropertyNotFoundException {
- if (base instanceof Skin) {
- return true;
- }
- return parent.isReadOnly(base, arg1);
- }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(Messages.getMessage(Messages.ACESSING_SKIN_PROPERTY_ERROR));
+ }
- /* (non-Javadoc)
- * @see javax.faces.el.PropertyResolver#setValue(java.lang.Object, int, java.lang.Object)
- */
- public void setValue(Object base, int index, Object value) throws EvaluationException, PropertyNotFoundException {
- if (base instanceof Skin) {
- throw new EvaluationException(Messages.getMessage(Messages.SKIN_PROPERTIES_READ_ONLY_ERROR));
- }
- parent.setValue(base, index, value);
- }
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.faces.el.PropertyResolver#setValue(java.lang.Object, java.lang.Object, java.lang.Object)
- */
- public void setValue(Object base, Object property, Object value) throws EvaluationException, PropertyNotFoundException {
- if (base instanceof Skin) {
- throw new EvaluationException(Messages.getMessage(Messages.SKIN_PROPERTIES_READ_ONLY_ERROR));
- }
- parent.setValue(base, property, value);
- }
+ return parent.getType(base, property);
+ }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.PropertyResolver#getValue(java.lang.Object, int)
+ */
+ @Override
+ public Object getValue(Object base, int index) {
+ if (base instanceof Skin) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(Messages.getMessage(Messages.ACESSING_SKIN_PROPERTY_AS_ARRAY_ERROR));
+ }
+ return null;
+ }
+
+ return parent.getValue(base, index);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.PropertyResolver#getValue(java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public Object getValue(Object base, Object property) {
+ if (base instanceof Skin) {
+ Skin skin = (Skin) base;
+
+ if (property instanceof String) {
+ return skin.getParameter(FacesContext.getCurrentInstance(), (String) property);
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(Messages.getMessage(Messages.ACESSING_SKIN_PROPERTY_ERROR));
+ }
+
+ return null;
+ }
+
+ return parent.getValue(base, property);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.PropertyResolver#isReadOnly(java.lang.Object, int)
+ */
+ @Override
+ public boolean isReadOnly(Object base, int arg1) {
+ if (base instanceof Skin) {
+ return true;
+ }
+
+ return parent.isReadOnly(base, arg1);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.PropertyResolver#isReadOnly(java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public boolean isReadOnly(Object base, Object arg1) {
+ if (base instanceof Skin) {
+ return true;
+ }
+
+ return parent.isReadOnly(base, arg1);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.PropertyResolver#setValue(java.lang.Object, int, java.lang.Object)
+ */
+ @Override
+ public void setValue(Object base, int index, Object value) {
+ if (base instanceof Skin) {
+ throw new EvaluationException(Messages.getMessage(Messages.SKIN_PROPERTIES_READ_ONLY_ERROR));
+ }
+
+ parent.setValue(base, index, value);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.PropertyResolver#setValue(java.lang.Object, java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void setValue(Object base, Object property, Object value) {
+ if (base instanceof Skin) {
+ throw new EvaluationException(Messages.getMessage(Messages.SKIN_PROPERTIES_READ_ONLY_ERROR));
+ }
+
+ parent.setValue(base, property, value);
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinVariableResolver.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinVariableResolver.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/SkinVariableResolver.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,15 +19,16 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
+import org.richfaces.VersionBean;
+
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.el.VariableResolver;
-import org.richfaces.VersionBean;
-import org.richfaces.skin.SkinFactory;
-
/**
* Resolve current skin as EL Variable. e.g. #{chameleonSkin['color'] } #{chameleonSkin.color}
* must be evaluated as Skin.getProperty(context,"color");
@@ -36,36 +37,31 @@
*
*/
public class SkinVariableResolver extends VariableResolver {
+ public static final String CHAMELEON_VARIABLE_NAME = "vcp";
+ public static final String SKIN_VARIABLE_NAME = "vcpSkin";
+ private VariableResolver parent = null;
+ public SkinVariableResolver(VariableResolver parent) {
+ this.parent = parent;
+ }
- public static final String SKIN_VARIABLE_NAME = "vcpSkin";
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.el.VariableResolver#resolveVariable(javax.faces.context.FacesContext, java.lang.String)
+ */
+ public Object resolveVariable(FacesContext context, String name) throws EvaluationException {
- public static final String CHAMELEON_VARIABLE_NAME = "vcp";
+ // TODO: Why do we need this?
+ if (SKIN_VARIABLE_NAME.equals(name)) {
+ return SkinFactory.getInstance().getSkin(context);
+ } else if (CHAMELEON_VARIABLE_NAME.equals(name)) {
+ return new VersionBean();
+ }
- private VariableResolver parent = null;
-
- public SkinVariableResolver(VariableResolver parent){
- this.parent = parent;
- }
- /* (non-Javadoc)
- * @see javax.faces.el.VariableResolver#resolveVariable(javax.faces.context.FacesContext, java.lang.String)
- */
- public Object resolveVariable(FacesContext context, String name)
- throws EvaluationException {
-
- // TODO: Why do we need this?
- if(SKIN_VARIABLE_NAME.equals(name)){
- return SkinFactory.getInstance().getSkin(context);
- } else if(CHAMELEON_VARIABLE_NAME.equals(name)){
- return new VersionBean();
- }
- if (parent!=null) {
- Object ret = null;
- ret = parent.resolveVariable(context,name);
- return ret;
- } else {
- return null;
- }
- }
-
+ if (parent != null) {
+ return parent.resolveVariable(context, name);
+ } else {
+ return null;
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/ThemeImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/ThemeImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/ThemeImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,11 +1,13 @@
+
/**
- *
+ *
*/
package org.richfaces.skin;
import java.util.Properties;
import javax.el.ValueExpression;
+
import javax.faces.context.FacesContext;
/**
@@ -13,47 +15,52 @@
*
*/
public class ThemeImpl implements Theme {
-
- private final Properties themeProperties;
+ private final Properties themeProperties;
- /**
- * @param themeProperties
- */
- public ThemeImpl(Properties themeProperties) {
- this.themeProperties = themeProperties;
- }
+ /**
+ * @param themeProperties
+ */
+ public ThemeImpl(Properties themeProperties) {
+ this.themeProperties = themeProperties;
+ }
- /* (non-Javadoc)
- * @see org.richfaces.skin.Theme#getProperty(java.lang.String)
- */
- public Object getProperty(String name) {
- Object property = themeProperties.get(name);
- if (property instanceof ValueExpression) {
- ValueExpression ve = (ValueExpression) property;
- property = ve.getValue(FacesContext.getCurrentInstance().getELContext());
- }
- return property;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.Theme#getProperty(java.lang.String)
+ */
+ public Object getProperty(String name) {
+ Object property = themeProperties.get(name);
- /* (non-Javadoc)
- * @see org.richfaces.skin.Theme#getRendererType()
- */
- public String getRendererType() {
- return (String) getProperty("rendererType");
- }
+ if (property instanceof ValueExpression) {
+ ValueExpression ve = (ValueExpression) property;
- /* (non-Javadoc)
- * @see org.richfaces.skin.Theme#getScript()
- */
- public String getScript() {
- return (String) getProperty("script");
- }
+ property = ve.getValue(FacesContext.getCurrentInstance().getELContext());
+ }
- /* (non-Javadoc)
- * @see org.richfaces.skin.Theme#getStyle()
- */
- public String getStyle() {
- return (String) getProperty("styleSheet");
- }
+ return property;
+ }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.Theme#getRendererType()
+ */
+ public String getRendererType() {
+ return (String) getProperty("rendererType");
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.Theme#getScript()
+ */
+ public String getScript() {
+ return (String) getProperty("script");
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.skin.Theme#getStyle()
+ */
+ public String getStyle() {
+ return (String) getProperty("styleSheet");
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/skin/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/skin/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/skin/package-info.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,3 +1,4 @@
+
/**
* Implementation of RichFaces skinning
*/
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/util/CollectionsUtils.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/util/CollectionsUtils.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/util/CollectionsUtils.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,8 +1,7 @@
+
/*
- * $Id$
+* $Id$
*/
-
-
package org.richfaces.util;
import java.util.Arrays;
@@ -18,50 +17,52 @@
* @author asmirnov(a)exadel.com
*
*/
-public class CollectionsUtils {
+public final class CollectionsUtils {
+ private CollectionsUtils() {
- private CollectionsUtils() {
- // this class contains static methods only.
- }
-
- public static <T> T[] ar(T...ts){
- return ts;
- }
-
- public static <T> T[] ar(){
- return null;
- }
+ // this class contains static methods only.
+ }
- public static <T,V> ConstMap<T,V> map() {
- return new ConstMap<T, V>();
- }
-
- public <T> Set<T> set(T...ts) {
- LinkedHashSet<T> set = new LinkedHashSet<T>(ts.length);
- for (T t : ts) {
- set.add(t);
- }
- return Collections.unmodifiableSet(set);
- }
-
- public <T> List<T> list(T...ts) {
- return Collections.unmodifiableList(Arrays.asList(ts));
- }
-
- @SuppressWarnings("serial")
- public static class ConstMap<T,V> extends LinkedHashMap<T,V> {
-
- public ConstMap() {
- super(50, 1.0F);
- }
-
- public ConstMap<T, V> add(T key, V value) {
- put(key, value);
- return this;
- }
-
- public Map<T,V> fix() {
- return Collections.unmodifiableMap(this);
- }
- }
+ public static <T> T[] ar(T... ts) {
+ return ts;
+ }
+
+ public static <T> T[] ar() {
+ return null;
+ }
+
+ public static <T, V> ConstMap<T, V> map() {
+ return new ConstMap<T, V>();
+ }
+
+ public <T> Set<T> set(T... ts) {
+ LinkedHashSet<T> set = new LinkedHashSet<T>(ts.length);
+
+ for (T t : ts) {
+ set.add(t);
+ }
+
+ return Collections.unmodifiableSet(set);
+ }
+
+ public <T> List<T> list(T... ts) {
+ return Collections.unmodifiableList(Arrays.asList(ts));
+ }
+
+ @SuppressWarnings("serial")
+ public static class ConstMap<T, V> extends LinkedHashMap<T, V> {
+ public ConstMap() {
+ super(50, 1.0F);
+ }
+
+ public ConstMap<T, V> add(T key, V value) {
+ put(key, value);
+
+ return this;
+ }
+
+ public Map<T, V> fix() {
+ return Collections.unmodifiableMap(this);
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/util/ReferenceMap.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/util/ReferenceMap.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/util/ReferenceMap.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,11 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.util;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
+
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
@@ -32,144 +35,146 @@
/**
* Created 17.03.2008
+ *
* @author Nick Belaevski
* @since 3.2
*/
-
public class ReferenceMap<K, V> implements Map<K, V> {
+ private ReferenceQueue<V> queue = new ReferenceQueue<V>();
+ private Map<K, Reference<V>> map;
- private Map<K, Reference<V>> map;
+ public ReferenceMap() {
+ this(Collections.synchronizedMap(new HashMap<K, Reference<V>>()));
+ }
- private ReferenceQueue<V> queue = new ReferenceQueue<V>();
+ public ReferenceMap(Map<K, Reference<V>> map) {
+ super();
+ this.map = map;
+ }
- protected static class ReferenceMapSoftReference<K, V> extends SoftReference<V> {
- private K key;
+ private void purge() {
+ Reference<? extends V> reference = null;
- public K getKey() {
- return key;
- }
+ while ((reference = queue.poll()) != null) {
+ ReferenceMapSoftReference<?, ?> entry = (ReferenceMapSoftReference<?, ?>) reference;
- public ReferenceMapSoftReference(K key, V value, ReferenceQueue<? super V> queue) {
- super(value, queue);
- this.key = key;
- }
- }
-
- public ReferenceMap() {
- this(Collections.synchronizedMap(new HashMap<K, Reference<V>>()));
- }
-
- public ReferenceMap(Map<K, Reference<V>> map) {
- super();
-
- this.map = map;
- }
-
- private void purge() {
- Reference<? extends V> reference = null;
- while ((reference = queue.poll()) != null) {
- ReferenceMapSoftReference<?, ?> entry = (ReferenceMapSoftReference<?, ?>) reference;
- entry.clear();
- map.remove(entry.getKey());
- }
- }
+ entry.clear();
+ map.remove(entry.getKey());
+ }
+ }
- public void clear() {
- map.clear();
-
- Reference<? extends V> reference = null;
- while ((reference = queue.poll()) != null) {
- //release queue entries
- reference.clear();
- }
- }
+ public void clear() {
+ map.clear();
- public boolean containsKey(Object key) {
- purge();
+ Reference<? extends V> reference = null;
- return map.containsKey(key);
- }
+ while ((reference = queue.poll()) != null) {
- public boolean containsValue(Object value) {
- throw new UnsupportedOperationException();
- }
+ // release queue entries
+ reference.clear();
+ }
+ }
- public Set<java.util.Map.Entry<K, V>> entrySet() {
- throw new UnsupportedOperationException();
- }
+ public boolean containsKey(Object key) {
+ purge();
- public V get(Object key) {
- purge();
+ return map.containsKey(key);
+ }
- Reference<V> reference = map.get(key);
- if (reference != null) {
- return reference.get();
- }
+ public boolean containsValue(Object value) {
+ throw new UnsupportedOperationException();
+ }
- return null;
- }
+ public Set<java.util.Map.Entry<K, V>> entrySet() {
+ throw new UnsupportedOperationException();
+ }
- public boolean isEmpty() {
- purge();
+ public V get(Object key) {
+ purge();
- return map.isEmpty();
- }
+ Reference<V> reference = map.get(key);
- public Set<K> keySet() {
- purge();
+ if (reference != null) {
+ return reference.get();
+ }
- return map.keySet();
- }
+ return null;
+ }
- private V doPut(K key, V value) {
- Reference<V> reference = map.put(key, new ReferenceMapSoftReference<K, V>(key, value, queue));
+ public boolean isEmpty() {
+ purge();
- if (reference != null) {
- return reference.get();
- }
+ return map.isEmpty();
+ }
- return null;
- }
+ public Set<K> keySet() {
+ purge();
- public V put(K key, V value) {
- purge();
+ return map.keySet();
+ }
- V v = doPut(key, value);
-
- purge();
-
- return v;
- }
+ private V doPut(K key, V value) {
+ Reference<V> reference = map.put(key, new ReferenceMapSoftReference<K, V>(key, value, queue));
- public void putAll(Map<? extends K, ? extends V> t) {
- purge();
+ if (reference != null) {
+ return reference.get();
+ }
- for (Map.Entry<? extends K, ? extends V> entry: t.entrySet()) {
- doPut(entry.getKey(), entry.getValue());
- }
-
- purge();
- }
+ return null;
+ }
- public V remove(Object key) {
- purge();
+ public V put(K key, V value) {
+ purge();
- Reference<V> reference = map.remove(key);
- if (reference != null) {
- return reference.get();
- }
+ V v = doPut(key, value);
- return null;
- }
+ purge();
- public int size() {
- purge();
+ return v;
+ }
- return map.size();
- }
+ public void putAll(Map<? extends K, ? extends V> t) {
+ purge();
- public Collection<V> values() {
- throw new UnsupportedOperationException();
- }
-
-}
\ No newline at end of file
+ for (Map.Entry<? extends K, ? extends V> entry : t.entrySet()) {
+ doPut(entry.getKey(), entry.getValue());
+ }
+
+ purge();
+ }
+
+ public V remove(Object key) {
+ purge();
+
+ Reference<V> reference = map.remove(key);
+
+ if (reference != null) {
+ return reference.get();
+ }
+
+ return null;
+ }
+
+ public int size() {
+ purge();
+
+ return map.size();
+ }
+
+ public Collection<V> values() {
+ throw new UnsupportedOperationException();
+ }
+
+ protected static class ReferenceMapSoftReference<K, V> extends SoftReference<V> {
+ private K key;
+
+ public ReferenceMapSoftReference(K key, V value, ReferenceQueue<? super V> queue) {
+ super(value, queue);
+ this.key = key;
+ }
+
+ public K getKey() {
+ return key;
+ }
+ }
+}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/util/RequestStateManager.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/util/RequestStateManager.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/util/RequestStateManager.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.util;
import java.util.HashMap;
@@ -31,98 +33,98 @@
* @since 4.0
*/
public final class RequestStateManager {
+ private static final String CONTEXT_ATTRIBUTE_NAME = RequestStateManager.class.getName();
- private static final String CONTEXT_ATTRIBUTE_NAME = RequestStateManager.class.getName();
-
- private RequestStateManager() {}
+ private RequestStateManager() {}
- //TODO remove this stuff
- public static enum BooleanRequestStateVariable {
-
- LegacyResourceRequest("org.richfaces.LEGACY_RESOURCE_REQUEST"),
+ // TODO remove this stuff
+ public static enum BooleanRequestStateVariable {
+ LegacyResourceRequest("org.richfaces.LEGACY_RESOURCE_REQUEST"),
+ ResourceRequest("org.richfaces.RESOURCE_REQUEST");
- ResourceRequest("org.richfaces.RESOURCE_REQUEST");
-
- private String attributeName;
-
- private BooleanRequestStateVariable(String attributeName) {
- this.attributeName = attributeName;
- }
-
- public Boolean get(FacesContext context) {
- return (Boolean) RequestStateManager.get(context, this.attributeName);
- }
-
- public void set(FacesContext context, Boolean value) {
- RequestStateManager.set(context, this.attributeName, value);
- }
- }
-
-
- @SuppressWarnings("unchecked")
- private static Map<String, Object> getStateMap(FacesContext context, boolean create) {
- Map<Object, Object> attributesMap = context.getAttributes();
-
- Map<String, Object> result = (Map<String, Object>) attributesMap.get(CONTEXT_ATTRIBUTE_NAME);
- if (create && result == null) {
- result = new HashMap<String, Object>();
- attributesMap.put(CONTEXT_ATTRIBUTE_NAME, result);
- }
-
- return result;
- }
-
- public static boolean containsKey(FacesContext context, String key) {
- if (context == null) {
- throw new NullPointerException("context");
- }
+ private String attributeName;
- if (key == null) {
- throw new NullPointerException("key");
- }
-
- Map<String, Object> stateMap = getStateMap(context, false);
- if (stateMap != null) {
- return stateMap.containsKey(key);
- } else {
- return false;
- }
- }
-
- public static Object get(FacesContext context, String key) {
- if (context == null) {
- throw new NullPointerException("context");
- }
+ private BooleanRequestStateVariable(String attributeName) {
+ this.attributeName = attributeName;
+ }
- if (key == null) {
- throw new NullPointerException("key");
- }
-
- Map<String, Object> stateMap = getStateMap(context, false);
- if (stateMap != null) {
- return stateMap.get(key);
- }
+ public Boolean get(FacesContext context) {
+ return (Boolean) RequestStateManager.get(context, this.attributeName);
+ }
+ public void set(FacesContext context, Boolean value) {
+ RequestStateManager.set(context, this.attributeName, value);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map<String, Object> getStateMap(FacesContext context, boolean create) {
+ Map<Object, Object> attributesMap = context.getAttributes();
+ Map<String, Object> result = (Map<String, Object>) attributesMap.get(CONTEXT_ATTRIBUTE_NAME);
+
+ if (create && (result == null)) {
+ result = new HashMap<String, Object>();
+ attributesMap.put(CONTEXT_ATTRIBUTE_NAME, result);
+ }
+
+ return result;
+ }
+
+ public static boolean containsKey(FacesContext context, String key) {
+ if (context == null) {
+ throw new NullPointerException("context");
+ }
+
+ if (key == null) {
+ throw new NullPointerException("key");
+ }
+
+ Map<String, Object> stateMap = getStateMap(context, false);
+
+ if (stateMap != null) {
+ return stateMap.containsKey(key);
+ } else {
+ return false;
+ }
+ }
+
+ public static Object get(FacesContext context, String key) {
+ if (context == null) {
+ throw new NullPointerException("context");
+ }
+
+ if (key == null) {
+ throw new NullPointerException("key");
+ }
+
+ Map<String, Object> stateMap = getStateMap(context, false);
+
+ if (stateMap != null) {
+ return stateMap.get(key);
+ }
+
return null;
- }
-
- public static void set(FacesContext context, String key, Object value) {
- if (context == null) {
- throw new NullPointerException("context");
- }
+ }
- if (key == null) {
- throw new NullPointerException("key");
- }
-
- if (value != null) {
- Map<String, Object> stateMap = getStateMap(context, true);
- stateMap.put(key, value);
- } else {
- Map<String, Object> stateMap = getStateMap(context, false);
- if (stateMap != null) {
- stateMap.remove(key);
- }
- }
- }
+ public static void set(FacesContext context, String key, Object value) {
+ if (context == null) {
+ throw new NullPointerException("context");
+ }
+
+ if (key == null) {
+ throw new NullPointerException("key");
+ }
+
+ if (value != null) {
+ Map<String, Object> stateMap = getStateMap(context, true);
+
+ stateMap.put(key, value);
+ } else {
+ Map<String, Object> stateMap = getStateMap(context, false);
+
+ if (stateMap != null) {
+ stateMap.remove(key);
+ }
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/util/Util.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/util/Util.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/util/Util.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,8 +1,8 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
- *
+ *
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
- *
+ *
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
@@ -10,7 +10,7 @@
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
- *
+ *
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
@@ -19,9 +19,9 @@
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
- *
+ *
* Contributor(s):
- *
+ *
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
@@ -32,23 +32,35 @@
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
- *
+ *
* Portions Copyrighted 2009 Exadel, Inc.
- *
- * Exadel. Inc, elects to include this software in this distribution under the
+ *
+ * Exadel. Inc, elects to include this software in this distribution under the
* GPL Version 2 license.
*/
+
+
package org.richfaces.util;
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.util.base64.Codec;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
import java.io.*;
+
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
+
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
+
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
@@ -62,37 +74,41 @@
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.util.base64.Codec;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public final class Util {
+ private static final String DATA_BYTES_SEPARATOR = "/DATB/";
+ private static final String DATA_SEPARATOR = "/DATA/";
+ // index of capturing group denoting version
+ private static final int DATA_SEPARATOR_DATA_GROUP_INDEX = 2;
+
+ // index of capturing group denoting data type encoded
+ private static final int DATA_SEPARATOR_TYPE_GROUP_INDEX = 1;
private static final Logger RESOURCE_LOGGER = RichfacesLogger.RESOURCE.getLogger();
- private Util() {
- }
-
/* HTTP Date format required by the HTTP/1.1 RFC */
private static final String RFC1123_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss zzz";
+ // TODO codec have settings
+ private static final Codec CODEC = new Codec();
+ private static final String VERSION_SEPARATOR = "/VER";
+ private static final Pattern DATA_SEPARATOR_PATTERN = Pattern.compile("/DAT(A|B)/([^/]*)");
private static final SimpleDateFormat RFC1123_DATE_FORMATTER;
static {
SimpleDateFormat format = new SimpleDateFormat(RFC1123_DATE_PATTERN, Locale.US);
+
format.setTimeZone(TimeZone.getTimeZone("GMT"));
-
RFC1123_DATE_FORMATTER = format;
}
+ private Util() {}
+
public static String getMappingForRequest(FacesContext context) {
ExternalContext externalContext = context.getExternalContext();
-
String servletPath = externalContext.getRequestServletPath();
if (servletPath == null) {
@@ -104,11 +120,13 @@
}
String pathInfo = externalContext.getRequestPathInfo();
+
if (pathInfo != null) {
return servletPath;
}
int idx = servletPath.lastIndexOf('.');
+
if (idx < 0) {
return servletPath;
} else {
@@ -123,6 +141,7 @@
try {
result = (Date) ((Format) RFC1123_DATE_FORMATTER.clone()).parseObject(s);
} catch (ParseException e) {
+
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -139,32 +158,20 @@
}
}
- //TODO codec have settings
- private static final Codec CODEC = new Codec();
-
- private static final String DATA_SEPARATOR = "/DATA/";
- private static final String DATA_BYTES_SEPARATOR = "/DATB/";
- private static final String VERSION_SEPARATOR = "/VER";
-
- private static final Pattern DATA_SEPARATOR_PATTERN = Pattern
- .compile("/DAT(A|B)/([^/]*)");
-
- //index of capturing group denoting data type encoded
- private static final int DATA_SEPARATOR_TYPE_GROUP_INDEX = 1;
-
- //index of capturing group denoting version
- private static final int DATA_SEPARATOR_DATA_GROUP_INDEX = 2;
-
protected static 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);
compressor.end();
+
return CODEC.encode(zipsrc);
} catch (Exception e) {
throw new FacesException("Error encode resource data", e);
@@ -176,32 +183,38 @@
byte[] zipsrc = CODEC.decode(src);
Inflater decompressor = new Inflater();
byte[] uncompressed = new byte[zipsrc.length * 5];
+
decompressor.setInput(zipsrc);
+
int totalOut = decompressor.inflate(uncompressed);
byte[] out = new byte[totalOut];
+
System.arraycopy(uncompressed, 0, out, 0, totalOut);
decompressor.end();
+
return out;
} catch (Exception e) {
throw new FacesException("Error decode resource data", e);
}
}
- public static String encodeResourceData(String resourceName, Object storeData,
- String resourceVersion) {
+ public static String encodeResourceData(String resourceName, Object storeData, String resourceVersion) {
+ StringBuilder uri = new StringBuilder(); // ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
- StringBuilder uri = new StringBuilder();// ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
uri.append(resourceName);
+
// append serialized data as Base-64 encoded request string.
if (storeData != null) {
try {
byte[] objectData;
+
if (storeData instanceof byte[]) {
objectData = (byte[]) storeData;
uri.append(DATA_BYTES_SEPARATOR);
} else {
ByteArrayOutputStream dataSteram = new ByteArrayOutputStream(1024);
ObjectOutputStream objStream = new ObjectOutputStream(dataSteram);
+
objStream.writeObject(storeData);
objStream.flush();
objStream.close();
@@ -209,7 +222,9 @@
objectData = dataSteram.toByteArray();
uri.append(DATA_SEPARATOR);
}
+
byte[] dataArray = encrypt(objectData);
+
uri.append(new String(dataArray, "ISO-8859-1"));
// / byte[] objectData = dataSteram.toByteArray();
@@ -221,33 +236,37 @@
}
}
- if (resourceVersion != null && resourceVersion.length() != 0) {
+ if ((resourceVersion != null) && (resourceVersion.length() != 0)) {
uri.append(VERSION_SEPARATOR);
uri.append(resourceVersion);
}
-//boolean isGlobal = !resource.isSessionAware();
-// String resourceURL = getFacesResourceURL(context,
-// uri.toString(), false /*isGlobal*/);// context.getApplication().getViewHandler().getResourceURL(context,uri.toString());
- //if (!isGlobal) {
- // resourceURL = context.getExternalContext().encodeResourceURL(
- // resourceURL);
- //}
-// if (log.isDebugEnabled()) {
-// log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
-// resource.getKey(), resourceURL));
-// }
- return uri.toString();// context.getExternalContext().encodeResourceURL(resourceURL);
+// boolean isGlobal = !resource.isSessionAware();
+// String resourceURL = getFacesResourceURL(context,
+// uri.toString(), false /*isGlobal*/);// context.getApplication().getViewHandler()
+// .getResourceURL(context,uri.toString());
+ // if (!isGlobal) {
+ // resourceURL = context.getExternalContext().encodeResourceURL(
+ // resourceURL);
+ // }
+// if (log.isDebugEnabled()) {
+// log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
+// resource.getKey(), resourceURL));
+// }
+ return uri.toString(); // context.getExternalContext().encodeResourceURL(resourceURL);
}
public static String getResourceName(String resourceUri) {
String resourceName = resourceUri;
Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(resourceName);
+
if (matcher.find()) {
int data = matcher.start();
+
resourceName = resourceName.substring(0, data);
} else {
int idx = resourceName.indexOf(VERSION_SEPARATOR);
+
if (idx > 0) {
resourceName = resourceName.substring(0, idx);
}
@@ -258,6 +277,7 @@
public static String getResourceVersion(String resourceUri) {
int idx = resourceUri.indexOf(VERSION_SEPARATOR);
+
if (idx > 0) {
return resourceUri.substring(idx + VERSION_SEPARATOR.length());
}
@@ -268,31 +288,33 @@
public static Object getResourceData(String resourceUri) {
Object data = null;
Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(resourceUri);
+
if (!matcher.find()) {
return data;
}
if (RESOURCE_LOGGER.isDebugEnabled()) {
- RESOURCE_LOGGER.debug(Messages.getMessage(
- Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, resourceUri, null));
+ RESOURCE_LOGGER.debug(Messages.getMessage(Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, resourceUri, null));
}
String dataString = matcher.group(DATA_SEPARATOR_DATA_GROUP_INDEX);
byte[] objectArray = null;
+
try {
byte[] dataArray = dataString.getBytes("ISO-8859-1");
+
objectArray = decrypt(dataArray);
} catch (UnsupportedEncodingException e1) {
+
// default encoding always presented.
}
-
if ("B".equals(matcher.group(DATA_SEPARATOR_TYPE_GROUP_INDEX))) {
data = objectArray;
} else {
try {
- ObjectInputStream in = new ObjectInputStream(
- new ByteArrayInputStream(objectArray));
+ ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(objectArray));
+
data = in.readObject();
} catch (StreamCorruptedException e) {
RESOURCE_LOGGER.error(Messages.getMessage(Messages.STREAM_CORRUPTED_ERROR), e);
@@ -308,8 +330,8 @@
public static String encodeResourceURL(FacesContext context, String url) {
String mapping = Util.getMappingForRequest(context);
+ String resourcePath = url;
- String resourcePath = url;
if (mapping.startsWith("/")) {
if (mapping.length() != 1) {
resourcePath = mapping + url;
@@ -319,22 +341,24 @@
}
ViewHandler viewHandler = context.getApplication().getViewHandler();
+
return viewHandler.getResourceURL(context, resourcePath);
}
public static String decodeResourceURL(FacesContext context) {
ExternalContext externalContext = context.getExternalContext();
String resourceName = null;
+ String facesMapping = Util.getMappingForRequest(context);
- String facesMapping = Util.getMappingForRequest(context);
if (facesMapping != null) {
if (facesMapping.startsWith("/")) {
- //prefix mapping
+
+ // prefix mapping
resourceName = externalContext.getRequestPathInfo();
} else {
String requestServletPath = externalContext.getRequestServletPath();
- resourceName = requestServletPath.substring(0,
- requestServletPath.length() - facesMapping.length());
+
+ resourceName = requestServletPath.substring(0, requestServletPath.length() - facesMapping.length());
}
}
@@ -345,7 +369,7 @@
ReadableByteChannel inChannel = Channels.newChannel(is);
WritableByteChannel outChannel = Channels.newChannel(os);
- //TODO make this configurable
+ // TODO make this configurable
ByteBuffer buffer = ByteBuffer.allocate(8192);
int read;
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/util/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/util/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/util/package-info.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,3 +1,4 @@
+
/**
* Utility classes
*/
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/BaseCacheTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/BaseCacheTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/BaseCacheTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.cache;
import java.util.Date;
@@ -26,79 +28,72 @@
import org.richfaces.test.AbstractFacesTest;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public abstract class BaseCacheTest extends AbstractFacesTest {
+ private Cache cache;
+ private String cacheManagerFactoryClassName;
- private String cacheManagerFactoryClassName;
-
- private Cache cache;
-
- public BaseCacheTest(String cacheManagerFactoryClassName) {
- super();
- this.cacheManagerFactoryClassName = cacheManagerFactoryClassName;
- }
+ public BaseCacheTest(String cacheManagerFactoryClassName) {
+ super();
+ this.cacheManagerFactoryClassName = cacheManagerFactoryClassName;
+ }
- @Override
- protected void setupJsfInitParameters() {
- super.setupJsfInitParameters();
-
- this.facesServer.addInitParameter(CacheManager.CACHE_MANAGER_FACTORY_CLASS,
- cacheManagerFactoryClassName);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
+ @Override
+ protected void setupJsfInitParameters() {
+ super.setupJsfInitParameters();
+ this.facesServer.addInitParameter(CacheManager.CACHE_MANAGER_FACTORY_CLASS, cacheManagerFactoryClassName);
+ }
- setupFacesRequest();
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
- CacheManager cacheManager = CacheManager.getInstance();
- Map<?, ?> initParameterMap = facesContext.getExternalContext().getInitParameterMap();
- this.cache = cacheManager.getCacheFactory(initParameterMap).createCache(initParameterMap);
- this.cache.start();
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
+ CacheManager cacheManager = CacheManager.getInstance();
+ Map<?, ?> initParameterMap = facesContext.getExternalContext().getInitParameterMap();
- if (this.cache != null) {
- this.cache.stop();
- this.cache = null;
- }
- }
-
- public void testBasic() throws Exception {
- assertNull(cache.get("a"));
- cache.put("a", "value-a", null);
- assertEquals("value-a", cache.get("a"));
- }
-
- public void testExpiration() throws Exception {
- assertNull(cache.get("a"));
+ this.cache = cacheManager.getCacheFactory(initParameterMap).createCache(initParameterMap);
+ this.cache.start();
+ }
- long sleepTime = 0;
- long expirationTime = System.currentTimeMillis() + 3000;
-
- cache.put("a", "value-a", new Date(expirationTime));
- assertEquals("value-a", cache.get("a"));
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
- //interval to reach 1 second before expiration time
- sleepTime = expirationTime - 1000 - System.currentTimeMillis();
- assertTrue(sleepTime > 0);
- Thread.sleep(sleepTime);
+ if (this.cache != null) {
+ this.cache.stop();
+ this.cache = null;
+ }
+ }
- assertEquals("value-a", cache.get("a"));
+ public void testBasic() throws Exception {
+ assertNull(cache.get("a"));
+ cache.put("a", "value-a", null);
+ assertEquals("value-a", cache.get("a"));
+ }
- //interval to reach 1 second after expiration time
- sleepTime = expirationTime + 1000 - System.currentTimeMillis();
- assertTrue(sleepTime > 0);
+ public void testExpiration() throws Exception {
+ assertNull(cache.get("a"));
- Thread.sleep(sleepTime);
- assertNull(cache.get("a"));
- }
+ long sleepTime = 0;
+ long expirationTime = System.currentTimeMillis() + 3000;
+
+ cache.put("a", "value-a", new Date(expirationTime));
+ assertEquals("value-a", cache.get("a"));
+
+ // interval to reach 1 second before expiration time
+ sleepTime = expirationTime - 1000 - System.currentTimeMillis();
+ assertTrue(sleepTime > 0);
+ Thread.sleep(sleepTime);
+ assertEquals("value-a", cache.get("a"));
+
+ // interval to reach 1 second after expiration time
+ sleepTime = expirationTime + 1000 - System.currentTimeMillis();
+ assertTrue(sleepTime > 0);
+ Thread.sleep(sleepTime);
+ assertNull(cache.get("a"));
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/EhCacheTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/EhCacheTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/EhCacheTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,19 +19,16 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-package org.ajax4jsf.cache;
+package org.ajax4jsf.cache;
/**
* @author Nick Belaevski
* @since 4.0
*/
public class EhCacheTest extends BaseCacheTest {
-
- public EhCacheTest() {
- super(EhCacheCacheFactory.class.getName());
- }
-
-
+ public EhCacheTest() {
+ super(EhCacheCacheFactory.class.getName());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/JBossCacheTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/JBossCacheTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/JBossCacheTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,19 +19,16 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-package org.ajax4jsf.cache;
+package org.ajax4jsf.cache;
/**
* @author Nick Belaevski
* @since 4.0
*/
public class JBossCacheTest extends BaseCacheTest {
-
- public JBossCacheTest() {
- super(JBossCacheCacheFactory.class.getName());
- }
-
-
+ public JBossCacheTest() {
+ super(JBossCacheCacheFactory.class.getName());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.cache;
import java.util.Date;
@@ -28,186 +30,176 @@
import org.ajax4jsf.cache.lru.CacheMap;
import org.ajax4jsf.cache.lru.LRUMapCache;
import org.ajax4jsf.cache.lru.CacheEntry;
+
import org.junit.Assert;
import org.junit.Test;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class LRUMapCacheTest {
+ @Test
+ public void testBasic() throws Exception {
+ LRUMapCache cache = new LRUMapCache();
- @Test
- public void testBasic() throws Exception {
- LRUMapCache cache = new LRUMapCache();
- cache.start();
-
- Assert.assertNull(cache.get("key"));
- cache.put("key", "value", null);
- Assert.assertEquals("value", cache.get("key"));
+ cache.start();
+ Assert.assertNull(cache.get("key"));
+ cache.put("key", "value", null);
+ Assert.assertEquals("value", cache.get("key"));
+ cache.stop();
+ }
- cache.stop();
- }
-
- @Test
- public void testLRUEviction() throws Exception {
- LRUMapCache cache = new LRUMapCache(3);
- cache.start();
+ @Test
+ public void testLRUEviction() throws Exception {
+ LRUMapCache cache = new LRUMapCache(3);
- cache.put("key1", "value1", null);
- cache.put("key2", "value2", null);
- cache.put("key3", "value3", null);
-
- Assert.assertEquals("value1", cache.get("key1"));
- Assert.assertEquals("value2", cache.get("key2"));
- Assert.assertEquals("value3", cache.get("key3"));
-
- cache.get("key1");
- cache.get("key3");
+ cache.start();
+ cache.put("key1", "value1", null);
+ cache.put("key2", "value2", null);
+ cache.put("key3", "value3", null);
+ Assert.assertEquals("value1", cache.get("key1"));
+ Assert.assertEquals("value2", cache.get("key2"));
+ Assert.assertEquals("value3", cache.get("key3"));
+ cache.get("key1");
+ cache.get("key3");
+ cache.put("key4", "value4", null);
+ Assert.assertEquals("value1", cache.get("key1"));
+ Assert.assertNull(cache.get("key2"));
+ Assert.assertEquals("value3", cache.get("key3"));
+ Assert.assertEquals("value4", cache.get("key4"));
+ cache.stop();
+ }
- cache.put("key4", "value4", null);
+ @Test
+ public void testCacheMap() throws Exception {
+ CacheMap cacheMap = new CacheMap();
- Assert.assertEquals("value1", cache.get("key1"));
- Assert.assertNull(cache.get("key2"));
- Assert.assertEquals("value3", cache.get("key3"));
- Assert.assertEquals("value4", cache.get("key4"));
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
- cache.stop();
- }
+ CacheEntry cacheEntry = new CacheEntry("key", "value", new Date(System.currentTimeMillis() + 1000));
- @Test
- public void testCacheMap() throws Exception {
- CacheMap cacheMap = new CacheMap();
- Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
-
- CacheEntry cacheEntry = new CacheEntry("key", "value", new Date(System.currentTimeMillis() + 1000));
- cacheMap.put("key", cacheEntry);
-
- Assert.assertNotNull(cacheMap.get("key"));
- Assert.assertSame(cacheEntry, cacheMap.get("key"));
- Assert.assertFalse(cacheMap.getExpirationQueue().isEmpty());
-
- cacheMap.clear();
- Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
+ cacheMap.put("key", cacheEntry);
+ Assert.assertNotNull(cacheMap.get("key"));
+ Assert.assertSame(cacheEntry, cacheMap.get("key"));
+ Assert.assertFalse(cacheMap.getExpirationQueue().isEmpty());
+ cacheMap.clear();
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
+ cacheMap.put("key2", new CacheEntry("key2", "value2", new Date(System.currentTimeMillis() + 1000)));
+ Assert.assertNotNull(cacheMap.get("key2"));
+ cacheMap.remove("key2");
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
+ }
- cacheMap.put("key2", new CacheEntry("key2", "value2", new Date(System.currentTimeMillis() + 1000)));
- Assert.assertNotNull(cacheMap.get("key2"));
- cacheMap.remove("key2");
- Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
- }
+ @Test
+ public void testExpiration() throws Exception {
- @Test
- public void testExpiration() throws Exception {
- //this test uses Thread.sleep, so may fail if debugged
-
- LRUMapCache cache = new LRUMapCache();
- cache.start();
-
- long baseTime = System.currentTimeMillis();
- cache.put("key", "value", new Date(baseTime + 2000));
- cache.put("key2", "value2", new Date(baseTime + 3000));
- cache.put("key3", "value3", new Date(baseTime + 1000));
- cache.put("key4", "value4", new Date(baseTime + 1000));
-
- Assert.assertEquals("value", cache.get("key"));
- Assert.assertEquals("value2", cache.get("key2"));
- Assert.assertEquals("value3", cache.get("key3"));
- Assert.assertEquals("value4", cache.get("key4"));
+ // this test uses Thread.sleep, so may fail if debugged
+ LRUMapCache cache = new LRUMapCache();
- //prolong key4
- cache.put("key4", "new value", new Date(baseTime + 2000));
-
- Thread.sleep(1500);
+ cache.start();
- Assert.assertEquals("value", cache.get("key"));
- Assert.assertEquals("value2", cache.get("key2"));
- Assert.assertNull(cache.get("key3"));
- Assert.assertEquals("new value", cache.get("key4"));
-
- Thread.sleep(1000);
+ long baseTime = System.currentTimeMillis();
- Assert.assertNull(cache.get("key"));
- Assert.assertEquals("value2", cache.get("key2"));
- Assert.assertNull(cache.get("key3"));
- Assert.assertNull(cache.get("key4"));
+ cache.put("key", "value", new Date(baseTime + 2000));
+ cache.put("key2", "value2", new Date(baseTime + 3000));
+ cache.put("key3", "value3", new Date(baseTime + 1000));
+ cache.put("key4", "value4", new Date(baseTime + 1000));
+ Assert.assertEquals("value", cache.get("key"));
+ Assert.assertEquals("value2", cache.get("key2"));
+ Assert.assertEquals("value3", cache.get("key3"));
+ Assert.assertEquals("value4", cache.get("key4"));
- Thread.sleep(1000);
+ // prolong key4
+ cache.put("key4", "new value", new Date(baseTime + 2000));
+ Thread.sleep(1500);
+ Assert.assertEquals("value", cache.get("key"));
+ Assert.assertEquals("value2", cache.get("key2"));
+ Assert.assertNull(cache.get("key3"));
+ Assert.assertEquals("new value", cache.get("key4"));
+ Thread.sleep(1000);
+ Assert.assertNull(cache.get("key"));
+ Assert.assertEquals("value2", cache.get("key2"));
+ Assert.assertNull(cache.get("key3"));
+ Assert.assertNull(cache.get("key4"));
+ Thread.sleep(1000);
+ Assert.assertNull(cache.get("key"));
+ Assert.assertNull(cache.get("key2"));
+ Assert.assertNull(cache.get("key3"));
+ cache.stop();
+ }
- Assert.assertNull(cache.get("key"));
- Assert.assertNull(cache.get("key2"));
- Assert.assertNull(cache.get("key3"));
+ @Test
+ public void testThreads() throws Exception {
+ final AtomicBoolean failure = new AtomicBoolean();
+ final LRUMapCache cache = new LRUMapCache();
- cache.stop();
- }
-
- @Test
- public void testThreads() throws Exception {
- final AtomicBoolean failure = new AtomicBoolean();
-
- final LRUMapCache cache = new LRUMapCache();
- cache.start();
+ cache.start();
- Thread[] writerThreads = new Thread[10];
-
- for (int i = 0; i < writerThreads.length; i++) {
- writerThreads[i] = new Thread() {
- public void run() {
- final String key = UUID.randomUUID().toString();
- final String value = UUID.randomUUID().toString();
+ Thread[] writerThreads = new Thread[10];
- cache.put(key, value, null);
-
- Thread[] threads = new Thread[25];
- for (int j = 0; j < threads.length; j++) {
- threads[j] = new Thread() {
- @Override
- public void run() {
- int retries = 1000;
-
- for (int k = 0; k < retries; k++) {
- if (!value.equals(cache.get(key))) {
- failure.set(true);
- return ;
- }
- }
- }
- };
- }
+ for (int i = 0; i < writerThreads.length; i++) {
+ writerThreads[i] = new Thread() {
+ public void run() {
+ final String key = UUID.randomUUID().toString();
+ final String value = UUID.randomUUID().toString();
- for (Thread thread : threads) {
- thread.start();
- }
- int retries = 1000;
-
- for (int k = 0; k < retries; k++) {
- if (!value.equals(cache.get(key))) {
- failure.set(true);
- }
- }
+ cache.put(key, value, null);
- for (Thread thread : threads) {
- try {
- thread.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- failure.set(true);
- }
- }
- };
- };
- }
-
- for (Thread thread : writerThreads) {
- thread.start();
- }
-
- for (Thread thread : writerThreads) {
- thread.join();
- }
+ Thread[] threads = new Thread[25];
- Assert.assertFalse(failure.get());
-
- cache.stop();
- }
+ for (int j = 0; j < threads.length; j++) {
+ threads[j] = new Thread() {
+ @Override
+ public void run() {
+ int retries = 1000;
+
+ for (int k = 0; k < retries; k++) {
+ if (!value.equals(cache.get(key))) {
+ failure.set(true);
+
+ return;
+ }
+ }
+ }
+ };
+ }
+
+ for (Thread thread : threads) {
+ thread.start();
+ }
+
+ int retries = 1000;
+
+ for (int k = 0; k < retries; k++) {
+ if (!value.equals(cache.get(key))) {
+ failure.set(true);
+ }
+ }
+
+ for (Thread thread : threads) {
+ try {
+ thread.join();
+ } catch (InterruptedException e) {
+
+ // TODO Auto-generated catch block
+ failure.set(true);
+ }
+ }
+ }
+ ;
+ };
+ }
+
+ for (Thread thread : writerThreads) {
+ thread.start();
+ }
+
+ for (Thread thread : writerThreads) {
+ thread.join();
+ }
+
+ Assert.assertFalse(failure.get());
+ cache.stop();
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/OsCacheTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/OsCacheTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/OsCacheTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,19 +19,16 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-package org.ajax4jsf.cache;
+package org.ajax4jsf.cache;
/**
* @author Nick Belaevski
* @since 4.0
*/
public class OsCacheTest extends BaseCacheTest {
-
- public OsCacheTest() {
- super(OSCacheCacheFactory.class.getName());
- }
-
-
+ public OsCacheTest() {
+ super(OSCacheCacheFactory.class.getName());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/codec/CodecTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/codec/CodecTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/codec/CodecTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,63 +19,73 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.codec;
import org.ajax4jsf.util.base64.Codec;
+
import org.richfaces.test.AbstractThreadedTest;
public class CodecTest extends AbstractThreadedTest {
- Codec c;
+ Codec c;
- public void setUp() throws Exception {
- super.setUp();
- String message = "";
- try {
- c = new Codec("anbshsquycwuudyft");
- } catch (Exception e) {
- message = "Cannot create Codec instance " + e.getMessage();
- }
- assertNotNull(message, c);
- }
+ public void setUp() throws Exception {
+ super.setUp();
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ String message = "";
- public void testCodec() {
- CodecTestRunnable[] runnables = new CodecTestRunnable[100];
- for (int i = 0; i < runnables.length; i++) {
- runnables[i] = new CodecTestRunnable(c, generateRandomString(), i);
- }
- runTestCaseRunnables(runnables);
- }
-
- private String generateRandomString() {
- StringBuffer ss = new StringBuffer();
- for (int i = 0; i < 50000; i++) {
- char c = (char)(96 + Math.random() * 26);
- ss.append(c);
- }
- return ss.toString();
- }
-
- class CodecTestRunnable extends TestCaseRunnable {
- Codec c;
- String s;
- int id;
-
- public CodecTestRunnable(Codec c, String s, int id) {
- this.c = c;
- this.s = s;
- this.id = id;
- }
+ try {
+ c = new Codec("anbshsquycwuudyft");
+ } catch (Exception e) {
+ message = "Cannot create Codec instance " + e.getMessage();
+ }
- public void runTestCase() throws Throwable {
- String s1 = c.encode(s);
- String s2 = c.decode(s1);
- assertEquals("Failure in thread " + id, s2, s);
- }
-
- }
+ assertNotNull(message, c);
+ }
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testCodec() {
+ CodecTestRunnable[] runnables = new CodecTestRunnable[100];
+
+ for (int i = 0; i < runnables.length; i++) {
+ runnables[i] = new CodecTestRunnable(c, generateRandomString(), i);
+ }
+
+ runTestCaseRunnables(runnables);
+ }
+
+ private String generateRandomString() {
+ StringBuffer ss = new StringBuffer();
+
+ for (int i = 0; i < 50000; i++) {
+ char c = (char) (96 + Math.random() * 26);
+
+ ss.append(c);
+ }
+
+ return ss.toString();
+ }
+
+ class CodecTestRunnable extends TestCaseRunnable {
+ Codec c;
+ int id;
+ String s;
+
+ public CodecTestRunnable(Codec c, String s, int id) {
+ this.c = c;
+ this.s = s;
+ this.id = id;
+ }
+
+ public void runTestCase() throws Throwable {
+ String s1 = c.encode(s);
+ String s2 = c.decode(s1);
+
+ assertEquals("Failure in thread " + id, s2, s);
+ }
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/FacesConfigTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/FacesConfigTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/FacesConfigTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,15 +18,21 @@
* 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.config;
import java.io.IOException;
import java.io.InputStream;
+
import java.net.URL;
+
import java.util.Enumeration;
import java.util.Vector;
import javax.faces.webapp.FacesServlet;
+
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
@@ -40,144 +46,154 @@
*/
public class FacesConfigTest extends TestCase {
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parse(javax.portlet.PortletContext)}.
- */
- public void testParsePortletContext() {
- FacesConfig config = new FacesConfig();
- MockServletContext context = new MockServletContext(){
- @Override
- public InputStream getResourceAsStream(String path) {
- return this.getClass().getResourceAsStream(path);
- }
-
- @Override
- public String getInitParameter(String name) {
- if(FacesServlet.CONFIG_FILES_ATTR.equals(name)){
- return "/WEB-INF/a-faces-config.xml ,/WEB-INF/b-faces-config.xml";
- }
- return super.getInitParameter(name);
- }
- };
- config.parse(context);
- assertEquals(6, config.getExcludedAttributes().size());
- }
+ /**
+ * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parse(javax.portlet.PortletContext)}.
+ */
+ public void testParsePortletContext() {
+ FacesConfig config = new FacesConfig();
+ MockServletContext context = new MockServletContext() {
+ @Override
+ public InputStream getResourceAsStream(String path) {
+ return this.getClass().getResourceAsStream(path);
+ }
+ @Override
+ public String getInitParameter(String name) {
+ if (FacesServlet.CONFIG_FILES_ATTR.equals(name)) {
+ return "/WEB-INF/a-faces-config.xml ,/WEB-INF/b-faces-config.xml";
+ }
- /**
- * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parseDefault(javax.portlet.PortletContext)}.
- */
- public void testParseDefault() throws Exception {
- FacesConfig config = new FacesConfig();
- MockServletContext context = new MockServletContext(){
- @Override
- public InputStream getResourceAsStream(String path) {
- return this.getClass().getResourceAsStream(path);
- }
-
- @Override
- public String getInitParameter(String name) {
- if(FacesServlet.CONFIG_FILES_ATTR.equals(name)){
- return "/WEB-INF/a-faces-config.xml ,/WEB-INF/b-faces-config.xml";
- }
- return super.getInitParameter(name);
- }
- };
- config.parseDefault(context);
- assertEquals(2, config.getExcludedAttributes().size());
- }
+ return super.getInitParameter(name);
+ }
+ };
- /**
- * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parseOptional(javax.portlet.PortletContext)}.
- */
- public void testParseOptional() throws Exception {
- FacesConfig config = new FacesConfig();
- MockServletContext context = new MockServletContext(){
- @Override
- public InputStream getResourceAsStream(String path) {
- return this.getClass().getResourceAsStream(path);
- }
-
- @Override
- public String getInitParameter(String name) {
- if(FacesServlet.CONFIG_FILES_ATTR.equals(name)){
- return "/WEB-INF/a-faces-config.xml ,/WEB-INF/b-faces-config.xml";
- }
- return super.getInitParameter(name);
- }
- };
- config.parseOptional(context);
- assertEquals(4, config.getExcludedAttributes().size());
- }
+ config.parse(context);
+ assertEquals(6, config.getExcludedAttributes().size());
+ }
- /**
- * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parseClasspath(javax.portlet.PortletContext)}.
- * @throws Exception
- */
- public void testParseClasspath() throws Exception {
- ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- try{
- ClassLoader classLoader = this.getClass().getClassLoader();
- ClassLoader classLoaderWrapper = new ClassLoader(classLoader){
-
- @Override
- public Enumeration<URL> getResources(String name)
- throws IOException {
- if("META-INF/faces-config.xml".equals(name)){
- Vector<URL> configs = new Vector<URL>(2);
- configs.add(getResource("WEB-INF/a-faces-config.xml"));
- configs.add(getResource("WEB-INF/b-faces-config.xml"));
- return configs.elements();
- }
- return super.getResources(name);
- }
- };
- Thread.currentThread().setContextClassLoader(classLoaderWrapper);
- FacesConfig config = new FacesConfig();
- MockServletContext context = new MockServletContext();
- config.parseClasspath(context);
- assertEquals(4, config.getExcludedAttributes().size());
- } finally {
- Thread.currentThread().setContextClassLoader(contextClassLoader);
- }
-
- }
+ /**
+ * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parseDefault(javax.portlet.PortletContext)}.
+ */
+ public void testParseDefault() throws Exception {
+ FacesConfig config = new FacesConfig();
+ MockServletContext context = new MockServletContext() {
+ @Override
+ public InputStream getResourceAsStream(String path) {
+ return this.getClass().getResourceAsStream(path);
+ }
+ @Override
+ public String getInitParameter(String name) {
+ if (FacesServlet.CONFIG_FILES_ATTR.equals(name)) {
+ return "/WEB-INF/a-faces-config.xml ,/WEB-INF/b-faces-config.xml";
+ }
- /**
- * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parse(java.io.InputStream)}.
- * @throws ParsingException
- */
- public void testParseInputStream() throws Exception {
- InputStream facesConfigResource = this.getClass().getResourceAsStream("/WEB-INF/faces-config.xml");
- FacesConfig config = new FacesConfig();
- config.parse(facesConfigResource);
- assertEquals(2, config.getExcludedAttributes().size());
- assertTrue(config.getExcludedAttributes().contains("foo.bar"));
- assertTrue(config.getExcludedAttributes().contains("foo.baz.*"));
- }
+ return super.getInitParameter(name);
+ }
+ };
- /**
- * Test method for {@link org.jboss.portletbridge.util.FacesConfig#getParser()}.
- * @throws SAXException
- * @throws ParserConfigurationException
- */
- public void testGetParser() throws Exception {
- FacesConfig config = new FacesConfig();
- SAXParser parser = config.getParser();
- assertNotSame(parser, config.getParser());
- }
+ config.parseDefault(context);
+ assertEquals(2, config.getExcludedAttributes().size());
+ }
+ /**
+ * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parseOptional(javax.portlet.PortletContext)}.
+ */
+ public void testParseOptional() throws Exception {
+ FacesConfig config = new FacesConfig();
+ MockServletContext context = new MockServletContext() {
+ @Override
+ public InputStream getResourceAsStream(String path) {
+ return this.getClass().getResourceAsStream(path);
+ }
+ @Override
+ public String getInitParameter(String name) {
+ if (FacesServlet.CONFIG_FILES_ATTR.equals(name)) {
+ return "/WEB-INF/a-faces-config.xml ,/WEB-INF/b-faces-config.xml";
+ }
+
+ return super.getInitParameter(name);
+ }
+ };
+
+ config.parseOptional(context);
+ assertEquals(4, config.getExcludedAttributes().size());
+ }
+
+ /**
+ * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parseClasspath(javax.portlet.PortletContext)}.
+ * @throws Exception
+ */
+ public void testParseClasspath() throws Exception {
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+
+ try {
+ ClassLoader classLoader = this.getClass().getClassLoader();
+ ClassLoader classLoaderWrapper = new ClassLoader(classLoader) {
+ @Override
+ public Enumeration<URL> getResources(String name) throws IOException {
+ if ("META-INF/faces-config.xml".equals(name)) {
+ Vector<URL> configs = new Vector<URL>(2);
+
+ configs.add(getResource("WEB-INF/a-faces-config.xml"));
+ configs.add(getResource("WEB-INF/b-faces-config.xml"));
+
+ return configs.elements();
+ }
+
+ return super.getResources(name);
+ }
+ };
+
+ Thread.currentThread().setContextClassLoader(classLoaderWrapper);
+
+ FacesConfig config = new FacesConfig();
+ MockServletContext context = new MockServletContext();
+
+ config.parseClasspath(context);
+ assertEquals(4, config.getExcludedAttributes().size());
+ } finally {
+ Thread.currentThread().setContextClassLoader(contextClassLoader);
+ }
+ }
+
+ /**
+ * Test method for {@link org.jboss.portletbridge.util.FacesConfig#parse(java.io.InputStream)}.
+ * @throws ParsingException
+ */
+ public void testParseInputStream() throws Exception {
+ InputStream facesConfigResource = this.getClass().getResourceAsStream("/WEB-INF/faces-config.xml");
+ FacesConfig config = new FacesConfig();
+
+ config.parse(facesConfigResource);
+ assertEquals(2, config.getExcludedAttributes().size());
+ assertTrue(config.getExcludedAttributes().contains("foo.bar"));
+ assertTrue(config.getExcludedAttributes().contains("foo.baz.*"));
+ }
+
+ /**
+ * Test method for {@link org.jboss.portletbridge.util.FacesConfig#getParser()}.
+ * @throws SAXException
+ * @throws ParserConfigurationException
+ */
+ public void testGetParser() throws Exception {
+ FacesConfig config = new FacesConfig();
+ SAXParser parser = config.getParser();
+
+ assertNotSame(parser, config.getParser());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/FrameworkConfigurationTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/FrameworkConfigurationTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/FrameworkConfigurationTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -6,108 +6,107 @@
import javax.faces.context.ExternalContext;
import org.ajax4jsf.config.FrameworkConfiguration.InitParam;
+
import org.richfaces.test.AbstractFacesTest;
/**
* @author Anton Belevich
*
*/
-public class FrameworkConfigurationTest extends AbstractFacesTest{
-
- private MockInitializationBean mockBean;
-
- private FrameworkConfiguration configuration;
+public class FrameworkConfigurationTest extends AbstractFacesTest {
+ private FrameworkConfiguration configuration;
+ Map<String, String> localInitParams;
+ private MockInitializationBean mockBean;
+ Map<String, String> refenceInitParams;
- Map <String, String> localInitParams;
-
- Map <String, String> refenceInitParams;
-
-
- public class MockInitializationBean {
-
- private String styleStrategy = "ALL";
- private boolean encryptResourceData = true;
-
-
- public boolean getEncryptResourceData() {
- return encryptResourceData;
- }
-
- public void setEncryptResourceData(boolean encryptResourceData) {
- this.encryptResourceData = encryptResourceData;
- }
-
- public String getStyleStrategy() {
- return styleStrategy;
- }
-
- public void setStyleStrategy(String styleStrategy) {
- this.styleStrategy = styleStrategy;
- }
-
- }
-
- public void testBooleanOption() {
- boolean actual = configuration.isOptionEnabled(InitParam.COMPRESS_SCRIPT);
- boolean expected = Boolean.parseBoolean(localInitParams.get(InitParam.COMPRESS_SCRIPT.name()));
- assertEquals(expected, actual);
- }
-
- public void testBooleanOptionValueReference() {
- boolean actual = configuration.isOptionEnabled(InitParam.ENCRYPT_RESOURCE_DATA);
- boolean expected = mockBean.getEncryptResourceData();
- assertEquals(expected, actual);
- }
-
- public void testNumberOption (){
- int actual = configuration.getOptionNumber(InitParam.DEFAULT_EXPIRE);
- int expected = Integer.parseInt(localInitParams.get(InitParam.DEFAULT_EXPIRE.name()));
- assertEquals(expected, actual);
- }
-
- public void testStringOption() {
- String actual = configuration.getOption(InitParam.SKIN);
- String expected = (String)localInitParams.get(InitParam.SKIN.name());
- assertEquals(expected, actual);
- }
-
- public void testStringOptionValueReference() {
- String actual = configuration.getOptionValue(InitParam.LoadStyleStrategy);
- String expected = mockBean.getStyleStrategy();
- assertEquals(expected, actual);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- mockBean = new MockInitializationBean();
- setupFacesRequest();
- ExternalContext externalContext = facesContext.getExternalContext();
- configuration = FrameworkConfiguration.getInstance(externalContext);
- facesContext.getExternalContext().getRequestMap().put("mockBean", mockBean);
- }
+ public void testBooleanOption() {
+ boolean actual = configuration.isOptionEnabled(InitParam.COMPRESS_SCRIPT);
+ boolean expected = Boolean.parseBoolean(localInitParams.get(InitParam.COMPRESS_SCRIPT.name()));
- @Override
- protected void setupJsfInitParameters() {
- super.setupJsfInitParameters();
- localInitParams = new HashMap<String, String>();
-
- localInitParams.put(InitParam.SKIN.name(), "blueSky");
- localInitParams.put(InitParam.COMPRESS_SCRIPT.name(), "false");
- localInitParams.put(InitParam.DEFAULT_EXPIRE.name(), "8500");
-
- facesServer.addInitParameter(FrameworkConfiguration.InitParam.SKIN.getQualifiedName(), "blueSky");
- facesServer.addInitParameter(FrameworkConfiguration.InitParam.LoadScriptStrategy.getQualifiedName(), "ALL");
- facesServer.addInitParameter(FrameworkConfiguration.InitParam.COMPRESS_SCRIPT.getQualifiedName(), "false");
- facesServer.addInitParameter(FrameworkConfiguration.InitParam.DEFAULT_EXPIRE.getQualifiedName(), "8500");
- facesServer.addInitParameter(FrameworkConfiguration.InitParam.ENCRYPT_RESOURCE_DATA.getQualifiedName(), "#{mockBean.encryptResourceData}");
- facesServer.addInitParameter(FrameworkConfiguration.InitParam.LoadStyleStrategy.getQualifiedName(), "#{mockBean.styleStrategy}");
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- mockBean = null;
- }
-
+ assertEquals(expected, actual);
+ }
+
+ public void testBooleanOptionValueReference() {
+ boolean actual = configuration.isOptionEnabled(InitParam.ENCRYPT_RESOURCE_DATA);
+ boolean expected = mockBean.getEncryptResourceData();
+
+ assertEquals(expected, actual);
+ }
+
+ public void testNumberOption() {
+ int actual = configuration.getOptionNumber(InitParam.DEFAULT_EXPIRE);
+ int expected = Integer.parseInt(localInitParams.get(InitParam.DEFAULT_EXPIRE.name()));
+
+ assertEquals(expected, actual);
+ }
+
+ public void testStringOption() {
+ String actual = configuration.getOption(InitParam.SKIN);
+ String expected = (String) localInitParams.get(InitParam.SKIN.name());
+
+ assertEquals(expected, actual);
+ }
+
+ public void testStringOptionValueReference() {
+ String actual = configuration.getOptionValue(InitParam.LoadStyleStrategy);
+ String expected = mockBean.getStyleStrategy();
+
+ assertEquals(expected, actual);
+ }
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ mockBean = new MockInitializationBean();
+ setupFacesRequest();
+
+ ExternalContext externalContext = facesContext.getExternalContext();
+
+ configuration = FrameworkConfiguration.getInstance(externalContext);
+ facesContext.getExternalContext().getRequestMap().put("mockBean", mockBean);
+ }
+
+ @Override
+ protected void setupJsfInitParameters() {
+ super.setupJsfInitParameters();
+ localInitParams = new HashMap<String, String>();
+ localInitParams.put(InitParam.SKIN.name(), "blueSky");
+ localInitParams.put(InitParam.COMPRESS_SCRIPT.name(), "false");
+ localInitParams.put(InitParam.DEFAULT_EXPIRE.name(), "8500");
+ facesServer.addInitParameter(FrameworkConfiguration.InitParam.SKIN.getQualifiedName(), "blueSky");
+ facesServer.addInitParameter(FrameworkConfiguration.InitParam.LoadScriptStrategy.getQualifiedName(), "ALL");
+ facesServer.addInitParameter(FrameworkConfiguration.InitParam.COMPRESS_SCRIPT.getQualifiedName(), "false");
+ facesServer.addInitParameter(FrameworkConfiguration.InitParam.DEFAULT_EXPIRE.getQualifiedName(), "8500");
+ facesServer.addInitParameter(FrameworkConfiguration.InitParam.ENCRYPT_RESOURCE_DATA.getQualifiedName(),
+ "#{mockBean.encryptResourceData}");
+ facesServer.addInitParameter(FrameworkConfiguration.InitParam.LoadStyleStrategy.getQualifiedName(),
+ "#{mockBean.styleStrategy}");
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ mockBean = null;
+ }
+
+ public class MockInitializationBean {
+ private String styleStrategy = "ALL";
+ private boolean encryptResourceData = true;
+
+ public boolean getEncryptResourceData() {
+ return encryptResourceData;
+ }
+
+ public void setEncryptResourceData(boolean encryptResourceData) {
+ this.encryptResourceData = encryptResourceData;
+ }
+
+ public String getStyleStrategy() {
+ return styleStrategy;
+ }
+
+ public void setStyleStrategy(String styleStrategy) {
+ this.styleStrategy = styleStrategy;
+ }
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/MockServletContext.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/MockServletContext.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/MockServletContext.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,11 +18,16 @@
* 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.config;
import java.io.InputStream;
+
import java.net.MalformedURLException;
import java.net.URL;
+
import java.util.Enumeration;
import java.util.Set;
@@ -37,203 +42,246 @@
*/
public class MockServletContext implements ServletContext {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getAttribute(java.lang.String)
- */
- public Object getAttribute(String name) {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getAttribute(java.lang.String)
+ */
+ public Object getAttribute(String name) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getAttributeNames()
- */
- public Enumeration getAttributeNames() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getContext(java.lang.String)
- */
- public ServletContext getContext(String uripath) {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getAttributeNames()
+ */
+ public Enumeration getAttributeNames() {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getContextPath()
- */
- public String getContextPath() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getInitParameter(java.lang.String)
- */
- public String getInitParameter(String name) {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getContext(java.lang.String)
+ */
+ public ServletContext getContext(String uripath) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getInitParameterNames()
- */
- public Enumeration getInitParameterNames() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getMajorVersion()
- */
- public int getMajorVersion() {
- // TODO Auto-generated method stub
- return 0;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getContextPath()
+ */
+ public String getContextPath() {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getMimeType(java.lang.String)
- */
- public String getMimeType(String file) {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getMinorVersion()
- */
- public int getMinorVersion() {
- // TODO Auto-generated method stub
- return 0;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getInitParameter(java.lang.String)
+ */
+ public String getInitParameter(String name) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getNamedDispatcher(java.lang.String)
- */
- public RequestDispatcher getNamedDispatcher(String name) {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getRealPath(java.lang.String)
- */
- public String getRealPath(String path) {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getInitParameterNames()
+ */
+ public Enumeration getInitParameterNames() {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getRequestDispatcher(java.lang.String)
- */
- public RequestDispatcher getRequestDispatcher(String path) {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getResource(java.lang.String)
- */
- public URL getResource(String path) throws MalformedURLException {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getMajorVersion()
+ */
+ public int getMajorVersion() {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getResourceAsStream(java.lang.String)
- */
- public InputStream getResourceAsStream(String path) {
- return getClass().getResourceAsStream(path);
- }
+ // TODO Auto-generated method stub
+ return 0;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String)
- */
- public Set getResourcePaths(String path) {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getMimeType(java.lang.String)
+ */
+ public String getMimeType(String file) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServerInfo()
- */
- public String getServerInfo() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServlet(java.lang.String)
- */
- public Servlet getServlet(String name) throws ServletException {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getMinorVersion()
+ */
+ public int getMinorVersion() {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServletContextName()
- */
- public String getServletContextName() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return 0;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServletNames()
- */
- public Enumeration getServletNames() {
- // TODO Auto-generated method stub
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getNamedDispatcher(java.lang.String)
+ */
+ public RequestDispatcher getNamedDispatcher(String name) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#getServlets()
- */
- public Enumeration getServlets() {
- // TODO Auto-generated method stub
- return null;
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#log(java.lang.String)
- */
- public void log(String msg) {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getRealPath(java.lang.String)
+ */
+ public String getRealPath(String path) {
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#log(java.lang.Exception, java.lang.String)
- */
- public void log(Exception exception, String msg) {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getRequestDispatcher(java.lang.String)
+ */
+ public RequestDispatcher getRequestDispatcher(String path) {
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#log(java.lang.String, java.lang.Throwable)
- */
- public void log(String message, Throwable throwable) {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getResource(java.lang.String)
+ */
+ public URL getResource(String path) throws MalformedURLException {
- }
+ // TODO Auto-generated method stub
+ return null;
+ }
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#removeAttribute(java.lang.String)
- */
- public void removeAttribute(String name) {
- // TODO Auto-generated method stub
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getResourceAsStream(java.lang.String)
+ */
+ public InputStream getResourceAsStream(String path) {
+ return getClass().getResourceAsStream(path);
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String)
+ */
+ public Set getResourcePaths(String path) {
- /* (non-Javadoc)
- * @see javax.servlet.ServletContext#setAttribute(java.lang.String, java.lang.Object)
- */
- public void setAttribute(String name, Object object) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
+ return null;
+ }
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServerInfo()
+ */
+ public String getServerInfo() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServlet(java.lang.String)
+ */
+ public Servlet getServlet(String name) throws ServletException {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServletContextName()
+ */
+ public String getServletContextName() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServletNames()
+ */
+ public Enumeration getServletNames() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#getServlets()
+ */
+ public Enumeration getServlets() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#log(java.lang.String)
+ */
+ public void log(String msg) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#log(java.lang.Exception, java.lang.String)
+ */
+ public void log(Exception exception, String msg) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#log(java.lang.String, java.lang.Throwable)
+ */
+ public void log(String message, Throwable throwable) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#removeAttribute(java.lang.String)
+ */
+ public void removeAttribute(String name) {
+
+ // TODO Auto-generated method stub
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.servlet.ServletContext#setAttribute(java.lang.String, java.lang.Object)
+ */
+ public void setAttribute(String name, Object object) {
+
+ // TODO Auto-generated method stub
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/MockXmlReader.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/MockXmlReader.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/MockXmlReader.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,6 +18,9 @@
* 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.config;
import java.io.IOException;
@@ -33,80 +36,47 @@
import org.xml.sax.XMLReader;
final class MockXmlReader implements XMLReader {
-
- ContentHandler contentHandler;
-
- public ContentHandler getContentHandler() {
- return contentHandler;
- }
+ ContentHandler contentHandler;
- public DTDHandler getDTDHandler() {
+ public ContentHandler getContentHandler() {
+ return contentHandler;
+ }
- return null;
- }
+ public DTDHandler getDTDHandler() {
+ return null;
+ }
- public EntityResolver getEntityResolver() {
+ public EntityResolver getEntityResolver() {
+ return null;
+ }
- return null;
- }
+ public ErrorHandler getErrorHandler() {
+ return null;
+ }
- public ErrorHandler getErrorHandler() {
+ public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
+ return false;
+ }
- return null;
- }
+ public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
+ return null;
+ }
- public boolean getFeature(String name)
- throws SAXNotRecognizedException, SAXNotSupportedException {
+ public void parse(InputSource input) throws IOException, SAXException {}
- return false;
- }
+ public void parse(String systemId) throws IOException, SAXException {}
- public Object getProperty(String name)
- throws SAXNotRecognizedException, SAXNotSupportedException {
+ public void setContentHandler(ContentHandler handler) {
+ contentHandler = handler;
+ }
- return null;
- }
+ public void setDTDHandler(DTDHandler handler) {}
- public void parse(InputSource input) throws IOException,
- SAXException {
+ public void setEntityResolver(EntityResolver resolver) {}
-
- }
+ public void setErrorHandler(ErrorHandler handler) {}
- public void parse(String systemId) throws IOException, SAXException {
+ public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {}
-
- }
-
- public void setContentHandler(ContentHandler handler) {
- contentHandler = handler;
-
- }
-
- public void setDTDHandler(DTDHandler handler) {
-
-
- }
-
- public void setEntityResolver(EntityResolver resolver) {
-
-
- }
-
- public void setErrorHandler(ErrorHandler handler) {
-
-
- }
-
- public void setFeature(String name, boolean value)
- throws SAXNotRecognizedException, SAXNotSupportedException {
-
-
- }
-
- public void setProperty(String name, Object value)
- throws SAXNotRecognizedException, SAXNotSupportedException {
-
-
- }
-}
\ No newline at end of file
+ public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {}
+}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/StateHandlerTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/StateHandlerTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/StateHandlerTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,9 +18,11 @@
* 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.config;
-
import junit.framework.TestCase;
import org.xml.sax.Attributes;
@@ -34,56 +36,55 @@
*
*/
public class StateHandlerTest extends TestCase {
-
- private static final String PREFIX = "foo:";
- private static final String BAR = "bar";
- private static final String NS = "http://foo.com/";
+ private static final String BAR = "bar";
+ private static final String NS = "http://foo.com/";
+ private static final String PREFIX = "foo:";
+ private XMLReader reader;
- private XMLReader reader;
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ reader = new MockXmlReader();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- reader = new MockXmlReader();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testReturnBack() throws Exception {
- ContentHandler parentHandler = new DefaultHandler() {
- @Override
- public void startElement(String uri, String localName, String name,
- Attributes attributes) throws SAXException {
- throw new SAXException();
- }
- @Override
- public void endElement(String uri, String localName, String name)
- throws SAXException {
- throw new SAXException();
- }
- };
- StateHandler handler = new StateHandler(parentHandler){
- @Override
- protected XMLReader getReader() {
- return reader;
- }
- };
- reader.setContentHandler(handler);
- handler.startElement(NS, BAR, PREFIX+BAR, null);
- handler.startElement(NS, BAR, PREFIX+BAR, null);
- handler.endElement(NS, BAR, PREFIX+BAR);
- assertSame(handler, reader.getContentHandler());
- handler.endElement(NS, BAR, PREFIX+BAR);
- assertSame(handler, reader.getContentHandler());
- handler.endElement(NS, BAR, PREFIX+BAR);
- assertSame(parentHandler, reader.getContentHandler());
- }
+ public void testReturnBack() throws Exception {
+ ContentHandler parentHandler = new DefaultHandler() {
+ @Override
+ public void startElement(String uri, String localName, String name, Attributes attributes)
+ throws SAXException {
+ throw new SAXException();
+ }
+ @Override
+ public void endElement(String uri, String localName, String name) throws SAXException {
+ throw new SAXException();
+ }
+ };
+ StateHandler handler = new StateHandler(parentHandler) {
+ @Override
+ protected XMLReader getReader() {
+ return reader;
+ }
+ };
+ reader.setContentHandler(handler);
+ handler.startElement(NS, BAR, PREFIX + BAR, null);
+ handler.startElement(NS, BAR, PREFIX + BAR, null);
+ handler.endElement(NS, BAR, PREFIX + BAR);
+ assertSame(handler, reader.getContentHandler());
+ handler.endElement(NS, BAR, PREFIX + BAR);
+ assertSame(handler, reader.getContentHandler());
+ handler.endElement(NS, BAR, PREFIX + BAR);
+ assertSame(parentHandler, reader.getContentHandler());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/WebXMLTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/WebXMLTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/WebXMLTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,9 +18,13 @@
* 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.config;
import java.io.InputStream;
+
import java.util.List;
import junit.framework.TestCase;
@@ -31,34 +35,38 @@
*/
public class WebXMLTest extends TestCase {
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.WebXMLParser.portletbridge.util.WebXML#init(java.io.InputStream, String)}.
- */
- public void testParse() throws Exception {
- WebXMLParser webXml = new WebXMLParser();
- InputStream inputStream = this.getClass().getResourceAsStream("/WEB-INF/web.xml");
- webXml.init(inputStream, "foo");
- inputStream.close();
- List<String> facesServletMappings = webXml.getFacesServletMappings();
- assertEquals(2, facesServletMappings.size());
- assertEquals("*.jsf", webXml.getFacesServletMappings().get(1));
- assertEquals("/faces/*", webXml.getFacesServletMappings().get(0));
- assertEquals(".jsf", webXml.getFacesServletSuffix());
- assertEquals("/faces", webXml.getFacesServletPrefix());
- }
+ /**
+ * Test method for {@link org.WebXMLParser.portletbridge.util.WebXML#init(java.io.InputStream, String)}.
+ */
+ public void testParse() throws Exception {
+ WebXMLParser webXml = new WebXMLParser();
+ InputStream inputStream = this.getClass().getResourceAsStream("/WEB-INF/web.xml");
+ webXml.init(inputStream, "foo");
+ inputStream.close();
+
+ List<String> facesServletMappings = webXml.getFacesServletMappings();
+
+ assertEquals(2, facesServletMappings.size());
+ assertEquals("*.jsf", webXml.getFacesServletMappings().get(1));
+ assertEquals("/faces/*", webXml.getFacesServletMappings().get(0));
+ assertEquals(".jsf", webXml.getFacesServletSuffix());
+ assertEquals("/faces", webXml.getFacesServletPrefix());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/WebappHandlerTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/WebappHandlerTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/config/WebappHandlerTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,6 +18,9 @@
* 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.config;
import java.util.List;
@@ -25,6 +28,7 @@
import junit.framework.TestCase;
import org.ajax4jsf.config.WebappHandler.ServletMappingHandler;
+
import org.xml.sax.ContentHandler;
/**
@@ -32,71 +36,82 @@
*
*/
public class WebappHandlerTest extends TestCase {
+ private static final char[] FACES_SERVLET = "Faces Servlet".toCharArray();
+ private static final char[] FACES_SERVLET_CLASS = "javax.faces.webapp.FacesServlet".toCharArray();
+ private static final String SERVLET = "servlet";
+ private static final String SERVLET_CLASS = "servlet-class";
+ private static final String SERVLET_MAPPING = "servlet-mapping";
+ private static final String SERVLET_NAME = "servlet-name";
+ private static final String WEBAPP = "web-app";
+ private MockXmlReader reader;
- private static final char[] FACES_SERVLET = "Faces Servlet".toCharArray();
- private static final char[] FACES_SERVLET_CLASS = "javax.faces.webapp.FacesServlet".toCharArray();
- private static final String SERVLET = "servlet";
- private static final String WEBAPP = "web-app";
- private static final String SERVLET_NAME = "servlet-name";
- private static final String SERVLET_CLASS = "servlet-class";
- private static final String SERVLET_MAPPING = "servlet-mapping";
- private MockXmlReader reader;
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ reader = new MockXmlReader();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- reader = new MockXmlReader();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testServletElement() throws Exception {
- WebappHandler handler = new WebappHandler(reader);
- reader.setContentHandler(handler);
- handler.startElement(null, WEBAPP, WEBAPP, null);
- assertEquals(handler, reader.getContentHandler());
- handler.startElement(null, SERVLET, SERVLET, null);
- ContentHandler servletHandler = reader.getContentHandler();
- assertSame(WebappHandler.ServletHandler.class, reader.getContentHandler().getClass());
- servletHandler.startElement(null, SERVLET_NAME, SERVLET_NAME, null);
- assertSame(StringContentHandler.class, reader.getContentHandler().getClass());
- ContentHandler servletNameHandler = reader.getContentHandler();
- servletNameHandler.characters(FACES_SERVLET, 0, FACES_SERVLET.length);
- servletNameHandler.endElement(null, SERVLET_NAME, SERVLET_NAME);
- assertSame(servletHandler, reader.getContentHandler());
- servletHandler.startElement(null, SERVLET_CLASS, SERVLET_CLASS, null);
- assertSame(StringContentHandler.class, reader.getContentHandler().getClass());
- ContentHandler servletClassHandler = reader.getContentHandler();
- servletClassHandler.characters(FACES_SERVLET_CLASS, 0, FACES_SERVLET_CLASS.length);
- servletClassHandler.endElement(null, SERVLET_CLASS, SERVLET_CLASS);
- assertSame(servletHandler, reader.getContentHandler());
- servletHandler.endElement(null, SERVLET, SERVLET);
- assertEquals(handler, reader.getContentHandler());
- handler.endElement(null, WEBAPP, WEBAPP);
- handler.endDocument();
- List<ServletBean> servlets = handler.getServlets();
- assertEquals(1, servlets.size());
- assertEquals(0, servlets.indexOf(new ServletBean("Faces Servlet",null)));
- }
-
- public void testMappingElement() throws Exception {
- WebappHandler handler = new WebappHandler(reader);
- reader.setContentHandler(handler);
- handler.startElement(null, WEBAPP, WEBAPP, null);
- assertEquals(handler, reader.getContentHandler());
- handler.startElement(null, SERVLET_MAPPING, SERVLET_MAPPING, null);
- ContentHandler servletHandler = reader.getContentHandler();
- assertSame(ServletMappingHandler.class, reader.getContentHandler().getClass());
- servletHandler.startElement(null, SERVLET_NAME, SERVLET_NAME, null);
- assertSame(StringContentHandler.class, reader.getContentHandler().getClass());
-
- }
+ public void testServletElement() throws Exception {
+ WebappHandler handler = new WebappHandler(reader);
+ reader.setContentHandler(handler);
+ handler.startElement(null, WEBAPP, WEBAPP, null);
+ assertEquals(handler, reader.getContentHandler());
+ handler.startElement(null, SERVLET, SERVLET, null);
+
+ ContentHandler servletHandler = reader.getContentHandler();
+
+ assertSame(WebappHandler.ServletHandler.class, reader.getContentHandler().getClass());
+ servletHandler.startElement(null, SERVLET_NAME, SERVLET_NAME, null);
+ assertSame(StringContentHandler.class, reader.getContentHandler().getClass());
+
+ ContentHandler servletNameHandler = reader.getContentHandler();
+
+ servletNameHandler.characters(FACES_SERVLET, 0, FACES_SERVLET.length);
+ servletNameHandler.endElement(null, SERVLET_NAME, SERVLET_NAME);
+ assertSame(servletHandler, reader.getContentHandler());
+ servletHandler.startElement(null, SERVLET_CLASS, SERVLET_CLASS, null);
+ assertSame(StringContentHandler.class, reader.getContentHandler().getClass());
+
+ ContentHandler servletClassHandler = reader.getContentHandler();
+
+ servletClassHandler.characters(FACES_SERVLET_CLASS, 0, FACES_SERVLET_CLASS.length);
+ servletClassHandler.endElement(null, SERVLET_CLASS, SERVLET_CLASS);
+ assertSame(servletHandler, reader.getContentHandler());
+ servletHandler.endElement(null, SERVLET, SERVLET);
+ assertEquals(handler, reader.getContentHandler());
+ handler.endElement(null, WEBAPP, WEBAPP);
+ handler.endDocument();
+
+ List<ServletBean> servlets = handler.getServlets();
+
+ assertEquals(1, servlets.size());
+ assertEquals(0, servlets.indexOf(new ServletBean("Faces Servlet", null)));
+ }
+
+ public void testMappingElement() throws Exception {
+ WebappHandler handler = new WebappHandler(reader);
+
+ reader.setContentHandler(handler);
+ handler.startElement(null, WEBAPP, WEBAPP, null);
+ assertEquals(handler, reader.getContentHandler());
+ handler.startElement(null, SERVLET_MAPPING, SERVLET_MAPPING, null);
+
+ ContentHandler servletHandler = reader.getContentHandler();
+
+ assertSame(ServletMappingHandler.class, reader.getContentHandler().getClass());
+ servletHandler.startElement(null, SERVLET_NAME, SERVLET_NAME, null);
+ assertSame(StringContentHandler.class, reader.getContentHandler().getClass());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/context/InitParametersTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/context/InitParametersTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/context/InitParametersTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.ajax4jsf.context;
@@ -12,104 +13,123 @@
*
*/
public class InitParametersTest extends AbstractFacesTest {
+ private static final int INT_PARAM = 367;
+ private static final String NO = "no";
+ private static final String ORG_AJAX4JSF_FALSE = "org.ajax4jsf.FALSE";
+ private static final String ORG_AJAX4JSF_INT = "org.ajax4jsf.INT";
+ private static final String ORG_AJAX4JSF_STRING = "org.ajax4jsf.STRING";
+ private static final String ORG_AJAX4JSF_TRUE = "org.ajax4jsf.TRUE";
+ private static final String STRING_PARAM = "init";
+ private static final String TRUE = "true";
- private static final String STRING_PARAM = "init";
- private static final int INT_PARAM = 367;
- private static final String NO = "no";
- private static final String TRUE = "true";
- private static final String ORG_AJAX4JSF_STRING = "org.ajax4jsf.STRING";
- private static final String ORG_AJAX4JSF_INT = "org.ajax4jsf.INT";
- private static final String ORG_AJAX4JSF_FALSE = "org.ajax4jsf.FALSE";
- private static final String ORG_AJAX4JSF_TRUE = "org.ajax4jsf.TRUE";
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
+ @Override
+ protected void setupJsfInitParameters() {
+ super.setupJsfInitParameters();
+ facesServer.addInitParameter(ORG_AJAX4JSF_TRUE, TRUE);
+ facesServer.addInitParameter(ORG_AJAX4JSF_FALSE, NO);
+ facesServer.addInitParameter(ORG_AJAX4JSF_INT, String.valueOf(INT_PARAM));
+ facesServer.addInitParameter(ORG_AJAX4JSF_STRING, STRING_PARAM);
+ }
- @Override
- protected void setupJsfInitParameters() {
- super.setupJsfInitParameters();
-
- facesServer.addInitParameter(ORG_AJAX4JSF_TRUE, TRUE);
- facesServer.addInitParameter(ORG_AJAX4JSF_FALSE, NO);
- facesServer.addInitParameter(ORG_AJAX4JSF_INT, String.valueOf(INT_PARAM));
- facesServer.addInitParameter(ORG_AJAX4JSF_STRING, STRING_PARAM);
- }
-
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.ajax4jsf.context.ContextInitParameters#getInteger(javax.faces.context.FacesContext, java.lang.String[], int)}.
- */
- public void testGetInteger() {
- String[] params = {"foo.bar",ORG_AJAX4JSF_INT};
- int value = ContextInitParameters.getInteger(facesContext, params, 12);
- assertEquals(INT_PARAM, value);
- String[] params2 = {"foo.bar"};
- value = ContextInitParameters.getInteger(facesContext, params2, 12);
- assertEquals(12, value);
- String[] params3 = {"foo.bar",ORG_AJAX4JSF_STRING};
- try {
- value = ContextInitParameters.getInteger(facesContext, params3, 12);
- } catch (FacesException e) {
- return;
- }
- assertFalse("No exception on invalid parameter",true);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.context.ContextInitParameters#getInteger(javax.faces.context.FacesContext, java.lang.String[], int)}.
+ */
+ public void testGetInteger() {
+ String[] params = {"foo.bar", ORG_AJAX4JSF_INT};
+ int value = ContextInitParameters.getInteger(facesContext, params, 12);
- /**
- * Test method for {@link org.ajax4jsf.context.ContextInitParameters#getString(javax.faces.context.FacesContext, java.lang.String[], java.lang.String)}.
- */
- public void testGetString() {
- String[] params = {"foo.bar",ORG_AJAX4JSF_STRING};
- String value = ContextInitParameters.getString(facesContext, params, "foo");
- assertEquals(STRING_PARAM, value);
- String[] params2 = {"foo.bar"};
- value = ContextInitParameters.getString(facesContext, params2, "foo");
- assertEquals("foo", value);
- }
+ assertEquals(INT_PARAM, value);
- /**
- * Test method for {@link org.ajax4jsf.context.ContextInitParameters#getBoolean(javax.faces.context.FacesContext, java.lang.String[], boolean)}.
- */
- public void testGetBoolean() {
- String[] params = {"foo.bar",ORG_AJAX4JSF_TRUE};
- boolean value = ContextInitParameters.getBoolean(facesContext, params, false);
- assertTrue(value);
- String[] params2 = {"foo.bar"};
- value = ContextInitParameters.getBoolean(facesContext, params2, true);
- assertTrue(value);
- String[] params3 = {"foo.bar",ORG_AJAX4JSF_FALSE};
- value = ContextInitParameters.getBoolean(facesContext, params3, true);
- assertFalse(value);
- String[] params4 = {"foo.bar",ORG_AJAX4JSF_STRING};
- try {
- value = ContextInitParameters.getBoolean(facesContext, params4, false);
- } catch (FacesException e) {
- return;
- }
- assertFalse("No exception on invalid parameter",true);
- }
+ String[] params2 = {"foo.bar"};
- /**
- * Test method for {@link org.ajax4jsf.context.ContextInitParameters#getInitParameter(javax.faces.context.FacesContext, java.lang.String[])}.
- */
- public void testGetInitParameter() {
- String[] params = {"foo.bar",ORG_AJAX4JSF_STRING};
- String value = ContextInitParameters.getInitParameter(facesContext, params);
- assertEquals(STRING_PARAM, value);
- String[] params2 = {"foo.bar"};
- value = ContextInitParameters.getInitParameter(facesContext, params2);
- assertNull(value);
- }
+ value = ContextInitParameters.getInteger(facesContext, params2, 12);
+ assertEquals(12, value);
+ String[] params3 = {"foo.bar", ORG_AJAX4JSF_STRING};
+
+ try {
+ value = ContextInitParameters.getInteger(facesContext, params3, 12);
+ } catch (FacesException e) {
+ return;
+ }
+
+ assertFalse("No exception on invalid parameter", true);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.context.ContextInitParameters#getString(javax.faces.context.FacesContext, java.lang.String[], java.lang.String)}.
+ */
+ public void testGetString() {
+ String[] params = {"foo.bar", ORG_AJAX4JSF_STRING};
+ String value = ContextInitParameters.getString(facesContext, params, "foo");
+
+ assertEquals(STRING_PARAM, value);
+
+ String[] params2 = {"foo.bar"};
+
+ value = ContextInitParameters.getString(facesContext, params2, "foo");
+ assertEquals("foo", value);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.context.ContextInitParameters#getBoolean(javax.faces.context.FacesContext, java.lang.String[], boolean)}.
+ */
+ public void testGetBoolean() {
+ String[] params = {"foo.bar", ORG_AJAX4JSF_TRUE};
+ boolean value = ContextInitParameters.getBoolean(facesContext, params, false);
+
+ assertTrue(value);
+
+ String[] params2 = {"foo.bar"};
+
+ value = ContextInitParameters.getBoolean(facesContext, params2, true);
+ assertTrue(value);
+
+ String[] params3 = {"foo.bar", ORG_AJAX4JSF_FALSE};
+
+ value = ContextInitParameters.getBoolean(facesContext, params3, true);
+ assertFalse(value);
+
+ String[] params4 = {"foo.bar", ORG_AJAX4JSF_STRING};
+
+ try {
+ value = ContextInitParameters.getBoolean(facesContext, params4, false);
+ } catch (FacesException e) {
+ return;
+ }
+
+ assertFalse("No exception on invalid parameter", true);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.context.ContextInitParameters#getInitParameter(javax.faces.context.FacesContext, java.lang.String[])}.
+ */
+ public void testGetInitParameter() {
+ String[] params = {"foo.bar", ORG_AJAX4JSF_STRING};
+ String value = ContextInitParameters.getInitParameter(facesContext, params);
+
+ assertEquals(STRING_PARAM, value);
+
+ String[] params2 = {"foo.bar"};
+
+ value = ContextInitParameters.getInitParameter(facesContext, params2);
+ assertNull(value);
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/css/CssCompressorTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/css/CssCompressorTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/css/CssCompressorTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,9 +1,9 @@
+
/*
- * CssCompressorTest.java Date created: 21.11.2007
- * Last modified by: $Author$
- * $Revision$ $Date$
+* CssCompressorTest.java Date created: 21.11.2007
+* Last modified by: $Author$
+* $Revision$ $Date$
*/
-
package org.ajax4jsf.css;
import java.io.IOException;
@@ -19,87 +19,85 @@
*
*/
public class CssCompressorTest extends TestCase {
-
+
+ /** css example to be comressed */
+ private static final String cssExample =
+ "HTML { \n" + "MARGIN-BOTTOM: 0.01em; HEIGHT: 100%; BACKGROUND-COLOR: #ffffff;\n" + "}\n" + "TD {\n"
+ + "FONT-SIZE: 10px; COLOR: #000000; FONT-FAMILY: verdana, arial\n" + "}\n" + "TH {\n"
+ + "FONT-WEIGHT: bold; FONT-SIZE: 10px; COLOR: #336699; FONT-FAMILY: verdana, arial; BACKGROUND-COLOR: #ffffff; text-align:left;\n"
+ + "}\n" + ".header {\n" + "FONT-WEIGHT: bold; FONT-SIZE: 11px; COLOR: #000000; FONT-FAMILY: verdana, arial\n"
+ + "}\n";
+
/** Length of correctly compressed css example */
private static final int lengthCompressed = 305;
-
- /** css example to be comressed */
- private static final String cssExample =
- "HTML { \n"+
- "MARGIN-BOTTOM: 0.01em; HEIGHT: 100%; BACKGROUND-COLOR: #ffffff;\n" +
- "}\n" +
- "TD {\n" +
- "FONT-SIZE: 10px; COLOR: #000000; FONT-FAMILY: verdana, arial\n" +
- "}\n" +
- "TH {\n" +
- "FONT-WEIGHT: bold; FONT-SIZE: 10px; COLOR: #336699; FONT-FAMILY: verdana, arial; BACKGROUND-COLOR: #ffffff; text-align:left;\n" +
- "}\n" +
- ".header {\n" +
- "FONT-WEIGHT: bold; FONT-SIZE: 11px; COLOR: #000000; FONT-FAMILY: verdana, arial\n" +
- "}\n";
-
+
/**
* Constructor
* @param name
*/
public CssCompressorTest(String name) {
- super(name);
- // TODO Auto-generated constructor stub
+ super(name);
+
+ // TODO Auto-generated constructor stub
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
- // TODO Auto-generated method stub
- super.setUp();
+
+ // TODO Auto-generated method stub
+ super.setUp();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
- // TODO Auto-generated method stub
- super.tearDown();
+
+ // TODO Auto-generated method stub
+ super.tearDown();
}
-
-
+
/**
* Test method
* @throws IOException
*/
- public void testCssCompressor () throws IOException {
-
- StringBuffer cssBuffer = new StringBuffer(cssExample);
- CssCompressor compressor = new CssCompressor(cssBuffer);
- CountingOutputWriter writer = new CountingOutputWriter();
- compressor.compress(writer, -1);
-
- // compressed length should equal
- assertEquals(writer.getWritten(), lengthCompressed);
-
- }
-
+ public void testCssCompressor() throws IOException {
+ StringBuffer cssBuffer = new StringBuffer(cssExample);
+ CssCompressor compressor = new CssCompressor(cssBuffer);
+ CountingOutputWriter writer = new CountingOutputWriter();
+
+ compressor.compress(writer, -1);
+
+ // compressed length should equal
+ assertEquals(writer.getWritten(), lengthCompressed);
+ }
+
public void testSequentialComments() throws Exception {
- StringBuffer cssBuffer = new StringBuffer("/* copyright */ body { color: red; } /* abc *//* cde */ html { color: red; } /* copyright end */");
- CssCompressor compressor = new CssCompressor(cssBuffer);
- StringWriter stringWriter = new StringWriter();
- compressor.compress(stringWriter, -1);
- stringWriter.close();
- assertEquals("body{color:red;}html{color:red;}", stringWriter.toString());
- }
-
- public void testFakeComment() throws Exception {
- //this test won't go as our CSS compressor is not aware of possible /**/ in url
-
- //StringBuffer cssBuffer = new StringBuffer("/* copyright */ body { /* my style */ background-image: url(/*/); color: red; background-image: url(/****/); } /* copyright end */");
- //CssCompressor compressor = new CssCompressor(cssBuffer);
- //StringWriter stringWriter = new StringWriter();
- //compressor.compress(stringWriter, -1);
- //stringWriter.close();
- //assertEquals("body{background-image:url(/*/);color:red;background-image:url(/****/);}", stringWriter.toString());
+ StringBuffer cssBuffer =
+ new StringBuffer(
+ "/* copyright */ body { color: red; } /* abc *//* cde */ html { color: red; } /* copyright end */");
+ CssCompressor compressor = new CssCompressor(cssBuffer);
+ StringWriter stringWriter = new StringWriter();
+
+ compressor.compress(stringWriter, -1);
+ stringWriter.close();
+ assertEquals("body{color:red;}html{color:red;}", stringWriter.toString());
}
+ public void testFakeComment() throws Exception {
+
+ // this test won't go as our CSS compressor is not aware of possible /**/ in url
+ // StringBuffer cssBuffer = new StringBuffer("/* copyright */ body { /* my style */ background-image: url(/*/); color: red; background-image: url(/****/); } /* copyright end */");
+ // CssCompressor compressor = new CssCompressor(cssBuffer);
+ // StringWriter stringWriter = new StringWriter();
+ // compressor.compress(stringWriter, -1);
+ // stringWriter.close();
+ // assertEquals("body{background-image:url(/*/);color:red;background-image:url(/****/);}", stringWriter.toString());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/event/EventsQueueTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/event/EventsQueueTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/event/EventsQueueTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,10 +18,11 @@
* 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.event;
+package org.ajax4jsf.event;
+
import java.util.NoSuchElementException;
import javax.faces.component.UICommand;
@@ -35,73 +36,84 @@
*/
public class EventsQueueTest extends TestCase {
- /**
- * @param name
- */
- public EventsQueueTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public EventsQueueTest(String name) {
+ super(name);
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.ajax4jsf.event.EventsQueue#remove()}.
- */
- public void testRemove() {
- ActionEvent event = new ActionEvent(new UICommand());
- EventsQueue queue = new EventsQueue();
- queue.offer(event);
- assertFalse(queue.isEmpty());
- ActionEvent event2 = new ActionEvent(new UICommand());
- queue.offer(event2);
- assertSame(event, queue.remove());
- assertSame(event2, queue.remove());
- assertTrue(queue.isEmpty());
- try {
- queue.remove();
- } catch (NoSuchElementException e) {
- return;
- }
- assertTrue("exception not thrown",false);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.event.EventsQueue#remove()}.
+ */
+ public void testRemove() {
+ ActionEvent event = new ActionEvent(new UICommand());
+ EventsQueue queue = new EventsQueue();
- /**
- * Test method for {@link org.ajax4jsf.event.EventsQueue#offer(javax.faces.event.FacesEvent)}.
- */
- public void testAdd() {
- ActionEvent event = new ActionEvent(new UICommand());
- EventsQueue queue = new EventsQueue();
- queue.offer(event);
- assertFalse(queue.isEmpty());
- ActionEvent event2 = new ActionEvent(new UICommand());
- queue.offer(event2);
- }
+ queue.offer(event);
+ assertFalse(queue.isEmpty());
- /**
- * Test method for {@link org.ajax4jsf.event.EventsQueue#clear()}.
- */
- public void testClear() {
- ActionEvent event = new ActionEvent(new UICommand());
- EventsQueue queue = new EventsQueue();
- queue.offer(event);
- assertFalse(queue.isEmpty());
- ActionEvent event2 = new ActionEvent(new UICommand());
- queue.offer(event2);
- queue.clear();
- assertTrue(queue.isEmpty());
- }
+ ActionEvent event2 = new ActionEvent(new UICommand());
+ queue.offer(event2);
+ assertSame(event, queue.remove());
+ assertSame(event2, queue.remove());
+ assertTrue(queue.isEmpty());
+ try {
+ queue.remove();
+ } catch (NoSuchElementException e) {
+ return;
+ }
+
+ assertTrue("exception not thrown", false);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.event.EventsQueue#offer(javax.faces.event.FacesEvent)}.
+ */
+ public void testAdd() {
+ ActionEvent event = new ActionEvent(new UICommand());
+ EventsQueue queue = new EventsQueue();
+
+ queue.offer(event);
+ assertFalse(queue.isEmpty());
+
+ ActionEvent event2 = new ActionEvent(new UICommand());
+
+ queue.offer(event2);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.event.EventsQueue#clear()}.
+ */
+ public void testClear() {
+ ActionEvent event = new ActionEvent(new UICommand());
+ EventsQueue queue = new EventsQueue();
+
+ queue.offer(event);
+ assertFalse(queue.isEmpty());
+
+ ActionEvent event2 = new ActionEvent(new UICommand());
+
+ queue.offer(event2);
+ queue.clear();
+ assertTrue(queue.isEmpty());
+ }
}
Copied: root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/Test.java (from rev 15745, root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/Test.java)
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/Test.java (rev 0)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/Test.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -0,0 +1,340 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - 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.io;
+
+import org.junit.Ignore;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+
+@Ignore
+public final class Test {
+ private static final int ARRAY_LENGTH = 27;
+ private static final int READ_LENGTH = 22;
+ private static final int READ_OFF = 4;
+ private static final boolean OUT_STRING = true;
+ private static final boolean BUILD_STRING = false;
+
+ private Test() {}
+
+ static void testStreams() throws IOException {
+ String s = "This is a senseless text to test streams.\n";
+
+ for (int i = 0; i < 10; i++) {
+ s = s + s; // repeated 16 times
+ }
+
+ byte[] bytes = s.getBytes();
+ FastBufferOutputStream output = new FastBufferOutputStream(16);
+
+ // write it several times.
+ for (int i = 0; i < 4; i++) {
+ output.write(bytes);
+ }
+
+ // write it one more time by one byte
+ for (int i = 0; i < bytes.length; i++) {
+ output.write(bytes[i]);
+ }
+
+ FastBufferInputStream input = new FastBufferInputStream(output);
+ StringBuffer sb = new StringBuffer();
+
+ // use for reading unconvenient array length.
+ byte[] bs = new byte[ARRAY_LENGTH];
+ int l = 0;
+
+ while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
+ if (BUILD_STRING) {
+ sb.append(new String(bs, READ_OFF, l));
+ }
+ }
+
+ if (BUILD_STRING && OUT_STRING) {
+ System.out.println(sb);
+ System.out.println("Length=" + output.getLength());
+ }
+ }
+
+ static void testStandardStreams() throws IOException {
+ String s = "This is a senseless text to test streams.\n";
+
+ for (int i = 0; i < 10; i++) {
+ s = s + s; // repeated 16 times
+ }
+
+ byte[] bytes = s.getBytes();
+ ByteArrayOutputStream output = new ByteArrayOutputStream(16);
+
+ // write it several times.
+ for (int i = 0; i < 4; i++) {
+ output.write(bytes);
+ }
+
+ // write it one more time by one byte
+ for (int i = 0; i < bytes.length; i++) {
+ output.write(bytes[i]);
+ }
+
+ ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
+ StringBuffer sb = new StringBuffer();
+
+ // use for reading unconvenient array length.
+ byte[] bs = new byte[ARRAY_LENGTH];
+ int l = 0;
+
+ while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
+ if (BUILD_STRING) {
+ sb.append(new String(bs, READ_OFF, l));
+ }
+ }
+
+ if (BUILD_STRING && OUT_STRING) {
+ System.out.println(sb);
+ }
+ }
+
+ static void testReaders() throws IOException {
+ String s = "This is a senseless text to test readers.\n";
+
+ for (int i = 0; i < 10; i++) {
+ s = s + s; // repeated 16 times
+ }
+
+ char[] bytes = s.toCharArray();
+ FastBufferWriter output = new FastBufferWriter(16);
+
+ // write it several times.
+ for (int i = 0; i < 4; i++) {
+ output.write(bytes);
+ }
+
+ // write it one more time by one byte
+ for (int i = 0; i < bytes.length; i++) {
+ output.write(bytes[i]);
+ }
+
+ FastBufferReader input = new FastBufferReader(output);
+ StringBuffer sb = new StringBuffer();
+
+ // use for reading unconvenient array length.
+ char[] bs = new char[ARRAY_LENGTH];
+ int l = 0;
+
+ while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
+ if (BUILD_STRING) {
+ sb.append(new String(bs, READ_OFF, l));
+ }
+ }
+
+ if (BUILD_STRING && OUT_STRING) {
+ System.out.println(sb);
+ }
+ }
+
+ static void testStandardReaders() throws IOException {
+ String s = "This is a senseless text to test readers.\n";
+
+ for (int i = 0; i < 10; i++) {
+ s = s + s; // repeated 16 times
+ }
+
+ char[] bytes = s.toCharArray();
+ StringWriter output = new StringWriter(16);
+
+ // write it several times.
+ for (int i = 0; i < 4; i++) {
+ output.write(bytes);
+ }
+
+ // write it one more time by one byte
+ for (int i = 0; i < bytes.length; i++) {
+ output.write(bytes[i]);
+ }
+
+ StringReader input = new StringReader(output.toString());
+ StringBuffer sb = new StringBuffer();
+
+ // use for reading unconvenient array length.
+ char[] bs = new char[ARRAY_LENGTH];
+ int l = 0;
+
+ while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
+ if (BUILD_STRING) {
+ sb.append(new String(bs, READ_OFF, l));
+ }
+ }
+
+ if (BUILD_STRING && OUT_STRING) {
+ System.out.println(sb);
+ }
+ }
+
+ static void testTransitionFromWriterToStream() throws IOException {
+ String s = "This is a senseless text to test transform from writer to stream.\n";
+
+ for (int i = 0; i < 10; i++) {
+ s = s + s; // repeated 16 times
+ }
+
+ char[] bytes = s.toCharArray();
+ FastBufferWriter output = new FastBufferWriter(16);
+
+ // write it several times.
+ for (int i = 0; i < 4; i++) {
+ output.write(bytes);
+ }
+
+ // write it one more time by one byte
+ for (int i = 0; i < bytes.length; i++) {
+ output.write(bytes[i]);
+ }
+
+ FastBufferOutputStream output2 = output.convertToOutputStream("UTF-8");
+ FastBufferInputStream input = new FastBufferInputStream(output2);
+ StringBuffer sb = new StringBuffer();
+
+ // use for reading unconvenient array length.
+ byte[] bs = new byte[ARRAY_LENGTH];
+ int l = 0;
+
+ while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
+ if (BUILD_STRING) {
+ sb.append(new String(bs, READ_OFF, l));
+ }
+ }
+
+ if (BUILD_STRING && OUT_STRING) {
+ System.out.println(sb);
+ }
+ }
+
+ static void testStandardTransitionFromWriterToStream() throws IOException {
+ String s = "This is a senseless text to test transform from writer to stream.\n";
+
+ for (int i = 0; i < 10; i++) {
+ s = s + s; // repeated 16 times
+ }
+
+ char[] bytes = s.toCharArray();
+ StringWriter output = new StringWriter(16);
+
+ // write it several times.
+ for (int i = 0; i < 4; i++) {
+ output.write(bytes);
+ }
+
+ // write it one more time by one byte
+ for (int i = 0; i < bytes.length; i++) {
+ output.write(bytes[i]);
+ }
+
+ String str = output.toString();
+ ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes());
+ StringBuffer sb = new StringBuffer();
+
+ // use for reading unconvenient array length.
+ byte[] bs = new byte[ARRAY_LENGTH];
+ int l = 0;
+
+ while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
+ if (BUILD_STRING) {
+ sb.append(new String(bs, READ_OFF, l));
+ }
+ }
+
+ if (BUILD_STRING && OUT_STRING) {
+ System.out.println(sb);
+ }
+ }
+
+ static void testTransitionFromStreamToWriter() throws IOException {
+ String s = "This is a senseless text to test transform from stream to writer.\n";
+
+ for (int i = 0; i < 10; i++) {
+ s = s + s; // repeated 16 times
+ }
+
+ byte[] bytes = s.getBytes();
+ FastBufferOutputStream output = new FastBufferOutputStream(16);
+
+ // write it several times.
+ for (int i = 0; i < 4; i++) {
+ output.write(bytes);
+ }
+
+ // write it one more time by one byte
+ for (int i = 0; i < bytes.length; i++) {
+ output.write(bytes[i]);
+ }
+
+ FastBufferWriter output2 = output.convertToWriter("UTF-8");
+ FastBufferReader input = new FastBufferReader(output2);
+ StringBuffer sb = new StringBuffer();
+
+ // use for reading unconvenient array length.
+ char[] bs = new char[ARRAY_LENGTH];
+ int l = 0;
+
+ while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
+ if (BUILD_STRING) {
+ sb.append(new String(bs, READ_OFF, l));
+ }
+ }
+
+ if (BUILD_STRING && OUT_STRING) {
+ System.out.println(sb);
+ }
+ }
+
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+ long t = System.currentTimeMillis();
+
+ try {
+ for (int i = 0; i < 10; i++) {
+
+// testStreams();
+// testStandardStreams();
+// testReaders();
+// testStandardReaders();
+// testTransitionFromWriterToStream();
+ testStandardTransitionFromWriterToStream();
+
+// testTransitionFromStreamToWriter();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ long dt = System.currentTimeMillis() - t;
+
+ System.out.println(dt);
+ }
+}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/parser/FastBufferOutputStreamTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/parser/FastBufferOutputStreamTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/parser/FastBufferOutputStreamTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.io.parser;
import junit.framework.TestCase;
@@ -30,53 +32,53 @@
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class FastBufferOutputStreamTest extends TestCase {
- /**
- * Test method for {@link org.ajax4jsf.io.FastBufferOutputStream#reset()}.
- */
- public void testResetOneBuffer() throws Exception {
- FastBufferOutputStream stream = new FastBufferOutputStream(256);
- for (int i = 0; i < 255; i++) {
- stream.write(i);
- }
-
- assertEquals(255, stream.getLength());
- ByteBuffer firstBuffer = stream.getFirstBuffer();
- assertNull(firstBuffer.getNext());
- assertNull(firstBuffer.getPrevious());
+ /**
+ * Test method for {@link org.ajax4jsf.io.FastBufferOutputStream#reset()}.
+ */
+ public void testResetOneBuffer() throws Exception {
+ FastBufferOutputStream stream = new FastBufferOutputStream(256);
- stream.reset();
-
- assertEquals(0, stream.getLength());
- firstBuffer = stream.getFirstBuffer();
- assertEquals(0, firstBuffer.getUsedSize());
- assertNull(firstBuffer.getNext());
- assertNull(firstBuffer.getPrevious());
- }
-
- /**
- * Test method for {@link org.ajax4jsf.io.FastBufferOutputStream#reset()}.
- */
- public void testResetTwoBuffers() throws Exception {
- FastBufferOutputStream stream = new FastBufferOutputStream(256);
- for (int i = 0; i < 257; i++) {
- stream.write(i);
- }
+ for (int i = 0; i < 255; i++) {
+ stream.write(i);
+ }
- assertEquals(257, stream.getLength());
- ByteBuffer firstBuffer = stream.getFirstBuffer();
- assertNotNull(firstBuffer.getNext());
- assertNull(firstBuffer.getPrevious());
+ assertEquals(255, stream.getLength());
- stream.reset();
-
- assertEquals(0, stream.getLength());
- firstBuffer = stream.getFirstBuffer();
- assertEquals(0, firstBuffer.getUsedSize());
- assertNull(firstBuffer.getNext());
- assertNull(firstBuffer.getPrevious());
- }
+ ByteBuffer firstBuffer = stream.getFirstBuffer();
+ assertNull(firstBuffer.getNext());
+ assertNull(firstBuffer.getPrevious());
+ stream.reset();
+ assertEquals(0, stream.getLength());
+ firstBuffer = stream.getFirstBuffer();
+ assertEquals(0, firstBuffer.getUsedSize());
+ assertNull(firstBuffer.getNext());
+ assertNull(firstBuffer.getPrevious());
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.io.FastBufferOutputStream#reset()}.
+ */
+ public void testResetTwoBuffers() throws Exception {
+ FastBufferOutputStream stream = new FastBufferOutputStream(256);
+
+ for (int i = 0; i < 257; i++) {
+ stream.write(i);
+ }
+
+ assertEquals(257, stream.getLength());
+
+ ByteBuffer firstBuffer = stream.getFirstBuffer();
+
+ assertNotNull(firstBuffer.getNext());
+ assertNull(firstBuffer.getPrevious());
+ stream.reset();
+ assertEquals(0, stream.getLength());
+ firstBuffer = stream.getFirstBuffer();
+ assertEquals(0, firstBuffer.getUsedSize());
+ assertNull(firstBuffer.getNext());
+ assertNull(firstBuffer.getPrevious());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/parser/FastBufferWriterTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/parser/FastBufferWriterTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/io/parser/FastBufferWriterTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.io.parser;
import junit.framework.TestCase;
@@ -31,84 +33,86 @@
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class FastBufferWriterTest extends TestCase {
- /**
- * Test method for {@link org.ajax4jsf.io.FastBufferWriter#reset()}.
- */
- public void testResetOneBuffer() throws Exception {
- FastBufferWriter stream = new FastBufferWriter(256);
- for (int i = 0; i < 255; i++) {
- stream.write(i);
- }
-
- assertEquals(255, stream.getLength());
- CharBuffer firstBuffer = stream.getFirstBuffer();
- assertNull(firstBuffer.getNext());
- assertNull(firstBuffer.getPrevious());
+ /**
+ * Test method for {@link org.ajax4jsf.io.FastBufferWriter#reset()}.
+ */
+ public void testResetOneBuffer() throws Exception {
+ FastBufferWriter stream = new FastBufferWriter(256);
- stream.reset();
-
- assertEquals(0, stream.getLength());
- firstBuffer = stream.getFirstBuffer();
- assertEquals(0, firstBuffer.getUsedSize());
- assertNull(firstBuffer.getNext());
- assertNull(firstBuffer.getPrevious());
- }
-
- /**
- * Test method for {@link org.ajax4jsf.io.FastBufferWriter#reset()}.
- */
- public void testResetTwoBuffers() throws Exception {
- FastBufferWriter stream = new FastBufferWriter(256);
- for (int i = 0; i < 257; i++) {
- stream.write(i);
- }
+ for (int i = 0; i < 255; i++) {
+ stream.write(i);
+ }
- assertEquals(257, stream.getLength());
- CharBuffer firstBuffer = stream.getFirstBuffer();
- assertNotNull(firstBuffer.getNext());
- assertNull(firstBuffer.getPrevious());
+ assertEquals(255, stream.getLength());
- stream.reset();
-
- assertEquals(0, stream.getLength());
- firstBuffer = stream.getFirstBuffer();
- assertEquals(0, firstBuffer.getUsedSize());
- assertNull(firstBuffer.getNext());
- assertNull(firstBuffer.getPrevious());
- }
-
- public void testCompact() throws Exception {
- int itemsTowWrite = 16384 + 16000;
+ CharBuffer firstBuffer = stream.getFirstBuffer();
- FastBufferWriter writer = new FastBufferWriter(16384);
- for (int i = 0; i < itemsTowWrite; i++) {
- writer.write(i);
- }
- writer.close();
-
- CharBuffer firstBuffer = writer.getFirstBuffer();
- assertNotNull(firstBuffer);
+ assertNull(firstBuffer.getNext());
+ assertNull(firstBuffer.getPrevious());
+ stream.reset();
+ assertEquals(0, stream.getLength());
+ firstBuffer = stream.getFirstBuffer();
+ assertEquals(0, firstBuffer.getUsedSize());
+ assertNull(firstBuffer.getNext());
+ assertNull(firstBuffer.getPrevious());
+ }
- CharBuffer nextBuffer = firstBuffer.getNext();
- assertNotNull(nextBuffer);
- assertNull(nextBuffer.getNext());
+ /**
+ * Test method for {@link org.ajax4jsf.io.FastBufferWriter#reset()}.
+ */
+ public void testResetTwoBuffers() throws Exception {
+ FastBufferWriter stream = new FastBufferWriter(256);
- assertTrue(firstBuffer.getUsedSize() == firstBuffer.getCacheSize());
- assertTrue(nextBuffer.getUsedSize() < nextBuffer.getCacheSize());
-
- firstBuffer.compact();
+ for (int i = 0; i < 257; i++) {
+ stream.write(i);
+ }
- assertTrue(firstBuffer.getUsedSize() == firstBuffer.getCacheSize());
- assertTrue(nextBuffer.getUsedSize() == nextBuffer.getCacheSize());
+ assertEquals(257, stream.getLength());
- FastBufferReader reader = new FastBufferReader(firstBuffer);
- for (int i = 0; i < itemsTowWrite; i++) {
- assertEquals(i, reader.read());
- }
- reader.close();
- }
+ CharBuffer firstBuffer = stream.getFirstBuffer();
+ assertNotNull(firstBuffer.getNext());
+ assertNull(firstBuffer.getPrevious());
+ stream.reset();
+ assertEquals(0, stream.getLength());
+ firstBuffer = stream.getFirstBuffer();
+ assertEquals(0, firstBuffer.getUsedSize());
+ assertNull(firstBuffer.getNext());
+ assertNull(firstBuffer.getPrevious());
+ }
+
+ public void testCompact() throws Exception {
+ int itemsTowWrite = 16384 + 16000;
+ FastBufferWriter writer = new FastBufferWriter(16384);
+
+ for (int i = 0; i < itemsTowWrite; i++) {
+ writer.write(i);
+ }
+
+ writer.close();
+
+ CharBuffer firstBuffer = writer.getFirstBuffer();
+
+ assertNotNull(firstBuffer);
+
+ CharBuffer nextBuffer = firstBuffer.getNext();
+
+ assertNotNull(nextBuffer);
+ assertNull(nextBuffer.getNext());
+ assertTrue(firstBuffer.getUsedSize() == firstBuffer.getCacheSize());
+ assertTrue(nextBuffer.getUsedSize() < nextBuffer.getCacheSize());
+ firstBuffer.compact();
+ assertTrue(firstBuffer.getUsedSize() == firstBuffer.getCacheSize());
+ assertTrue(nextBuffer.getUsedSize() == nextBuffer.getCacheSize());
+
+ FastBufferReader reader = new FastBufferReader(firstBuffer);
+
+ for (int i = 0; i < itemsTowWrite; i++) {
+ assertEquals(i, reader.read());
+ }
+
+ reader.close();
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/javascript/JSMinTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/javascript/JSMinTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/javascript/JSMinTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,6 +18,9 @@
* 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.javascript;
import java.io.ByteArrayInputStream;
@@ -35,54 +38,53 @@
*/
public class JSMinTest extends TestCase {
- /**
- * @param name
- */
- public JSMinTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public JSMinTest(String name) {
+ super(name);
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.ajax4jsf.javascript.JSMin#jsmin()}.
- * @throws UnterminatedStringLiteralException
- * @throws UnterminatedCommentException
- * @throws UnterminatedRegExpLiteralException
- * @throws IOException
- */
- public void testJsmin() throws IOException, UnterminatedRegExpLiteralException, UnterminatedCommentException, UnterminatedStringLiteralException {
- String script =" patterns: {\n" +
- " // combinators must be listed first\n" +
- " // (and descendant needs to be last combinator)\n" +
- " laterSibling: /^\\s*~\\s*/,\n" +
- " child: /^\\s*>\\s*/,\n" +
- " adjacent: /^\\s*\\+\\s*/,\n" +
- " descendant: /^\\s/,\n" +
- "\n" +
- " // selectors follow\n" +
- " tagName: /^\\s*(\\*|[\\w\\-]+)(\\b|$)?/,\n" +
- " id: /^#([\\w\\-\\*]+)(\\b|$)/,\n" +
- " className: /^\\.([\\w\\-\\*]+)(\\b|$)/,\n" +
- " pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\\((.*?)\\))?(\\b|$|\\s|(?=:))/,\n" +
- " attrPresence: /^\\[([\\w]+)\\]/,\n" +
- " attr: /\\[((?:[\\w-]*:)?[\\w-]+)\\s*(?:([!^$*~|]?=)\\s*(([\'\"])([^\\]]*?)\\4|([^\'\"][^\\]]*?)))?\\]/\n" +
- " }";
- ByteArrayInputStream in = new ByteArrayInputStream(script.getBytes());
- JSMin jsmin = new JSMin(in,System.out);
- jsmin.jsmin();
- }
+ /**
+ * Test method for {@link org.ajax4jsf.javascript.JSMin#jsmin()}.
+ * @throws UnterminatedStringLiteralException
+ * @throws UnterminatedCommentException
+ * @throws UnterminatedRegExpLiteralException
+ * @throws IOException
+ */
+ public void testJsmin()
+ throws IOException, UnterminatedRegExpLiteralException, UnterminatedCommentException,
+ UnterminatedStringLiteralException {
+ String script =
+ " patterns: {\n" + " // combinators must be listed first\n"
+ + " // (and descendant needs to be last combinator)\n" + " laterSibling: /^\\s*~\\s*/,\n"
+ + " child: /^\\s*>\\s*/,\n" + " adjacent: /^\\s*\\+\\s*/,\n"
+ + " descendant: /^\\s/,\n" + "\n" + " // selectors follow\n"
+ + " tagName: /^\\s*(\\*|[\\w\\-]+)(\\b|$)?/,\n" + " id: /^#([\\w\\-\\*]+)(\\b|$)/,\n"
+ + " className: /^\\.([\\w\\-\\*]+)(\\b|$)/,\n"
+ + " pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\\((.*?)\\))?(\\b|$|\\s|(?=:))/,\n"
+ + " attrPresence: /^\\[([\\w]+)\\]/,\n"
+ + " attr: /\\[((?:[\\w-]*:)?[\\w-]+)\\s*(?:([!^$*~|]?=)\\s*(([\'\"])([^\\]]*?)\\4|([^\'\"][^\\]]*?)))?\\]/\n"
+ + " }";
+ ByteArrayInputStream in = new ByteArrayInputStream(script.getBytes());
+ JSMin jsmin = new JSMin(in, System.out);
+ jsmin.jsmin();
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/renderkit/RendererUtilsTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/renderkit/RendererUtilsTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/renderkit/RendererUtilsTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,6 +18,9 @@
* 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.renderkit;
import java.util.ArrayList;
@@ -36,131 +39,108 @@
* @since 3.3.2
*/
public class RendererUtilsTest extends TestCase {
+ public void testIsEmpty() throws Exception {
+ RendererUtils utils = RendererUtils.getInstance();
- public void testIsEmpty() throws Exception {
- RendererUtils utils = RendererUtils.getInstance();
-
- assertTrue(utils.isEmpty(null));
- assertFalse(utils.isEmpty(new Object()));
- assertFalse(utils.isEmpty(Boolean.FALSE));
- assertFalse(utils.isEmpty(Long.valueOf(0)));
- assertFalse(utils.isEmpty(Integer.valueOf(0)));
- assertFalse(utils.isEmpty(Short.valueOf((short) 0)));
- assertFalse(utils.isEmpty(Byte.valueOf((byte) 0)));
-
- assertTrue(utils.isEmpty(""));
- assertFalse(utils.isEmpty("s"));
-
- assertTrue(utils.isEmpty(new ArrayList<Object>()));
- assertTrue(utils.isEmpty(Collections.EMPTY_LIST));
-
- List<Object> testList = new ArrayList<Object>();
- testList.add("x");
- assertFalse(utils.isEmpty(testList));
+ assertTrue(utils.isEmpty(null));
+ assertFalse(utils.isEmpty(new Object()));
+ assertFalse(utils.isEmpty(Boolean.FALSE));
+ assertFalse(utils.isEmpty(Long.valueOf(0)));
+ assertFalse(utils.isEmpty(Integer.valueOf(0)));
+ assertFalse(utils.isEmpty(Short.valueOf((short) 0)));
+ assertFalse(utils.isEmpty(Byte.valueOf((byte) 0)));
+ assertTrue(utils.isEmpty(""));
+ assertFalse(utils.isEmpty("s"));
+ assertTrue(utils.isEmpty(new ArrayList<Object>()));
+ assertTrue(utils.isEmpty(Collections.EMPTY_LIST));
- assertTrue(utils.isEmpty(new HashMap<String, Object>()));
- assertTrue(utils.isEmpty(Collections.EMPTY_MAP));
+ List<Object> testList = new ArrayList<Object>();
- Map<String, Object> testMap = new HashMap<String, Object>();
- testMap.put("x", "y");
- assertFalse(utils.isEmpty(testMap));
-
- assertTrue(utils.isEmpty(new Object[0]));
- assertTrue(utils.isEmpty(new int[0]));
+ testList.add("x");
+ assertFalse(utils.isEmpty(testList));
+ assertTrue(utils.isEmpty(new HashMap<String, Object>()));
+ assertTrue(utils.isEmpty(Collections.EMPTY_MAP));
- assertFalse(utils.isEmpty(new Object[1]));
- assertFalse(utils.isEmpty(new int[1]));
- }
-
- public void testScriptHashVariableWrapper() throws Exception {
- assertEquals("abc", RendererUtils.ScriptHashVariableWrapper.DEFAULT.wrap("abc"));
+ Map<String, Object> testMap = new HashMap<String, Object>();
- Object eventHandler = RendererUtils.ScriptHashVariableWrapper.EVENT_HANDLER.wrap("abc");
- assertTrue(eventHandler instanceof JSFunctionDefinition);
+ testMap.put("x", "y");
+ assertFalse(utils.isEmpty(testMap));
+ assertTrue(utils.isEmpty(new Object[0]));
+ assertTrue(utils.isEmpty(new int[0]));
+ assertFalse(utils.isEmpty(new Object[1]));
+ assertFalse(utils.isEmpty(new int[1]));
+ }
- JSFunctionDefinition handlerFunction = (JSFunctionDefinition) eventHandler;
- assertEquals("function(event){abc}", handlerFunction.toScript().replaceAll("\\s", ""));
- }
-
- public void testAddToScriptHash() throws Exception {
- Map<String,Object> hash = new HashMap<String, Object>();
- RendererUtils utils = RendererUtils.getInstance();
-
- utils.addToScriptHash(hash, "x", "y", null, null);
- assertEquals("y", hash.get("x"));
-
- utils.addToScriptHash(hash, "y", "", null, null);
- assertNull(hash.get("y"));
- assertFalse(hash.containsKey("y"));
-
- utils.addToScriptHash(hash, "y1", null, null, null);
- assertNull(hash.get("y1"));
- assertFalse(hash.containsKey("y1"));
+ public void testScriptHashVariableWrapper() throws Exception {
+ assertEquals("abc", RendererUtils.ScriptHashVariableWrapper.DEFAULT.wrap("abc"));
- utils.addToScriptHash(hash, "st", "server", "", null);
- assertEquals("server", hash.get("st"));
+ Object eventHandler = RendererUtils.ScriptHashVariableWrapper.EVENT_HANDLER.wrap("abc");
- utils.addToScriptHash(hash, "st1", "ajax", "ajax", null);
- assertNull(hash.get("st1"));
- assertFalse(hash.containsKey("st1"));
+ assertTrue(eventHandler instanceof JSFunctionDefinition);
- utils.addToScriptHash(hash, "st2", "", "ajax", null);
- assertNull(hash.get("st2"));
- assertFalse(hash.containsKey("st2"));
-
- utils.addToScriptHash(hash, "null", null, "server", null);
- assertNull(hash.get("null"));
- assertFalse(hash.containsKey("null"));
+ JSFunctionDefinition handlerFunction = (JSFunctionDefinition) eventHandler;
- utils.addToScriptHash(hash, "b", false, null, null);
- assertNull(hash.get("b"));
- assertFalse(hash.containsKey("b"));
-
- utils.addToScriptHash(hash, "b1", true, null, null);
- assertEquals(Boolean.TRUE, hash.get("b1"));
-
- utils.addToScriptHash(hash, "b2", true, "true", null);
- assertNull(hash.get("b2"));
- assertFalse(hash.containsKey("b2"));
+ assertEquals("function(event){abc}", handlerFunction.toScript().replaceAll("\\s", ""));
+ }
- utils.addToScriptHash(hash, "b3", false, "true", null);
- assertEquals(Boolean.FALSE, hash.get("b3"));
-
- utils.addToScriptHash(hash, "b4", true, "false", null);
- assertEquals(Boolean.TRUE, hash.get("b4"));
-
- utils.addToScriptHash(hash, "b5", false, "false", null);
- assertNull(hash.get("b5"));
- assertFalse(hash.containsKey("b5"));
-
- utils.addToScriptHash(hash, "i", Integer.valueOf(0), null, null);
- assertEquals(Integer.valueOf(0), hash.get("i"));
-
- utils.addToScriptHash(hash, "i1", Integer.valueOf(0), "0", null);
- assertNull(hash.get("i1"));
- assertFalse(hash.containsKey("i1"));
+ public void testAddToScriptHash() throws Exception {
+ Map<String, Object> hash = new HashMap<String, Object>();
+ RendererUtils utils = RendererUtils.getInstance();
- utils.addToScriptHash(hash, "i2", Integer.valueOf(0), "1", null);
- assertEquals(Integer.valueOf(0), hash.get("i2"));
-
- utils.addToScriptHash(hash, "i3", Integer.MIN_VALUE, null, null);
- assertNull(hash.get("i3"));
- assertFalse(hash.containsKey("i3"));
-
- utils.addToScriptHash(hash, "i4", Integer.MIN_VALUE, "0", null);
- assertNull(hash.get("i4"));
- assertFalse(hash.containsKey("i4"));
-
- utils.addToScriptHash(hash, "plain", "test", null, ScriptHashVariableWrapper.DEFAULT);
- assertEquals("test", hash.get("plain"));
-
- utils.addToScriptHash(hash, "plain1", "newtest", "blank", ScriptHashVariableWrapper.DEFAULT);
- assertEquals("newtest", hash.get("plain1"));
-
- utils.addToScriptHash(hash, "onclick", "alert(1)", null, ScriptHashVariableWrapper.EVENT_HANDLER);
- assertTrue(hash.get("onclick") instanceof JSFunctionDefinition);
-
- utils.addToScriptHash(hash, "onclick1", "alert(1)", "no-val", ScriptHashVariableWrapper.EVENT_HANDLER);
- assertTrue(hash.get("onclick1") instanceof JSFunctionDefinition);
- }
+ utils.addToScriptHash(hash, "x", "y", null, null);
+ assertEquals("y", hash.get("x"));
+ utils.addToScriptHash(hash, "y", "", null, null);
+ assertNull(hash.get("y"));
+ assertFalse(hash.containsKey("y"));
+ utils.addToScriptHash(hash, "y1", null, null, null);
+ assertNull(hash.get("y1"));
+ assertFalse(hash.containsKey("y1"));
+ utils.addToScriptHash(hash, "st", "server", "", null);
+ assertEquals("server", hash.get("st"));
+ utils.addToScriptHash(hash, "st1", "ajax", "ajax", null);
+ assertNull(hash.get("st1"));
+ assertFalse(hash.containsKey("st1"));
+ utils.addToScriptHash(hash, "st2", "", "ajax", null);
+ assertNull(hash.get("st2"));
+ assertFalse(hash.containsKey("st2"));
+ utils.addToScriptHash(hash, "null", null, "server", null);
+ assertNull(hash.get("null"));
+ assertFalse(hash.containsKey("null"));
+ utils.addToScriptHash(hash, "b", false, null, null);
+ assertNull(hash.get("b"));
+ assertFalse(hash.containsKey("b"));
+ utils.addToScriptHash(hash, "b1", true, null, null);
+ assertEquals(Boolean.TRUE, hash.get("b1"));
+ utils.addToScriptHash(hash, "b2", true, "true", null);
+ assertNull(hash.get("b2"));
+ assertFalse(hash.containsKey("b2"));
+ utils.addToScriptHash(hash, "b3", false, "true", null);
+ assertEquals(Boolean.FALSE, hash.get("b3"));
+ utils.addToScriptHash(hash, "b4", true, "false", null);
+ assertEquals(Boolean.TRUE, hash.get("b4"));
+ utils.addToScriptHash(hash, "b5", false, "false", null);
+ assertNull(hash.get("b5"));
+ assertFalse(hash.containsKey("b5"));
+ utils.addToScriptHash(hash, "i", Integer.valueOf(0), null, null);
+ assertEquals(Integer.valueOf(0), hash.get("i"));
+ utils.addToScriptHash(hash, "i1", Integer.valueOf(0), "0", null);
+ assertNull(hash.get("i1"));
+ assertFalse(hash.containsKey("i1"));
+ utils.addToScriptHash(hash, "i2", Integer.valueOf(0), "1", null);
+ assertEquals(Integer.valueOf(0), hash.get("i2"));
+ utils.addToScriptHash(hash, "i3", Integer.MIN_VALUE, null, null);
+ assertNull(hash.get("i3"));
+ assertFalse(hash.containsKey("i3"));
+ utils.addToScriptHash(hash, "i4", Integer.MIN_VALUE, "0", null);
+ assertNull(hash.get("i4"));
+ assertFalse(hash.containsKey("i4"));
+ utils.addToScriptHash(hash, "plain", "test", null, ScriptHashVariableWrapper.DEFAULT);
+ assertEquals("test", hash.get("plain"));
+ utils.addToScriptHash(hash, "plain1", "newtest", "blank", ScriptHashVariableWrapper.DEFAULT);
+ assertEquals("newtest", hash.get("plain1"));
+ utils.addToScriptHash(hash, "onclick", "alert(1)", null, ScriptHashVariableWrapper.EVENT_HANDLER);
+ assertTrue(hash.get("onclick") instanceof JSFunctionDefinition);
+ utils.addToScriptHash(hash, "onclick1", "alert(1)", "no-val", ScriptHashVariableWrapper.EVENT_HANDLER);
+ assertTrue(hash.get("onclick1") instanceof JSFunctionDefinition);
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/resource/cached/DualLRUMapTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/resource/cached/DualLRUMapTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/resource/cached/DualLRUMapTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.resource.cached;
import junit.framework.TestCase;
@@ -27,52 +29,41 @@
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class DualLRUMapTest extends TestCase {
+ public void testBasic() throws Exception {
+ DualLRUMap<String, String> map = new DualLRUMap<String, String>(16);
- public void testBasic() throws Exception {
- DualLRUMap<String, String> map = new DualLRUMap<String, String>(16);
-
- map.put("1", "a");
- map.put("2", "b");
- map.put("3", "c");
-
- assertEquals("a", map.get("1"));
- assertEquals("b", map.get("2"));
- assertEquals("c", map.get("3"));
+ map.put("1", "a");
+ map.put("2", "b");
+ map.put("3", "c");
+ assertEquals("a", map.get("1"));
+ assertEquals("b", map.get("2"));
+ assertEquals("c", map.get("3"));
+ assertEquals("1", map.getKey("a"));
+ assertEquals("2", map.getKey("b"));
+ assertEquals("3", map.getKey("c"));
+ assertTrue(map.containsKey("1"));
+ assertTrue(map.containsValue("a"));
+ assertTrue(map.containsKey("2"));
+ assertTrue(map.containsValue("b"));
+ assertTrue(map.containsKey("3"));
+ assertTrue(map.containsValue("c"));
+ map.remove("2");
+ assertNull(map.get("2"));
+ assertNull(map.getKey("b"));
+ assertFalse(map.containsKey("2"));
+ assertFalse(map.containsValue("b"));
+ }
- assertEquals("1", map.getKey("a"));
- assertEquals("2", map.getKey("b"));
- assertEquals("3", map.getKey("c"));
+ public void testRemoveEldest() throws Exception {
+ DualLRUMap<String, String> map = new DualLRUMap<String, String>(2);
- assertTrue(map.containsKey("1"));
- assertTrue(map.containsValue("a"));
- assertTrue(map.containsKey("2"));
- assertTrue(map.containsValue("b"));
- assertTrue(map.containsKey("3"));
- assertTrue(map.containsValue("c"));
-
- map.remove("2");
- assertNull(map.get("2"));
- assertNull(map.getKey("b"));
-
- assertFalse(map.containsKey("2"));
- assertFalse(map.containsValue("b"));
- }
-
- public void testRemoveEldest() throws Exception {
- DualLRUMap<String,String> map = new DualLRUMap<String, String>(2);
-
- map.put("1", "a");
- map.put("2", "b");
-
- assertNotNull(map.get("2"));
- assertNotNull(map.get("1"));
-
- map.put("3", "c");
-
- assertNull(map.get("2"));
- assertNull(map.getKey("b"));
- }
-
+ map.put("1", "a");
+ map.put("2", "b");
+ assertNotNull(map.get("2"));
+ assertNotNull(map.get("1"));
+ map.put("3", "c");
+ assertNull(map.get("2"));
+ assertNull(map.getKey("b"));
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/util/LRUMapTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/util/LRUMapTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/util/LRUMapTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,6 +18,9 @@
* 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.util;
import java.util.Iterator;
@@ -31,84 +34,99 @@
*/
public class LRUMapTest extends TestCase {
- /**
- * @param name
- */
- public LRUMapTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public LRUMapTest(String name) {
+ super(name);
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.ajax4jsf.util.LRUMap#LRUMap(int)}.
- */
- public void testLRUMap() {
- LRUMap map = new LRUMap(5);
- for (int i = 0; i < 10; i++) {
- map.put(new Integer(i), "Val"+(new Integer(i)));
- }
- assertEquals(map.size(), 5);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.util.LRUMap#LRUMap(int)}.
+ */
+ public void testLRUMap() {
+ LRUMap map = new LRUMap(5);
- /**
- * Test method for {@link org.ajax4jsf.util.LRUMap#removeEldestEntry(java.util.Map.Entry)}.
- */
- public void testRemoveEldestEntryEntry() {
-
- LRUMap map = new LRUMap(5){
- protected boolean removeEldestEntry(Entry arg0) {
- boolean eldestEntry = super.removeEldestEntry(arg0);
- assertTrue(eldestEntry ^ size()<=5);
- return false;
- }
- };
- for (int i = 0; i < 10; i++) {
- map.put(new Integer(i), "Val"+(new Integer(i)));
- }
- }
+ for (int i = 0; i < 10; i++) {
+ map.put(new Integer(i), "Val" + (new Integer(i)));
+ }
- /**
- * Test method for {@link java.util.HashMap#put(K, V)}.
- */
- public void testPut() {
- LRUMap map = new LRUMap(5);
- for (int i = 0; i < 10; i++) {
- map.put(new Integer(i), "Val"+(new Integer(i)));
- }
- assertEquals(map.size(), 5);
- Iterator iterator = map.values().iterator();
- for (int i = 5; i < 10; i++) {
- assertTrue(iterator.hasNext());
- assertEquals("Val"+(new Integer(i)), iterator.next());
- }
- assertFalse(iterator.hasNext());
- }
+ assertEquals(map.size(), 5);
+ }
- public void testGetMostRecent() throws Exception {
- LRUMap map = new LRUMap(5);
- for (int i = 0; i < 10; i++) {
- String last = "Val"+(new Integer(i));
- map.put(new Integer(i), last);
- assertSame(last, map.getMostRecent());
- }
- assertEquals(map.size(), 5);
- for (int i = 5; i < 10; i++) {
- Object lastGet = map.get(new Integer(i));
- assertSame(lastGet, map.getMostRecent());
- }
-
- }
+ /**
+ * Test method for {@link org.ajax4jsf.util.LRUMap#removeEldestEntry(java.util.Map.Entry)}.
+ */
+ public void testRemoveEldestEntryEntry() {
+ LRUMap map = new LRUMap(5) {
+ protected boolean removeEldestEntry(Entry arg0) {
+ boolean eldestEntry = super.removeEldestEntry(arg0);
+
+ assertTrue(eldestEntry ^ size() <= 5);
+
+ return false;
+ }
+ };
+
+ for (int i = 0; i < 10; i++) {
+ map.put(new Integer(i), "Val" + (new Integer(i)));
+ }
+ }
+
+ /**
+ * Test method for {@link java.util.HashMap#put(K, V)}.
+ */
+ public void testPut() {
+ LRUMap map = new LRUMap(5);
+
+ for (int i = 0; i < 10; i++) {
+ map.put(new Integer(i), "Val" + (new Integer(i)));
+ }
+
+ assertEquals(map.size(), 5);
+
+ Iterator iterator = map.values().iterator();
+
+ for (int i = 5; i < 10; i++) {
+ assertTrue(iterator.hasNext());
+ assertEquals("Val" + (new Integer(i)), iterator.next());
+ }
+
+ assertFalse(iterator.hasNext());
+ }
+
+ public void testGetMostRecent() throws Exception {
+ LRUMap map = new LRUMap(5);
+
+ for (int i = 0; i < 10; i++) {
+ String last = "Val" + (new Integer(i));
+
+ map.put(new Integer(i), last);
+ assertSame(last, map.getMostRecent());
+ }
+
+ assertEquals(map.size(), 5);
+
+ for (int i = 5; i < 10; i++) {
+ Object lastGet = map.get(new Integer(i));
+
+ assertSame(lastGet, map.getMostRecent());
+ }
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/util/NumericStreamsTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/ajax4jsf/util/NumericStreamsTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/ajax4jsf/util/NumericStreamsTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.util;
import java.awt.Color;
@@ -29,47 +31,44 @@
* @author Nick Belaevski
* @since 4.0
*/
-
public class NumericStreamsTest extends TestCase {
+ public void testByte() throws Exception {
+ byte[] bytes = new NumericDataOutputStream().writeByte((byte) 0xDF).writeByte((byte) 0x90).writeByte(
+ (byte) 0xAA).getBytes();
+ NumericDataInputStream inputStream = new NumericDataInputStream(bytes);
- public void testByte() throws Exception {
- byte[] bytes = new NumericDataOutputStream().writeByte((byte) 0xDF).writeByte((byte) 0x90).
- writeByte((byte) 0xAA).getBytes();
+ assertEquals((byte) 0xDF, inputStream.readByte());
+ assertEquals((byte) 0x90, inputStream.readByte());
+ assertEquals((byte) 0xAA, inputStream.readByte());
+ }
- NumericDataInputStream inputStream = new NumericDataInputStream(bytes);
- assertEquals((byte) 0xDF, inputStream.readByte());
- assertEquals((byte) 0x90, inputStream.readByte());
- assertEquals((byte) 0xAA, inputStream.readByte());
- }
+ public void testShort() throws Exception {
+ byte[] bytes = new NumericDataOutputStream().writeShort((short) 0xA7DF).writeShort((short) 0xFE90).writeShort(
+ (short) 0x34AA).getBytes();
+ NumericDataInputStream inputStream = new NumericDataInputStream(bytes);
- public void testShort() throws Exception {
- byte[] bytes = new NumericDataOutputStream().writeShort((short) 0xA7DF).writeShort((short) 0xFE90).
- writeShort((short) 0x34AA).getBytes();
+ assertEquals((short) 0xA7DF, inputStream.readShort());
+ assertEquals((short) 0xFE90, inputStream.readShort());
+ assertEquals((short) 0x34AA, inputStream.readShort());
+ }
- NumericDataInputStream inputStream = new NumericDataInputStream(bytes);
- assertEquals((short) 0xA7DF, inputStream.readShort());
- assertEquals((short) 0xFE90, inputStream.readShort());
- assertEquals((short) 0x34AA, inputStream.readShort());
- }
-
- public void testColor() throws Exception {
- byte[] bytes = new NumericDataOutputStream().writeColor(new Color(0xA7DFE0)).
- writeIntColor(0xE2349A).writeColor(new Color(0x4812F9)).getBytes();
-
- NumericDataInputStream inputStream = new NumericDataInputStream(bytes);
- assertEquals(0xA7DFE0, inputStream.readIntColor());
- assertEquals(new Color(0xE2349A), inputStream.readColor());
- assertEquals(0x4812F9, inputStream.readIntColor());
- }
-
- public void testInt() throws Exception {
- byte[] bytes = new NumericDataOutputStream().writeInt(0x12A7DFE0).writeInt(0x67E2349A).
- writeInt(0xBD4812F9).getBytes();
-
- NumericDataInputStream inputStream = new NumericDataInputStream(bytes);
- assertEquals(0x12A7DFE0, inputStream.readInt());
- assertEquals(0x67E2349A, inputStream.readInt());
- assertEquals(0xBD4812F9, inputStream.readInt());
- }
+ public void testColor() throws Exception {
+ byte[] bytes = new NumericDataOutputStream().writeColor(new Color(0xA7DFE0)).writeIntColor(0xE2349A).writeColor(
+ new Color(0x4812F9)).getBytes();
+ NumericDataInputStream inputStream = new NumericDataInputStream(bytes);
+ assertEquals(0xA7DFE0, inputStream.readIntColor());
+ assertEquals(new Color(0xE2349A), inputStream.readColor());
+ assertEquals(0x4812F9, inputStream.readIntColor());
+ }
+
+ public void testInt() throws Exception {
+ byte[] bytes =
+ new NumericDataOutputStream().writeInt(0x12A7DFE0).writeInt(0x67E2349A).writeInt(0xBD4812F9).getBytes();
+ NumericDataInputStream inputStream = new NumericDataInputStream(bytes);
+
+ assertEquals(0x12A7DFE0, inputStream.readInt());
+ assertEquals(0x67E2349A, inputStream.readInt());
+ assertEquals(0xBD4812F9, inputStream.readInt());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/component/UIRangedNumberInputTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/component/UIRangedNumberInputTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/component/UIRangedNumberInputTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,107 +19,102 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import org.richfaces.test.AbstractFacesTest;
-
public class UIRangedNumberInputTest extends AbstractFacesTest {
+ private UIRangedNumberInput input;
- private UIRangedNumberInput input;
-
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
-
- input = new UIRangedNumberInput() {
- private String minValue;
- private String maxValue;
- private boolean disabled;
-
- public String getMinValue() {
- return minValue;
- }
- public void setMinValue(String minValue) {
- this.minValue = minValue;
- }
- public String getMaxValue() {
- return maxValue;
- }
- public void setMaxValue(String maxValue) {
- this.maxValue = maxValue;
- }
- public boolean isDisabled() {
- return disabled;
- }
- public void setDisabled(boolean disabled) {
- this.disabled = disabled;
- }
- };
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ input = new UIRangedNumberInput() {
+ private String minValue;
+ private String maxValue;
+ private boolean disabled;
+ public String getMinValue() {
+ return minValue;
+ }
+ public void setMinValue(String minValue) {
+ this.minValue = minValue;
+ }
+ public String getMaxValue() {
+ return maxValue;
+ }
+ public void setMaxValue(String maxValue) {
+ this.maxValue = maxValue;
+ }
+ public boolean isDisabled() {
+ return disabled;
+ }
+ public void setDisabled(boolean disabled) {
+ this.disabled = disabled;
+ }
+ };
+ input.setMaxValue("100");
+ input.setMinValue("0");
+ input.setValid(true);
+ }
- input.setMaxValue("100");
- input.setMinValue("0");
- input.setValid(true);
- }
+ public void tearDown() throws Exception {
+ super.tearDown();
+ this.input = null;
+ }
- public void tearDown() throws Exception {
- super.tearDown();
+ private void checkValid() {
+ assertTrue(input.isValid());
+ assertFalse(facesContext.getMessages().hasNext());
+ }
- this.input = null;
- }
+ private void checkInvalid() {
+ assertFalse(input.isValid());
+ assertTrue(facesContext.getMessages().hasNext());
+ }
- private void checkValid() {
- assertTrue(input.isValid());
- assertFalse(facesContext.getMessages().hasNext());
- }
-
- private void checkInvalid() {
- assertFalse(input.isValid());
- assertTrue(facesContext.getMessages().hasNext());
- }
+ public void testValidateValueFacesContextObject() {
+ checkValid();
+ input.validateValue(facesContext, new Double(23.45));
+ checkValid();
+ }
- public void testValidateValueFacesContextObject() {
- checkValid();
- input.validateValue(facesContext, new Double(23.45));
- checkValid();
- }
+ public void testValidateNullValue() throws Exception {
+ checkValid();
+ input.validateValue(facesContext, null);
+ checkValid();
+ }
- public void testValidateNullValue() throws Exception {
- checkValid();
- input.validateValue(facesContext, null);
- checkValid();
- }
+ public void testValidateMinValue() throws Exception {
+ checkValid();
+ input.validateValue(facesContext, new Double(-23.45));
+ checkInvalid();
+ }
- public void testValidateMinValue() throws Exception {
- checkValid();
- input.validateValue(facesContext, new Double(-23.45));
- checkInvalid();
- }
+ public void testValidateMaxValue() throws Exception {
+ checkValid();
+ input.validateValue(facesContext, new Double(223.45));
+ checkInvalid();
+ }
- public void testValidateMaxValue() throws Exception {
- checkValid();
- input.validateValue(facesContext, new Double(223.45));
- checkInvalid();
- }
+ public void testValidateMinNullMinValue() throws Exception {
+ input.setMinValue(null);
+ checkValid();
+ input.validateValue(facesContext, new Double(-23.45));
+ checkInvalid();
+ }
+ public void testValidateMaxNullMaxValue() throws Exception {
+ input.setMaxValue(null);
+ checkValid();
+ input.validateValue(facesContext, new Double(223.45));
+ checkInvalid();
+ }
- public void testValidateMinNullMinValue() throws Exception {
- input.setMinValue(null);
- checkValid();
- input.validateValue(facesContext, new Double(-23.45));
- checkInvalid();
- }
-
- public void testValidateMaxNullMaxValue() throws Exception {
- input.setMaxValue(null);
- checkValid();
- input.validateValue(facesContext, new Double(223.45));
- checkInvalid();
- }
-
- public void testValidateIllegalValue() throws Exception {
- checkValid();
- input.validateValue(facesContext, "string");
- checkInvalid();
- }
+ public void testValidateIllegalValue() throws Exception {
+ checkValid();
+ input.validateValue(facesContext, "string");
+ checkInvalid();
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/component/nsutils/NSUtilsTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/component/nsutils/NSUtilsTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/component/nsutils/NSUtilsTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.nsutils;
import java.io.StringWriter;
@@ -29,32 +31,31 @@
import org.richfaces.test.AbstractFacesTest;
public class NSUtilsTest extends AbstractFacesTest {
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ public void testWriteNameSpace() throws Exception {
+ final StringWriter stringWriter = new StringWriter();
+ ResponseWriter writer = facesContext.getRenderKit().createResponseWriter(stringWriter, "text/html", "UTF-8");
- public void testWriteNameSpace() throws Exception {
- final StringWriter stringWriter = new StringWriter();
- ResponseWriter writer = facesContext.getRenderKit().createResponseWriter(stringWriter, "text/html", "UTF-8");
- facesContext.setResponseWriter(writer);
-
- UIInput input = new UIInput();
-
- writer.startDocument();
- writer.startElement("span", input);
-
- NSUtils.writeNameSpace(facesContext, input);
-
- writer.endElement("span");
- writer.endDocument();
+ facesContext.setResponseWriter(writer);
- String result = stringWriter.getBuffer().toString();
- assertTrue(result.contains("span xmlns:rich=\"http://richfaces.ajax4jsf.org/rich\""));
- }
+ UIInput input = new UIInput();
+
+ writer.startDocument();
+ writer.startElement("span", input);
+ NSUtils.writeNameSpace(facesContext, input);
+ writer.endElement("span");
+ writer.endDocument();
+
+ String result = stringWriter.getBuffer().toString();
+
+ assertTrue(result.contains("span xmlns:rich=\"http://richfaces.ajax4jsf.org/rich\""));
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/component/util/ComponentUtilTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/component/util/ComponentUtilTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/component/util/ComponentUtilTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -18,6 +18,9 @@
* 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.richfaces.component.util;
import java.util.ArrayList;
@@ -34,53 +37,57 @@
*
*/
public class ComponentUtilTest extends TestCase {
+ public void testAsArray() {
+ assertNull(ComponentUtil.asArray(null));
+ }
- public void testAsArray() {
- assertNull(ComponentUtil.asArray(null));
- }
+ public void testAsArray1() {
+ String[] strings = new String[] {"a", "b"};
+ String[] array = ComponentUtil.asArray(strings);
- public void testAsArray1() {
- String[] strings = new String[] {"a", "b"};
- String[] array = ComponentUtil.asArray(strings);
- assertSame(strings, array);
- }
+ assertSame(strings, array);
+ }
- public void testAsArray2() {
- Object[] objects = new Object[] {
- Integer.valueOf(12), null, Integer.valueOf(22), Integer.valueOf(42)
- };
- String[] array = ComponentUtil.asArray(objects);
- String[] etalon = new String[] {"12", null, "22", "42"};
- assertTrue(Arrays.equals(etalon, array));
- }
+ public void testAsArray2() {
+ Object[] objects = new Object[] {Integer.valueOf(12), null, Integer.valueOf(22), Integer.valueOf(42)};
+ String[] array = ComponentUtil.asArray(objects);
+ String[] etalon = new String[] {"12", null, "22", "42"};
- public void testAsArray3() {
- ArrayList list = new ArrayList();
- list.add(new Integer(12));
- list.add(null);
- list.add(new Integer(22));
- list.add(new Integer(42));
+ assertTrue(Arrays.equals(etalon, array));
+ }
- String[] array = ComponentUtil.asArray(list);
- String[] etalon = new String[] {"12", null, "22", "42"};
- assertTrue(Arrays.equals(etalon, array));
- }
+ public void testAsArray3() {
+ ArrayList list = new ArrayList();
- public void testAsArray31() {
- Set set = new TreeSet();
- set.add(new Integer(12));
- set.add(new Integer(22));
- set.add(new Integer(42));
+ list.add(new Integer(12));
+ list.add(null);
+ list.add(new Integer(22));
+ list.add(new Integer(42));
- String[] array = ComponentUtil.asArray(set);
- String[] etalon = new String[] {"12", "22", "42"};
- assertTrue(Arrays.equals(etalon, array));
- }
+ String[] array = ComponentUtil.asArray(list);
+ String[] etalon = new String[] {"12", null, "22", "42"};
- public void testAsArray4() {
- String string = " a , \t\n b \n , c ";
- String[] strings = ComponentUtil.asArray(string);
- String[] etalon = new String[] {"a", "b", "c"};
- assertTrue(Arrays.equals(etalon, strings));
- }
-}
\ No newline at end of file
+ assertTrue(Arrays.equals(etalon, array));
+ }
+
+ public void testAsArray31() {
+ Set set = new TreeSet();
+
+ set.add(new Integer(12));
+ set.add(new Integer(22));
+ set.add(new Integer(42));
+
+ String[] array = ComponentUtil.asArray(set);
+ String[] etalon = new String[] {"12", "22", "42"};
+
+ assertTrue(Arrays.equals(etalon, array));
+ }
+
+ public void testAsArray4() {
+ String string = " a , \t\n b \n , c ";
+ String[] strings = ComponentUtil.asArray(string);
+ String[] etalon = new String[] {"a", "b", "c"};
+
+ assertTrue(Arrays.equals(etalon, strings));
+ }
+}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/component/util/FormUtilTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/component/util/FormUtilTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/component/util/FormUtilTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.util;
import javax.faces.component.UIComponent;
@@ -32,54 +34,50 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 11.04.2007
- *
+ *
*/
public class FormUtilTest extends AbstractFacesTest {
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- @Override
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testThrowEnclFormReqExceptionIfNeed() throws Exception {
- UIViewRoot viewRoot = facesContext.getViewRoot();
- UIComponent form = application.createComponent(UIForm.COMPONENT_TYPE);
- viewRoot.getChildren().add(form);
-
- UIComponent testComponent = application.createComponent(UIOutput.COMPONENT_TYPE);
- form.getChildren().add(testComponent);
-
- FormUtil.throwEnclFormReqExceptionIfNeed(facesContext, testComponent);
- }
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- public void testThrowEnclFormReqExceptionIfNeedNoForm() throws Exception {
- UIViewRoot viewRoot = facesContext.getViewRoot();
+ public void testThrowEnclFormReqExceptionIfNeed() throws Exception {
+ UIViewRoot viewRoot = facesContext.getViewRoot();
+ UIComponent form = application.createComponent(UIForm.COMPONENT_TYPE);
- UIComponent testComponent = application.createComponent(UIOutput.COMPONENT_TYPE);
- viewRoot.getChildren().add(testComponent);
-
- try {
- FormUtil.throwEnclFormReqExceptionIfNeed(facesContext, testComponent);
+ viewRoot.getChildren().add(form);
- fail();
- } catch (EnclosingFormRequiredException e) {
+ UIComponent testComponent = application.createComponent(UIOutput.COMPONENT_TYPE);
- }
- }
+ form.getChildren().add(testComponent);
+ FormUtil.throwEnclFormReqExceptionIfNeed(facesContext, testComponent);
+ }
- public void testThrowEnclFormReqExceptionIfNeedClient() throws Exception {
- UIViewRoot viewRoot = facesContext.getViewRoot();
-
- UIComponent testComponent = application.createComponent(UIOutput.COMPONENT_TYPE);
- testComponent.getAttributes().put("switchType", "CLIENT");
- viewRoot.getChildren().add(testComponent);
-
- FormUtil.throwEnclFormReqExceptionIfNeed(facesContext, testComponent);
- }
+ public void testThrowEnclFormReqExceptionIfNeedNoForm() throws Exception {
+ UIViewRoot viewRoot = facesContext.getViewRoot();
+ UIComponent testComponent = application.createComponent(UIOutput.COMPONENT_TYPE);
+
+ viewRoot.getChildren().add(testComponent);
+
+ try {
+ FormUtil.throwEnclFormReqExceptionIfNeed(facesContext, testComponent);
+ fail();
+ } catch (EnclosingFormRequiredException e) {}
+ }
+
+ public void testThrowEnclFormReqExceptionIfNeedClient() throws Exception {
+ UIViewRoot viewRoot = facesContext.getViewRoot();
+ UIComponent testComponent = application.createComponent(UIOutput.COMPONENT_TYPE);
+
+ testComponent.getAttributes().put("switchType", "CLIENT");
+ viewRoot.getChildren().add(testComponent);
+ FormUtil.throwEnclFormReqExceptionIfNeed(facesContext, testComponent);
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/component/util/HtmlUtilTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/component/util/HtmlUtilTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/component/util/HtmlUtilTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.util;
import javax.faces.component.UIComponent;
@@ -30,83 +32,81 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 11.04.2007
- *
+ *
*/
public class HtmlUtilTest extends TestCase {
-
- public HtmlUtilTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testQualifySize() throws Exception {
- assertEquals("", HtmlUtil.qualifySize(""));
+ public HtmlUtilTest(String name) {
+ super(name);
+ }
- assertEquals("100px", HtmlUtil.qualifySize("100px"));
- assertEquals("100px", HtmlUtil.qualifySize("100"));
- assertEquals("100pt", HtmlUtil.qualifySize("100pt"));
+ public void setUp() throws Exception {
+ super.setUp();
+ }
- assertEquals("100in", HtmlUtil.qualifySize("100in"));
- assertEquals("100cm", HtmlUtil.qualifySize("100cm"));
- assertEquals("100em", HtmlUtil.qualifySize("100em"));
- assertEquals("100%", HtmlUtil.qualifySize("100%"));
- }
-
- public void testAddToSize() throws Exception {
- assertEquals("120px", HtmlUtil.addToSize("100", "20px"));
- assertEquals("120px", HtmlUtil.addToSize("100px", "20"));
- assertEquals("120px", HtmlUtil.addToSize("100", "20"));
- assertEquals("120px", HtmlUtil.addToSize("100px", "20px"));
- }
-
- public void testExpandIdSelector() {
- String selector = ".class_form+#-Test .class2 #_aaaa";
-
- UIComponent component = new UIComponentBase() {
- public String getFamily() {
- // TODO Auto-generated method stub
- return null;
- }
- public UIComponent findComponent(String expr) {
- if ("-Test".equals(expr)) {
- return new UIComponentBase() {
- public String getClientId(FacesContext context) {
- return "component1";
- }
- public String getFamily() {
- // TODO Auto-generated method stub
- return null;
- }
- };
- } else if ("_aaaa".equals(expr)) {
- return new UIComponentBase() {
- public String getClientId(FacesContext context) {
- return "component2";
- }
- public String getFamily() {
- // TODO Auto-generated method stub
- return null;
- }
- };
- }
-
- return null;
- }
- };
-
- String string =
- HtmlUtil.expandIdSelector(selector, component, null);
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- assertEquals(".class_form+#component1 .class2 #component2", string);
-
- String s = ".class_form+.component1 .class2 #1component2";
- assertEquals(s, HtmlUtil.expandIdSelector(s, component, null));
- }
+ public void testQualifySize() throws Exception {
+ assertEquals("", HtmlUtil.qualifySize(""));
+ assertEquals("100px", HtmlUtil.qualifySize("100px"));
+ assertEquals("100px", HtmlUtil.qualifySize("100"));
+ assertEquals("100pt", HtmlUtil.qualifySize("100pt"));
+ assertEquals("100in", HtmlUtil.qualifySize("100in"));
+ assertEquals("100cm", HtmlUtil.qualifySize("100cm"));
+ assertEquals("100em", HtmlUtil.qualifySize("100em"));
+ assertEquals("100%", HtmlUtil.qualifySize("100%"));
+ }
+
+ public void testAddToSize() throws Exception {
+ assertEquals("120px", HtmlUtil.addToSize("100", "20px"));
+ assertEquals("120px", HtmlUtil.addToSize("100px", "20"));
+ assertEquals("120px", HtmlUtil.addToSize("100", "20"));
+ assertEquals("120px", HtmlUtil.addToSize("100px", "20px"));
+ }
+
+ public void testExpandIdSelector() {
+ String selector = ".class_form+#-Test .class2 #_aaaa";
+ UIComponent component = new UIComponentBase() {
+ public String getFamily() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+ public UIComponent findComponent(String expr) {
+ if ("-Test".equals(expr)) {
+ return new UIComponentBase() {
+ public String getClientId(FacesContext context) {
+ return "component1";
+ }
+ public String getFamily() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+ };
+ } else if ("_aaaa".equals(expr)) {
+ return new UIComponentBase() {
+ public String getClientId(FacesContext context) {
+ return "component2";
+ }
+ public String getFamily() {
+
+ // TODO Auto-generated method stub
+ return null;
+ }
+ };
+ }
+
+ return null;
+ }
+ };
+ String string = HtmlUtil.expandIdSelector(selector, component, null);
+
+ assertEquals(".class_form+#component1 .class2 #component2", string);
+
+ String s = ".class_form+.component1 .class2 #1component2";
+
+ assertEquals(s, HtmlUtil.expandIdSelector(s, component, null));
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/javascript/QUnitTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/javascript/QUnitTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/javascript/QUnitTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,11 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.javascript;
import static org.junit.Assert.fail;
import java.net.URL;
+
import java.util.Iterator;
import org.junit.After;
@@ -41,14 +44,13 @@
* @author Konstantin Mishin
*/
public class QUnitTest {
-
private WebClient webClient_;
@Before
public void setUp() {
- webClient_ = new WebClient();
+ webClient_ = new WebClient();
}
-
+
@After
public void tearDown() {
webClient_.closeAllWindows();
@@ -60,33 +62,45 @@
HtmlElement doc = page.getDocumentElement();
HtmlElement tests = (HtmlElement) doc.getElementById("tests");
Iterator<HtmlElement> iter = tests.getChildElements().iterator();
+
if (!iter.hasNext()) {
fail("No result found");
}
+
StringBuilder sb = new StringBuilder();
- int i = 1;
- while (iter.hasNext()) {
+ int i = 1;
+
+ while (iter.hasNext()) {
final HtmlListItem testNode = (HtmlListItem) iter.next();
- if (testNode.getAttribute("class").contains("fail")) {
- sb.append(i).append(". ").append(testNode.<HtmlElement>getFirstByXPath("./strong").getFirstChild().getTextContent()).append("\n");
- int j = 1;
- for(HtmlElement li : testNode.<HtmlElement>getFirstByXPath("./ol").getChildElements()) {
- if (li.getAttribute("class").contains("fail")) {
- sb.append(" ").append(j).append(". ").append(li.getTextContent()).append("\n");
- }
- j++;
- }
- }
- i++;
+
+ if (testNode.getAttribute("class").contains("fail")) {
+ sb.append(i).append(". ").append(
+ testNode.<HtmlElement>getFirstByXPath("./strong").getFirstChild().getTextContent()).append("\n");
+
+ int j = 1;
+
+ for (HtmlElement li : testNode.<HtmlElement>getFirstByXPath("./ol").getChildElements()) {
+ if (li.getAttribute("class").contains("fail")) {
+ sb.append(" ").append(j).append(". ").append(li.getTextContent()).append("\n");
+ }
+
+ j++;
+ }
+ }
+
+ i++;
}
- if(sb.length() > 0) {
- fail("Failures:\n" + sb + "User Agent: " + doc.getElementById("userAgent").getTextContent());
- }
+
+ if (sb.length() > 0) {
+ fail("Failures:\n" + sb + "User Agent: " + doc.getElementById("userAgent").getTextContent());
+ }
}
protected HtmlPage loadPage(URL url) throws Exception {
HtmlPage page = webClient_.getPage(url);
+
webClient_.waitForBackgroundJavaScriptStartingBefore(4 * 60 * 1000);
+
return page;
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/json/JsonTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/json/JsonTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/json/JsonTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -1,5 +1,6 @@
+
/**
- *
+ *
*/
package org.richfaces.json;
@@ -15,152 +16,156 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
* created 12.04.2007
- *
+ *
*/
public class JsonTest extends TestCase {
- /**
- * @param name
- */
- public JsonTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public JsonTest(String name) {
+ super(name);
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- public void testMap() throws Exception {
- JSONMap map = new JSONMap("{text: 12, moreData: { key: value, key1: 23.04 }}");
- assertEquals(12, ((Integer) map.get("text")).intValue());
- assertEquals(2, map.size());
-
- Map innerMap = (Map) map.get("moreData");
- assertEquals("value", innerMap.get("key"));
- assertEquals(23.04, ((Double) innerMap.get("key1")).doubleValue(), 0);
- assertEquals(2, innerMap.size());
- }
+ public void testMap() throws Exception {
+ JSONMap map = new JSONMap("{text: 12, moreData: { key: value, key1: 23.04 }}");
- public void testCollection() throws Exception {
- JSONCollection collection = new JSONCollection("[text, { key: value, key1: 23.04 }, [1, a, 3]]");
- assertEquals(3, collection.size());
+ assertEquals(12, ((Integer) map.get("text")).intValue());
+ assertEquals(2, map.size());
- Iterator iterator = collection.iterator();
- assertTrue(iterator.hasNext());
-
- assertEquals("text", iterator.next());
- assertTrue(iterator.hasNext());
-
- Map innerMap = (Map) iterator.next();
- assertTrue(iterator.hasNext());
+ Map innerMap = (Map) map.get("moreData");
- assertEquals("value", innerMap.get("key"));
- assertEquals(23.04, ((Double) innerMap.get("key1")).doubleValue(), 0);
- assertEquals(2, innerMap.size());
-
- Collection innerCollection = (Collection) iterator.next();
- assertEquals(3, innerCollection.size());
- Iterator innerIterator = innerCollection.iterator();
-
- assertTrue(innerIterator.hasNext());
- assertEquals(1, ((Integer) innerIterator.next()).intValue());
- assertTrue(innerIterator.hasNext());
- assertEquals("a", innerIterator.next());
- assertTrue(innerIterator.hasNext());
- assertEquals(3, ((Integer) innerIterator.next()).intValue());
- assertFalse(innerIterator.hasNext());
-
- assertFalse(iterator.hasNext());
- }
+ assertEquals("value", innerMap.get("key"));
+ assertEquals(23.04, ((Double) innerMap.get("key1")).doubleValue(), 0);
+ assertEquals(2, innerMap.size());
+ }
- public void testNewCollection() throws Exception {
- JSONCollection collection = new JSONCollection();
- assertTrue(collection.isEmpty());
- }
+ public void testCollection() throws Exception {
+ JSONCollection collection = new JSONCollection("[text, { key: value, key1: 23.04 }, [1, a, 3]]");
- public void testNewMap() throws Exception {
- JSONMap map = new JSONMap();
- assertTrue(map.isEmpty());
- }
-
- public void testMapAddiition() throws Exception {
- JSONMap map = new JSONMap();
- Set set = map.entrySet();
- set.add(new JsonTestMockMapEntry("boolean", new Boolean(true)));
- set.add(new JsonTestMockMapEntry("double", new Double(23.45)));
- set.add(new JsonTestMockMapEntry("integer", new Integer(56)));
- set.add(new JsonTestMockMapEntry("long", new Long(89)));
- set.add(new JsonTestMockMapEntry("string", "testString"));
+ assertEquals(3, collection.size());
- HashSet hashSet = new HashSet();
+ Iterator iterator = collection.iterator();
- hashSet.add("15");
- hashSet.add(new Double(45.01));
-
- HashSet etalonSet = (HashSet) hashSet.clone();
+ assertTrue(iterator.hasNext());
+ assertEquals("text", iterator.next());
+ assertTrue(iterator.hasNext());
-
- HashMap hashMap = new HashMap();
+ Map innerMap = (Map) iterator.next();
- hashMap.put("16", new Boolean(false));
- hashMap.put("key", new Double(145.01));
-
- HashMap etalonMap = (HashMap) hashMap.clone();
+ assertTrue(iterator.hasNext());
+ assertEquals("value", innerMap.get("key"));
+ assertEquals(23.04, ((Double) innerMap.get("key1")).doubleValue(), 0);
+ assertEquals(2, innerMap.size());
- set.add(new JsonTestMockMapEntry("collection", hashSet));
- set.add(new JsonTestMockMapEntry("map", hashMap));
-
- assertEquals(Boolean.TRUE, map.get("boolean"));
- assertEquals(new Double(23.45), map.get("double"));
- assertEquals(new Integer(56), map.get("integer"));
- assertEquals(new Long(89), map.get("long"));
- assertEquals("testString", map.get("string"));
-
- Collection collection = (Collection) map.get("collection");
- assertTrue(etalonSet.containsAll(collection));
- etalonSet.removeAll(collection);
- assertTrue(etalonSet.isEmpty());
-
- assertEquals(etalonMap, map.get("map"));
- }
+ Collection innerCollection = (Collection) iterator.next();
+ assertEquals(3, innerCollection.size());
+
+ Iterator innerIterator = innerCollection.iterator();
+
+ assertTrue(innerIterator.hasNext());
+ assertEquals(1, ((Integer) innerIterator.next()).intValue());
+ assertTrue(innerIterator.hasNext());
+ assertEquals("a", innerIterator.next());
+ assertTrue(innerIterator.hasNext());
+ assertEquals(3, ((Integer) innerIterator.next()).intValue());
+ assertFalse(innerIterator.hasNext());
+ assertFalse(iterator.hasNext());
+ }
+
+ public void testNewCollection() throws Exception {
+ JSONCollection collection = new JSONCollection();
+
+ assertTrue(collection.isEmpty());
+ }
+
+ public void testNewMap() throws Exception {
+ JSONMap map = new JSONMap();
+
+ assertTrue(map.isEmpty());
+ }
+
+ public void testMapAddiition() throws Exception {
+ JSONMap map = new JSONMap();
+ Set set = map.entrySet();
+
+ set.add(new JsonTestMockMapEntry("boolean", new Boolean(true)));
+ set.add(new JsonTestMockMapEntry("double", new Double(23.45)));
+ set.add(new JsonTestMockMapEntry("integer", new Integer(56)));
+ set.add(new JsonTestMockMapEntry("long", new Long(89)));
+ set.add(new JsonTestMockMapEntry("string", "testString"));
+
+ HashSet hashSet = new HashSet();
+
+ hashSet.add("15");
+ hashSet.add(new Double(45.01));
+
+ HashSet etalonSet = (HashSet) hashSet.clone();
+ HashMap hashMap = new HashMap();
+
+ hashMap.put("16", new Boolean(false));
+ hashMap.put("key", new Double(145.01));
+
+ HashMap etalonMap = (HashMap) hashMap.clone();
+
+ set.add(new JsonTestMockMapEntry("collection", hashSet));
+ set.add(new JsonTestMockMapEntry("map", hashMap));
+ assertEquals(Boolean.TRUE, map.get("boolean"));
+ assertEquals(new Double(23.45), map.get("double"));
+ assertEquals(new Integer(56), map.get("integer"));
+ assertEquals(new Long(89), map.get("long"));
+ assertEquals("testString", map.get("string"));
+
+ Collection collection = (Collection) map.get("collection");
+
+ assertTrue(etalonSet.containsAll(collection));
+ etalonSet.removeAll(collection);
+ assertTrue(etalonSet.isEmpty());
+ assertEquals(etalonMap, map.get("map"));
+ }
}
+
class JsonTestMockMapEntry implements Map.Entry {
+ private Object key;
+ private Object value;
- private Object key;
- private Object value;
-
-
-
- public JsonTestMockMapEntry(Object key, Object value) {
- super();
- this.key = key;
- this.value = value;
- }
+ public JsonTestMockMapEntry(Object key, Object value) {
+ super();
+ this.key = key;
+ this.value = value;
+ }
- public Object getKey() {
- return key;
- }
+ public Object getKey() {
+ return key;
+ }
- public Object getValue() {
- return value;
- }
+ public Object getValue() {
+ return value;
+ }
- public Object setValue(Object newValue) {
- Object oldValue = value;
- value = newValue;
- return oldValue;
- }
-
-}
\ No newline at end of file
+ public Object setValue(Object newValue) {
+ Object oldValue = value;
+
+ value = newValue;
+
+ return oldValue;
+ }
+}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/json/SerializationTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/json/SerializationTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/json/SerializationTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.json;
import java.io.ByteArrayInputStream;
@@ -26,6 +28,7 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
+
import java.util.Iterator;
import junit.framework.TestCase;
@@ -34,78 +37,81 @@
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class SerializationTest extends TestCase {
-
- private <T> T saveRestore(T t) throws IOException, ClassNotFoundException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(t);
- oos.close();
-
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
- T restoredT = (T) t.getClass().cast(ois.readObject());
-
- return restoredT;
- }
-
- public void testJSONObject() throws Exception {
- JSONObject restoredObject = saveRestore(
- new JSONObject("{a:null, b:'abc', c: {d: 'e', f: 'g'}, h: ['i', 'j']}"));
+ private <T> T saveRestore(T t) throws IOException, ClassNotFoundException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
- assertSame(JSONObject.NULL, restoredObject.get("a"));
- assertEquals("abc", restoredObject.get("b"));
-
- JSONObject nestedObject = (JSONObject) restoredObject.get("c");
- assertEquals("e", nestedObject.get("d"));
- assertEquals("g", nestedObject.get("f"));
-
- JSONArray array = (JSONArray) restoredObject.get("h");
- assertEquals(2, array.length());
- assertEquals("i", array.get(0));
- assertEquals("j", array.get(1));
-
- }
-
- public void testJSONCollection() throws Exception {
- JSONCollection restored = saveRestore(new JSONCollection("[1, '2', null, [3, 4], {a: 'b', c: 'd'}]"));
- Iterator iterator = restored.iterator();
-
- assertEquals(Integer.valueOf(1), iterator.next());
- assertEquals("2", iterator.next());
- assertSame(JSONObject.NULL, iterator.next());
+ oos.writeObject(t);
+ oos.close();
- JSONCollection nestedCollection = (JSONCollection) iterator.next();
- Iterator nestedIterator = nestedCollection.iterator();
- assertEquals(Integer.valueOf(3), nestedIterator.next());
- assertEquals(Integer.valueOf(4), nestedIterator.next());
- assertFalse(nestedIterator.hasNext());
-
- JSONMap nestedMap = (JSONMap) iterator.next();
- assertEquals("b", nestedMap.get("a"));
- assertEquals("d", nestedMap.get("c"));
- assertEquals(2, nestedMap.size());
-
- assertFalse(iterator.hasNext());
- }
-
- public void testJSONMap() throws Exception {
- JSONMap restored = saveRestore(new JSONMap("{a: 'b', c: 3, d: null, e: [5, 'v'], f: {x: 'y', z: 2}}"));
- assertEquals("b", restored.get("a"));
- assertEquals(Integer.valueOf(3), restored.get("c"));
- assertSame(JSONObject.NULL, restored.get("d"));
-
- JSONCollection nestedCollection = (JSONCollection) restored.get("e");
- Iterator nestedIterator = nestedCollection.iterator();
- assertEquals(Integer.valueOf(5), nestedIterator.next());
- assertEquals("v", nestedIterator.next());
- assertFalse(nestedIterator.hasNext());
-
- JSONMap nestedObject = (JSONMap) restored.get("f");
- assertEquals("y", nestedObject.get("x"));
- assertEquals(Integer.valueOf(2), nestedObject.get("z"));
- assertEquals(2, nestedObject.size());
-
- assertEquals(5, restored.size());
- }
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
+ T restoredT = (T) t.getClass().cast(ois.readObject());
+
+ return restoredT;
+ }
+
+ public void testJSONObject() throws Exception {
+ JSONObject restoredObject =
+ saveRestore(new JSONObject("{a:null, b:'abc', c: {d: 'e', f: 'g'}, h: ['i', 'j']}"));
+
+ assertSame(JSONObject.NULL, restoredObject.get("a"));
+ assertEquals("abc", restoredObject.get("b"));
+
+ JSONObject nestedObject = (JSONObject) restoredObject.get("c");
+
+ assertEquals("e", nestedObject.get("d"));
+ assertEquals("g", nestedObject.get("f"));
+
+ JSONArray array = (JSONArray) restoredObject.get("h");
+
+ assertEquals(2, array.length());
+ assertEquals("i", array.get(0));
+ assertEquals("j", array.get(1));
+ }
+
+ public void testJSONCollection() throws Exception {
+ JSONCollection restored = saveRestore(new JSONCollection("[1, '2', null, [3, 4], {a: 'b', c: 'd'}]"));
+ Iterator iterator = restored.iterator();
+
+ assertEquals(Integer.valueOf(1), iterator.next());
+ assertEquals("2", iterator.next());
+ assertSame(JSONObject.NULL, iterator.next());
+
+ JSONCollection nestedCollection = (JSONCollection) iterator.next();
+ Iterator nestedIterator = nestedCollection.iterator();
+
+ assertEquals(Integer.valueOf(3), nestedIterator.next());
+ assertEquals(Integer.valueOf(4), nestedIterator.next());
+ assertFalse(nestedIterator.hasNext());
+
+ JSONMap nestedMap = (JSONMap) iterator.next();
+
+ assertEquals("b", nestedMap.get("a"));
+ assertEquals("d", nestedMap.get("c"));
+ assertEquals(2, nestedMap.size());
+ assertFalse(iterator.hasNext());
+ }
+
+ public void testJSONMap() throws Exception {
+ JSONMap restored = saveRestore(new JSONMap("{a: 'b', c: 3, d: null, e: [5, 'v'], f: {x: 'y', z: 2}}"));
+
+ assertEquals("b", restored.get("a"));
+ assertEquals(Integer.valueOf(3), restored.get("c"));
+ assertSame(JSONObject.NULL, restored.get("d"));
+
+ JSONCollection nestedCollection = (JSONCollection) restored.get("e");
+ Iterator nestedIterator = nestedCollection.iterator();
+
+ assertEquals(Integer.valueOf(5), nestedIterator.next());
+ assertEquals("v", nestedIterator.next());
+ assertFalse(nestedIterator.hasNext());
+
+ JSONMap nestedObject = (JSONMap) restored.get("f");
+
+ assertEquals("y", nestedObject.get("x"));
+ assertEquals(Integer.valueOf(2), nestedObject.get("z"));
+ assertEquals(2, nestedObject.size());
+ assertEquals(5, restored.size());
+ }
}
Copied: root/framework/trunk/impl/src/test/java/org/richfaces/json/Test.java (from rev 15745, root/framework/trunk/impl/src/main/java/org/richfaces/json/Test.java)
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/json/Test.java (rev 0)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/json/Test.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -0,0 +1,410 @@
+/**
+ * License Agreement.
+ *
+ * JBoss RichFaces - Ajax4jsf Component Library
+ *
+ * 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.richfaces.json;
+
+import junit.framework.TestCase;
+
+import java.io.StringWriter;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.junit.Ignore;
+
+/**
+ * Test class. This file is not formally a member of the org.json library.
+ * It is just a casual test tool.
+ *
+ * TODO Refactoring
+ */
+@Ignore
+public class Test extends TestCase {
+ public void testMain() {
+ Iterator it;
+ JSONArray a;
+ JSONObject j;
+ JSONStringer jj;
+ String s;
+
+// Obj is a typical class that implements JSONString.
+ try {
+ String[] sa = {"aString", "aNumber", "aBoolean"};
+ Obj obj = new Obj("A string, a number, and a boolean", 42, true);
+
+ j = XML.toJSONObject("<![CDATA[This is a collection of test patterns and examples for org.json.]]>");
+ System.out.println(j.toString());
+ jj = new JSONStringer();
+ s = jj.object().key("foo").value("bar").key("baz").array().object().key("quux").value(
+ "Thanks, Josh!").endObject().endArray().endObject().toString();
+ System.out.println(s);
+ System.out.println(
+ new JSONStringer().object().key("a").array().array().array().value(
+ "b").endArray().endArray().endArray().endObject().toString());
+ jj = new JSONStringer();
+ jj.array();
+ jj.value(1);
+ jj.array();
+ jj.value(null);
+ jj.array();
+ jj.object();
+ jj.key("empty-array").array().endArray();
+ jj.key("answer").value(42);
+ jj.key("null").value(null);
+ jj.key("false").value(false);
+ jj.key("true").value(true);
+ jj.key("big").value(123456789e+88);
+ jj.key("small").value(123456789e-88);
+ jj.key("empty-object").object().endObject();
+ jj.key("long");
+ jj.value(9223372036854775807L);
+ jj.endObject();
+ jj.value("two");
+ jj.endArray();
+ jj.value(true);
+ jj.endArray();
+ jj.value(98.6);
+ jj.value(-100.0);
+ jj.object();
+ jj.endObject();
+ jj.object();
+ jj.key("one");
+ jj.value(1.00);
+ jj.endObject();
+ jj.value(obj);
+ jj.endArray();
+ System.out.println(jj.toString());
+ System.out.println(new JSONArray(jj.toString()).toString(4));
+ j = new JSONObject(obj, sa);
+ j.put("test", obj);
+ j.put("comment", "This object contains a test object that implements JSONString");
+ System.out.println(j.toString(4));
+ j = new JSONObject(
+ "{slashes: '///', closetag: '</script>', backslash:'\\\\', ei: {quotes: '\"\\''},eo: {a: '\"quoted\"', b:\"don't\"}, quotes: [\"'\", '\"']}");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = new JSONObject(
+ "/*comment*/{foo: [true, false,9876543210, 0.0, 1.00000001, 1.000000000001, 1.00000000000000001,"
+ + " .00000000000000001, 2.00, 0.1, 2e100, -32,[],{}, \"string\"], " + " to : null, op : 'Good',"
+ + "ten:10} postfix comment");
+ j.put("String", "98.6");
+ j.put("JSONObject", new JSONObject());
+ j.put("JSONArray", new JSONArray());
+ j.put("int", 57);
+ j.put("double", 123456789012345678901234567890.);
+ j.put("true", true);
+ j.put("false", false);
+ j.put("null", JSONObject.NULL);
+ j.put("bool", "true");
+ j.put("zero", -0.0);
+ a = j.getJSONArray("foo");
+ a.put(666);
+ a.put(2001.99);
+ a.put("so \"fine\".");
+ a.put("so <fine>.");
+ a.put(true);
+ a.put(false);
+ a.put(new JSONArray());
+ a.put(new JSONObject());
+ System.out.println(j.toString(4));
+ System.out.println(XML.toString(j));
+ System.out.println("String: " + j.getDouble("String"));
+ System.out.println(" bool: " + j.getBoolean("bool"));
+ System.out.println(" to: " + j.getString("to"));
+ System.out.println(" true: " + j.getString("true"));
+ System.out.println(" foo: " + j.getJSONArray("foo"));
+ System.out.println(" op: " + j.getString("op"));
+ System.out.println(" ten: " + j.getInt("ten"));
+ System.out.println(" oops: " + j.optBoolean("oops"));
+ j = XML.toJSONObject(
+ "<xml one = 1 two=' \"2\" '><five></five>First \u0009<content><five></five> This is \"content\". <three> 3 </three>JSON does not preserve the sequencing of elements and contents.<three> III </three> <three> T H R E E</three><four/>Content text is an implied structure in XML. <six content=\"6\"/>JSON does not have implied structure:<seven>7</seven>everything is explicit.<![CDATA[CDATA blocks<are><supported>!]]></xml>");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = XML.toJSONObject(
+ "<mapping><empty/> <class name = \"Customer\"> <field name = \"ID\" type = \"string\"> <bind-xml name=\"ID\" node=\"attribute\"/> </field> <field name = \"FirstName\" type = \"FirstName\"/> <field name = \"MI\" type = \"MI\"/> <field name = \"LastName\" type = \"LastName\"/> </class> <class name = \"FirstName\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class> <class name = \"MI\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class> <class name = \"LastName\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class></mapping>");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = XML.toJSONObject(
+ "<?xml version=\"1.0\" ?><Book Author=\"Anonymous\"><Title>Sample Book</Title><Chapter id=\"1\">This is chapter 1. It is not very long or interesting.</Chapter><Chapter id=\"2\">This is chapter 2. Although it is longer than chapter 1, it is not any more interesting.</Chapter></Book>");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = XML.toJSONObject(
+ "<!DOCTYPE bCard 'http://www.cs.caltech.edu/~adam/schemas/bCard'><bCard><?xml default bCard firstname = '' lastname = '' company = '' email = '' homepage = ''?><bCard firstname = 'Rohit' lastname = 'Khare' company = 'MCI' email = 'khare(a)mci.net' homepage = 'http://pest.w3.org/'/><bCard firstname = 'Adam' lastname = 'Rifkin' company = 'Caltech Infospheres Project' email = 'adam(a)cs.caltech.edu' homepage = 'http://www.cs.caltech.edu/~adam/'/></bCard>");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = XML.toJSONObject(
+ "<?xml version=\"1.0\"?><customer> <firstName> <text>Fred</text> </firstName> <ID>fbs0001</ID> <lastName> <text>Scerbo</text> </lastName> <MI> <text>B</text> </MI></customer>");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = XML.toJSONObject(
+ "<!ENTITY tp-address PUBLIC '-//ABC University::Special Collections Library//TEXT (titlepage: name and address)//EN' 'tpspcoll.sgm'><list type='simple'><head>Repository Address </head><item>Special Collections Library</item><item>ABC University</item><item>Main Library, 40 Circle Drive</item><item>Ourtown, Pennsylvania</item><item>17654 USA</item></list>");
+ System.out.println(j.toString());
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = XML.toJSONObject(
+ "<test intertag status=ok><empty/>deluxe<blip sweet=true>&"toot"&toot;A</blip><x>eks</x><w>bonus</w><w>bonus2</w></test>");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = HTTP.toJSONObject(
+ "GET / HTTP/1.0\nAccept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\nAccept-Language: en-us\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90; T312461; Q312461)\nHost: www.nokko.com\nConnection: keep-alive\nAccept-encoding: gzip, deflate\n");
+ System.out.println(j.toString(2));
+ System.out.println(HTTP.toString(j));
+ System.out.println("");
+ j = HTTP.toJSONObject(
+ "HTTP/1.1 200 Oki Doki\nDate: Sun, 26 May 2002 17:38:52 GMT\nServer: Apache/1.3.23 (Unix) mod_perl/1.26\nKeep-Alive: timeout=15, max=100\nConnection: Keep-Alive\nTransfer-Encoding: chunked\nContent-Type: text/html\n");
+ System.out.println(j.toString(2));
+ System.out.println(HTTP.toString(j));
+ System.out.println("");
+ j = new JSONObject(
+ "{nix: null, nux: false, null: 'null', 'Request-URI': '/', Method: 'GET', 'HTTP-Version': 'HTTP/1.0'}");
+ System.out.println(j.toString(2));
+ System.out.println("isNull: " + j.isNull("nix"));
+ System.out.println(" has: " + j.has("nix"));
+ System.out.println(XML.toString(j));
+ System.out.println(HTTP.toString(j));
+ System.out.println("");
+ j = XML.toJSONObject("<?xml version='1.0' encoding='UTF-8'?>" + "\n\n" + "<SOAP-ENV:Envelope"
+ + " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ + " xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\""
+ + " xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\">"
+ + "<SOAP-ENV:Body><ns1:doGoogleSearch" + " xmlns:ns1=\"urn:GoogleSearch\""
+ + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+ + "<key xsi:type=\"xsd:string\">GOOGLEKEY</key> <q"
+ + " xsi:type=\"xsd:string\">'+search+'</q> <start"
+ + " xsi:type=\"xsd:int\">0</start> <maxResults"
+ + " xsi:type=\"xsd:int\">10</maxResults> <filter"
+ + " xsi:type=\"xsd:boolean\">true</filter> <restrict"
+ + " xsi:type=\"xsd:string\"></restrict> <safeSearch"
+ + " xsi:type=\"xsd:boolean\">false</safeSearch> <lr"
+ + " xsi:type=\"xsd:string\"></lr> <ie" + " xsi:type=\"xsd:string\">latin1</ie> <oe"
+ + " xsi:type=\"xsd:string\">latin1</oe>" + "</ns1:doGoogleSearch>"
+ + "</SOAP-ENV:Body></SOAP-ENV:Envelope>");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = new JSONObject(
+ "{Envelope: {Body: {\"ns1:doGoogleSearch\": {oe: \"latin1\", filter: true, q: \"'+search+'\", key: \"GOOGLEKEY\", maxResults: 10, \"SOAP-ENV:encodingStyle\": \"http://schemas.xmlsoap.org/soap/encoding/\", start: 0, ie: \"latin1\", safeSearch:false, \"xmlns:ns1\": \"urn:GoogleSearch\"}}}}");
+ System.out.println(j.toString(2));
+ System.out.println(XML.toString(j));
+ System.out.println("");
+ j = CookieList.toJSONObject(" f%oo = b+l=ah ; o;n%40e = t.wo ");
+ System.out.println(j.toString(2));
+ System.out.println(CookieList.toString(j));
+ System.out.println("");
+ j = Cookie.toJSONObject("f%oo=blah; secure ;expires = April 24, 2002");
+ System.out.println(j.toString(2));
+ System.out.println(Cookie.toString(j));
+ System.out.println("");
+ j = new JSONObject(
+ "{script: 'It is not allowed in HTML to send a close script tag in a string<script>because it confuses browsers</script>so we insert a backslash before the /'}");
+ System.out.println(j.toString());
+ System.out.println("");
+
+ JSONTokener jt = new JSONTokener("{op:'test', to:'session', pre:1}{op:'test', to:'session', pre:2}");
+
+ j = new JSONObject(jt);
+ System.out.println(j.toString());
+ System.out.println("pre: " + j.optInt("pre"));
+
+ int i = jt.skipTo('{');
+
+ System.out.println(i);
+ j = new JSONObject(jt);
+ System.out.println(j.toString());
+ System.out.println("");
+ a = CDL.toJSONArray(
+ "No quotes, 'Single Quotes', \"Double Quotes\"\n1,'2',\"3\"\n,'It is \"good,\"', \"It works.\"\n\n");
+ System.out.println(CDL.toString(a));
+ System.out.println("");
+ System.out.println(a.toString(4));
+ System.out.println("");
+ a = new JSONArray(" [\"<escape>\", next is an implied null , , ok,] ");
+ System.out.println(a.toString());
+ System.out.println("");
+ System.out.println(XML.toString(a));
+ System.out.println("");
+ j = new JSONObject(
+ "{ fun => with non-standard forms ; forgiving => This package can be used to parse formats that are similar to but not stricting conforming to JSON; why=To make it easier to migrate existing data to JSON,one = [[1.00]]; uno=[[{1=>1}]];'+':+6e66 ;pluses=+++;empty = '' , 'double':0.666,true: TRUE, false: FALSE, null=NULL;[true] = [[!,@;*]]; string=> o. k. ; # comment\r oct=0666; hex=0x666; dec=666; o=0999; noh=0x0x}");
+ System.out.println(j.toString(4));
+ System.out.println("");
+
+ if (j.getBoolean("true") && !j.getBoolean("false")) {
+ System.out.println("It's all good");
+ }
+
+ System.out.println("");
+ j = new JSONObject(j, new String[] {"dec", "oct", "hex", "missing"});
+ System.out.println(j.toString(4));
+ System.out.println("");
+ System.out.println(new JSONStringer().array().value(a).value(j).endArray());
+ j = new JSONObject(
+ "{string: \"98.6\", long: 2147483648, int: 2147483647, longer: 9223372036854775807, double: 9223372036854775808}");
+ System.out.println(j.toString(4));
+ System.out.println("\ngetInt");
+ System.out.println("int " + j.getInt("int"));
+ System.out.println("long " + j.getInt("long"));
+ System.out.println("longer " + j.getInt("longer"));
+ System.out.println("double " + j.getInt("double"));
+ System.out.println("string " + j.getInt("string"));
+ System.out.println("\ngetLong");
+ System.out.println("int " + j.getLong("int"));
+ System.out.println("long " + j.getLong("long"));
+ System.out.println("longer " + j.getLong("longer"));
+ System.out.println("double " + j.getLong("double"));
+ System.out.println("string " + j.getLong("string"));
+ System.out.println("\ngetDouble");
+ System.out.println("int " + j.getDouble("int"));
+ System.out.println("long " + j.getDouble("long"));
+ System.out.println("longer " + j.getDouble("longer"));
+ System.out.println("double " + j.getDouble("double"));
+ System.out.println("string " + j.getDouble("string"));
+ j.put("good sized", 9223372036854775807L);
+ System.out.println(j.toString(4));
+ a = new JSONArray("[2147483647, 2147483648, 9223372036854775807, 9223372036854775808]");
+ System.out.println(a.toString(4));
+ System.out.println("\nKeys: ");
+ it = j.keys();
+
+ while (it.hasNext()) {
+ s = (String) it.next();
+ System.out.println(s + ": " + j.getString(s));
+ }
+
+ System.out.println("\naccumulate: ");
+ j = new JSONObject();
+ j.accumulate("stooge", "Curly");
+ j.accumulate("stooge", "Larry");
+ j.accumulate("stooge", "Moe");
+ a = j.getJSONArray("stooge");
+ a.put(5, "Shemp");
+ System.out.println(j.toString(4));
+ System.out.println("\nwrite:");
+ System.out.println(j.write(new StringWriter()));
+ s = "<xml empty><a></a><a>1</a><a>22</a><a>333</a></xml>";
+ j = XML.toJSONObject(s);
+ System.out.println(j.toString(4));
+ System.out.println(XML.toString(j));
+ s = "<book><chapter>Content of the first chapter</chapter><chapter>Content of the second chapter <chapter>Content of the first subchapter</chapter> <chapter>Content of the second subchapter</chapter></chapter><chapter>Third Chapter</chapter></book>";
+ j = XML.toJSONObject(s);
+ System.out.println(j.toString(4));
+ System.out.println(XML.toString(j));
+
+ Collection c = null;
+ Map m = null;
+
+ j = new JSONObject(m);
+ a = new JSONArray(c);
+ j.append("stooge", "Joe DeRita");
+ j.append("stooge", "Shemp");
+ j.accumulate("stooges", "Curly");
+ j.accumulate("stooges", "Larry");
+ j.accumulate("stooges", "Moe");
+ j.accumulate("stoogearray", j.get("stooges"));
+ j.put("map", m);
+ j.put("collection", c);
+ j.put("array", a);
+ a.put(m);
+ a.put(c);
+ System.out.println(j.toString(4));
+ System.out.println("\nTesting Exceptions: ");
+ System.out.print("Exception: ");
+
+ try {
+ System.out.println(j.getDouble("stooge"));
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+ System.out.print("Exception: ");
+
+ try {
+ System.out.println(j.getDouble("howard"));
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+ System.out.print("Exception: ");
+
+ try {
+ System.out.println(j.put(null, "howard"));
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+ System.out.print("Exception: ");
+
+ try {
+ System.out.println(a.getDouble(0));
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+ System.out.print("Exception: ");
+
+ try {
+ System.out.println(a.get(-1));
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+
+ System.out.print("Exception: ");
+
+ try {
+ System.out.println(a.put(Double.NaN));
+ } catch (Exception e) {
+ System.out.println(e);
+ }
+ } catch (Exception e) {
+ System.out.println(e.toString());
+ }
+ }
+
+ class Obj implements JSONString {
+ private boolean aBoolean;
+ private double aNumber;
+ private String aString;
+
+ public Obj(String string, double n, boolean b) {
+ this.aString = string;
+ this.aNumber = n;
+ this.aBoolean = b;
+ }
+
+ public String toJSONString() {
+ return "{" + JSONObject.quote(this.aString) + ":" + JSONObject.doubleToString(this.aNumber) + "}";
+ }
+
+ @Override
+ public String toString() {
+ return this.aString + " " + this.aNumber + " " + this.aBoolean;
+ }
+ }
+}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/CompositeRendererTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/CompositeRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/CompositeRendererTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -2,6 +2,7 @@
import java.io.IOException;
import java.io.StringWriter;
+
import java.util.Arrays;
import java.util.Map;
@@ -15,369 +16,354 @@
import org.richfaces.test.AbstractFacesTest;
public class CompositeRendererTest extends AbstractFacesTest {
+ private CompositeRenderer compositeRenderer;
- private CompositeRenderer compositeRenderer;
-
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
-
- this.compositeRenderer = new CompositeRenderer() {
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ this.compositeRenderer = new CompositeRenderer() {
+ protected Class getComponentClass() {
+ return UIComponent.class;
+ }
+ };
+ }
- protected Class getComponentClass() {
- return UIComponent.class;
- }
- };
- }
+ public void tearDown() throws Exception {
+ super.tearDown();
+ this.compositeRenderer = null;
+ }
- public void tearDown() throws Exception {
- super.tearDown();
+ public final void testDoDecodeFacesContextUIComponent() {
+ MockDecodeContributor[] contributors = new MockDecodeContributor[5];
- this.compositeRenderer = null;
- }
+ for (int i = 0; i < contributors.length; i++) {
+ contributors[i] = new MockDecodeContributor();
+ compositeRenderer.addContributor(contributors[i]);
+ }
- public final void testDoDecodeFacesContextUIComponent() {
- MockDecodeContributor[] contributors = new MockDecodeContributor[5];
- for (int i = 0; i < contributors.length; i++) {
- contributors[i] = new MockDecodeContributor();
- compositeRenderer.addContributor(contributors[i]);
- }
-
- UIInput component = new UIInput();
- compositeRenderer.doDecode(facesContext, component);
+ UIInput component = new UIInput();
- for (int i = 0; i < contributors.length; i++) {
- assertSame(compositeRenderer, contributors[i].getRenderer());
- assertSame(facesContext, contributors[i].getContext());
- assertSame(component, contributors[i].getComponent());
- }
- }
+ compositeRenderer.doDecode(facesContext, component);
- public final void testMergeScriptOptionsScriptOptionsFacesContextUIComponent() {
- UIInput input = new UIInput();
+ for (int i = 0; i < contributors.length; i++) {
+ assertSame(compositeRenderer, contributors[i].getRenderer());
+ assertSame(facesContext, contributors[i].getContext());
+ assertSame(component, contributors[i].getComponent());
+ }
+ }
- ScriptOptions inputOptions = new ScriptOptions(input);
- inputOptions.addOption("input", "1");
-
- ScriptOptions formOptions = new ScriptOptions(input);
- formOptions.addOption("form", "2");
-
- ScriptOptions options = new ScriptOptions(input);
- options.addOption("generic", "3");
-
- MockDecodeContributor inputContributor;
- MockDecodeContributor formContributor;
- MockDecodeContributor contributor;
- MockDecodeContributor nullContributor;
+ public final void testMergeScriptOptionsScriptOptionsFacesContextUIComponent() {
+ UIInput input = new UIInput();
+ ScriptOptions inputOptions = new ScriptOptions(input);
- inputContributor = new MockDecodeContributor(UIComponent.class, inputOptions);
- formContributor = new MockDecodeContributor(UIComponent.class, formOptions);
- contributor = new MockDecodeContributor(UIComponent.class, options);
- nullContributor = new MockDecodeContributor(UIComponent.class, (ScriptOptions) null);
-
- compositeRenderer.addContributor(contributor);
- compositeRenderer.addContributor(formContributor);
- compositeRenderer.addContributor(inputContributor);
- compositeRenderer.addContributor(nullContributor);
-
- ScriptOptions scriptOptions = new ScriptOptions(input);
- compositeRenderer.mergeScriptOptions(scriptOptions, facesContext, input);
- Map map = scriptOptions.getMap();
-
- assertEquals(3, map.size());
- assertEquals("1", map.get("input"));
- assertEquals("2", map.get("form"));
- assertEquals("3", map.get("generic"));
- }
+ inputOptions.addOption("input", "1");
- public final void testMergeScriptOptionsScriptOptionsFacesContextUIComponentClass() {
- UIInput input = new UIInput();
+ ScriptOptions formOptions = new ScriptOptions(input);
- ScriptOptions inputOptions = new ScriptOptions(input);
- inputOptions.addOption("input", "1");
-
- ScriptOptions formOptions = new ScriptOptions(input);
- formOptions.addOption("form", "2");
-
- ScriptOptions options = new ScriptOptions(input);
- options.addOption("generic", "3");
+ formOptions.addOption("form", "2");
- MockDecodeContributor inputContributor;
- MockDecodeContributor formContributor;
- MockDecodeContributor contributor;
- MockDecodeContributor nullContributor;
+ ScriptOptions options = new ScriptOptions(input);
- inputContributor = new MockDecodeContributor(UIInput.class, inputOptions);
- formContributor = new MockDecodeContributor(NamingContainer.class, formOptions);
- contributor = new MockDecodeContributor(UIComponent.class, options);
- nullContributor = new MockDecodeContributor(UIForm.class, (ScriptOptions) null);
-
- compositeRenderer.addContributor(contributor);
- compositeRenderer.addContributor(formContributor);
- compositeRenderer.addContributor(inputContributor);
- compositeRenderer.addContributor(nullContributor);
-
- ScriptOptions scriptOptions = new ScriptOptions(input);
- compositeRenderer.mergeScriptOptions(scriptOptions, facesContext, input, UIForm.class);
- Map map = scriptOptions.getMap();
+ options.addOption("generic", "3");
- assertEquals(2, map.size());
- assertEquals("2", map.get("form"));
- assertEquals("3", map.get("generic"));
- }
+ MockDecodeContributor inputContributor;
+ MockDecodeContributor formContributor;
+ MockDecodeContributor contributor;
+ MockDecodeContributor nullContributor;
- public final void testGetScriptContributionsStringFacesContextUIComponent() {
- MockDecodeContributor inputContributor;
- MockDecodeContributor formContributor;
- MockDecodeContributor contributor;
- MockDecodeContributor nullContributor;
+ inputContributor = new MockDecodeContributor(UIComponent.class, inputOptions);
+ formContributor = new MockDecodeContributor(UIComponent.class, formOptions);
+ contributor = new MockDecodeContributor(UIComponent.class, options);
+ nullContributor = new MockDecodeContributor(UIComponent.class, (ScriptOptions) null);
+ compositeRenderer.addContributor(contributor);
+ compositeRenderer.addContributor(formContributor);
+ compositeRenderer.addContributor(inputContributor);
+ compositeRenderer.addContributor(nullContributor);
- inputContributor = new MockDecodeContributor(UIComponent.class, ".1;");
- formContributor = new MockDecodeContributor(UIComponent.class, ".2;");
- contributor = new MockDecodeContributor(UIComponent.class, ".3;");
- nullContributor = new MockDecodeContributor(UIForm.class, (String) null);
-
- compositeRenderer.addContributor(contributor);
- compositeRenderer.addContributor(formContributor);
- compositeRenderer.addContributor(inputContributor);
- compositeRenderer.addContributor(nullContributor);
-
- UIInput input = new UIInput();
- input.getAttributes().put("test", ".testValue");
+ ScriptOptions scriptOptions = new ScriptOptions(input);
- String contributions = compositeRenderer.getScriptContributions("theVar", facesContext, input);
-
- assertEquals("theVar.testValue.3;theVar.testValue.2;theVar.testValue.1;", contributions);
- }
+ compositeRenderer.mergeScriptOptions(scriptOptions, facesContext, input);
- public final void testGetScriptContributionsStringFacesContextUIComponentClass() {
- MockDecodeContributor inputContributor;
- MockDecodeContributor formContributor;
- MockDecodeContributor contributor;
- MockDecodeContributor nullContributor;
+ Map map = scriptOptions.getMap();
- inputContributor = new MockDecodeContributor(UIInput.class, ".input;");
- formContributor = new MockDecodeContributor(NamingContainer.class, ".namingContainer;");
- contributor = new MockDecodeContributor(UIComponent.class, ".generic;");
- nullContributor = new MockDecodeContributor(UIForm.class, (String) null);
-
- compositeRenderer.addContributor(contributor);
- compositeRenderer.addContributor(formContributor);
- compositeRenderer.addContributor(inputContributor);
- compositeRenderer.addContributor(nullContributor);
-
- UIInput input = new UIInput();
- input.getAttributes().put("test", ".testValue");
-
- String contributions = compositeRenderer.getScriptContributions("theVar", facesContext, input,
- UIForm.class);
-
- assertEquals("theVar.testValue.generic;theVar.testValue.namingContainer;", contributions);
- }
+ assertEquals(3, map.size());
+ assertEquals("1", map.get("input"));
+ assertEquals("2", map.get("form"));
+ assertEquals("3", map.get("generic"));
+ }
- public final void testAddContributor() {
- MockDecodeContributor[] contributors = new MockDecodeContributor[5];
- for (int i = 0; i < contributors.length; i++) {
- contributors[i] = new MockDecodeContributor();
- compositeRenderer.addContributor(contributors[i]);
- }
+ public final void testMergeScriptOptionsScriptOptionsFacesContextUIComponentClass() {
+ UIInput input = new UIInput();
+ ScriptOptions inputOptions = new ScriptOptions(input);
- assertTrue(Arrays.deepEquals(contributors, compositeRenderer.getContributors()));
- }
+ inputOptions.addOption("input", "1");
- public final void testContributorDecodeCallback() {
- MockDecodeContributor inputContributor;
- MockDecodeContributor formContributor;
+ ScriptOptions formOptions = new ScriptOptions(input);
- formContributor = new MockDecodeContributor(NamingContainer.class);
- inputContributor = new MockDecodeContributor(UIInput.class);
+ formOptions.addOption("form", "2");
- compositeRenderer.addContributor(inputContributor);
- compositeRenderer.addContributor(formContributor);
-
- UIComponent component = new UIInput();
- compositeRenderer.doDecode(facesContext, component);
+ ScriptOptions options = new ScriptOptions(input);
- assertSame(compositeRenderer, inputContributor.getRenderer());
- assertSame(facesContext, inputContributor.getContext());
- assertSame(component, inputContributor.getComponent());
-
- assertNull(formContributor.getRenderer());
- assertNull(formContributor.getContext());
- assertNull(formContributor.getComponent());
+ options.addOption("generic", "3");
- inputContributor.reset();
- formContributor.reset();
+ MockDecodeContributor inputContributor;
+ MockDecodeContributor formContributor;
+ MockDecodeContributor contributor;
+ MockDecodeContributor nullContributor;
- assertNull(inputContributor.getRenderer());
- assertNull(inputContributor.getContext());
- assertNull(inputContributor.getComponent());
+ inputContributor = new MockDecodeContributor(UIInput.class, inputOptions);
+ formContributor = new MockDecodeContributor(NamingContainer.class, formOptions);
+ contributor = new MockDecodeContributor(UIComponent.class, options);
+ nullContributor = new MockDecodeContributor(UIForm.class, (ScriptOptions) null);
+ compositeRenderer.addContributor(contributor);
+ compositeRenderer.addContributor(formContributor);
+ compositeRenderer.addContributor(inputContributor);
+ compositeRenderer.addContributor(nullContributor);
- assertNull(formContributor.getRenderer());
- assertNull(formContributor.getContext());
- assertNull(formContributor.getComponent());
+ ScriptOptions scriptOptions = new ScriptOptions(input);
- component = new UIForm();
- compositeRenderer.doDecode(facesContext, component);
+ compositeRenderer.mergeScriptOptions(scriptOptions, facesContext, input, UIForm.class);
- assertSame(compositeRenderer, formContributor.getRenderer());
- assertSame(facesContext, formContributor.getContext());
- assertSame(component, formContributor.getComponent());
-
- assertNull(inputContributor.getRenderer());
- assertNull(inputContributor.getContext());
- assertNull(inputContributor.getComponent());
- }
+ Map map = scriptOptions.getMap();
- public final void testAddParameterEncoder() {
- MockAttributeParameterEncoder[] encoders = new MockAttributeParameterEncoder[5];
- for (int i = 0; i < encoders.length; i++) {
- encoders[i] = new MockAttributeParameterEncoder("aaa");
- compositeRenderer.addParameterEncoder(encoders[i]);
- }
+ assertEquals(2, map.size());
+ assertEquals("2", map.get("form"));
+ assertEquals("3", map.get("generic"));
+ }
- assertTrue(Arrays.deepEquals(encoders, compositeRenderer.getParameterEncoders()));
- }
+ public final void testGetScriptContributionsStringFacesContextUIComponent() {
+ MockDecodeContributor inputContributor;
+ MockDecodeContributor formContributor;
+ MockDecodeContributor contributor;
+ MockDecodeContributor nullContributor;
- public final void testEncodeAttributeParameters() throws IOException {
+ inputContributor = new MockDecodeContributor(UIComponent.class, ".1;");
+ formContributor = new MockDecodeContributor(UIComponent.class, ".2;");
+ contributor = new MockDecodeContributor(UIComponent.class, ".3;");
+ nullContributor = new MockDecodeContributor(UIForm.class, (String) null);
+ compositeRenderer.addContributor(contributor);
+ compositeRenderer.addContributor(formContributor);
+ compositeRenderer.addContributor(inputContributor);
+ compositeRenderer.addContributor(nullContributor);
- MockAttributeParameterEncoder encoder1 = new MockAttributeParameterEncoder("Attribute");
- MockAttributeParameterEncoder encoder2 = new MockAttributeParameterEncoder("MoreAttribute");
-
- compositeRenderer.addParameterEncoder(encoder1);
- compositeRenderer.addParameterEncoder(encoder2);
+ UIInput input = new UIInput();
- UIInput input = new UIInput();
- input.getAttributes().put("Attribute", "testValue1");
- input.getAttributes().put("MoreAttribute", "testValue2");
-
- //ResponseWriter responseWriter = facesContext.getResponseWriter();
- StringWriter stringWriter = new StringWriter();
- ResponseWriter responseWriter = facesContext.getRenderKit().createResponseWriter(stringWriter, "text/html", "UTF8");
- facesContext.setResponseWriter(responseWriter);
+ input.getAttributes().put("test", ".testValue");
- responseWriter.startDocument();
- responseWriter.startElement("span", input);
- compositeRenderer.encodeAttributeParameters(facesContext, input);
- responseWriter.endElement("span");
- responseWriter.endDocument();
-
- responseWriter.flush();
-
- String result = stringWriter.getBuffer().toString();
- assertTrue(result.contains("testAttribute=\"testValue1\""));
- assertTrue(result.contains("testMoreAttribute=\"testValue2\""));
- }
-}
+ String contributions = compositeRenderer.getScriptContributions("theVar", facesContext, input);
-class MockDecodeContributor implements RendererContributor {
+ assertEquals("theVar.testValue.3;theVar.testValue.2;theVar.testValue.1;", contributions);
+ }
- private String[] scriptDependencies;
- private String[] styleDependencies;
-
- private String scriptContribution;
-
- private Class componentClass;
- private FacesContext context;
- private UIComponent component;
- private CompositeRenderer renderer;
- private ScriptOptions options;
-
- public MockDecodeContributor(Class componentClass, ScriptOptions options) {
- super();
+ public final void testGetScriptContributionsStringFacesContextUIComponentClass() {
+ MockDecodeContributor inputContributor;
+ MockDecodeContributor formContributor;
+ MockDecodeContributor contributor;
+ MockDecodeContributor nullContributor;
- this.componentClass = componentClass;
- this.options = options;
- }
+ inputContributor = new MockDecodeContributor(UIInput.class, ".input;");
+ formContributor = new MockDecodeContributor(NamingContainer.class, ".namingContainer;");
+ contributor = new MockDecodeContributor(UIComponent.class, ".generic;");
+ nullContributor = new MockDecodeContributor(UIForm.class, (String) null);
+ compositeRenderer.addContributor(contributor);
+ compositeRenderer.addContributor(formContributor);
+ compositeRenderer.addContributor(inputContributor);
+ compositeRenderer.addContributor(nullContributor);
- public MockDecodeContributor() {
- this(UIComponent.class);
- }
-
- public MockDecodeContributor(Class componentClass) {
- super();
- this.componentClass = componentClass;
- }
+ UIInput input = new UIInput();
- public MockDecodeContributor(Class componentClass, String scriptContribution) {
- super();
+ input.getAttributes().put("test", ".testValue");
- this.componentClass = componentClass;
- this.scriptContribution = scriptContribution;
- }
+ String contributions = compositeRenderer.getScriptContributions("theVar", facesContext, input, UIForm.class);
- public MockDecodeContributor(Class componentClass, String[] scriptDependencies,
- String[] styleDependencies) {
- super();
-
- this.componentClass = componentClass;
- this.scriptDependencies = scriptDependencies;
- this.styleDependencies = styleDependencies;
- }
+ assertEquals("theVar.testValue.generic;theVar.testValue.namingContainer;", contributions);
+ }
- public void decode(FacesContext context, UIComponent component,
- CompositeRenderer compositeRenderer) {
+ public final void testAddContributor() {
+ MockDecodeContributor[] contributors = new MockDecodeContributor[5];
- this.component = component;
- this.context = context;
- this.renderer = compositeRenderer;
- }
+ for (int i = 0; i < contributors.length; i++) {
+ contributors[i] = new MockDecodeContributor();
+ compositeRenderer.addContributor(contributors[i]);
+ }
- public Class getAcceptableClass() {
- return componentClass;
- }
+ assertTrue(Arrays.deepEquals(contributors, compositeRenderer.getContributors()));
+ }
- public String getScriptContribution(FacesContext context,
- UIComponent component) {
- return scriptContribution != null ? component.getAttributes().get("test") + scriptContribution :
- null;
- }
+ public final void testContributorDecodeCallback() {
+ MockDecodeContributor inputContributor;
+ MockDecodeContributor formContributor;
- public String[] getScriptDependencies() {
- return scriptDependencies;
- }
+ formContributor = new MockDecodeContributor(NamingContainer.class);
+ inputContributor = new MockDecodeContributor(UIInput.class);
+ compositeRenderer.addContributor(inputContributor);
+ compositeRenderer.addContributor(formContributor);
- public String[] getStyleDependencies() {
- return styleDependencies;
- }
+ UIComponent component = new UIInput();
- public ScriptOptions buildOptions(FacesContext context,
- UIComponent component) {
- return options;
- }
-
- public UIComponent getComponent() {
- return component;
- }
-
- public FacesContext getContext() {
- return context;
- }
-
- public CompositeRenderer getRenderer() {
- return renderer;
- }
-
- public void reset() {
- this.component = null;
- this.context = null;
- this.renderer = null;
- }
+ compositeRenderer.doDecode(facesContext, component);
+ assertSame(compositeRenderer, inputContributor.getRenderer());
+ assertSame(facesContext, inputContributor.getContext());
+ assertSame(component, inputContributor.getComponent());
+ assertNull(formContributor.getRenderer());
+ assertNull(formContributor.getContext());
+ assertNull(formContributor.getComponent());
+ inputContributor.reset();
+ formContributor.reset();
+ assertNull(inputContributor.getRenderer());
+ assertNull(inputContributor.getContext());
+ assertNull(inputContributor.getComponent());
+ assertNull(formContributor.getRenderer());
+ assertNull(formContributor.getContext());
+ assertNull(formContributor.getComponent());
+ component = new UIForm();
+ compositeRenderer.doDecode(facesContext, component);
+ assertSame(compositeRenderer, formContributor.getRenderer());
+ assertSame(facesContext, formContributor.getContext());
+ assertSame(component, formContributor.getComponent());
+ assertNull(inputContributor.getRenderer());
+ assertNull(inputContributor.getContext());
+ assertNull(inputContributor.getComponent());
+ }
+
+ public final void testAddParameterEncoder() {
+ MockAttributeParameterEncoder[] encoders = new MockAttributeParameterEncoder[5];
+
+ for (int i = 0; i < encoders.length; i++) {
+ encoders[i] = new MockAttributeParameterEncoder("aaa");
+ compositeRenderer.addParameterEncoder(encoders[i]);
+ }
+
+ assertTrue(Arrays.deepEquals(encoders, compositeRenderer.getParameterEncoders()));
+ }
+
+ public final void testEncodeAttributeParameters() throws IOException {
+ MockAttributeParameterEncoder encoder1 = new MockAttributeParameterEncoder("Attribute");
+ MockAttributeParameterEncoder encoder2 = new MockAttributeParameterEncoder("MoreAttribute");
+
+ compositeRenderer.addParameterEncoder(encoder1);
+ compositeRenderer.addParameterEncoder(encoder2);
+
+ UIInput input = new UIInput();
+
+ input.getAttributes().put("Attribute", "testValue1");
+ input.getAttributes().put("MoreAttribute", "testValue2");
+
+ // ResponseWriter responseWriter = facesContext.getResponseWriter();
+ StringWriter stringWriter = new StringWriter();
+ ResponseWriter responseWriter = facesContext.getRenderKit().createResponseWriter(stringWriter, "text/html",
+ "UTF8");
+
+ facesContext.setResponseWriter(responseWriter);
+ responseWriter.startDocument();
+ responseWriter.startElement("span", input);
+ compositeRenderer.encodeAttributeParameters(facesContext, input);
+ responseWriter.endElement("span");
+ responseWriter.endDocument();
+ responseWriter.flush();
+
+ String result = stringWriter.getBuffer().toString();
+
+ assertTrue(result.contains("testAttribute=\"testValue1\""));
+ assertTrue(result.contains("testMoreAttribute=\"testValue2\""));
+ }
}
+
class MockAttributeParameterEncoder implements AttributeParametersEncoder {
+ private String attributeName;
- private String attributeName;
-
- public MockAttributeParameterEncoder(String attributeName) {
- super();
- this.attributeName = attributeName;
- }
+ public MockAttributeParameterEncoder(String attributeName) {
+ super();
+ this.attributeName = attributeName;
+ }
- public void doEncode(FacesContext context, UIComponent component)
- throws IOException {
+ public void doEncode(FacesContext context, UIComponent component) throws IOException {
+ context.getResponseWriter().writeAttribute("test" + attributeName,
+ component.getAttributes().get(attributeName), null);
+ }
+}
- context.getResponseWriter().writeAttribute("test" + attributeName, component.getAttributes().get(attributeName)
- , null);
- }
+
+class MockDecodeContributor implements RendererContributor {
+ private UIComponent component;
+ private Class componentClass;
+ private FacesContext context;
+ private ScriptOptions options;
+ private CompositeRenderer renderer;
+ private String scriptContribution;
+ private String[] scriptDependencies;
+ private String[] styleDependencies;
+
+ public MockDecodeContributor() {
+ this(UIComponent.class);
+ }
+
+ public MockDecodeContributor(Class componentClass) {
+ super();
+ this.componentClass = componentClass;
+ }
+
+ public MockDecodeContributor(Class componentClass, ScriptOptions options) {
+ super();
+ this.componentClass = componentClass;
+ this.options = options;
+ }
+
+ public MockDecodeContributor(Class componentClass, String scriptContribution) {
+ super();
+ this.componentClass = componentClass;
+ this.scriptContribution = scriptContribution;
+ }
+
+ public MockDecodeContributor(Class componentClass, String[] scriptDependencies, String[] styleDependencies) {
+ super();
+ this.componentClass = componentClass;
+ this.scriptDependencies = scriptDependencies;
+ this.styleDependencies = styleDependencies;
+ }
+
+ public void decode(FacesContext context, UIComponent component, CompositeRenderer compositeRenderer) {
+ this.component = component;
+ this.context = context;
+ this.renderer = compositeRenderer;
+ }
+
+ public Class getAcceptableClass() {
+ return componentClass;
+ }
+
+ public String getScriptContribution(FacesContext context, UIComponent component) {
+ return scriptContribution != null ? component.getAttributes().get("test") + scriptContribution : null;
+ }
+
+ public String[] getScriptDependencies() {
+ return scriptDependencies;
+ }
+
+ public String[] getStyleDependencies() {
+ return styleDependencies;
+ }
+
+ public ScriptOptions buildOptions(FacesContext context, UIComponent component) {
+ return options;
+ }
+
+ public UIComponent getComponent() {
+ return component;
+ }
+
+ public FacesContext getContext() {
+ return context;
+ }
+
+ public CompositeRenderer getRenderer() {
+ return renderer;
+ }
+
+ public void reset() {
+ this.component = null;
+ this.context = null;
+ this.renderer = null;
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/TemplateEncoderRendererBaseTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/TemplateEncoderRendererBaseTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/TemplateEncoderRendererBaseTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import java.io.StringWriter;
@@ -35,75 +37,74 @@
* @author Nick Belaevski - mailto:nbelaevski@exadel.com
* @since 3.2
*/
-
public class TemplateEncoderRendererBaseTest extends AbstractFacesTest {
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- @Override
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testEncodeNonRendered() throws Exception {
- ResponseWriter responseWriter = facesContext.getRenderKit().createResponseWriter(new StringWriter(), "text/html", "UTF-8");
- facesContext.setResponseWriter(responseWriter);
-
- TemplateEncoderRendererBase rendererBase = new TemplateEncoderRendererBase() {
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- @Override
- protected Class<? extends UIComponent> getComponentClass() {
- return UIOutput.class;
- }
- };
-
- UIOutput output = new UIOutput();
+ public void testEncodeNonRendered() throws Exception {
+ ResponseWriter responseWriter = facesContext.getRenderKit().createResponseWriter(new StringWriter(),
+ "text/html", "UTF-8");
- UIOutput c = new UIOutput();
- c.setRendered(false);
- c.setValue("");
- output.getChildren().add(c);
-
- //that should not fail
- rendererBase.writeScriptBody(facesContext, c, true);
- }
+ facesContext.setResponseWriter(responseWriter);
- public void testEncode() throws Exception {
- StringWriter controlWriter = new StringWriter();
- ResponseWriter responseWriter = facesContext.getRenderKit().createResponseWriter(controlWriter, "text/html", "UTF-8");
- facesContext.setResponseWriter(responseWriter);
-
- TemplateEncoderRendererBase rendererBase = new TemplateEncoderRendererBase() {
+ TemplateEncoderRendererBase rendererBase = new TemplateEncoderRendererBase() {
+ @Override
+ protected Class<? extends UIComponent> getComponentClass() {
+ return UIOutput.class;
+ }
+ };
+ UIOutput output = new UIOutput();
+ UIOutput c = new UIOutput();
- @Override
- protected Class<? extends UIComponent> getComponentClass() {
- return UIOutput.class;
- }
- };
-
- HtmlPanelGroup c = new HtmlPanelGroup();
+ c.setRendered(false);
+ c.setValue("");
+ output.getChildren().add(c);
- for (int i = 0; i < 3; i++) {
- HtmlPanelGroup c1 = new HtmlPanelGroup();
- c1.setId("panel" + i);
-
- UIOutput text = new UIOutput();
- text.setValue("some text");
-
- c1.getChildren().add(text);
- UIOutput text2 = new UIOutput();
- text2.setValue("some text");
- c.getChildren().add(text2);
- c.getChildren().add(c1);
+ // that should not fail
+ rendererBase.writeScriptBody(facesContext, c, true);
+ }
- }
-
- rendererBase.writeScriptBody(facesContext, c, false);
- System.out.println(controlWriter.toString());
- }
+ public void testEncode() throws Exception {
+ StringWriter controlWriter = new StringWriter();
+ ResponseWriter responseWriter = facesContext.getRenderKit().createResponseWriter(controlWriter, "text/html",
+ "UTF-8");
+ facesContext.setResponseWriter(responseWriter);
+
+ TemplateEncoderRendererBase rendererBase = new TemplateEncoderRendererBase() {
+ @Override
+ protected Class<? extends UIComponent> getComponentClass() {
+ return UIOutput.class;
+ }
+ };
+ HtmlPanelGroup c = new HtmlPanelGroup();
+
+ for (int i = 0; i < 3; i++) {
+ HtmlPanelGroup c1 = new HtmlPanelGroup();
+
+ c1.setId("panel" + i);
+
+ UIOutput text = new UIOutput();
+
+ text.setValue("some text");
+ c1.getChildren().add(text);
+
+ UIOutput text2 = new UIOutput();
+
+ text2.setValue("some text");
+ c.getChildren().add(text2);
+ c.getChildren().add(c1);
+ }
+
+ rendererBase.writeScriptBody(facesContext, c, false);
+ System.out.println(controlWriter.toString());
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/TemplateUtilTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/TemplateUtilTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/TemplateUtilTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import java.io.StringReader;
+
import java.util.List;
import junit.framework.TestCase;
@@ -34,12 +37,11 @@
*
*/
public class TemplateUtilTest extends TestCase {
+ public void testAntlr() throws Exception {
+ List result = new RichMacroDefinition(new StringReader("{aa{b\\}}a}\\\\ a\\}b\\{c")).expression();
+ Expression holder = (Expression) result.get(0);
-
- public void testAntlr() throws Exception {
- List result = new RichMacroDefinition(new StringReader("{aa{b\\}}a}\\\\ a\\}b\\{c")).expression();
- Expression holder = (Expression) result.get(0);
- assertEquals("aa{b}}a", holder.getExpression());
- assertEquals("\\ a}b{c", result.get(1));
- }
+ assertEquals("aa{b}}a", holder.getExpression());
+ assertEquals("\\ a}b{c", result.get(1));
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/html/images/GradientEnumsTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/html/images/GradientEnumsTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/renderkit/html/images/GradientEnumsTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit.html.images;
import java.util.Locale;
@@ -29,19 +31,17 @@
* Covers https://jira.jboss.org/jira/browse/RF-4142
*/
public class GradientEnumsTest extends TestCase {
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ Locale.setDefault(new Locale("tr", "TR"));
+ }
- @Override
- protected void setUp() throws Exception {
- super.setUp();
+ public void testAlignment() throws Exception {
+ GradientAlignment.MIDDLE.equals(GradientAlignment.getByParameter("middle"));
+ }
- Locale.setDefault(new Locale("tr", "TR"));
- }
-
- public void testAlignment() throws Exception {
- GradientAlignment.MIDDLE.equals(GradientAlignment.getByParameter("middle"));
- }
-
- public void testType() throws Exception {
- GradientType.PLAIN.equals(GradientType.getByParameter("plain"));
- }
+ public void testType() throws Exception {
+ GradientType.PLAIN.equals(GradientType.getByParameter("plain"));
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractBaseResourceTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractBaseResourceTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractBaseResourceTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,12 +19,16 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
+
import java.net.URL;
import java.net.URLConnection;
+
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
@@ -35,361 +39,351 @@
import javax.faces.context.FacesContext;
import org.easymock.EasyMock;
+
import org.richfaces.test.AbstractFacesTest;
import org.richfaces.util.Util;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class AbstractBaseResourceTest extends AbstractFacesTest {
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- @Override
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- private class ResourceImpl extends AbstractBaseResource {
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- @Override
- public InputStream getInputStream() {
- throw new UnsupportedOperationException();
- }
+ public void testGetHeaders() throws Exception {
+ MockResourceImpl mockResource = new MockResourceImpl();
- public ResourceImpl() {
- super();
-
- setResourceName("org.richfaces.resource.ResourceImpl");
- }
- }
-
- private class MockStateAwareResourceImpl extends MockResourceImpl implements StateHolder {
+ mockResource.setCacheable(true);
+ mockResource.setEntityTag("\"etag0\"");
+ mockResource.setContentLength(80);
+ mockResource.setContentType("image/png");
- private Object resourceState;
-
- private boolean _transient = false;
-
- public MockStateAwareResourceImpl() {
- super();
-
- setResourceName("org.richfaces.resource.MockStateAwareResource");
- }
-
- public boolean isTransient() {
- return _transient;
- }
+ Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- public void setTransient(boolean newTransientValue) {
- this._transient = newTransientValue;
- }
+ calendar.clear();
+ calendar.set(2009, Calendar.JULY, 13, 12, 45, 9);
+ mockResource.setLastModified(calendar.getTime());
+ calendar.add(Calendar.DATE, 1);
+ mockResource.setCurrentTime(calendar.getTimeInMillis());
+ calendar.add(Calendar.DATE, 7);
+ mockResource.setExpired(calendar.getTime());
- public Object saveState(FacesContext context) {
- return resourceState;
- }
-
- public void restoreState(FacesContext context, Object state) {
- this.resourceState = state;
- }
-
- }
-
- private class MockResourceImpl extends AbstractBaseResource {
+ Map<String, String> headers = mockResource.getResponseHeaders();
- private String version;
-
- private int contentLength = -1;
-
- private InputStream inputStream;
-
- private Date lastModified;
-
- private Date expired;
-
- private long currentTime;
-
- private String entityTag;
-
- private int ttl;
-
- public MockResourceImpl() {
- super();
-
- setResourceName("org.richfaces.resource.MockResource");
- }
-
- @Override
- protected int getContentLength(FacesContext context) {
- return contentLength;
- }
-
- @Override
- public InputStream getInputStream() {
- return inputStream;
- }
+ assertEquals("Tue, 21 Jul 2009 12:45:09 GMT", headers.get("Expires"));
+ assertEquals("Mon, 13 Jul 2009 12:45:09 GMT", headers.get("Last-Modified"));
+ assertEquals("Tue, 14 Jul 2009 12:45:09 GMT", headers.get("Date"));
+ assertEquals("\"etag0\"", headers.get("ETag"));
+ assertEquals("max-age=604800", headers.get("Cache-Control"));
+ assertEquals("80", headers.get("Content-Length"));
+ assertEquals("image/png", headers.get("Content-Type"));
+ assertEquals(7, headers.size());
+ mockResource.setTimeToLive(14 * 24 * 60 * 60 /* 14 days */);
+ headers = mockResource.getResponseHeaders();
+ assertEquals("Tue, 28 Jul 2009 12:45:09 GMT", headers.get("Expires"));
+ assertEquals("Mon, 13 Jul 2009 12:45:09 GMT", headers.get("Last-Modified"));
+ assertEquals("Tue, 14 Jul 2009 12:45:09 GMT", headers.get("Date"));
+ assertEquals("max-age=1209600", headers.get("Cache-Control"));
+ }
- /* (non-Javadoc)
- * @see org.richfaces.resource.ResourceImpl#getVersion()
- */
- @Override
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
+ public void testGetHeadersNonCacheable() throws Exception {
+ MockResourceImpl mockResource = new MockResourceImpl();
- public void setContentLength(int contentLength) {
- this.contentLength = contentLength;
- }
+ mockResource.setCacheable(false);
+ mockResource.setContentLength(120);
+ mockResource.setContentType("image/jpg");
+ mockResource.setEntityTag("\"etag1\"");
- public void setInputStream(InputStream inputStream) {
- this.inputStream = inputStream;
- }
+ Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- @Override
- protected Date getLastModified(FacesContext context) {
- return lastModified;
- }
-
- public void setLastModified(Date lastModified) {
- this.lastModified = lastModified;
- }
-
- @Override
- protected Date getExpires(FacesContext context) {
- return expired;
- }
-
- public void setExpired(Date expired) {
- this.expired = expired;
- }
-
- @Override
- protected String getEntityTag(FacesContext context) {
- return entityTag;
- }
-
- /**
- * @param entityTag the entityTag to set
- */
- public void setEntityTag(String entityTag) {
- this.entityTag = entityTag;
- }
-
- @Override
- boolean isResourceRequest() {
- return true;
- }
-
- @Override
- protected long getCurrentTime() {
- return currentTime;
- }
-
- void setCurrentTime(long currentTime) {
- this.currentTime = currentTime;
- }
-
- @Override
- protected int getTimeToLive(FacesContext context) {
- return ttl;
- }
-
- public void setTimeToLive(int ttl) {
- this.ttl = ttl;
- }
- }
-
- public void testGetHeaders() throws Exception {
- MockResourceImpl mockResource = new MockResourceImpl();
- mockResource.setCacheable(true);
- mockResource.setEntityTag("\"etag0\"");
-
- mockResource.setContentLength(80);
- mockResource.setContentType("image/png");
-
- Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- calendar.clear();
- calendar.set(2009, Calendar.JULY, 13, 12, 45, 9);
-
- mockResource.setLastModified(calendar.getTime());
- calendar.add(Calendar.DATE, 1);
- mockResource.setCurrentTime(calendar.getTimeInMillis());
- calendar.add(Calendar.DATE, 7);
- mockResource.setExpired(calendar.getTime());
-
- Map<String, String> headers = mockResource.getResponseHeaders();
- assertEquals("Tue, 21 Jul 2009 12:45:09 GMT", headers.get("Expires"));
- assertEquals("Mon, 13 Jul 2009 12:45:09 GMT", headers.get("Last-Modified"));
- assertEquals("Tue, 14 Jul 2009 12:45:09 GMT", headers.get("Date"));
+ calendar.clear();
+ calendar.set(2009, Calendar.JULY, 13, 12, 45, 9);
+ mockResource.setLastModified(calendar.getTime());
+ calendar.add(Calendar.DATE, 1);
+ mockResource.setCurrentTime(calendar.getTimeInMillis());
+ calendar.add(Calendar.DATE, 7);
+ mockResource.setExpired(calendar.getTime());
- assertEquals("\"etag0\"", headers.get("ETag"));
- assertEquals("max-age=604800", headers.get("Cache-Control"));
-
- assertEquals("80", headers.get("Content-Length"));
- assertEquals("image/png", headers.get("Content-Type"));
-
- assertEquals(7, headers.size());
+ Map<String, String> headers = mockResource.getResponseHeaders();
- mockResource.setTimeToLive(14 * 24 * 60 * 60 /* 14 days */);
- headers = mockResource.getResponseHeaders();
- assertEquals("Tue, 28 Jul 2009 12:45:09 GMT", headers.get("Expires"));
- assertEquals("Mon, 13 Jul 2009 12:45:09 GMT", headers.get("Last-Modified"));
- assertEquals("Tue, 14 Jul 2009 12:45:09 GMT", headers.get("Date"));
- assertEquals("max-age=1209600", headers.get("Cache-Control"));
- }
-
- public void testGetHeadersNonCacheable() throws Exception {
- MockResourceImpl mockResource = new MockResourceImpl();
- mockResource.setCacheable(false);
-
- mockResource.setContentLength(120);
- mockResource.setContentType("image/jpg");
- mockResource.setEntityTag("\"etag1\"");
-
- Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- calendar.clear();
- calendar.set(2009, Calendar.JULY, 13, 12, 45, 9);
-
- mockResource.setLastModified(calendar.getTime());
- calendar.add(Calendar.DATE, 1);
- mockResource.setCurrentTime(calendar.getTimeInMillis());
- calendar.add(Calendar.DATE, 7);
- mockResource.setExpired(calendar.getTime());
-
- Map<String, String> headers = mockResource.getResponseHeaders();
- assertEquals("0", headers.get("Expires"));
- assertEquals("max-age=0, no-store, no-cache", headers.get("Cache-Control"));
- assertEquals("no-cache", headers.get("Pragma"));
- assertEquals("120", headers.get("Content-Length"));
- assertEquals("image/jpg", headers.get("Content-Type"));
- assertEquals("Mon, 13 Jul 2009 12:45:09 GMT", headers.get("Last-Modified"));
- assertEquals("Tue, 14 Jul 2009 12:45:09 GMT", headers.get("Date"));
+ assertEquals("0", headers.get("Expires"));
+ assertEquals("max-age=0, no-store, no-cache", headers.get("Cache-Control"));
+ assertEquals("no-cache", headers.get("Pragma"));
+ assertEquals("120", headers.get("Content-Length"));
+ assertEquals("image/jpg", headers.get("Content-Type"));
+ assertEquals("Mon, 13 Jul 2009 12:45:09 GMT", headers.get("Last-Modified"));
+ assertEquals("Tue, 14 Jul 2009 12:45:09 GMT", headers.get("Date"));
+ assertEquals(7, headers.size());
+ }
- assertEquals(7, headers.size());
- }
+ public void testGetRequestPath() throws Exception {
+ Object resourceState = new Object();
+ ResourceCodec resourceCodec = EasyMock.createMock(ResourceCodec.class);
- public void testGetRequestPath() throws Exception {
- Object resourceState = new Object();
-
- ResourceCodec resourceCodec = EasyMock.createMock(ResourceCodec.class);
- EasyMock.expect(resourceCodec.encodeResource(EasyMock.eq("org.richfaces.resource.MockStateAwareResource"),
- EasyMock.same(resourceState), EasyMock.eq("4_0_alpha"))).andReturn("Resource0/4_0_alpha/data");
+ EasyMock.expect(resourceCodec.encodeResource(EasyMock.eq("org.richfaces.resource.MockStateAwareResource"),
+ EasyMock.same(resourceState), EasyMock.eq("4_0_alpha"))).andReturn("Resource0/4_0_alpha/data");
+ EasyMock.expect(resourceCodec.encodeResource(EasyMock.eq("org.richfaces.resource.MockStateAwareResource"),
+ EasyMock.eq(null), EasyMock.eq("4_0_alpha"))).andReturn("Resource1/4_0_alpha");
+ EasyMock.expect(resourceCodec.encodeResource(EasyMock.eq("org.richfaces.resource.MockResource"),
+ EasyMock.eq(null), EasyMock.eq("4_0_alpha"))).andReturn("Resource2/4_0_alpha");
+ EasyMock.replay(resourceCodec);
+ ResourceHandlerImpl.setResourceCodec(resourceCodec);
- EasyMock.expect(resourceCodec.encodeResource(EasyMock.eq("org.richfaces.resource.MockStateAwareResource"),
- EasyMock.eq(null), EasyMock.eq("4_0_alpha"))).andReturn("Resource1/4_0_alpha");
-
- EasyMock.expect(resourceCodec.encodeResource(EasyMock.eq("org.richfaces.resource.MockResource"),
- EasyMock.eq(null), EasyMock.eq("4_0_alpha"))).andReturn("Resource2/4_0_alpha");
+ MockStateAwareResourceImpl stateAwareResourceImpl = new MockStateAwareResourceImpl();
- EasyMock.replay(resourceCodec);
- ResourceHandlerImpl.setResourceCodec(resourceCodec);
+ stateAwareResourceImpl.setVersion("4_0_alpha");
+ stateAwareResourceImpl.restoreState(facesContext, resourceState);
+ assertEquals("org.richfaces.resource.MockStateAwareResource", stateAwareResourceImpl.getResourceName());
+ assertEquals("/rfRes/Resource0/4_0_alpha/data.jsf", stateAwareResourceImpl.getRequestPath());
+ stateAwareResourceImpl.setTransient(true);
+ assertEquals("/rfRes/Resource1/4_0_alpha.jsf", stateAwareResourceImpl.getRequestPath());
- MockStateAwareResourceImpl stateAwareResourceImpl = new MockStateAwareResourceImpl();
- stateAwareResourceImpl.setVersion("4_0_alpha");
- stateAwareResourceImpl.restoreState(facesContext, resourceState);
-
- assertEquals("org.richfaces.resource.MockStateAwareResource", stateAwareResourceImpl.getResourceName());
- assertEquals("/rfRes/Resource0/4_0_alpha/data.jsf", stateAwareResourceImpl.getRequestPath());
+ MockResourceImpl resourceImpl = new MockResourceImpl();
- stateAwareResourceImpl.setTransient(true);
+ resourceImpl.setVersion("4_0_alpha");
+ assertEquals("org.richfaces.resource.MockResource", resourceImpl.getResourceName());
+ assertEquals("/rfRes/Resource2/4_0_alpha.jsf", resourceImpl.getRequestPath());
+ EasyMock.verify(resourceCodec);
+ }
- assertEquals("/rfRes/Resource1/4_0_alpha.jsf", stateAwareResourceImpl.getRequestPath());
-
- MockResourceImpl resourceImpl = new MockResourceImpl();
- resourceImpl.setVersion("4_0_alpha");
-
- assertEquals("org.richfaces.resource.MockResource", resourceImpl.getResourceName());
+ public void testGetURL() throws Exception {
+ InputStream stream = new ByteArrayInputStream(new byte[0]);
+ MockResourceImpl mockResource = new MockResourceImpl();
- assertEquals("/rfRes/Resource2/4_0_alpha.jsf", resourceImpl.getRequestPath());
- EasyMock.verify(resourceCodec);
- }
-
- public void testGetURL() throws Exception {
- InputStream stream = new ByteArrayInputStream(new byte[0]);
- MockResourceImpl mockResource = new MockResourceImpl();
- mockResource.setContentLength(130);
- mockResource.setContentType("image/gif");
- mockResource.setInputStream(stream);
-
- Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- calendar.clear();
- calendar.set(2009, Calendar.JUNE, 12, 21, 38, 59);
- Date lastModified = calendar.getTime();
- mockResource.setLastModified(lastModified);
- calendar.add(Calendar.MONTH, 1);
-
- Date expired = calendar.getTime();
- mockResource.setExpired(expired);
-
- URL url = mockResource.getURL();
-
- assertNotNull(url);
- assertEquals("jsfresource:org.richfaces.resource.MockResource", url.toExternalForm());
+ mockResource.setContentLength(130);
+ mockResource.setContentType("image/gif");
+ mockResource.setInputStream(stream);
- URLConnection urlConnection = url.openConnection();
- assertNotNull(urlConnection);
-
- urlConnection.connect();
- assertEquals(130, urlConnection.getContentLength());
- assertEquals("image/gif", urlConnection.getContentType());
- assertEquals(lastModified.getTime(), urlConnection.getLastModified());
- assertEquals(expired.getTime(), urlConnection.getExpiration());
- assertSame(stream, urlConnection.getInputStream());
- assertSame(url, urlConnection.getURL());
+ Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- MockResourceImpl mockResource2 = new MockResourceImpl();
- URLConnection urlConnection2 = mockResource2.getURL().openConnection();
- urlConnection2.connect();
- assertEquals(-1, urlConnection2.getContentLength());
- assertNull(urlConnection2.getContentType());
- assertEquals(0, urlConnection2.getLastModified());
- assertTrue(urlConnection2.getExpiration() > 0);
- }
-
- public void testDefaults() throws Exception {
- ResourceImpl defaultResource = new ResourceImpl();
- assertTrue(defaultResource.isCacheable(facesContext));
- assertEquals("org.richfaces.resource.ResourceImpl", defaultResource.getResourceName());
- assertEquals(-1, defaultResource.getContentLength(facesContext));
- assertNull(defaultResource.getEntityTag(facesContext));
- assertNull(defaultResource.getVersion());
- assertNull(defaultResource.getExpires(facesContext));
- Date lastModified = defaultResource.getLastModified(facesContext);
- assertNotNull(lastModified);
- assertTrue(System.currentTimeMillis() >= lastModified.getTime());
+ calendar.clear();
+ calendar.set(2009, Calendar.JUNE, 12, 21, 38, 59);
- ResourceImpl defaultETagResource = new ResourceImpl() {
- protected Date getLastModified(FacesContext context) { return new Date(12471234567890l); };
-
- protected int getContentLength(FacesContext context) { return 1297; };
- };
-
- assertEquals("W/\"1297-12471234567890\"", defaultETagResource.getEntityTag(facesContext));
- }
+ Date lastModified = calendar.getTime();
- public void testUserAgentNeedsUpdate() throws Exception {
- long currentTime = System.currentTimeMillis();
-
- MockResourceImpl actualResource = new MockResourceImpl();
- actualResource.setLastModified(new Date(currentTime - 30000));
+ mockResource.setLastModified(lastModified);
+ calendar.add(Calendar.MONTH, 1);
- MockResourceImpl expiredResource = new MockResourceImpl();
- expiredResource.setLastModified(new Date(currentTime - 10000));
-
- this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
- Util.formatHttpDate(new Date(currentTime - 20000))));
-
- assertTrue(expiredResource.userAgentNeedsUpdate(facesContext));
- assertFalse(actualResource.userAgentNeedsUpdate(facesContext));
- }
-}
+ Date expired = calendar.getTime();
+ mockResource.setExpired(expired);
+
+ URL url = mockResource.getURL();
+
+ assertNotNull(url);
+ assertEquals("jsfresource:org.richfaces.resource.MockResource", url.toExternalForm());
+
+ URLConnection urlConnection = url.openConnection();
+
+ assertNotNull(urlConnection);
+ urlConnection.connect();
+ assertEquals(130, urlConnection.getContentLength());
+ assertEquals("image/gif", urlConnection.getContentType());
+ assertEquals(lastModified.getTime(), urlConnection.getLastModified());
+ assertEquals(expired.getTime(), urlConnection.getExpiration());
+ assertSame(stream, urlConnection.getInputStream());
+ assertSame(url, urlConnection.getURL());
+
+ MockResourceImpl mockResource2 = new MockResourceImpl();
+ URLConnection urlConnection2 = mockResource2.getURL().openConnection();
+
+ urlConnection2.connect();
+ assertEquals(-1, urlConnection2.getContentLength());
+ assertNull(urlConnection2.getContentType());
+ assertEquals(0, urlConnection2.getLastModified());
+ assertTrue(urlConnection2.getExpiration() > 0);
+ }
+
+ public void testDefaults() throws Exception {
+ ResourceImpl defaultResource = new ResourceImpl();
+
+ assertTrue(defaultResource.isCacheable(facesContext));
+ assertEquals("org.richfaces.resource.ResourceImpl", defaultResource.getResourceName());
+ assertEquals(-1, defaultResource.getContentLength(facesContext));
+ assertNull(defaultResource.getEntityTag(facesContext));
+ assertNull(defaultResource.getVersion());
+ assertNull(defaultResource.getExpires(facesContext));
+
+ Date lastModified = defaultResource.getLastModified(facesContext);
+
+ assertNotNull(lastModified);
+ assertTrue(System.currentTimeMillis() >= lastModified.getTime());
+
+ ResourceImpl defaultETagResource = new ResourceImpl() {
+ protected Date getLastModified(FacesContext context) {
+ return new Date(12471234567890l);
+ }
+ ;
+ protected int getContentLength(FacesContext context) {
+ return 1297;
+ }
+ ;
+ };
+
+ assertEquals("W/\"1297-12471234567890\"", defaultETagResource.getEntityTag(facesContext));
+ }
+
+ public void testUserAgentNeedsUpdate() throws Exception {
+ long currentTime = System.currentTimeMillis();
+ MockResourceImpl actualResource = new MockResourceImpl();
+
+ actualResource.setLastModified(new Date(currentTime - 30000));
+
+ MockResourceImpl expiredResource = new MockResourceImpl();
+
+ expiredResource.setLastModified(new Date(currentTime - 10000));
+ this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
+ Util.formatHttpDate(new Date(currentTime - 20000))));
+ assertTrue(expiredResource.userAgentNeedsUpdate(facesContext));
+ assertFalse(actualResource.userAgentNeedsUpdate(facesContext));
+ }
+
+ private class MockResourceImpl extends AbstractBaseResource {
+ private int contentLength = -1;
+ private long currentTime;
+ private String entityTag;
+ private Date expired;
+ private InputStream inputStream;
+ private Date lastModified;
+ private int ttl;
+ private String version;
+
+ public MockResourceImpl() {
+ super();
+ setResourceName("org.richfaces.resource.MockResource");
+ }
+
+ @Override
+ protected int getContentLength(FacesContext context) {
+ return contentLength;
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ return inputStream;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.resource.ResourceImpl#getVersion()
+ */
+ @Override
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public void setContentLength(int contentLength) {
+ this.contentLength = contentLength;
+ }
+
+ public void setInputStream(InputStream inputStream) {
+ this.inputStream = inputStream;
+ }
+
+ @Override
+ protected Date getLastModified(FacesContext context) {
+ return lastModified;
+ }
+
+ public void setLastModified(Date lastModified) {
+ this.lastModified = lastModified;
+ }
+
+ @Override
+ protected Date getExpires(FacesContext context) {
+ return expired;
+ }
+
+ public void setExpired(Date expired) {
+ this.expired = expired;
+ }
+
+ @Override
+ protected String getEntityTag(FacesContext context) {
+ return entityTag;
+ }
+
+ /**
+ * @param entityTag the entityTag to set
+ */
+ public void setEntityTag(String entityTag) {
+ this.entityTag = entityTag;
+ }
+
+ @Override
+ boolean isResourceRequest() {
+ return true;
+ }
+
+ @Override
+ protected long getCurrentTime() {
+ return currentTime;
+ }
+
+ void setCurrentTime(long currentTime) {
+ this.currentTime = currentTime;
+ }
+
+ @Override
+ protected int getTimeToLive(FacesContext context) {
+ return ttl;
+ }
+
+ public void setTimeToLive(int ttl) {
+ this.ttl = ttl;
+ }
+ }
+
+
+ private class MockStateAwareResourceImpl extends MockResourceImpl implements StateHolder {
+ private boolean _transient = false;
+ private Object resourceState;
+
+ public MockStateAwareResourceImpl() {
+ super();
+ setResourceName("org.richfaces.resource.MockStateAwareResource");
+ }
+
+ public boolean isTransient() {
+ return _transient;
+ }
+
+ public void setTransient(boolean newTransientValue) {
+ this._transient = newTransientValue;
+ }
+
+ public Object saveState(FacesContext context) {
+ return resourceState;
+ }
+
+ public void restoreState(FacesContext context, Object state) {
+ this.resourceState = state;
+ }
+ }
+
+
+ private class ResourceImpl extends AbstractBaseResource {
+ public ResourceImpl() {
+ super();
+ setResourceName("org.richfaces.resource.ResourceImpl");
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractCacheableResourceTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractCacheableResourceTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractCacheableResourceTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,12 +19,17 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.io.IOException;
import java.io.InputStream;
+
import java.net.URL;
+
import java.text.SimpleDateFormat;
+
import java.util.Collections;
import java.util.Date;
import java.util.Locale;
@@ -35,279 +40,277 @@
import org.easymock.IAnswer;
import org.easymock.classextension.EasyMock;
+
import org.richfaces.test.AbstractFacesTest;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class AbstractCacheableResourceTest extends AbstractFacesTest {
+ private static final int MILLISECONDS_IN_HOUR = 60 * 60 * 1000;
- private static final int MILLISECONDS_IN_HOUR = 60 * 60 * 1000;
-
- /* HTTP Date format required by the HTTP/1.1 RFC */
+ /* HTTP Date format required by the HTTP/1.1 RFC */
private static final String RFC1123_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss zzz";
-
private static final SimpleDateFormat RFC1123_DATE_FORMATTER;
-
+
static {
- SimpleDateFormat format = new SimpleDateFormat(RFC1123_DATE_PATTERN, Locale.US);
- format.setTimeZone(TimeZone.getTimeZone("GMT"));
+ SimpleDateFormat format = new SimpleDateFormat(RFC1123_DATE_PATTERN, Locale.US);
- RFC1123_DATE_FORMATTER = format;
+ format.setTimeZone(TimeZone.getTimeZone("GMT"));
+ RFC1123_DATE_FORMATTER = format;
}
@Override
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
-
- /* (non-Javadoc)
- * @see org.richfaces.test.AbstractFacesTest#tearDown()
- */
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- public void testInitialRequest() throws Exception {
- MockAbstractResource defaultResource = new MockAbstractResource();
-
- assertNull(defaultResource.isMatchesEntityTag(facesContext));
- assertNull(defaultResource.isMatchesLastModified(facesContext));
-
- MockAbstractResource entityTaggedResource = new MockAbstractResource();
- entityTaggedResource.setEntityTag("3456");
- assertNull(entityTaggedResource.isMatchesEntityTag(facesContext));
- assertNull(entityTaggedResource.isMatchesLastModified(facesContext));
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.test.AbstractFacesTest#tearDown()
+ */
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- MockAbstractResource timeKnownResource = new MockAbstractResource();
- timeKnownResource.setLastModified(new Date(System.currentTimeMillis() - MILLISECONDS_IN_HOUR));
- assertNull(timeKnownResource.isMatchesEntityTag(facesContext));
- assertNull(timeKnownResource.isMatchesLastModified(facesContext));
- }
-
- public void testEntityTag() throws Exception {
- this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", "\"3456\""));
+ public void testInitialRequest() throws Exception {
+ MockAbstractResource defaultResource = new MockAbstractResource();
- MockAbstractResource defaultResource = new MockAbstractResource();
- assertFalse(defaultResource.isMatchesEntityTag(facesContext));
+ assertNull(defaultResource.isMatchesEntityTag(facesContext));
+ assertNull(defaultResource.isMatchesLastModified(facesContext));
- MockAbstractResource entityTaggedResource = new MockAbstractResource();
- entityTaggedResource.setEntityTag("\"3456\"");
- assertTrue(entityTaggedResource.isMatchesEntityTag(facesContext));
+ MockAbstractResource entityTaggedResource = new MockAbstractResource();
- MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
- unmatchedTaggedResource.setEntityTag("\"123\"");
- assertFalse(unmatchedTaggedResource.isMatchesEntityTag(facesContext));
- }
+ entityTaggedResource.setEntityTag("3456");
+ assertNull(entityTaggedResource.isMatchesEntityTag(facesContext));
+ assertNull(entityTaggedResource.isMatchesLastModified(facesContext));
- public void testWeakEntityTag() throws Exception {
- this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", "W/\"3456\""));
+ MockAbstractResource timeKnownResource = new MockAbstractResource();
- MockAbstractResource defaultResource = new MockAbstractResource();
- assertEquals(Boolean.FALSE, defaultResource.isMatchesEntityTag(facesContext));
+ timeKnownResource.setLastModified(new Date(System.currentTimeMillis() - MILLISECONDS_IN_HOUR));
+ assertNull(timeKnownResource.isMatchesEntityTag(facesContext));
+ assertNull(timeKnownResource.isMatchesLastModified(facesContext));
+ }
- MockAbstractResource entityTaggedResource = new MockAbstractResource();
- entityTaggedResource.setEntityTag("\"3456\"");
- assertEquals(Boolean.TRUE, entityTaggedResource.isMatchesEntityTag(facesContext));
+ public void testEntityTag() throws Exception {
+ this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", "\"3456\""));
- MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
- unmatchedTaggedResource.setEntityTag("\"123\"");
- assertEquals(Boolean.FALSE, unmatchedTaggedResource.isMatchesEntityTag(facesContext));
- }
+ MockAbstractResource defaultResource = new MockAbstractResource();
- public void testMultiEntityTags() throws Exception {
- this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", "W/\"3456\", \"012\""));
+ assertFalse(defaultResource.isMatchesEntityTag(facesContext));
- MockAbstractResource defaultResource = new MockAbstractResource();
- assertEquals(Boolean.FALSE, defaultResource.isMatchesEntityTag(facesContext));
+ MockAbstractResource entityTaggedResource = new MockAbstractResource();
- MockAbstractResource entityTaggedResource = new MockAbstractResource();
- entityTaggedResource.setEntityTag("\"3456\"");
- assertEquals(Boolean.TRUE, entityTaggedResource.isMatchesEntityTag(facesContext));
+ entityTaggedResource.setEntityTag("\"3456\"");
+ assertTrue(entityTaggedResource.isMatchesEntityTag(facesContext));
- MockAbstractResource anotherTaggedResource = new MockAbstractResource();
- anotherTaggedResource.setEntityTag("W/\"012\"");
- assertEquals(Boolean.TRUE, anotherTaggedResource.isMatchesEntityTag(facesContext));
-
- MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
- unmatchedTaggedResource.setEntityTag("\"123\"");
- assertEquals(Boolean.FALSE, unmatchedTaggedResource.isMatchesEntityTag(facesContext));
- }
-
- public void testIfModified() throws Exception {
- Date baseDate = new Date();
- Date beforeBaseDate = new Date(baseDate.getTime() - MILLISECONDS_IN_HOUR);
- Date afterBaseDate = new Date(baseDate.getTime() + MILLISECONDS_IN_HOUR);
+ MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
- this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since", RFC1123_DATE_FORMATTER.format(baseDate)));
+ unmatchedTaggedResource.setEntityTag("\"123\"");
+ assertFalse(unmatchedTaggedResource.isMatchesEntityTag(facesContext));
+ }
- MockAbstractResource defaultResource = new MockAbstractResource();
- assertEquals(Boolean.FALSE, defaultResource.isMatchesLastModified(facesContext));
-
- MockAbstractResource actualResource = new MockAbstractResource();
- actualResource.setLastModified(beforeBaseDate);
- assertEquals(Boolean.TRUE, actualResource.isMatchesLastModified(facesContext));
+ public void testWeakEntityTag() throws Exception {
+ this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", "W/\"3456\""));
- MockAbstractResource expiredResource = new MockAbstractResource();
- expiredResource.setLastModified(afterBaseDate);
- assertEquals(Boolean.FALSE, expiredResource.isMatchesLastModified(facesContext));
- }
+ MockAbstractResource defaultResource = new MockAbstractResource();
- private static class BooleanAnswer implements IAnswer<Boolean> {
- private Boolean value;
-
- public Boolean answer() throws Throwable {
- return value;
- }
+ assertEquals(Boolean.FALSE, defaultResource.isMatchesEntityTag(facesContext));
- public void setValue(Boolean value) {
- this.value = value;
- }
- }
-
- private static abstract class AbstractTestResource extends AbstractCacheableResource {
- @Override
- public String toString() {
- return "mock";
- }
-
- @Override
- public boolean isCacheable(FacesContext context) {
- return false;
- }
-
- @Override
- protected boolean isMatchesEntityTag(FacesContext context, String matchHeaderValue) {
- return super.isMatchesEntityTag(context, matchHeaderValue);
- }
+ MockAbstractResource entityTaggedResource = new MockAbstractResource();
- @Override
- protected boolean isMatchesLastModified(FacesContext context, String modifiedCondition) {
- return super.isMatchesLastModified(context, modifiedCondition);
- }
+ entityTaggedResource.setEntityTag("\"3456\"");
+ assertEquals(Boolean.TRUE, entityTaggedResource.isMatchesEntityTag(facesContext));
+
+ MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
+
+ unmatchedTaggedResource.setEntityTag("\"123\"");
+ assertEquals(Boolean.FALSE, unmatchedTaggedResource.isMatchesEntityTag(facesContext));
}
+ public void testMultiEntityTags() throws Exception {
+ this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", "W/\"3456\", \"012\""));
+
+ MockAbstractResource defaultResource = new MockAbstractResource();
+
+ assertEquals(Boolean.FALSE, defaultResource.isMatchesEntityTag(facesContext));
+
+ MockAbstractResource entityTaggedResource = new MockAbstractResource();
+
+ entityTaggedResource.setEntityTag("\"3456\"");
+ assertEquals(Boolean.TRUE, entityTaggedResource.isMatchesEntityTag(facesContext));
+
+ MockAbstractResource anotherTaggedResource = new MockAbstractResource();
+
+ anotherTaggedResource.setEntityTag("W/\"012\"");
+ assertEquals(Boolean.TRUE, anotherTaggedResource.isMatchesEntityTag(facesContext));
+
+ MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
+
+ unmatchedTaggedResource.setEntityTag("\"123\"");
+ assertEquals(Boolean.FALSE, unmatchedTaggedResource.isMatchesEntityTag(facesContext));
+ }
+
+ public void testIfModified() throws Exception {
+ Date baseDate = new Date();
+ Date beforeBaseDate = new Date(baseDate.getTime() - MILLISECONDS_IN_HOUR);
+ Date afterBaseDate = new Date(baseDate.getTime() + MILLISECONDS_IN_HOUR);
+
+ this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
+ RFC1123_DATE_FORMATTER.format(baseDate)));
+
+ MockAbstractResource defaultResource = new MockAbstractResource();
+
+ assertEquals(Boolean.FALSE, defaultResource.isMatchesLastModified(facesContext));
+
+ MockAbstractResource actualResource = new MockAbstractResource();
+
+ actualResource.setLastModified(beforeBaseDate);
+ assertEquals(Boolean.TRUE, actualResource.isMatchesLastModified(facesContext));
+
+ MockAbstractResource expiredResource = new MockAbstractResource();
+
+ expiredResource.setLastModified(afterBaseDate);
+ assertEquals(Boolean.FALSE, expiredResource.isMatchesLastModified(facesContext));
+ }
+
public void testUserAgentNeedsUpdate() throws Exception {
BooleanAnswer tagMatches = new BooleanAnswer();
BooleanAnswer lastModifiedMatches = new BooleanAnswer();
BooleanAnswer cacheable = new BooleanAnswer();
-
AbstractCacheableResource resource = EasyMock.createNiceMock(AbstractTestResource.class,
- AbstractTestResource.class.getDeclaredMethods());
+ AbstractTestResource.class.getDeclaredMethods());
EasyMock.expect(resource.isCacheable(facesContext)).andStubAnswer(cacheable);
String matchHeaderValue = RFC1123_DATE_FORMATTER.format(new Date());
+
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", matchHeaderValue));
EasyMock.expect(resource.isMatchesEntityTag(facesContext, matchHeaderValue)).andStubAnswer(tagMatches);
String modifiedCondition = "\"1234\"";
+
this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since", modifiedCondition));
- EasyMock.expect(resource.isMatchesLastModified(facesContext, modifiedCondition)).andStubAnswer(lastModifiedMatches);
-
+ EasyMock.expect(resource.isMatchesLastModified(facesContext,
+ modifiedCondition)).andStubAnswer(lastModifiedMatches);
EasyMock.replay(resource);
-
cacheable.setValue(false);
assertTrue(resource.userAgentNeedsUpdate(facesContext));
-
-
cacheable.setValue(true);
-
tagMatches.setValue(Boolean.TRUE);
lastModifiedMatches.setValue(Boolean.TRUE);
assertFalse(resource.userAgentNeedsUpdate(facesContext));
-
tagMatches.setValue(Boolean.FALSE);
lastModifiedMatches.setValue(Boolean.FALSE);
assertTrue(resource.userAgentNeedsUpdate(facesContext));
-
tagMatches.setValue(Boolean.FALSE);
lastModifiedMatches.setValue(Boolean.TRUE);
assertTrue(resource.userAgentNeedsUpdate(facesContext));
-
tagMatches.setValue(Boolean.TRUE);
lastModifiedMatches.setValue(Boolean.FALSE);
assertTrue(resource.userAgentNeedsUpdate(facesContext));
-
-
-
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", (String) null));
lastModifiedMatches.setValue(Boolean.FALSE);
assertTrue(resource.userAgentNeedsUpdate(facesContext));
-
lastModifiedMatches.setValue(Boolean.TRUE);
assertFalse(resource.userAgentNeedsUpdate(facesContext));
-
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", matchHeaderValue));
this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since", (String) null));
tagMatches.setValue(Boolean.FALSE);
assertTrue(resource.userAgentNeedsUpdate(facesContext));
-
tagMatches.setValue(Boolean.TRUE);
assertFalse(resource.userAgentNeedsUpdate(facesContext));
-
this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since", (String) null));
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match", (String) null));
assertTrue(resource.userAgentNeedsUpdate(facesContext));
-
cacheable.setValue(false);
assertTrue(resource.userAgentNeedsUpdate(facesContext));
}
+
+ private static abstract class AbstractTestResource extends AbstractCacheableResource {
+ @Override
+ public String toString() {
+ return "mock";
+ }
+
+ @Override
+ public boolean isCacheable(FacesContext context) {
+ return false;
+ }
+
+ @Override
+ protected boolean isMatchesEntityTag(FacesContext context, String matchHeaderValue) {
+ return super.isMatchesEntityTag(context, matchHeaderValue);
+ }
+
+ @Override
+ protected boolean isMatchesLastModified(FacesContext context, String modifiedCondition) {
+ return super.isMatchesLastModified(context, modifiedCondition);
+ }
+ }
+
+
+ private static class BooleanAnswer implements IAnswer<Boolean> {
+ private Boolean value;
+
+ public Boolean answer() throws Throwable {
+ return value;
+ }
+
+ public void setValue(Boolean value) {
+ this.value = value;
+ }
+ }
}
-
class MockAbstractResource extends AbstractCacheableResource {
+ private String entityTag;
+ private Date lastModified;
- private String entityTag;
-
- private Date lastModified;
-
- public void setEntityTag(String entityTag) {
- this.entityTag = entityTag;
- }
+ public void setEntityTag(String entityTag) {
+ this.entityTag = entityTag;
+ }
- public void setLastModified(Date lastModified) {
- this.lastModified = lastModified;
- }
+ public void setLastModified(Date lastModified) {
+ this.lastModified = lastModified;
+ }
- @Override
- protected String getEntityTag(FacesContext context) {
- return entityTag;
- }
+ @Override
+ protected String getEntityTag(FacesContext context) {
+ return entityTag;
+ }
- @Override
- protected Date getLastModified(FacesContext context) {
- return lastModified;
- }
+ @Override
+ protected Date getLastModified(FacesContext context) {
+ return lastModified;
+ }
- @Override
- public InputStream getInputStream() throws IOException {
- throw new UnsupportedOperationException();
- }
+ @Override
+ public InputStream getInputStream() throws IOException {
+ throw new UnsupportedOperationException();
+ }
- @Override
- public String getRequestPath() {
- throw new UnsupportedOperationException();
- }
+ @Override
+ public String getRequestPath() {
+ throw new UnsupportedOperationException();
+ }
- @Override
- public Map<String, String> getResponseHeaders() {
- throw new UnsupportedOperationException();
- }
+ @Override
+ public Map<String, String> getResponseHeaders() {
+ throw new UnsupportedOperationException();
+ }
- @Override
- public URL getURL() {
- throw new UnsupportedOperationException();
- }
+ @Override
+ public URL getURL() {
+ throw new UnsupportedOperationException();
+ }
- @Override
- public boolean isCacheable(FacesContext context) {
- throw new UnsupportedOperationException();
- }
-
+ @Override
+ public boolean isCacheable(FacesContext context) {
+ throw new UnsupportedOperationException();
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/CacheableResourceImpl.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/CacheableResourceImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/CacheableResourceImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,11 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
+
import java.util.Date;
import java.util.Map;
@@ -37,47 +40,49 @@
*/
public class CacheableResourceImpl extends AbstractBaseResource {
- /* (non-Javadoc)
- * @see org.richfaces.resource.AbstractBaseResource#getInputStream()
- */
- @Override
- public InputStream getInputStream() {
- return new ByteArrayInputStream(getContentToEcho());
- }
+ /*
+ * (non-Javadoc)
+ * @see org.richfaces.resource.AbstractBaseResource#getInputStream()
+ */
+ @Override
+ public InputStream getInputStream() {
+ return new ByteArrayInputStream(getContentToEcho());
+ }
- private byte[] getContentToEcho() {
- ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
- Map<String, String> headers = externalContext.getRequestHeaderMap();
- Object content = headers.get(ResourceHandlerImplTest.ECHO_HEADER);
- try {
- return content.toString().getBytes("US-ASCII");
- } catch (UnsupportedEncodingException e) {
- throw new FacesException(e.getMessage(), e);
- }
- }
+ private byte[] getContentToEcho() {
+ ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
+ Map<String, String> headers = externalContext.getRequestHeaderMap();
+ Object content = headers.get(ResourceHandlerImplTest.ECHO_HEADER);
- @Override
- protected int getContentLength(FacesContext context) {
- return getContentToEcho().length;
- }
-
- @Override
- public String getContentType() {
- return "text/plain";
- }
-
- @Override
- long getCurrentTime() {
- return ResourceHandlerImplTest.currentTime.getTime();
- }
-
- @Override
- protected Date getLastModified(FacesContext context) {
- return ResourceHandlerImplTest.lastModified;
- }
-
- @Override
- protected Date getExpires(FacesContext context) {
- return ResourceHandlerImplTest.expires;
- }
+ try {
+ return content.toString().getBytes("US-ASCII");
+ } catch (UnsupportedEncodingException e) {
+ throw new FacesException(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ protected int getContentLength(FacesContext context) {
+ return getContentToEcho().length;
+ }
+
+ @Override
+ public String getContentType() {
+ return "text/plain";
+ }
+
+ @Override
+ long getCurrentTime() {
+ return ResourceHandlerImplTest.currentTime.getTime();
+ }
+
+ @Override
+ protected Date getLastModified(FacesContext context) {
+ return ResourceHandlerImplTest.lastModified;
+ }
+
+ @Override
+ protected Date getExpires(FacesContext context) {
+ return ResourceHandlerImplTest.expires;
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/CachedResourceImplTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/CachedResourceImplTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/CachedResourceImplTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.io.BufferedReader;
@@ -26,7 +28,9 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
+
import java.net.URL;
+
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
@@ -47,249 +51,268 @@
*/
public class CachedResourceImplTest extends AbstractFacesTest {
- /**
- *
- */
- private static final String EXPIRES = "Expires";
- /**
- *
- */
- private static final String CACHE_CONTROL = "Cache-Control";
- /**
- *
- */
- private static final String LAST_MODIFIED = "Last-Modified";
+ /**
+ *
+ */
+ private static final String CACHE_CONTROL = "Cache-Control";
- @Override
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
+ /**
+ *
+ */
+ private static final String EXPIRES = "Expires";
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ /**
+ *
+ */
+ private static final String LAST_MODIFIED = "Last-Modified";
- private class MockHeadersResourceImpl extends Resource {
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- private Map<String, String> headers;
-
- private InputStream stream;
-
- public MockHeadersResourceImpl(Map<String, String> headers,
- InputStream stream) {
- super();
- setResourceName(getClass().getName());
- setContentType("image/png");
- this.headers = headers;
- this.stream = stream != null ? stream : new ByteArrayInputStream(new byte[0]);
- }
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- @Override
- public Map<String, String> getResponseHeaders() {
- return headers;
- }
+ private CachedResourceImpl createCachedResource() throws IOException {
+ return createCachedResource(createTestHeaders());
+ }
- @Override
- public InputStream getInputStream() throws IOException {
- return stream;
- }
+ private CachedResourceImpl createCachedResource(Map<String, String> headers) throws IOException {
+ return createCachedResource(headers, null);
+ }
- @Override
- public String getRequestPath() {
- throw new UnsupportedOperationException();
- }
+ private CachedResourceImpl createCachedResource(Map<String, String> headers, InputStream stream)
+ throws IOException {
+ MockHeadersResourceImpl mockResource = new MockHeadersResourceImpl(headers, stream);
+ CachedResourceImpl cachedResource = new MockCachedResourceImpl();
- @Override
- public URL getURL() {
- throw new UnsupportedOperationException();
- }
+ cachedResource.initialize(mockResource);
- @Override
- public boolean userAgentNeedsUpdate(FacesContext context) {
- throw new UnsupportedOperationException();
- }
+ return cachedResource;
+ }
- };
+ private Map<String, String> createTestHeaders() {
+ Map<String, String> headers = new HashMap<String, String>();
- private class MockCachedResourceImpl extends CachedResourceImpl {
- private final long currentTime;
-
- @Override
- long getCurrentTime() {
- return currentTime;
- }
-
- public MockCachedResourceImpl() {
- super();
+ headers.put("ETag", "W/\"123\"");
+ headers.put(LAST_MODIFIED, "Tue, 21 Jul 2009 12:45:09 GMT");
+ headers.put(EXPIRES, "Tue, 28 Jul 2009 12:45:09 GMT");
+ headers.put(CACHE_CONTROL, "public, max-age=86400");
- this.currentTime = createBaseDateCalendar().getTimeInMillis();
- }
+ return headers;
+ }
- }
-
- private CachedResourceImpl createCachedResource() throws IOException {
- return createCachedResource(createTestHeaders());
- }
-
- private CachedResourceImpl createCachedResource(Map<String, String> headers) throws IOException {
- return createCachedResource(headers, null);
- }
-
- private CachedResourceImpl createCachedResource(Map<String, String> headers, InputStream stream) throws IOException {
- MockHeadersResourceImpl mockResource = new MockHeadersResourceImpl(headers, stream);
- CachedResourceImpl cachedResource = new MockCachedResourceImpl();
- cachedResource.initialize(mockResource);
- return cachedResource;
- }
-
- private Map<String, String> createTestHeaders() {
- Map<String, String> headers = new HashMap<String, String>();
- headers.put("ETag", "W/\"123\"");
- headers.put(LAST_MODIFIED, "Tue, 21 Jul 2009 12:45:09 GMT");
- headers.put(EXPIRES, "Tue, 28 Jul 2009 12:45:09 GMT");
- headers.put(CACHE_CONTROL, "public, max-age=86400");
- return headers;
- }
-
- private Calendar createBaseDateCalendar() {
- Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- calendar.clear();
- calendar.set(2009, Calendar.JULY, 21, 12, 45, 9);
- return calendar;
- }
-
- public void testInitialize() throws Exception {
- CachedResourceImpl cachedResource = createCachedResource();
- Calendar calendar = createBaseDateCalendar();
- Date baseDate = calendar.getTime();
-
- assertEquals("W/\"123\"", cachedResource.getEntityTag(facesContext));
- assertEquals(baseDate, cachedResource.getLastModified(facesContext));
- assertEquals(createTestHeaders(), cachedResource.getResponseHeaders());
- assertEquals("image/png", cachedResource.getContentType());
+ private Calendar createBaseDateCalendar() {
+ Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- Date expired = cachedResource.getExpired(facesContext);
- assertNotNull(expired);
+ calendar.clear();
+ calendar.set(2009, Calendar.JULY, 21, 12, 45, 9);
- assertTrue(expired.after(baseDate));
- calendar.add(Calendar.DATE, 1);
- assertFalse(calendar.getTime().before(expired));
- }
+ return calendar;
+ }
- public void testInitializeExpires() throws Exception {
- Map<String, String> headers = createTestHeaders();
- headers.remove(CACHE_CONTROL);
- CachedResourceImpl cachedResource = createCachedResource(headers);
+ public void testInitialize() throws Exception {
+ CachedResourceImpl cachedResource = createCachedResource();
+ Calendar calendar = createBaseDateCalendar();
+ Date baseDate = calendar.getTime();
- Date expired = cachedResource.getExpired(facesContext);
- assertNotNull(expired);
+ assertEquals("W/\"123\"", cachedResource.getEntityTag(facesContext));
+ assertEquals(baseDate, cachedResource.getLastModified(facesContext));
+ assertEquals(createTestHeaders(), cachedResource.getResponseHeaders());
+ assertEquals("image/png", cachedResource.getContentType());
- Calendar calendar = createBaseDateCalendar();
- assertTrue(expired.after(calendar.getTime()));
- calendar.add(Calendar.DATE, 1);
- assertFalse(expired.before(calendar.getTime()));
- calendar.add(Calendar.DATE, 6);
- assertTrue(expired.before(calendar.getTime()));
- }
+ Date expired = cachedResource.getExpired(facesContext);
- public void testInitializeMaxAge() throws Exception {
- Map<String, String> headers = createTestHeaders();
- headers.remove(EXPIRES);
- CachedResourceImpl cachedResource = createCachedResource(headers);
+ assertNotNull(expired);
+ assertTrue(expired.after(baseDate));
+ calendar.add(Calendar.DATE, 1);
+ assertFalse(calendar.getTime().before(expired));
+ }
- Date expired = cachedResource.getExpired(facesContext);
- assertNotNull(expired);
+ public void testInitializeExpires() throws Exception {
+ Map<String, String> headers = createTestHeaders();
- Calendar calendar = createBaseDateCalendar();
- assertTrue(expired.after(calendar.getTime()));
- calendar.add(Calendar.DATE, 1);
- assertTrue(expired.before(calendar.getTime()));
- }
+ headers.remove(CACHE_CONTROL);
- public void testInitializeSMaxAge() throws Exception {
- Map<String, String> headers = createTestHeaders();
- headers.put(CACHE_CONTROL, "public, max-age=86400, s-maxage=172800");
- CachedResourceImpl cachedResource = createCachedResource(headers);
+ CachedResourceImpl cachedResource = createCachedResource(headers);
+ Date expired = cachedResource.getExpired(facesContext);
- Date expired = cachedResource.getExpired(facesContext);
- assertNotNull(expired);
- Calendar calendar = createBaseDateCalendar();
+ assertNotNull(expired);
- assertTrue(expired.after(calendar.getTime()));
- calendar.add(Calendar.DATE, 1);
- assertFalse(expired.before(calendar.getTime()));
- calendar.add(Calendar.DATE, 1);
- assertTrue(expired.before(calendar.getTime()));
- }
-
- public void testGetStream() throws Exception {
- ByteArrayInputStream testStream = new ByteArrayInputStream("test".getBytes("US-ASCII"));
+ Calendar calendar = createBaseDateCalendar();
- CachedResourceImpl cachedResource = createCachedResource(createTestHeaders(), testStream);
+ assertTrue(expired.after(calendar.getTime()));
+ calendar.add(Calendar.DATE, 1);
+ assertFalse(expired.before(calendar.getTime()));
+ calendar.add(Calendar.DATE, 6);
+ assertTrue(expired.before(calendar.getTime()));
+ }
- InputStream stream = cachedResource.getInputStream();
- assertNotNull(stream);
-
- BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "US-ASCII"));
- assertEquals("test", reader.readLine());
- assertNull(reader.readLine());
- reader.close();
- }
-
- public void testGetBigStream() throws Exception {
- byte[] bs = new byte[127123];
- new Random().nextBytes(bs);
+ public void testInitializeMaxAge() throws Exception {
+ Map<String, String> headers = createTestHeaders();
- ByteArrayInputStream bigStream = new ByteArrayInputStream(bs);
- CachedResourceImpl cachedResource = createCachedResource(createTestHeaders(), bigStream);
-
- InputStream stream = cachedResource.getInputStream();
- byte[] testBs = new byte[bs.length];
- assertEquals(testBs.length, stream.read(testBs));
- assertTrue(Arrays.equals(testBs, bs));
- assertEquals(-1, stream.read());
- stream.close();
- }
-
- public void testCacheable() throws Exception {
- CachedResourceImpl cachedResource = createCachedResource();
-
- assertTrue(cachedResource.isCacheable(facesContext));
- }
-
- public void testDefaults() throws Exception {
- CachedResourceImpl cachedResource = createCachedResource();
+ headers.remove(EXPIRES);
- try {
- cachedResource.getURL();
-
- fail();
- } catch (UnsupportedOperationException e) {
- //ok
- }
+ CachedResourceImpl cachedResource = createCachedResource(headers);
+ Date expired = cachedResource.getExpired(facesContext);
- try {
- cachedResource.getRequestPath();
-
- fail();
- } catch (UnsupportedOperationException e) {
- //ok
- }
- }
+ assertNotNull(expired);
- public void testUserAgentNeedsUpdate() throws Exception {
- CachedResourceImpl cachedResource = createCachedResource();
-
- this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since", "Tue, 21 Jul 2009 14:45:09 GMT"));
- assertFalse(cachedResource.userAgentNeedsUpdate(facesContext));
- }
+ Calendar calendar = createBaseDateCalendar();
- public void testUserAgentNeedsUpdate2() throws Exception {
- CachedResourceImpl cachedResource = createCachedResource();
-
- this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since", "Tue, 21 Jul 2009 09:45:09 GMT"));
- assertTrue(cachedResource.userAgentNeedsUpdate(facesContext));
- }
-}
\ No newline at end of file
+ assertTrue(expired.after(calendar.getTime()));
+ calendar.add(Calendar.DATE, 1);
+ assertTrue(expired.before(calendar.getTime()));
+ }
+
+ public void testInitializeSMaxAge() throws Exception {
+ Map<String, String> headers = createTestHeaders();
+
+ headers.put(CACHE_CONTROL, "public, max-age=86400, s-maxage=172800");
+
+ CachedResourceImpl cachedResource = createCachedResource(headers);
+ Date expired = cachedResource.getExpired(facesContext);
+
+ assertNotNull(expired);
+
+ Calendar calendar = createBaseDateCalendar();
+
+ assertTrue(expired.after(calendar.getTime()));
+ calendar.add(Calendar.DATE, 1);
+ assertFalse(expired.before(calendar.getTime()));
+ calendar.add(Calendar.DATE, 1);
+ assertTrue(expired.before(calendar.getTime()));
+ }
+
+ public void testGetStream() throws Exception {
+ ByteArrayInputStream testStream = new ByteArrayInputStream("test".getBytes("US-ASCII"));
+ CachedResourceImpl cachedResource = createCachedResource(createTestHeaders(), testStream);
+ InputStream stream = cachedResource.getInputStream();
+
+ assertNotNull(stream);
+
+ BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "US-ASCII"));
+
+ assertEquals("test", reader.readLine());
+ assertNull(reader.readLine());
+ reader.close();
+ }
+
+ public void testGetBigStream() throws Exception {
+ byte[] bs = new byte[127123];
+
+ new Random().nextBytes(bs);
+
+ ByteArrayInputStream bigStream = new ByteArrayInputStream(bs);
+ CachedResourceImpl cachedResource = createCachedResource(createTestHeaders(), bigStream);
+ InputStream stream = cachedResource.getInputStream();
+ byte[] testBs = new byte[bs.length];
+
+ assertEquals(testBs.length, stream.read(testBs));
+ assertTrue(Arrays.equals(testBs, bs));
+ assertEquals(-1, stream.read());
+ stream.close();
+ }
+
+ public void testCacheable() throws Exception {
+ CachedResourceImpl cachedResource = createCachedResource();
+
+ assertTrue(cachedResource.isCacheable(facesContext));
+ }
+
+ public void testDefaults() throws Exception {
+ CachedResourceImpl cachedResource = createCachedResource();
+
+ try {
+ cachedResource.getURL();
+ fail();
+ } catch (UnsupportedOperationException e) {
+
+ // ok
+ }
+
+ try {
+ cachedResource.getRequestPath();
+ fail();
+ } catch (UnsupportedOperationException e) {
+
+ // ok
+ }
+ }
+
+ public void testUserAgentNeedsUpdate() throws Exception {
+ CachedResourceImpl cachedResource = createCachedResource();
+
+ this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
+ "Tue, 21 Jul 2009 14:45:09 GMT"));
+ assertFalse(cachedResource.userAgentNeedsUpdate(facesContext));
+ }
+
+ public void testUserAgentNeedsUpdate2() throws Exception {
+ CachedResourceImpl cachedResource = createCachedResource();
+
+ this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
+ "Tue, 21 Jul 2009 09:45:09 GMT"));
+ assertTrue(cachedResource.userAgentNeedsUpdate(facesContext));
+ }
+
+ private class MockCachedResourceImpl extends CachedResourceImpl {
+ private final long currentTime;
+
+ public MockCachedResourceImpl() {
+ super();
+ this.currentTime = createBaseDateCalendar().getTimeInMillis();
+ }
+
+ @Override
+ long getCurrentTime() {
+ return currentTime;
+ }
+ }
+
+
+ private class MockHeadersResourceImpl extends Resource {
+ private Map<String, String> headers;
+ private InputStream stream;
+
+ public MockHeadersResourceImpl(Map<String, String> headers, InputStream stream) {
+ super();
+ setResourceName(getClass().getName());
+ setContentType("image/png");
+ this.headers = headers;
+ this.stream = stream != null ? stream : new ByteArrayInputStream(new byte[0]);
+ }
+
+ @Override
+ public Map<String, String> getResponseHeaders() {
+ return headers;
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return stream;
+ }
+
+ @Override
+ public String getRequestPath() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public URL getURL() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean userAgentNeedsUpdate(FacesContext context) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+
+ ;
+}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/EmptyStreamResource.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/EmptyStreamResource.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/EmptyStreamResource.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.io.ByteArrayInputStream;
@@ -29,12 +31,10 @@
* @since 4.0
*/
public class EmptyStreamResource extends AbstractBaseResource {
+ protected InputStream EMPTY_STREAM = new ByteArrayInputStream(new byte[0]);
- protected InputStream EMPTY_STREAM = new ByteArrayInputStream(new byte[0]);
-
- @Override
- public InputStream getInputStream() {
- return EMPTY_STREAM;
- }
-
+ @Override
+ public InputStream getInputStream() {
+ return EMPTY_STREAM;
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/MarkerFileResourceImpl.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/MarkerFileResourceImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/MarkerFileResourceImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,13 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-package org.richfaces.resource;
+package org.richfaces.resource;
+
/**
* @author Nick Belaevski
* @since 4.0
*/
-public class MarkerFileResourceImpl extends EmptyStreamResource {
-
-}
+public class MarkerFileResourceImpl extends EmptyStreamResource {}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/NoMarkerFileResourceImpl.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/NoMarkerFileResourceImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/NoMarkerFileResourceImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,13 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-package org.richfaces.resource;
+package org.richfaces.resource;
+
/**
* @author Nick Belaevski
* @since 4.0
*/
-public class NoMarkerFileResourceImpl extends EmptyStreamResource {
-
-}
+public class NoMarkerFileResourceImpl extends EmptyStreamResource {}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/NonCacheableResourceImpl.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/NonCacheableResourceImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/NonCacheableResourceImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import javax.faces.context.FacesContext;
@@ -28,9 +30,8 @@
* @since 4.0
*/
public class NonCacheableResourceImpl extends CacheableResourceImpl {
-
- @Override
- public boolean isCacheable(FacesContext context) {
- return false;
- }
+ @Override
+ public boolean isCacheable(FacesContext context) {
+ return false;
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceHandlerImplTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceHandlerImplTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceHandlerImplTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,18 +19,24 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.io.File;
+
import java.net.URL;
+
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.faces.application.ResourceHandler;
+
import javax.servlet.http.HttpServletResponse;
import org.easymock.classextension.EasyMock;
+
import org.richfaces.test.AbstractFacesTest;
import org.richfaces.test.LocalWebClient;
import org.richfaces.util.Util;
@@ -38,207 +44,213 @@
import com.gargoylesoftware.htmlunit.WebRequestSettings;
import com.gargoylesoftware.htmlunit.WebResponse;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class ResourceHandlerImplTest extends AbstractFacesTest {
+ protected static final String ECHO_HEADER = "RichFaces-Echo";
+ private static final String IF_MODIFIED_SINCE = "If-Modified-Since";
+ private static final String RESOURCES_FOLDER_PATH = "resources/";
+ private static final String TEST_RESOURCE_NAME = RESOURCES_FOLDER_PATH + "defaultResourceHandlerResource.js";
+ protected static final Date currentTime;
+ protected static final Date expires;
+ protected static final Date lastModified;
- private static final String IF_MODIFIED_SINCE = "If-Modified-Since";
+ static {
+ Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- protected static final String ECHO_HEADER = "RichFaces-Echo";
+ currentTime = calendar.getTime();
+ calendar.add(Calendar.DATE, -1);
+ lastModified = calendar.getTime();
+ calendar.add(Calendar.DATE, 15);
+ expires = calendar.getTime();
+ }
- protected static final Date currentTime;
+ private LocalWebClient webClient;
- protected static final Date lastModified;
+ private void addClasspathResources() {
+ ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+ File testResourceFile = new File(classLoader.getResource(TEST_RESOURCE_NAME).getFile());
+ File testResourceFolder = testResourceFile.getParentFile();
- protected static final Date expires;
+ facesServer.addResourcesFromDirectory("/" + RESOURCES_FOLDER_PATH, testResourceFolder);
+ }
- static {
- Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ addClasspathResources();
+ webClient = new LocalWebClient(this.facesServer);
- currentTime = calendar.getTime();
- calendar.add(Calendar.DATE, -1);
- lastModified = calendar.getTime();
- calendar.add(Calendar.DATE, 15);
- expires = calendar.getTime();
- }
+ // quick fix for https://sourceforge.net/tracker/?func=detail&aid=2821888&group_id=47038&a...
+ webClient.setRedirectEnabled(false);
+ }
- private LocalWebClient webClient;
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ webClient = null;
+ }
- private static final String RESOURCES_FOLDER_PATH = "resources/";
- private static final String TEST_RESOURCE_NAME = RESOURCES_FOLDER_PATH +
- "defaultResourceHandlerResource.js";
+ public void testReadCacheableResource() throws Exception {
+ WebRequestSettings webRequestSettings =
+ new WebRequestSettings(new URL("http://localhost/rfRes/org.richfaces.resource.CacheableResourceImpl.jsf"));
-
- private void addClasspathResources() {
- ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- File testResourceFile = new File(classLoader.getResource(TEST_RESOURCE_NAME).getFile());
- File testResourceFolder = testResourceFile.getParentFile();
- facesServer.addResourcesFromDirectory("/" + RESOURCES_FOLDER_PATH, testResourceFolder);
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
+ webRequestSettings.getAdditionalHeaders().put(ECHO_HEADER, "ping?");
- addClasspathResources();
- webClient = new LocalWebClient(this.facesServer);
- //quick fix for https://sourceforge.net/tracker/?func=detail&aid=2821888&group_id=47038&a...
- webClient.setRedirectEnabled(false);
- }
+ WebResponse webResponse = webClient.loadWebResponse(webRequestSettings);
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
+ assertEquals(HttpServletResponse.SC_OK, webResponse.getStatusCode());
+ assertEquals(Util.formatHttpDate(lastModified.getTime()), webResponse.getResponseHeaderValue("Last-Modified"));
+ assertEquals(Util.formatHttpDate(currentTime.getTime()), webResponse.getResponseHeaderValue("Date"));
+ assertEquals(Util.formatHttpDate(expires.getTime()), webResponse.getResponseHeaderValue("Expires"));
+ assertEquals("max-age=1209600", webResponse.getResponseHeaderValue("Cache-Control"));
+ assertTrue(webResponse.getResponseHeaderValue("Content-Type").startsWith("text/plain"));
+ assertEquals("W/\"" + "ping?".length() + "-" + lastModified.getTime() + "\"",
+ webResponse.getResponseHeaderValue("ETag"));
+ assertNull(webResponse.getResponseHeaderValue("Pragma"));
+ assertEquals("ping?", webResponse.getContentAsString("US-ASCII"));
+ webRequestSettings.getAdditionalHeaders().put(ECHO_HEADER, "pong");
- webClient = null;
- }
+ WebResponse cachedWebResponse = webClient.loadWebResponse(webRequestSettings);
- public void testReadCacheableResource() throws Exception {
- WebRequestSettings webRequestSettings = new WebRequestSettings(
- new URL("http://localhost/rfRes/org.richfaces.resource.CacheableResourceImpl.jsf"));
- webRequestSettings.getAdditionalHeaders().put(ECHO_HEADER, "ping?");
+ assertEquals(HttpServletResponse.SC_OK, cachedWebResponse.getStatusCode());
+ assertEquals("ping?", cachedWebResponse.getContentAsString("US-ASCII"));
+ webRequestSettings.getAdditionalHeaders().put(IF_MODIFIED_SINCE, Util.formatHttpDate(currentTime));
- WebResponse webResponse = webClient.loadWebResponse(webRequestSettings);
- assertEquals(HttpServletResponse.SC_OK, webResponse.getStatusCode());
- assertEquals(Util.formatHttpDate(lastModified.getTime()), webResponse.getResponseHeaderValue("Last-Modified"));
- assertEquals(Util.formatHttpDate(currentTime.getTime()), webResponse.getResponseHeaderValue("Date"));
- assertEquals(Util.formatHttpDate(expires.getTime()), webResponse.getResponseHeaderValue("Expires"));
- assertEquals("max-age=1209600", webResponse.getResponseHeaderValue("Cache-Control"));
- assertTrue(webResponse.getResponseHeaderValue("Content-Type").startsWith("text/plain"));
- assertEquals("W/\"" + "ping?".length() + "-" + lastModified.getTime() + "\"", webResponse.getResponseHeaderValue("ETag"));
- assertNull(webResponse.getResponseHeaderValue("Pragma"));
+ WebResponse cachedWebResponse2 = webClient.loadWebResponse(webRequestSettings);
- assertEquals("ping?", webResponse.getContentAsString("US-ASCII"));
+ assertEquals(HttpServletResponse.SC_NOT_MODIFIED, cachedWebResponse2.getStatusCode());
+ }
- webRequestSettings.getAdditionalHeaders().put(ECHO_HEADER, "pong");
- WebResponse cachedWebResponse = webClient.loadWebResponse(webRequestSettings);
- assertEquals(HttpServletResponse.SC_OK, cachedWebResponse.getStatusCode());
- assertEquals("ping?", cachedWebResponse.getContentAsString("US-ASCII"));
+ public void testReadNonCacheableResource() throws Exception {
+ WebRequestSettings webRequestSettings =
+ new WebRequestSettings(
+ new URL("http://localhost/rfRes/org.richfaces.resource.NonCacheableResourceImpl.jsf"));
- webRequestSettings.getAdditionalHeaders().put(IF_MODIFIED_SINCE, Util.formatHttpDate(currentTime));
- WebResponse cachedWebResponse2 = webClient.loadWebResponse(webRequestSettings);
- assertEquals(HttpServletResponse.SC_NOT_MODIFIED, cachedWebResponse2.getStatusCode());
- }
+ webRequestSettings.getAdditionalHeaders().put(ECHO_HEADER, "ping?");
- public void testReadNonCacheableResource() throws Exception {
- WebRequestSettings webRequestSettings = new WebRequestSettings(
- new URL("http://localhost/rfRes/org.richfaces.resource.NonCacheableResourceImpl.jsf"));
- webRequestSettings.getAdditionalHeaders().put(ECHO_HEADER, "ping?");
+ WebResponse webResponse = webClient.loadWebResponse(webRequestSettings);
- WebResponse webResponse = webClient.loadWebResponse(webRequestSettings);
- assertEquals(HttpServletResponse.SC_OK, webResponse.getStatusCode());
- assertEquals(Util.formatHttpDate(lastModified.getTime()), webResponse.getResponseHeaderValue("Last-Modified"));
- assertEquals(Util.formatHttpDate(currentTime.getTime()), webResponse.getResponseHeaderValue("Date"));
- assertEquals("0", webResponse.getResponseHeaderValue("Expires"));
- assertEquals("max-age=0, no-store, no-cache", webResponse.getResponseHeaderValue("Cache-Control"));
- assertTrue(webResponse.getResponseHeaderValue("Content-Type").startsWith("text/plain"));
- assertNull(webResponse.getResponseHeaderValue("ETag"));
- assertEquals("no-cache", webResponse.getResponseHeaderValue("Pragma"));
+ assertEquals(HttpServletResponse.SC_OK, webResponse.getStatusCode());
+ assertEquals(Util.formatHttpDate(lastModified.getTime()), webResponse.getResponseHeaderValue("Last-Modified"));
+ assertEquals(Util.formatHttpDate(currentTime.getTime()), webResponse.getResponseHeaderValue("Date"));
+ assertEquals("0", webResponse.getResponseHeaderValue("Expires"));
+ assertEquals("max-age=0, no-store, no-cache", webResponse.getResponseHeaderValue("Cache-Control"));
+ assertTrue(webResponse.getResponseHeaderValue("Content-Type").startsWith("text/plain"));
+ assertNull(webResponse.getResponseHeaderValue("ETag"));
+ assertEquals("no-cache", webResponse.getResponseHeaderValue("Pragma"));
+ assertEquals("ping?", webResponse.getContentAsString("US-ASCII"));
+ webRequestSettings.getAdditionalHeaders().put(ECHO_HEADER, "pong");
- assertEquals("ping?", webResponse.getContentAsString("US-ASCII"));
+ WebResponse cachedWebResponse = webClient.loadWebResponse(webRequestSettings);
- webRequestSettings.getAdditionalHeaders().put(ECHO_HEADER, "pong");
- WebResponse cachedWebResponse = webClient.loadWebResponse(webRequestSettings);
- assertEquals(HttpServletResponse.SC_OK, cachedWebResponse.getStatusCode());
- assertEquals("pong", cachedWebResponse.getContentAsString("US-ASCII"));
+ assertEquals(HttpServletResponse.SC_OK, cachedWebResponse.getStatusCode());
+ assertEquals("pong", cachedWebResponse.getContentAsString("US-ASCII"));
+ webRequestSettings.getAdditionalHeaders().put(IF_MODIFIED_SINCE, Util.formatHttpDate(currentTime));
- webRequestSettings.getAdditionalHeaders().put(IF_MODIFIED_SINCE, Util.formatHttpDate(currentTime));
- WebResponse cachedWebResponse2 = webClient.loadWebResponse(webRequestSettings);
- assertEquals(HttpServletResponse.SC_OK, cachedWebResponse2.getStatusCode());
- }
+ WebResponse cachedWebResponse2 = webClient.loadWebResponse(webRequestSettings);
- public void testNonExistingResource() throws Exception {
- WebRequestSettings emptyResourceNameSettings = new WebRequestSettings(
- new URL("http://localhost/rfRes/x.jsf"));
+ assertEquals(HttpServletResponse.SC_OK, cachedWebResponse2.getStatusCode());
+ }
- WebResponse emptyResourceNameResponse = webClient.loadWebResponse(emptyResourceNameSettings);
- assertEquals(HttpServletResponse.SC_NOT_FOUND, emptyResourceNameResponse.getStatusCode());
- }
+ public void testNonExistingResource() throws Exception {
+ WebRequestSettings emptyResourceNameSettings = new WebRequestSettings(new URL("http://localhost/rfRes/x.jsf"));
+ WebResponse emptyResourceNameResponse = webClient.loadWebResponse(emptyResourceNameSettings);
- public void testDefaultMojarraResource() throws Exception {
- WebRequestSettings mojarraResourceSettings = new WebRequestSettings(
- new URL("http://localhost/javax.faces.resource/defaultResourceHandlerResource.js.jsf"));
- WebResponse mojarraResourceNameResponse = webClient.loadWebResponse(mojarraResourceSettings);
- assertEquals(HttpServletResponse.SC_OK, mojarraResourceNameResponse.getStatusCode());
- }
+ assertEquals(HttpServletResponse.SC_NOT_FOUND, emptyResourceNameResponse.getStatusCode());
+ }
- public void testMarkerFile() throws Exception {
- ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ public void testDefaultMojarraResource() throws Exception {
+ WebRequestSettings mojarraResourceSettings =
+ new WebRequestSettings(
+ new URL("http://localhost/javax.faces.resource/defaultResourceHandlerResource.js.jsf"));
+ WebResponse mojarraResourceNameResponse = webClient.loadWebResponse(mojarraResourceSettings);
- assertNotNull(Class.forName("org.richfaces.resource.MarkerFileResourceImpl",
- true, contextClassLoader));
- assertNotNull(contextClassLoader.getResource("META-INF/org.richfaces.resource.MarkerFileResourceImpl.resource.properties"));
+ assertEquals(HttpServletResponse.SC_OK, mojarraResourceNameResponse.getStatusCode());
+ }
- WebRequestSettings markerFileRequestSettings = new WebRequestSettings(
- new URL("http://localhost/rfRes/org.richfaces.resource.MarkerFileResourceImpl.jsf"));
- WebResponse markerFileResponse = webClient.loadWebResponse(markerFileRequestSettings);
- assertEquals(HttpServletResponse.SC_OK, markerFileResponse.getStatusCode());
+ public void testMarkerFile() throws Exception {
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- assertNotNull(Class.forName("org.richfaces.resource.NoMarkerFileResourceImpl",
- true, contextClassLoader));
- assertNull(contextClassLoader.getResource("META-INF/org.richfaces.resource.NoMarkerFileResourceImpl.resource.properties"));
-
- WebRequestSettings noMarkerFileRequestSettings = new WebRequestSettings(
- new URL("http://localhost/rfRes/org.richfaces.resource.NoMarkerFileResourceImpl.jsf"));
- WebResponse noMarkerResponse = webClient.loadWebResponse(noMarkerFileRequestSettings);
- assertEquals(HttpServletResponse.SC_NOT_FOUND, noMarkerResponse.getStatusCode());
+ assertNotNull(Class.forName("org.richfaces.resource.MarkerFileResourceImpl", true, contextClassLoader));
+ assertNotNull(
+ contextClassLoader.getResource(
+ "META-INF/org.richfaces.resource.MarkerFileResourceImpl.resource.properties"));
- }
-
- public void testStateHolder() throws Exception {
- setupFacesRequest();
- ResourceCodec mockedCodec = EasyMock.createNiceMock(ResourceCodec.class);
- EasyMock.expect(mockedCodec.decodeResourceName(EasyMock.eq("StateHolderResource/DATA/1"))).andReturn("org.richfaces.resource.StateHolderResourceImpl");
- EasyMock.expect(mockedCodec.decodeResourceData(EasyMock.eq("StateHolderResource/DATA/1"))).andReturn("test text");
- EasyMock.expect(mockedCodec.decodeResourceVersion(EasyMock.eq("StateHolderResource/DATA/1"))).andReturn(null);
- EasyMock.replay(mockedCodec);
-
- ResourceHandlerImpl.setResourceCodec(mockedCodec);
-
- WebRequestSettings settings = new WebRequestSettings(
- new URL("http://localhost/rfRes/StateHolderResource/DATA/1.jsf"));
-
- WebResponse resourceResponse = webClient.loadWebResponse(settings);
- assertEquals(HttpServletResponse.SC_OK, resourceResponse.getStatusCode());
- assertEquals("test text", resourceResponse.getContentAsString("US-ASCII"));
- }
+ WebRequestSettings markerFileRequestSettings =
+ new WebRequestSettings(new URL("http://localhost/rfRes/org.richfaces.resource.MarkerFileResourceImpl.jsf"));
+ WebResponse markerFileResponse = webClient.loadWebResponse(markerFileRequestSettings);
- public void testVersionedResource() throws Exception {
- WebRequestSettings settings = new WebRequestSettings(
- new URL("http://localhost/rfRes/org.richfaces.resource.VersionedResourceImpl.jsf"));
- WebResponse resourceResponse = webClient.loadWebResponse(settings);
- assertEquals(HttpServletResponse.SC_OK, resourceResponse.getStatusCode());
+ assertEquals(HttpServletResponse.SC_OK, markerFileResponse.getStatusCode());
+ assertNotNull(Class.forName("org.richfaces.resource.NoMarkerFileResourceImpl", true, contextClassLoader));
+ assertNull(
+ contextClassLoader.getResource(
+ "META-INF/org.richfaces.resource.NoMarkerFileResourceImpl.resource.properties"));
- settings = new WebRequestSettings(
- new URL("http://localhost/rfRes/org.richfaces.resource.VersionedResourceImpl/VER1_..."));
- resourceResponse = webClient.loadWebResponse(settings);
- assertEquals(HttpServletResponse.SC_OK, resourceResponse.getStatusCode());
+ WebRequestSettings noMarkerFileRequestSettings =
+ new WebRequestSettings(
+ new URL("http://localhost/rfRes/org.richfaces.resource.NoMarkerFileResourceImpl.jsf"));
+ WebResponse noMarkerResponse = webClient.loadWebResponse(noMarkerFileRequestSettings);
- settings = new WebRequestSettings(
- new URL("http://localhost/rfRes/org.richfaces.resource.VersionedResourceImpl/VER1_..."));
- resourceResponse = webClient.loadWebResponse(settings);
- assertEquals(HttpServletResponse.SC_NOT_FOUND, resourceResponse.getStatusCode());
- }
-
- public void testCreateResource() throws Exception {
- setupFacesRequest();
- ResourceHandler resourceHandler = facesContext.getApplication().getResourceHandler();
-
- assertNotNull(resourceHandler.createResource("org.richfaces.resource.CacheableResourceImpl"));
- assertNotNull(resourceHandler.createResource("org.richfaces.resource.CacheableResourceImpl", ""));
- assertNotNull(resourceHandler.createResource("org.richfaces.resource.CacheableResourceImpl", null));
+ assertEquals(HttpServletResponse.SC_NOT_FOUND, noMarkerResponse.getStatusCode());
+ }
- assertNotNull(resourceHandler.createResource("defaultResourceHandlerResource.js"));
- assertNotNull(resourceHandler.createResource("libraryResource.js", "org.richfaces.resource.test"));
- }
-
- public void testLibraryExists() throws Exception {
- setupFacesRequest();
- ResourceHandler resourceHandler = facesContext.getApplication().getResourceHandler();
+ public void testStateHolder() throws Exception {
+ setupFacesRequest();
- assertTrue(resourceHandler.libraryExists("org.richfaces.resource.test"));
- }
+ ResourceCodec mockedCodec = EasyMock.createNiceMock(ResourceCodec.class);
+
+ EasyMock.expect(mockedCodec.decodeResourceName(EasyMock.eq("StateHolderResource/DATA/1"))).andReturn(
+ "org.richfaces.resource.StateHolderResourceImpl");
+ EasyMock.expect(mockedCodec.decodeResourceData(EasyMock.eq("StateHolderResource/DATA/1"))).andReturn(
+ "test text");
+ EasyMock.expect(mockedCodec.decodeResourceVersion(EasyMock.eq("StateHolderResource/DATA/1"))).andReturn(null);
+ EasyMock.replay(mockedCodec);
+ ResourceHandlerImpl.setResourceCodec(mockedCodec);
+
+ WebRequestSettings settings =
+ new WebRequestSettings(new URL("http://localhost/rfRes/StateHolderResource/DATA/1.jsf"));
+ WebResponse resourceResponse = webClient.loadWebResponse(settings);
+
+ assertEquals(HttpServletResponse.SC_OK, resourceResponse.getStatusCode());
+ assertEquals("test text", resourceResponse.getContentAsString("US-ASCII"));
+ }
+
+ public void testVersionedResource() throws Exception {
+ WebRequestSettings settings =
+ new WebRequestSettings(new URL("http://localhost/rfRes/org.richfaces.resource.VersionedResourceImpl.jsf"));
+ WebResponse resourceResponse = webClient.loadWebResponse(settings);
+
+ assertEquals(HttpServletResponse.SC_OK, resourceResponse.getStatusCode());
+ settings = new WebRequestSettings(
+ new URL("http://localhost/rfRes/org.richfaces.resource.VersionedResourceImpl/VER1_..."));
+ resourceResponse = webClient.loadWebResponse(settings);
+ assertEquals(HttpServletResponse.SC_OK, resourceResponse.getStatusCode());
+ settings = new WebRequestSettings(
+ new URL("http://localhost/rfRes/org.richfaces.resource.VersionedResourceImpl/VER1_..."));
+ resourceResponse = webClient.loadWebResponse(settings);
+ assertEquals(HttpServletResponse.SC_NOT_FOUND, resourceResponse.getStatusCode());
+ }
+
+ public void testCreateResource() throws Exception {
+ setupFacesRequest();
+
+ ResourceHandler resourceHandler = facesContext.getApplication().getResourceHandler();
+
+ assertNotNull(resourceHandler.createResource("org.richfaces.resource.CacheableResourceImpl"));
+ assertNotNull(resourceHandler.createResource("org.richfaces.resource.CacheableResourceImpl", ""));
+ assertNotNull(resourceHandler.createResource("org.richfaces.resource.CacheableResourceImpl", null));
+ assertNotNull(resourceHandler.createResource("defaultResourceHandlerResource.js"));
+ assertNotNull(resourceHandler.createResource("libraryResource.js", "org.richfaces.resource.test"));
+ }
+
+ public void testLibraryExists() throws Exception {
+ setupFacesRequest();
+
+ ResourceHandler resourceHandler = facesContext.getApplication().getResourceHandler();
+
+ assertTrue(resourceHandler.libraryExists("org.richfaces.resource.test"));
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceUtilsTest.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceUtilsTest.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceUtilsTest.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import static junit.framework.Assert.assertEquals;
@@ -29,71 +31,70 @@
import org.junit.Test;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class ResourceUtilsTest {
+ @Test
+ public void testFormatWeakTag() throws Exception {
+ assertNull(ResourceUtils.formatWeakTag(null));
+ assertEquals("W/\"123-456789\"", ResourceUtils.formatWeakTag("123-456789"));
- @Test
- public void testFormatWeakTag() throws Exception {
- assertNull(ResourceUtils.formatWeakTag(null));
- assertEquals("W/\"123-456789\"", ResourceUtils.formatWeakTag("123-456789"));
- try {
- ResourceUtils.formatWeakTag("123\"456789");
-
- fail();
- } catch (IllegalArgumentException e) {
- //ok
- }
- }
+ try {
+ ResourceUtils.formatWeakTag("123\"456789");
+ fail();
+ } catch (IllegalArgumentException e) {
- @Test
- public void testFormatTag() throws Exception {
- assertNull(ResourceUtils.formatTag(null));
- assertEquals("\"123-456789\"", ResourceUtils.formatTag("123-456789"));
- try {
- ResourceUtils.formatTag("123\"456789");
-
- fail();
- } catch (IllegalArgumentException e) {
- //ok
- }
- }
+ // ok
+ }
+ }
- @Test
- public void testMatchTag() throws Exception {
- assertTrue(ResourceUtils.matchTag("\"123-4567890\"", "W/\"123-4567890\""));
- assertTrue(ResourceUtils.matchTag("\"123-4567890\"", "W/\"123-4567890\", \"123-4567891\""));
- assertTrue(ResourceUtils.matchTag("W/\"123-4567891\"", "W/\"123-4567890\", \"123-4567891\""));
-
- assertFalse(ResourceUtils.matchTag("\"123-4567890\"", "W/\"023-4567890\""));
- assertFalse(ResourceUtils.matchTag("\"123-4567890\"", "W/\"023-4567890\", \"023-4567891\""));
- assertFalse(ResourceUtils.matchTag("W/\"123-4567891\"", "W/\"023-4567890\", \"023-4567891\""));
+ @Test
+ public void testFormatTag() throws Exception {
+ assertNull(ResourceUtils.formatTag(null));
+ assertEquals("\"123-456789\"", ResourceUtils.formatTag("123-456789"));
- try {
- ResourceUtils.matchTag(null, "W/\"123-4567890\", \"123-4567891\"");
-
- fail();
- } catch (IllegalArgumentException e) {
- //ok
- }
+ try {
+ ResourceUtils.formatTag("123\"456789");
+ fail();
+ } catch (IllegalArgumentException e) {
- try {
- ResourceUtils.matchTag("W/\"123-4567890\"", null);
-
- fail();
- } catch (IllegalArgumentException e) {
- //ok
- }
-
- try {
- ResourceUtils.matchTag("123\"456789", "W/\"123\"");
-
- fail();
- } catch (IllegalArgumentException e) {
- //ok
- }
- }
+ // ok
+ }
+ }
+
+ @Test
+ public void testMatchTag() throws Exception {
+ assertTrue(ResourceUtils.matchTag("\"123-4567890\"", "W/\"123-4567890\""));
+ assertTrue(ResourceUtils.matchTag("\"123-4567890\"", "W/\"123-4567890\", \"123-4567891\""));
+ assertTrue(ResourceUtils.matchTag("W/\"123-4567891\"", "W/\"123-4567890\", \"123-4567891\""));
+ assertFalse(ResourceUtils.matchTag("\"123-4567890\"", "W/\"023-4567890\""));
+ assertFalse(ResourceUtils.matchTag("\"123-4567890\"", "W/\"023-4567890\", \"023-4567891\""));
+ assertFalse(ResourceUtils.matchTag("W/\"123-4567891\"", "W/\"023-4567890\", \"023-4567891\""));
+
+ try {
+ ResourceUtils.matchTag(null, "W/\"123-4567890\", \"123-4567891\"");
+ fail();
+ } catch (IllegalArgumentException e) {
+
+ // ok
+ }
+
+ try {
+ ResourceUtils.matchTag("W/\"123-4567890\"", null);
+ fail();
+ } catch (IllegalArgumentException e) {
+
+ // ok
+ }
+
+ try {
+ ResourceUtils.matchTag("123\"456789", "W/\"123\"");
+ fail();
+ } catch (IllegalArgumentException e) {
+
+ // ok
+ }
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/StateHolderResourceImpl.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/StateHolderResourceImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/StateHolderResourceImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.io.ByteArrayInputStream;
@@ -34,32 +36,30 @@
* @since 4.0
*/
public class StateHolderResourceImpl extends AbstractBaseResource implements StateHolder {
+ private Object state = "";
- private Object state = "";
-
- @Override
- public InputStream getInputStream() {
- try {
- return new ByteArrayInputStream(state.toString().getBytes("US-ASCII"));
- } catch (UnsupportedEncodingException e) {
- throw new FacesException(e.getMessage(), e);
- }
- }
+ @Override
+ public InputStream getInputStream() {
+ try {
+ return new ByteArrayInputStream(state.toString().getBytes("US-ASCII"));
+ } catch (UnsupportedEncodingException e) {
+ throw new FacesException(e.getMessage(), e);
+ }
+ }
- public boolean isTransient() {
- return false;
- }
+ public boolean isTransient() {
+ return false;
+ }
- public void restoreState(FacesContext context, Object state) {
- this.state = state;
- }
+ public void restoreState(FacesContext context, Object state) {
+ this.state = state;
+ }
- public Object saveState(FacesContext context) {
- return state;
- }
+ public Object saveState(FacesContext context) {
+ return state;
+ }
- public void setTransient(boolean newTransientValue) {
- throw new UnsupportedOperationException();
- }
-
+ public void setTransient(boolean newTransientValue) {
+ throw new UnsupportedOperationException();
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/resource/VersionedResourceImpl.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/resource/VersionedResourceImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/resource/VersionedResourceImpl.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,17 +19,17 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class VersionedResourceImpl extends EmptyStreamResource {
-
- @Override
- public String getVersion() {
- return "1_0_2";
- }
+ @Override
+ public String getVersion() {
+ return "1_0_2";
+ }
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/skin/Bean.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/skin/Bean.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/skin/Bean.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -19,9 +19,16 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.skin;
public class Bean {
- public String getName(){return "bindedtest";}
- public String getBean(){return "binded.string";}
-}
\ No newline at end of file
+ public String getName() {
+ return "bindedtest";
+ }
+
+ public String getBean() {
+ return "binded.string";
+ }
+}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/skin/SkinTestCase.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/skin/SkinTestCase.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/skin/SkinTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -26,6 +26,7 @@
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
+
import java.util.HashMap;
import java.util.Map;
@@ -41,230 +42,256 @@
*/
public class SkinTestCase extends AbstractFacesTest {
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.METHOD)
- private @interface SkinParameters {
- String skinName() default "";
- String baseSkinName() default "";
- };
-
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- public void tearDown() throws Exception {
- SkinFactory.reset();
- super.tearDown();
- }
+ @Override
+ public void tearDown() throws Exception {
+ SkinFactory.reset();
+ super.tearDown();
+ }
- @Override
- protected void setupJsfInitParameters() {
- super.setupJsfInitParameters();
-
- setupSkinParameters();
- }
+ @Override
+ protected void setupJsfInitParameters() {
+ super.setupJsfInitParameters();
+ setupSkinParameters();
+ }
- private void setupSkinParameters() {
- try {
- Method method = getClass().getMethod(getName());
- SkinParameters skinParameters = method.getAnnotation(SkinParameters.class);
- if (skinParameters != null) {
- String skinName = skinParameters.skinName();
- if (skinName != null && skinName.length() != 0) {
- facesServer.addInitParameter(SkinFactory.SKIN_PARAMETER, skinName);
- }
-
- String baseSkinName = skinParameters.baseSkinName();
- if (baseSkinName != null && baseSkinName.length() != 0) {
- facesServer.addInitParameter(SkinFactory.BASE_SKIN_PARAMETER, baseSkinName);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
+ private void setupSkinParameters() {
+ try {
+ Method method = getClass().getMethod(getName());
+ SkinParameters skinParameters = method.getAnnotation(SkinParameters.class);
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getInstance()'
- */
- public void testGetInstance() {
- SkinFactory factory = SkinFactory.getInstance();
- SkinFactory factory1 = SkinFactory.getInstance();
- assertSame(factory,factory1);
- }
+ if (skinParameters != null) {
+ String skinName = skinParameters.skinName();
- private void addParameters(Object[][] strings) {
- Map<Object,Object> baseMap = new HashMap<Object, Object>();
- for (Object[] objects : strings) {
- baseMap.put(objects[0], objects[1]);
- }
+ if (skinName != null && skinName.length() != 0) {
+ facesServer.addInitParameter(SkinFactory.SKIN_PARAMETER, skinName);
+ }
- facesContext.getExternalContext().getRequestMap().put("test", baseMap);
- }
+ String baseSkinName = skinParameters.baseSkinName();
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
- */
- @SkinParameters(skinName = "test")
- public void testGetSkin() {
- addParameters(new Object[][]{new Object[] {"bean", "test.value"}});
+ if (baseSkinName != null && baseSkinName.length() != 0) {
+ facesServer.addInitParameter(SkinFactory.BASE_SKIN_PARAMETER, baseSkinName);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
- SkinFactory factory = SkinFactory.getInstance();
- // test call
- Skin skin = factory.getSkin(facesContext);
- assertNotNull("Null skin!",skin);
- // test properties
- assertEquals("string",skin.getParameter(facesContext, "string.property"));
- assertEquals("base.string",skin.getParameter(facesContext, "base.property"));
- assertEquals("test.value",skin.getParameter(facesContext, "bind.property"));
- // assertEquals("HTML_BASIC",skin.getRenderKitId(mockContext));
- }
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getInstance()'
+ */
+ public void testGetInstance() {
+ SkinFactory factory = SkinFactory.getInstance();
+ SkinFactory factory1 = SkinFactory.getInstance();
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
- */
- @SkinParameters(skinName = "test")
- public void testSkinReferences() {
- SkinFactory factory = SkinFactory.getInstance();
+ assertSame(factory, factory1);
+ }
- // test call
- Skin skin = factory.getSkin(facesContext);
- assertNotNull("Null skin!",skin);
- assertEquals("default",skin.getParameter(facesContext, "c"));
- assertEquals("yyy",skin.getParameter(facesContext, "y"));
- }
+ private void addParameters(Object[][] strings) {
+ Map<Object, Object> baseMap = new HashMap<Object, Object>();
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
- */
- @SkinParameters(skinName = "style", baseSkinName = "style_base")
- public void testSkinReferences1() {
- SkinFactory factory = SkinFactory.getInstance();
- // test call
- Skin skin = factory.getSkin(facesContext);
- assertNotNull("Null skin!",skin);
- assertEquals("#F5F0E7",skin.getParameter(facesContext, "intermediateTextColor"));
- assertEquals("10px",skin.getParameter(facesContext, "intermediateTextSize"));
- assertEquals("#F5F0E7",skin.getParameter(facesContext, "generalTextColor"));
+ for (Object[] objects : strings) {
+ baseMap.put(objects[0], objects[1]);
+ }
- assertEquals("white.textcolor",skin.getParameter(facesContext, "additionalTextColor"));
- }
+ facesContext.getExternalContext().getRequestMap().put("test", baseMap);
+ }
- @SkinParameters(skinName = "dynatest", baseSkinName = "dynatest_base")
- public void testBaseSkin() {
- SkinFactory factory = SkinFactory.getInstance();
- addParameters(new Object[][]{new Object[] {"bean", "dynabase1"}});
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
+ */
+ @SkinParameters(skinName = "test")
+ public void testGetSkin() {
+ addParameters(new Object[][] {
+ new Object[] {"bean", "test.value"}
+ });
- Skin skin = factory.getSkin(facesContext);
- assertEquals("default", skin.getParameter(facesContext, "default"));
- assertEquals("itself", skin.getParameter(facesContext, "selfValue"));
- assertEquals("#AAA", skin.getParameter(facesContext, "customFormColor"));
+ SkinFactory factory = SkinFactory.getInstance();
- Map<String, String> map = (Map<String, String>) facesContext.getExternalContext().getRequestMap().get("test");
- map.put("bean", "dynabase2");
+ // test call
+ Skin skin = factory.getSkin(facesContext);
- assertEquals("xxx", skin.getParameter(facesContext, "default"));
- assertEquals("itself", skin.getParameter(facesContext, "selfValue"));
- assertEquals("#AAA", skin.getParameter(facesContext, "customFormColor"));
- }
+ assertNotNull("Null skin!", skin);
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
- */
- @SkinParameters(skinName = "cyclic")
- public void testCyclicSkinReferences() {
- SkinFactory factory = SkinFactory.getInstance();
+ // test properties
+ assertEquals("string", skin.getParameter(facesContext, "string.property"));
+ assertEquals("base.string", skin.getParameter(facesContext, "base.property"));
+ assertEquals("test.value", skin.getParameter(facesContext, "bind.property"));
- try {
- Skin skin = factory.getSkin(facesContext);
- skin.getParameter(facesContext, "x");
- fail();
- } catch(FacesException e){
- //it's ok
- }
- }
+ // assertEquals("HTML_BASIC",skin.getRenderKitId(mockContext));
+ }
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
- */
- @SkinParameters(skinName = "noref")
- public void testBadSkinReferences() {
- SkinFactory factory = SkinFactory.getInstance();
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
+ */
+ @SkinParameters(skinName = "test")
+ public void testSkinReferences() {
+ SkinFactory factory = SkinFactory.getInstance();
- // test call
- try {
- Skin skin = factory.getSkin(facesContext);
- skin.getParameter(facesContext, "x");
- fail();
- } catch(FacesException e){
- //it's ok
- }
- }
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
- */
- @SkinParameters(skinName = "#{test.skin}")
- public void testGetBindedSkin() {
- SkinFactory factory = SkinFactory.getInstance();
+ // test call
+ Skin skin = factory.getSkin(facesContext);
- addParameters(new Object[][] {
- new Object[] {"skin", "bindedtest"},
- new Object[] {"bean", "binded.test.value"}
- });
+ assertNotNull("Null skin!", skin);
+ assertEquals("default", skin.getParameter(facesContext, "c"));
+ assertEquals("yyy", skin.getParameter(facesContext, "y"));
+ }
- // test call
- Skin skin = factory.getSkin(facesContext);
- assertNotNull("Null skin!",skin);
- // test properties
- assertEquals("bindedstring",skin.getParameter(facesContext, "string.property"));
- // assertEquals("base.string",skin.getParameter(mockContext,"base.property"));
- assertEquals("binded.test.value",skin.getParameter(facesContext, "bind.property"));
- assertEquals("TEST",skin.getRenderKitId(facesContext));
- }
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
+ */
+ @SkinParameters(skinName = "style", baseSkinName = "style_base")
+ public void testSkinReferences1() {
+ SkinFactory factory = SkinFactory.getInstance();
- @SkinParameters(skinName = "#{test.skin}")
- public void testSkinHash() {
- SkinFactory factory = SkinFactory.getInstance();
+ // test call
+ Skin skin = factory.getSkin(facesContext);
- addParameters(new Object[][] {
- new Object[] {"skin", "bindedtest"},
- new Object[] {"bean", "binded.test.value"}
- });
+ assertNotNull("Null skin!", skin);
+ assertEquals("#F5F0E7", skin.getParameter(facesContext, "intermediateTextColor"));
+ assertEquals("10px", skin.getParameter(facesContext, "intermediateTextSize"));
+ assertEquals("#F5F0E7", skin.getParameter(facesContext, "generalTextColor"));
+ assertEquals("white.textcolor", skin.getParameter(facesContext, "additionalTextColor"));
+ }
- Skin skin = factory.getSkin(facesContext);
- Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
+ @SkinParameters(skinName = "dynatest", baseSkinName = "dynatest_base")
+ public void testBaseSkin() {
+ SkinFactory factory = SkinFactory.getInstance();
- // test properties
- int hash = skin.hashCode(facesContext);
- assertTrue(requestMap.containsKey(BasicSkinImpl.REQUEST_HASH_CODES_MAP_PARAMETER));
- assertEquals(hash,skin.hashCode(facesContext));
- requestMap.remove(BasicSkinImpl.REQUEST_HASH_CODES_MAP_PARAMETER);
- assertEquals(hash,skin.hashCode(facesContext));
- // setup Value binding mock for different value - hash must differ.
- requestMap.remove(BasicSkinImpl.REQUEST_HASH_CODES_MAP_PARAMETER);
+ addParameters(new Object[][] {
+ new Object[] {"bean", "dynabase1"}
+ });
- Map map = (Map) requestMap.get("test");
- map.put("bean", "other.test.value");
+ Skin skin = factory.getSkin(facesContext);
- assertFalse( hash==skin.hashCode(facesContext) );
+ assertEquals("default", skin.getParameter(facesContext, "default"));
+ assertEquals("itself", skin.getParameter(facesContext, "selfValue"));
+ assertEquals("#AAA", skin.getParameter(facesContext, "customFormColor"));
- }
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getDefaultProperties()'
- */
- public void testGetDefaultProperties() {
- SkinFactory factory = (SkinFactory) SkinFactory.getInstance();
- // assertEquals("HTML_BASIC",defaultProps.getProperty("render.kit"));
- // Second default config
- assertEquals("default",factory.getDefaultSkin(facesContext).getParameter(facesContext, "a"));
- }
+ Map<String, String> map = (Map<String, String>) facesContext.getExternalContext().getRequestMap().get("test");
- /*
- * Test method for 'org.richfaces.skin.SkinFactory.getSkinName(FacesContext)'
- */
- public void testGetSkinName() {
+ map.put("bean", "dynabase2");
+ assertEquals("xxx", skin.getParameter(facesContext, "default"));
+ assertEquals("itself", skin.getParameter(facesContext, "selfValue"));
+ assertEquals("#AAA", skin.getParameter(facesContext, "customFormColor"));
+ }
- }
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
+ */
+ @SkinParameters(skinName = "cyclic")
+ public void testCyclicSkinReferences() {
+ SkinFactory factory = SkinFactory.getInstance();
+ try {
+ Skin skin = factory.getSkin(facesContext);
+
+ skin.getParameter(facesContext, "x");
+ fail();
+ } catch (FacesException e) {
+
+ // it's ok
+ }
+ }
+
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
+ */
+ @SkinParameters(skinName = "noref")
+ public void testBadSkinReferences() {
+ SkinFactory factory = SkinFactory.getInstance();
+
+ // test call
+ try {
+ Skin skin = factory.getSkin(facesContext);
+
+ skin.getParameter(facesContext, "x");
+ fail();
+ } catch (FacesException e) {
+
+ // it's ok
+ }
+ }
+
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getSkin(FacesContext)'
+ */
+ @SkinParameters(skinName = "#{test.skin}")
+ public void testGetBindedSkin() {
+ SkinFactory factory = SkinFactory.getInstance();
+
+ addParameters(new Object[][] {
+ new Object[] {"skin", "bindedtest"}, new Object[] {"bean", "binded.test.value"}
+ });
+
+ // test call
+ Skin skin = factory.getSkin(facesContext);
+
+ assertNotNull("Null skin!", skin);
+
+ // test properties
+ assertEquals("bindedstring", skin.getParameter(facesContext, "string.property"));
+
+ // assertEquals("base.string",skin.getParameter(mockContext,"base.property"));
+ assertEquals("binded.test.value", skin.getParameter(facesContext, "bind.property"));
+ assertEquals("TEST", skin.getRenderKitId(facesContext));
+ }
+
+ @SkinParameters(skinName = "#{test.skin}")
+ public void testSkinHash() {
+ SkinFactory factory = SkinFactory.getInstance();
+
+ addParameters(new Object[][] {
+ new Object[] {"skin", "bindedtest"}, new Object[] {"bean", "binded.test.value"}
+ });
+
+ Skin skin = factory.getSkin(facesContext);
+ Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
+
+ // test properties
+ int hash = skin.hashCode(facesContext);
+
+ assertTrue(requestMap.containsKey(BasicSkinImpl.REQUEST_HASH_CODES_MAP_PARAMETER));
+ assertEquals(hash, skin.hashCode(facesContext));
+ requestMap.remove(BasicSkinImpl.REQUEST_HASH_CODES_MAP_PARAMETER);
+ assertEquals(hash, skin.hashCode(facesContext));
+
+ // setup Value binding mock for different value - hash must differ.
+ requestMap.remove(BasicSkinImpl.REQUEST_HASH_CODES_MAP_PARAMETER);
+
+ Map map = (Map) requestMap.get("test");
+
+ map.put("bean", "other.test.value");
+ assertFalse(hash == skin.hashCode(facesContext));
+ }
+
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getDefaultProperties()'
+ */
+ public void testGetDefaultProperties() {
+ SkinFactory factory = (SkinFactory) SkinFactory.getInstance();
+
+ // assertEquals("HTML_BASIC",defaultProps.getProperty("render.kit"));
+ // Second default config
+ assertEquals("default", factory.getDefaultSkin(facesContext).getParameter(facesContext, "a"));
+ }
+
+ /*
+ * Test method for 'org.richfaces.skin.SkinFactory.getSkinName(FacesContext)'
+ */
+ public void testGetSkinName() {}
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.METHOD)
+ private @interface SkinParameters {
+ String skinName() default "";
+ String baseSkinName() default "";
+ }
+
+ ;
}
Modified: root/framework/trunk/impl/src/test/java/org/richfaces/skin/SkinThreadsTestCase.java
===================================================================
--- root/framework/trunk/impl/src/test/java/org/richfaces/skin/SkinThreadsTestCase.java 2009-11-02 11:26:36 UTC (rev 15805)
+++ root/framework/trunk/impl/src/test/java/org/richfaces/skin/SkinThreadsTestCase.java 2009-11-02 11:33:49 UTC (rev 15806)
@@ -34,79 +34,82 @@
// */
//public class SkinThreadsTestCase extends AbstractThreadedAjax4JsfTestCase {
//
-// /**
-// * @param s
-// */
-// public SkinThreadsTestCase(String s) {
-// super(s);
-// // TODO Auto-generated constructor stub
-// }
+// /**
+// * @param s
+// */
+// public SkinThreadsTestCase(String s) {
+// super(s);
+// // TODO Auto-generated constructor stub
+// }
//
-// /*
-// * (non-Javadoc)
-// *
-// * @see com.exadel.vcp.tests.VcpJsfTestCase#setUp()
-// */
+// /*
+// * (non-Javadoc)
+// *
+// * @see com.exadel.vcp.tests.VcpJsfTestCase#setUp()
+// */
//public void setUp() throws Exception {
-// // TODO Auto-generated method stub
-// super.setUp();
-// servletContext.setAttribute("skin", new Bean());
-// }
-// /*
-// * (non-Javadoc)
-// *
-// * @see com.exadel.vcp.tests.VcpJsfTestCase#tearDown()
-// */
-// public void tearDown() throws Exception {
-// // TODO Auto-generated method stub
-// super.tearDown();
-// }
+// // TODO Auto-generated method stub
+// super.setUp();
+// servletContext.setAttribute("skin", new Bean());
+// }
+// /*
+// * (non-Javadoc)
+// *
+// * @see com.exadel.vcp.tests.VcpJsfTestCase#tearDown()
+// */
+// public void tearDown() throws Exception {
+// // TODO Auto-generated method stub
+// super.tearDown();
+// }
//
-//
-// public class SkinTestRunnable extends TestCaseRunnable {
+//
+// public class SkinTestRunnable extends TestCaseRunnable {
//
-//
-// /**
-// *
-// */
-// public SkinTestRunnable() {
-// // TODO Auto-generated constructor stub
-// }
+//
+// /**
+// *
+// */
+// public SkinTestRunnable() {
+// // TODO Auto-generated constructor stub
+// }
//
-// /* (non-Javadoc)
-// * @see com.exadel.vcp.tests.ThreadedVcpJsfTestCase.TestCaseRunnable#runTestCase(javax.faces.context.FacesContext)
-// */
-// public void runTestCase(FacesContext context) throws Throwable {
-// context.getExternalContext().getRequestMap().put("test", new Bean());
-// Skin skin = SkinFactory.getInstance().getSkin(context);
-// assertNotNull(skin);
-// assertEquals("TEST", skin.getRenderKitId(context));
-// assertEquals("binded.string", skin.getParameter(context, "bind.property"));
-// assertEquals("bindedstring", skin.getParameter(context, "string.property"));
-// assertEquals("10", skin.getParameter(context, "int.property"));
-// assertNull(skin.getParameter(context, "notexist"));
-// }
-//
-// }
-//
-// /**
-// * Test skin factory for thread-safe.
-// */
-// public void testThreadsafe() {
-// TestCaseRunnable[] runnables = new TestCaseRunnable[20];
-// for (int i = 0; i < runnables.length; i++) {
-// runnables[i] = new SkinTestRunnable();
-//
-// }
-// this.runTestCaseRunnables(runnables);
-// }
-// /*
-// * (non-Javadoc)
-// *
-// * @see com.exadel.vcp.tests.VcpJsfTestCase#getSkinName()
-// */
-// protected String getSkinName() {
-// // TODO Auto-generated method stub
-// return "#{skin.name}";
-// }
+// /* (non-Javadoc)
+// * @see com.exadel.vcp.tests.ThreadedVcpJsfTestCase.TestCaseRunnable#runTestCase(javax.faces.context.FacesContext)
+// */
+// public void runTestCase(FacesContext context) throws Throwable {
+// context.getExternalContext().getRequestMap().put("test", new Bean());
+// Skin skin = SkinFactory.getInstance().getSkin(context);
+// assertNotNull(skin);
+// assertEquals("TEST", skin.getRenderKitId(context));
+// assertEquals("binded.string", skin.getParameter(context, "bind.property"));
+// assertEquals("bindedstring", skin.getParameter(context, "string.property"));
+// assertEquals("10", skin.getParameter(context, "int.property"));
+// assertNull(skin.getParameter(context, "notexist"));
+// }
+//
+// }
+//
+// /**
+// * Test skin factory for thread-safe.
+// */
+// public void testThreadsafe() {
+// TestCaseRunnable[] runnables = new TestCaseRunnable[20];
+// for (int i = 0; i < runnables.length; i++) {
+// runnables[i] = new SkinTestRunnable();
+//
+// }
+// this.runTestCaseRunnables(runnables);
+// }
+// /*
+// * (non-Javadoc)
+// *
+// * @see com.exadel.vcp.tests.VcpJsfTestCase#getSkinName()
+// */
+// protected String getSkinName() {
+// // TODO Auto-generated method stub
+// return "#{skin.name}";
+// }
//}
+
+
+
15 years, 10 months
JBoss Rich Faces SVN: r15805 - in root/ui/trunk/components: core/src/main/java/org/ajax4jsf/component and 15 other directories.
by richfaces-svn-commits@lists.jboss.org
Author: Alex.Kolonitsky
Date: 2009-11-02 06:26:36 -0500 (Mon, 02 Nov 2009)
New Revision: 15805
Modified:
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/ajax/ForceRender.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/ajax/package-info.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/UIActionParameter.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/UIPoll.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/behavior/AjaxBehavior.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/package-info.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/AjaxHandler.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorStack.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorsAddingComponentHandlerWrapper.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorsTagHandlerDelegateFactoryImpl.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/AjaxBehaviorRenderer.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/html/package-info.java
root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/package-info.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/PushEventTracker.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/PushListenersManager.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxCommandButton.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxCommandLink.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxFunction.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxLog.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxOutputPanel.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxStatus.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIMediaOutput.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIPush.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxFunction.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxLog.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxStatus.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlCommandButton.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlCommandLink.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlMediaOutput.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlOutputPanel.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlPush.java
root/ui/trunk/components/core/src/main/java/org/richfaces/component/package-info.java
root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxCommandRendererBase.java
root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxComponentRendererBase.java
root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxFunctionRendererBase.java
root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/CommandRendererBase.java
root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/html/AjaxCommandButtonRendererBase.java
root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/html/MediaOutputRenderer.java
root/ui/trunk/components/core/src/main/java/org/richfaces/resource/MediaOutputResource.java
root/ui/trunk/components/core/src/main/java/org/richfaces/resource/PushResource.java
root/ui/trunk/components/core/src/main/java/org/richfaces/taglib/html/facelets/AjaxPushHandler.java
root/ui/trunk/components/core/src/main/java/org/richfaces/taglib/html/facelets/MediaOutputHandler.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/AbstractQueueComponentTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/ActionListenerTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/AjaxFormQueuesTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/DataAdaptorTestCase.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/ImplicitQueuesTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/IncludeComponentTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/LoadBundleComponentTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/LoadResourceComponentTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/MediaOutputComponentBaseTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/MockDataAdaptor.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueDiscoveryTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueParallelTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueScriptedTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueSimilarityTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueSizeTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueuedPollTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/RepeatTestCase.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/UIAjaxFormTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxFormRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxIncludeRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxOutputPanelRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxPageRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxPushRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxStatusRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/HtmlCommandLinkRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/MediaOutputRendererTest.java
root/ui/trunk/components/core/src/test/java/org/ajax4jsf/taglib/html/KeepAliveTagsTest.java
root/ui/trunk/components/tree/tree/api/src/main/java/ITest.java
root/ui/trunk/components/tree/tree/ui/src/main/java/UITest.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/ajax/ForceRender.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/ajax/ForceRender.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/ajax/ForceRender.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.ajax;
import javax.faces.component.UIComponent;
@@ -36,22 +38,25 @@
*/
public class ForceRender implements AjaxListener, AjaxRenderListener {
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.ajax.AjaxListener#processAjax(org.ajax4jsf.framework.ajax.AjaxEvent)
- */
- public void processAjax(AjaxEvent event) {
- UIComponent component = event.getComponent();
- AjaxRenderEvent renderEvent = new AjaxRenderEvent(component);
- renderEvent.setPhaseId(event.getPhaseId());
- component.queueEvent(renderEvent);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.framework.ajax.AjaxListener#processAjax(org.ajax4jsf.framework.ajax.AjaxEvent)
+ */
+ public void processAjax(AjaxEvent event) {
+ UIComponent component = event.getComponent();
+ AjaxRenderEvent renderEvent = new AjaxRenderEvent(component);
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.ajax.AjaxRenderListener#processAjaxRender(org.ajax4jsf.framework.ajax.AjaxRenderEvent)
- */
- public void processAjaxRender(AjaxRenderEvent event) {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- AjaxContext.getCurrentInstance(facesContext).renderAjax(facesContext);
- }
+ renderEvent.setPhaseId(event.getPhaseId());
+ component.queueEvent(renderEvent);
+ }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.framework.ajax.AjaxRenderListener#processAjaxRender(org.ajax4jsf.framework.ajax.AjaxRenderEvent)
+ */
+ public void processAjaxRender(AjaxRenderEvent event) {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+
+ AjaxContext.getCurrentInstance(facesContext).renderAjax(facesContext);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/ajax/package-info.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/ajax/package-info.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/ajax/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -1,3 +1,4 @@
+
/**
* AJAX utility classes
*/
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/UIActionParameter.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/UIActionParameter.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/UIActionParameter.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,11 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import javax.el.ELContext;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
+
import javax.faces.FacesException;
import javax.faces.component.UIComponentBase;
import javax.faces.component.UIParameter;
@@ -38,225 +41,229 @@
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.2 $ $Date: 2007/02/01 15:31:55 $
- *
+ *
*/
-public class UIActionParameter extends UIParameter implements ActionListener,
- JavaScriptParameter {
+public class UIActionParameter extends UIParameter implements ActionListener, JavaScriptParameter {
+ public static final String COMPONENT_TYPE = "org.ajax4jsf.components.UIActionParameter";
+ private static String noEscapeAttr = "noEscape";
- public static final String COMPONENT_TYPE = "org.ajax4jsf.components.UIActionParameter";
+ /** ********************************************************* */
- /***************************************************************************
- * Binding for update on ActionEvent
- */
- private ValueExpression _assignToBinding = null;
+ /**
+ * Action listener to call after binding has been updated
+ */
+ private MethodExpression actionListener = null;
- public void setAssignToBinding(ValueExpression propertyBinding) {
- this._assignToBinding = propertyBinding;
- }
+ /**
+ * Binding for update on ActionEvent
+ */
+ private ValueExpression assignToBinding = null;
- public ValueExpression getAssignToBinding() {
- return _assignToBinding;
- }
+ /** ********************************************************* */
- /** ********************************************************* */
+ /**
+ * Converter for update value with this parameter
+ */
+ private Converter converter = null;
- /***************************************************************************
- * Action listener to call after binding has been updated
- */
- private MethodExpression _actionListener = null;
-
- public MethodExpression getActionListener() {
- return _actionListener;
- }
+ /** ********************************************************* */
- public void setActionListener(MethodExpression actionListener) {
- this._actionListener = actionListener;
- }
+ /**
+ * Skip quota escaping of parameter value - for substitute JavaScript
+ * exspression on submit
+ */
+ private Boolean noEscape = null;
- /** ********************************************************* */
-
- /***************************************************************************
- * Converter for update value with this parameter
- */
- private Converter _converter = null;
+ public void setAssignToBinding(ValueExpression propertyBinding) {
+ this.assignToBinding = propertyBinding;
+ }
- public void setConverter(Converter converter) {
- this._converter = converter;
- }
+ public ValueExpression getAssignToBinding() {
+ return assignToBinding;
+ }
- public Converter getConverter() {
- return _converter;
- }
+ public MethodExpression getActionListener() {
+ return actionListener;
+ }
- /** ********************************************************* */
+ public void setActionListener(MethodExpression actionListener) {
+ this.actionListener = actionListener;
+ }
- /***************************************************************************
- * Skip quota escaping of parameter value - for substitute JavaScript
- * exspression on submit
- */
- private Boolean _noEscape = null;
+ public void setConverter(Converter converter) {
+ this.converter = converter;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.ajax4jsf.framework.ajax.JavaScriptParameter#setNoEscape(boolean)
- */
- public void setNoEscape(boolean noEscape) {
- this._noEscape = Boolean.valueOf(noEscape);
- }
+ public Converter getConverter() {
+ return converter;
+ }
- private static String NO_ESCAPE_ATTR = "noEscape";
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.ajax.JavaScriptParameter#setNoEscape(boolean)
+ */
+ public void setNoEscape(boolean noEscape) {
+ this.noEscape = Boolean.valueOf(noEscape);
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.ajax4jsf.framework.ajax.JavaScriptParameter#isNoEscape()
- */
- public boolean isNoEscape() {
- return isValueOrBinding(_noEscape, NO_ESCAPE_ATTR);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.ajax.JavaScriptParameter#isNoEscape()
+ */
+ public boolean isNoEscape() {
+ return isValueOrBinding(noEscape, noEscapeAttr);
+ }
- /*
- * (non-Javadoc)
- *
- * @see javax.faces.component.UIParameter#getName()
- */
- public String getName() {
- String name = super.getName();
- // If name not set - use clientId. be Careful !
- if (null == name) {
- name = getClientId(FacesContext.getCurrentInstance());
- }
- return name;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.faces.component.UIParameter#getName()
+ */
+ public String getName() {
+ String name = super.getName();
- public Object getValue() {
- Object value = super.getValue();
- // TODO - perform conversion if converter is present.
- if (null != value) {
- Class<?> type = value.getClass();
- FacesContext context = getFacesContext();
- Converter converter = createConverter(context, type);
- if (null != converter) {
- value = converter.getAsString(context, this, value);
+ // If name not set - use clientId. be Careful !
+ if (null == name) {
+ name = getClientId(FacesContext.getCurrentInstance());
+ }
- }
+ return name;
+ }
- }
- return value;
- }
+ public Object getValue() {
+ Object value = super.getValue();
- /** ********************************************************* */
+ // TODO - perform conversion if converter is present.
+ if (null != value) {
+ Class<?> type = value.getClass();
+ FacesContext context = getFacesContext();
+ Converter converter = createConverter(context, type);
- /*
- * (non-Javadoc)
- *
- * @see javax.faces.event.ActionListener#processAction(javax.faces.event.ActionEvent)
- */
- public void processAction(ActionEvent actionEvent)
- throws AbortProcessingException {
- FacesContext context = getFacesContext();
- ELContext elContext = context.getELContext();
- ValueExpression updateBinding = getAssignToBinding();
- if (updateBinding != null && (!updateBinding.isReadOnly(elContext))) {
- Object requestValue = context.getExternalContext()
- .getRequestParameterMap().get(getName());
- if (requestValue != null && requestValue instanceof String) {
- Class<?> type = updateBinding.getType(elContext);
- Converter converter = createConverter(context, type);
- if (null != converter) {
- requestValue = converter.getAsObject(context, this,
- (String) requestValue);
+ if (null != converter) {
+ value = converter.getAsString(context, this, value);
+ }
+ }
- }
- }
- if (null != requestValue) {
- updateBinding.setValue(elContext, requestValue);
- }
+ return value;
+ }
- MethodExpression listener = getActionListener();
- if (listener != null) {
- listener.invoke(elContext, new Object[] {actionEvent});
- }
- }
- }
+ /** ********************************************************* */
- /**
- * @param context
- * @param type
- * @return
- * @throws FacesException
- */
- private Converter createConverter(FacesContext context, Class<?> type)
- throws FacesException {
- Converter converter = getConverter();
- if (converter == null && type != null && !type.equals(String.class)
- && !type.equals(Object.class)) {
- try {
- converter = context.getApplication().createConverter(type);
- } catch (Exception e) {
- throw new FacesException(Messages.getMessage(
- Messages.NO_CONVERTER_REGISTERED, type.getName()), e);
- }
- }
- return converter;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.faces.event.ActionListener#processAction(javax.faces.event.ActionEvent)
+ */
+ public void processAction(ActionEvent actionEvent) throws AbortProcessingException {
+ FacesContext context = getFacesContext();
+ ELContext elContext = context.getELContext();
+ ValueExpression updateBinding = getAssignToBinding();
- /*
- * (non-Javadoc)
- *
- * @see javax.faces.component.UIComponentBase#restoreState(javax.faces.context.FacesContext)
- */
- public void restoreState(FacesContext context, Object state) {
- Object values[] = (Object[]) state;
- super.restoreState(context, values[0]);
- // restore fields values
- _assignToBinding = (ValueExpression) UIComponentBase.restoreAttachedState(
- context, values[1]);
- _noEscape = (Boolean) values[2];
- _converter = (Converter) UIComponentBase.restoreAttachedState(context,
- values[3]);
- _actionListener = (MethodExpression) UIComponentBase.restoreAttachedState(context,
- values[4]);
+ if (updateBinding != null && (!updateBinding.isReadOnly(elContext))) {
+ Object requestValue = context.getExternalContext().getRequestParameterMap().get(getName());
- }
+ if (requestValue != null && requestValue instanceof String) {
+ Class<?> type = updateBinding.getType(elContext);
+ Converter converter = createConverter(context, type);
- /*
- * (non-Javadoc)
- *
- * @see javax.faces.component.UIComponentBase#saveState(javax.faces.context.FacesContext)
- */
- public Object saveState(FacesContext context) {
- Object values[] = new Object[5];
- values[0] = super.saveState(context);
- // save fields values
- values[1] = UIComponentBase
- .saveAttachedState(context, _assignToBinding);
- values[2] = _noEscape;
- values[3] = UIComponentBase.saveAttachedState(context, _converter);
- values[4] = UIComponentBase.saveAttachedState(context, _actionListener);
- return ((Object) (values));
- }
+ if (null != converter) {
+ requestValue = converter.getAsObject(context, this, (String) requestValue);
+ }
+ }
- /**
- * @param field -
- * value of field to get.
- * @param name -
- * name of field, to get from ValueBinding
- * @return boolean value, based on field or valuebinding.
- */
- private boolean isValueOrBinding(Boolean field, String name) {
- if (null != field) {
- return field.booleanValue();
- }
- ValueExpression vb = getValueExpression(name);
- if (null != vb) {
- FacesContext context = getFacesContext();
- ELContext elContext = context.getELContext();
- return ((Boolean) vb.getValue(elContext)).booleanValue();
- } else {
- return false;
- }
- }
+ if (null != requestValue) {
+ updateBinding.setValue(elContext, requestValue);
+ }
+ MethodExpression listener = getActionListener();
+
+ if (listener != null) {
+ listener.invoke(elContext, new Object[] {actionEvent});
+ }
+ }
+ }
+
+ /**
+ * @param context
+ * @param type
+ * @return
+ * @throws FacesException
+ */
+ private Converter createConverter(FacesContext context, Class<?> type) throws FacesException {
+ Converter converter = getConverter();
+
+ if (converter == null && type != null && !type.equals(String.class) && !type.equals(Object.class)) {
+ try {
+ converter = context.getApplication().createConverter(type);
+ } catch (Exception e) {
+ throw new FacesException(Messages.getMessage(Messages.NO_CONVERTER_REGISTERED, type.getName()), e);
+ }
+ }
+
+ return converter;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.faces.component.UIComponentBase#restoreState(javax.faces.context.FacesContext)
+ */
+ @Override
+ public void restoreState(FacesContext context, Object state) {
+ Object[] values = (Object[]) state;
+
+ super.restoreState(context, values[0]);
+
+ // restore fields values
+ assignToBinding = (ValueExpression) UIComponentBase.restoreAttachedState(context, values[1]);
+ noEscape = (Boolean) values[2];
+ converter = (Converter) UIComponentBase.restoreAttachedState(context, values[3]);
+ actionListener = (MethodExpression) UIComponentBase.restoreAttachedState(context, values[4]);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.faces.component.UIComponentBase#saveState(javax.faces.context.FacesContext)
+ */
+ @Override
+ public Object saveState(FacesContext context) {
+ Object[] values = new Object[5];
+
+ values[0] = super.saveState(context);
+
+ // save fields values
+ values[1] = UIComponentBase.saveAttachedState(context, assignToBinding);
+ values[2] = noEscape;
+ values[3] = UIComponentBase.saveAttachedState(context, converter);
+ values[4] = UIComponentBase.saveAttachedState(context, actionListener);
+
+ return values;
+ }
+
+ /**
+ * @param field -
+ * value of field to get.
+ * @param name -
+ * name of field, to get from ValueBinding
+ * @return boolean value, based on field or valuebinding.
+ */
+ private boolean isValueOrBinding(Boolean field, String name) {
+ if (null != field) {
+ return field.booleanValue();
+ }
+
+ ValueExpression vb = getValueExpression(name);
+
+ if (null != vb) {
+ FacesContext context = getFacesContext();
+ ELContext elContext = context.getELContext();
+
+ return ((Boolean) vb.getValue(elContext)).booleanValue();
+ } else {
+ return false;
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/UIPoll.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/UIPoll.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/UIPoll.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import javax.faces.context.FacesContext;
@@ -30,46 +32,40 @@
* @author shura
*
*/
-public abstract class UIPoll extends AjaxActionComponent {
-
- public static final String COMPONENT_TYPE="org.ajax4jsf.Poll";
-
+public abstract class UIPoll extends AjaxActionComponent {
+ public static final String COMPONENT_TYPE = "org.ajax4jsf.Poll";
+ private transient boolean submitted = false;
- private transient boolean _submitted = false;
+ /**
+ * @return the submitted
+ */
+ public boolean isSubmitted() {
+ return submitted;
+ }
- /**
- * @return the submitted
- */
- public boolean isSubmitted() {
- return _submitted;
- }
+ /**
+ * @param submitted the submitted to set
+ */
+ public void setSubmitted(boolean submitted) {
+ this.submitted = submitted;
+ }
+ /**
+ * @return time in mc for polling interval.
+ */
+ public abstract int getInterval();
- /**
- * @param submitted the submitted to set
- */
- public void setSubmitted(boolean submitted) {
- _submitted = submitted;
- }
+ /**
+ * @param interval time in mc for polling interval.
+ */
+ public abstract void setInterval(int interval);
- /**
- * @return time in mc for polling interval.
- */
- public abstract int getInterval();
-
- /**
- * @param interval time in mc for polling interval.
- */
- public abstract void setInterval(int interval);
-
- public abstract boolean isEnabled();
-
- public abstract void setEnabled(boolean enable);
-
- protected void setupReRender(FacesContext facesContext) {
- super.setupReRender(facesContext);
- AjaxContext.getCurrentInstance(facesContext).addComponentToAjaxRender(this);
- }
-
+ public abstract boolean isEnabled();
+ public abstract void setEnabled(boolean enable);
+
+ protected void setupReRender(FacesContext facesContext) {
+ super.setupReRender(facesContext);
+ AjaxContext.getCurrentInstance(facesContext).addComponentToAjaxRender(this);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/behavior/AjaxBehavior.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/behavior/AjaxBehavior.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/behavior/AjaxBehavior.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -5,6 +5,7 @@
import javax.el.ELContext;
import javax.el.ValueExpression;
+
import javax.faces.component.behavior.FacesBehavior;
import javax.faces.context.FacesContext;
@@ -13,321 +14,339 @@
/**
* @author Anton Belevich
- *
*/
-@FacesBehavior(value="org.ajax4jsf.behavior.Ajax")
+@FacesBehavior(value = "org.ajax4jsf.behavior.Ajax")
public class AjaxBehavior extends javax.faces.component.behavior.AjaxBehavior implements AjaxClientBehavior {
-
- public static final String BEHAVIOR_ID = "org.ajax4jsf.behavior.Ajax";
-
- private static enum Attributes {
-
- limitRender, queueId, status, render, execute, similarityGroupingId, oncomplete, onbegin, onbeforedomupdate, other;
-
- public static Attributes toAttribute(String name) {
-
- try {
- return valueOf(name);
- } catch (Exception ex) {
- return other;
- }
- }
- };
-
- private Boolean limitRender;
-
- private String queueId;
-
- private String statusId;
+ public static final String BEHAVIOR_ID = "org.ajax4jsf.behavior.Ajax";
+ private Set<String> execute;
+ private Boolean limitRender;
+ private String onbeforedomupdate;
+ private String onbegin;
+ private String oncomplete;
+ private String queueId;
+ private Set<String> render;
+ private String similarityGroupingId;
+ private String statusId;
- private String similarityGroupingId;
-
- private Set <String> render;
-
- private Set <String> execute;
-
- private String oncomplete;
-
- private String onbeforedomupdate;
-
- private String onbegin;
-
- protected Set<String> asSet(Object render) {
- return AjaxRendererUtils.asSet(render);
- }
-
- public void setOnbegin(String onbegin) {
- this.onbegin = onbegin;
- clearInitialState();
- }
-
- public String getOnbegin() {
- if(this.onbegin != null) {
- return this.onbegin;
- }
-
- ValueExpression ve = getValueExpression(Attributes.onbegin.toString());
- if(ve != null) {
- ELContext elContext = FacesContext.getCurrentInstance().getELContext();
- String value = ((String)ve.getValue(elContext));
- return value;
- }
-
- return this.onbegin;
- }
-
- public void setOnbeforedomupdate(String onbeforedomupdate) {
- this.onbeforedomupdate = onbeforedomupdate;
- clearInitialState();
- }
-
- public String getOnbeforedomupdate() {
- if(this.onbeforedomupdate != null) {
- return this.onbeforedomupdate;
- }
-
- ValueExpression ve = getValueExpression(Attributes.onbeforedomupdate.toString());
- if(ve != null) {
- ELContext elContext = FacesContext.getCurrentInstance().getELContext();
- String value = ((String)ve.getValue(elContext));
- return value;
- }
-
- return this.onbeforedomupdate;
- }
+ private static enum Attributes {
+ limitRender, queueId, status, render, execute, similarityGroupingId, oncomplete, onbegin, onbeforedomupdate,
+ other;
-
- public void setOncomplete(String oncomplete) {
- this.oncomplete = oncomplete;
- clearInitialState();
- }
-
- public String getOncomplete() {
- if(this.oncomplete != null) {
- return this.oncomplete;
- }
-
- ValueExpression ve = getValueExpression(Attributes.oncomplete.toString());
- if(ve != null) {
- ELContext elContext = FacesContext.getCurrentInstance().getELContext();
- String value = ((String)ve.getValue(elContext));
- return value;
- }
-
- return this.oncomplete;
- }
-
- public void setRender(Collection<String> render) {
- this.render = asSet(render);
- clearInitialState();
- }
-
- public Collection<String> getRender() {
- return getCollectionValue(render, "RENDER");
- }
-
- public void setExecute(Collection<String> execute) {
- this.execute = asSet(execute);
- clearInitialState();
- }
-
- public Collection<String> getExecute() {
- return getCollectionValue(execute, Attributes.execute.toString());
- }
-
- protected Collection<String> getCollectionValue(Collection<String> collection, String attribute) {
- if(collection != null) {
- return collection;
- }
-
- ValueExpression ve = getValueExpression(attribute) ;
- if(ve != null) {
- FacesContext context = FacesContext.getCurrentInstance();
- Object value = ve.getValue(context.getELContext());
- return asSet(value);
- }
-
- return this.render;
- }
-
- public String getSimilarityGroupingId() {
- if(this.similarityGroupingId != null) {
- return this.similarityGroupingId;
- }
-
- ValueExpression ve = getValueExpression(Attributes.similarityGroupingId.toString());
- if(ve != null) {
- ELContext elContext = FacesContext.getCurrentInstance().getELContext();
- String value = ((String)ve.getValue(elContext));
- return value;
- }
-
- return this.similarityGroupingId;
- }
+ public static Attributes toAttribute(String name) {
+ try {
+ return valueOf(name);
+ } catch (Exception ex) {
+ return other;
+ }
+ }
+ }
- public void setSimilarityGroupingId(String similarityGroupingId) {
- this.similarityGroupingId = similarityGroupingId;
- clearInitialState();
- }
-
- public String getStatus() {
- if(this.statusId != null) {
- return this.statusId;
- }
-
- ValueExpression ve = getValueExpression(Attributes.status.toString());
- if(ve != null) {
- ELContext elContext = FacesContext.getCurrentInstance().getELContext();
- String value = ((String)ve.getValue(elContext));
- return value;
- }
-
- return this.statusId;
- }
+ protected Set<String> asSet(Object render) {
+ return AjaxRendererUtils.asSet(render);
+ }
- public void setStatus(String statusId) {
- this.statusId = statusId;
- clearInitialState();
- }
+ public void setOnbegin(String onbegin) {
+ this.onbegin = onbegin;
+ clearInitialState();
+ }
- public String getQueueId() {
- if(this.queueId != null) {
- return this.queueId;
- }
-
- ValueExpression ve = getValueExpression(Attributes.queueId.toString());
- if(ve != null) {
- ELContext elContext = FacesContext.getCurrentInstance().getELContext();
- String value = ((String)ve.getValue(elContext));
- return value;
- }
-
- return this.queueId;
- }
+ public String getOnbegin() {
+ if (this.onbegin != null) {
+ return this.onbegin;
+ }
+ ValueExpression ve = getValueExpression(Attributes.onbegin.toString());
- public void setQueueId(String queueId) {
- this.queueId = queueId;
- clearInitialState();
- }
+ if (ve != null) {
+ ELContext elContext = FacesContext.getCurrentInstance().getELContext();
+ return (String) ve.getValue(elContext);
+ }
- public boolean isLimitRender() {
- if(this.limitRender != null) {
- return this.limitRender.booleanValue();
- }
-
- ValueExpression ve = getValueExpression(Attributes.limitRender.toString());
- if(ve != null) {
- ELContext elContext = FacesContext.getCurrentInstance().getELContext();
- Boolean value = ((Boolean)ve.getValue(elContext));
- return value != null ? value.booleanValue() : false;
- }
-
- return false;
- }
+ return this.onbegin;
+ }
+ public void setOnbeforedomupdate(String onbeforedomupdate) {
+ this.onbeforedomupdate = onbeforedomupdate;
+ clearInitialState();
+ }
- public void setLimitRender(boolean limitRender) {
- this.limitRender = limitRender;
- clearInitialState();
- }
+ public String getOnbeforedomupdate() {
+ if (this.onbeforedomupdate != null) {
+ return this.onbeforedomupdate;
+ }
- @Override
- public String getRendererType() {
- return BEHAVIOR_ID;
- }
-
- @Override
- public void setValueExpression(String name, ValueExpression expression) {
- if(expression != null && expression.isLiteralText()) {
- Object value = getExpressionLiteralValue(expression);
- switch(Attributes.toAttribute(name)) {
-
- case limitRender:
- this.limitRender = value != null ? (Boolean)value : Boolean.FALSE ; break;
-
- case execute :
- this.execute = value != null ? asSet(value) : null; break;
-
- case render :
- this.render = value != null ? asSet(value) : null; break;
-
- case queueId :
- this.queueId = value != null ? (String)value : null; break;
-
- case status :
- this.statusId = value != null ? (String)value : null; break;
-
- case similarityGroupingId :
- this.similarityGroupingId = value != null ? (String)value: null; break;
-
- case onbeforedomupdate :
- this.onbeforedomupdate = value != null ? (String)value : null; break;
-
- case onbegin :
- this.onbegin = value != null ? (String)value : null; break;
-
- case oncomplete :
- this.oncomplete = value != null ? (String)value : null; break;
- default: break;
-
- }
- }
- super.setValueExpression(name, expression);
- }
-
- protected Object getExpressionLiteralValue(ValueExpression expression) {
- return expression != null ? expression.getValue(FacesContext.getCurrentInstance().getELContext()) : null;
- }
-
- @Override
- public Object saveState(FacesContext context) {
- Object superState = super.saveState(context);
- Object[] values;
-
- if (initialStateMarked()) {
- if (superState == null) {
- values = null;
- } else {
- values = new Object[] { superState };
- }
- } else {
- values = new Object[10];
- values[0] = superState;
- values[1] = limitRender;
- values[2] = execute;
- values[3] = render;
- values[4] = queueId;
- values[5] = statusId;
- values[6] = similarityGroupingId;
- values[7] = onbeforedomupdate;
- values[8] = onbegin;
- values[9] = oncomplete;
- }
+ ValueExpression ve = getValueExpression(Attributes.onbeforedomupdate.toString());
- return values;
- }
-
- @Override
- public void restoreState(FacesContext context, Object state) {
- if (state != null) {
-
- Object[] values = (Object[]) state;
- super.restoreState(context, values[0]);
-
- if (values.length != 1) {
- this.limitRender = (Boolean)values[1];
- this.execute = asSet(values[2]);
- this.render = asSet(values[3]);
- this.queueId = (String)values[4];
- this.statusId = (String)values[5];
- this.similarityGroupingId = (String)values[6];
- this.onbeforedomupdate = (String)values[7];
- this.onbegin = (String)values[8];
- this.oncomplete = (String)values[9];
- clearInitialState();
- }
- }
- }
-}
\ No newline at end of file
+ if (ve != null) {
+ ELContext elContext = FacesContext.getCurrentInstance().getELContext();
+
+ return (String) ve.getValue(elContext);
+ }
+
+ return this.onbeforedomupdate;
+ }
+
+ public void setOncomplete(String oncomplete) {
+ this.oncomplete = oncomplete;
+ clearInitialState();
+ }
+
+ public String getOncomplete() {
+ if (this.oncomplete != null) {
+ return this.oncomplete;
+ }
+
+ ValueExpression ve = getValueExpression(Attributes.oncomplete.toString());
+
+ if (ve != null) {
+ ELContext elContext = FacesContext.getCurrentInstance().getELContext();
+
+ return (String) ve.getValue(elContext);
+ }
+
+ return this.oncomplete;
+ }
+
+ @Override
+ public void setRender(Collection<String> render) {
+ this.render = asSet(render);
+ clearInitialState();
+ }
+
+ @Override
+ public Collection<String> getRender() {
+ return getCollectionValue(render, "RENDER");
+ }
+
+ @Override
+ public void setExecute(Collection<String> execute) {
+ this.execute = asSet(execute);
+ clearInitialState();
+ }
+
+ @Override
+ public Collection<String> getExecute() {
+ return getCollectionValue(execute, Attributes.execute.toString());
+ }
+
+ protected Collection<String> getCollectionValue(Collection<String> collection, String attribute) {
+ if (collection != null) {
+ return collection;
+ }
+
+ ValueExpression ve = getValueExpression(attribute);
+
+ if (ve != null) {
+ FacesContext context = FacesContext.getCurrentInstance();
+ Object value = ve.getValue(context.getELContext());
+
+ return asSet(value);
+ }
+
+ return this.render;
+ }
+
+ public String getSimilarityGroupingId() {
+ if (this.similarityGroupingId != null) {
+ return this.similarityGroupingId;
+ }
+
+ ValueExpression ve = getValueExpression(Attributes.similarityGroupingId.toString());
+
+ if (ve != null) {
+ ELContext elContext = FacesContext.getCurrentInstance().getELContext();
+
+ return (String) ve.getValue(elContext);
+ }
+
+ return this.similarityGroupingId;
+ }
+
+ public void setSimilarityGroupingId(String similarityGroupingId) {
+ this.similarityGroupingId = similarityGroupingId;
+ clearInitialState();
+ }
+
+ public String getStatus() {
+ if (this.statusId != null) {
+ return this.statusId;
+ }
+
+ ValueExpression ve = getValueExpression(Attributes.status.toString());
+
+ if (ve != null) {
+ ELContext elContext = FacesContext.getCurrentInstance().getELContext();
+
+ return (String) ve.getValue(elContext);
+ }
+
+ return this.statusId;
+ }
+
+ public void setStatus(String statusId) {
+ this.statusId = statusId;
+ clearInitialState();
+ }
+
+ public String getQueueId() {
+ if (this.queueId != null) {
+ return this.queueId;
+ }
+
+ ValueExpression ve = getValueExpression(Attributes.queueId.toString());
+
+ if (ve != null) {
+ ELContext elContext = FacesContext.getCurrentInstance().getELContext();
+
+ return (String) ve.getValue(elContext);
+ }
+
+ return this.queueId;
+ }
+
+ public void setQueueId(String queueId) {
+ this.queueId = queueId;
+ clearInitialState();
+ }
+
+ public boolean isLimitRender() {
+ if (this.limitRender != null) {
+ return this.limitRender.booleanValue();
+ }
+
+ ValueExpression ve = getValueExpression(Attributes.limitRender.toString());
+
+ if (ve != null) {
+ ELContext elContext = FacesContext.getCurrentInstance().getELContext();
+ Boolean value = (Boolean) ve.getValue(elContext);
+
+ return value != null ? value.booleanValue() : false;
+ }
+
+ return false;
+ }
+
+ public void setLimitRender(boolean limitRender) {
+ this.limitRender = limitRender;
+ clearInitialState();
+ }
+
+ @Override
+ public String getRendererType() {
+ return BEHAVIOR_ID;
+ }
+
+ @Override
+ public void setValueExpression(String name, ValueExpression expression) {
+ if (expression != null && expression.isLiteralText()) {
+ Object value = getExpressionLiteralValue(expression);
+
+ switch (Attributes.toAttribute(name)) {
+ case limitRender :
+ this.limitRender = value != null ? (Boolean) value : Boolean.FALSE;
+
+ break;
+
+ case execute :
+ this.execute = value != null ? asSet(value) : null;
+
+ break;
+
+ case render :
+ this.render = value != null ? asSet(value) : null;
+
+ break;
+
+ case queueId :
+ this.queueId = value != null ? (String) value : null;
+
+ break;
+
+ case status :
+ this.statusId = value != null ? (String) value : null;
+
+ break;
+
+ case similarityGroupingId :
+ this.similarityGroupingId = value != null ? (String) value : null;
+
+ break;
+
+ case onbeforedomupdate :
+ this.onbeforedomupdate = value != null ? (String) value : null;
+
+ break;
+
+ case onbegin :
+ this.onbegin = value != null ? (String) value : null;
+
+ break;
+
+ case oncomplete :
+ this.oncomplete = value != null ? (String) value : null;
+
+ break;
+
+ default :
+ break;
+ }
+ }
+
+ super.setValueExpression(name, expression);
+ }
+
+ protected Object getExpressionLiteralValue(ValueExpression expression) {
+ return expression != null ? expression.getValue(FacesContext.getCurrentInstance().getELContext()) : null;
+ }
+
+ @Override
+ public Object saveState(FacesContext context) {
+ Object superState = super.saveState(context);
+ Object[] values;
+
+ if (initialStateMarked()) {
+ if (superState == null) {
+ values = null;
+ } else {
+ values = new Object[] {superState};
+ }
+ } else {
+ values = new Object[10];
+ values[0] = superState;
+ values[1] = limitRender;
+ values[2] = execute;
+ values[3] = render;
+ values[4] = queueId;
+ values[5] = statusId;
+ values[6] = similarityGroupingId;
+ values[7] = onbeforedomupdate;
+ values[8] = onbegin;
+ values[9] = oncomplete;
+ }
+
+ return values;
+ }
+
+ @Override
+ public void restoreState(FacesContext context, Object state) {
+ if (state != null) {
+ Object[] values = (Object[]) state;
+
+ super.restoreState(context, values[0]);
+
+ if (values.length != 1) {
+ this.limitRender = (Boolean) values[1];
+ this.execute = asSet(values[2]);
+ this.render = asSet(values[3]);
+ this.queueId = (String) values[4];
+ this.statusId = (String) values[5];
+ this.similarityGroupingId = (String) values[6];
+ this.onbeforedomupdate = (String) values[7];
+ this.onbegin = (String) values[8];
+ this.oncomplete = (String) values[9];
+ clearInitialState();
+ }
+ }
+ }
+}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/package-info.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/package-info.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/component/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -1,3 +1,4 @@
+
/**
* Fundamental APIs for ajax core components
*/
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/AjaxHandler.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/AjaxHandler.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/AjaxHandler.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -2,7 +2,9 @@
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
+
import java.io.IOException;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -10,6 +12,7 @@
import javax.el.ELContext;
import javax.el.MethodExpression;
+
import javax.faces.application.Application;
import javax.faces.component.UIComponent;
import javax.faces.component.behavior.ClientBehaviorHolder;
@@ -31,239 +34,236 @@
import org.ajax4jsf.component.behavior.AjaxBehavior;
-
public class AjaxHandler extends TagHandler implements BehaviorHolderAttachedObjectHandler {
- /**
- *
- */
- //TODO - is that implementation dependency?
- private static final String JAVAX_FACES_RETARGETABLE_HANDLERS = "javax.faces.RetargetableHandlers";
-
- private final TagAttribute event;
- private final TagAttribute execute;
- private final TagAttribute render;
- private final TagAttribute disabled;
- private final TagAttribute immediate;
- private final TagAttribute listener;
- private final TagAttribute limitRender;
- private final TagAttribute queueId;
- private final TagAttribute statusId;
- private final TagAttribute similarityGroupingId;
- private final TagAttribute onevent;
- private final TagAttribute onerror;
- private final TagAttribute onbegin;
- private final TagAttribute oncomplete;
- private final TagAttribute onbeforedomupdate;
+ // TODO - is that implementation dependency?
+ private static final String JAVAX_FACES_RETARGETABLE_HANDLERS = "javax.faces.RetargetableHandlers";
+ private final TagAttribute disabled;
+ private final TagAttribute event;
+ private final TagAttribute execute;
+ private final TagAttribute immediate;
+ private final TagAttribute limitRender;
+ private final TagAttribute listener;
+ private final TagAttribute onbeforedomupdate;
+ private final TagAttribute onbegin;
+ private final TagAttribute oncomplete;
+ private final TagAttribute onerror;
+ private final TagAttribute onevent;
+ private final TagAttribute queueId;
+ private final TagAttribute render;
+ private final TagAttribute similarityGroupingId;
+ private final TagAttribute statusId;
private final boolean wrapping;
-
- public AjaxHandler(BehaviorConfig config) {
- super(config);
- this.event = this.getAttribute("event");
- this.execute = this.getAttribute("execute");
- this.render = this.getAttribute("render");
- this.disabled = this.getAttribute("disabled");
- this.immediate = this.getAttribute("immediate");
- this.listener = this.getAttribute("listener");
- this.limitRender = this.getAttribute("limitRender");
- this.queueId = this.getAttribute("queueId");
- this.statusId = this.getAttribute("status");
- this.similarityGroupingId = this.getAttribute("similarityGroupingId");
- this.onevent = this.getAttribute("onevent");
- this.onerror = this.getAttribute("onerror");
- this.onbegin = this.getAttribute("onbegin");
- this.oncomplete = this.getAttribute("oncomplete");
- this.onbeforedomupdate = this.getAttribute("onbeforedomupdate");
- this.wrapping = isWrapping();
- }
+ public AjaxHandler(BehaviorConfig config) {
+ super(config);
+ this.event = this.getAttribute("event");
+ this.execute = this.getAttribute("execute");
+ this.render = this.getAttribute("render");
+ this.disabled = this.getAttribute("disabled");
+ this.immediate = this.getAttribute("immediate");
+ this.listener = this.getAttribute("listener");
+ this.limitRender = this.getAttribute("limitRender");
+ this.queueId = this.getAttribute("queueId");
+ this.statusId = this.getAttribute("status");
+ this.similarityGroupingId = this.getAttribute("similarityGroupingId");
+ this.onevent = this.getAttribute("onevent");
+ this.onerror = this.getAttribute("onerror");
+ this.onbegin = this.getAttribute("onbegin");
+ this.oncomplete = this.getAttribute("oncomplete");
+ this.onbeforedomupdate = this.getAttribute("onbeforedomupdate");
+ this.wrapping = isWrapping();
+ }
- public void apply(FaceletContext fContext, UIComponent parent) throws IOException {
+ public void apply(FaceletContext fContext, UIComponent parent) throws IOException {
String eventName = getEventName();
+
if (this.wrapping) {
- applyWrapping(fContext, parent, eventName);
+ applyWrapping(fContext, parent, eventName);
} else {
- applyNested(fContext, parent, eventName);
+ applyNested(fContext, parent, eventName);
}
- }
+ }
- private static List<AttachedObjectHandler> getOrCreateRetargetableHandlersList(UIComponent component) {
+ private static List<AttachedObjectHandler> getOrCreateRetargetableHandlersList(UIComponent component) {
Map<String, Object> attrs = component.getAttributes();
- @SuppressWarnings({"unchecked"})
- List<AttachedObjectHandler> list = (List<AttachedObjectHandler>)
- attrs.get(JAVAX_FACES_RETARGETABLE_HANDLERS);
+ @SuppressWarnings({
+ "unchecked"}) List<AttachedObjectHandler> list =
+ (List<AttachedObjectHandler>) attrs.get(JAVAX_FACES_RETARGETABLE_HANDLERS);
if (list == null) {
list = new ArrayList<AttachedObjectHandler>();
attrs.put(JAVAX_FACES_RETARGETABLE_HANDLERS, list);
}
-
+
return list;
- }
-
- private void applyNested(FaceletContext ctx, UIComponent parent, String eventName) {
- if (!ComponentHandler.isNew(parent)) {
- return;
- }
+ }
- if (UIComponent.isCompositeComponent(parent)) {
+ private void applyNested(FaceletContext ctx, UIComponent parent, String eventName) {
+ if (!ComponentHandler.isNew(parent)) {
+ return;
+ }
+
+ if (UIComponent.isCompositeComponent(parent)) {
BeanInfo componentBeanInfo = (BeanInfo) parent.getAttributes().get(UIComponent.BEANINFO_KEY);
+
if (null == componentBeanInfo) {
- throw new TagException(
- tag,
- "Error: enclosing composite component does not have BeanInfo attribute");
+ throw new TagException(tag, "Error: enclosing composite component does not have BeanInfo attribute");
}
+
BeanDescriptor componentDescriptor = componentBeanInfo.getBeanDescriptor();
+
if (null == componentDescriptor) {
- throw new TagException(
- tag,
- "Error: enclosing composite component BeanInfo does not have BeanDescriptor");
+ throw new TagException(tag,
+ "Error: enclosing composite component BeanInfo does not have BeanDescriptor");
}
- @SuppressWarnings("unchecked")
- List<AttachedObjectTarget> targetList = (List<AttachedObjectTarget>)
- componentDescriptor.getValue(AttachedObjectTarget.ATTACHED_OBJECT_TARGETS_KEY);
-
+ @SuppressWarnings(
+ "unchecked") List<AttachedObjectTarget> targetList =
+ (List<AttachedObjectTarget>) componentDescriptor.getValue(
+ AttachedObjectTarget.ATTACHED_OBJECT_TARGETS_KEY);
+
if (null == targetList) {
- throw new TagException(
- tag,
- "Error: enclosing composite component does not support behavior events");
+ throw new TagException(tag, "Error: enclosing composite component does not support behavior events");
}
+
boolean supportedEvent = false;
+
for (AttachedObjectTarget target : targetList) {
if (target instanceof BehaviorHolderAttachedObjectTarget) {
BehaviorHolderAttachedObjectTarget behaviorTarget = (BehaviorHolderAttachedObjectTarget) target;
+
if ((null != eventName && eventName.equals(behaviorTarget.getName()))
- || (null == eventName && behaviorTarget.isDefaultEvent())) {
+ || (null == eventName && behaviorTarget.isDefaultEvent())) {
supportedEvent = true;
+
break;
}
}
}
+
if (supportedEvent) {
- getOrCreateRetargetableHandlersList(parent).add(this);
+ getOrCreateRetargetableHandlersList(parent).add(this);
} else {
- throw new TagException(
- tag,
- "Error: enclosing composite component does not support event "
- + eventName);
+ throw new TagException(tag, "Error: enclosing composite component does not support event " + eventName);
}
- } else if (parent instanceof ClientBehaviorHolder) {
- applyAttachedObject(ctx, parent, eventName);
- } else {
- throw new TagException(this.tag,"Unable to attach <a4j:ajax> to non-ClientBehaviorHolder parent");
- }
- }
+ } else if (parent instanceof ClientBehaviorHolder) {
+ applyAttachedObject(ctx, parent, eventName);
+ } else {
+ throw new TagException(this.tag, "Unable to attach <a4j:ajax> to non-ClientBehaviorHolder parent");
+ }
+ }
-
- private void applyWrapping(FaceletContext ctx, UIComponent parent, String eventName) throws IOException {
- AjaxBehavior ajaxBehavior = createAjaxBehavior(ctx, eventName);
+ private void applyWrapping(FaceletContext ctx, UIComponent parent, String eventName) throws IOException {
+ AjaxBehavior ajaxBehavior = createAjaxBehavior(ctx, eventName);
+ FacesContext context = ctx.getFacesContext();
+ BehaviorStack ajaxBehaviors = BehaviorStack.getBehaviorStack(context, true);
- FacesContext context = ctx.getFacesContext();
- BehaviorStack ajaxBehaviors = BehaviorStack.getBehaviorStack(context, true);
- ajaxBehaviors.pushBehavior(context, ajaxBehavior, AjaxBehavior.BEHAVIOR_ID, eventName);
+ ajaxBehaviors.pushBehavior(context, ajaxBehavior, AjaxBehavior.BEHAVIOR_ID, eventName);
+ nextHandler.apply(ctx, parent);
+ ajaxBehaviors.popBehavior();
+ }
- nextHandler.apply(ctx, parent);
+ public void applyAttachedObject(FaceletContext fContext, UIComponent parent, String eventName) {
+ ClientBehaviorHolder bHolder = (ClientBehaviorHolder) parent;
- ajaxBehaviors.popBehavior();
- }
+ if (null == eventName) {
+ eventName = bHolder.getDefaultEventName();
-
- public void applyAttachedObject(FaceletContext fContext, UIComponent parent, String eventName) {
- ClientBehaviorHolder bHolder = (ClientBehaviorHolder) parent;
- if (null == eventName) {
- eventName = bHolder.getDefaultEventName();
- if (null == eventName) {
- throw new TagException(this.tag, "Event attribute could not be determined: " + eventName);
- }
- } else {
- Collection<String> eventNames = bHolder.getEventNames();
- if (!eventNames.contains(eventName)) {
- throw new TagException(this.tag, eventName + "event is not supported for the " + parent.getClass().getSimpleName());
- }
- }
- AjaxBehavior ajaxBehavior = createAjaxBehavior(fContext, eventName);
- bHolder.addClientBehavior(eventName, ajaxBehavior);
- }
-
-
- public AjaxBehavior createAjaxBehavior(FaceletContext fContext, String eventName) {
- Application application = fContext.getFacesContext().getApplication();
- AjaxBehavior ajaxBehavior = (AjaxBehavior)application.createBehavior(AjaxBehavior.BEHAVIOR_ID);
-
- setBehaviorAttribute(fContext, ajaxBehavior, this.disabled, Boolean.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.immediate, Boolean.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.execute, Object.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.render, Object.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.limitRender, Boolean.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.queueId, String.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.statusId, String.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.similarityGroupingId, String.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.onevent, String.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.onerror, String.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.onbegin, String.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.oncomplete, String.class);
- setBehaviorAttribute(fContext, ajaxBehavior, this.onbeforedomupdate, String.class);
-
- registerBehaviorListener(fContext, ajaxBehavior, listener);
+ if (null == eventName) {
+ throw new TagException(this.tag, "Event attribute could not be determined: " + eventName);
+ }
+ } else {
+ Collection<String> eventNames = bHolder.getEventNames();
- return ajaxBehavior;
- }
-
- public void applyAttachedObject(FacesContext context, UIComponent parent) {
- FaceletContext ctx = (FaceletContext) context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
- applyAttachedObject(ctx, parent, getEventName());
- }
-
- private void setBehaviorAttribute(FaceletContext ctx, AjaxBehavior behavior, TagAttribute attr, Class<?> type) {
- if (attr != null) {
- behavior.setValueExpression(attr.getLocalName(),
- attr.getValueExpression(ctx, type));
- }
- }
-
- public String getEventName() {
- return (this.event != null) ? this.event.getValue() : null;
- }
+ if (!eventNames.contains(eventName)) {
+ throw new TagException(this.tag,
+ eventName + "event is not supported for the "
+ + parent.getClass().getSimpleName());
+ }
+ }
- public String getFor() {
- return null;
- }
-
+ AjaxBehavior ajaxBehavior = createAjaxBehavior(fContext, eventName);
+
+ bHolder.addClientBehavior(eventName, ajaxBehavior);
+ }
+
+ public AjaxBehavior createAjaxBehavior(FaceletContext fContext, String eventName) {
+ Application application = fContext.getFacesContext().getApplication();
+ AjaxBehavior ajaxBehavior = (AjaxBehavior) application.createBehavior(AjaxBehavior.BEHAVIOR_ID);
+
+ setBehaviorAttribute(fContext, ajaxBehavior, this.disabled, Boolean.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.immediate, Boolean.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.execute, Object.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.render, Object.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.limitRender, Boolean.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.queueId, String.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.statusId, String.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.similarityGroupingId, String.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.onevent, String.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.onerror, String.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.onbegin, String.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.oncomplete, String.class);
+ setBehaviorAttribute(fContext, ajaxBehavior, this.onbeforedomupdate, String.class);
+ registerBehaviorListener(fContext, ajaxBehavior, listener);
+
+ return ajaxBehavior;
+ }
+
+ public void applyAttachedObject(FacesContext context, UIComponent parent) {
+ FaceletContext ctx = (FaceletContext) context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
+
+ applyAttachedObject(ctx, parent, getEventName());
+ }
+
+ private void setBehaviorAttribute(FaceletContext ctx, AjaxBehavior behavior, TagAttribute attr, Class<?> type) {
+ if (attr != null) {
+ behavior.setValueExpression(attr.getLocalName(), attr.getValueExpression(ctx, type));
+ }
+ }
+
+ public String getEventName() {
+ return (this.event != null) ? this.event.getValue() : null;
+ }
+
+ public String getFor() {
+ return null;
+ }
+
private boolean isWrapping() {
- return ((this.nextHandler instanceof TagHandler) || (this.nextHandler instanceof CompositeFaceletHandler));
+ return (this.nextHandler instanceof TagHandler) || (this.nextHandler instanceof CompositeFaceletHandler);
}
-
+
public void registerBehaviorListener(FaceletContext fContext, AjaxBehavior behavior, TagAttribute listenerAttr) {
- if(listenerAttr != null) {
- MethodExpression mExpression = listenerAttr.getMethodExpression(fContext, Object.class, new Class[]{AjaxBehaviorEvent.class});
- behavior.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(mExpression));
- }
+ if (listenerAttr != null) {
+ MethodExpression mExpression = listenerAttr.getMethodExpression(fContext, Object.class,
+ new Class[] {AjaxBehaviorEvent.class});
+
+ behavior.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(mExpression));
+ }
}
-
+
public class AjaxBehaviorListenerImpl implements AjaxBehaviorListener {
-
- private MethodExpression methodExpression;
-
- public AjaxBehaviorListenerImpl() {};
-
- public AjaxBehaviorListenerImpl(MethodExpression expression) {
- this.methodExpression = expression;
- }
-
- public void processAjaxBehavior(AjaxBehaviorEvent event) throws AbortProcessingException {
- if(methodExpression != null) {
- ELContext elContext = FacesContext.getCurrentInstance().getELContext();
-
- try {
- methodExpression.invoke(elContext, new Object[] {event});
- } catch (Exception e) {
- //TODO: log or message ??
- throw new AbortProcessingException(e);
- }
- }
- }
-
+ private MethodExpression methodExpression;
+
+ public AjaxBehaviorListenerImpl() {}
+
+ public AjaxBehaviorListenerImpl(MethodExpression expression) {
+ this.methodExpression = expression;
+ }
+
+ public void processAjaxBehavior(AjaxBehaviorEvent event) throws AbortProcessingException {
+ if (methodExpression != null) {
+ ELContext elContext = FacesContext.getCurrentInstance().getELContext();
+
+ try {
+ methodExpression.invoke(elContext, new Object[] {event});
+ } catch (Exception e) {
+
+ // TODO: log or message ??
+ throw new AbortProcessingException(e);
+ }
+ }
+ }
}
-
}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorStack.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorStack.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorStack.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,9 @@
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
+
+
+
package org.ajax4jsf.facelets.tag;
import java.util.LinkedList;
@@ -35,118 +38,115 @@
/**
* @author Nick Belaevski
- *
+ *
* This class is necessary to handle nesting wrapping behaviors properly and is created
* to work around this issue: https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=655
*
*/
+
//TODO - check for bug resolution
final class BehaviorStack {
+ private static final String BEHAVIOR_STACK = "org.richfaces.BehaviorStack";
+ private LinkedList<BehaviorInfo> behaviorStack = null;
- private static final String BEHAVIOR_STACK = "org.richfaces.BehaviorStack";
+ public BehaviorStack() {
+ behaviorStack = new LinkedList<BehaviorInfo>();
+ }
- private static class BehaviorInfo {
+ public static BehaviorStack getBehaviorStack(FacesContext context, boolean createIfNull) {
+ Map<Object, Object> attributes = context.getAttributes();
+ BehaviorStack behaviorStack = (BehaviorStack) attributes.get(BEHAVIOR_STACK);
- private String behaviorId;
- private String eventName;
- private Object behaviorState;
+ if (behaviorStack == null && createIfNull) {
+ behaviorStack = new BehaviorStack();
+ attributes.put(BEHAVIOR_STACK, behaviorStack);
+ }
- public BehaviorInfo(String behaviorId, String eventName,
- Object behaviorState) {
- this.behaviorId = behaviorId;
- this.eventName = eventName;
- this.behaviorState = behaviorState;
- }
+ return behaviorStack;
+ }
- public void addBehavior(FacesContext context, ClientBehaviorHolder behaviorHolder) {
- String eventName = this.eventName;
- if (eventName == null) {
- eventName = behaviorHolder.getDefaultEventName();
+ public void addBehaviors(FacesContext context, ClientBehaviorHolder behaviorHolder) {
+ if (behaviorStack == null || behaviorStack.isEmpty()) {
+ return;
+ }
- if (eventName == null) {
- return;
- }
- }
+ for (BehaviorInfo behaviorInfo : behaviorStack) {
+ behaviorInfo.addBehavior(context, behaviorHolder);
+ }
+ }
- if (shouldAddBehavior(behaviorHolder, eventName)) {
- ClientBehavior behavior = createBehavior(context);
- behaviorHolder.addClientBehavior(eventName, behavior);
- }
- }
+ public void pushBehavior(FacesContext context, ClientBehavior clientBehavior, String behaviorId, String eventName) {
+ Object behaviorState = ((StateHolder) clientBehavior).saveState(context);
- private boolean shouldAddBehavior(ClientBehaviorHolder behaviorHolder, String eventName) {
+ // closer behaviors are processed earlier
+ behaviorStack.addFirst(new BehaviorInfo(behaviorId, eventName, behaviorState));
+ }
- if (!behaviorHolder.getEventNames().contains(eventName)) {
- return false;
- }
+ public void popBehavior() {
+ if (!behaviorStack.isEmpty()) {
+ behaviorStack.removeFirst();
+ }
+ }
- Map<String,List<ClientBehavior>> clientBehaviorsMap = behaviorHolder.getClientBehaviors();
- List<ClientBehavior> clientBehaviors = clientBehaviorsMap.get(eventName);
+ private static class BehaviorInfo {
+ private String behaviorId;
+ private Object behaviorState;
+ private String eventName;
- if (clientBehaviors == null || clientBehaviors.isEmpty()) {
- return true;
- }
+ public BehaviorInfo(String behaviorId, String eventName, Object behaviorState) {
+ this.behaviorId = behaviorId;
+ this.eventName = eventName;
+ this.behaviorState = behaviorState;
+ }
- for (ClientBehavior behavior : clientBehaviors) {
- Set<ClientBehaviorHint> hints = behavior.getHints();
+ public void addBehavior(FacesContext context, ClientBehaviorHolder behaviorHolder) {
+ String eventName = this.eventName;
- if (hints.contains(ClientBehaviorHint.SUBMITTING)) {
- return false;
- }
- }
+ if (eventName == null) {
+ eventName = behaviorHolder.getDefaultEventName();
- return true;
- }
+ if (eventName == null) {
+ return;
+ }
+ }
- private ClientBehavior createBehavior(FacesContext context) {
- Application application = context.getApplication();
+ if (shouldAddBehavior(behaviorHolder, eventName)) {
+ ClientBehavior behavior = createBehavior(context);
- ClientBehavior behavior = (ClientBehavior) application.createBehavior(this.behaviorId);
+ behaviorHolder.addClientBehavior(eventName, behavior);
+ }
+ }
- ((StateHolder) behavior).restoreState(context, behaviorState);
+ private boolean shouldAddBehavior(ClientBehaviorHolder behaviorHolder, String eventName) {
+ if (!behaviorHolder.getEventNames().contains(eventName)) {
+ return false;
+ }
- return behavior;
- }
- }
+ Map<String, List<ClientBehavior>> clientBehaviorsMap = behaviorHolder.getClientBehaviors();
+ List<ClientBehavior> clientBehaviors = clientBehaviorsMap.get(eventName);
- private LinkedList<BehaviorInfo> behaviorStack = null;
+ if (clientBehaviors == null || clientBehaviors.isEmpty()) {
+ return true;
+ }
- public BehaviorStack() {
- behaviorStack = new LinkedList<BehaviorInfo>();
- }
+ for (ClientBehavior behavior : clientBehaviors) {
+ Set<ClientBehaviorHint> hints = behavior.getHints();
- public static BehaviorStack getBehaviorStack(FacesContext context, boolean createIfNull) {
- Map<Object, Object> attributes = context.getAttributes();
- BehaviorStack behaviorStack = (BehaviorStack) attributes.get(BEHAVIOR_STACK);
- if (behaviorStack == null && createIfNull) {
- behaviorStack = new BehaviorStack();
- attributes.put(BEHAVIOR_STACK, behaviorStack);
- }
+ if (hints.contains(ClientBehaviorHint.SUBMITTING)) {
+ return false;
+ }
+ }
- return behaviorStack;
- }
+ return true;
+ }
- public void addBehaviors(FacesContext context, ClientBehaviorHolder behaviorHolder) {
- if (behaviorStack == null || behaviorStack.isEmpty()) {
- return;
- }
+ private ClientBehavior createBehavior(FacesContext context) {
+ Application application = context.getApplication();
+ ClientBehavior behavior = (ClientBehavior) application.createBehavior(this.behaviorId);
- for (BehaviorInfo behaviorInfo : behaviorStack) {
- behaviorInfo.addBehavior(context, behaviorHolder);
- }
- }
+ ((StateHolder) behavior).restoreState(context, behaviorState);
- public void pushBehavior(FacesContext context, ClientBehavior clientBehavior, String behaviorId,
- String eventName) {
-
- Object behaviorState = ((StateHolder) clientBehavior).saveState(context);
- //closer behaviors are processed earlier
- behaviorStack.addFirst(new BehaviorInfo(behaviorId, eventName, behaviorState));
- }
-
- public void popBehavior() {
- if (!behaviorStack.isEmpty()) {
- behaviorStack.removeFirst();
- }
- }
+ return behavior;
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorsAddingComponentHandlerWrapper.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorsAddingComponentHandlerWrapper.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorsAddingComponentHandlerWrapper.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,11 +19,15 @@
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
+
+
+
package org.ajax4jsf.facelets.tag;
import java.io.IOException;
import javax.el.ELException;
+
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.component.behavior.ClientBehaviorHolder;
@@ -38,82 +42,77 @@
* @author Nick Belaevski
*/
public class BehaviorsAddingComponentHandlerWrapper extends ComponentHandler {
+ private ComponentHandler componentHandler;
- private ComponentHandler componentHandler;
+ public BehaviorsAddingComponentHandlerWrapper(ComponentHandler componentHandler) {
+ super(componentHandler.getComponentConfig());
+ this.componentHandler = componentHandler;
+ }
- public BehaviorsAddingComponentHandlerWrapper(ComponentHandler componentHandler) {
- super(componentHandler.getComponentConfig());
- this.componentHandler = componentHandler;
- }
+ public void apply(FaceletContext ctx, UIComponent parent) throws IOException {
+ componentHandler.apply(ctx, parent);
+ }
- public void apply(FaceletContext ctx, UIComponent parent)
- throws IOException {
- componentHandler.apply(ctx, parent);
- }
+ public void applyNextHandler(FaceletContext ctx, UIComponent c) throws IOException, FacesException, ELException {
+ componentHandler.applyNextHandler(ctx, c);
+ }
- public void applyNextHandler(FaceletContext ctx, UIComponent c)
- throws IOException, FacesException, ELException {
- componentHandler.applyNextHandler(ctx, c);
- }
+ public TagAttribute getBinding() {
+ return componentHandler.getBinding();
+ }
- public TagAttribute getBinding() {
- return componentHandler.getBinding();
- }
+ public ComponentConfig getComponentConfig() {
+ return componentHandler.getComponentConfig();
+ }
- public ComponentConfig getComponentConfig() {
- return componentHandler.getComponentConfig();
- }
+ public Tag getTag() {
+ return componentHandler.getTag();
+ }
- public Tag getTag() {
- return componentHandler.getTag();
- }
+ public TagAttribute getTagAttribute(String localName) {
+ return componentHandler.getTagAttribute(localName);
+ }
- public TagAttribute getTagAttribute(String localName) {
- return componentHandler.getTagAttribute(localName);
- }
+ public String getTagId() {
+ return componentHandler.getTagId();
+ }
- public String getTagId() {
- return componentHandler.getTagId();
- }
+ public boolean equals(Object obj) {
+ return componentHandler.equals(obj);
+ }
- public boolean equals(Object obj) {
- return componentHandler.equals(obj);
- }
+ public int hashCode() {
+ return componentHandler.hashCode();
+ }
- public int hashCode() {
- return componentHandler.hashCode();
- }
+ public String toString() {
+ return componentHandler.toString();
+ }
- public String toString() {
- return componentHandler.toString();
- }
-
- public boolean isDisabled(FaceletContext ctx) {
- return componentHandler.isDisabled(ctx);
- }
+ public boolean isDisabled(FaceletContext ctx) {
+ return componentHandler.isDisabled(ctx);
+ }
- public void onComponentCreated(FaceletContext ctx, UIComponent c,
- UIComponent parent) {
- componentHandler.onComponentCreated(ctx, c, parent);
- }
+ public void onComponentCreated(FaceletContext ctx, UIComponent c, UIComponent parent) {
+ componentHandler.onComponentCreated(ctx, c, parent);
+ }
- public void onComponentPopulated(FaceletContext ctx, UIComponent c,
- UIComponent parent) {
-
- FacesContext facesContext = ctx.getFacesContext();
- BehaviorStack behaviorStack = BehaviorStack.getBehaviorStack(facesContext, false);
- if (behaviorStack != null) {
- if (c instanceof ClientBehaviorHolder) {
- ClientBehaviorHolder behaviorHolder = (ClientBehaviorHolder) c;
- behaviorStack.addBehaviors(facesContext, behaviorHolder);
- }
- }
-
- componentHandler.onComponentPopulated(ctx, c, parent);
- }
+ public void onComponentPopulated(FaceletContext ctx, UIComponent c, UIComponent parent) {
+ FacesContext facesContext = ctx.getFacesContext();
+ BehaviorStack behaviorStack = BehaviorStack.getBehaviorStack(facesContext, false);
- public void setAttributes(FaceletContext ctx, Object instance) {
- componentHandler.setAttributes(ctx, instance);
- }
+ if (behaviorStack != null) {
+ if (c instanceof ClientBehaviorHolder) {
+ ClientBehaviorHolder behaviorHolder = (ClientBehaviorHolder) c;
+ behaviorStack.addBehaviors(facesContext, behaviorHolder);
+ }
+ }
+
+ componentHandler.onComponentPopulated(ctx, c, parent);
+ }
+
+ public void setAttributes(FaceletContext ctx, Object instance) {
+ componentHandler.setAttributes(ctx, instance);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorsTagHandlerDelegateFactoryImpl.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorsTagHandlerDelegateFactoryImpl.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/facelets/tag/BehaviorsTagHandlerDelegateFactoryImpl.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,9 @@
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
+
+
+
package org.ajax4jsf.facelets.tag;
import javax.faces.view.facelets.BehaviorHandler;
@@ -32,48 +35,48 @@
* @author Nick Belaevski
*/
public class BehaviorsTagHandlerDelegateFactoryImpl extends TagHandlerDelegateFactory {
+ private TagHandlerDelegateFactory factory;
- private TagHandlerDelegateFactory factory;
-
- public BehaviorsTagHandlerDelegateFactoryImpl(TagHandlerDelegateFactory factory) {
- this.factory = factory;
- }
-
- /* (non-Javadoc)
- * @see javax.faces.view.facelets.TagHandlerDelegateFactory#createBehaviorHandlerDelegate(javax.faces.view.facelets.BehaviorHandler)
- */
- @Override
- public TagHandlerDelegate createBehaviorHandlerDelegate(
- BehaviorHandler owner) {
- return factory.createBehaviorHandlerDelegate(owner);
- }
+ public BehaviorsTagHandlerDelegateFactoryImpl(TagHandlerDelegateFactory factory) {
+ this.factory = factory;
+ }
- /* (non-Javadoc)
- * @see javax.faces.view.facelets.TagHandlerDelegateFactory#createComponentHandlerDelegate(javax.faces.view.facelets.ComponentHandler)
- */
- @Override
- public TagHandlerDelegate createComponentHandlerDelegate(ComponentHandler owner) {
- //TagHandlers structure is created when view is compiled
- //so there's no need to check for BehaviorsStack
- return factory.createComponentHandlerDelegate(new BehaviorsAddingComponentHandlerWrapper(owner));
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.view.facelets.TagHandlerDelegateFactory#createBehaviorHandlerDelegate(javax.faces.view.facelets.BehaviorHandler)
+ */
+ @Override
+ public TagHandlerDelegate createBehaviorHandlerDelegate(BehaviorHandler owner) {
+ return factory.createBehaviorHandlerDelegate(owner);
+ }
- /* (non-Javadoc)
- * @see javax.faces.view.facelets.TagHandlerDelegateFactory#createConverterHandlerDelegate(javax.faces.view.facelets.ConverterHandler)
- */
- @Override
- public TagHandlerDelegate createConverterHandlerDelegate(
- ConverterHandler owner) {
- return factory.createConverterHandlerDelegate(owner);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.view.facelets.TagHandlerDelegateFactory#createComponentHandlerDelegate(javax.faces.view.facelets.ComponentHandler)
+ */
+ @Override
+ public TagHandlerDelegate createComponentHandlerDelegate(ComponentHandler owner) {
- /* (non-Javadoc)
- * @see javax.faces.view.facelets.TagHandlerDelegateFactory#createValidatorHandlerDelegate(javax.faces.view.facelets.ValidatorHandler)
- */
- @Override
- public TagHandlerDelegate createValidatorHandlerDelegate(
- ValidatorHandler owner) {
- return factory.createValidatorHandlerDelegate(owner);
- }
+ // TagHandlers structure is created when view is compiled
+ // so there's no need to check for BehaviorsStack
+ return factory.createComponentHandlerDelegate(new BehaviorsAddingComponentHandlerWrapper(owner));
+ }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.view.facelets.TagHandlerDelegateFactory#createConverterHandlerDelegate(javax.faces.view.facelets.ConverterHandler)
+ */
+ @Override
+ public TagHandlerDelegate createConverterHandlerDelegate(ConverterHandler owner) {
+ return factory.createConverterHandlerDelegate(owner);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.view.facelets.TagHandlerDelegateFactory#createValidatorHandlerDelegate(javax.faces.view.facelets.ValidatorHandler)
+ */
+ @Override
+ public TagHandlerDelegate createValidatorHandlerDelegate(ValidatorHandler owner) {
+ return factory.createValidatorHandlerDelegate(owner);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/AjaxBehaviorRenderer.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/AjaxBehaviorRenderer.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/AjaxBehaviorRenderer.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -17,6 +17,7 @@
import org.ajax4jsf.component.AjaxClientBehavior;
import org.ajax4jsf.component.behavior.AjaxBehavior;
import org.ajax4jsf.javascript.JSFunction;
+
import org.richfaces.context.PartialViewContextFactoryImpl;
import org.richfaces.context.PartialViewContextImpl;
@@ -24,83 +25,87 @@
* @author Anton Belevich
*
*/
-@FacesBehaviorRenderer(rendererType="org.ajax4jsf.behavior.Ajax",renderKitId=RenderKitFactory.HTML_BASIC_RENDER_KIT)
-@ResourceDependencies({
- @ResourceDependency(library = "javax.faces", name = "jsf.js"),
- @ResourceDependency(name="jquery.js", target="head"),
- @ResourceDependency(name="richfaces.js", target="head")
-})
+@FacesBehaviorRenderer(rendererType = "org.ajax4jsf.behavior.Ajax",
+ renderKitId = RenderKitFactory.HTML_BASIC_RENDER_KIT)
+@ResourceDependencies({@ResourceDependency(library = "javax.faces", name = "jsf.js") ,
+ @ResourceDependency(name = "jquery.js", target = "head") ,
+ @ResourceDependency(name = "richfaces.js", target = "head") })
public class AjaxBehaviorRenderer extends ClientBehaviorRenderer {
- @Override
- public void decode(FacesContext context, UIComponent component, ClientBehavior behavior) {
-
- if (null == context || null == component || null == behavior) {
+ @Override
+ public void decode(FacesContext context, UIComponent component, ClientBehavior behavior) {
+ if (null == context || null == component || null == behavior) {
throw new NullPointerException();
}
if (!(behavior instanceof AjaxBehavior)) {
- throw new IllegalArgumentException("org.ajax4jsf.component.behavior.AjaxBehavior required: " + behavior);
+ throw new IllegalArgumentException("org.ajax4jsf.component.behavior.AjaxBehavior required: " + behavior);
}
- AjaxBehavior ajaxBehavior = (AjaxBehavior)behavior;
-
+ AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior;
+
if (ajaxBehavior.isDisabled()) {
return;
- }
-
+ }
+
component.queueEvent(createEvent(component, ajaxBehavior));
- }
-
+ }
+
private static AjaxBehaviorEvent createEvent(UIComponent component, AjaxBehavior ajaxBehavior) {
AjaxBehaviorEvent event = new AjaxBehaviorEvent(component, ajaxBehavior);
- PhaseId phaseId = isImmediate(component, ajaxBehavior) ? PhaseId.APPLY_REQUEST_VALUES : PhaseId.INVOKE_APPLICATION;
+ PhaseId phaseId = isImmediate(component, ajaxBehavior)
+ ? PhaseId.APPLY_REQUEST_VALUES : PhaseId.INVOKE_APPLICATION;
+
event.setPhaseId(phaseId);
-
+
return event;
}
-
- private static boolean isImmediate(UIComponent component, AjaxBehavior ajaxBehavior) {
- boolean immediate = false;
- if (ajaxBehavior.isImmediateSet()) {
- immediate = ajaxBehavior.isImmediate();
- } else if (component instanceof EditableValueHolder) {
- immediate = ((EditableValueHolder)component).isImmediate();
- } else if (component instanceof ActionSource) {
- immediate = ((ActionSource)component).isImmediate();
- }
- return immediate;
- }
-
- @Override
- public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) {
- String script = null;
- if(behavior instanceof AjaxBehavior) {
- script = buildAjaxCommand(behaviorContext, (AjaxBehavior)behavior);
- }
- return script;
- }
-
- public String buildAjaxCommand(ClientBehaviorContext bContext, AjaxBehavior behavior) {
- UIComponent parent = bContext.getComponent();
- FacesContext context = bContext.getFacesContext();
-
- JSFunction ajaxFunction = AjaxRendererUtils.buildAjaxFunction(context, parent, AjaxRendererUtils.AJAX_FUNCTION_NAME);
-
- AjaxEventOptions options = buildOptions(context, bContext, behavior);
- ajaxFunction.addParameter(options);
-
- return ajaxFunction.toString();
- }
-
- public AjaxEventOptions buildOptions(FacesContext context, ClientBehaviorContext bContext, AjaxClientBehavior behavior) {
- UIComponent parent = bContext.getComponent();
- String eventName = bContext.getEventName();
- AjaxEventOptions options = AjaxRendererUtils.buildEventOptions(context, parent, behavior);
- options.setParameter(PartialViewContextImpl.BEHAVIOR_EVENT_PARAMETER, eventName);
- options.setParameter(PartialViewContextFactoryImpl.RICHFACES_AJAX, parent.getClientId());
-
- return options;
- }
-
+ private static boolean isImmediate(UIComponent component, AjaxBehavior ajaxBehavior) {
+ boolean immediate = false;
+
+ if (ajaxBehavior.isImmediateSet()) {
+ immediate = ajaxBehavior.isImmediate();
+ } else if (component instanceof EditableValueHolder) {
+ immediate = ((EditableValueHolder) component).isImmediate();
+ } else if (component instanceof ActionSource) {
+ immediate = ((ActionSource) component).isImmediate();
+ }
+
+ return immediate;
+ }
+
+ @Override
+ public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) {
+ String script = null;
+
+ if (behavior instanceof AjaxBehavior) {
+ script = buildAjaxCommand(behaviorContext, (AjaxBehavior) behavior);
+ }
+
+ return script;
+ }
+
+ public String buildAjaxCommand(ClientBehaviorContext bContext, AjaxBehavior behavior) {
+ UIComponent parent = bContext.getComponent();
+ FacesContext context = bContext.getFacesContext();
+ JSFunction ajaxFunction = AjaxRendererUtils.buildAjaxFunction(context, parent,
+ AjaxRendererUtils.AJAX_FUNCTION_NAME);
+ AjaxEventOptions options = buildOptions(context, bContext, behavior);
+
+ ajaxFunction.addParameter(options);
+
+ return ajaxFunction.toString();
+ }
+
+ public AjaxEventOptions buildOptions(FacesContext context, ClientBehaviorContext bContext,
+ AjaxClientBehavior behavior) {
+ UIComponent parent = bContext.getComponent();
+ String eventName = bContext.getEventName();
+ AjaxEventOptions options = AjaxRendererUtils.buildEventOptions(context, parent, behavior);
+
+ options.setParameter(PartialViewContextImpl.BEHAVIOR_EVENT_PARAMETER, eventName);
+ options.setParameter(PartialViewContextFactoryImpl.RICHFACES_AJAX, parent.getClientId());
+
+ return options;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/html/package-info.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/html/package-info.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/html/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -1,3 +1,4 @@
+
/**
* Tag library contains facelets tag handlers that are useful in creating dynamic reusable components
*/
Modified: root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/package-info.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/package-info.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/ajax4jsf/renderkit/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -1,3 +1,4 @@
+
/**
* Fundamental classes and interfaces defining the rendering model
*/
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/PushEventTracker.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/PushEventTracker.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/PushEventTracker.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import java.io.Serializable;
+
import java.util.EventObject;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -33,19 +36,17 @@
*/
public class PushEventTracker implements PushEventListener, Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -4362297582678089326L;
-
- private final AtomicBoolean eventPerformed = new AtomicBoolean(false);
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4362297582678089326L;
+ private final AtomicBoolean eventPerformed = new AtomicBoolean(false);
- public void onEvent(EventObject event) {
- eventPerformed.set(true);
- }
-
- public boolean pollStatus() {
- return eventPerformed.compareAndSet(true, false);
- }
+ public void onEvent(EventObject event) {
+ eventPerformed.set(true);
+ }
+ public boolean pollStatus() {
+ return eventPerformed.compareAndSet(true, false);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/PushListenersManager.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/PushListenersManager.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/PushListenersManager.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import javax.faces.context.FacesContext;
@@ -30,31 +32,31 @@
* @since 4.0
*/
public class PushListenersManager {
+ private static final String CONTEXT_ATTRIBUTE_NAME = "richFacesPushListenersManager";
+ private LRUMap<String, PushEventTracker> listeners;
- private static final String CONTEXT_ATTRIBUTE_NAME = "richFacesPushListenersManager";
-
- private LRUMap<String, PushEventTracker> listeners;
-
- public PushListenersManager() {
- //TODO configure map size
- this.listeners = new LRUMap<String, PushEventTracker>();
- }
-
- public static PushListenersManager getInstance(FacesContext context) {
- return (PushListenersManager) context.getExternalContext().
- getApplicationMap().get(CONTEXT_ATTRIBUTE_NAME);
- }
-
- public PushEventTracker getListener(String name) {
- synchronized (listeners) {
- //LRUMap involves write for each operation, so RWLock is not acceptable here
- PushEventTracker listener = listeners.get(name);
- if (listener == null) {
- listener = new PushEventTracker();
- listeners.put(name, listener);
- }
+ public PushListenersManager() {
- return listener;
- }
- }
+ // TODO configure map size
+ this.listeners = new LRUMap<String, PushEventTracker>();
+ }
+
+ public static PushListenersManager getInstance(FacesContext context) {
+ return (PushListenersManager) context.getExternalContext().getApplicationMap().get(CONTEXT_ATTRIBUTE_NAME);
+ }
+
+ public PushEventTracker getListener(String name) {
+ synchronized (listeners) {
+
+ // LRUMap involves write for each operation, so RWLock is not acceptable here
+ PushEventTracker listener = listeners.get(name);
+
+ if (listener == null) {
+ listener = new PushEventTracker();
+ listeners.put(name, listener);
+ }
+
+ return listener;
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxCommandButton.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxCommandButton.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxCommandButton.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,21 +19,21 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import javax.faces.component.UIComponentBase;
/**
* @author Nick Belaevski
- *
+ *
*/
public class UIAjaxCommandButton extends UIComponentBase {
+ public static final String COMPONENT_FAMILY = "org.richfaces.AjaxCommandButton";
- public static final String COMPONENT_FAMILY = "org.richfaces.AjaxCommandButton";
-
- @Override
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
-
+ @Override
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxCommandLink.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxCommandLink.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxCommandLink.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,21 +19,21 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import javax.faces.component.UIComponentBase;
/**
* @author Nick Belaevski
- *
+ *
*/
public class UIAjaxCommandLink extends UIComponentBase {
+ public static final String COMPONENT_FAMILY = "org.richfaces.AjaxCommandLink";
- public static final String COMPONENT_FAMILY = "org.richfaces.AjaxCommandLink";
-
- @Override
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
-
+ @Override
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxFunction.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxFunction.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxFunction.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import org.ajax4jsf.component.AjaxActionComponent;
@@ -29,10 +31,9 @@
*
*/
public abstract class UIAjaxFunction extends AjaxActionComponent {
+ public static final String COMPONENT_TYPE = "org.richfaces.Function";
- public static final String COMPONENT_TYPE = "org.richfaces.Function";
-
- public abstract String getName();
-
- public abstract void setName(String name);
+ public abstract String getName();
+
+ public abstract void setName(String name);
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxLog.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxLog.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxLog.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import javax.faces.application.ResourceDependencies;
@@ -27,39 +29,36 @@
/**
* @author Nick Belaevski
- *
+ *
*/
@ResourceDependencies(value = {
- @ResourceDependency(name = "jquery.js"),
- @ResourceDependency(name = "richfaces.js"),
- @ResourceDependency(name = "richfaces-jsf-log.js"),
- @ResourceDependency(name = "richfaces.css")
- })
+ @ResourceDependency(name = "jquery.js") , @ResourceDependency(name = "richfaces.js") ,
+ @ResourceDependency(name = "richfaces-jsf-log.js") , @ResourceDependency(name = "richfaces.css")
+ })
public class UIAjaxLog extends UIComponentBase {
+ public static final String COMPONENT_FAMILY = "org.richfaces.AjaxLog";
- public static final String COMPONENT_FAMILY = "org.richfaces.AjaxLog";
+ @Override
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
- @Override
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
-
- // public abstract String getHotkey();
-//
-// public abstract void setHotkey(String newvalue);
+ // public abstract String getHotkey();
+//
+// public abstract void setHotkey(String newvalue);
//
-// public abstract String getName();
-// public abstract void setName(String newvalue);
+// public abstract String getName();
+// public abstract void setName(String newvalue);
//
-// public abstract String getWidth();
-// public abstract void setWidth(String newvalue);
+// public abstract String getWidth();
+// public abstract void setWidth(String newvalue);
//
-// public abstract String getHeight();
-// public abstract void setHeight(String newvalue);
-//
-// public abstract String getLevel();
-// public abstract void setLevel(String newvalue);
-//
-// public abstract boolean isPopup();
-// public abstract void setPopup(boolean popup);
+// public abstract String getHeight();
+// public abstract void setHeight(String newvalue);
+//
+// public abstract String getLevel();
+// public abstract void setLevel(String newvalue);
+//
+// public abstract boolean isPopup();
+// public abstract void setPopup(boolean popup);
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxOutputPanel.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxOutputPanel.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxOutputPanel.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,47 +19,42 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import javax.faces.component.UIPanel;
import org.ajax4jsf.component.AjaxOutput;
-
/**
* @author asmirnov(a)exadel.com (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:26 $
*
*/
public class UIAjaxOutputPanel extends UIPanel implements AjaxOutput {
-
public static final String COMPONENT_TYPE = "org.richfaces.AjaxOutputPanel";
- private static enum PropertyKeys {
- ajaxRendered,
- keepTransient
- };
-
- public UIAjaxOutputPanel() {
- super();
+ private static enum PropertyKeys {ajaxRendered, keepTransient}
+
+ public UIAjaxOutputPanel() {
+ super();
setRendererType("org.richfaces.OutputPanelRenderer");
- }
-
- public boolean isAjaxRendered() {
- return Boolean.valueOf(getStateHelper().eval(PropertyKeys.ajaxRendered, Boolean.FALSE).
- toString());
- }
+ }
- public boolean isKeepTransient() {
- return Boolean.valueOf(getStateHelper().eval(PropertyKeys.keepTransient, Boolean.FALSE).
- toString());
- }
+ public boolean isAjaxRendered() {
+ return Boolean.valueOf(getStateHelper().eval(PropertyKeys.ajaxRendered, Boolean.FALSE).toString());
+ }
- public void setAjaxRendered(boolean ajaxRendered) {
- getStateHelper().put(PropertyKeys.ajaxRendered, ajaxRendered);
- }
+ public boolean isKeepTransient() {
+ return Boolean.valueOf(getStateHelper().eval(PropertyKeys.keepTransient, Boolean.FALSE).toString());
+ }
- public void setKeepTransient(boolean keepTransient) {
- getStateHelper().put(PropertyKeys.keepTransient, keepTransient);
- }
+ public void setAjaxRendered(boolean ajaxRendered) {
+ getStateHelper().put(PropertyKeys.ajaxRendered, ajaxRendered);
+ }
+
+ public void setKeepTransient(boolean keepTransient) {
+ getStateHelper().put(PropertyKeys.keepTransient, keepTransient);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxStatus.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxStatus.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIAjaxStatus.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,19 +19,20 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import javax.faces.component.UIOutput;
/**
* @author Nick Belaevski
- *
+ *
*/
public class UIAjaxStatus extends UIOutput {
+ public static final String COMPONENT_TYPE = "org.richfaces.Status";
- public static final String COMPONENT_TYPE = "org.richfaces.Status";
-
- public static String getComponentType() {
- return COMPONENT_TYPE;
- }
+ public static String getComponentType() {
+ return COMPONENT_TYPE;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIMediaOutput.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIMediaOutput.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIMediaOutput.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import javax.el.MethodExpression;
+
import javax.faces.application.Resource;
import javax.faces.application.ResourceHandler;
import javax.faces.component.UIOutput;
@@ -29,92 +32,96 @@
import javax.faces.el.MethodBinding;
import org.ajax4jsf.resource.ResourceComponent2;
+
import org.richfaces.resource.MediaOutputResource;
import org.richfaces.webapp.taglib.MethodBindingMethodExpressionAdaptor;
import org.richfaces.webapp.taglib.MethodExpressionMethodBindingAdaptor;
-
/**
* @author shura
*
*/
public abstract class UIMediaOutput extends UIOutput implements ResourceComponent2 {
+ public static final String COMPONENT_TYPE = "org.richfaces.MediaOutput";
- public static final String COMPONENT_TYPE = "org.richfaces.MediaOutput";
+ /**
+ * Get URI attribute for resource ( src for images, href for links etc ).
+ * @return
+ */
+ public abstract String getUriAttribute();
- /**
- * Get URI attribute for resource ( src for images, href for links etc ).
- * @return
- */
- public abstract String getUriAttribute();
+ /**
+ * Set URI attribute for resource ( src for images, href for links etc ).
+ * @param newvalue
+ */
+ public abstract void setUriAttribute(String newvalue);
- /**
- * Set URI attribute for resource ( src for images, href for links etc ).
- * @param newvalue
- */
- public abstract void setUriAttribute(String newvalue);
+ /**
+ * Get Element name for rendering ( imj , a , object, applet ).
+ * @return
+ */
+ public abstract String getElement();
- /**
- * Get Element name for rendering ( imj , a , object, applet ).
- * @return
- */
- public abstract String getElement();
+ /**
+ * Set Element name for rendering ( imj , a , object, applet ).
+ * @param newvalue
+ */
+ public abstract void setElement(String newvalue);
- /**
- * Set Element name for rendering ( imj , a , object, applet ).
- * @param newvalue
- */
- public abstract void setElement(String newvalue);
+ /**
+ * Get EL binding to method in user bean to send resource. Method will
+ * called with two parameters - restored data object and servlet output
+ * stream.
+ *
+ * @return MethodBinding to createContent
+ */
+ public MethodBinding getCreateContent() {
+ MethodBinding result = null;
+ MethodExpression me = getCreateContentExpression();
- /**
- * Get EL binding to method in user bean to send resource. Method will
- * called with two parameters - restored data object and servlet output
- * stream.
- *
- * @return MethodBinding to createContent
- */
- public MethodBinding getCreateContent() {
- MethodBinding result = null;
- MethodExpression me = getCreateContentExpression();
+ if (me != null) {
- if (me != null) {
- // if the MethodExpression is an instance of our private
- // wrapper class.
- if (me instanceof MethodExpressionMethodBindingAdaptor) {
- result = ((MethodExpressionMethodBindingAdaptor) me).getBinding();
- } else {
- // otherwise, this is a real MethodExpression. Wrap it
- // in a MethodBinding.
- result = new MethodBindingMethodExpressionAdaptor(me);
- }
- }
+ // if the MethodExpression is an instance of our private
+ // wrapper class.
+ if (me instanceof MethodExpressionMethodBindingAdaptor) {
+ result = ((MethodExpressionMethodBindingAdaptor) me).getBinding();
+ } else {
- return result;
- }
+ // otherwise, this is a real MethodExpression. Wrap it
+ // in a MethodBinding.
+ result = new MethodBindingMethodExpressionAdaptor(me);
+ }
+ }
- /**
- * Set EL binding to method in user bean to send resource. Method will
- * called with two parameters - restored data object and servlet output
- * stream.
- *
- * @param newvalue - new value of createContent method binding
- */
- public void setCreateContent(MethodBinding newvalue) {
- MethodExpressionMethodBindingAdaptor adapter;
- if (newvalue != null) {
- adapter = new MethodExpressionMethodBindingAdaptor(newvalue);
- setCreateContentExpression(adapter);
- } else {
- setCreateContentExpression(null);
- }
- }
+ return result;
+ }
- public Resource getResource() {
- FacesContext facesContext = getFacesContext();
- ResourceHandler resourceHandler = facesContext.getApplication().getResourceHandler();
- MediaOutputResource resource = (MediaOutputResource) resourceHandler.createResource(MediaOutputResource.class.getName());
- resource.initialize(this);
-
- return resource;
- }
+ /**
+ * Set EL binding to method in user bean to send resource. Method will
+ * called with two parameters - restored data object and servlet output
+ * stream.
+ *
+ * @param newvalue - new value of createContent method binding
+ */
+ public void setCreateContent(MethodBinding newvalue) {
+ MethodExpressionMethodBindingAdaptor adapter;
+
+ if (newvalue != null) {
+ adapter = new MethodExpressionMethodBindingAdaptor(newvalue);
+ setCreateContentExpression(adapter);
+ } else {
+ setCreateContentExpression(null);
+ }
+ }
+
+ public Resource getResource() {
+ FacesContext facesContext = getFacesContext();
+ ResourceHandler resourceHandler = facesContext.getApplication().getResourceHandler();
+ MediaOutputResource resource =
+ (MediaOutputResource) resourceHandler.createResource(MediaOutputResource.class.getName());
+
+ resource.initialize(this);
+
+ return resource;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIPush.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIPush.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/UIPush.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,16 +19,20 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component;
import java.io.IOException;
import javax.el.MethodExpression;
+
import javax.faces.component.NamingContainer;
import javax.faces.component.UICommand;
import javax.faces.context.FacesContext;
import javax.faces.event.BehaviorEvent;
import javax.faces.event.FacesEvent;
+
import javax.servlet.http.HttpSession;
/**
@@ -37,93 +41,95 @@
*
*/
public class UIPush extends UICommand {
+ public static final String COMPONENT_FAMILY = "org.richfaces.Push";
+ public static final String COMPONENT_TYPE = "org.richfaces.Push";
+ private transient boolean hasActiveBehavior = false;
- public static final String COMPONENT_TYPE = "org.richfaces.Push";
+ private static enum PropertyKeys {eventProducer, enabled, interval}
- public final static String COMPONENT_FAMILY = "org.richfaces.Push";
+ @Override
+ public void encodeBegin(FacesContext context) throws IOException {
+ MethodExpression producer = getEventProducer();
- private transient boolean hasActiveBehavior = false;
-
- private static enum PropertyKeys {
- eventProducer, enabled, interval
- }
-
- public void encodeBegin(FacesContext context) throws IOException {
- MethodExpression producer = getEventProducer();
- // Subscribe events producer to push status listener.
- if (null != producer) {
- producer.invoke(context.getELContext(), new Object[]{getListener(context)});
- }
-
- super.encodeBegin(context);
- }
+ // Subscribe events producer to push status listener.
+ if (null != producer) {
+ producer.invoke(context.getELContext(), new Object[] {getListener(context)});
+ }
- private PushEventTracker getListener(FacesContext context) {
- PushListenersManager pushListenersManager = PushListenersManager.getInstance(context);
- return pushListenersManager.getListener(getListenerId(context));
- }
+ super.encodeBegin(context);
+ }
- public String getListenerId(FacesContext context){
- Object session = context.getExternalContext().getSession(false);
- StringBuffer id = new StringBuffer();
- if(null != session && session instanceof HttpSession){
- HttpSession httpSession = (HttpSession) session;
- id.append(httpSession.getId());
- }
- id.append(context.getViewRoot().getViewId());
- id.append(NamingContainer.SEPARATOR_CHAR);
- id.append(getClientId(context));
- return id.toString();
- }
+ private PushEventTracker getListener(FacesContext context) {
+ PushListenersManager pushListenersManager = PushListenersManager.getInstance(context);
- public MethodExpression getEventProducer() {
- return (MethodExpression) getStateHelper().get(PropertyKeys.eventProducer);
- }
+ return pushListenersManager.getListener(getListenerId(context));
+ }
- public void setEventProducer(MethodExpression producer) {
- getStateHelper().put(PropertyKeys.eventProducer, producer);
- }
-
- /**
- * @return time in mc for polling interval.
- */
- public int getInterval() {
- return (Integer) getStateHelper().eval(PropertyKeys.interval, 1000);
- }
+ public String getListenerId(FacesContext context) {
+ Object session = context.getExternalContext().getSession(false);
+ StringBuffer id = new StringBuffer();
- /**
- * @param interval time in mc for polling interval.
- */
- public void setInterval(int interval) {
- getStateHelper().put(PropertyKeys.interval, interval);
- }
+ if (null != session && session instanceof HttpSession) {
+ HttpSession httpSession = (HttpSession) session;
- public boolean isEnabled() {
- return Boolean.valueOf(getStateHelper().eval(PropertyKeys.enabled, Boolean.TRUE).toString());
- }
+ id.append(httpSession.getId());
+ }
- public void setEnabled(boolean enable) {
- getStateHelper().put(PropertyKeys.enabled, enable);
- }
+ id.append(context.getViewRoot().getViewId());
+ id.append(NamingContainer.SEPARATOR_CHAR);
+ id.append(getClientId(context));
- @Override
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
+ return id.toString();
+ }
- @Override
- public void queueEvent(FacesEvent e) {
- if (e instanceof BehaviorEvent) {
- hasActiveBehavior = true;
- }
-
- super.queueEvent(e);
- }
-
- /**
- * @return the hasActiveBehavior
- */
- public boolean isHasActiveBehavior() {
- return hasActiveBehavior;
- }
+ public MethodExpression getEventProducer() {
+ return (MethodExpression) getStateHelper().get(PropertyKeys.eventProducer);
+ }
+
+ public void setEventProducer(MethodExpression producer) {
+ getStateHelper().put(PropertyKeys.eventProducer, producer);
+ }
+
+ /**
+ * @return time in mc for polling interval.
+ */
+ public int getInterval() {
+ return (Integer) getStateHelper().eval(PropertyKeys.interval, 1000);
+ }
+
+ /**
+ * @param interval time in mc for polling interval.
+ */
+ public void setInterval(int interval) {
+ getStateHelper().put(PropertyKeys.interval, interval);
+ }
+
+ public boolean isEnabled() {
+ return Boolean.valueOf(getStateHelper().eval(PropertyKeys.enabled, Boolean.TRUE).toString());
+ }
+
+ public void setEnabled(boolean enable) {
+ getStateHelper().put(PropertyKeys.enabled, enable);
+ }
+
+ @Override
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
+
+ @Override
+ public void queueEvent(FacesEvent e) {
+ if (e instanceof BehaviorEvent) {
+ hasActiveBehavior = true;
+ }
+
+ super.queueEvent(e);
+ }
+
+ /**
+ * @return the hasActiveBehavior
+ */
+ public boolean isHasActiveBehavior() {
+ return hasActiveBehavior;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxFunction.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxFunction.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxFunction.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -9,92 +9,88 @@
import javax.faces.component.behavior.ClientBehaviorHolder;
public class HtmlAjaxFunction extends UICommand implements ClientBehaviorHolder {
+ public static final String COMPONENT_FAMILY = "javax.faces.Command";
+ public static final String COMPONENT_TYPE = "org.richfaces.Function";
+ private static final Collection<String> EVENT_NAMES =
+ Collections.unmodifiableCollection(new LinkedHashSet<String>(Arrays.asList("begin", "complete",
+ "beforedomupdate")));
- public final static String COMPONENT_FAMILY = "javax.faces.Command";
+ private static enum PropertyKeys {
+ limitRender, name, onbeforedomupdate, onbegin, oncomplete, execute, render, status
+ }
- public final static String COMPONENT_TYPE = "org.richfaces.Function";
+ public HtmlAjaxFunction() {
+ setRendererType("org.richfaces.FunctionRenderer");
+ }
- private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(
- new LinkedHashSet<String>(Arrays.asList("begin", "complete", "beforedomupdate"))
- );
+ public boolean isLimitRender() {
+ return Boolean.parseBoolean(getStateHelper().eval(PropertyKeys.limitRender, Boolean.FALSE).toString());
+ }
- private static enum PropertyKeys {
- limitRender, name, onbeforedomupdate, onbegin, oncomplete, execute, render, status
- }
-
- public HtmlAjaxFunction() {
- setRendererType("org.richfaces.FunctionRenderer");
- }
-
- public boolean isLimitRender() {
- return Boolean.parseBoolean(getStateHelper().eval(PropertyKeys.limitRender,
- Boolean.FALSE).toString());
- }
-
- public void setLimitRender(boolean limitRenderValue) {
- getStateHelper().put(PropertyKeys.limitRender, limitRenderValue);
- }
-
- public String getName() {
- //TODO required attribute
- return (String) getStateHelper().eval(PropertyKeys.name);
- }
-
- public void setName(String name) {
- getStateHelper().put(PropertyKeys.name, name);
- }
-
- public String getOnbegin() {
- return (String) getStateHelper().eval(PropertyKeys.onbegin);
- }
-
- public void setOnbegin(String onbegin) {
- getStateHelper().put(PropertyKeys.onbegin, onbegin);
- }
-
- public String getOnbeforedomupdate() {
- return (String) getStateHelper().eval(PropertyKeys.onbeforedomupdate);
- }
+ public void setLimitRender(boolean limitRenderValue) {
+ getStateHelper().put(PropertyKeys.limitRender, limitRenderValue);
+ }
- public void setOnbeforedomupdate(String onbeforedomupdate) {
- getStateHelper().put(PropertyKeys.onbeforedomupdate, onbeforedomupdate);
- }
+ public String getName() {
- public String getOncomplete() {
- return (String) getStateHelper().eval(PropertyKeys.oncomplete);
- }
+ // TODO required attribute
+ return (String) getStateHelper().eval(PropertyKeys.name);
+ }
- public void setOncomplete(String oncomplete) {
- getStateHelper().put(PropertyKeys.oncomplete, oncomplete);
- }
+ public void setName(String name) {
+ getStateHelper().put(PropertyKeys.name, name);
+ }
- public Object getExecute() {
- return getStateHelper().eval(PropertyKeys.execute);
- }
-
- public void setExecute(Object execute) {
- getStateHelper().put(PropertyKeys.execute, execute);
- }
-
- public Object getRender() {
- return getStateHelper().eval(PropertyKeys.render);
- }
+ public String getOnbegin() {
+ return (String) getStateHelper().eval(PropertyKeys.onbegin);
+ }
- public void setRender(Object render) {
- getStateHelper().put(PropertyKeys.render, render);
- }
-
- public String getStatus() {
- return (String) getStateHelper().eval(PropertyKeys.status);
- }
+ public void setOnbegin(String onbegin) {
+ getStateHelper().put(PropertyKeys.onbegin, onbegin);
+ }
- public void setStatus(String status) {
- getStateHelper().put(PropertyKeys.status, status);
- }
-
- @Override
- public Collection<String> getEventNames() {
- return EVENT_NAMES;
- }
-
+ public String getOnbeforedomupdate() {
+ return (String) getStateHelper().eval(PropertyKeys.onbeforedomupdate);
+ }
+
+ public void setOnbeforedomupdate(String onbeforedomupdate) {
+ getStateHelper().put(PropertyKeys.onbeforedomupdate, onbeforedomupdate);
+ }
+
+ public String getOncomplete() {
+ return (String) getStateHelper().eval(PropertyKeys.oncomplete);
+ }
+
+ public void setOncomplete(String oncomplete) {
+ getStateHelper().put(PropertyKeys.oncomplete, oncomplete);
+ }
+
+ public Object getExecute() {
+ return getStateHelper().eval(PropertyKeys.execute);
+ }
+
+ public void setExecute(Object execute) {
+ getStateHelper().put(PropertyKeys.execute, execute);
+ }
+
+ public Object getRender() {
+ return getStateHelper().eval(PropertyKeys.render);
+ }
+
+ public void setRender(Object render) {
+ getStateHelper().put(PropertyKeys.render, render);
+ }
+
+ public String getStatus() {
+ return (String) getStateHelper().eval(PropertyKeys.status);
+ }
+
+ public void setStatus(String status) {
+ getStateHelper().put(PropertyKeys.status, status);
+ }
+
+ @Override
+ public Collection<String> getEventNames() {
+ return EVENT_NAMES;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxLog.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxLog.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxLog.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,48 +19,46 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.html;
/**
* @author Konstantin Mishin
- *
+ *
*/
-
import org.richfaces.component.UIAjaxLog;
public class HtmlAjaxLog extends UIAjaxLog {
+ public static final String COMPONENT_TYPE = "org.richfaces.AjaxLog";
- public final static String COMPONENT_TYPE = "org.richfaces.AjaxLog";
+ private static enum PropertyKeys {style, level, styleClass}
- private static enum PropertyKeys {
- style, level, styleClass
- }
+ public HtmlAjaxLog() {
+ setRendererType("org.richfaces.AjaxLogRenderer");
+ }
- public HtmlAjaxLog(){
- setRendererType("org.richfaces.AjaxLogRenderer");
- }
-
- public String getStyle() {
- return (String) getStateHelper().eval(PropertyKeys.style, "");
- }
+ public String getStyle() {
+ return (String) getStateHelper().eval(PropertyKeys.style, "");
+ }
- public void setStyle(String style) {
- getStateHelper().put(PropertyKeys.style, style);
- }
-
- public String getLevel() {
- return (String) getStateHelper().eval(PropertyKeys.level, "");
- }
+ public void setStyle(String style) {
+ getStateHelper().put(PropertyKeys.style, style);
+ }
- public void setLevel(String level) {
- getStateHelper().put(PropertyKeys.level, level);
- }
-
- public String getStyleClass() {
- return (String) getStateHelper().eval(PropertyKeys.styleClass, "");
- }
+ public String getLevel() {
+ return (String) getStateHelper().eval(PropertyKeys.level, "");
+ }
- public void setStyleClass(String styleClass) {
- getStateHelper().put(PropertyKeys.styleClass, styleClass);
- }
+ public void setLevel(String level) {
+ getStateHelper().put(PropertyKeys.level, level);
+ }
+
+ public String getStyleClass() {
+ return (String) getStateHelper().eval(PropertyKeys.styleClass, "");
+ }
+
+ public void setStyleClass(String styleClass) {
+ getStateHelper().put(PropertyKeys.styleClass, styleClass);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxStatus.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxStatus.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlAjaxStatus.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.html;
import java.util.Arrays;
@@ -32,65 +34,61 @@
/**
* @author Nick Belaevski
- *
+ *
*/
public class HtmlAjaxStatus extends UIAjaxStatus implements ClientBehaviorHolder {
+ public static final String COMPONENT_FAMILY = "org.richfaces.Status";
+ public static final String COMPONENT_TYPE = "org.richfaces.Status";
+ private static final Collection<String> EVENT_NAMES =
+ Collections.unmodifiableCollection(new LinkedHashSet<String>(Arrays.asList("start", "stop", "error",
+ "success")));
- public static final String COMPONENT_TYPE = "org.richfaces.Status";
+ private static enum PropertyKeys {
+ onstart, onstop, onerror, onsuccess
+ }
- public static final String COMPONENT_FAMILY = "org.richfaces.Status";
-
- private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(
- new LinkedHashSet<String>(
- Arrays.asList("start", "stop", "error", "success"))
- );
-
- private static enum PropertyKeys {
- onstart, onstop, onerror, onsuccess
- }
-
- public HtmlAjaxStatus() {
- setRendererType("org.richfaces.StatusRenderer");
- }
-
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
-
- @Override
- public Collection<String> getEventNames() {
- return EVENT_NAMES;
- }
-
- public String getOnstart() {
- return (String) getStateHelper().eval(PropertyKeys.onstart);
- }
-
- public void setOnstart(String onstart) {
- getStateHelper().put(PropertyKeys.onstart, onstart);
- }
-
- public String getOnstop() {
- return (String) getStateHelper().eval(PropertyKeys.onstop);
- }
-
- public void setOnstop(String onstop) {
- getStateHelper().put(PropertyKeys.onstop, onstop);
- }
-
- public String getOnerror() {
- return (String) getStateHelper().eval(PropertyKeys.onerror);
- }
-
- public void setOnerror(String onerror) {
- getStateHelper().put(PropertyKeys.onerror, onerror);
- }
-
- public String getOnsuccess() {
- return (String) getStateHelper().eval(PropertyKeys.onsuccess);
- }
+ public HtmlAjaxStatus() {
+ setRendererType("org.richfaces.StatusRenderer");
+ }
- public void setOnsuccess(String onsuccess) {
- getStateHelper().put(PropertyKeys.onsuccess, onsuccess);
- }
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
+
+ @Override
+ public Collection<String> getEventNames() {
+ return EVENT_NAMES;
+ }
+
+ public String getOnstart() {
+ return (String) getStateHelper().eval(PropertyKeys.onstart);
+ }
+
+ public void setOnstart(String onstart) {
+ getStateHelper().put(PropertyKeys.onstart, onstart);
+ }
+
+ public String getOnstop() {
+ return (String) getStateHelper().eval(PropertyKeys.onstop);
+ }
+
+ public void setOnstop(String onstop) {
+ getStateHelper().put(PropertyKeys.onstop, onstop);
+ }
+
+ public String getOnerror() {
+ return (String) getStateHelper().eval(PropertyKeys.onerror);
+ }
+
+ public void setOnerror(String onerror) {
+ getStateHelper().put(PropertyKeys.onerror, onerror);
+ }
+
+ public String getOnsuccess() {
+ return (String) getStateHelper().eval(PropertyKeys.onsuccess);
+ }
+
+ public void setOnsuccess(String onsuccess) {
+ getStateHelper().put(PropertyKeys.onsuccess, onsuccess);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlCommandButton.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlCommandButton.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlCommandButton.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.html;
import java.util.Arrays;
@@ -31,57 +33,50 @@
/**
* @author Konstantin Mishin
- *
+ *
*/
-
public class HtmlCommandButton extends UICommand implements ClientBehaviorHolder {
+ public static final String COMPONENT_TYPE = "org.richfaces.CommandButton";
+ private static final Collection<String> EVENT_NAMES =
+ Collections.unmodifiableCollection(new LinkedHashSet<String>(Arrays.asList("click", "mousemove", "dblclick",
+ "keydown", "keypress", "keyup", "mousedown", "mouseout", "mouseover", "mouseup", "action")));
- public final static String COMPONENT_TYPE = "org.richfaces.CommandButton";
+ private static enum PropertyKeys {style, styleClass, limitRender}
- private static enum PropertyKeys {
- style, styleClass, limitRender
- }
+ public HtmlCommandButton() {
+ setRendererType("org.richfaces.CommandButtonRenderer");
+ }
- private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(
- new LinkedHashSet<String>(
- Arrays.asList("click", "mousemove", "dblclick", "keydown", "keypress",
- "keyup", "mousedown", "mouseout", "mouseover", "mouseup", "action"))
- );
-
- public HtmlCommandButton(){
- setRendererType("org.richfaces.CommandButtonRenderer");
- }
+ public String getStyle() {
+ return (String) getStateHelper().eval(PropertyKeys.style, "");
+ }
- public String getStyle() {
- return (String) getStateHelper().eval(PropertyKeys.style, "");
- }
+ public void setStyle(String style) {
+ getStateHelper().put(PropertyKeys.style, style);
+ }
- public void setStyle(String style) {
- getStateHelper().put(PropertyKeys.style, style);
- }
+ public String getStyleClass() {
+ return (String) getStateHelper().eval(PropertyKeys.styleClass, "");
+ }
- public String getStyleClass() {
- return (String) getStateHelper().eval(PropertyKeys.styleClass, "");
- }
+ public void setStyleClass(String styleClass) {
+ getStateHelper().put(PropertyKeys.styleClass, styleClass);
+ }
- public void setStyleClass(String styleClass) {
- getStateHelper().put(PropertyKeys.styleClass, styleClass);
- }
-
- public boolean isLimitRender() {
- return Boolean.valueOf(getStateHelper().eval(PropertyKeys.limitRender, Boolean.FALSE).toString());
- }
+ public boolean isLimitRender() {
+ return Boolean.valueOf(getStateHelper().eval(PropertyKeys.limitRender, Boolean.FALSE).toString());
+ }
- public void setLimitRender(boolean limitRender) {
- getStateHelper().put(PropertyKeys.limitRender, limitRender);
- }
-
- @Override
- public Collection<String> getEventNames() {
- return EVENT_NAMES;
- }
-
- @Override
+ public void setLimitRender(boolean limitRender) {
+ getStateHelper().put(PropertyKeys.limitRender, limitRender);
+ }
+
+ @Override
+ public Collection<String> getEventNames() {
+ return EVENT_NAMES;
+ }
+
+ @Override
public String getDefaultEventName() {
return "action";
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlCommandLink.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlCommandLink.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlCommandLink.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.html;
import java.util.Arrays;
@@ -31,58 +33,50 @@
/**
* @author Konstantin Mishin
- *
+ *
*/
+public class HtmlCommandLink extends UICommand implements ClientBehaviorHolder {
+ public static final String COMPONENT_TYPE = "org.richfaces.CommandLink";
+ private static final Collection<String> EVENT_NAMES =
+ Collections.unmodifiableCollection(new LinkedHashSet<String>(Arrays.asList("click", "mousemove", "dblclick",
+ "keydown", "keypress", "keyup", "mousedown", "mouseout", "mouseover", "mouseup", "action")));
+ private static enum PropertyKeys {style, styleClass, limitRender}
-public class HtmlCommandLink extends UICommand implements ClientBehaviorHolder {
+ public HtmlCommandLink() {
+ setRendererType("org.richfaces.CommandLinkRenderer");
+ }
- public final static String COMPONENT_TYPE = "org.richfaces.CommandLink";
+ public String getStyle() {
+ return (String) getStateHelper().eval(PropertyKeys.style, "");
+ }
- private static enum PropertyKeys {
- style, styleClass, limitRender
- }
+ public void setStyle(String style) {
+ getStateHelper().put(PropertyKeys.style, style);
+ }
- private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(
- new LinkedHashSet<String>(
- Arrays.asList("click", "mousemove", "dblclick", "keydown", "keypress",
- "keyup", "mousedown", "mouseout", "mouseover", "mouseup", "action"))
- );
-
- public HtmlCommandLink() {
- setRendererType("org.richfaces.CommandLinkRenderer");
- }
+ public String getStyleClass() {
+ return (String) getStateHelper().eval(PropertyKeys.styleClass, "");
+ }
- public String getStyle() {
- return (String) getStateHelper().eval(PropertyKeys.style, "");
- }
+ public void setStyleClass(String styleClass) {
+ getStateHelper().put(PropertyKeys.styleClass, styleClass);
+ }
- public void setStyle(String style) {
- getStateHelper().put(PropertyKeys.style, style);
- }
+ public boolean isLimitRender() {
+ return Boolean.valueOf(getStateHelper().eval(PropertyKeys.limitRender, Boolean.FALSE).toString());
+ }
- public String getStyleClass() {
- return (String) getStateHelper().eval(PropertyKeys.styleClass, "");
- }
+ public void setLimitRender(boolean limitRender) {
+ getStateHelper().put(PropertyKeys.limitRender, limitRender);
+ }
- public void setStyleClass(String styleClass) {
- getStateHelper().put(PropertyKeys.styleClass, styleClass);
- }
-
- public boolean isLimitRender() {
- return Boolean.valueOf(getStateHelper().eval(PropertyKeys.limitRender, Boolean.FALSE).toString());
- }
+ @Override
+ public Collection<String> getEventNames() {
+ return EVENT_NAMES;
+ }
- public void setLimitRender(boolean limitRender) {
- getStateHelper().put(PropertyKeys.limitRender, limitRender);
- }
-
- @Override
- public Collection<String> getEventNames() {
- return EVENT_NAMES;
- }
-
- @Override
+ @Override
public String getDefaultEventName() {
return "action";
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlMediaOutput.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlMediaOutput.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlMediaOutput.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -7,424 +7,417 @@
import java.util.LinkedHashSet;
import javax.el.MethodExpression;
+
import javax.faces.component.behavior.ClientBehaviorHolder;
import org.richfaces.component.UIMediaOutput;
public class HtmlMediaOutput extends UIMediaOutput implements ClientBehaviorHolder {
+ public static final String COMPONENT_FAMILY = "org.richfaces.MediaOutput";
+ public static final String COMPONENT_TYPE = "org.richfaces.MediaOutput";
+ private static final Collection<String> EVENT_NAMES =
+ Collections.unmodifiableCollection(new LinkedHashSet<String>(Arrays.asList("click", "mousemove", "dblclick",
+ "keydown", "keypress", "keyup", "mousedown", "mouseout", "mouseover", "mouseup")));
- static public final String COMPONENT_FAMILY = "org.richfaces.MediaOutput";
+ private static enum PropertyKeys {
+ onblur, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout,
+ onmouseover, onmouseup, rel, rev, type, title, target, tabindex, styleClass, vspace, usemap, shape, standby,
+ style, uriAttribute, accesskey, align, archive, border, element, declare, coords, hreflang, hspace, dir,
+ codetype, codebase, charset, classid, lang, mimeType, lastModified, cacheable, createContentExpression, ismap,
+ session, expires
+ }
- static public final String COMPONENT_TYPE = "org.richfaces.MediaOutput";
+ public HtmlMediaOutput() {
+ setRendererType("org.richfaces.MediaOutputRenderer");
+ }
- private static enum PropertyKeys {
- onblur, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown,
- onmousemove, onmouseout, onmouseover, onmouseup, rel, rev, type, title, target,
- tabindex, styleClass, vspace, usemap, shape, standby, style, uriAttribute, accesskey,
- align, archive, border, element, declare, coords, hreflang, hspace, dir, codetype, codebase,
- charset, classid, lang, mimeType, lastModified, cacheable, createContentExpression, ismap,
- session, expires
- }
+ public String getAccesskey() {
+ return (String) getStateHelper().eval(PropertyKeys.accesskey);
+ }
- private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(
- new LinkedHashSet<String>(
- Arrays.asList("click", "mousemove", "dblclick", "keydown", "keypress",
- "keyup", "mousedown", "mouseout", "mouseover", "mouseup"))
- );
-
- public HtmlMediaOutput() {
- setRendererType("org.richfaces.MediaOutputRenderer");
- }
+ public void setAccesskey(String accesskey) {
+ getStateHelper().put(PropertyKeys.accesskey, accesskey);
+ }
- public String getAccesskey() {
- return (String) getStateHelper().eval(PropertyKeys.accesskey);
- }
+ public String getAlign() {
+ return (String) getStateHelper().eval(PropertyKeys.align);
+ }
- public void setAccesskey(String accesskey) {
- getStateHelper().put(PropertyKeys.accesskey, accesskey);
- }
+ public void setAlign(String align) {
+ getStateHelper().put(PropertyKeys.align, align);
+ }
- public String getAlign() {
- return (String) getStateHelper().eval(PropertyKeys.align);
- }
+ public String getArchive() {
+ return (String) getStateHelper().eval(PropertyKeys.archive);
+ }
- public void setAlign(String align) {
- getStateHelper().put(PropertyKeys.align, align);
- }
+ public void setArchive(String archive) {
+ getStateHelper().put(PropertyKeys.archive, archive);
+ }
- public String getArchive() {
- return (String) getStateHelper().eval(PropertyKeys.archive);
- }
+ public String getBorder() {
+ return (String) getStateHelper().eval(PropertyKeys.border);
+ }
- public void setArchive(String archive) {
- getStateHelper().put(PropertyKeys.archive, archive);
- }
+ public void setBorder(String border) {
+ getStateHelper().put(PropertyKeys.border, border);
+ }
- public String getBorder() {
- return (String) getStateHelper().eval(PropertyKeys.border);
- }
+ public boolean isCacheable() {
+ return Boolean.parseBoolean(getStateHelper().eval(PropertyKeys.cacheable, Boolean.FALSE).toString());
+ }
- public void setBorder(String border) {
- getStateHelper().put(PropertyKeys.border, border);
- }
+ public void setCacheable(boolean cacheable) {
+ getStateHelper().put(PropertyKeys.cacheable, cacheable);
+ }
- public boolean isCacheable() {
- return Boolean.parseBoolean(getStateHelper().eval(PropertyKeys.cacheable,
- Boolean.FALSE).toString());
- }
+ public String getCharset() {
+ return (String) getStateHelper().eval(PropertyKeys.charset);
+ }
- public void setCacheable(boolean cacheable) {
- getStateHelper().put(PropertyKeys.cacheable, cacheable);
- }
+ public void setCharset(String charset) {
+ getStateHelper().put(PropertyKeys.charset, charset);
+ }
- public String getCharset() {
- return (String) getStateHelper().eval(PropertyKeys.charset);
- }
+ public String getClassid() {
+ return (String) getStateHelper().eval(PropertyKeys.classid);
+ }
- public void setCharset(String charset) {
- getStateHelper().put(PropertyKeys.charset, charset);
- }
+ public void setClassid(String classid) {
+ getStateHelper().put(PropertyKeys.classid, classid);
+ }
- public String getClassid() {
- return (String) getStateHelper().eval(PropertyKeys.classid);
- }
+ public String getCodebase() {
+ return (String) getStateHelper().eval(PropertyKeys.codebase);
+ }
- public void setClassid(String classid) {
- getStateHelper().put(PropertyKeys.classid, classid);
- }
+ public void setCodebase(String codebase) {
+ getStateHelper().put(PropertyKeys.codebase, codebase);
+ }
- public String getCodebase() {
- return (String) getStateHelper().eval(PropertyKeys.codebase);
- }
+ public String getCodetype() {
+ return (String) getStateHelper().eval(PropertyKeys.codetype);
+ }
- public void setCodebase(String codebase) {
- getStateHelper().put(PropertyKeys.codebase, codebase);
- }
+ public void setCodetype(String codetype) {
+ getStateHelper().put(PropertyKeys.codetype, codetype);
+ }
- public String getCodetype() {
- return (String) getStateHelper().eval(PropertyKeys.codetype);
- }
+ public String getCoords() {
+ return (String) getStateHelper().eval(PropertyKeys.coords);
+ }
- public void setCodetype(String codetype) {
- getStateHelper().put(PropertyKeys.codetype, codetype);
- }
+ public void setCoords(String coords) {
+ getStateHelper().put(PropertyKeys.coords, coords);
+ }
- public String getCoords() {
- return (String) getStateHelper().eval(PropertyKeys.coords);
- }
+ public MethodExpression getCreateContentExpression() {
+ return (MethodExpression) getStateHelper().get(PropertyKeys.createContentExpression);
+ }
- public void setCoords(String coords) {
- getStateHelper().put(PropertyKeys.coords, coords);
- }
+ public void setCreateContentExpression(MethodExpression createContentExpression) {
+ getStateHelper().put(PropertyKeys.createContentExpression, createContentExpression);
+ }
- public MethodExpression getCreateContentExpression() {
- return (MethodExpression) getStateHelper().get(PropertyKeys.createContentExpression);
- }
+ public String getDeclare() {
+ return (String) getStateHelper().eval(PropertyKeys.declare);
+ }
- public void setCreateContentExpression(
- MethodExpression createContentExpression) {
- getStateHelper().put(PropertyKeys.createContentExpression,
- createContentExpression);
- }
+ public void setDeclare(String declare) {
+ getStateHelper().put(PropertyKeys.declare, declare);
+ }
- public String getDeclare() {
- return (String) getStateHelper().eval(PropertyKeys.declare);
- }
+ public String getDir() {
+ return (String) getStateHelper().eval(PropertyKeys.dir);
+ }
- public void setDeclare(String declare) {
- getStateHelper().put(PropertyKeys.declare, declare);
- }
+ public void setDir(String dir) {
+ getStateHelper().put(PropertyKeys.dir, dir);
+ }
- public String getDir() {
- return (String) getStateHelper().eval(PropertyKeys.dir);
- }
+ public String getElement() {
+ return (String) getStateHelper().eval(PropertyKeys.element);
+ }
- public void setDir(String dir) {
- getStateHelper().put(PropertyKeys.dir, dir);
- }
+ public void setElement(String element) {
+ getStateHelper().put(PropertyKeys.element, element);
+ }
- public String getElement() {
- return (String) getStateHelper().eval(PropertyKeys.element);
- }
+ public Date getExpires() {
+ return (Date) getStateHelper().eval(PropertyKeys.expires);
+ }
- public void setElement(String element) {
- getStateHelper().put(PropertyKeys.element, element);
- }
+ public void setExpires(Date expires) {
+ getStateHelper().put(PropertyKeys.expires, expires);
+ }
- public Date getExpires() {
- return (Date) getStateHelper().eval(PropertyKeys.expires);
- }
+ public String getHreflang() {
+ return (String) getStateHelper().eval(PropertyKeys.hreflang);
+ }
- public void setExpires(Date expires) {
- getStateHelper().put(PropertyKeys.expires, expires);
- }
+ public void setHreflang(String hreflang) {
+ getStateHelper().put(PropertyKeys.hreflang, hreflang);
+ }
- public String getHreflang() {
- return (String) getStateHelper().eval(PropertyKeys.hreflang);
- }
+ public String getHspace() {
+ return (String) getStateHelper().eval(PropertyKeys.hspace);
+ }
- public void setHreflang(String hreflang) {
- getStateHelper().put(PropertyKeys.hreflang, hreflang);
- }
+ public void setHspace(String hspace) {
+ getStateHelper().put(PropertyKeys.hspace, hspace);
+ }
- public String getHspace() {
- return (String) getStateHelper().eval(PropertyKeys.hspace);
- }
+ public boolean isIsmap() {
+ return Boolean.parseBoolean(getStateHelper().eval(PropertyKeys.ismap, Boolean.FALSE).toString());
+ }
- public void setHspace(String hspace) {
- getStateHelper().put(PropertyKeys.hspace, hspace);
- }
+ public void setIsmap(boolean ismap) {
+ getStateHelper().put(PropertyKeys.ismap, ismap);
+ }
- public boolean isIsmap() {
- return Boolean.parseBoolean(getStateHelper().eval(PropertyKeys.ismap, Boolean.FALSE).toString());
- }
+ public String getLang() {
+ return (String) getStateHelper().eval(PropertyKeys.lang);
+ }
- public void setIsmap(boolean ismap) {
- getStateHelper().put(PropertyKeys.ismap, ismap);
- }
+ public void setLang(String lang) {
+ getStateHelper().put(PropertyKeys.lang, lang);
+ }
- public String getLang() {
- return (String) getStateHelper().eval(PropertyKeys.lang);
- }
+ public Date getLastModified() {
+ return (Date) getStateHelper().eval(PropertyKeys.lastModified);
+ }
- public void setLang(String lang) {
- getStateHelper().put(PropertyKeys.lang, lang);
- }
+ public void setLastModified(Date lastModified) {
+ getStateHelper().put(PropertyKeys.lastModified, lastModified);
+ }
- public Date getLastModified() {
- return (Date) getStateHelper().eval(PropertyKeys.lastModified);
- }
+ public String getMimeType() {
+ return (String) getStateHelper().eval(PropertyKeys.mimeType);
+ }
- public void setLastModified(Date lastModified) {
- getStateHelper().put(PropertyKeys.lastModified, lastModified);
- }
+ public void setMimeType(String mimeType) {
+ getStateHelper().put(PropertyKeys.mimeType, mimeType);
+ }
- public String getMimeType() {
- return (String) getStateHelper().eval(PropertyKeys.mimeType);
- }
+ public String getOnblur() {
+ return (String) getStateHelper().eval(PropertyKeys.onblur);
+ }
- public void setMimeType(String mimeType) {
- getStateHelper().put(PropertyKeys.mimeType, mimeType);
- }
+ public void setOnblur(String onblur) {
+ getStateHelper().put(PropertyKeys.onblur, onblur);
+ }
- public String getOnblur() {
- return (String) getStateHelper().eval(PropertyKeys.onblur);
- }
+ public String getOnclick() {
+ return (String) getStateHelper().eval(PropertyKeys.onclick);
+ }
- public void setOnblur(String onblur) {
- getStateHelper().put(PropertyKeys.onblur, onblur);
- }
+ public void setOnclick(String onclick) {
+ getStateHelper().put(PropertyKeys.onclick, onclick);
+ }
- public String getOnclick() {
- return (String) getStateHelper().eval(PropertyKeys.onclick);
- }
+ public String getOndblclick() {
+ return (String) getStateHelper().eval(PropertyKeys.ondblclick);
+ }
- public void setOnclick(String onclick) {
- getStateHelper().put(PropertyKeys.onclick, onclick);
- }
+ public void setOndblclick(String ondblclick) {
+ getStateHelper().put(PropertyKeys.ondblclick, ondblclick);
+ }
- public String getOndblclick() {
- return (String) getStateHelper().eval(PropertyKeys.ondblclick);
- }
+ public String getOnfocus() {
+ return (String) getStateHelper().eval(PropertyKeys.onfocus);
+ }
- public void setOndblclick(String ondblclick) {
- getStateHelper().put(PropertyKeys.ondblclick, ondblclick);
- }
+ public void setOnfocus(String onfocus) {
+ getStateHelper().put(PropertyKeys.onfocus, onfocus);
+ }
- public String getOnfocus() {
- return (String) getStateHelper().eval(PropertyKeys.onfocus);
- }
+ public String getOnkeydown() {
+ return (String) getStateHelper().eval(PropertyKeys.onkeydown);
+ }
- public void setOnfocus(String onfocus) {
- getStateHelper().put(PropertyKeys.onfocus, onfocus);
- }
+ public void setOnkeydown(String onkeydown) {
+ getStateHelper().put(PropertyKeys.onkeydown, onkeydown);
+ }
- public String getOnkeydown() {
- return (String) getStateHelper().eval(PropertyKeys.onkeydown);
- }
+ public String getOnkeypress() {
+ return (String) getStateHelper().eval(PropertyKeys.onkeypress);
+ }
- public void setOnkeydown(String onkeydown) {
- getStateHelper().put(PropertyKeys.onkeydown, onkeydown);
- }
+ public void setOnkeypress(String onkeypress) {
+ getStateHelper().put(PropertyKeys.onkeypress, onkeypress);
+ }
- public String getOnkeypress() {
- return (String) getStateHelper().eval(PropertyKeys.onkeypress);
- }
+ public String getOnkeyup() {
+ return (String) getStateHelper().eval(PropertyKeys.onkeyup);
+ }
- public void setOnkeypress(String onkeypress) {
- getStateHelper().put(PropertyKeys.onkeypress, onkeypress);
- }
+ public void setOnkeyup(String onkeyup) {
+ getStateHelper().put(PropertyKeys.onkeyup, onkeyup);
+ }
- public String getOnkeyup() {
- return (String) getStateHelper().eval(PropertyKeys.onkeyup);
- }
+ public String getOnmousedown() {
+ return (String) getStateHelper().eval(PropertyKeys.onmousedown);
+ }
- public void setOnkeyup(String onkeyup) {
- getStateHelper().put(PropertyKeys.onkeyup, onkeyup);
- }
+ public void setOnmousedown(String onmousedown) {
+ getStateHelper().put(PropertyKeys.onmousedown, onmousedown);
+ }
- public String getOnmousedown() {
- return (String) getStateHelper().eval(PropertyKeys.onmousedown);
- }
+ public String getOnmousemove() {
+ return (String) getStateHelper().eval(PropertyKeys.onmousemove);
+ }
- public void setOnmousedown(String onmousedown) {
- getStateHelper().put(PropertyKeys.onmousedown, onmousedown);
- }
+ public void setOnmousemove(String onmousemove) {
+ getStateHelper().put(PropertyKeys.onmousemove, onmousemove);
+ }
- public String getOnmousemove() {
- return (String) getStateHelper().eval(PropertyKeys.onmousemove);
- }
+ public String getOnmouseout() {
+ return (String) getStateHelper().eval(PropertyKeys.onmouseout);
+ }
- public void setOnmousemove(String onmousemove) {
- getStateHelper().put(PropertyKeys.onmousemove, onmousemove);
- }
+ public void setOnmouseout(String onmouseout) {
+ getStateHelper().put(PropertyKeys.onmouseout, onmouseout);
+ }
- public String getOnmouseout() {
- return (String) getStateHelper().eval(PropertyKeys.onmouseout);
- }
+ public String getOnmouseover() {
+ return (String) getStateHelper().eval(PropertyKeys.onmouseover);
+ }
- public void setOnmouseout(String onmouseout) {
- getStateHelper().put(PropertyKeys.onmouseout, onmouseout);
- }
+ public void setOnmouseover(String onmouseover) {
+ getStateHelper().put(PropertyKeys.onmouseover, onmouseover);
+ }
- public String getOnmouseover() {
- return (String) getStateHelper().eval(PropertyKeys.onmouseover);
- }
+ public String getOnmouseup() {
+ return (String) getStateHelper().eval(PropertyKeys.onmouseup);
+ }
- public void setOnmouseover(String onmouseover) {
- getStateHelper().put(PropertyKeys.onmouseover, onmouseover);
- }
+ public void setOnmouseup(String onmouseup) {
+ getStateHelper().put(PropertyKeys.onmouseup, onmouseup);
+ }
- public String getOnmouseup() {
- return (String) getStateHelper().eval(PropertyKeys.onmouseup);
- }
+ public String getRel() {
+ return (String) getStateHelper().eval(PropertyKeys.rel);
+ }
- public void setOnmouseup(String onmouseup) {
- getStateHelper().put(PropertyKeys.onmouseup, onmouseup);
- }
+ public void setRel(String rel) {
+ getStateHelper().put(PropertyKeys.rel, rel);
+ }
- public String getRel() {
- return (String) getStateHelper().eval(PropertyKeys.rel);
- }
+ public String getRev() {
+ return (String) getStateHelper().eval(PropertyKeys.rev);
+ }
- public void setRel(String rel) {
- getStateHelper().put(PropertyKeys.rel, rel);
- }
+ public void setRev(String rev) {
+ getStateHelper().put(PropertyKeys.rev, rev);
+ }
- public String getRev() {
- return (String) getStateHelper().eval(PropertyKeys.rev);
- }
+ @Deprecated
+ public boolean isSession() {
+ return true;
+ }
- public void setRev(String rev) {
- getStateHelper().put(PropertyKeys.rev, rev);
- }
+ @Deprecated
+ public void setSession(boolean session) {
+ if (!session) {
- @Deprecated
- public boolean isSession() {
- return true;
- }
+ // TODO: log
+ }
+ }
- @Deprecated
- public void setSession(boolean session) {
- if (!session) {
- //TODO: log
- }
- }
+ public String getShape() {
+ return (String) getStateHelper().eval(PropertyKeys.shape);
+ }
- public String getShape() {
- return (String) getStateHelper().eval(PropertyKeys.shape);
- }
+ public void setShape(String shape) {
+ getStateHelper().put(PropertyKeys.shape, shape);
+ }
- public void setShape(String shape) {
- getStateHelper().put(PropertyKeys.shape, shape);
- }
+ public String getStandby() {
+ return (String) getStateHelper().eval(PropertyKeys.standby);
+ }
- public String getStandby() {
- return (String) getStateHelper().eval(PropertyKeys.standby);
- }
+ public void setStandby(String standby) {
+ getStateHelper().put(PropertyKeys.standby, standby);
+ }
- public void setStandby(String standby) {
- getStateHelper().put(PropertyKeys.standby, standby);
- }
+ public String getStyle() {
+ return (String) getStateHelper().eval(PropertyKeys.style);
+ }
- public String getStyle() {
- return (String) getStateHelper().eval(PropertyKeys.style);
- }
+ public void setStyle(String style) {
+ getStateHelper().put(PropertyKeys.style, style);
+ }
- public void setStyle(String style) {
- getStateHelper().put(PropertyKeys.style, style);
- }
+ public String getStyleClass() {
+ return (String) getStateHelper().eval(PropertyKeys.styleClass);
+ }
- public String getStyleClass() {
- return (String) getStateHelper().eval(PropertyKeys.styleClass);
- }
+ public void setStyleClass(String styleClass) {
+ getStateHelper().put(PropertyKeys.styleClass, styleClass);
+ }
- public void setStyleClass(String styleClass) {
- getStateHelper().put(PropertyKeys.styleClass, styleClass);
- }
+ public String getTabindex() {
+ return (String) getStateHelper().eval(PropertyKeys.tabindex);
+ }
- public String getTabindex() {
- return (String) getStateHelper().eval(PropertyKeys.tabindex);
- }
+ public void setTabindex(String tabindex) {
+ getStateHelper().put(PropertyKeys.tabindex, tabindex);
+ }
- public void setTabindex(String tabindex) {
- getStateHelper().put(PropertyKeys.tabindex, tabindex);
- }
+ public String getTarget() {
+ return (String) getStateHelper().eval(PropertyKeys.target);
+ }
- public String getTarget() {
- return (String) getStateHelper().eval(PropertyKeys.target);
- }
+ public void setTarget(String target) {
+ getStateHelper().put(PropertyKeys.target, target);
+ }
- public void setTarget(String target) {
- getStateHelper().put(PropertyKeys.target, target);
- }
+ public String getTitle() {
+ return (String) getStateHelper().eval(PropertyKeys.title);
+ }
- public String getTitle() {
- return (String) getStateHelper().eval(PropertyKeys.title);
- }
+ public void setTitle(String title) {
+ getStateHelper().put(PropertyKeys.title, title);
+ }
- public void setTitle(String title) {
- getStateHelper().put(PropertyKeys.title, title);
- }
+ public String getType() {
+ return (String) getStateHelper().eval(PropertyKeys.type);
+ }
- public String getType() {
- return (String) getStateHelper().eval(PropertyKeys.type);
- }
+ public void setType(String type) {
+ getStateHelper().put(PropertyKeys.type, type);
+ }
- public void setType(String type) {
- getStateHelper().put(PropertyKeys.type, type);
- }
+ public String getUriAttribute() {
+ return (String) getStateHelper().eval(PropertyKeys.uriAttribute);
+ }
- public String getUriAttribute() {
- return (String) getStateHelper().eval(PropertyKeys.uriAttribute);
- }
+ public void setUriAttribute(String uriAttribute) {
+ getStateHelper().put(PropertyKeys.uriAttribute, uriAttribute);
+ }
- public void setUriAttribute(String uriAttribute) {
- getStateHelper().put(PropertyKeys.uriAttribute, uriAttribute);
- }
+ public String getUsemap() {
+ return (String) getStateHelper().eval(PropertyKeys.usemap);
+ }
- public String getUsemap() {
- return (String) getStateHelper().eval(PropertyKeys.usemap);
- }
+ public void setUsemap(String usemap) {
+ getStateHelper().put(PropertyKeys.usemap, usemap);
+ }
- public void setUsemap(String usemap) {
- getStateHelper().put(PropertyKeys.usemap, usemap);
- }
+ public String getVspace() {
+ return (String) getStateHelper().eval(PropertyKeys.vspace);
+ }
- public String getVspace() {
- return (String) getStateHelper().eval(PropertyKeys.vspace);
- }
+ public void setVspace(String vspace) {
+ getStateHelper().put(PropertyKeys.vspace, vspace);
+ }
- public void setVspace(String vspace) {
- getStateHelper().put(PropertyKeys.vspace, vspace);
- }
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
-
- @Override
- public Collection<String> getEventNames() {
- return EVENT_NAMES;
- }
+ @Override
+ public Collection<String> getEventNames() {
+ return EVENT_NAMES;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlOutputPanel.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlOutputPanel.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlOutputPanel.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -10,161 +10,157 @@
import org.richfaces.component.UIAjaxOutputPanel;
public class HtmlOutputPanel extends UIAjaxOutputPanel implements ClientBehaviorHolder {
+ public static final String COMPONENT_FAMILY = "javax.faces.Panel";
+ public static final String COMPONENT_TYPE = "org.richfaces.OutputPanel";
+ private static final Collection<String> EVENT_NAMES =
+ Collections.unmodifiableCollection(new LinkedHashSet<String>(Arrays.asList("click", "mousemove", "dblclick",
+ "keydown", "keypress", "keyup", "mousedown", "mouseout", "mouseover", "mouseup")));
- static final public String COMPONENT_FAMILY = "javax.faces.Panel";
+ private static enum PropertyKeys {
+ dir, lang, layout, onclick, onmousemove, ondblclick, onkeydown, onkeypress, onkeyup, onmousedown, title, style,
+ onmouseout, onmouseover, onmouseup, styleClass
+ }
- static final public String COMPONENT_TYPE = "org.richfaces.OutputPanel";
+ public HtmlOutputPanel() {
+ super();
+ setRendererType("org.richfaces.OutputPanelRenderer");
+ }
- private static enum PropertyKeys {
- dir, lang, layout, onclick, onmousemove, ondblclick, onkeydown, onkeypress,
- onkeyup, onmousedown, title, style, onmouseout, onmouseover, onmouseup, styleClass
- }
+ public String getDir() {
+ return (String) getStateHelper().eval(PropertyKeys.dir);
+ }
- private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(
- new LinkedHashSet<String>(
- Arrays.asList("click", "mousemove", "dblclick", "keydown", "keypress",
- "keyup", "mousedown", "mouseout", "mouseover", "mouseup"))
- );
-
- public HtmlOutputPanel() {
- super();
- setRendererType("org.richfaces.OutputPanelRenderer");
- }
+ public void setDir(String dir) {
+ getStateHelper().put(PropertyKeys.dir, dir);
+ }
- public String getDir() {
- return (String) getStateHelper().eval(PropertyKeys.dir);
- }
+ public String getLang() {
+ return (String) getStateHelper().eval(PropertyKeys.lang);
+ }
- public void setDir(String dir) {
- getStateHelper().put(PropertyKeys.dir, dir);
- }
+ public void setLang(String lang) {
+ getStateHelper().put(PropertyKeys.lang, lang);
+ }
- public String getLang() {
- return (String) getStateHelper().eval(PropertyKeys.lang);
- }
+ public String getLayout() {
+ return (String) getStateHelper().eval(PropertyKeys.layout, "inline");
+ }
- public void setLang(String lang) {
- getStateHelper().put(PropertyKeys.lang, lang);
- }
+ public void setLayout(String layout) {
+ getStateHelper().put(PropertyKeys.layout, layout);
+ }
- public String getLayout() {
- return (String) getStateHelper().eval(PropertyKeys.layout, "inline");
- }
+ public String getOnclick() {
+ return (String) getStateHelper().eval(PropertyKeys.onclick);
+ }
- public void setLayout(String layout) {
- getStateHelper().put(PropertyKeys.layout, layout);
- }
+ public void setOnclick(String onclick) {
+ getStateHelper().put(PropertyKeys.onclick, onclick);
+ }
- public String getOnclick() {
- return (String) getStateHelper().eval(PropertyKeys.onclick);
- }
+ public String getOndblclick() {
+ return (String) getStateHelper().eval(PropertyKeys.ondblclick);
+ }
- public void setOnclick(String onclick) {
- getStateHelper().put(PropertyKeys.onclick, onclick);
- }
+ public void setOndblclick(String ondblclick) {
+ getStateHelper().put(PropertyKeys.ondblclick, ondblclick);
+ }
- public String getOndblclick() {
- return (String) getStateHelper().eval(PropertyKeys.ondblclick);
- }
+ public String getOnkeydown() {
+ return (String) getStateHelper().eval(PropertyKeys.onkeydown);
+ }
- public void setOndblclick(String ondblclick) {
- getStateHelper().put(PropertyKeys.ondblclick, ondblclick);
- }
+ public void setOnkeydown(String onkeydown) {
+ getStateHelper().put(PropertyKeys.onkeydown, onkeydown);
+ }
- public String getOnkeydown() {
- return (String) getStateHelper().eval(PropertyKeys.onkeydown);
- }
+ public String getOnkeypress() {
+ return (String) getStateHelper().eval(PropertyKeys.onkeypress);
+ }
- public void setOnkeydown(String onkeydown) {
- getStateHelper().put(PropertyKeys.onkeydown, onkeydown);
- }
+ public void setOnkeypress(String onkeypress) {
+ getStateHelper().put(PropertyKeys.onkeypress, onkeypress);
+ }
- public String getOnkeypress() {
- return (String) getStateHelper().eval(PropertyKeys.onkeypress);
- }
+ public String getOnkeyup() {
+ return (String) getStateHelper().eval(PropertyKeys.onkeyup);
+ }
- public void setOnkeypress(String onkeypress) {
- getStateHelper().put(PropertyKeys.onkeypress, onkeypress);
- }
+ public void setOnkeyup(String onkeyup) {
+ getStateHelper().put(PropertyKeys.onkeyup, onkeyup);
+ }
- public String getOnkeyup() {
- return (String) getStateHelper().eval(PropertyKeys.onkeyup);
- }
+ public String getOnmousedown() {
+ return (String) getStateHelper().eval(PropertyKeys.onmousedown);
+ }
- public void setOnkeyup(String onkeyup) {
- getStateHelper().put(PropertyKeys.onkeyup, onkeyup);
- }
+ public void setOnmousedown(String onmousedown) {
+ getStateHelper().put(PropertyKeys.onmousedown, onmousedown);
+ }
- public String getOnmousedown() {
- return (String) getStateHelper().eval(PropertyKeys.onmousedown);
- }
+ public String getOnmousemove() {
+ return (String) getStateHelper().eval(PropertyKeys.onmousemove);
+ }
- public void setOnmousedown(String onmousedown) {
- getStateHelper().put(PropertyKeys.onmousedown, onmousedown);
- }
+ public void setOnmousemove(String onmousemove) {
+ getStateHelper().put(PropertyKeys.onmousemove, onmousemove);
+ }
- public String getOnmousemove() {
- return (String) getStateHelper().eval(PropertyKeys.onmousemove);
- }
+ public String getOnmouseout() {
+ return (String) getStateHelper().eval(PropertyKeys.onmouseout);
+ }
- public void setOnmousemove(String onmousemove) {
- getStateHelper().put(PropertyKeys.onmousemove, onmousemove);
- }
+ public void setOnmouseout(String onmouseout) {
+ getStateHelper().put(PropertyKeys.onmouseout, onmouseout);
+ }
- public String getOnmouseout() {
- return (String) getStateHelper().eval(PropertyKeys.onmouseout);
- }
+ public String getOnmouseover() {
+ return (String) getStateHelper().eval(PropertyKeys.onmouseover);
+ }
- public void setOnmouseout(String onmouseout) {
- getStateHelper().put(PropertyKeys.onmouseout, onmouseout);
- }
+ public void setOnmouseover(String onmouseover) {
+ getStateHelper().put(PropertyKeys.onmouseover, onmouseover);
+ }
- public String getOnmouseover() {
- return (String) getStateHelper().eval(PropertyKeys.onmouseover);
- }
+ public String getOnmouseup() {
+ return (String) getStateHelper().eval(PropertyKeys.onmouseup);
+ }
- public void setOnmouseover(String onmouseover) {
- getStateHelper().put(PropertyKeys.onmouseover, onmouseover);
- }
+ public void setOnmouseup(String onmouseup) {
+ getStateHelper().put(PropertyKeys.onmouseup, onmouseup);
+ }
- public String getOnmouseup() {
- return (String) getStateHelper().eval(PropertyKeys.onmouseup);
- }
+ public String getStyle() {
+ return (String) getStateHelper().eval(PropertyKeys.style);
+ }
- public void setOnmouseup(String onmouseup) {
- getStateHelper().put(PropertyKeys.onmouseup, onmouseup);
- }
+ public void setStyle(String style) {
+ getStateHelper().put(PropertyKeys.style, style);
+ }
- public String getStyle() {
- return (String) getStateHelper().eval(PropertyKeys.style);
- }
+ public String getStyleClass() {
+ return (String) getStateHelper().eval(PropertyKeys.styleClass);
+ }
- public void setStyle(String style) {
- getStateHelper().put(PropertyKeys.style, style);
- }
+ public void setStyleClass(String styleClass) {
+ getStateHelper().put(PropertyKeys.styleClass, styleClass);
+ }
- public String getStyleClass() {
- return (String) getStateHelper().eval(PropertyKeys.styleClass);
- }
+ public String getTitle() {
+ return (String) getStateHelper().eval(PropertyKeys.title);
+ }
- public void setStyleClass(String styleClass) {
- getStateHelper().put(PropertyKeys.styleClass, styleClass);
- }
+ public void setTitle(String title) {
+ getStateHelper().put(PropertyKeys.title, title);
+ }
- public String getTitle() {
- return (String) getStateHelper().eval(PropertyKeys.title);
- }
+ @Override
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
- public void setTitle(String title) {
- getStateHelper().put(PropertyKeys.title, title);
- }
-
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
-
- @Override
- public Collection<String> getEventNames() {
- return EVENT_NAMES;
- }
+ @Override
+ public Collection<String> getEventNames() {
+ return EVENT_NAMES;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlPush.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlPush.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/html/HtmlPush.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,13 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.component.html;
/**
* @author Nick Belaevski
- *
+ *
*/
-
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -36,69 +37,66 @@
import org.richfaces.component.UIPush;
public class HtmlPush extends UIPush implements ClientBehaviorHolder {
+ public static final String COMPONENT_FAMILY = "org.richfaces.Push";
+ public static final String COMPONENT_TYPE = "org.richfaces.Push";
+ public static final String DATA_AVAILABLE = "dataAvailable";
+ public static final String ON_DATA_AVAILABLE = "ondataavailable";
+ private static final Collection<String> EVENT_NAMES =
+ Collections.unmodifiableCollection(new LinkedHashSet<String>(Arrays.asList(DATA_AVAILABLE, "begin",
+ "beforedomupdate", "complete")));
- public final static String COMPONENT_FAMILY = "org.richfaces.Push";
+ private static enum PropertyKeys {
+ ondataavailable, onbegin, onbeforedomupdate, oncomplete
+ }
- public final static String COMPONENT_TYPE = "org.richfaces.Push";
+ public HtmlPush() {
+ setRendererType("org.richfaces.PushRenderer");
+ }
- public static final String ON_DATA_AVAILABLE = "ondataavailable";
+ @Override
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
- public static final String DATA_AVAILABLE = "dataAvailable";
+ @Override
+ public String getDefaultEventName() {
+ return DATA_AVAILABLE;
+ }
- private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(
- new LinkedHashSet<String>(Arrays.asList(DATA_AVAILABLE, "begin", "beforedomupdate", "complete")));
+ @Override
+ public Collection<String> getEventNames() {
+ return EVENT_NAMES;
+ }
- private static enum PropertyKeys {
- ondataavailable, onbegin, onbeforedomupdate, oncomplete
- }
-
- public HtmlPush(){
- setRendererType("org.richfaces.PushRenderer");
- }
+ public String getOndataavailable() {
+ return (String) getStateHelper().eval(PropertyKeys.ondataavailable);
+ }
- public String getFamily(){
- return COMPONENT_FAMILY;
- }
+ public void setOndataavailable(String ondataavailable) {
+ getStateHelper().put(PropertyKeys.ondataavailable, ondataavailable);
+ }
- @Override
- public String getDefaultEventName() {
- return DATA_AVAILABLE;
- }
+ public String getOnbegin() {
+ return (String) getStateHelper().eval(PropertyKeys.onbegin);
+ }
- @Override
- public Collection<String> getEventNames() {
- return EVENT_NAMES;
- }
+ public void setOnbegin(String onbegin) {
+ getStateHelper().put(PropertyKeys.onbegin, onbegin);
+ }
- public String getOndataavailable() {
- return (String) getStateHelper().eval(PropertyKeys.ondataavailable);
- }
-
- public void setOndataavailable(String ondataavailable) {
- getStateHelper().put(PropertyKeys.ondataavailable, ondataavailable);
- }
-
- public String getOnbegin() {
- return (String) getStateHelper().eval(PropertyKeys.onbegin);
- }
-
- public void setOnbegin(String onbegin) {
- getStateHelper().put(PropertyKeys.onbegin, onbegin);
- }
-
- public String getOnbeforedomupdate() {
- return (String) getStateHelper().eval(PropertyKeys.onbeforedomupdate);
- }
-
- public void setOnbeforedomupdate(String onbeforedomupdate) {
- getStateHelper().put(PropertyKeys.onbeforedomupdate, onbeforedomupdate);
- }
-
- public String getOncomplete() {
- return (String) getStateHelper().eval(PropertyKeys.oncomplete);
- }
-
- public void setOncomplete(String oncomplete) {
- getStateHelper().put(PropertyKeys.oncomplete, oncomplete);
- }
+ public String getOnbeforedomupdate() {
+ return (String) getStateHelper().eval(PropertyKeys.onbeforedomupdate);
+ }
+
+ public void setOnbeforedomupdate(String onbeforedomupdate) {
+ getStateHelper().put(PropertyKeys.onbeforedomupdate, onbeforedomupdate);
+ }
+
+ public String getOncomplete() {
+ return (String) getStateHelper().eval(PropertyKeys.oncomplete);
+ }
+
+ public void setOncomplete(String oncomplete) {
+ getStateHelper().put(PropertyKeys.oncomplete, oncomplete);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/component/package-info.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/component/package-info.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/component/package-info.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -1,3 +1,4 @@
+
/**
* Fundamental APIs for user interface components
*/
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxCommandRendererBase.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxCommandRendererBase.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxCommandRendererBase.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import static org.ajax4jsf.renderkit.AjaxRendererUtils.AJAX_FUNCTION_NAME;
@@ -37,118 +39,125 @@
import org.ajax4jsf.renderkit.AjaxEventOptions;
import org.ajax4jsf.renderkit.HandlersChain;
import org.ajax4jsf.renderkit.RendererBase;
+
import org.richfaces.log.RichfacesLogger;
+
import org.slf4j.Logger;
/**
* @author asmirnov(a)exadel.com (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.3 $ $Date: 2007/02/12 17:46:53 $
- *
+ *
*/
-@ResourceDependencies({
- @ResourceDependency(library = "javax.faces", name = "jsf.js"),
- @ResourceDependency(name = "jquery.js"),
- @ResourceDependency(name = "richfaces.js")
-})
+@ResourceDependencies({@ResourceDependency(library = "javax.faces", name = "jsf.js") ,
+ @ResourceDependency(name = "jquery.js") , @ResourceDependency(name = "richfaces.js") })
public abstract class AjaxCommandRendererBase extends RendererBase {
+ private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
- private static final Logger _log = RichfacesLogger.RENDERKIT.getLogger();
+ @Override
+ protected void doDecode(FacesContext facesContext, UIComponent uiComponent) {
+ if (isSubmitted(facesContext, uiComponent)) {
+ new ActionEvent(uiComponent).queue();
+ }
+ }
- protected void doDecode(FacesContext facesContext, UIComponent uiComponent) {
- if (isSubmitted(facesContext, uiComponent)) {
- new ActionEvent(uiComponent).queue();
- }
- }
+ protected boolean isSubmitted(FacesContext facesContext, UIComponent uiComponent) {
+ if (getUtils().isBooleanAttribute(uiComponent, "disabled")) {
+ return false;
+ }
- protected boolean isSubmitted(FacesContext facesContext,
- UIComponent uiComponent) {
- if (getUtils().isBooleanAttribute(uiComponent, "disabled")) {
- return false;
- }
- String clientId = uiComponent.getClientId(facesContext);
- Map<String, String> paramMap = facesContext.getExternalContext()
- .getRequestParameterMap();
- Object value = paramMap.get(clientId);
- boolean submitted = null != value;
- if (submitted && _log.isDebugEnabled()) {
- _log.debug("Decode submit of the Ajax component " + clientId);
- }
- return submitted;
- }
-
- public String getOnClick(FacesContext context, UIComponent component) {
- StringBuffer onClick = new StringBuffer();
- if (!getUtils().isBooleanAttribute(component, "disabled")) {
- HandlersChain handlersChain = new HandlersChain(component);
- handlersChain.addInlineHandlerFromAttribute(context, "onclick");
- handlersChain.addBehaviors(context, "click", "action");
- if(!handlersChain.hasSubmittingBehavior()) {
- JSFunction ajaxFunction = buildAjaxFunction(context, component, AJAX_FUNCTION_NAME);
- AjaxEventOptions eventOptions = buildEventOptions(context, component);
- if (!eventOptions.isEmpty()) {
- ajaxFunction.addParameter(eventOptions);
- }
- handlersChain.addInlineHandlerAsValue(context, ajaxFunction.toScript());
- }
-
- String handlerScript = handlersChain.toScript();
- if (handlerScript != null) {
- onClick.append(handlerScript);
- }
-
- if (!"reset".equals(component.getAttributes().get("type"))) {
- onClick.append(";return false;");
- }
- } else {
- onClick.append("return false;");
- }
- return onClick.toString();
- }
-
-/* public String getStringValue(UIComponent component) {
- Object value = getValue(component);
- return convertToString(value);
- }
-
- protected String convertToString(Object obj ) {
- return ( obj == null ? "" : obj.toString() );
- }
-
- protected String convertToString(boolean b ) {
- return String.valueOf(b);
- }
-
- protected String convertToString(int b ) {
- return b!=Integer.MIN_VALUE?String.valueOf(b):"";
- }
-
- protected String convertToString(long b ) {
- return b!=Long.MIN_VALUE?String.valueOf(b):"";
- }
+ String clientId = uiComponent.getClientId(facesContext);
+ Map<String, String> paramMap = facesContext.getExternalContext().getRequestParameterMap();
+ Object value = paramMap.get(clientId);
+ boolean submitted = null != value;
- public void encodeChildren(FacesContext context, UIComponent component)
- throws IOException {
- renderChildren(context, component);
- }
+ if (submitted && LOG.isDebugEnabled()) {
+ LOG.debug("Decode submit of the Ajax component " + clientId);
+ }
- public Object getValue(UIComponent component) {
- if (component instanceof ValueHolder) {
- return ((ValueHolder) component).getValue();
- }
- return component.getAttributes().get("value");
- }
+ return submitted;
+ }
+ public String getOnClick(FacesContext context, UIComponent component) {
+ StringBuffer onClick = new StringBuffer();
- public String getType(UIComponent uiComponent) {
- String type;
- if (uiComponent instanceof HtmlCommandButton) {
- type = ((HtmlCommandButton) uiComponent).getType();
- } else {
- type = (String) uiComponent.getAttributes().get("type");
- }
- if (type == null) {
- type = "button";
- }
- return type;
- }*/
+ if (!getUtils().isBooleanAttribute(component, "disabled")) {
+ HandlersChain handlersChain = new HandlersChain(component);
+
+ handlersChain.addInlineHandlerFromAttribute(context, "onclick");
+ handlersChain.addBehaviors(context, "click", "action");
+
+ if (!handlersChain.hasSubmittingBehavior()) {
+ JSFunction ajaxFunction = buildAjaxFunction(context, component, AJAX_FUNCTION_NAME);
+ AjaxEventOptions eventOptions = buildEventOptions(context, component);
+
+ if (!eventOptions.isEmpty()) {
+ ajaxFunction.addParameter(eventOptions);
+ }
+
+ handlersChain.addInlineHandlerAsValue(context, ajaxFunction.toScript());
+ }
+
+ String handlerScript = handlersChain.toScript();
+
+ if (handlerScript != null) {
+ onClick.append(handlerScript);
+ }
+
+ if (!"reset".equals(component.getAttributes().get("type"))) {
+ onClick.append(";return false;");
+ }
+ } else {
+ onClick.append("return false;");
+ }
+
+ return onClick.toString();
+ }
+
+/* public String getStringValue(UIComponent component) {
+ Object value = getValue(component);
+ return convertToString(value);
+ }
+
+ protected String convertToString(Object obj ) {
+ return ( obj == null ? "" : obj.toString() );
+ }
+
+ protected String convertToString(boolean b ) {
+ return String.valueOf(b);
+ }
+
+ protected String convertToString(int b ) {
+ return b!=Integer.MIN_VALUE?String.valueOf(b):"";
+ }
+
+ protected String convertToString(long b ) {
+ return b!=Long.MIN_VALUE?String.valueOf(b):"";
+ }
+
+ public void encodeChildren(FacesContext context, UIComponent component)
+ throws IOException {
+ renderChildren(context, component);
+ }
+
+ public Object getValue(UIComponent component) {
+ if (component instanceof ValueHolder) {
+ return ((ValueHolder) component).getValue();
+ }
+ return component.getAttributes().get("value");
+ }
+
+
+ public String getType(UIComponent uiComponent) {
+ String type;
+ if (uiComponent instanceof HtmlCommandButton) {
+ type = ((HtmlCommandButton) uiComponent).getType();
+ } else {
+ type = (String) uiComponent.getAttributes().get("type");
+ }
+ if (type == null) {
+ type = "button";
+ }
+ return type;
+ }*/
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxComponentRendererBase.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxComponentRendererBase.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxComponentRendererBase.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,14 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import javax.faces.render.Renderer;
/**
* @author Nick Belaevski
- *
+ *
*/
-public class AjaxComponentRendererBase extends Renderer {
-
-}
+public class AjaxComponentRendererBase extends Renderer {}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxFunctionRendererBase.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxFunctionRendererBase.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/AjaxFunctionRendererBase.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import java.util.Iterator;
@@ -38,59 +40,64 @@
/**
* @author shura
- *
+ *
*/
public abstract class AjaxFunctionRendererBase extends AjaxCommandRendererBase {
+ public String getFunction(FacesContext context, UIComponent component) {
+ String functionName = (String) component.getAttributes().get("name");
- public String getFunction(FacesContext context, UIComponent component) {
- String functionName = (String)component.getAttributes().get("name");
- if (functionName == null) {
- throw new FacesException("Value of 'name' attribute of a4j:jsFunction component is null!");
- }
-
- StringBuffer script = new StringBuffer(functionName).append("=");
- JSFunctionDefinition func = new JSFunctionDefinition();
- //func.setName(component.getName());
- // Create AJAX Submit function.
- JSFunction ajaxFunction = AjaxRendererUtils.buildAjaxFunction(
- context, component, AjaxRendererUtils.AJAX_FUNCTION_NAME);
- AjaxEventOptions options = AjaxRendererUtils.buildEventOptions(context, component);
+ if (functionName == null) {
+ throw new FacesException("Value of 'name' attribute of a4j:jsFunction component is null!");
+ }
- if (options.hasParameters()) {
- Map<String, Object> parameters = options.getParameters();
-// if (null == parameters) {
-// parameters = new HashMap<String, Object>();
-// options.put("parameters", parameters);
-// }
- // Fill parameters.
- for (Iterator<UIComponent> it = component.getChildren().iterator(); it.hasNext();) {
- UIComponent child = it.next();
- if (child instanceof UIParameter) {
- UIParameter parameter = ((UIParameter) child);
- String name = parameter.getName();
- func.addParameter(name);
- // Put parameter name to AJAX.Submit parameter, with default value.
- JSReference reference = new JSReference(name);
- if (null != parameter.getValue()) {
- reference = new JSReference(name + "||"
- + ScriptUtils.toScript(parameters.get(name)));
+ StringBuffer script = new StringBuffer(functionName).append("=");
+ JSFunctionDefinition func = new JSFunctionDefinition();
- }
- // Replace parameter value to reference.
- parameters.put(name, reference);
- }
- }
- }
-
- if (!options.isEmpty()) {
- ajaxFunction.addParameter(options);
- }
-
- //TODO - added in 4.0 - ?
- func.addParameter(JSReference.EVENT);
-
- func.addToBody(ajaxFunction.toScript());
- func.appendScript(script);
- return script.toString();
- }
+ // func.setName(component.getName());
+ // Create AJAX Submit function.
+ JSFunction ajaxFunction = AjaxRendererUtils.buildAjaxFunction(context, component,
+ AjaxRendererUtils.AJAX_FUNCTION_NAME);
+ AjaxEventOptions options = AjaxRendererUtils.buildEventOptions(context, component);
+
+ if (options.hasParameters()) {
+ Map<String, Object> parameters = options.getParameters();
+
+// if (null == parameters) {
+// parameters = new HashMap<String, Object>();
+// options.put("parameters", parameters);
+// }
+ // Fill parameters.
+ for (Iterator<UIComponent> it = component.getChildren().iterator(); it.hasNext(); ) {
+ UIComponent child = it.next();
+
+ if (child instanceof UIParameter) {
+ UIParameter parameter = (UIParameter) child;
+ String name = parameter.getName();
+
+ func.addParameter(name);
+
+ // Put parameter name to AJAX.Submit parameter, with default value.
+ JSReference reference = new JSReference(name);
+
+ if (null != parameter.getValue()) {
+ reference = new JSReference(name + "||" + ScriptUtils.toScript(parameters.get(name)));
+ }
+
+ // Replace parameter value to reference.
+ parameters.put(name, reference);
+ }
+ }
+ }
+
+ if (!options.isEmpty()) {
+ ajaxFunction.addParameter(options);
+ }
+
+ // TODO - added in 4.0 - ?
+ func.addParameter(JSReference.EVENT);
+ func.addToBody(ajaxFunction.toScript());
+ func.appendScript(script);
+
+ return script.toString();
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/CommandRendererBase.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/CommandRendererBase.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/CommandRendererBase.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit;
import javax.faces.component.UIComponent;
@@ -27,16 +29,18 @@
/**
* @author Nick Belaevski
- *
+ *
*/
public class CommandRendererBase extends Renderer {
- /* (non-Javadoc)
- * @see javax.faces.render.Renderer#decode(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
- */
- @Override
- public void decode(FacesContext context, UIComponent component) {
- // TODO Auto-generated method stub
- super.decode(context, component);
- }
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.render.Renderer#decode(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+ */
+ @Override
+ public void decode(FacesContext context, UIComponent component) {
+
+ // TODO Auto-generated method stub
+ super.decode(context, component);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/html/AjaxCommandButtonRendererBase.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/html/AjaxCommandButtonRendererBase.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/html/AjaxCommandButtonRendererBase.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit.html;
import java.io.IOException;
@@ -31,29 +33,31 @@
/**
* @author Nick Belaevski
- *
+ *
*/
public abstract class AjaxCommandButtonRendererBase extends AjaxCommandRendererBase {
+ protected void encodeTypeAndImage(FacesContext context, UIComponent uiComponent) throws IOException {
+ ResponseWriter writer = context.getResponseWriter();
+ String type = (String) uiComponent.getAttributes().get("type");
+ String image = (String) uiComponent.getAttributes().get("image");
- protected void encodeTypeAndImage(FacesContext context, UIComponent uiComponent) throws IOException {
- ResponseWriter writer = context.getResponseWriter();
- String type = (String)uiComponent.getAttributes().get("type");
- String image = (String)uiComponent.getAttributes().get("image");
- if(image != null){
- image = context.getApplication().getViewHandler().getResourceURL(context,image);
- image = context.getExternalContext().encodeResourceURL(image);
- writer.writeAttribute("type","image","image");
- writer.writeURIAttribute("src",image,"image");
- Object value;
- if (null == uiComponent.getAttributes().get("alt") && null != (value = uiComponent.getAttributes().get("value")) ) {
- writer.writeAttribute("alt",value,"value");
- }
- } else {
- if(null != type ){
- writer.writeAttribute("type",type.toLowerCase(),"type");
- } else {
- writer.writeAttribute("type","submit","type");
- }
- }
- }
+ if (image != null) {
+ image = context.getApplication().getViewHandler().getResourceURL(context, image);
+ image = context.getExternalContext().encodeResourceURL(image);
+ writer.writeAttribute("type", "image", "image");
+ writer.writeURIAttribute("src", image, "image");
+
+ Object value = uiComponent.getAttributes().get("value");
+
+ if (null == uiComponent.getAttributes().get("alt") && null != value) {
+ writer.writeAttribute("alt", value, "value");
+ }
+ } else {
+ if (null != type) {
+ writer.writeAttribute("type", type.toLowerCase(), "type");
+ } else {
+ writer.writeAttribute("type", "submit", "type");
+ }
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/html/MediaOutputRenderer.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/html/MediaOutputRenderer.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/renderkit/html/MediaOutputRenderer.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.renderkit.html;
import java.io.IOException;
+
import java.util.HashMap;
import java.util.Map;
@@ -34,6 +37,7 @@
import org.ajax4jsf.Messages;
import org.ajax4jsf.renderkit.RendererBase;
import org.ajax4jsf.renderkit.RendererUtils.HTML;
+
import org.richfaces.component.UIMediaOutput;
/**
@@ -41,88 +45,108 @@
*
*/
public class MediaOutputRenderer extends RendererBase {
-
public static final String RENDERER_TYPE = "org.richfaces.MediaOutputRenderer";
-
+
/**
* Associationd between element name and uri attributes
*/
- private static final Map<String, String> uriAttributes;
-
+ private static final Map<String, String> URI_ATTRIBUTES;
+
static {
- uriAttributes = new HashMap<String, String>();
- uriAttributes.put("a","href");
- uriAttributes.put("img","src");
- uriAttributes.put("object","data");
- uriAttributes.put("link","href");
+ URI_ATTRIBUTES = new HashMap<String, String>();
+ URI_ATTRIBUTES.put("a", "href");
+ URI_ATTRIBUTES.put("img", "src");
+ URI_ATTRIBUTES.put("object", "data");
+ URI_ATTRIBUTES.put("link", "href");
}
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.renderkit.RendererBase#doEncodeEnd(javax.faces.context.ResponseWriter,
+ * javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+ */
+ @Override
+ protected void doEncodeEnd(ResponseWriter writer, FacesContext context, UIComponent component) throws IOException {
+ UIMediaOutput mmedia = (UIMediaOutput) component;
+ String element = mmedia.getElement();
- /* (non-Javadoc)
- * @see org.ajax4jsf.renderkit.RendererBase#doEncodeEnd(javax.faces.context.ResponseWriter, javax.faces.context.FacesContext, javax.faces.component.UIComponent)
- */
- protected void doEncodeEnd(ResponseWriter writer, FacesContext context, UIComponent component) throws IOException {
- UIMediaOutput mmedia = (UIMediaOutput) component;
- String element = mmedia.getElement();
- if(null == element){
- throw new FacesException(Messages.getMessage(Messages.NULL_ATTRIBUTE_ERROR,"element",component.getClientId(context)));
- }
- writer.endElement(element);
- }
+ if (null == element) {
+ throw new FacesException(Messages.getMessage(Messages.NULL_ATTRIBUTE_ERROR, "element",
+ component.getClientId(context)));
+ }
+ writer.endElement(element);
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.renderkit.RendererBase#getComponentClass()
- */
- protected Class<? extends UIComponent> getComponentClass() {
- // TODO Auto-generated method stub
- return UIMediaOutput.class;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.renderkit.RendererBase#getComponentClass()
+ */
+ @Override
+ protected Class<? extends UIComponent> getComponentClass() {
+ // TODO Auto-generated method stub
+ return UIMediaOutput.class;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.renderkit.RendererBase#doEncodeBegin(javax.faces.context.ResponseWriter, javax.faces.context.FacesContext, javax.faces.component.UIComponent)
- */
- protected void doEncodeBegin(ResponseWriter writer, FacesContext context, UIComponent component) throws IOException {
- UIMediaOutput mmedia = (UIMediaOutput) component;
- String element = mmedia.getElement();
- if(null == element){
- throw new FacesException(Messages.getMessage(Messages.NULL_ATTRIBUTE_ERROR,"element",component.getClientId(context)));
- }
- String uriAttribute = mmedia.getUriAttribute();
- // Check for pre-defined attributes
- if(null == uriAttribute){
- uriAttribute = (String) uriAttributes.get(element);
-
- if (null == uriAttribute) {
- throw new FacesException(Messages.getMessage(Messages.NULL_ATTRIBUTE_ERROR,"uriAttribute",component.getClientId(context)));
- }
- }
- writer.startElement(element,mmedia);
- getUtils().encodeId(context, component);
-
- StringBuilder uri = new StringBuilder(mmedia.getResource().getRequestPath());
- // Append parameters to resource Uri
- boolean haveQestion = uri.indexOf("?") >= 0;
- for (UIComponent child : component.getChildren()) {
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.renderkit.RendererBase#doEncodeBegin(javax.faces.context.ResponseWriter,
+ * javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+ */
+ @Override
+ protected void doEncodeBegin(ResponseWriter writer, FacesContext context, UIComponent component)
+ throws IOException {
+
+ UIMediaOutput mmedia = (UIMediaOutput) component;
+ String element = mmedia.getElement();
+
+ if (null == element) {
+ throw new FacesException(Messages.getMessage(Messages.NULL_ATTRIBUTE_ERROR, "element",
+ component.getClientId(context)));
+ }
+
+ String uriAttribute = mmedia.getUriAttribute();
+
+ // Check for pre-defined attributes
+ if (null == uriAttribute) {
+ uriAttribute = URI_ATTRIBUTES.get(element);
+
+ if (null == uriAttribute) {
+ throw new FacesException(Messages.getMessage(Messages.NULL_ATTRIBUTE_ERROR, "uriAttribute",
+ component.getClientId(context)));
+ }
+ }
+
+ writer.startElement(element, mmedia);
+ getUtils().encodeId(context, component);
+
+ StringBuilder uri = new StringBuilder(mmedia.getResource().getRequestPath());
+
+ // Append parameters to resource Uri
+ boolean haveQestion = uri.indexOf("?") >= 0;
+
+ for (UIComponent child : component.getChildren()) {
if (child instanceof UIParameter) {
UIParameter uiParam = (UIParameter) child;
String name = uiParam.getName();
Object value = uiParam.getValue();
- if(null != value){
- if(haveQestion){
- uri.append('&');
- } else {
- uri.append('?');
- haveQestion = true;
- }
- uri.append(name).append('=').append(value.toString());
+
+ if (null != value) {
+ if (haveQestion) {
+ uri.append('&');
+ } else {
+ uri.append('?');
+ haveQestion = true;
+ }
+
+ uri.append(name).append('=').append(value.toString());
}
}
- }
- writer.writeURIAttribute(uriAttribute,uri,"uri");
- getUtils().encodeAttributesFromArray(context,component,HTML.PASS_THRU_STYLES);
- getUtils().encodePassThru(context, mmedia, null);
- }
+ }
+ writer.writeURIAttribute(uriAttribute, uri, "uri");
+ getUtils().encodeAttributesFromArray(context, component, HTML.PASS_THRU_STYLES);
+ getUtils().encodePassThru(context, mmedia, null);
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/resource/MediaOutputResource.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/resource/MediaOutputResource.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/resource/MediaOutputResource.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
import java.io.ByteArrayInputStream;
@@ -27,6 +29,7 @@
import javax.el.MethodExpression;
import javax.el.ValueExpression;
+
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
@@ -38,71 +41,70 @@
* @since 4.0
*/
public class MediaOutputResource extends AbstractBaseResource implements StateHolder {
+ private MethodExpression contentProducer;
+ private ValueExpression expiresExpression;
- private Object userData;
-
- private MethodExpression contentProducer;
-
- /*
- * TODO: add handling for expressions:
- *
- * 1. State saving
- * 2. Evaluation
- */
- private ValueExpression lastModifiedExpression;
+ /*
+ * TODO: add handling for expressions:
+ *
+ * 1. State saving
+ * 2. Evaluation
+ */
+ private ValueExpression lastModifiedExpression;
+ private ValueExpression timeToLiveExpression;
+ private Object userData;
- private ValueExpression expiresExpression;
-
- private ValueExpression timeToLiveExpression;
+ @Override
+ public InputStream getInputStream() {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ FacesContext facesContext = FacesContext.getCurrentInstance();
- @Override
- public InputStream getInputStream() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- FacesContext facesContext = FacesContext.getCurrentInstance();
- contentProducer.invoke(facesContext.getELContext(), new Object[]{baos, userData});
- return new ByteArrayInputStream(baos.toByteArray());
- }
+ contentProducer.invoke(facesContext.getELContext(), new Object[] {baos, userData});
- public boolean isTransient() {
- return false;
- }
+ return new ByteArrayInputStream(baos.toByteArray());
+ }
- public void setTransient(boolean newTransientValue) {
- throw new UnsupportedOperationException();
- }
-
- public Object saveState(FacesContext context) {
- Object[] state = new Object[4];
-
- //parent fields state saving
- state[0] = isCacheable(context) ? Boolean.TRUE : Boolean.FALSE;
- state[1] = getContentType();
- state[2] = UIComponentBase.saveAttachedState(context, userData);
- state[3] = UIComponentBase.saveAttachedState(context, contentProducer);
-
- return state;
- }
+ public boolean isTransient() {
+ return false;
+ }
- public void restoreState(FacesContext context, Object stateObject) {
- Object[] state = (Object[]) stateObject;
+ public void setTransient(boolean newTransientValue) {
+ throw new UnsupportedOperationException();
+ }
- setCacheable((Boolean) state[0]);
- setContentType((String) state[1]);
- userData = UIComponentBase.restoreAttachedState(context, state[2]);
- contentProducer = (MethodExpression) UIComponentBase.restoreAttachedState(context, state[3]);
- }
+ public Object saveState(FacesContext context) {
+ Object[] state = new Object[4];
- /**
- * @param uiMediaOutput
- */
- //TODO use ResourceComponent or exchange object as argument?
- public void initialize(UIMediaOutput uiMediaOutput) {
- this.setCacheable(uiMediaOutput.isCacheable());
- this.setContentType(uiMediaOutput.getMimeType());
- this.userData = uiMediaOutput.getValue();
- this.contentProducer = uiMediaOutput.getCreateContentExpression();
- this.lastModifiedExpression = uiMediaOutput.getValueExpression("lastModfied");
- this.expiresExpression = uiMediaOutput.getValueExpression("expires");
- this.timeToLiveExpression = uiMediaOutput.getValueExpression("timeToLive");
- }
+ // parent fields state saving
+ state[0] = isCacheable(context) ? Boolean.TRUE : Boolean.FALSE;
+ state[1] = getContentType();
+ state[2] = UIComponentBase.saveAttachedState(context, userData);
+ state[3] = UIComponentBase.saveAttachedState(context, contentProducer);
+
+ return state;
+ }
+
+ public void restoreState(FacesContext context, Object stateObject) {
+ Object[] state = (Object[]) stateObject;
+
+ setCacheable((Boolean) state[0]);
+ setContentType((String) state[1]);
+ userData = UIComponentBase.restoreAttachedState(context, state[2]);
+ contentProducer = (MethodExpression) UIComponentBase.restoreAttachedState(context, state[3]);
+ }
+
+ /**
+ * @param uiMediaOutput
+ */
+
+ // TODO use ResourceComponent or exchange object as argument?
+ public void initialize(UIMediaOutput uiMediaOutput) {
+ this.setCacheable(uiMediaOutput.isCacheable());
+ this.setContentType(uiMediaOutput.getMimeType());
+ this.userData = uiMediaOutput.getValue();
+ this.contentProducer = uiMediaOutput.getCreateContentExpression();
+ this.lastModifiedExpression = uiMediaOutput.getValueExpression("lastModfied");
+ this.expiresExpression = uiMediaOutput.getValueExpression("expires");
+ this.timeToLiveExpression = uiMediaOutput.getValueExpression("timeToLive");
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/resource/PushResource.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/resource/PushResource.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/resource/PushResource.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,53 +19,55 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.resource;
-import java.io.InputStream;
-import java.util.Map;
+import org.richfaces.component.PushEventTracker;
+import org.richfaces.component.PushListenersManager;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
-import org.richfaces.component.PushEventTracker;
-import org.richfaces.component.PushListenersManager;
-import org.richfaces.resource.AbstractBaseResource;
+import java.io.InputStream;
+import java.util.Map;
+
/**
* @author Nick Belaevski
* @since 4.0
*/
+
//TODO make this a singleton
public class PushResource extends AbstractBaseResource {
+ @Override
+ public boolean isCacheable(FacesContext context) {
+ return false;
+ }
- @Override
- public boolean isCacheable(FacesContext context) {
- return false;
- }
-
- @Override
- public InputStream getInputStream() {
- return null;
- }
+ @Override
+ public InputStream getInputStream() {
+ return null;
+ }
- @Override
- public Map<String, String> getResponseHeaders() {
- Map<String, String> headers = super.getResponseHeaders();
-
- FacesContext facesContext = FacesContext.getCurrentInstance();
- ExternalContext externalContext = facesContext.getExternalContext();
- String pushId = externalContext.getRequestParameterMap().get("id");
- if (pushId != null && pushId.length() != 0) {
- PushListenersManager manager = PushListenersManager.getInstance(facesContext);
-
- PushEventTracker eventTracker = manager.getListener(pushId);
- if (eventTracker != null) {
- if (eventTracker.pollStatus()) {
- headers.put("Ajax-Push-Status", "READY");
- }
- }
- }
-
- return headers;
- }
+ @Override
+ public Map<String, String> getResponseHeaders() {
+ Map<String, String> headers = super.getResponseHeaders();
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ ExternalContext externalContext = facesContext.getExternalContext();
+ String pushId = externalContext.getRequestParameterMap().get("id");
+
+ if (pushId != null && pushId.length() != 0) {
+ PushListenersManager manager = PushListenersManager.getInstance(facesContext);
+ PushEventTracker eventTracker = manager.getListener(pushId);
+
+ if (eventTracker != null) {
+ if (eventTracker.pollStatus()) {
+ headers.put("Ajax-Push-Status", "READY");
+ }
+ }
+ }
+
+ return headers;
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/taglib/html/facelets/AjaxPushHandler.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/taglib/html/facelets/AjaxPushHandler.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/taglib/html/facelets/AjaxPushHandler.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.taglib.html.facelets;
import java.util.EventListener;
@@ -38,97 +40,92 @@
* @author shura (latest modification by $Author$)
* @version $Revision$ $Date: 2009-07-31 14:34:48 +0300 (Пт, 31 июл
* 2009) $
- *
+ *
*/
public class AjaxPushHandler extends ComponentHandler {
+ private static final MetaRule AJAX_PUSH_META_RULE = new AjaxPushMetaRule();
- private static final MetaRule ajaxPushMetaRule = new AjaxPushMetaRule();
+ /**
+ * @param config
+ */
+ public AjaxPushHandler(ComponentConfig config) {
+ super(config);
+ }
- /**
- * @param config
- */
- public AjaxPushHandler(ComponentConfig config) {
- super(config);
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.ajax4jsf.tag.AjaxComponentHandler#createMetaRuleset(java.lang.Class)
+ */
+ @Override
+ protected MetaRuleset createMetaRuleset(Class type) {
+ MetaRuleset metaRules = super.createMetaRuleset(type);
- }
+ metaRules.addRule(AJAX_PUSH_META_RULE);
- /*
- * (non-Javadoc)
- *
- * @see
- * org.ajax4jsf.tag.AjaxComponentHandler#createMetaRuleset(java.lang.Class)
- */
- protected MetaRuleset createMetaRuleset(Class type) {
- MetaRuleset metaRules = super.createMetaRuleset(type);
- metaRules.addRule(ajaxPushMetaRule);
- return metaRules;
- }
+ return metaRules;
+ }
- /**
- * @author shura (latest modification by $Author$)
- * @version $Revision$ $Date: 2009-07-31 14:34:48 +0300 (Пт, 31
- * июл 2009) $
- *
- */
- static class AjaxPushMetaRule extends MetaRule {
+ /**
+ * @author shura (latest modification by $Author$)
+ * @version $Revision$ $Date: 2009-07-31 14:34:48 +0300 (Пт, 31
+ * июл 2009) $
+ *
+ */
+ static class AjaxPushActionMapper extends Metadata {
+ private static final Class<?>[] AJAX_PUSH_ACTION_SIG = new Class[] {EventListener.class};
+ private final TagAttribute send;
- /**
- *
- */
- public AjaxPushMetaRule() {
- super();
- }
+ /**
+ * @param attribute
+ */
+ public AjaxPushActionMapper(TagAttribute attribute) {
+ send = attribute;
+ }
- /*
- * (non-Javadoc)
- *
- * @see com.sun.facelets.tag.MetaRule#applyRule(java.lang.String,
- * com.sun.facelets.tag.TagAttribute,
- * com.sun.facelets.tag.MetadataTarget)
- */
- public Metadata applyRule(String name, TagAttribute attribute,
- MetadataTarget meta) {
- if (meta.isTargetInstanceOf(UIPush.class)) {
+ /*
+ * (non-Javadoc)
+ *
+ * @seecom.sun.facelets.tag.Metadata#applyMetadata(com.sun.facelets.
+ * FaceletContext, java.lang.Object)
+ */
+ public void applyMetadata(FaceletContext ctx, Object instance) {
+ ((UIPush) instance).setEventProducer(this.send.getMethodExpression(ctx, null, AJAX_PUSH_ACTION_SIG));
+ }
+ }
- if ("eventProducer".equals(name)) {
- return new AjaxPushActionMapper(attribute);
- }
- }
- return null;
- }
- }
+ /**
+ * @author shura (latest modification by $Author$)
+ * @version $Revision$ $Date: 2009-07-31 14:34:48 +0300 (Пт, 31
+ * июл 2009) $
+ *
+ */
+ static class AjaxPushMetaRule extends MetaRule {
- /**
- * @author shura (latest modification by $Author$)
- * @version $Revision$ $Date: 2009-07-31 14:34:48 +0300 (Пт, 31
- * июл 2009) $
- *
- */
- static class AjaxPushActionMapper extends Metadata {
+ /**
+ *
+ */
+ public AjaxPushMetaRule() {
+ super();
+ }
- private static final Class<?>[] AJAX_PUSH_ACTION_SIG = new Class[] { EventListener.class };
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.sun.facelets.tag.MetaRule#applyRule(java.lang.String,
+ * com.sun.facelets.tag.TagAttribute,
+ * com.sun.facelets.tag.MetadataTarget)
+ */
+ public Metadata applyRule(String name, TagAttribute attribute, MetadataTarget meta) {
+ if (meta.isTargetInstanceOf(UIPush.class)) {
+ if ("eventProducer".equals(name)) {
+ return new AjaxPushActionMapper(attribute);
+ }
+ }
- private final TagAttribute _send;
-
- /**
- * @param attribute
- */
- public AjaxPushActionMapper(TagAttribute attribute) {
- _send = attribute;
- }
-
- /*
- * (non-Javadoc)
- *
- * @seecom.sun.facelets.tag.Metadata#applyMetadata(com.sun.facelets.
- * FaceletContext, java.lang.Object)
- */
- public void applyMetadata(FaceletContext ctx, Object instance) {
- ((UIPush) instance).setEventProducer(this._send
- .getMethodExpression(ctx, null, AJAX_PUSH_ACTION_SIG));
- }
-
- }
-
+ return null;
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/main/java/org/richfaces/taglib/html/facelets/MediaOutputHandler.java
===================================================================
--- root/ui/trunk/components/core/src/main/java/org/richfaces/taglib/html/facelets/MediaOutputHandler.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/main/java/org/richfaces/taglib/html/facelets/MediaOutputHandler.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.richfaces.taglib.html.facelets;
import java.io.OutputStream;
@@ -37,88 +39,85 @@
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/02/01 15:31:22 $
- *
+ *
*/
public class MediaOutputHandler extends ComponentHandler {
+ private static final MetaRule MMEDIA_META_RULE = new MMediaMetaRule();
- private static final MetaRule mmediaMetaRule = new MMediaMetaRule();
+ /**
+ * @param config
+ */
+ public MediaOutputHandler(ComponentConfig config) {
+ super(config);
+ }
- /**
- * @param config
- */
- public MediaOutputHandler(ComponentConfig config) {
- super(config);
- }
+ @Override
+ protected MetaRuleset createMetaRuleset(Class type) {
+ MetaRuleset metaRules = super.createMetaRuleset(type);
- protected MetaRuleset createMetaRuleset(Class type) {
- MetaRuleset metaRules = super.createMetaRuleset(type);
- metaRules.addRule(mmediaMetaRule);
- return metaRules;
- }
+ metaRules.addRule(MMEDIA_META_RULE);
- /**
- * @author shura (latest modification by $Author: alexsmirnov $)
- * @version $Revision: 1.1.2.1 $ $Date: 2007/02/01 15:31:22 $
- *
- */
- static class MMediaMetaRule extends MetaRule {
+ return metaRules;
+ }
- /**
- *
- */
- public MMediaMetaRule() {
- super();
- }
+ /**
+ * @author shura (latest modification by $Author: alexsmirnov $)
+ * @version $Revision: 1.1.2.1 $ $Date: 2007/02/01 15:31:22 $
+ *
+ */
+ static class MMediaActionMapper extends Metadata {
+ private static final Class<?>[] MMEDIA_ACTION_SIG = new Class[] {OutputStream.class, Object.class};
+ private final TagAttribute send;
- /*
- * (non-Javadoc)
- *
- * @see com.sun.facelets.tag.MetaRule#applyRule(java.lang.String,
- * com.sun.facelets.tag.TagAttribute,
- * com.sun.facelets.tag.MetadataTarget)
- */
- public Metadata applyRule(String name, TagAttribute attribute,
- MetadataTarget meta) {
- if (meta.isTargetInstanceOf(UIMediaOutput.class)) {
- if ("createContent".equals(name)) {
- return new MMediaActionMapper(attribute);
- }
- }
- return null;
- }
+ /**
+ * @param attribute
+ */
+ public MMediaActionMapper(TagAttribute attribute) {
+ send = attribute;
+ }
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @seecom.sun.facelets.tag.Metadata#applyMetadata(com.sun.facelets.
+ * FaceletContext, java.lang.Object)
+ */
+ public void applyMetadata(FaceletContext ctx, Object instance) {
+ ((UIMediaOutput) instance).setCreateContentExpression(this.send.getMethodExpression(ctx, null,
+ MMEDIA_ACTION_SIG));
+ }
+ }
- /**
- * @author shura (latest modification by $Author: alexsmirnov $)
- * @version $Revision: 1.1.2.1 $ $Date: 2007/02/01 15:31:22 $
- *
- */
- static class MMediaActionMapper extends Metadata {
- private static final Class<?>[] MMEDIA_ACTION_SIG = new Class[] {
- OutputStream.class, Object.class };
+ /**
+ * @author shura (latest modification by $Author: alexsmirnov $)
+ * @version $Revision: 1.1.2.1 $ $Date: 2007/02/01 15:31:22 $
+ *
+ */
+ static class MMediaMetaRule extends MetaRule {
- private final TagAttribute _send;
+ /**
+ *
+ */
+ public MMediaMetaRule() {
+ super();
+ }
- /**
- * @param attribute
- */
- public MMediaActionMapper(TagAttribute attribute) {
- _send = attribute;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.sun.facelets.tag.MetaRule#applyRule(java.lang.String,
+ * com.sun.facelets.tag.TagAttribute,
+ * com.sun.facelets.tag.MetadataTarget)
+ */
+ public Metadata applyRule(String name, TagAttribute attribute, MetadataTarget meta) {
+ if (meta.isTargetInstanceOf(UIMediaOutput.class)) {
+ if ("createContent".equals(name)) {
+ return new MMediaActionMapper(attribute);
+ }
+ }
- /*
- * (non-Javadoc)
- *
- * @seecom.sun.facelets.tag.Metadata#applyMetadata(com.sun.facelets.
- * FaceletContext, java.lang.Object)
- */
- public void applyMetadata(FaceletContext ctx, Object instance) {
- ((UIMediaOutput) instance).setCreateContentExpression(this._send
- .getMethodExpression(ctx, null, MMEDIA_ACTION_SIG));
- }
-
- }
-
+ return null;
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/AbstractQueueComponentTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/AbstractQueueComponentTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/AbstractQueueComponentTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -20,10 +20,13 @@
*/
+
package org.ajax4jsf.component;
import java.io.IOException;
+
import java.net.URL;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -49,6 +52,7 @@
import org.ajax4jsf.resource.InternetResourceBuilder;
import org.ajax4jsf.resource.ResourceNotFoundException;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.mozilla.javascript.FunctionObject;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
@@ -62,6 +66,7 @@
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine;
+
import com.sun.facelets.Facelet;
import com.sun.facelets.FaceletFactory;
import com.sun.facelets.compiler.Compiler;
@@ -74,522 +79,515 @@
* @since 3.3.0
*/
public abstract class AbstractQueueComponentTest extends AbstractAjax4JsfTestCase {
+ private static final String AJAX_SUBMIT = "ajaxSubmit";
+ private static final String COMPONENT_TYPE = AjaxSubmitFunctionComponent.class.getName();
+ public static final int DEFAULT_REQUEST_TIME = 1000;
+ private static final String SIMULATION_SCRIPT_NAME = "org/ajax4jsf/component/simulation.js";
+ private static final Compiler compiler = new SAXCompiler();
+ private static final ScriptableObject systemOut = new ScriptableObject() {
- private static final String COMPONENT_TYPE = AjaxSubmitFunctionComponent.class.getName();
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8574162538513136625L;
+ @Override
+ public String getClassName() {
+ return "systemOut";
+ }
+ @SuppressWarnings("unused")
+ public void println(String s) {
+ System.out.println(s);
+ }
+ };
- private static final String AJAX_SUBMIT = "ajaxSubmit";
-
- public static final int DEFAULT_REQUEST_TIME = 1000;
-
- protected HtmlPage page;
-
- public final static class AjaxSubmitFunctionComponent extends UIComponentBase {
+ static {
+ try {
+ systemOut.defineProperty("println",
+ new FunctionObject(null, systemOut.getClass().getMethod("println", String.class),
+ systemOut), ScriptableObject.READONLY);
+ } catch (SecurityException e) {
+ throw new IllegalStateException(e.getMessage(), e);
+ } catch (NoSuchMethodException e) {
+ throw new IllegalStateException(e.getMessage(), e);
+ }
+ }
- @Override
- public String getRendererType() {
- return COMPONENT_TYPE;
- }
-
- @Override
- public String getFamily() {
- return COMPONENT_TYPE;
- }
+ protected HtmlPage page;
- }
+ public AbstractQueueComponentTest(String name) {
+ super(name);
+ }
- private final static class AjaxSubmitFunctionResourceRenderer extends
- Renderer implements UserResourceRenderer2 {
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
- public void encodeToHead(FacesContext facesContext, UIComponent component)
- throws IOException {
- JSFunction ajaxFunction = AjaxRendererUtils.buildAjaxFunction(component, facesContext);
- Map<String, Object> options = AjaxRendererUtils.buildEventOptions(facesContext, component, true);
- options.put("requestDelay", new JSReference("options.requestDelay"));
- options.put("similarityGroupingId", new JSReference("options.similarityGroupingId || '" +
- component.getClientId(facesContext) + "'"));
- options.put("data", new JSReference("data"));
- options.put("requestTime", new JSReference("options.requestTime"));
- options.put("timeout", new JSReference("options.timeout"));
- options.put("eventsQueue", new JSReference("options.eventsQueue"));
- options.put("implicitEventsQueue", new JSReference("options.implicitEventsQueue"));
- options.put("ignoreDupResponses", new JSReference("options.ignoreDupResponses"));
-
- ajaxFunction.addParameter(options);
-
- ResponseWriter responseWriter = facesContext.getResponseWriter();
- responseWriter.startElement(HTML.SCRIPT_ELEM, component);
- responseWriter.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
- responseWriter.writeText("var " + AJAX_SUBMIT + " = function(data, options) {" + ajaxFunction.toScript() + "};", null);
- responseWriter.endElement(HTML.SCRIPT_ELEM);
- }
-
- }
-
- public AbstractQueueComponentTest(String name) {
- super(name);
- }
+ InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
- private static final String SIMULATION_SCRIPT_NAME = "org/ajax4jsf/component/simulation.js";
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
+ try {
+ resourceBuilder.getResource(SIMULATION_SCRIPT_NAME);
+ } catch (ResourceNotFoundException e) {
+ resourceBuilder.createResource(null, SIMULATION_SCRIPT_NAME);
+ }
- InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
- try {
- resourceBuilder.getResource(SIMULATION_SCRIPT_NAME);
- } catch (ResourceNotFoundException e) {
- resourceBuilder.createResource(null, SIMULATION_SCRIPT_NAME);
- }
-
- UIViewRoot viewRoot = facesContext.getViewRoot();
- UIResource resource;
-
- UIComponent form = application.createComponent(UIForm.COMPONENT_TYPE);
- viewRoot.getChildren().add(form);
- final UIComponent commandButton = application.createComponent(UIAjaxCommandButton.COMPONENT_TYPE);
- form.getChildren().add(commandButton);
-
- facesContext.getRenderKit().addRenderer(COMPONENT_TYPE, COMPONENT_TYPE, new AjaxSubmitFunctionResourceRenderer());
- form.getChildren().add(new AjaxSubmitFunctionComponent());
-
- resource = (UIResource) application.createComponent("org.ajax4jsf.LoadScript");
- resource.setSrc("resource:///" + SIMULATION_SCRIPT_NAME);
- viewRoot.getChildren().add(resource);
- }
-
- @Override
- public void tearDown() throws Exception {
- this.page = null;
- super.tearDown();
- }
+ UIViewRoot viewRoot = facesContext.getViewRoot();
+ UIResource resource;
+ UIComponent form = application.createComponent(UIForm.COMPONENT_TYPE);
- protected static final class ParametersBuilder {
- private Map<String, Object> parameters;
-
- private ParametersBuilder() {
- this.parameters = new HashMap<String, Object>();
- }
-
- private ParametersBuilder(Map<String, Object> parameters) {
- this.parameters = new HashMap<String, Object>(parameters);
- }
+ viewRoot.getChildren().add(form);
- private ParametersBuilder put(String key, Object value) {
- this.parameters.put(key, value);
- return this;
- }
-
- protected Map<String, Object> getParameters() {
- return parameters;
- }
+ final UIComponent commandButton = application.createComponent(UIAjaxCommandButton.COMPONENT_TYPE);
- /**
- * Sets value of requestDelay parameter
- * @param value
- * @return
- */
- public ParametersBuilder requestDelay(double value) {
- return new ParametersBuilder(this.parameters).put("requestDelay", value);
- }
+ form.getChildren().add(commandButton);
+ facesContext.getRenderKit().addRenderer(COMPONENT_TYPE, COMPONENT_TYPE,
+ new AjaxSubmitFunctionResourceRenderer());
+ form.getChildren().add(new AjaxSubmitFunctionComponent());
+ resource = (UIResource) application.createComponent("org.ajax4jsf.LoadScript");
+ resource.setSrc("resource:///" + SIMULATION_SCRIPT_NAME);
+ viewRoot.getChildren().add(resource);
+ }
- /**
- * Sets value of similarityGroupingId parameter
- * @param id
- * @return
- */
- public ParametersBuilder similarityGroupingId(Object id) {
- return new ParametersBuilder(this.parameters).put("similarityGroupingId", id);
- }
-
- /**
- * Defines how long this request will be executed on server
- * @param value
- * @return
- */
- public ParametersBuilder requestTime(double value) {
- return new ParametersBuilder(this.parameters).put("requestTime", value);
- }
+ @Override
+ public void tearDown() throws Exception {
+ this.page = null;
+ super.tearDown();
+ }
- /**
- * Sets value of timeout parameter
- * @param value
- * @return
- */
- public ParametersBuilder timeout(double value) {
- return new ParametersBuilder(this.parameters).put("timeout", value);
- }
-
- /**
- * Sets value of eventsQueue parameter
- * @param name
- * @return
- */
- public ParametersBuilder eventsQueue(String name) {
- return new ParametersBuilder(this.parameters).put("eventsQueue", name);
- }
-
- /**
- * Sets value of implicitEventsQueue parameter
- * @param name
- * @return
- */
- public ParametersBuilder implicitEventsQueue(String name) {
- return new ParametersBuilder(this.parameters).put("implicitEventsQueue", name);
- }
-
- /**
- * Sets value of ignoreDupResponses parameter
- * @param value
- * @return
- */
- public ParametersBuilder ignoreDupResponses(boolean value) {
- return new ParametersBuilder(this.parameters).put("ignoreDupResponses", value);
- }
- }
-
- protected ParametersBuilder createAjaxParameters() {
- return new ParametersBuilder();
- }
-
- protected static final class TestsResult {
- private List<RequestData> dataList = new ArrayList<RequestData>();
-
- private double currentTime;
-
- public void addData(RequestData data) {
- this.dataList.add(data);
- }
-
- public List<RequestData> getDataList() {
- return dataList;
- }
-
- public void setCurrentTime(double number) {
- this.currentTime = number;
- }
-
- public double getCurrentTime() {
- return currentTime;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
-
- builder.append("[\n");
- for (RequestData data : dataList) {
- builder.append(" ");
- builder.append(data);
- builder.append("\n");
- }
- builder.append("]\n");
- builder.append("Current time: " + this.currentTime);
-
- return builder.toString();
- }
- }
-
- protected static final class RequestData {
- private boolean aborted;
-
- private double startTime;
-
- private double endTime;
-
- private String data;
+ protected ParametersBuilder createAjaxParameters() {
+ return new ParametersBuilder();
+ }
- public RequestData(String data, double startTime, double endTime,
- boolean aborted) {
- super();
- this.data = data;
- this.startTime = startTime;
- this.endTime = endTime;
- this.aborted = aborted;
- }
+ protected void checkRequestData(RequestData requestData, String data, double startTime, double endTime,
+ boolean aborted) {
+ assertEquals("Data check failed for " + requestData, data, requestData.getData());
+ assertEquals("Start time check failed for " + requestData, startTime, requestData.getStartTime());
+ assertEquals("End time check failed for " + requestData, endTime, requestData.getEndTime());
+ assertEquals("Aborted check failed for " + requestData, aborted, requestData.isAborted());
+ }
- public boolean isAborted() {
- return aborted;
- }
-
- public double getStartTime() {
- return startTime;
- }
-
- public double getEndTime() {
- return endTime;
- }
-
- public String getData() {
- return data;
- }
+ /**
+ * Execute simulated ajax request starting on given time and having data and paramaters passed as arguments.
+ * For simulated requests defaut value of data is id of the element firing request and default request time
+ * is 1000
+ *
+ * @param time
+ * @param data
+ * @param builder
+ */
+ protected void ajax(int time, String data, ParametersBuilder builder) {
+ JSFunction function = new JSFunction("simulationContext.ajax", time, data, builder.getParameters());
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
-
- builder.append("data: ");
- builder.append(data);
- builder.append(", ");
-
- builder.append("startTime: ");
- builder.append(startTime);
- builder.append(", ");
-
- builder.append("endTime: ");
- builder.append(endTime);
-
- if (isAborted()) {
- builder.append(", aborted: ");
- builder.append(true);
- }
-
- return builder.toString();
- }
- };
-
- protected void checkRequestData(RequestData requestData, String data,
- double startTime, double endTime, boolean aborted) {
-
- assertEquals("Data check failed for " + requestData, data, requestData.getData());
- assertEquals("Start time check failed for " + requestData, startTime, requestData.getStartTime());
- assertEquals("End time check failed for " + requestData, endTime, requestData.getEndTime());
- assertEquals("Aborted check failed for " + requestData, aborted, requestData.isAborted());
-
- }
-
- /**
- * Execute simulated ajax request starting on given time and having data and paramaters passed as arguments.
- * For simulated requests defaut value of data is id of the element firing request and default request time
- * is 1000
- *
- * @param time
- * @param data
- * @param builder
- */
- protected void ajax(int time, String data, ParametersBuilder builder) {
- JSFunction function = new JSFunction("simulationContext.ajax", time, data, builder.getParameters());
- page.executeJavaScript(function.toScript());
- }
+ page.executeJavaScript(function.toScript());
+ }
- protected void executeOnTime(int time, String expression) {
- JSFunction function = new JSFunction("simulationContext.executeOnTime",
- time, new JSFunctionDefinition().addToBody(expression));
-
- page.executeJavaScript(function.toScript());
- }
+ protected void executeOnTime(int time, String expression) {
+ JSFunction function = new JSFunction("simulationContext.executeOnTime", time,
+ new JSFunctionDefinition().addToBody(expression));
- private String buildClickExpression(String id) {
- return "document.getElementById('" + id + "').click()";
- }
-
- protected void clickOnTime(int time, String id) {
- JSFunction function = new JSFunction("simulationContext.executeOnTime",
- time, new JSFunctionDefinition().addToBody(buildClickExpression(id)));
-
- page.executeJavaScript(function.toScript());
- }
+ page.executeJavaScript(function.toScript());
+ }
- protected String getRootContextPath() {
- return this.getClass().getPackage().getName().replace('.', '/');
- }
-
- protected ResourceResolver createResourceResolver() {
- return new ResourceResolver() {
+ private String buildClickExpression(String id) {
+ return "document.getElementById('" + id + "').click()";
+ }
- public URL resolveUrl(String path) {
- return Thread.currentThread().getContextClassLoader().getResource(getRootContextPath() + path);
- }
-
- };
- }
-
- private static final Compiler compiler = new SAXCompiler();
-
- protected void buildView(String viewId) throws IOException {
- FaceletFactory factory = new DefaultFaceletFactory(compiler, createResourceResolver());
- FaceletFactory.setInstance(factory);
+ protected void clickOnTime(int time, String id) {
+ JSFunction function = new JSFunction("simulationContext.executeOnTime", time,
+ new JSFunctionDefinition().addToBody(buildClickExpression(id)));
- FaceletFactory f = FaceletFactory.getInstance();
- Facelet at = f.getFacelet(viewId);
+ page.executeJavaScript(function.toScript());
+ }
- UIViewRoot root = facesContext.getViewRoot();
- root.setViewId(viewId);
- at.apply(facesContext, root);
- }
-
- protected void preRenderView() throws Exception {
- StringBuilder builder = new StringBuilder("<script type='text/javascript'>");
- builder.append("DEFAULT_REQUEST_TIME = " + DEFAULT_REQUEST_TIME + ";");
- builder.append("window.simulationContext = new SimulationContext(");
- builder.append(AJAX_SUBMIT);
- builder.append(");</script>");
-
- HtmlOutputText text = new HtmlOutputText();
- text.setEscape(false);
- text.setValue(builder.toString());
-
- List<UIComponent> childList = facesContext.getViewRoot().getChildren();
- childList.add(childList.size(), text);
- }
-
- protected void postRenderView() throws Exception {
- ScriptableObject scriptableObject = (ScriptableObject) this.page.executeJavaScript("window.LOG").getJavaScriptResult();
- scriptableObject.defineProperty("out", systemOut, ScriptableObject.READONLY);
- }
+ protected String getRootContextPath() {
+ return this.getClass().getPackage().getName().replace('.', '/');
+ }
- private static final ScriptableObject systemOut = new ScriptableObject() {
+ protected ResourceResolver createResourceResolver() {
+ return new ResourceResolver() {
+ public URL resolveUrl(String path) {
+ return Thread.currentThread().getContextClassLoader().getResource(getRootContextPath() + path);
+ }
+ };
+ }
- /**
- *
- */
- private static final long serialVersionUID = -8574162538513136625L;
+ protected void buildView(String viewId) throws IOException {
+ FaceletFactory factory = new DefaultFaceletFactory(compiler, createResourceResolver());
- @Override
- public String getClassName() {
- return "systemOut";
- }
+ FaceletFactory.setInstance(factory);
- @SuppressWarnings("unused")
- public void println(String s) {
- System.out.println(s);
- }
- };
-
- static {
- try {
- systemOut.defineProperty("println",
- new FunctionObject(null, systemOut.getClass().getMethod("println", String.class), systemOut),
- ScriptableObject.READONLY);
- } catch (SecurityException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (NoSuchMethodException e) {
- throw new IllegalStateException(e.getMessage(), e);
- }
- }
-
- protected HtmlPage renderView(String viewId) throws Exception {
- buildView(viewId);
- preRenderView();
- this.page = super.renderView();
- postRenderView();
-
- return this.page;
- }
+ FaceletFactory f = FaceletFactory.getInstance();
+ Facelet at = f.getFacelet(viewId);
+ UIViewRoot root = facesContext.getViewRoot();
- @Override
- protected HtmlPage renderView() throws Exception {
- preRenderView();
- this.page = super.renderView();
- postRenderView();
-
- return this.page;
- }
-
- protected void click(String id) {
- executeJavaScript(buildClickExpression(id));
- }
-
- protected Object executeJavaScript(String expression) {
- return page.executeJavaScript(expression).getJavaScriptResult();
- }
+ root.setViewId(viewId);
+ at.apply(facesContext, root);
+ }
- protected void executeTimer() {
- page.executeJavaScript("Timer.execute();");
- }
-
- protected TestsResult getTestsResult() {
- TestsResult result = new TestsResult();
+ protected void preRenderView() throws Exception {
+ StringBuilder builder = new StringBuilder("<script type='text/javascript'>");
- executeTimer();
- ScriptResult scriptResult = page.executeJavaScript("window.simulationContext.results");
- NativeArray array = (NativeArray) scriptResult.getJavaScriptResult();
-
- for (int i = 0; i < array.getLength(); i++) {
- NativeObject object = (NativeObject) array.get(i, array);
+ builder.append("DEFAULT_REQUEST_TIME = " + DEFAULT_REQUEST_TIME + ";");
+ builder.append("window.simulationContext = new SimulationContext(");
+ builder.append(AJAX_SUBMIT);
+ builder.append(");</script>");
- String data = null;
-
- Object dataObject = object.get("data", object);
- if (!(dataObject instanceof Undefined)) {
- data = (String) dataObject;
- }
-
- Double startTime = (Double) object.get("startTime", object);
- Double endTime = (Double) object.get("endTime", object);
-
- Object aborted = object.get("aborted", object);
- boolean abortedBoolean = aborted instanceof Boolean && (Boolean) aborted;
-
- result.addData(new RequestData(data, startTime, endTime, abortedBoolean));
- }
-
- scriptResult = page.executeJavaScript("Timer.currentTime");
- result.setCurrentTime((Double) scriptResult.getJavaScriptResult());
-
- return result;
- }
-
- @Override
- protected void setupWebClient() {
- super.setupWebClient();
- webClient.setJavaScriptEngine(new JavaScriptEngine(webClient));
- webClient.setScriptPreProcessor(new UnescapingScriptPreprocessor());
- webClient.setThrowExceptionOnScriptError(true);
- webClient.setAlertHandler(new AlertHandler() {
+ HtmlOutputText text = new HtmlOutputText();
- public void handleAlert(Page page, String message) {
- fail(message);
- }
- });
- }
+ text.setEscape(false);
+ text.setValue(builder.toString());
+
+ List<UIComponent> childList = facesContext.getViewRoot().getChildren();
+
+ childList.add(childList.size(), text);
+ }
+
+ protected void postRenderView() throws Exception {
+ ScriptableObject scriptableObject =
+ (ScriptableObject) this.page.executeJavaScript("window.LOG").getJavaScriptResult();
+
+ scriptableObject.defineProperty("out", systemOut, ScriptableObject.READONLY);
+ }
+
+ protected HtmlPage renderView(String viewId) throws Exception {
+ buildView(viewId);
+ preRenderView();
+ this.page = super.renderView();
+ postRenderView();
+
+ return this.page;
+ }
+
+ @Override
+ protected HtmlPage renderView() throws Exception {
+ preRenderView();
+ this.page = super.renderView();
+ postRenderView();
+
+ return this.page;
+ }
+
+ protected void click(String id) {
+ executeJavaScript(buildClickExpression(id));
+ }
+
+ protected Object executeJavaScript(String expression) {
+ return page.executeJavaScript(expression).getJavaScriptResult();
+ }
+
+ protected void executeTimer() {
+ page.executeJavaScript("Timer.execute();");
+ }
+
+ protected TestsResult getTestsResult() {
+ TestsResult result = new TestsResult();
+
+ executeTimer();
+
+ ScriptResult scriptResult = page.executeJavaScript("window.simulationContext.results");
+ NativeArray array = (NativeArray) scriptResult.getJavaScriptResult();
+
+ for (int i = 0; i < array.getLength(); i++) {
+ NativeObject object = (NativeObject) array.get(i, array);
+ String data = null;
+ Object dataObject = object.get("data", object);
+
+ if (!(dataObject instanceof Undefined)) {
+ data = (String) dataObject;
+ }
+
+ Double startTime = (Double) object.get("startTime", object);
+ Double endTime = (Double) object.get("endTime", object);
+ Object aborted = object.get("aborted", object);
+ boolean abortedBoolean = aborted instanceof Boolean && (Boolean) aborted;
+
+ result.addData(new RequestData(data, startTime, endTime, abortedBoolean));
+ }
+
+ scriptResult = page.executeJavaScript("Timer.currentTime");
+ result.setCurrentTime((Double) scriptResult.getJavaScriptResult());
+
+ return result;
+ }
+
+ @Override
+ protected void setupWebClient() {
+ super.setupWebClient();
+ webClient.setJavaScriptEngine(new JavaScriptEngine(webClient));
+ webClient.setScriptPreProcessor(new UnescapingScriptPreprocessor());
+ webClient.setThrowExceptionOnScriptError(true);
+ webClient.setAlertHandler(new AlertHandler() {
+ public void handleAlert(Page page, String message) {
+ fail(message);
+ }
+ });
+ }
+
+ public final static class AjaxSubmitFunctionComponent extends UIComponentBase {
+ @Override
+ public String getRendererType() {
+ return COMPONENT_TYPE;
+ }
+
+ @Override
+ public String getFamily() {
+ return COMPONENT_TYPE;
+ }
+ }
+
+
+ private final static class AjaxSubmitFunctionResourceRenderer extends Renderer implements UserResourceRenderer2 {
+ public void encodeToHead(FacesContext facesContext, UIComponent component) throws IOException {
+ JSFunction ajaxFunction = AjaxRendererUtils.buildAjaxFunction(component, facesContext);
+ Map<String, Object> options = AjaxRendererUtils.buildEventOptions(facesContext, component, true);
+
+ options.put("requestDelay", new JSReference("options.requestDelay"));
+ options.put("similarityGroupingId",
+ new JSReference("options.similarityGroupingId || '" + component.getClientId(facesContext)
+ + "'"));
+ options.put("data", new JSReference("data"));
+ options.put("requestTime", new JSReference("options.requestTime"));
+ options.put("timeout", new JSReference("options.timeout"));
+ options.put("eventsQueue", new JSReference("options.eventsQueue"));
+ options.put("implicitEventsQueue", new JSReference("options.implicitEventsQueue"));
+ options.put("ignoreDupResponses", new JSReference("options.ignoreDupResponses"));
+ ajaxFunction.addParameter(options);
+
+ ResponseWriter responseWriter = facesContext.getResponseWriter();
+
+ responseWriter.startElement(HTML.SCRIPT_ELEM, component);
+ responseWriter.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
+ responseWriter.writeText("var " + AJAX_SUBMIT + " = function(data, options) {" + ajaxFunction.toScript()
+ + "};", null);
+ responseWriter.endElement(HTML.SCRIPT_ELEM);
+ }
+ }
+
+
+ protected static final class ParametersBuilder {
+ private Map<String, Object> parameters;
+
+ private ParametersBuilder() {
+ this.parameters = new HashMap<String, Object>();
+ }
+
+ private ParametersBuilder(Map<String, Object> parameters) {
+ this.parameters = new HashMap<String, Object>(parameters);
+ }
+
+ private ParametersBuilder put(String key, Object value) {
+ this.parameters.put(key, value);
+
+ return this;
+ }
+
+ protected Map<String, Object> getParameters() {
+ return parameters;
+ }
+
+ /**
+ * Sets value of requestDelay parameter
+ * @param value
+ * @return
+ */
+ public ParametersBuilder requestDelay(double value) {
+ return new ParametersBuilder(this.parameters).put("requestDelay", value);
+ }
+
+ /**
+ * Sets value of similarityGroupingId parameter
+ * @param id
+ * @return
+ */
+ public ParametersBuilder similarityGroupingId(Object id) {
+ return new ParametersBuilder(this.parameters).put("similarityGroupingId", id);
+ }
+
+ /**
+ * Defines how long this request will be executed on server
+ * @param value
+ * @return
+ */
+ public ParametersBuilder requestTime(double value) {
+ return new ParametersBuilder(this.parameters).put("requestTime", value);
+ }
+
+ /**
+ * Sets value of timeout parameter
+ * @param value
+ * @return
+ */
+ public ParametersBuilder timeout(double value) {
+ return new ParametersBuilder(this.parameters).put("timeout", value);
+ }
+
+ /**
+ * Sets value of eventsQueue parameter
+ * @param name
+ * @return
+ */
+ public ParametersBuilder eventsQueue(String name) {
+ return new ParametersBuilder(this.parameters).put("eventsQueue", name);
+ }
+
+ /**
+ * Sets value of implicitEventsQueue parameter
+ * @param name
+ * @return
+ */
+ public ParametersBuilder implicitEventsQueue(String name) {
+ return new ParametersBuilder(this.parameters).put("implicitEventsQueue", name);
+ }
+
+ /**
+ * Sets value of ignoreDupResponses parameter
+ * @param value
+ * @return
+ */
+ public ParametersBuilder ignoreDupResponses(boolean value) {
+ return new ParametersBuilder(this.parameters).put("ignoreDupResponses", value);
+ }
+ }
+
+
+ protected static final class RequestData {
+ private boolean aborted;
+ private String data;
+ private double endTime;
+ private double startTime;
+
+ public RequestData(String data, double startTime, double endTime, boolean aborted) {
+ super();
+ this.data = data;
+ this.startTime = startTime;
+ this.endTime = endTime;
+ this.aborted = aborted;
+ }
+
+ public boolean isAborted() {
+ return aborted;
+ }
+
+ public double getStartTime() {
+ return startTime;
+ }
+
+ public double getEndTime() {
+ return endTime;
+ }
+
+ public String getData() {
+ return data;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+
+ builder.append("data: ");
+ builder.append(data);
+ builder.append(", ");
+ builder.append("startTime: ");
+ builder.append(startTime);
+ builder.append(", ");
+ builder.append("endTime: ");
+ builder.append(endTime);
+
+ if (isAborted()) {
+ builder.append(", aborted: ");
+ builder.append(true);
+ }
+
+ return builder.toString();
+ }
+ }
+
+
+ protected static final class TestsResult {
+ private List<RequestData> dataList = new ArrayList<RequestData>();
+ private double currentTime;
+
+ public void addData(RequestData data) {
+ this.dataList.add(data);
+ }
+
+ public List<RequestData> getDataList() {
+ return dataList;
+ }
+
+ public void setCurrentTime(double number) {
+ this.currentTime = number;
+ }
+
+ public double getCurrentTime() {
+ return currentTime;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+
+ builder.append("[\n");
+
+ for (RequestData data : dataList) {
+ builder.append(" ");
+ builder.append(data);
+ builder.append("\n");
+ }
+
+ builder.append("]\n");
+ builder.append("Current time: " + this.currentTime);
+
+ return builder.toString();
+ }
+ }
+
+
+ ;
}
+
class UnescapingScriptPreprocessor implements ScriptPreProcessor {
+ private static final Map<String, String> ENTITIES_MAP = new HashMap<String, String>();
+ private static final Pattern ENTITIES_PATTERN;
- private static final Map<String, String> ENTITIES_MAP = new HashMap<String, String>();
+ static {
+ ENTITIES_MAP.put("'", "\"");
+ ENTITIES_MAP.put(""", "'");
+ ENTITIES_MAP.put("&", "&");
+ ENTITIES_MAP.put("<", "<");
+ ENTITIES_MAP.put(">", ">");
+ }
- static {
- ENTITIES_MAP.put("'", "\"");
- ENTITIES_MAP.put(""", "'");
- ENTITIES_MAP.put("&", "&");
- ENTITIES_MAP.put("<", "<");
- ENTITIES_MAP.put(">", ">");
- }
+ static {
+ StringBuilder sb = new StringBuilder();
- private static final Pattern ENTITIES_PATTERN;
-
- static {
- StringBuilder sb = new StringBuilder();
-
- for (String entity : ENTITIES_MAP.keySet()) {
- if (sb.length() != 0) {
- sb.append('|');
- }
-
- sb.append(Pattern.quote(entity));
- }
-
- ENTITIES_PATTERN = Pattern.compile("(" + sb.toString() + ")");
- }
-
- public String preProcess(HtmlPage htmlPage, String sourceCode,
- String sourceName, HtmlElement htmlElement) {
+ for (String entity : ENTITIES_MAP.keySet()) {
+ if (sb.length() != 0) {
+ sb.append('|');
+ }
- if (sourceName != null && !sourceName.startsWith("http:/")) {
- Matcher m = ENTITIES_PATTERN.matcher(sourceCode);
- StringBuffer sb = new StringBuffer();
- while (m.find()) {
- String entity = m.group(1);
- m.appendReplacement(sb, ENTITIES_MAP.get(entity));
- }
+ sb.append(Pattern.quote(entity));
+ }
- m.appendTail(sb);
-
- return sb.toString();
- } else {
- return sourceCode;
- }
+ ENTITIES_PATTERN = Pattern.compile("(" + sb.toString() + ")");
+ }
- }
+ public String preProcess(HtmlPage htmlPage, String sourceCode, String sourceName, HtmlElement htmlElement) {
+ if (sourceName != null && !sourceName.startsWith("http:/")) {
+ Matcher m = ENTITIES_PATTERN.matcher(sourceCode);
+ StringBuffer sb = new StringBuffer();
+
+ while (m.find()) {
+ String entity = m.group(1);
+
+ m.appendReplacement(sb, ENTITIES_MAP.get(entity));
+ }
+
+ m.appendTail(sb);
+
+ return sb.toString();
+ } else {
+ return sourceCode;
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/ActionListenerTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/ActionListenerTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/ActionListenerTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.io.Serializable;
@@ -26,6 +28,7 @@
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
+
import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
@@ -41,112 +44,130 @@
*/
public class ActionListenerTest extends AbstractFacesTest {
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- setupFacesRequest();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
+ setupFacesRequest();
+ }
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ /*
+ * (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
- /**
- * Test method for {@link org.ajax4jsf.component.UIActionParameter#getValue()}.
- */
- public void testGetValue() {
- Bean bean = new Bean();
- bean.setFirst(1);
- bean.setSecond(2.0);
- UIActionParameter param = new UIActionParameter();
- param.setConverter(new TestConverter());
- param.setValue(bean);
- assertEquals("1;2.0", param.getValue());
- }
-
- public void testGetIntValue() throws Exception {
- UIActionParameter param = new UIActionParameter();
- application.addConverter(Integer.class, IntegerConverter.class.getName());
- param.setValue(new Integer(1));
- assertEquals("1", param.getValue());
- }
-
- static class TestConverter implements Converter {
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIActionParameter#getValue()}.
+ */
+ public void testGetValue() {
+ Bean bean = new Bean();
- /* (non-Javadoc)
- * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
- */
- public Object getAsObject(FacesContext context, UIComponent comp, String str) {
- Bean bean = new Bean();
- String[] values = str.split(";");
- bean.setFirst(Integer.parseInt(values[0]));
- bean.setSecond(Double.parseDouble(values[1]));
- return bean;
- }
+ bean.setFirst(1);
+ bean.setSecond(2.0);
- /* (non-Javadoc)
- * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
- */
- public String getAsString(FacesContext context, UIComponent comp, Object value) {
- Bean bean = (Bean) value;
- return String.valueOf(bean.getFirst())+";"+String.valueOf(bean.getSecond());
- }
-
- }
-
- public static class Bean implements Serializable {
- int _first;
- double _second;
- /**
- * @return the first
- */
- public int getFirst() {
- return this._first;
- }
- /**
- * @param first the first to set
- */
- public void setFirst(int first) {
- this._first = first;
- }
- /**
- * @return the second
- */
- public double getSecond() {
- return this._second;
- }
- /**
- * @param second the second to set
- */
- public void setSecond(double second) {
- this._second = second;
- }
- }
+ UIActionParameter param = new UIActionParameter();
- /**
- * Test method for {@link org.ajax4jsf.component.UIActionParameter#processAction(javax.faces.event.ActionEvent)}.
- */
- public void testProcessAction() {
- UICommand command = new UICommand();
- UIActionParameter param = new UIActionParameter();
- param.setConverter(new IntegerConverter());
- param.setName("param");
- ELContext elContext = facesContext.getELContext();
- ExpressionFactory expressionFactory = application.getExpressionFactory();
- ValueExpression expression =
- expressionFactory.createValueExpression(elContext, "#{bean.first}", Integer.TYPE);
- param.setAssignToBinding(expression);
- Bean bean = new Bean();
- facesContext.getExternalContext().getRequestMap().put("bean", bean);
- this.connection.addRequestParameter("param", "123");
- command.addActionListener(param);
- command.broadcast(new ActionEvent(command));
- assertEquals(123, bean.getFirst());
- }
+ param.setConverter(new TestConverter());
+ param.setValue(bean);
+ assertEquals("1;2.0", param.getValue());
+ }
+ public void testGetIntValue() throws Exception {
+ UIActionParameter param = new UIActionParameter();
+
+ application.addConverter(Integer.class, IntegerConverter.class.getName());
+ param.setValue(new Integer(1));
+ assertEquals("1", param.getValue());
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIActionParameter#processAction(javax.faces.event.ActionEvent)}.
+ */
+ public void testProcessAction() {
+ UICommand command = new UICommand();
+ UIActionParameter param = new UIActionParameter();
+
+ param.setConverter(new IntegerConverter());
+ param.setName("param");
+
+ ELContext elContext = facesContext.getELContext();
+ ExpressionFactory expressionFactory = application.getExpressionFactory();
+ ValueExpression expression = expressionFactory.createValueExpression(elContext, "#{bean.first}", Integer.TYPE);
+
+ param.setAssignToBinding(expression);
+
+ Bean bean = new Bean();
+
+ facesContext.getExternalContext().getRequestMap().put("bean", bean);
+ this.connection.addRequestParameter("param", "123");
+ command.addActionListener(param);
+ command.broadcast(new ActionEvent(command));
+ assertEquals(123, bean.getFirst());
+ }
+
+ public static class Bean implements Serializable {
+ int _first;
+ double _second;
+
+ /**
+ * @return the first
+ */
+ public int getFirst() {
+ return this._first;
+ }
+
+ /**
+ * @param first the first to set
+ */
+ public void setFirst(int first) {
+ this._first = first;
+ }
+
+ /**
+ * @return the second
+ */
+ public double getSecond() {
+ return this._second;
+ }
+
+ /**
+ * @param second the second to set
+ */
+ public void setSecond(double second) {
+ this._second = second;
+ }
+ }
+
+
+ static class TestConverter implements Converter {
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
+ */
+ public Object getAsObject(FacesContext context, UIComponent comp, String str) {
+ Bean bean = new Bean();
+ String[] values = str.split(";");
+
+ bean.setFirst(Integer.parseInt(values[0]));
+ bean.setSecond(Double.parseDouble(values[1]));
+
+ return bean;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
+ */
+ public String getAsString(FacesContext context, UIComponent comp, Object value) {
+ Bean bean = (Bean) value;
+
+ return String.valueOf(bean.getFirst()) + ";" + String.valueOf(bean.getSecond());
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/AjaxFormQueuesTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/AjaxFormQueuesTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/AjaxFormQueuesTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -20,10 +20,9 @@
*/
+
package org.ajax4jsf.component;
-
-
/**
* @author Nick Belaevski
* @since 3.3.0
@@ -31,36 +30,36 @@
*/
public class AjaxFormQueuesTest extends AbstractQueueComponentTest {
- /**
- * @param name
- */
- public AjaxFormQueuesTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public AjaxFormQueuesTest(String name) {
+ super(name);
+ }
- protected void checkForm(String formName) throws Exception {
- renderView("/queue-ajax-form.xhtml");
- click(formName + ":link");
- executeTimer();
-
- Object resultObject = executeJavaScript("window.testResults." + formName);
-
- assertTrue(formName, resultObject instanceof Boolean && (Boolean) resultObject);
- }
-
- public void testViewDefault() throws Exception {
- checkForm("viewDefault");
- }
-
- public void testViewNamed() throws Exception {
- checkForm("viewNamed");
- }
-
- public void testFormDefault() throws Exception {
- checkForm("formDefault");
- }
-
- public void testFormNamed() throws Exception {
- checkForm("formNamed");
- }
+ protected void checkForm(String formName) throws Exception {
+ renderView("/queue-ajax-form.xhtml");
+ click(formName + ":link");
+ executeTimer();
+
+ Object resultObject = executeJavaScript("window.testResults." + formName);
+
+ assertTrue(formName, resultObject instanceof Boolean && (Boolean) resultObject);
+ }
+
+ public void testViewDefault() throws Exception {
+ checkForm("viewDefault");
+ }
+
+ public void testViewNamed() throws Exception {
+ checkForm("viewNamed");
+ }
+
+ public void testFormDefault() throws Exception {
+ checkForm("formDefault");
+ }
+
+ public void testFormNamed() throws Exception {
+ checkForm("formNamed");
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/DataAdaptorTestCase.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/DataAdaptorTestCase.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/DataAdaptorTestCase.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.ArrayList;
@@ -41,360 +43,386 @@
*
*/
public class DataAdaptorTestCase extends AbstractAjax4JsfTestCase {
-
- private UIDataAdaptor adaptor;
-
- private UIInput child;
-
- private int childInvoked;
-
- private UIInput facetChild;
-
- private int facetInvoked;
+ private UIDataAdaptor adaptor;
+ private UIInput child;
+ private UIInput childChild;
+ private UIInput childChildFacet;
+ private int childChildFacetInvoked;
+ private int childChildInvoked;
+ private int childInvoked;
+ UIData data;
+ private UIInput facetChild;
+ private int facetInvoked;
- private UIInput childChild;
-
- private int childChildInvoked;
+ /**
+ * @param name
+ */
+ public DataAdaptorTestCase(String name) {
+ super(name);
+ }
- private UIInput childChildFacet;
-
- private int childChildFacetInvoked;
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
- UIData data;
- /**
- * @param name
- */
- public DataAdaptorTestCase(String name) {
- super(name);
- }
+ // Create mock DataAdaptor and childs.
+ adaptor = new MockDataAdaptor();
+ child = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ childInvoked++;
+ super.processDecodes(context);
+ }
+ };
+ childInvoked = 0;
+ child.setId("child");
+ adaptor.getChildren().add(child);
+ facetChild = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ facetInvoked++;
+ super.processDecodes(context);
+ }
+ };
+ facetInvoked = 0;
+ facetChild.setId("facetChild");
+ adaptor.getFacets().put("facet", facetChild);
+ childChild = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ childChildInvoked++;
+ super.processDecodes(context);
+ }
+ };;
+ childChildInvoked = 0;
+ childChild.setId("childChild");
+ child.getChildren().add(childChild);
+ childChildFacet = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ childChildFacetInvoked++;
+ super.processDecodes(context);
+ }
+ };;
+ childChildFacetInvoked = 0;
+ childChildFacet.setId("childChildFacet");
+ childChild.getFacets().put("facet", childChildFacet);
+ data = new UIData();
+ renderKit.addRenderer(child.getFamily(), child.getRendererType(), new MockUIInputRenderer());
+ renderKit.addRenderer(adaptor.getFamily(), adaptor.getRendererType(), new MockUIInputRenderer());
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- // Create mock DataAdaptor and childs.
- adaptor = new MockDataAdaptor();
- child = new UIInput(){
- public void processDecodes(FacesContext context) {
- childInvoked++;
- super.processDecodes(context);
- }
- };
- childInvoked = 0;
- child.setId("child");
- adaptor.getChildren().add(child);
- facetChild = new UIInput(){
- public void processDecodes(FacesContext context) {
- facetInvoked++;
- super.processDecodes(context);
- }
- };
- facetInvoked = 0;
- facetChild.setId("facetChild");
- adaptor.getFacets().put("facet", facetChild);
- childChild = new UIInput(){
- public void processDecodes(FacesContext context) {
- childChildInvoked++;
- super.processDecodes(context);
- }
- };;
- childChildInvoked = 0;
- childChild.setId("childChild");
- child.getChildren().add(childChild);
- childChildFacet = new UIInput(){
- public void processDecodes(FacesContext context) {
- childChildFacetInvoked++;
- super.processDecodes(context);
- }
- };;
- childChildFacetInvoked = 0;
- childChildFacet.setId("childChildFacet");
- childChild.getFacets().put("facet", childChildFacet);
- data = new UIData();
- renderKit.addRenderer(child.getFamily(), child.getRendererType(), new MockUIInputRenderer());
- renderKit.addRenderer(adaptor.getFamily(), adaptor.getRendererType(), new MockUIInputRenderer());
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ adaptor = null;
+ child = null;
+ childChild = null;
+ childChildFacet = null;
+ facetChild = null;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- adaptor = null;
- child = null;
- childChild = null;
- childChildFacet = null;
- facetChild = null;
- }
-
- private void createTree(){
- facesContext.getViewRoot().getChildren().add(adaptor);
- adaptor.setId("adaptor");
- }
-
- private void createDataTree(){
- data.setId("data");
- adaptor.setId("adaptor");
- ArrayList value = new ArrayList(2);
- value.add("first");
- value.add("second");
- data.setValue(value);
- data.setVar("var");
- UIColumn column = new UIColumn();
- data.getChildren().add(column);
- column.getChildren().add(adaptor);
- facesContext.getViewRoot().getChildren().add(data);
- }
+ private void createTree() {
+ facesContext.getViewRoot().getChildren().add(adaptor);
+ adaptor.setId("adaptor");
+ }
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#isRowAvailable()}.
- */
- public void testIsRowAvailable() {
- adaptor.setRowKey(new Integer(0));
- assertTrue(adaptor.isRowAvailable());
- adaptor.setRowKey(new Integer(MockDataModel.ROWS-1));
- assertTrue(adaptor.isRowAvailable());
- adaptor.setRowKey(new Integer(MockDataModel.ROWS+1));
- assertFalse(adaptor.isRowAvailable());
- adaptor.setRowKey(null);
- assertFalse(adaptor.isRowAvailable());
- }
+ private void createDataTree() {
+ data.setId("data");
+ adaptor.setId("adaptor");
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#getRowKey()}.
- */
- public void testGetRowKey() {
- adaptor.setRowIndex(0);
- assertEquals(new Integer(0), adaptor.getRowKey());
- adaptor.setRowIndex(-1);
- assertNull(adaptor.getRowKey());
- }
+ ArrayList value = new ArrayList(2);
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#setRowKey(java.lang.Object)}.
- */
- public void testSetRowKey() {
- adaptor.setRowKey(new Integer(1));
- assertEquals(1, adaptor.getRowIndex());
- adaptor.setRowKey(null);
- assertEquals(-1, adaptor.getRowIndex());
- }
+ value.add("first");
+ value.add("second");
+ data.setValue(value);
+ data.setVar("var");
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#resetDataModel()}.
- */
- public void testResetDataModel() {
- adaptor.setRowKey(new Integer(1));
- adaptor.resetDataModel();
- assertEquals(0, adaptor.getRowIndex());
- }
+ UIColumn column = new UIColumn();
- public void testGetBaseClientId(){
- createDataTree();
- data.setRowIndex(-1);
- assertEquals(adaptor.getBaseClientId(facesContext), "data:adaptor");
- data.setRowIndex(0);
- assertEquals(adaptor.getBaseClientId(facesContext), "data:0:adaptor");
- data.setRowIndex(1);
- assertEquals(adaptor.getBaseClientId(facesContext), "data:1:adaptor");
- adaptor.setRowIndex(1);
- assertEquals(adaptor.getBaseClientId(facesContext), "data:1:adaptor");
- }
-
-
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#setExtendedDataModel(org.ajax4jsf.ajax.repeat.ExtendedDataModel)}.
- */
- public void testSetIterableDataModel() {
- createDataTree();
- data.setRowIndex(0);
- MockDataModel mockDataModel0 = new MockDataModel();
- adaptor.setExtendedDataModel(mockDataModel0);
- data.setRowIndex(1);
- MockDataModel mockDataModel1 = new MockDataModel();
- adaptor.setExtendedDataModel(mockDataModel1);
- data.setRowIndex(0);
- assertSame(mockDataModel0, adaptor.getExtendedDataModel());
- data.setRowIndex(1);
- assertSame(mockDataModel1, adaptor.getExtendedDataModel());
- }
-
- public void testSetDataModel(){
- MockDataModel mockDataModel1 = new MockDataModel();
- adaptor.setExtendedDataModel(mockDataModel1);
- assertSame(mockDataModel1, adaptor.getExtendedDataModel());
- }
+ data.getChildren().add(column);
+ column.getChildren().add(adaptor);
+ facesContext.getViewRoot().getChildren().add(data);
+ }
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#getExtendedDataModel()}.
- */
- public void testGetIterableDataModel() {
- ExtendedDataModel dataModel = adaptor.getExtendedDataModel();
- assertTrue(dataModel instanceof MockDataModel);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#isRowAvailable()}.
+ */
+ public void testIsRowAvailable() {
+ adaptor.setRowKey(new Integer(0));
+ assertTrue(adaptor.isRowAvailable());
+ adaptor.setRowKey(new Integer(MockDataModel.ROWS - 1));
+ assertTrue(adaptor.isRowAvailable());
+ adaptor.setRowKey(new Integer(MockDataModel.ROWS + 1));
+ assertFalse(adaptor.isRowAvailable());
+ adaptor.setRowKey(null);
+ assertFalse(adaptor.isRowAvailable());
+ }
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#getComponentState()}.
- */
- public void testGetComponentState() {
- createDataTree();
- data.setRowIndex(0);
- DataComponentState state0 = adaptor.getComponentState();
- assertTrue(state0 instanceof MockComponentState);
- data.setRowIndex(1);
- DataComponentState state1 = adaptor.getComponentState();
- data.setRowIndex(0);
- assertSame(state0, adaptor.getComponentState());
- data.setRowIndex(1);
- assertSame(state1, adaptor.getComponentState());
- }
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#getRowKey()}.
+ */
+ public void testGetRowKey() {
+ adaptor.setRowIndex(0);
+ assertEquals(new Integer(0), adaptor.getRowKey());
+ adaptor.setRowIndex(-1);
+ assertNull(adaptor.getRowKey());
+ }
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#createComponentState()}.
- */
- public void testCreateComponentState() {
- DataComponentState state = adaptor.createComponentState();
- assertTrue(state instanceof MockComponentState);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#setRowKey(java.lang.Object)}.
+ */
+ public void testSetRowKey() {
+ adaptor.setRowKey(new Integer(1));
+ assertEquals(1, adaptor.getRowIndex());
+ adaptor.setRowKey(null);
+ assertEquals(-1, adaptor.getRowIndex());
+ }
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#iterate(javax.faces.context.FacesContext, org.ajax4jsf.ajax.repeat.RepeaterInvoker)}.
- */
- public void testProcess() {
- createTree();
- MockComponentState mockState = (MockComponentState) adaptor.getComponentState();
- mockState.setCount(4);
- adaptor.processDecodes(facesContext);
- assertEquals(childInvoked, 4);
- assertEquals(facetInvoked, 1);
- }
-
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#iterate(javax.faces.context.FacesContext, org.ajax4jsf.ajax.repeat.RepeaterInvoker)}.
- */
- public void testProcessMore() {
- createTree();
- MockComponentState mockState = (MockComponentState) adaptor.getComponentState();
- mockState.setCount(Integer.MAX_VALUE);
- adaptor.processDecodes(facesContext);
- assertEquals(childInvoked, MockDataModel.ROWS);
- assertEquals(facetInvoked, 1);
- }
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#resetDataModel()}.
+ */
+ public void testResetDataModel() {
+ adaptor.setRowKey(new Integer(1));
+ adaptor.resetDataModel();
+ assertEquals(0, adaptor.getRowIndex());
+ }
-
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#restoreState(javax.faces.context.FacesContext, java.lang.Object)}.
- * @throws IllegalAccessException
- * @throws InstantiationException
- */
- public void testRestoreStateFacesContextObject() throws Exception {
- createTree();
- MockComponentState mockState = (MockComponentState) adaptor.getComponentState();
- mockState.setCount(123);
- adaptor.encodeBegin(facesContext);
- UIViewRoot viewRoot = facesContext.getViewRoot();
- Object treeState = viewRoot.processSaveState(facesContext);
- UIViewRoot root = (UIViewRoot) viewRoot.getClass().newInstance();
- UIDataAdaptor restoredAdaptor = new MockDataAdaptor();
- root.getChildren().add(restoredAdaptor);
- root.processRestoreState(facesContext, treeState);
- mockState = (MockComponentState) restoredAdaptor.getComponentState();
- assertEquals(mockState.getCount(), 123);
- }
+ public void testGetBaseClientId() {
+ createDataTree();
+ data.setRowIndex(-1);
+ assertEquals(adaptor.getBaseClientId(facesContext), "data:adaptor");
+ data.setRowIndex(0);
+ assertEquals(adaptor.getBaseClientId(facesContext), "data:0:adaptor");
+ data.setRowIndex(1);
+ assertEquals(adaptor.getBaseClientId(facesContext), "data:1:adaptor");
+ adaptor.setRowIndex(1);
+ assertEquals(adaptor.getBaseClientId(facesContext), "data:1:adaptor");
+ }
- /**
- * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#saveState(javax.faces.context.FacesContext)}.
- */
- public void testSaveStateFacesContext() throws Exception {
- createDataTree();
- data.setRowIndex(0);
- MockComponentState mockState = (MockComponentState) adaptor.getComponentState();
- mockState.setCount(123);
- adaptor.encodeBegin(facesContext);
- data.setRowIndex(1);
- mockState = (MockComponentState) adaptor.getComponentState();
- mockState.setCount(321);
- adaptor.encodeBegin(facesContext);
- UIViewRoot viewRoot = facesContext.getViewRoot();
- Object treeState = viewRoot.processSaveState(facesContext);
- UIViewRoot root = (UIViewRoot) viewRoot.getClass().newInstance();
- UIData restoredData = new UIData();
- UIDataAdaptor restoredAdaptor = new MockDataAdaptor();
- root.getChildren().add(restoredData);
- UIColumn column = new UIColumn();
- restoredData.getChildren().add(column);
- column.getChildren().add(restoredAdaptor);
- root.processRestoreState(facesContext, treeState);
- restoredData.setRowIndex(0);
- mockState = (MockComponentState) restoredAdaptor.getComponentState();
- assertEquals(123,mockState.getCount());
- restoredData.setRowIndex(1);
- mockState = (MockComponentState) restoredAdaptor.getComponentState();
- assertEquals(321,mockState.getCount());
- }
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#setExtendedDataModel(org.ajax4jsf.ajax.repeat.ExtendedDataModel)}.
+ */
+ public void testSetIterableDataModel() {
+ createDataTree();
+ data.setRowIndex(0);
- public void testSaveChildState(){
- createTree();
- child.setSubmittedValue("Submitted");
- child.setValid(true);
- child.setValue("Value");
- child.setLocalValueSet(true);
- adaptor.saveChildState(facesContext);
- child.setSubmittedValue("NonSubmitted");
- child.setValid(false);
- child.setValue(null);
- child.setLocalValueSet(false);
- adaptor.restoreChildState(facesContext);
- assertEquals(child.getSubmittedValue(), "Submitted");
- assertTrue(child.isValid());
- assertEquals(child.getValue(), "Value");
- assertTrue(child.isLocalValueSet());
- }
-
- public void testSaveChildChildState(){
- createTree();
- childChild.setSubmittedValue("Submitted");
- childChild.setValid(true);
- childChild.setValue("Value");
- childChild.setLocalValueSet(true);
- adaptor.saveChildState(facesContext);
- childChild.setSubmittedValue("NonSubmitted");
- childChild.setValid(false);
- childChild.setValue(null);
- childChild.setLocalValueSet(false);
- adaptor.restoreChildState(facesContext);
- assertEquals(childChild.getSubmittedValue(), "Submitted");
- assertTrue(childChild.isValid());
- assertEquals(childChild.getValue(), "Value");
- assertTrue(childChild.isLocalValueSet());
- }
- public void testSaveChildChildFacetState(){
- createTree();
- childChildFacet.setSubmittedValue("Submitted");
- childChildFacet.setValid(true);
- childChildFacet.setValue("Value");
- childChildFacet.setLocalValueSet(true);
- adaptor.saveChildState(facesContext);
- childChildFacet.setSubmittedValue("NonSubmitted");
- childChildFacet.setValid(false);
- childChildFacet.setValue(null);
- childChildFacet.setLocalValueSet(false);
- adaptor.restoreChildState(facesContext);
- assertEquals(childChildFacet.getSubmittedValue(), "Submitted");
- assertTrue(childChildFacet.isValid());
- assertEquals(childChildFacet.getValue(), "Value");
- assertTrue(childChildFacet.isLocalValueSet());
- }
-
- public void testSetValue() {
- ExtendedDataModel model1 = adaptor.getExtendedDataModel();
- adaptor.setValue("value");
- ExtendedDataModel model2 = adaptor.getExtendedDataModel();
- assertNotSame(model1, model2);
-
- Object value = adaptor.getValue();
- assertNotNull(value);
- assertEquals("value", value);
- }
+ MockDataModel mockDataModel0 = new MockDataModel();
+
+ adaptor.setExtendedDataModel(mockDataModel0);
+ data.setRowIndex(1);
+
+ MockDataModel mockDataModel1 = new MockDataModel();
+
+ adaptor.setExtendedDataModel(mockDataModel1);
+ data.setRowIndex(0);
+ assertSame(mockDataModel0, adaptor.getExtendedDataModel());
+ data.setRowIndex(1);
+ assertSame(mockDataModel1, adaptor.getExtendedDataModel());
+ }
+
+ public void testSetDataModel() {
+ MockDataModel mockDataModel1 = new MockDataModel();
+
+ adaptor.setExtendedDataModel(mockDataModel1);
+ assertSame(mockDataModel1, adaptor.getExtendedDataModel());
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#getExtendedDataModel()}.
+ */
+ public void testGetIterableDataModel() {
+ ExtendedDataModel dataModel = adaptor.getExtendedDataModel();
+
+ assertTrue(dataModel instanceof MockDataModel);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#getComponentState()}.
+ */
+ public void testGetComponentState() {
+ createDataTree();
+ data.setRowIndex(0);
+
+ DataComponentState state0 = adaptor.getComponentState();
+
+ assertTrue(state0 instanceof MockComponentState);
+ data.setRowIndex(1);
+
+ DataComponentState state1 = adaptor.getComponentState();
+
+ data.setRowIndex(0);
+ assertSame(state0, adaptor.getComponentState());
+ data.setRowIndex(1);
+ assertSame(state1, adaptor.getComponentState());
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#createComponentState()}.
+ */
+ public void testCreateComponentState() {
+ DataComponentState state = adaptor.createComponentState();
+
+ assertTrue(state instanceof MockComponentState);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#iterate(javax.faces.context.FacesContext, org.ajax4jsf.ajax.repeat.RepeaterInvoker)}.
+ */
+ public void testProcess() {
+ createTree();
+
+ MockComponentState mockState = (MockComponentState) adaptor.getComponentState();
+
+ mockState.setCount(4);
+ adaptor.processDecodes(facesContext);
+ assertEquals(childInvoked, 4);
+ assertEquals(facetInvoked, 1);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#iterate(javax.faces.context.FacesContext, org.ajax4jsf.ajax.repeat.RepeaterInvoker)}.
+ */
+ public void testProcessMore() {
+ createTree();
+
+ MockComponentState mockState = (MockComponentState) adaptor.getComponentState();
+
+ mockState.setCount(Integer.MAX_VALUE);
+ adaptor.processDecodes(facesContext);
+ assertEquals(childInvoked, MockDataModel.ROWS);
+ assertEquals(facetInvoked, 1);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#restoreState(javax.faces.context.FacesContext, java.lang.Object)}.
+ * @throws IllegalAccessException
+ * @throws InstantiationException
+ */
+ public void testRestoreStateFacesContextObject() throws Exception {
+ createTree();
+
+ MockComponentState mockState = (MockComponentState) adaptor.getComponentState();
+
+ mockState.setCount(123);
+ adaptor.encodeBegin(facesContext);
+
+ UIViewRoot viewRoot = facesContext.getViewRoot();
+ Object treeState = viewRoot.processSaveState(facesContext);
+ UIViewRoot root = (UIViewRoot) viewRoot.getClass().newInstance();
+ UIDataAdaptor restoredAdaptor = new MockDataAdaptor();
+
+ root.getChildren().add(restoredAdaptor);
+ root.processRestoreState(facesContext, treeState);
+ mockState = (MockComponentState) restoredAdaptor.getComponentState();
+ assertEquals(mockState.getCount(), 123);
+ }
+
+ /**
+ * Test method for {@link org.ajax4jsf.component.UIDataAdaptor#saveState(javax.faces.context.FacesContext)}.
+ */
+ public void testSaveStateFacesContext() throws Exception {
+ createDataTree();
+ data.setRowIndex(0);
+
+ MockComponentState mockState = (MockComponentState) adaptor.getComponentState();
+
+ mockState.setCount(123);
+ adaptor.encodeBegin(facesContext);
+ data.setRowIndex(1);
+ mockState = (MockComponentState) adaptor.getComponentState();
+ mockState.setCount(321);
+ adaptor.encodeBegin(facesContext);
+
+ UIViewRoot viewRoot = facesContext.getViewRoot();
+ Object treeState = viewRoot.processSaveState(facesContext);
+ UIViewRoot root = (UIViewRoot) viewRoot.getClass().newInstance();
+ UIData restoredData = new UIData();
+ UIDataAdaptor restoredAdaptor = new MockDataAdaptor();
+
+ root.getChildren().add(restoredData);
+
+ UIColumn column = new UIColumn();
+
+ restoredData.getChildren().add(column);
+ column.getChildren().add(restoredAdaptor);
+ root.processRestoreState(facesContext, treeState);
+ restoredData.setRowIndex(0);
+ mockState = (MockComponentState) restoredAdaptor.getComponentState();
+ assertEquals(123, mockState.getCount());
+ restoredData.setRowIndex(1);
+ mockState = (MockComponentState) restoredAdaptor.getComponentState();
+ assertEquals(321, mockState.getCount());
+ }
+
+ public void testSaveChildState() {
+ createTree();
+ child.setSubmittedValue("Submitted");
+ child.setValid(true);
+ child.setValue("Value");
+ child.setLocalValueSet(true);
+ adaptor.saveChildState(facesContext);
+ child.setSubmittedValue("NonSubmitted");
+ child.setValid(false);
+ child.setValue(null);
+ child.setLocalValueSet(false);
+ adaptor.restoreChildState(facesContext);
+ assertEquals(child.getSubmittedValue(), "Submitted");
+ assertTrue(child.isValid());
+ assertEquals(child.getValue(), "Value");
+ assertTrue(child.isLocalValueSet());
+ }
+
+ public void testSaveChildChildState() {
+ createTree();
+ childChild.setSubmittedValue("Submitted");
+ childChild.setValid(true);
+ childChild.setValue("Value");
+ childChild.setLocalValueSet(true);
+ adaptor.saveChildState(facesContext);
+ childChild.setSubmittedValue("NonSubmitted");
+ childChild.setValid(false);
+ childChild.setValue(null);
+ childChild.setLocalValueSet(false);
+ adaptor.restoreChildState(facesContext);
+ assertEquals(childChild.getSubmittedValue(), "Submitted");
+ assertTrue(childChild.isValid());
+ assertEquals(childChild.getValue(), "Value");
+ assertTrue(childChild.isLocalValueSet());
+ }
+
+ public void testSaveChildChildFacetState() {
+ createTree();
+ childChildFacet.setSubmittedValue("Submitted");
+ childChildFacet.setValid(true);
+ childChildFacet.setValue("Value");
+ childChildFacet.setLocalValueSet(true);
+ adaptor.saveChildState(facesContext);
+ childChildFacet.setSubmittedValue("NonSubmitted");
+ childChildFacet.setValid(false);
+ childChildFacet.setValue(null);
+ childChildFacet.setLocalValueSet(false);
+ adaptor.restoreChildState(facesContext);
+ assertEquals(childChildFacet.getSubmittedValue(), "Submitted");
+ assertTrue(childChildFacet.isValid());
+ assertEquals(childChildFacet.getValue(), "Value");
+ assertTrue(childChildFacet.isLocalValueSet());
+ }
+
+ public void testSetValue() {
+ ExtendedDataModel model1 = adaptor.getExtendedDataModel();
+
+ adaptor.setValue("value");
+
+ ExtendedDataModel model2 = adaptor.getExtendedDataModel();
+
+ assertNotSame(model1, model2);
+
+ Object value = adaptor.getValue();
+
+ assertNotNull(value);
+ assertEquals("value", value);
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/ImplicitQueuesTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/ImplicitQueuesTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/ImplicitQueuesTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,11 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.List;
-
/**
* @author Nick Belaevski
* @since 3.3.0
@@ -31,85 +32,83 @@
*/
public class ImplicitQueuesTest extends AbstractQueueComponentTest {
- /**
- * @param name
- */
- public ImplicitQueuesTest(String name) {
- super(name);
- }
-
- public void testImplicitGlobalQueueEnabled() throws Exception {
- servletContext.addInitParameter("org.richfaces.queue.global.enabled", "true");
+ /**
+ * @param name
+ */
+ public ImplicitQueuesTest(String name) {
+ super(name);
+ }
- renderView();
-
- ajax(0, "a", createAjaxParameters().requestTime(1000));
- ajax(0, "b", createAjaxParameters().requestTime(1000));
-
- TestsResult result = getTestsResult();
- assertEquals(2000d, result.getCurrentTime());
- }
+ public void testImplicitGlobalQueueEnabled() throws Exception {
+ servletContext.addInitParameter("org.richfaces.queue.global.enabled", "true");
+ renderView();
+ ajax(0, "a", createAjaxParameters().requestTime(1000));
+ ajax(0, "b", createAjaxParameters().requestTime(1000));
- public void testImplicitGlobalQueueDefault() throws Exception {
- renderView();
-
- ajax(0, "a", createAjaxParameters().requestTime(1000));
- ajax(0, "b", createAjaxParameters().requestTime(1000));
-
- TestsResult result = getTestsResult();
- assertEquals(1000d, result.getCurrentTime());
- }
-
- public void testLegacyQueuesRequestDelay() throws Exception {
- renderView("/queue-legacy.xhtml");
+ TestsResult result = getTestsResult();
- clickOnTime(0, "form:buttonDelayed");
- clickOnTime(500, "form:buttonDelayed");
- clickOnTime(750, "form:buttonDelayed");
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
- assertEquals(1, dataList.size());
-
- //request time set to 5000 in .xhtml file
- RequestData data = dataList.get(0);
- checkRequestData(data, "form:buttonDelayed", 1750, 6750, false);
-
- assertEquals(6750d, result.getCurrentTime());
- }
+ assertEquals(2000d, result.getCurrentTime());
+ }
- public void testLegacyQueuesIgnoreDupResponces() throws Exception {
- renderView("/queue-legacy.xhtml");
+ public void testImplicitGlobalQueueDefault() throws Exception {
+ renderView();
+ ajax(0, "a", createAjaxParameters().requestTime(1000));
+ ajax(0, "b", createAjaxParameters().requestTime(1000));
- clickOnTime(0, "form:buttonIgnoreDupResponces");
- clickOnTime(500, "form:buttonIgnoreDupResponces");
-
- executeTimer();
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
+ TestsResult result = getTestsResult();
- //RF-5788
- //assertEquals(3, dataList.size());
- assertEquals(2, dataList.size());
-
- //request time set to 5000 in .xhtml file
- checkRequestData(dataList.get(0), "form:buttonIgnoreDupResponces", 0, 5000, false);
- checkRequestData(dataList.get(1), "form:buttonIgnoreDupResponces", 5000, 10000, false);
+ assertEquals(1000d, result.getCurrentTime());
+ }
- //RF-5788
- //checkRequestData(dataList.get(2), "form:buttonIgnoreDupResponces", 750, 5750, false);
-
- //RF-5788
- //assertEquals(5750d, result.getCurrentTime());
- assertEquals(10000d, result.getCurrentTime());
+ public void testLegacyQueuesRequestDelay() throws Exception {
+ renderView("/queue-legacy.xhtml");
+ clickOnTime(0, "form:buttonDelayed");
+ clickOnTime(500, "form:buttonDelayed");
+ clickOnTime(750, "form:buttonDelayed");
- Double requestsCompletedCounter = (Double) executeJavaScript("counter");
- assertEquals(1d, requestsCompletedCounter);
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
- Double requestsCompletionTime = (Double) executeJavaScript("time");
+ assertEquals(1, dataList.size());
- //RF-5788
- //assertEquals(5750d, requestsCompletionTime);
- assertEquals(10000d, requestsCompletionTime);
- }
+ // request time set to 5000 in .xhtml file
+ RequestData data = dataList.get(0);
+
+ checkRequestData(data, "form:buttonDelayed", 1750, 6750, false);
+ assertEquals(6750d, result.getCurrentTime());
+ }
+
+ public void testLegacyQueuesIgnoreDupResponces() throws Exception {
+ renderView("/queue-legacy.xhtml");
+ clickOnTime(0, "form:buttonIgnoreDupResponces");
+ clickOnTime(500, "form:buttonIgnoreDupResponces");
+ executeTimer();
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ // RF-5788
+ // assertEquals(3, dataList.size());
+ assertEquals(2, dataList.size());
+
+ // request time set to 5000 in .xhtml file
+ checkRequestData(dataList.get(0), "form:buttonIgnoreDupResponces", 0, 5000, false);
+ checkRequestData(dataList.get(1), "form:buttonIgnoreDupResponces", 5000, 10000, false);
+
+ // RF-5788
+ // checkRequestData(dataList.get(2), "form:buttonIgnoreDupResponces", 750, 5750, false);
+ // RF-5788
+ // assertEquals(5750d, result.getCurrentTime());
+ assertEquals(10000d, result.getCurrentTime());
+
+ Double requestsCompletedCounter = (Double) executeJavaScript("counter");
+
+ assertEquals(1d, requestsCompletedCounter);
+
+ Double requestsCompletionTime = (Double) executeJavaScript("time");
+
+ // RF-5788
+ // assertEquals(5750d, requestsCompletionTime);
+ assertEquals(10000d, requestsCompletionTime);
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/IncludeComponentTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/IncludeComponentTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/IncludeComponentTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,68 +19,66 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import javax.faces.component.UIForm;
import javax.faces.component.html.HtmlForm;
public class IncludeComponentTest extends org.ajax4jsf.tests.AbstractAjax4JsfTestCase {
- private UIInclude include = null;
- private UIForm form = null;
+ private UIForm form = null;
+ private UIInclude include = null;
- public IncludeComponentTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
-
- form = new HtmlForm();
- form.setId("form");
- facesContext.getViewRoot().getChildren().add(form);
-
- include = (UIInclude) application.createComponent(UIInclude.COMPONENT_TYPE);
- include.setId("include");
- include.setLayout(UIInclude.LAYOUT_NONE);
-
- form.getChildren().add(include);
-
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
-
- form = null;
- include = null;
- }
-
- public void testState() throws Exception {
-
- }
-
- public void testViewId() throws Exception {
- include.setViewId(null);
- assertNull(include.getViewId());
-
- String viewId = "viewId";
- include.setViewId(viewId);
- String newViewId = include.getViewId();
- assertNotNull(newViewId);
- assertEquals(viewId, newViewId);
- }
-
- public void testLayout() throws Exception {
- include.setLayout(null);
- assertNull(include.getLayout());
-
- include.setLayout(UIInclude.LAYOUT_BLOCK);
- String newLayout = include.getLayout();
- assertNotNull(newLayout);
- assertEquals(UIInclude.LAYOUT_BLOCK, newLayout);
- }
-
- public void testAjaxRendered() throws Exception {
- assertFalse(include.isAjaxRendered());
- }
-
+ public IncludeComponentTest(String name) {
+ super(name);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ form = new HtmlForm();
+ form.setId("form");
+ facesContext.getViewRoot().getChildren().add(form);
+ include = (UIInclude) application.createComponent(UIInclude.COMPONENT_TYPE);
+ include.setId("include");
+ include.setLayout(UIInclude.LAYOUT_NONE);
+ form.getChildren().add(include);
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ form = null;
+ include = null;
+ }
+
+ public void testState() throws Exception {}
+
+ public void testViewId() throws Exception {
+ include.setViewId(null);
+ assertNull(include.getViewId());
+
+ String viewId = "viewId";
+
+ include.setViewId(viewId);
+
+ String newViewId = include.getViewId();
+
+ assertNotNull(newViewId);
+ assertEquals(viewId, newViewId);
+ }
+
+ public void testLayout() throws Exception {
+ include.setLayout(null);
+ assertNull(include.getLayout());
+ include.setLayout(UIInclude.LAYOUT_BLOCK);
+
+ String newLayout = include.getLayout();
+
+ assertNotNull(newLayout);
+ assertEquals(UIInclude.LAYOUT_BLOCK, newLayout);
+ }
+
+ public void testAjaxRendered() throws Exception {
+ assertFalse(include.isAjaxRendered());
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/LoadBundleComponentTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/LoadBundleComponentTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/LoadBundleComponentTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.HashMap;
@@ -30,115 +32,104 @@
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class LoadBundleComponentTest extends org.ajax4jsf.tests.AbstractAjax4JsfTestCase {
- private UIForm form;
- private UILoadBundle bundle = null;
- private static final String BUNDLE_NAME = "testBundle";
+ private static final String BUNDLE_NAME = "testBundle";
+ private UILoadBundle bundle = null;
+ private UIForm form;
- public LoadBundleComponentTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
-
- form = new HtmlForm();
- form.setId("form");
- facesContext.getViewRoot().getChildren().add(form);
-
- bundle = (UILoadBundle) application.createComponent(UILoadBundle.COMPONENT_TYPE);
- if (null != bundle) {
- bundle.setId("loadBundle");
- bundle.setVar(BUNDLE_NAME);
- bundle.setBasename("org.ajax4jsf.component.test_skin");
- form.getChildren().add(bundle);
- }
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
-
- form = null;
- bundle = null;
+ public LoadBundleComponentTest(String name) {
+ super(name);
}
- public void testLoadBundle() throws Exception {
- HtmlPage page = renderView();
+ public void setUp() throws Exception {
+ super.setUp();
+ form = new HtmlForm();
+ form.setId("form");
+ facesContext.getViewRoot().getChildren().add(form);
+ bundle = (UILoadBundle) application.createComponent(UILoadBundle.COMPONENT_TYPE);
+
+ if (null != bundle) {
+ bundle.setId("loadBundle");
+ bundle.setVar(BUNDLE_NAME);
+ bundle.setBasename("org.ajax4jsf.component.test_skin");
+ form.getChildren().add(bundle);
+ }
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ form = null;
+ bundle = null;
+ }
+
+ public void testLoadBundle() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
-
- Map loadedMap = (Map)facesContext.getExternalContext().getRequestMap().get(BUNDLE_NAME);
+
+ Map loadedMap = (Map) facesContext.getExternalContext().getRequestMap().get(BUNDLE_NAME);
+
assertNotNull(loadedMap);
-
assertEquals("non-existent key", loadedMap.get("non-existent key"));
-
assertEquals("#000000", loadedMap.get("shadowBackgroundColor"));
- }
-
- public void testSize() throws Exception {
- HtmlPage page = renderView();
+ }
+
+ public void testSize() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
-
- Map loadedMap = (Map)facesContext.getExternalContext().getRequestMap().get(BUNDLE_NAME);
+
+ Map loadedMap = (Map) facesContext.getExternalContext().getRequestMap().get(BUNDLE_NAME);
+
assertNotNull(loadedMap);
-
assertEquals(0, loadedMap.size());
- }
-
- public void testContainsKey() throws Exception {
- HtmlPage page = renderView();
+ }
+
+ public void testContainsKey() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
-
- Map loadedMap = (Map)facesContext.getExternalContext().getRequestMap().get(BUNDLE_NAME);
+
+ Map loadedMap = (Map) facesContext.getExternalContext().getRequestMap().get(BUNDLE_NAME);
+
assertNotNull(loadedMap);
-
assertTrue(loadedMap.containsKey("shadowBackgroundColor"));
-
assertFalse(loadedMap.containsKey("non-existent key"));
- }
-
- public void testFakeFunctions() throws Exception {
- HtmlPage page = renderView();
+ }
+
+ public void testFakeFunctions() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
-
- Map loadedMap = (Map)facesContext.getExternalContext().getRequestMap().get(BUNDLE_NAME);
+
+ Map loadedMap = (Map) facesContext.getExternalContext().getRequestMap().get(BUNDLE_NAME);
+
assertNotNull(loadedMap);
-
assertFalse(loadedMap.isEmpty());
-
assertFalse(loadedMap.containsValue(null));
assertFalse(loadedMap.containsValue("any-string"));
-
+
try {
- loadedMap.put("key1", "value1");
- assertFalse("UnsupportedOperationException was not thrown", true);
- } catch (UnsupportedOperationException e) {
-
- }
-
+ loadedMap.put("key1", "value1");
+ assertFalse("UnsupportedOperationException was not thrown", true);
+ } catch (UnsupportedOperationException e) {}
+
try {
- loadedMap.putAll(new HashMap());
- assertFalse("UnsupportedOperationException was not thrown", true);
- } catch (UnsupportedOperationException e) {
-
- }
-
+ loadedMap.putAll(new HashMap());
+ assertFalse("UnsupportedOperationException was not thrown", true);
+ } catch (UnsupportedOperationException e) {}
+
try {
- loadedMap.remove("key1");
- assertFalse("UnsupportedOperationException was not thrown", true);
- } catch (UnsupportedOperationException e) {
-
- }
-
+ loadedMap.remove("key1");
+ assertFalse("UnsupportedOperationException was not thrown", true);
+ } catch (UnsupportedOperationException e) {}
+
try {
- loadedMap.clear();
- assertFalse("UnsupportedOperationException was not thrown", true);
- } catch (UnsupportedOperationException e) {
-
- }
-
+ loadedMap.clear();
+ assertFalse("UnsupportedOperationException was not thrown", true);
+ } catch (UnsupportedOperationException e) {}
+
assertNull(loadedMap.keySet());
-
assertNull(loadedMap.values());
-
assertNull(loadedMap.entrySet());
- }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/LoadResourceComponentTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/LoadResourceComponentTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/LoadResourceComponentTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,11 +19,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import static org.ajax4jsf.resource.InternetResource.RESOURCE_URI_PREFIX;
import java.io.IOException;
+
import java.util.Collections;
import java.util.List;
@@ -49,316 +52,317 @@
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class LoadResourceComponentTest extends AbstractAjax4JsfTestCase {
+ private String componentJs;
+ private String componentXcss;
+ private String userJs;
+ private String userXcss;
- private String componentJs;
- private String userJs;
+ /**
+ * @param name
+ */
+ public LoadResourceComponentTest(String name) {
+ super(name);
+ }
- private String componentXcss;
- private String userXcss;
+ private void registerResource(String path) {
+ InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
- /**
- * @param name
- */
- public LoadResourceComponentTest(String name) {
- super(name);
- }
-
- private void registerResource(String path) {
- InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
+ try {
+ resourceBuilder.getResource(path);
+ } catch (ResourceNotFoundException e) {
+ resourceBuilder.createResource(null, path);
+ }
+ }
- try {
- resourceBuilder.getResource(path);
- } catch (ResourceNotFoundException e) {
- resourceBuilder.createResource(null, path);
- }
- }
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ renderKit.addRenderer(ResourceDependentComponent.COMPONENT_FAMILY, ResourceDependentComponent.COMPONENT_TYPE,
+ new ResourceDependentComponentRenderer());
- @Override
- public void setUp() throws Exception {
- super.setUp();
- renderKit.addRenderer(ResourceDependentComponent.COMPONENT_FAMILY,
- ResourceDependentComponent.COMPONENT_TYPE, new ResourceDependentComponentRenderer());
-
- String resourcePackage = getClass().getPackage().getName().replace('.', '/') + "/";
- componentJs = resourcePackage + "component.js";
- componentXcss = resourcePackage + "component.xcss";
-
- userJs = resourcePackage + "user.js";
- userXcss = resourcePackage + "user.xcss";
-
- registerResource(componentJs);
- registerResource(userJs);
- registerResource(componentXcss);
- registerResource(userXcss);
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
-
- componentJs = null;
- userJs = null;
-
- componentXcss = null;
- userXcss = null;
- }
-
- private UIResource createLoadScriptComponent() {
- return (UIResource) application.createComponent("org.ajax4jsf.LoadScript");
- }
+ String resourcePackage = getClass().getPackage().getName().replace('.', '/') + "/";
- private UIResource createLoadStyleComponent() {
- return (UIResource) application.createComponent("org.ajax4jsf.LoadStyle");
- }
-
- private List<HtmlScript> selectScriptsBySrc(HtmlPage page, String src) throws Exception {
- return Collections.checkedList(page.getByXPath("//script[@src[contains(string(.), '" + src + "')]]"),
- HtmlScript.class);
- }
-
- private List<HtmlLink> selectStylesByHhref(HtmlPage page, String src) throws Exception {
- return Collections.checkedList(page.getByXPath("//link[@type = 'text/css'][@rel = 'stylesheet'][@href[contains(string(.), '" + src + "')]]"),
- HtmlLink.class);
- }
+ componentJs = resourcePackage + "component.js";
+ componentXcss = resourcePackage + "component.xcss";
+ userJs = resourcePackage + "user.js";
+ userXcss = resourcePackage + "user.xcss";
+ registerResource(componentJs);
+ registerResource(userJs);
+ registerResource(componentXcss);
+ registerResource(userXcss);
+ }
- protected UIResource createAndAddScriptResource(Object src) {
- UIResource scriptComponent = createLoadScriptComponent();
- scriptComponent.setSrc(src);
- facesContext.getViewRoot().getChildren().add(scriptComponent);
-
- return scriptComponent;
- }
-
- protected UIResource createAndAddStyleResource(Object src) {
- UIResource styleComponent = createLoadStyleComponent();
- styleComponent.setSrc(src);
- facesContext.getViewRoot().getChildren().add(styleComponent);
-
- return styleComponent;
- }
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ componentJs = null;
+ userJs = null;
+ componentXcss = null;
+ userXcss = null;
+ }
- public void testRenderScript() throws Exception {
- createAndAddScriptResource(RESOURCE_URI_PREFIX + userJs);
- createAndAddScriptResource(RESOURCE_URI_PREFIX + componentJs).setRendered(false);
-
- HtmlPage page = renderView();
- List<HtmlScript> scripts;
-
- scripts = selectScriptsBySrc(page, userJs);
- assertEquals(1, scripts.size());
+ private UIResource createLoadScriptComponent() {
+ return (UIResource) application.createComponent("org.ajax4jsf.LoadScript");
+ }
- scripts = selectScriptsBySrc(page, componentJs);
- assertEquals(0, scripts.size());
- }
-
- public void testRenderScriptResource() throws Exception {
- InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
- createAndAddScriptResource(resourceBuilder.getResourceForKey(userJs));
- createAndAddScriptResource(resourceBuilder.getResourceForKey(componentJs)).setRendered(false);
+ private UIResource createLoadStyleComponent() {
+ return (UIResource) application.createComponent("org.ajax4jsf.LoadStyle");
+ }
- HtmlPage page = renderView();
- List<HtmlScript> scripts;
-
- scripts = selectScriptsBySrc(page, userJs);
- assertEquals(1, scripts.size());
+ private List<HtmlScript> selectScriptsBySrc(HtmlPage page, String src) throws Exception {
+ return Collections.checkedList(page.getByXPath("//script[@src[contains(string(.), '" + src + "')]]"),
+ HtmlScript.class);
+ }
- scripts = selectScriptsBySrc(page, componentJs);
- assertEquals(1, scripts.size());
- }
-
- public void testRenderStyle() throws Exception {
- createAndAddStyleResource(RESOURCE_URI_PREFIX + userXcss);
- createAndAddStyleResource(RESOURCE_URI_PREFIX + componentXcss).setRendered(false);
-
- HtmlPage page = renderView();
- List<HtmlLink> styles;
- HtmlLink userLink;
-
- styles = selectStylesByHhref(page, userXcss);
- assertEquals(1, styles.size());
- userLink = styles.get(0);
- assertEquals("user", userLink.getClassAttribute());
- assertEquals("", userLink.getMediaAttribute());
+ private List<HtmlLink> selectStylesByHhref(HtmlPage page, String src) throws Exception {
+ return Collections.checkedList(
+ page.getByXPath(
+ "//link[@type = 'text/css'][@rel = 'stylesheet'][@href[contains(string(.), '" + src
+ + "')]]"), HtmlLink.class);
+ }
- styles = selectStylesByHhref(page, componentXcss);
- assertEquals(0, styles.size());
- }
-
- public void testRenderStyleResource() throws Exception {
- InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
- createAndAddStyleResource(resourceBuilder.getResourceForKey(userXcss));
- createAndAddStyleResource(resourceBuilder.getResourceForKey(componentXcss)).setRendered(false);
+ protected UIResource createAndAddScriptResource(Object src) {
+ UIResource scriptComponent = createLoadScriptComponent();
- UIResource styleComponent = createLoadStyleComponent();
- styleComponent.setSrc(InternetResourceBuilder.getInstance().getResourceForKey(userXcss));
- facesContext.getViewRoot().getChildren().add(styleComponent);
-
- HtmlPage page = renderView();
- List<HtmlLink> styles;
- HtmlLink userLink;
-
- styles = selectStylesByHhref(page, userXcss);
- assertEquals(1, styles.size());
- userLink = styles.get(0);
- assertEquals("user", userLink.getClassAttribute());
- assertEquals("", userLink.getMediaAttribute());
+ scriptComponent.setSrc(src);
+ facesContext.getViewRoot().getChildren().add(scriptComponent);
- styles = selectStylesByHhref(page, componentXcss);
- assertEquals(1, styles.size());
- userLink = styles.get(0);
- assertEquals("user", userLink.getClassAttribute());
- assertEquals("", userLink.getMediaAttribute());
- }
-
- public void testRenderMedia() throws Exception {
- createAndAddStyleResource(RESOURCE_URI_PREFIX + userXcss).
- getAttributes().put(HTML.media_ATTRIBUTE, "screen print");
-
- HtmlPage page = renderView();
- List<HtmlLink> styles = selectStylesByHhref(page, userXcss);
- assertEquals(1, styles.size());
- HtmlLink userLink = styles.get(0);
- assertEquals("user", userLink.getClassAttribute());
- assertEquals("screen print", userLink.getMediaAttribute());
- }
-
- public void testRenderOverridenScript() throws Exception {
- List<UIComponent> childrenList = facesContext.getViewRoot().getChildren();
+ return scriptComponent;
+ }
- UIResource userJsComponent = createLoadScriptComponent();
- userJsComponent.setSrc(RESOURCE_URI_PREFIX + userJs);
- childrenList.add(userJsComponent);
-
- InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
-
- childrenList.add(new ResourceDependentComponent(true,
- resourceBuilder.getResourceForKey(componentJs),
- resourceBuilder.getResourceForKey(userJs)));
+ protected UIResource createAndAddStyleResource(Object src) {
+ UIResource styleComponent = createLoadStyleComponent();
- UIResource componentJsComponent = createLoadScriptComponent();
- componentJsComponent.setSrc(RESOURCE_URI_PREFIX + componentJs);
- childrenList.add(componentJsComponent);
-
- HtmlPage page = renderView();
- List<HtmlScript> userScripts = selectScriptsBySrc(page, userJs);
- assertEquals(1, userScripts.size());
- List<HtmlScript> componentScripts = selectScriptsBySrc(page, componentJs);
- assertEquals(1, componentScripts.size());
- }
-
- public void testRenderOverridenStyle() throws Exception {
- List<UIComponent> childrenList = facesContext.getViewRoot().getChildren();
+ styleComponent.setSrc(src);
+ facesContext.getViewRoot().getChildren().add(styleComponent);
- UIResource userXcssComponent = createLoadStyleComponent();
- userXcssComponent.setSrc(RESOURCE_URI_PREFIX + userXcss);
- childrenList.add(userXcssComponent);
-
- InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
-
- childrenList.add(new ResourceDependentComponent(false,
- resourceBuilder.getResourceForKey(componentXcss),
- resourceBuilder.getResourceForKey(userXcss)));
-
- UIResource componentXcssComponent = createLoadStyleComponent();
- componentXcssComponent.setSrc(RESOURCE_URI_PREFIX + componentXcss);
- childrenList.add(componentXcssComponent);
-
- HtmlPage page = renderView();
- List<HtmlLink> styles = selectStylesByHhref(page, userXcss);
- assertEquals(2, styles.size());
- assertEquals("component", styles.get(0).getClassAttribute());
- assertEquals("user", styles.get(1).getClassAttribute());
+ return styleComponent;
+ }
- styles = selectStylesByHhref(page, componentXcss);
- assertEquals(2, styles.size());
- assertEquals("component", styles.get(0).getClassAttribute());
- assertEquals("user", styles.get(1).getClassAttribute());
- }
-
- public void testRenderOverridenAjaxScript() throws Exception {
- UIResource userComponent = createLoadScriptComponent();
- userComponent.setSrc(RESOURCE_URI_PREFIX + "/org/ajax4jsf/javascript/scripts/AJAX.js");
-
- List<UIComponent> childrenList = facesContext.getViewRoot().getChildren();
- childrenList.add(userComponent);
-
- childrenList.add(new ResourceDependentComponent(true, new AjaxScript()));
-
- HtmlPage page = renderView();
- List<HtmlScript> scripts = selectScriptsBySrc(page, "AjaxScript");
- assertEquals(1, scripts.size());
+ public void testRenderScript() throws Exception {
+ createAndAddScriptResource(RESOURCE_URI_PREFIX + userJs);
+ createAndAddScriptResource(RESOURCE_URI_PREFIX + componentJs).setRendered(false);
- scripts = selectScriptsBySrc(page, "AJAX.js");
- //TODO change to 0 after related issue resolution
- assertEquals(1, scripts.size());
- }
+ HtmlPage page = renderView();
+ List<HtmlScript> scripts;
+
+ scripts = selectScriptsBySrc(page, userJs);
+ assertEquals(1, scripts.size());
+ scripts = selectScriptsBySrc(page, componentJs);
+ assertEquals(0, scripts.size());
+ }
+
+ public void testRenderScriptResource() throws Exception {
+ InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
+
+ createAndAddScriptResource(resourceBuilder.getResourceForKey(userJs));
+ createAndAddScriptResource(resourceBuilder.getResourceForKey(componentJs)).setRendered(false);
+
+ HtmlPage page = renderView();
+ List<HtmlScript> scripts;
+
+ scripts = selectScriptsBySrc(page, userJs);
+ assertEquals(1, scripts.size());
+ scripts = selectScriptsBySrc(page, componentJs);
+ assertEquals(1, scripts.size());
+ }
+
+ public void testRenderStyle() throws Exception {
+ createAndAddStyleResource(RESOURCE_URI_PREFIX + userXcss);
+ createAndAddStyleResource(RESOURCE_URI_PREFIX + componentXcss).setRendered(false);
+
+ HtmlPage page = renderView();
+ List<HtmlLink> styles;
+ HtmlLink userLink;
+
+ styles = selectStylesByHhref(page, userXcss);
+ assertEquals(1, styles.size());
+ userLink = styles.get(0);
+ assertEquals("user", userLink.getClassAttribute());
+ assertEquals("", userLink.getMediaAttribute());
+ styles = selectStylesByHhref(page, componentXcss);
+ assertEquals(0, styles.size());
+ }
+
+ public void testRenderStyleResource() throws Exception {
+ InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
+
+ createAndAddStyleResource(resourceBuilder.getResourceForKey(userXcss));
+ createAndAddStyleResource(resourceBuilder.getResourceForKey(componentXcss)).setRendered(false);
+
+ UIResource styleComponent = createLoadStyleComponent();
+
+ styleComponent.setSrc(InternetResourceBuilder.getInstance().getResourceForKey(userXcss));
+ facesContext.getViewRoot().getChildren().add(styleComponent);
+
+ HtmlPage page = renderView();
+ List<HtmlLink> styles;
+ HtmlLink userLink;
+
+ styles = selectStylesByHhref(page, userXcss);
+ assertEquals(1, styles.size());
+ userLink = styles.get(0);
+ assertEquals("user", userLink.getClassAttribute());
+ assertEquals("", userLink.getMediaAttribute());
+ styles = selectStylesByHhref(page, componentXcss);
+ assertEquals(1, styles.size());
+ userLink = styles.get(0);
+ assertEquals("user", userLink.getClassAttribute());
+ assertEquals("", userLink.getMediaAttribute());
+ }
+
+ public void testRenderMedia() throws Exception {
+ createAndAddStyleResource(RESOURCE_URI_PREFIX + userXcss).getAttributes().put(HTML.media_ATTRIBUTE,
+ "screen print");
+
+ HtmlPage page = renderView();
+ List<HtmlLink> styles = selectStylesByHhref(page, userXcss);
+
+ assertEquals(1, styles.size());
+
+ HtmlLink userLink = styles.get(0);
+
+ assertEquals("user", userLink.getClassAttribute());
+ assertEquals("screen print", userLink.getMediaAttribute());
+ }
+
+ public void testRenderOverridenScript() throws Exception {
+ List<UIComponent> childrenList = facesContext.getViewRoot().getChildren();
+ UIResource userJsComponent = createLoadScriptComponent();
+
+ userJsComponent.setSrc(RESOURCE_URI_PREFIX + userJs);
+ childrenList.add(userJsComponent);
+
+ InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
+
+ childrenList.add(new ResourceDependentComponent(true, resourceBuilder.getResourceForKey(componentJs),
+ resourceBuilder.getResourceForKey(userJs)));
+
+ UIResource componentJsComponent = createLoadScriptComponent();
+
+ componentJsComponent.setSrc(RESOURCE_URI_PREFIX + componentJs);
+ childrenList.add(componentJsComponent);
+
+ HtmlPage page = renderView();
+ List<HtmlScript> userScripts = selectScriptsBySrc(page, userJs);
+
+ assertEquals(1, userScripts.size());
+
+ List<HtmlScript> componentScripts = selectScriptsBySrc(page, componentJs);
+
+ assertEquals(1, componentScripts.size());
+ }
+
+ public void testRenderOverridenStyle() throws Exception {
+ List<UIComponent> childrenList = facesContext.getViewRoot().getChildren();
+ UIResource userXcssComponent = createLoadStyleComponent();
+
+ userXcssComponent.setSrc(RESOURCE_URI_PREFIX + userXcss);
+ childrenList.add(userXcssComponent);
+
+ InternetResourceBuilder resourceBuilder = InternetResourceBuilder.getInstance();
+
+ childrenList.add(new ResourceDependentComponent(false, resourceBuilder.getResourceForKey(componentXcss),
+ resourceBuilder.getResourceForKey(userXcss)));
+
+ UIResource componentXcssComponent = createLoadStyleComponent();
+
+ componentXcssComponent.setSrc(RESOURCE_URI_PREFIX + componentXcss);
+ childrenList.add(componentXcssComponent);
+
+ HtmlPage page = renderView();
+ List<HtmlLink> styles = selectStylesByHhref(page, userXcss);
+
+ assertEquals(2, styles.size());
+ assertEquals("component", styles.get(0).getClassAttribute());
+ assertEquals("user", styles.get(1).getClassAttribute());
+ styles = selectStylesByHhref(page, componentXcss);
+ assertEquals(2, styles.size());
+ assertEquals("component", styles.get(0).getClassAttribute());
+ assertEquals("user", styles.get(1).getClassAttribute());
+ }
+
+ public void testRenderOverridenAjaxScript() throws Exception {
+ UIResource userComponent = createLoadScriptComponent();
+
+ userComponent.setSrc(RESOURCE_URI_PREFIX + "/org/ajax4jsf/javascript/scripts/AJAX.js");
+
+ List<UIComponent> childrenList = facesContext.getViewRoot().getChildren();
+
+ childrenList.add(userComponent);
+ childrenList.add(new ResourceDependentComponent(true, new AjaxScript()));
+
+ HtmlPage page = renderView();
+ List<HtmlScript> scripts = selectScriptsBySrc(page, "AjaxScript");
+
+ assertEquals(1, scripts.size());
+ scripts = selectScriptsBySrc(page, "AJAX.js");
+
+ // TODO change to 0 after related issue resolution
+ assertEquals(1, scripts.size());
+ }
}
+
class ResourceDependentComponent extends UIComponentBase {
+ static String COMPONENT_TYPE = "org.ajax4jsf.component.Test$ResourceDependentComponent";
+ static String COMPONENT_FAMILY = COMPONENT_TYPE;
+ private InternetResource[] resources;
+ private boolean useScripts;
- static String COMPONENT_TYPE = "org.ajax4jsf.component.Test$ResourceDependentComponent";
-
- static String COMPONENT_FAMILY = COMPONENT_TYPE;
+ public ResourceDependentComponent(boolean useScripts, InternetResource... resources) {
+ this.useScripts = useScripts;
+ this.resources = resources;
+ }
- private InternetResource[] resources;
-
- private boolean useScripts;
+ @Override
+ public String getFamily() {
+ return COMPONENT_FAMILY;
+ }
- public ResourceDependentComponent(boolean useScripts, InternetResource... resources) {
- this.useScripts = useScripts;
- this.resources = resources;
- }
-
- @Override
- public String getFamily() {
- return COMPONENT_FAMILY;
- }
-
- @Override
- public String getRendererType() {
- return COMPONENT_TYPE;
- }
-
- public InternetResource[] getScripts() {
- return useScripts ? resources : null;
- }
-
- public InternetResource[] getStyles() {
- return useScripts ? null : resources;
- }
+ @Override
+ public String getRendererType() {
+ return COMPONENT_TYPE;
+ }
+
+ public InternetResource[] getScripts() {
+ return useScripts ? resources : null;
+ }
+
+ public InternetResource[] getStyles() {
+ return useScripts ? null : resources;
+ }
}
+
class ResourceDependentComponentRenderer extends RendererBase implements HeaderResourceProducer2 {
+ @Override
+ protected Class<? extends UIComponent> getComponentClass() {
+ return ResourceDependentComponent.class;
+ }
- @Override
- protected Class<? extends UIComponent> getComponentClass() {
- return ResourceDependentComponent.class;
- }
+ public void encodeToHead(FacesContext context, UIComponent component, ProducerContext pc) throws IOException {
+ ResourceDependentComponent resourceDependentComponent = (ResourceDependentComponent) component;
- public void encodeToHead(FacesContext context, UIComponent component,
- ProducerContext pc) throws IOException {
+ if (pc.isProcessScripts()) {
+ InternetResource[] scripts = resourceDependentComponent.getScripts();
- ResourceDependentComponent resourceDependentComponent = (ResourceDependentComponent) component;
-
- if (pc.isProcessScripts()) {
- InternetResource[] scripts = resourceDependentComponent.getScripts();
- if (scripts != null) {
- for (InternetResource script : scripts) {
- script.encode(context, null);
- }
- }
- }
+ if (scripts != null) {
+ for (InternetResource script : scripts) {
+ script.encode(context, null);
+ }
+ }
+ }
- if (pc.isProcessStyles()) {
- InternetResource[] styles = resourceDependentComponent.getStyles();
- if (styles != null) {
- for (InternetResource script : styles) {
- script.encode(context, null);
- }
- }
- }
- }
-
+ if (pc.isProcessStyles()) {
+ InternetResource[] styles = resourceDependentComponent.getStyles();
+
+ if (styles != null) {
+ for (InternetResource script : styles) {
+ script.encode(context, null);
+ }
+ }
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/MediaOutputComponentBaseTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/MediaOutputComponentBaseTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/MediaOutputComponentBaseTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,53 +19,56 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.Calendar;
import java.util.Date;
/**
- *
+ *
* <br /><br />
- *
+ *
* Created 03.09.2007
* @author Nick Belaevski
* @since 3.1
*/
-
public class MediaOutputComponentBaseTest extends org.ajax4jsf.tests.AbstractAjax4JsfTestCase {
+ public MediaOutputComponentBaseTest(String name) {
+ super(name);
+ }
- public MediaOutputComponentBaseTest(String name) {
- super(name);
- }
+ protected Date createTestData_lastModified() {
+ Calendar calendar = Calendar.getInstance();
- protected Date createTestData_lastModified() {
- Calendar calendar = Calendar.getInstance();
- calendar.clear();
- calendar.set(Calendar.YEAR, 2007);
- calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
- calendar.set(Calendar.DATE, 3);
- calendar.set(Calendar.HOUR, 22);
- calendar.set(Calendar.MINUTE, 12);
- calendar.set(Calendar.SECOND, 40);
+ calendar.clear();
+ calendar.set(Calendar.YEAR, 2007);
+ calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
+ calendar.set(Calendar.DATE, 3);
+ calendar.set(Calendar.HOUR, 22);
+ calendar.set(Calendar.MINUTE, 12);
+ calendar.set(Calendar.SECOND, 40);
- return calendar.getTime();
- }
+ return calendar.getTime();
+ }
- protected Date createTestData_expires() {
- Calendar calendar = Calendar.getInstance();
- calendar.clear();
- calendar.set(Calendar.YEAR, 2007);
- calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
- calendar.set(Calendar.DATE, 8);
- calendar.set(Calendar.HOUR, 11);
- calendar.set(Calendar.MINUTE, 56);
- calendar.set(Calendar.SECOND, 9);
+ protected Date createTestData_expires() {
+ Calendar calendar = Calendar.getInstance();
- return calendar.getTime();
- }
+ calendar.clear();
+ calendar.set(Calendar.YEAR, 2007);
+ calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
+ calendar.set(Calendar.DATE, 8);
+ calendar.set(Calendar.HOUR, 11);
+ calendar.set(Calendar.MINUTE, 56);
+ calendar.set(Calendar.SECOND, 9);
- public void testVoid() throws Exception {
- //empty
- }
+ return calendar.getTime();
+ }
+
+ public void testVoid() throws Exception {
+
+ // empty
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/MockDataAdaptor.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/MockDataAdaptor.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/MockDataAdaptor.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.Iterator;
@@ -36,36 +38,43 @@
*/
public class MockDataAdaptor extends UIDataAdaptor {
- /* (non-Javadoc)
- * @see org.ajax4jsf.ajax.repeat.UIDataAdaptor#createComponentState()
- */
- protected DataComponentState createComponentState() {
- // TODO Auto-generated method stub
- return new MockComponentState();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.ajax.repeat.UIDataAdaptor#createComponentState()
+ */
+ protected DataComponentState createComponentState() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.ajax.repeat.UIDataAdaptor#createDataModel()
- */
- protected ExtendedDataModel createDataModel() {
- // TODO Auto-generated method stub
- return new MockDataModel();
- }
+ // TODO Auto-generated method stub
+ return new MockComponentState();
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.ajax.repeat.UIDataAdaptor#dataChildren()
- */
- protected Iterator<UIComponent> dataChildren() {
- // TODO Auto-generated method stub
- return getChildren().iterator();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.ajax.repeat.UIDataAdaptor#createDataModel()
+ */
+ protected ExtendedDataModel createDataModel() {
- /* (non-Javadoc)
- * @see org.ajax4jsf.ajax.repeat.UIDataAdaptor#fixedChildren()
- */
- protected Iterator<UIComponent> fixedChildren() {
- // TODO Auto-generated method stub
- return getFacets().values().iterator();
- }
+ // TODO Auto-generated method stub
+ return new MockDataModel();
+ }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.ajax.repeat.UIDataAdaptor#dataChildren()
+ */
+ protected Iterator<UIComponent> dataChildren() {
+
+ // TODO Auto-generated method stub
+ return getChildren().iterator();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.ajax.repeat.UIDataAdaptor#fixedChildren()
+ */
+ protected Iterator<UIComponent> fixedChildren() {
+
+ // TODO Auto-generated method stub
+ return getFacets().values().iterator();
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueDiscoveryTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueDiscoveryTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueDiscoveryTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.ArrayList;
@@ -28,7 +30,6 @@
import com.gargoylesoftware.htmlunit.html.HtmlPage;
-
/**
* @author Nick Belaevski
* @since 3.3.0
@@ -36,175 +37,150 @@
*/
public class QueueDiscoveryTest extends AbstractQueueComponentTest {
- /**
- * @param name
- */
- public QueueDiscoveryTest(String name) {
- super(name);
- }
-
- protected void assertListsEqual(List<String> list1, List<String> list2)
- throws Exception {
-
- assertEquals(list1 + ":" + list2, list1, list2);
- }
-
- protected List<String> getResults(HtmlPage page) {
- List<String> result = new ArrayList<String>();
+ /**
+ * @param name
+ */
+ public QueueDiscoveryTest(String name) {
+ super(name);
+ }
- executeJavaScript("Timer.execute()");
- NativeArray array = (NativeArray) executeJavaScript("window.testResult");
- for (int i = 0; i < array.getLength(); i++) {
- result.add((String) array.get(i, array));
- }
-
- return result;
- }
-
- public void testGlobalViewQueue() throws Exception {
- renderView("/queue-global-view.xhtml");
+ protected void assertListsEqual(List<String> list1, List<String> list2) throws Exception {
+ assertEquals(list1 + ":" + list2, list1, list2);
+ }
- List<String> list = new ArrayList<String>();
- assertListsEqual(list, getResults(page));
-
- list.add("button");
- click("form:button");
- assertListsEqual(list, getResults(page));
+ protected List<String> getResults(HtmlPage page) {
+ List<String> result = new ArrayList<String>();
- list.add("implicitQueue");
- click("form:implicitQueue");
- assertListsEqual(list, getResults(page));
-
- list.add("alternativeQueueButton");
- list.add("alt:alternativeQueueButton");
- click("form:alternativeQueueButton");
- assertListsEqual(list, getResults(page));
-
- list.add("function");
- executeJavaScript("ajaxFunction()");
- assertListsEqual(list, getResults(page));
+ executeJavaScript("Timer.execute()");
- list.add("implicitDelayedQueue");
- click("form2:implicitDelayedQueue");
- assertListsEqual(list, getResults(page));
- }
-
- public void testGlobalFormQueue() throws Exception {
- renderView("/queue-global-form.xhtml");
-
- List<String> list = new ArrayList<String>();
- assertListsEqual(list, getResults(page));
-
- list.add("alternativeQueueButton");
- list.add("alt:alternativeQueueButton");
- click("form2:alternativeQueueButton");
- assertListsEqual(list, getResults(page));
-
- list.add("alternativeQueueButton");
- click("form:alternativeQueueButton");
- assertListsEqual(list, getResults(page));
-
- list.add("buttonFormQueue");
- click("form:button");
- assertListsEqual(list, getResults(page));
-
- list.add("implicitQueue");
- click("form:implicitQueue");
- assertListsEqual(list, getResults(page));
-
- list.add("alternativeQueue1Button");
- list.add("alt1:alternativeQueue1Button");
- click("form:alternativeQueue1Button");
- assertListsEqual(list, getResults(page));
-
- list.add("buttonForm2Queue");
- click("form2:button");
- assertListsEqual(list, getResults(page));
-
- list.add("implicitDelayedQueue");
- click("form2:implicitDelayedQueue");
- assertListsEqual(list, getResults(page));
+ NativeArray array = (NativeArray) executeJavaScript("window.testResult");
- list.add("ajaxFunction");
- executeJavaScript("ajaxFunction()");
- assertListsEqual(list, getResults(page));
- }
+ for (int i = 0; i < array.getLength(); i++) {
+ result.add((String) array.get(i, array));
+ }
- public void testGlobalFormBoth() throws Exception {
- renderView("/queue-global-both.xhtml");
+ return result;
+ }
- List<String> list = new ArrayList<String>();
- assertListsEqual(list, getResults(page));
-
- list.add("buttonFormQueue");
- click("form:button");
- assertListsEqual(list, getResults(page));
-
- list.add("implicitDelayedQueue");
- click("form:implicitDelayedQueue");
- assertListsEqual(list, getResults(page));
+ public void testGlobalViewQueue() throws Exception {
+ renderView("/queue-global-view.xhtml");
- list.add("implicitQueue");
- click("form2:implicitQueue");
- assertListsEqual(list, getResults(page));
-
- list.add("viewQueue:viewQueueButton");
- click("form:viewQueueButton");
- assertListsEqual(list, getResults(page));
-
- list.add("form2Button");
- click("form2:button");
- assertListsEqual(list, getResults(page));
-
- list.add("anotherImplicitQueue");
- click("form3:anotherImplicitQueue");
- assertListsEqual(list, getResults(page));
-
- list.add("form3Button");
- click("form3:button");
- assertListsEqual(list, getResults(page));
-
- list.add("functionFormQueue");
- executeJavaScript("ajaxFunction()");
- assertListsEqual(list, getResults(page));
- }
-
- public void testDisabled() throws Exception {
- renderView("/queue-disabled.xhtml");
+ List<String> list = new ArrayList<String>();
- List<String> list = new ArrayList<String>();
- assertListsEqual(list, getResults(page));
-
- list.add("button");
- click("form:button");
- assertListsEqual(list, getResults(page));
+ assertListsEqual(list, getResults(page));
+ list.add("button");
+ click("form:button");
+ assertListsEqual(list, getResults(page));
+ list.add("implicitQueue");
+ click("form:implicitQueue");
+ assertListsEqual(list, getResults(page));
+ list.add("alternativeQueueButton");
+ list.add("alt:alternativeQueueButton");
+ click("form:alternativeQueueButton");
+ assertListsEqual(list, getResults(page));
+ list.add("function");
+ executeJavaScript("ajaxFunction()");
+ assertListsEqual(list, getResults(page));
+ list.add("implicitDelayedQueue");
+ click("form2:implicitDelayedQueue");
+ assertListsEqual(list, getResults(page));
+ }
- list.add("formQueueButton");
- click("form:formQueueButton");
- assertListsEqual(list, getResults(page));
+ public void testGlobalFormQueue() throws Exception {
+ renderView("/queue-global-form.xhtml");
- list.add("button2");
- list.add("form2-global:button2");
- click("form2:button2");
- assertListsEqual(list, getResults(page));
+ List<String> list = new ArrayList<String>();
- list.add("formQueueButton2");
- list.add("form2-queue:formQueueButton2");
- click("form2:formQueueButton2");
- assertListsEqual(list, getResults(page));
+ assertListsEqual(list, getResults(page));
+ list.add("alternativeQueueButton");
+ list.add("alt:alternativeQueueButton");
+ click("form2:alternativeQueueButton");
+ assertListsEqual(list, getResults(page));
+ list.add("alternativeQueueButton");
+ click("form:alternativeQueueButton");
+ assertListsEqual(list, getResults(page));
+ list.add("buttonFormQueue");
+ click("form:button");
+ assertListsEqual(list, getResults(page));
+ list.add("implicitQueue");
+ click("form:implicitQueue");
+ assertListsEqual(list, getResults(page));
+ list.add("alternativeQueue1Button");
+ list.add("alt1:alternativeQueue1Button");
+ click("form:alternativeQueue1Button");
+ assertListsEqual(list, getResults(page));
+ list.add("buttonForm2Queue");
+ click("form2:button");
+ assertListsEqual(list, getResults(page));
+ list.add("implicitDelayedQueue");
+ click("form2:implicitDelayedQueue");
+ assertListsEqual(list, getResults(page));
+ list.add("ajaxFunction");
+ executeJavaScript("ajaxFunction()");
+ assertListsEqual(list, getResults(page));
+ }
- list.add("global");
- click("form3:global");
- assertListsEqual(list, getResults(page));
+ public void testGlobalFormBoth() throws Exception {
+ renderView("/queue-global-both.xhtml");
- list.add("globalNamed");
- click("form3:globalNamed");
- assertListsEqual(list, getResults(page));
+ List<String> list = new ArrayList<String>();
- list.add("globalNamedX");
- list.add("viewNamedX:globalNamedX");
- click("form3:globalNamedX");
- assertListsEqual(list, getResults(page));
- }
-
+ assertListsEqual(list, getResults(page));
+ list.add("buttonFormQueue");
+ click("form:button");
+ assertListsEqual(list, getResults(page));
+ list.add("implicitDelayedQueue");
+ click("form:implicitDelayedQueue");
+ assertListsEqual(list, getResults(page));
+ list.add("implicitQueue");
+ click("form2:implicitQueue");
+ assertListsEqual(list, getResults(page));
+ list.add("viewQueue:viewQueueButton");
+ click("form:viewQueueButton");
+ assertListsEqual(list, getResults(page));
+ list.add("form2Button");
+ click("form2:button");
+ assertListsEqual(list, getResults(page));
+ list.add("anotherImplicitQueue");
+ click("form3:anotherImplicitQueue");
+ assertListsEqual(list, getResults(page));
+ list.add("form3Button");
+ click("form3:button");
+ assertListsEqual(list, getResults(page));
+ list.add("functionFormQueue");
+ executeJavaScript("ajaxFunction()");
+ assertListsEqual(list, getResults(page));
+ }
+
+ public void testDisabled() throws Exception {
+ renderView("/queue-disabled.xhtml");
+
+ List<String> list = new ArrayList<String>();
+
+ assertListsEqual(list, getResults(page));
+ list.add("button");
+ click("form:button");
+ assertListsEqual(list, getResults(page));
+ list.add("formQueueButton");
+ click("form:formQueueButton");
+ assertListsEqual(list, getResults(page));
+ list.add("button2");
+ list.add("form2-global:button2");
+ click("form2:button2");
+ assertListsEqual(list, getResults(page));
+ list.add("formQueueButton2");
+ list.add("form2-queue:formQueueButton2");
+ click("form2:formQueueButton2");
+ assertListsEqual(list, getResults(page));
+ list.add("global");
+ click("form3:global");
+ assertListsEqual(list, getResults(page));
+ list.add("globalNamed");
+ click("form3:globalNamed");
+ assertListsEqual(list, getResults(page));
+ list.add("globalNamedX");
+ list.add("viewNamedX:globalNamedX");
+ click("form3:globalNamedX");
+ assertListsEqual(list, getResults(page));
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueParallelTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueParallelTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueParallelTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,29 +19,27 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
/**
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class QueueParallelTest extends AbstractQueueComponentTest {
- /**
- * @param name
- */
- public QueueParallelTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public QueueParallelTest(String name) {
+ super(name);
+ }
- public void testParallel() throws Exception {
- renderView("/queue-parallel.xhtml");
-
- clickOnTime(0, "form:asyncButton");
- clickOnTime(0, "form:asyncButton1");
- clickOnTime(0, "form:asyncButton2");
-
-
- }
+ public void testParallel() throws Exception {
+ renderView("/queue-parallel.xhtml");
+ clickOnTime(0, "form:asyncButton");
+ clickOnTime(0, "form:asyncButton1");
+ clickOnTime(0, "form:asyncButton2");
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.List;
@@ -30,6 +32,7 @@
import org.ajax4jsf.renderkit.html.scripts.QueueScriptResourceRenderer;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.jaxen.JaxenException;
import com.gargoylesoftware.htmlunit.html.DomText;
@@ -39,214 +42,220 @@
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class QueueRendererTest extends AbstractAjax4JsfTestCase {
+ private UIForm form;
- private UIForm form;
+ /**
+ * @param name
+ */
+ public QueueRendererTest(String name) {
+ super(name);
+ }
- private static final String dry(String s) {
- return s.replace(" ", "");
- }
-
- /**
- * @param name
- */
- public QueueRendererTest(String name) {
- super(name);
- }
+ private static final String dry(String s) {
+ return s.replace(" ", "");
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
-
- UIViewRoot root = facesContext.getViewRoot();
- List<UIComponent> children = root.getChildren();
-
- form = (UIForm) application.createComponent(UIForm.COMPONENT_TYPE);
- form.setId("theform");
- form.getChildren().add(application.createComponent(UIInput.COMPONENT_TYPE));
- children.add(form);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
-
- form = null;
- }
+ UIViewRoot root = facesContext.getViewRoot();
+ List<UIComponent> children = root.getChildren();
- private String getQueueScript(HtmlPage page) throws JaxenException {
- List<?> list = page.getByXPath("//head/script[@id='" + QueueScriptResourceRenderer.QUEUE_SCRIPT_ID + "']/text()");
- DomText text = (DomText) list.get(0);
- String scriptData = text.getData();
-
- return scriptData.replaceAll("^\\Qif (typeof A4J != 'undefined') { if (A4J.AJAX) { with (A4J.AJAX) {\\E|\\Q}}};\\E$", "");
- }
-
- private String[] splitScript(String s) {
- String[] split = s.split(";");
- for (int i = 0; i < split.length; i++) {
- split[i] = split[i] + ";";
- }
-
- return split;
- }
-
- private String createQueueInitString(String queueName, String queueParams, String requestParams) {
- StringBuilder builder = new StringBuilder("if (!EventQueue.getQueue('").append(queueName).append("')) { EventQueue.addQueue(new EventQueue('").
- append(queueName).append("'");
+ form = (UIForm) application.createComponent(UIForm.COMPONENT_TYPE);
+ form.setId("theform");
+ form.getChildren().add(application.createComponent(UIInput.COMPONENT_TYPE));
+ children.add(form);
+ }
- builder.append(",");
- builder.append(String.valueOf(queueParams));
-
- builder.append(",");
- builder.append(String.valueOf(requestParams));
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ form = null;
+ }
- builder.append(")) };");
-
- return builder.toString();
- }
+ private String getQueueScript(HtmlPage page) throws JaxenException {
+ List<?> list = page.getByXPath("//head/script[@id='" + QueueScriptResourceRenderer.QUEUE_SCRIPT_ID
+ + "']/text()");
+ DomText text = (DomText) list.get(0);
+ String scriptData = text.getData();
- public void testViewQueueName() throws Exception {
- UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- queue.setName("test_view_queue");
- facesContext.getViewRoot().getChildren().add(queue);
-
- HtmlPage page = renderView();
- String queueScript = getQueueScript(page);
-
- assertEquals(createQueueInitString("test_view_queue", null, null), queueScript);
- }
-
- public void testViewQueueDefaultName() throws Exception {
- UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- facesContext.getViewRoot().getChildren().add(queue);
-
- HtmlPage page = renderView();
- String queueScript = getQueueScript(page);
- assertEquals(createQueueInitString(UIQueue.GLOBAL_QUEUE_NAME, null, null), queueScript);
- }
+ return scriptData.replaceAll(
+ "^\\Qif (typeof A4J != 'undefined') { if (A4J.AJAX) { with (A4J.AJAX) {\\E|\\Q}}};\\E$", "");
+ }
- public void testFormQueueName() throws Exception {
- UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- queue.setName("test_view_queue");
- form.getChildren().add(queue);
-
- HtmlPage page = renderView();
- String queueScript = getQueueScript(page);
- assertEquals(createQueueInitString("theform:test_view_queue", null, null), queueScript);
- }
-
- public void testFormQueueDefaultName() throws Exception {
- UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- form.getChildren().add(queue);
-
- HtmlPage page = renderView();
- String queueScript = getQueueScript(page);
- assertEquals(createQueueInitString("theform", null, null), queueScript);
- }
-
- public void testRenderQueueAttributes() throws Exception {
- UIQueue queue1 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
-
- queue1.setSize(10);
- queue1.setOnsizeexceeded("sizeexceeded_handler()");
- queue1.setSizeExceededBehavior("dropNext");
- queue1.setOnrequestqueue("request_queue_handler()");
- queue1.setOnrequestdequeue("request_de_queue_handler()");
- form.getChildren().add(queue1);
-
- UIQueue queue2 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- queue2.setSize(-1);
- queue2.setName("unsizedQueue");
- form.getChildren().add(queue2);
+ private String[] splitScript(String s) {
+ String[] split = s.split(";");
- UIQueue queue3 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- queue3.setName("defaultSizeQueue");
- form.getChildren().add(queue3);
+ for (int i = 0; i < split.length; i++) {
+ split[i] = split[i] + ";";
+ }
- HtmlPage page = renderView();
- String queueScript = dry(getQueueScript(page));
- String[] scripts = splitScript(queueScript);
- assertEquals(3, scripts.length);
-
- assertEquals(dry(createQueueInitString("theform",
- "{'size':10,'sizeExceededBehavior':'dropNext','onsizeexceeded':function(query,options,event){sizeexceeded_handler()},'onrequestqueue':function(query,options,event){request_queue_handler()},'onrequestdequeue':function(query,options,event){request_de_queue_handler()}}",
- null)),
- scripts[0]);
+ return split;
+ }
- assertEquals(dry(createQueueInitString("theform:unsizedQueue", "{'size':-1}", null)), scripts[1]);
+ private String createQueueInitString(String queueName, String queueParams, String requestParams) {
+ StringBuilder builder = new StringBuilder("if (!EventQueue.getQueue('").append(queueName).append(
+ "')) { EventQueue.addQueue(new EventQueue('").append(queueName).append("'");
- assertEquals(dry(createQueueInitString("theform:defaultSizeQueue", null, null)), scripts[2]);
- }
+ builder.append(",");
+ builder.append(String.valueOf(queueParams));
+ builder.append(",");
+ builder.append(String.valueOf(requestParams));
+ builder.append(")) };");
- public void testRenderRequestAttributes() throws Exception {
- UIQueue queue1 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+ return builder.toString();
+ }
- queue1.setName("queue1");
- queue1.setTimeout(50021);
- queue1.setOnerror("error_queue_handler()");
- queue1.setOnsubmit("submit_queue_handler()");
- queue1.setIgnoreDupResponses(false);
- form.getChildren().add(queue1);
+ public void testViewQueueName() throws Exception {
+ UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- UIQueue queue2 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+ queue.setName("test_view_queue");
+ facesContext.getViewRoot().getChildren().add(queue);
- queue2.setName("queue2");
- queue2.setRequestDelay(600);
- queue2.setIgnoreDupResponses(true);
- queue2.setOnbeforedomupdate("beforedomupdate_handler()");
- queue2.setOncomplete("complete_handler()");
- queue2.setStatus("mystatus");
- form.getChildren().add(queue2);
+ HtmlPage page = renderView();
+ String queueScript = getQueueScript(page);
- HtmlPage page = renderView();
- String queueScript = dry(getQueueScript(page));
- String[] scripts = splitScript(queueScript);
- assertEquals(2, scripts.length);
-
- assertEquals(dry(createQueueInitString("theform:queue1", null,
- "{'timeout':50021,'queueonsubmit':function(request){submit_queue_handler()},'queueonerror':function(request,status,message){error_queue_handler()}}")), scripts[0]);
- assertEquals(dry(createQueueInitString("theform:queue2", null,
- "{'ignoreDupResponses':true,'requestDelay':600,'status':'mystatus','queueonbeforedomupdate':function(request,event,data){beforedomupdate_handler()},'queueoncomplete':function(request,event,data){complete_handler()}}")),
- scripts[1]);
- }
-
- public void testInvalidSizeExceededBehavior() throws Exception {
- UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- queue.setSizeExceededBehavior("unknownBehavior");
- form.getChildren().add(queue);
-
- try {
- renderView();
- fail();
- } catch (IllegalArgumentException e) {
- //ok
- }
- }
-
- public void testDuplicateQueues() throws Exception {
- UIQueue queue1 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- queue1.setName("testQueue");
- queue1.setSize(2);
- form.getChildren().add(queue1);
+ assertEquals(createQueueInitString("test_view_queue", null, null), queueScript);
+ }
- UIQueue queue2 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- queue2.setName("testQueue");
- queue2.setSize(5);
- form.getChildren().add(queue2);
+ public void testViewQueueDefaultName() throws Exception {
+ UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
- HtmlPage page = renderView();
+ facesContext.getViewRoot().getChildren().add(queue);
- String queueScript = dry(getQueueScript(page));
- String[] scripts = splitScript(queueScript);
- assertEquals(1, scripts.length);
+ HtmlPage page = renderView();
+ String queueScript = getQueueScript(page);
- assertEquals(dry(createQueueInitString("theform:testQueue", "{'size':2}",null)), scripts[0]);
- }
-
+ assertEquals(createQueueInitString(UIQueue.GLOBAL_QUEUE_NAME, null, null), queueScript);
+ }
+
+ public void testFormQueueName() throws Exception {
+ UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue.setName("test_view_queue");
+ form.getChildren().add(queue);
+
+ HtmlPage page = renderView();
+ String queueScript = getQueueScript(page);
+
+ assertEquals(createQueueInitString("theform:test_view_queue", null, null), queueScript);
+ }
+
+ public void testFormQueueDefaultName() throws Exception {
+ UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ form.getChildren().add(queue);
+
+ HtmlPage page = renderView();
+ String queueScript = getQueueScript(page);
+
+ assertEquals(createQueueInitString("theform", null, null), queueScript);
+ }
+
+ public void testRenderQueueAttributes() throws Exception {
+ UIQueue queue1 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue1.setSize(10);
+ queue1.setOnsizeexceeded("sizeexceeded_handler()");
+ queue1.setSizeExceededBehavior("dropNext");
+ queue1.setOnrequestqueue("request_queue_handler()");
+ queue1.setOnrequestdequeue("request_de_queue_handler()");
+ form.getChildren().add(queue1);
+
+ UIQueue queue2 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue2.setSize(-1);
+ queue2.setName("unsizedQueue");
+ form.getChildren().add(queue2);
+
+ UIQueue queue3 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue3.setName("defaultSizeQueue");
+ form.getChildren().add(queue3);
+
+ HtmlPage page = renderView();
+ String queueScript = dry(getQueueScript(page));
+ String[] scripts = splitScript(queueScript);
+
+ assertEquals(3, scripts.length);
+ assertEquals(dry(createQueueInitString("theform",
+ "{'size':10,'sizeExceededBehavior':'dropNext','onsizeexceeded':function(query,options,event){sizeexceeded_handler()},'onrequestqueue':function(query,options,event){request_queue_handler()},'onrequestdequeue':function(query,options,event){request_de_queue_handler()}}", null)), scripts[0]);
+ assertEquals(dry(createQueueInitString("theform:unsizedQueue", "{'size':-1}", null)), scripts[1]);
+ assertEquals(dry(createQueueInitString("theform:defaultSizeQueue", null, null)), scripts[2]);
+ }
+
+ public void testRenderRequestAttributes() throws Exception {
+ UIQueue queue1 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue1.setName("queue1");
+ queue1.setTimeout(50021);
+ queue1.setOnerror("error_queue_handler()");
+ queue1.setOnsubmit("submit_queue_handler()");
+ queue1.setIgnoreDupResponses(false);
+ form.getChildren().add(queue1);
+
+ UIQueue queue2 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue2.setName("queue2");
+ queue2.setRequestDelay(600);
+ queue2.setIgnoreDupResponses(true);
+ queue2.setOnbeforedomupdate("beforedomupdate_handler()");
+ queue2.setOncomplete("complete_handler()");
+ queue2.setStatus("mystatus");
+ form.getChildren().add(queue2);
+
+ HtmlPage page = renderView();
+ String queueScript = dry(getQueueScript(page));
+ String[] scripts = splitScript(queueScript);
+
+ assertEquals(2, scripts.length);
+ assertEquals(dry(createQueueInitString("theform:queue1", null,
+ "{'timeout':50021,'queueonsubmit':function(request){submit_queue_handler()},'queueonerror':function(request,status,message){error_queue_handler()}}")), scripts[0]);
+ assertEquals(dry(createQueueInitString("theform:queue2", null,
+ "{'ignoreDupResponses':true,'requestDelay':600,'status':'mystatus','queueonbeforedomupdate':function(request,event,data){beforedomupdate_handler()},'queueoncomplete':function(request,event,data){complete_handler()}}")), scripts[1]);
+ }
+
+ public void testInvalidSizeExceededBehavior() throws Exception {
+ UIQueue queue = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue.setSizeExceededBehavior("unknownBehavior");
+ form.getChildren().add(queue);
+
+ try {
+ renderView();
+ fail();
+ } catch (IllegalArgumentException e) {
+
+ // ok
+ }
+ }
+
+ public void testDuplicateQueues() throws Exception {
+ UIQueue queue1 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue1.setName("testQueue");
+ queue1.setSize(2);
+ form.getChildren().add(queue1);
+
+ UIQueue queue2 = (UIQueue) application.createComponent(UIQueue.COMPONENT_TYPE);
+
+ queue2.setName("testQueue");
+ queue2.setSize(5);
+ form.getChildren().add(queue2);
+
+ HtmlPage page = renderView();
+ String queueScript = dry(getQueueScript(page));
+ String[] scripts = splitScript(queueScript);
+
+ assertEquals(1, scripts.length);
+ assertEquals(dry(createQueueInitString("theform:testQueue", "{'size':2}", null)), scripts[0]);
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueScriptedTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueScriptedTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueScriptedTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -20,6 +20,7 @@
*/
+
package org.ajax4jsf.component;
import java.util.List;
@@ -31,227 +32,213 @@
* @author Nick Belaevski
*/
public class QueueScriptedTest extends AbstractQueueComponentTest {
+ private static final String QUEUE_NAME = "testQueue";
+ private static final String VIEW_NAME = "/queue-scripted.xhtml";
- private static final String QUEUE_NAME = "testQueue";
-
- private static final String VIEW_NAME = "/queue-scripted.xhtml";
-
- public QueueScriptedTest(String name) {
- super(name);
- }
+ public QueueScriptedTest(String name) {
+ super(name);
+ }
- public void testRequestDelayDefined() throws Exception {
- renderView(VIEW_NAME);
+ public void testRequestDelayDefined() throws Exception {
+ renderView(VIEW_NAME);
- ParametersBuilder parametersBuilder = createAjaxParameters().
- eventsQueue("queueRequestDelay").requestTime(5);
-
- ajax(0, "a", parametersBuilder);
- ajax(25, "b", parametersBuilder);
- ajax(50, "c", parametersBuilder.requestDelay(30));
- ajax(90, "d", parametersBuilder.requestDelay(10));
- ajax(95, "d", parametersBuilder.requestDelay(50));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(4, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 15, 20, false);
- checkRequestData(dataList.get(1), "b", 40, 45, false);
- checkRequestData(dataList.get(2), "c", 80, 85, false);
- checkRequestData(dataList.get(3), "d", 145, 150, false);
- }
-
- public void testRequestDelayDefault() throws Exception {
- renderView(VIEW_NAME);
-
- ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("queueDefaults").
- requestTime(100);
-
- ajax(0, "a", parametersBuilder.requestDelay(100));
- ajax(300, "b", parametersBuilder);
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(2, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 100, 200, false);
- checkRequestData(dataList.get(1), "b", 300, 400, false);
- }
-
- public void testTimeout() throws Exception {
- renderView(VIEW_NAME);
+ ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("queueRequestDelay").requestTime(5);
- ParametersBuilder parametersBuilder = createAjaxParameters().
- eventsQueue("queueTimeout").requestDelay(0);
-
- ajax(0, "a", parametersBuilder.requestTime(4999));
- ajax(10000, "b", parametersBuilder.requestTime(5001).similarityGroupingId("b"));
- ajax(10000, "c", parametersBuilder.requestTime(100).similarityGroupingId("c"));
- ajax(20000, "d", parametersBuilder.requestTime(10000).timeout(10000));
- ajax(40000, "e", parametersBuilder.requestTime(10001).timeout(10000));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(5, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 0, 4999, false);
- checkRequestData(dataList.get(1), "b", 10000, 15000, true);
- checkRequestData(dataList.get(2), "c", 15000, 15100, false);
- checkRequestData(dataList.get(3), "d", 20000, 30000, false);
- checkRequestData(dataList.get(4), "e", 40000, 50000, true);
-
- }
-
- public void testIgnoreDupResponses() throws Exception {
- renderView(VIEW_NAME);
+ ajax(0, "a", parametersBuilder);
+ ajax(25, "b", parametersBuilder);
+ ajax(50, "c", parametersBuilder.requestDelay(30));
+ ajax(90, "d", parametersBuilder.requestDelay(10));
+ ajax(95, "d", parametersBuilder.requestDelay(50));
- ParametersBuilder parametersBuilder = createAjaxParameters().
- eventsQueue("queueIgnoreDupResponses").requestDelay(0).requestTime(1000);
-
- ajax(0, "a", parametersBuilder.similarityGroupingId("a"));
- ajax(500, "b", parametersBuilder.similarityGroupingId("a"));
- ajax(2500, "c", parametersBuilder.similarityGroupingId("a"));
- ajax(3000, "d", parametersBuilder.similarityGroupingId("a").ignoreDupResponses(false));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(4, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 0, 1000, false);
- checkRequestData(dataList.get(1), "b", 1000, 2000, false);
-
- checkRequestData(dataList.get(2), "c", 2500, 3500, false);
- checkRequestData(dataList.get(3), "d", 3500, 4500, false);
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
- NativeArray array = (NativeArray) executeJavaScript("queueIgnoreDupResponsesTest");
- long length = array.getLength();
- assertEquals(3, length);
+ assertEquals(4, dataList.size());
+ checkRequestData(dataList.get(0), "a", 15, 20, false);
+ checkRequestData(dataList.get(1), "b", 40, 45, false);
+ checkRequestData(dataList.get(2), "c", 80, 85, false);
+ checkRequestData(dataList.get(3), "d", 145, 150, false);
+ }
- assertEquals("b:2000", (String) array.get(0, array));
- assertEquals("c:3500", (String) array.get(1, array));
- assertEquals("d:4500", (String) array.get(2, array));
- }
-
- public void testIgnoreDupResponsesDefault() throws Exception {
- renderView(VIEW_NAME);
-
- ParametersBuilder parametersBuilder = createAjaxParameters().
- eventsQueue("queueDefaults").requestTime(500);
-
- ajax(0, "a", parametersBuilder);
- ajax(250, "b", parametersBuilder);
- ajax(750, "c", parametersBuilder.ignoreDupResponses(true));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(3, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 0, 500, false);
- checkRequestData(dataList.get(1), "b", 500, 1000, false);
- checkRequestData(dataList.get(2), "c", 1000, 1500, false);
- }
-
- public void testIgnoreDupResponsesTimeout() throws Exception {
- renderView(VIEW_NAME);
-
- ParametersBuilder parametersBuilder = createAjaxParameters().
- eventsQueue("queueTimeout").ignoreDupResponses(true).requestDelay(0).requestTime(1000);
+ public void testRequestDelayDefault() throws Exception {
+ renderView(VIEW_NAME);
- ajax(0, "a", parametersBuilder.timeout(500));
- ajax(100, "b", parametersBuilder);
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(2, dataList.size());
- checkRequestData(dataList.get(0), "a", 0, 500, true);
- checkRequestData(dataList.get(1), "b", 500, 1500, false);
- }
-
- public void testSimpleAjax() throws Exception {
- renderView(VIEW_NAME);
-
- ajax(50, "a", createAjaxParameters().requestTime(100));
- ajax(50, "b", createAjaxParameters().requestTime(150));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
- assertEquals(2, dataList.size());
- checkRequestData(dataList.get(0), "a", 50, 150, false);
- checkRequestData(dataList.get(1), "b", 50, 200, false);
-
- assertEquals(200d, result.getCurrentTime());
- }
-
- public void testSimpleQueuedAjax() throws Exception {
- renderView(VIEW_NAME);
+ ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("queueDefaults").requestTime(100);
- ParametersBuilder queueParameters = createAjaxParameters().requestTime(500).eventsQueue(QUEUE_NAME);
- ajax(50, "a", queueParameters.similarityGroupingId(0));
- ajax(250, "b", queueParameters.similarityGroupingId(1));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
- assertEquals(2, dataList.size());
- checkRequestData(dataList.get(0), "a", 50, 550, false);
- checkRequestData(dataList.get(1), "b", 550, 1050, false);
-
- assertEquals(1050d, result.getCurrentTime());
- }
-
- public void testImplicitQueue() throws Exception {
- renderView(VIEW_NAME);
+ ajax(0, "a", parametersBuilder.requestDelay(100));
+ ajax(300, "b", parametersBuilder);
- ParametersBuilder parameters = createAjaxParameters().
- requestDelay(100).
- implicitEventsQueue("myqueue").
- requestTime(10);
-
- ajax(0, "a", parameters);
- ajax(10, "b", parameters);
- ajax(20, "c", parameters.requestDelay(50));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
- assertEquals(1, dataList.size());
-
- RequestData requestData = dataList.get(0);
- checkRequestData(requestData, "c", 70, 80, false);
-
- assertEquals(80d, result.getCurrentTime());
-
- }
-
- public void testStatusIgnoreDupResponses() throws Exception {
- renderView(VIEW_NAME);
-
- ParametersBuilder parameters = createAjaxParameters().requestDelay(0).eventsQueue("queueIgnoreDupResponses");
-
- ajax(0, "a", parameters);
- ajax(100, "b", parameters);
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
- assertEquals(2, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 0, DEFAULT_REQUEST_TIME, false);
- checkRequestData(dataList.get(1), "b", DEFAULT_REQUEST_TIME, 2 * DEFAULT_REQUEST_TIME, false);
-
- NativeArray array = (NativeArray) executeJavaScript("window.statusData");
- assertEquals(2, array.getLength());
-
- NativeArray nestedArray = (NativeArray) array.get(0, array);
- assertEquals(Double.valueOf(0), nestedArray.get(0, nestedArray));
- assertEquals(Double.valueOf(DEFAULT_REQUEST_TIME), nestedArray.get(1, nestedArray));
+ assertEquals(2, dataList.size());
+ checkRequestData(dataList.get(0), "a", 100, 200, false);
+ checkRequestData(dataList.get(1), "b", 300, 400, false);
+ }
- nestedArray = (NativeArray) array.get(1, array);
- assertEquals(Double.valueOf(DEFAULT_REQUEST_TIME), nestedArray.get(0, nestedArray));
- assertEquals(Double.valueOf(2 * DEFAULT_REQUEST_TIME), nestedArray.get(1, nestedArray));
- }
+ public void testTimeout() throws Exception {
+ renderView(VIEW_NAME);
+
+ ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("queueTimeout").requestDelay(0);
+
+ ajax(0, "a", parametersBuilder.requestTime(4999));
+ ajax(10000, "b", parametersBuilder.requestTime(5001).similarityGroupingId("b"));
+ ajax(10000, "c", parametersBuilder.requestTime(100).similarityGroupingId("c"));
+ ajax(20000, "d", parametersBuilder.requestTime(10000).timeout(10000));
+ ajax(40000, "e", parametersBuilder.requestTime(10001).timeout(10000));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(5, dataList.size());
+ checkRequestData(dataList.get(0), "a", 0, 4999, false);
+ checkRequestData(dataList.get(1), "b", 10000, 15000, true);
+ checkRequestData(dataList.get(2), "c", 15000, 15100, false);
+ checkRequestData(dataList.get(3), "d", 20000, 30000, false);
+ checkRequestData(dataList.get(4), "e", 40000, 50000, true);
+ }
+
+ public void testIgnoreDupResponses() throws Exception {
+ renderView(VIEW_NAME);
+
+ ParametersBuilder parametersBuilder =
+ createAjaxParameters().eventsQueue("queueIgnoreDupResponses").requestDelay(0).requestTime(1000);
+
+ ajax(0, "a", parametersBuilder.similarityGroupingId("a"));
+ ajax(500, "b", parametersBuilder.similarityGroupingId("a"));
+ ajax(2500, "c", parametersBuilder.similarityGroupingId("a"));
+ ajax(3000, "d", parametersBuilder.similarityGroupingId("a").ignoreDupResponses(false));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(4, dataList.size());
+ checkRequestData(dataList.get(0), "a", 0, 1000, false);
+ checkRequestData(dataList.get(1), "b", 1000, 2000, false);
+ checkRequestData(dataList.get(2), "c", 2500, 3500, false);
+ checkRequestData(dataList.get(3), "d", 3500, 4500, false);
+
+ NativeArray array = (NativeArray) executeJavaScript("queueIgnoreDupResponsesTest");
+ long length = array.getLength();
+
+ assertEquals(3, length);
+ assertEquals("b:2000", (String) array.get(0, array));
+ assertEquals("c:3500", (String) array.get(1, array));
+ assertEquals("d:4500", (String) array.get(2, array));
+ }
+
+ public void testIgnoreDupResponsesDefault() throws Exception {
+ renderView(VIEW_NAME);
+
+ ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("queueDefaults").requestTime(500);
+
+ ajax(0, "a", parametersBuilder);
+ ajax(250, "b", parametersBuilder);
+ ajax(750, "c", parametersBuilder.ignoreDupResponses(true));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(3, dataList.size());
+ checkRequestData(dataList.get(0), "a", 0, 500, false);
+ checkRequestData(dataList.get(1), "b", 500, 1000, false);
+ checkRequestData(dataList.get(2), "c", 1000, 1500, false);
+ }
+
+ public void testIgnoreDupResponsesTimeout() throws Exception {
+ renderView(VIEW_NAME);
+
+ ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("queueTimeout").ignoreDupResponses(
+ true).requestDelay(0).requestTime(1000);
+
+ ajax(0, "a", parametersBuilder.timeout(500));
+ ajax(100, "b", parametersBuilder);
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(2, dataList.size());
+ checkRequestData(dataList.get(0), "a", 0, 500, true);
+ checkRequestData(dataList.get(1), "b", 500, 1500, false);
+ }
+
+ public void testSimpleAjax() throws Exception {
+ renderView(VIEW_NAME);
+ ajax(50, "a", createAjaxParameters().requestTime(100));
+ ajax(50, "b", createAjaxParameters().requestTime(150));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(2, dataList.size());
+ checkRequestData(dataList.get(0), "a", 50, 150, false);
+ checkRequestData(dataList.get(1), "b", 50, 200, false);
+ assertEquals(200d, result.getCurrentTime());
+ }
+
+ public void testSimpleQueuedAjax() throws Exception {
+ renderView(VIEW_NAME);
+
+ ParametersBuilder queueParameters = createAjaxParameters().requestTime(500).eventsQueue(QUEUE_NAME);
+
+ ajax(50, "a", queueParameters.similarityGroupingId(0));
+ ajax(250, "b", queueParameters.similarityGroupingId(1));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(2, dataList.size());
+ checkRequestData(dataList.get(0), "a", 50, 550, false);
+ checkRequestData(dataList.get(1), "b", 550, 1050, false);
+ assertEquals(1050d, result.getCurrentTime());
+ }
+
+ public void testImplicitQueue() throws Exception {
+ renderView(VIEW_NAME);
+
+ ParametersBuilder parameters =
+ createAjaxParameters().requestDelay(100).implicitEventsQueue("myqueue").requestTime(10);
+
+ ajax(0, "a", parameters);
+ ajax(10, "b", parameters);
+ ajax(20, "c", parameters.requestDelay(50));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(1, dataList.size());
+
+ RequestData requestData = dataList.get(0);
+
+ checkRequestData(requestData, "c", 70, 80, false);
+ assertEquals(80d, result.getCurrentTime());
+ }
+
+ public void testStatusIgnoreDupResponses() throws Exception {
+ renderView(VIEW_NAME);
+
+ ParametersBuilder parameters = createAjaxParameters().requestDelay(0).eventsQueue("queueIgnoreDupResponses");
+
+ ajax(0, "a", parameters);
+ ajax(100, "b", parameters);
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(2, dataList.size());
+ checkRequestData(dataList.get(0), "a", 0, DEFAULT_REQUEST_TIME, false);
+ checkRequestData(dataList.get(1), "b", DEFAULT_REQUEST_TIME, 2 * DEFAULT_REQUEST_TIME, false);
+
+ NativeArray array = (NativeArray) executeJavaScript("window.statusData");
+
+ assertEquals(2, array.getLength());
+
+ NativeArray nestedArray = (NativeArray) array.get(0, array);
+
+ assertEquals(Double.valueOf(0), nestedArray.get(0, nestedArray));
+ assertEquals(Double.valueOf(DEFAULT_REQUEST_TIME), nestedArray.get(1, nestedArray));
+ nestedArray = (NativeArray) array.get(1, array);
+ assertEquals(Double.valueOf(DEFAULT_REQUEST_TIME), nestedArray.get(0, nestedArray));
+ assertEquals(Double.valueOf(2 * DEFAULT_REQUEST_TIME), nestedArray.get(1, nestedArray));
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueSimilarityTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueSimilarityTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueSimilarityTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.List;
@@ -27,135 +29,121 @@
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class QueueSimilarityTest extends AbstractQueueComponentTest {
+ private static final String VIEW_NAME = "/queue-similarity.xhtml";
- /**
- * @param name
- */
- public QueueSimilarityTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public QueueSimilarityTest(String name) {
+ super(name);
+ }
- private static final String VIEW_NAME = "/queue-similarity.xhtml";
-
- public void testDefaultBehavior() throws Exception {
- renderView(VIEW_NAME);
-
- clickOnTime(0, "form:button3");
- clickOnTime(100, "form:button3");
- clickOnTime(200, "form:button4");
- clickOnTime(400, "form:button3");
-
- clickOnTime(4000, "form:button3");
- clickOnTime(4300, "form:button3");
- clickOnTime(4500, "form:button3");
+ public void testDefaultBehavior() throws Exception {
+ renderView(VIEW_NAME);
+ clickOnTime(0, "form:button3");
+ clickOnTime(100, "form:button3");
+ clickOnTime(200, "form:button4");
+ clickOnTime(400, "form:button3");
+ clickOnTime(4000, "form:button3");
+ clickOnTime(4300, "form:button3");
+ clickOnTime(4500, "form:button3");
- TestsResult testsResult = getTestsResult();
- List<RequestData> dataList = testsResult.getDataList();
-
- assertEquals(4, dataList.size());
-
- checkRequestData(dataList.get(0), "form:button3", 200, 1200, false);
- checkRequestData(dataList.get(1), "form:button4", 1200, 2200, false);
- checkRequestData(dataList.get(2), "form:button3", 2200, 3200, false);
- checkRequestData(dataList.get(3), "form:button3", 5000, 6000, false);
- }
-
- public void testGrouping() throws Exception {
- renderView(VIEW_NAME);
+ TestsResult testsResult = getTestsResult();
+ List<RequestData> dataList = testsResult.getDataList();
- clickOnTime(0, "form:button1");
- clickOnTime(100, "form:button1");
- clickOnTime(200, "form:button2");
- clickOnTime(300, "form:button1");
-
-
- TestsResult testsResult = getTestsResult();
- List<RequestData> dataList = testsResult.getDataList();
-
- assertEquals(1, dataList.size());
-
- checkRequestData(dataList.get(0), "form:button1", 700, 1700, false);
- }
-
- public void testSizeExceededGroupingDropNext() throws Exception {
- renderView(VIEW_NAME);
+ assertEquals(4, dataList.size());
+ checkRequestData(dataList.get(0), "form:button3", 200, 1200, false);
+ checkRequestData(dataList.get(1), "form:button4", 1200, 2200, false);
+ checkRequestData(dataList.get(2), "form:button3", 2200, 3200, false);
+ checkRequestData(dataList.get(3), "form:button3", 5000, 6000, false);
+ }
- clickOnTime(0, "dropNext:button1");
- clickOnTime(100, "dropNext:button2");
- clickOnTime(200, "dropNext:button1");
- clickOnTime(300, "dropNext:button2");
- clickOnTime(2000, "dropNext:button1");
-
- TestsResult testsResult = getTestsResult();
- List<RequestData> dataList = testsResult.getDataList();
-
- assertEquals(4, dataList.size());
-
- checkRequestData(dataList.get(0), "dropNext:button1", 100, 1100, false);
- checkRequestData(dataList.get(1), "dropNext:button1", 1100, 2100, false);
- checkRequestData(dataList.get(2), "dropNext:button2", 2100, 3100, false);
- checkRequestData(dataList.get(3), "dropNext:button1", 3100, 4100, false);
- }
+ public void testGrouping() throws Exception {
+ renderView(VIEW_NAME);
+ clickOnTime(0, "form:button1");
+ clickOnTime(100, "form:button1");
+ clickOnTime(200, "form:button2");
+ clickOnTime(300, "form:button1");
- public void testSizeExceededGroupingDropNew() throws Exception {
- renderView(VIEW_NAME);
+ TestsResult testsResult = getTestsResult();
+ List<RequestData> dataList = testsResult.getDataList();
- clickOnTime(0, "dropNew:button1");
- clickOnTime(100, "dropNew:button2");
- clickOnTime(200, "dropNew:button1");
- clickOnTime(300, "dropNew:button2");
- clickOnTime(2000, "dropNew:button1");
-
- TestsResult testsResult = getTestsResult();
- List<RequestData> dataList = testsResult.getDataList();
-
- assertEquals(4, dataList.size());
- checkRequestData(dataList.get(0), "dropNew:button1", 100, 1100, false);
- checkRequestData(dataList.get(1), "dropNew:button2", 1100, 2100, false);
- checkRequestData(dataList.get(2), "dropNew:button1", 2100, 3100, false);
- checkRequestData(dataList.get(3), "dropNew:button1", 3100, 4100, false);
- }
+ assertEquals(1, dataList.size());
+ checkRequestData(dataList.get(0), "form:button1", 700, 1700, false);
+ }
- public void testSizeExceededGroupingFireNext() throws Exception {
- renderView(VIEW_NAME);
+ public void testSizeExceededGroupingDropNext() throws Exception {
+ renderView(VIEW_NAME);
+ clickOnTime(0, "dropNext:button1");
+ clickOnTime(100, "dropNext:button2");
+ clickOnTime(200, "dropNext:button1");
+ clickOnTime(300, "dropNext:button2");
+ clickOnTime(2000, "dropNext:button1");
- clickOnTime(0, "fireNext:button1");
- clickOnTime(100, "fireNext:button2");
- clickOnTime(200, "fireNext:button1");
- clickOnTime(300, "fireNext:button2");
- clickOnTime(2000, "fireNext:button1");
+ TestsResult testsResult = getTestsResult();
+ List<RequestData> dataList = testsResult.getDataList();
- TestsResult testsResult = getTestsResult();
- List<RequestData> dataList = testsResult.getDataList();
-
- assertEquals(5, dataList.size());
- checkRequestData(dataList.get(0), "fireNext:button1", 100, 1100, false);
- checkRequestData(dataList.get(1), "fireNext:button2", 300, 1300, false);
- checkRequestData(dataList.get(2), "fireNext:button1", 1100, 2100, false);
- checkRequestData(dataList.get(3), "fireNext:button2", 2100, 3100, false);
- checkRequestData(dataList.get(4), "fireNext:button1", 3100, 4100, false);
- }
+ assertEquals(4, dataList.size());
+ checkRequestData(dataList.get(0), "dropNext:button1", 100, 1100, false);
+ checkRequestData(dataList.get(1), "dropNext:button1", 1100, 2100, false);
+ checkRequestData(dataList.get(2), "dropNext:button2", 2100, 3100, false);
+ checkRequestData(dataList.get(3), "dropNext:button1", 3100, 4100, false);
+ }
- public void testSizeExceededGroupingFireNew() throws Exception {
- renderView(VIEW_NAME);
+ public void testSizeExceededGroupingDropNew() throws Exception {
+ renderView(VIEW_NAME);
+ clickOnTime(0, "dropNew:button1");
+ clickOnTime(100, "dropNew:button2");
+ clickOnTime(200, "dropNew:button1");
+ clickOnTime(300, "dropNew:button2");
+ clickOnTime(2000, "dropNew:button1");
- clickOnTime(0, "fireNew:button1");
- clickOnTime(100, "fireNew:button2");
- clickOnTime(200, "fireNew:button1");
- clickOnTime(300, "fireNew:button2");
- clickOnTime(2000, "fireNew:button1");
+ TestsResult testsResult = getTestsResult();
+ List<RequestData> dataList = testsResult.getDataList();
- TestsResult testsResult = getTestsResult();
- List<RequestData> dataList = testsResult.getDataList();
-
- assertEquals(5, dataList.size());
- checkRequestData(dataList.get(0), "fireNew:button1", 100, 1100, false);
- checkRequestData(dataList.get(1), "fireNew:button2", 300, 1300, false);
-
- checkRequestData(dataList.get(2), "fireNew:button2", 1100, 2100, false);
- checkRequestData(dataList.get(3), "fireNew:button1", 2100, 3100, false);
- checkRequestData(dataList.get(4), "fireNew:button1", 3100, 4100, false);
- }
+ assertEquals(4, dataList.size());
+ checkRequestData(dataList.get(0), "dropNew:button1", 100, 1100, false);
+ checkRequestData(dataList.get(1), "dropNew:button2", 1100, 2100, false);
+ checkRequestData(dataList.get(2), "dropNew:button1", 2100, 3100, false);
+ checkRequestData(dataList.get(3), "dropNew:button1", 3100, 4100, false);
+ }
+
+ public void testSizeExceededGroupingFireNext() throws Exception {
+ renderView(VIEW_NAME);
+ clickOnTime(0, "fireNext:button1");
+ clickOnTime(100, "fireNext:button2");
+ clickOnTime(200, "fireNext:button1");
+ clickOnTime(300, "fireNext:button2");
+ clickOnTime(2000, "fireNext:button1");
+
+ TestsResult testsResult = getTestsResult();
+ List<RequestData> dataList = testsResult.getDataList();
+
+ assertEquals(5, dataList.size());
+ checkRequestData(dataList.get(0), "fireNext:button1", 100, 1100, false);
+ checkRequestData(dataList.get(1), "fireNext:button2", 300, 1300, false);
+ checkRequestData(dataList.get(2), "fireNext:button1", 1100, 2100, false);
+ checkRequestData(dataList.get(3), "fireNext:button2", 2100, 3100, false);
+ checkRequestData(dataList.get(4), "fireNext:button1", 3100, 4100, false);
+ }
+
+ public void testSizeExceededGroupingFireNew() throws Exception {
+ renderView(VIEW_NAME);
+ clickOnTime(0, "fireNew:button1");
+ clickOnTime(100, "fireNew:button2");
+ clickOnTime(200, "fireNew:button1");
+ clickOnTime(300, "fireNew:button2");
+ clickOnTime(2000, "fireNew:button1");
+
+ TestsResult testsResult = getTestsResult();
+ List<RequestData> dataList = testsResult.getDataList();
+
+ assertEquals(5, dataList.size());
+ checkRequestData(dataList.get(0), "fireNew:button1", 100, 1100, false);
+ checkRequestData(dataList.get(1), "fireNew:button2", 300, 1300, false);
+ checkRequestData(dataList.get(2), "fireNew:button2", 1100, 2100, false);
+ checkRequestData(dataList.get(3), "fireNew:button1", 2100, 3100, false);
+ checkRequestData(dataList.get(4), "fireNew:button1", 3100, 4100, false);
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueSizeTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueSizeTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueueSizeTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.text.NumberFormat;
+
import java.util.Iterator;
import java.util.List;
import java.util.Random;
@@ -30,393 +33,365 @@
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.ScriptableObject;
-
-
/**
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class QueueSizeTest extends AbstractQueueComponentTest {
+ private static final int numberOfEvents = 250;
- public QueueSizeTest(String name) {
- super(name);
- }
+ public QueueSizeTest(String name) {
+ super(name);
+ }
- private static final int numberOfEvents = 250;
-
- private static abstract interface SequenceGenerator<T> {
- public abstract T next();
- }
-
- protected TestsResult simulate(int numberOfEvents,
- SequenceGenerator<Integer> userDelayGenerator,
- SequenceGenerator<Integer> processTimeGenerator,
- SequenceGenerator<String> requestIdGenerator) throws Exception {
-
- NumberFormat numberFormat = NumberFormat.getInstance();
- numberFormat.setGroupingUsed(false);
- numberFormat.setMinimumIntegerDigits(String.valueOf(numberOfEvents).length());
-
- renderView("/queue-size.xhtml");
-
- ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("defaultSizeQueue");
+ protected TestsResult simulate(int numberOfEvents, SequenceGenerator<Integer> userDelayGenerator,
+ SequenceGenerator<Integer> processTimeGenerator,
+ SequenceGenerator<String> requestIdGenerator)
+ throws Exception {
+ NumberFormat numberFormat = NumberFormat.getInstance();
- int time = 0;
-
- for (int i = 0; i < numberOfEvents; i++) {
- int userDelay = userDelayGenerator.next();
- int requestTime = processTimeGenerator.next();
-
- time += userDelay;
- ajax(time, numberFormat.format(i), parametersBuilder.similarityGroupingId(requestIdGenerator.next()).
- requestTime(requestTime));
-
- }
+ numberFormat.setGroupingUsed(false);
+ numberFormat.setMinimumIntegerDigits(String.valueOf(numberOfEvents).length());
+ renderView("/queue-size.xhtml");
- TestsResult result = getTestsResult();
- return result;
- }
-
- protected void checkQueueOrdering(TestsResult result) throws Exception {
- double time = 0;
- String lastRequestId = "";
-
- List<RequestData> dataList = result.getDataList();
- Iterator<RequestData> itr = dataList.iterator();
- while (itr.hasNext()) {
- RequestData data = itr.next();
+ ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("defaultSizeQueue");
+ int time = 0;
- assertTrue(data.getStartTime() >= time);
- assertTrue(data.getEndTime() >= data.getStartTime());
- assertTrue(data.getData().compareTo(lastRequestId) > 0);
-
- lastRequestId = data.getData();
- time = data.getEndTime();
- }
- }
-
- private static final class UUIDGenerator implements SequenceGenerator<String> {
+ for (int i = 0; i < numberOfEvents; i++) {
+ int userDelay = userDelayGenerator.next();
+ int requestTime = processTimeGenerator.next();
- public String next() {
- return UUID.randomUUID().toString();
- }
-
- }
-
- private static final class RandomSequenceGenerator implements SequenceGenerator<Integer> {
+ time += userDelay;
+ ajax(time, numberFormat.format(i),
+ parametersBuilder.similarityGroupingId(requestIdGenerator.next()).requestTime(requestTime));
+ }
- private int offset;
-
- private int limit;
-
- public RandomSequenceGenerator(int minimum, int maximum) {
- super();
-
- this.limit = maximum - minimum;
- this.offset = minimum;
- }
+ TestsResult result = getTestsResult();
- private Random random = new Random();
-
- public Integer next() {
- return random.nextInt(this.limit) + this.offset;
- }
-
- }
-
- public void testUnlimitedOverload() throws Exception {
- TestsResult result = simulate(numberOfEvents,
- new RandomSequenceGenerator(5, 100),
- new RandomSequenceGenerator(50, 300),
- new UUIDGenerator()
- );
-
- checkQueueOrdering(result);
- assertEquals(numberOfEvents, result.getDataList().size());
- }
-
- public void testUnlimitedUnderload() throws Exception {
- TestsResult result = simulate(numberOfEvents,
- new RandomSequenceGenerator(50, 300),
- new RandomSequenceGenerator(5, 100),
- new UUIDGenerator()
- );
+ return result;
+ }
- checkQueueOrdering(result);
- assertEquals(numberOfEvents, result.getDataList().size());
- }
+ protected void checkQueueOrdering(TestsResult result) throws Exception {
+ double time = 0;
+ String lastRequestId = "";
+ List<RequestData> dataList = result.getDataList();
+ Iterator<RequestData> itr = dataList.iterator();
- private static final class TableRequestIdGenerator implements SequenceGenerator<String> {
- private static final String[] requestIds = new String[] {
- "aaa", "bbb", "ccc", "ddd", "eee", "fff"
- };
+ while (itr.hasNext()) {
+ RequestData data = itr.next();
- private Random random = new Random();
-
- private String lastValue;
-
- private int uniqueIdsCounter = 0;
-
- public String next() {
- String newValue = requestIds[random.nextInt(requestIds.length)];
-
- if (!newValue.equals(lastValue)) {
- lastValue = newValue;
- uniqueIdsCounter++;
- }
+ assertTrue(data.getStartTime() >= time);
+ assertTrue(data.getEndTime() >= data.getStartTime());
+ assertTrue(data.getData().compareTo(lastRequestId) > 0);
+ lastRequestId = data.getData();
+ time = data.getEndTime();
+ }
+ }
- return newValue;
- }
-
- public int getUniqueIdsCounter() {
- return uniqueIdsCounter;
- }
- };
+ public void testUnlimitedOverload() throws Exception {
+ TestsResult result = simulate(numberOfEvents, new RandomSequenceGenerator(5, 100),
+ new RandomSequenceGenerator(50, 300), new UUIDGenerator());
-
- public void testUnlimitedEmulateUser() throws Exception {
- TableRequestIdGenerator requestIdGenerator = new TableRequestIdGenerator();
-
- TestsResult result = simulate(numberOfEvents,
- new RandomSequenceGenerator(5, 100),
- new RandomSequenceGenerator(5, 100),
- requestIdGenerator
- );
+ checkQueueOrdering(result);
+ assertEquals(numberOfEvents, result.getDataList().size());
+ }
- checkQueueOrdering(result);
- assertTrue(requestIdGenerator.getUniqueIdsCounter() <= result.getDataList().size());
- assertTrue(result.getDataList().size() <= numberOfEvents);
- }
-
- protected TestsResult checkQueue(String queueName) throws Exception {
- renderView("/queue-size.xhtml");
-
- ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue(queueName).
- requestDelay(300).requestTime(300);
-
- ajax(0, "a", parametersBuilder.similarityGroupingId("a"));
- ajax(100, "b", parametersBuilder.similarityGroupingId("b"));
- ajax(200, "c", parametersBuilder.similarityGroupingId("c"));
- ajax(300, "d", parametersBuilder.similarityGroupingId("d"));
- ajax(500, "e", parametersBuilder.similarityGroupingId("e"));
- ajax(600, "f", parametersBuilder.similarityGroupingId("f"));
-
- TestsResult result = getTestsResult();
- return result;
- }
-
- protected TestsResult checkSingleQueue(String queueName) throws Exception {
- renderView("/queue-size.xhtml");
-
- ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue(queueName).
- requestTime(300).requestDelay(200);
+ public void testUnlimitedUnderload() throws Exception {
+ TestsResult result = simulate(numberOfEvents, new RandomSequenceGenerator(50, 300),
+ new RandomSequenceGenerator(5, 100), new UUIDGenerator());
- ajax(0, "a", parametersBuilder.similarityGroupingId("a"));
- ajax(100, "b", parametersBuilder.similarityGroupingId("b"));
- ajax(400, "c", parametersBuilder.similarityGroupingId("c"));
- ajax(500, "d", parametersBuilder.similarityGroupingId("d"));
- ajax(700, "e", parametersBuilder.similarityGroupingId("e"));
-
- ajax(9800, "f", parametersBuilder.similarityGroupingId("f").requestTime(1000));
- ajax(10100, "g", parametersBuilder.similarityGroupingId("f").requestTime(1500));
-
- TestsResult result = getTestsResult();
- return result;
- }
-
- public void testDropNext() throws Exception {
- TestsResult result = checkQueue("dropNextQueue");
- List<RequestData> dataList = result.getDataList();
-
- for (RequestData requestData : dataList) {
- System.out.println(" " + requestData);
- }
- System.out.println();
-
- assertEquals(4, dataList.size());
+ checkQueueOrdering(result);
+ assertEquals(numberOfEvents, result.getDataList().size());
+ }
- checkRequestData(dataList.get(0), "a", 100, 400, false);
- checkRequestData(dataList.get(1), "c", 400, 700, false);
- checkRequestData(dataList.get(2), "e", 700, 1000, false);
- checkRequestData(dataList.get(3), "f", 1000, 1300, false);
- }
-
- public void testDropNew() throws Exception {
- TestsResult result = checkQueue("dropNewQueue");
- List<RequestData> dataList = result.getDataList();
+ public void testUnlimitedEmulateUser() throws Exception {
+ TableRequestIdGenerator requestIdGenerator = new TableRequestIdGenerator();
+ TestsResult result = simulate(numberOfEvents, new RandomSequenceGenerator(5, 100),
+ new RandomSequenceGenerator(5, 100), requestIdGenerator);
- for (RequestData requestData : dataList) {
- System.out.println(" " + requestData);
- }
- System.out.println();
-
- assertEquals(4, dataList.size());
+ checkQueueOrdering(result);
+ assertTrue(requestIdGenerator.getUniqueIdsCounter() <= result.getDataList().size());
+ assertTrue(result.getDataList().size() <= numberOfEvents);
+ }
- checkRequestData(dataList.get(0), "a", 100, 400, false);
- checkRequestData(dataList.get(1), "b", 400, 700, false);
- checkRequestData(dataList.get(2), "c", 700, 1000, false);
- checkRequestData(dataList.get(3), "e", 1000, 1300, false);
- }
+ protected TestsResult checkQueue(String queueName) throws Exception {
+ renderView("/queue-size.xhtml");
- public void testFireNext() throws Exception {
- TestsResult result = checkQueue("fireNextQueue");
- List<RequestData> dataList = result.getDataList();
+ ParametersBuilder parametersBuilder =
+ createAjaxParameters().eventsQueue(queueName).requestDelay(300).requestTime(300);
- for (RequestData requestData : dataList) {
- System.out.println(" " + requestData);
- }
- System.out.println();
-
- assertEquals(6, dataList.size());
+ ajax(0, "a", parametersBuilder.similarityGroupingId("a"));
+ ajax(100, "b", parametersBuilder.similarityGroupingId("b"));
+ ajax(200, "c", parametersBuilder.similarityGroupingId("c"));
+ ajax(300, "d", parametersBuilder.similarityGroupingId("d"));
+ ajax(500, "e", parametersBuilder.similarityGroupingId("e"));
+ ajax(600, "f", parametersBuilder.similarityGroupingId("f"));
- checkRequestData(dataList.get(0), "a", 100, 400, false);
- checkRequestData(dataList.get(1), "b", 300, 600, false);
- checkRequestData(dataList.get(2), "c", 400, 700, false);
- checkRequestData(dataList.get(3), "d", 600, 900, false);
- checkRequestData(dataList.get(4), "e", 700, 1000, false);
- checkRequestData(dataList.get(5), "f", 1000, 1300, false);
- }
-
- public void testFireNew() throws Exception {
- TestsResult result = checkQueue("fireNewQueue");
- List<RequestData> dataList = result.getDataList();
+ TestsResult result = getTestsResult();
- for (RequestData requestData : dataList) {
- System.out.println(" " + requestData);
- }
- System.out.println();
-
- assertEquals(6, dataList.size());
+ return result;
+ }
- checkRequestData(dataList.get(0), "a", 100, 400, false);
- checkRequestData(dataList.get(1), "d", 300, 600, false);
- checkRequestData(dataList.get(2), "b", 400, 700, false);
- checkRequestData(dataList.get(3), "f", 600, 900, false);
- checkRequestData(dataList.get(4), "c", 700, 1000, false);
- checkRequestData(dataList.get(5), "e", 1000, 1300, false);
- }
-
- public void testDropNextSingle() throws Exception {
- TestsResult result = checkSingleQueue("dropNextQueueSingle");
- List<RequestData> dataList = result.getDataList();
-
- for (RequestData requestData : dataList) {
- System.out.println(" " + requestData);
- }
- System.out.println();
-
- assertEquals(3, dataList.size());
+ protected TestsResult checkSingleQueue(String queueName) throws Exception {
+ renderView("/queue-size.xhtml");
- checkRequestData(dataList.get(0), "b", 300, 600, false);
- checkRequestData(dataList.get(1), "e", 900, 1200, false);
- checkRequestData(dataList.get(2), "f", 10000, 11000, false);
- }
-
- public void testDropNewSingle() throws Exception {
- TestsResult result = checkSingleQueue("dropNewQueueSingle");
- List<RequestData> dataList = result.getDataList();
-
- for (RequestData requestData : dataList) {
- System.out.println(" " + requestData);
- }
- System.out.println();
-
- assertEquals(3, dataList.size());
+ ParametersBuilder parametersBuilder =
+ createAjaxParameters().eventsQueue(queueName).requestTime(300).requestDelay(200);
- checkRequestData(dataList.get(0), "a", 100, 400, false);
- checkRequestData(dataList.get(1), "d", 700, 1000, false);
- checkRequestData(dataList.get(2), "f", 10000, 11000, false);
- }
-
- public void testFireNextSingle() throws Exception {
- TestsResult result = checkSingleQueue("fireNextQueueSingle");
- List<RequestData> dataList = result.getDataList();
-
- for (RequestData requestData : dataList) {
- System.out.println(" " + requestData);
- }
- System.out.println();
-
- assertEquals(7, dataList.size());
+ ajax(0, "a", parametersBuilder.similarityGroupingId("a"));
+ ajax(100, "b", parametersBuilder.similarityGroupingId("b"));
+ ajax(400, "c", parametersBuilder.similarityGroupingId("c"));
+ ajax(500, "d", parametersBuilder.similarityGroupingId("d"));
+ ajax(700, "e", parametersBuilder.similarityGroupingId("e"));
+ ajax(9800, "f", parametersBuilder.similarityGroupingId("f").requestTime(1000));
+ ajax(10100, "g", parametersBuilder.similarityGroupingId("f").requestTime(1500));
- checkRequestData(dataList.get(0), "a", 100, 400, false);
- checkRequestData(dataList.get(1), "b", 300, 600, false);
- checkRequestData(dataList.get(2), "c", 400, 700, false);
- checkRequestData(dataList.get(3), "d", 500, 800, false);
- checkRequestData(dataList.get(4), "e", 900, 1200, false);
+ TestsResult result = getTestsResult();
- checkRequestData(dataList.get(5), "f", 10000, 11000, false);
- checkRequestData(dataList.get(6), "g", 10100, 11600, false);
- }
-
- public void testFireNewSingle() throws Exception {
- TestsResult result = checkSingleQueue("fireNewQueueSingle");
- List<RequestData> dataList = result.getDataList();
-
- for (RequestData requestData : dataList) {
- System.out.println(" " + requestData);
- }
- System.out.println();
-
- assertEquals(7, dataList.size());
+ return result;
+ }
- checkRequestData(dataList.get(0), "b", 100, 400, false);
- checkRequestData(dataList.get(1), "a", 100, 400, false);
- checkRequestData(dataList.get(2), "c", 400, 700, false);
- checkRequestData(dataList.get(3), "e", 700, 1000, false);
- checkRequestData(dataList.get(4), "d", 700, 1000, false);
+ public void testDropNext() throws Exception {
+ TestsResult result = checkQueue("dropNextQueue");
+ List<RequestData> dataList = result.getDataList();
- checkRequestData(dataList.get(5), "f", 10000, 11000, false);
- checkRequestData(dataList.get(6), "g", 10100, 11600, false);
- }
-
- public void testOnSizeExceeded() throws Exception {
- renderView("/queue-size.xhtml");
-
- for (int i = 0; i <= 3; i++) {
- clickOnTime(i, "form:button" + i);
- }
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(2, dataList.size());
-
- //dropNext is default
- checkRequestData(dataList.get(0), "form:button0", 0, DEFAULT_REQUEST_TIME, false);
- checkRequestData(dataList.get(1), "form:button3", DEFAULT_REQUEST_TIME, DEFAULT_REQUEST_TIME * 2, false);
-
- NativeArray handlersData = (NativeArray) executeJavaScript("defaultExceededQueueResults");
- assertEquals(2, handlersData.getLength());
-
- ScriptableObject firstHandlerData = (ScriptableObject) handlersData.get(0, handlersData);
- Double firstEventTime = (Double) firstHandlerData.get("_time", firstHandlerData);
- assertEquals(2d, firstEventTime);
-
- ScriptableObject secondHandlerData = (ScriptableObject) handlersData.get(1, handlersData);
- Double secondEventTime = (Double) secondHandlerData.get("_time", secondHandlerData);
- assertEquals(3d, secondEventTime);
- }
-
- public void testSingleSizedQueueIgnoreDupResponses() throws Exception {
- renderView("/queue-size.xhtml");
-
- ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("singleSizedDefaultQueue").
- requestDelay(0);
-
- ajax(0, "a", parametersBuilder);
- ajax(500, "b", parametersBuilder);
-
- TestsResult result = getTestsResult();
- List<RequestData> list = result.getDataList();
- assertEquals(1, list.size());
-
- checkRequestData(list.get(0), "a", 0, DEFAULT_REQUEST_TIME, false);
-
- NativeArray handlersData = (NativeArray) executeJavaScript("defaultSingleSizedQueueResults");
- assertEquals(1, handlersData.getLength());
-
- assertEquals("a", handlersData.get(0, handlersData));
- }
+ for (RequestData requestData : dataList) {
+ System.out.println(" " + requestData);
+ }
+
+ System.out.println();
+ assertEquals(4, dataList.size());
+ checkRequestData(dataList.get(0), "a", 100, 400, false);
+ checkRequestData(dataList.get(1), "c", 400, 700, false);
+ checkRequestData(dataList.get(2), "e", 700, 1000, false);
+ checkRequestData(dataList.get(3), "f", 1000, 1300, false);
+ }
+
+ public void testDropNew() throws Exception {
+ TestsResult result = checkQueue("dropNewQueue");
+ List<RequestData> dataList = result.getDataList();
+
+ for (RequestData requestData : dataList) {
+ System.out.println(" " + requestData);
+ }
+
+ System.out.println();
+ assertEquals(4, dataList.size());
+ checkRequestData(dataList.get(0), "a", 100, 400, false);
+ checkRequestData(dataList.get(1), "b", 400, 700, false);
+ checkRequestData(dataList.get(2), "c", 700, 1000, false);
+ checkRequestData(dataList.get(3), "e", 1000, 1300, false);
+ }
+
+ public void testFireNext() throws Exception {
+ TestsResult result = checkQueue("fireNextQueue");
+ List<RequestData> dataList = result.getDataList();
+
+ for (RequestData requestData : dataList) {
+ System.out.println(" " + requestData);
+ }
+
+ System.out.println();
+ assertEquals(6, dataList.size());
+ checkRequestData(dataList.get(0), "a", 100, 400, false);
+ checkRequestData(dataList.get(1), "b", 300, 600, false);
+ checkRequestData(dataList.get(2), "c", 400, 700, false);
+ checkRequestData(dataList.get(3), "d", 600, 900, false);
+ checkRequestData(dataList.get(4), "e", 700, 1000, false);
+ checkRequestData(dataList.get(5), "f", 1000, 1300, false);
+ }
+
+ public void testFireNew() throws Exception {
+ TestsResult result = checkQueue("fireNewQueue");
+ List<RequestData> dataList = result.getDataList();
+
+ for (RequestData requestData : dataList) {
+ System.out.println(" " + requestData);
+ }
+
+ System.out.println();
+ assertEquals(6, dataList.size());
+ checkRequestData(dataList.get(0), "a", 100, 400, false);
+ checkRequestData(dataList.get(1), "d", 300, 600, false);
+ checkRequestData(dataList.get(2), "b", 400, 700, false);
+ checkRequestData(dataList.get(3), "f", 600, 900, false);
+ checkRequestData(dataList.get(4), "c", 700, 1000, false);
+ checkRequestData(dataList.get(5), "e", 1000, 1300, false);
+ }
+
+ public void testDropNextSingle() throws Exception {
+ TestsResult result = checkSingleQueue("dropNextQueueSingle");
+ List<RequestData> dataList = result.getDataList();
+
+ for (RequestData requestData : dataList) {
+ System.out.println(" " + requestData);
+ }
+
+ System.out.println();
+ assertEquals(3, dataList.size());
+ checkRequestData(dataList.get(0), "b", 300, 600, false);
+ checkRequestData(dataList.get(1), "e", 900, 1200, false);
+ checkRequestData(dataList.get(2), "f", 10000, 11000, false);
+ }
+
+ public void testDropNewSingle() throws Exception {
+ TestsResult result = checkSingleQueue("dropNewQueueSingle");
+ List<RequestData> dataList = result.getDataList();
+
+ for (RequestData requestData : dataList) {
+ System.out.println(" " + requestData);
+ }
+
+ System.out.println();
+ assertEquals(3, dataList.size());
+ checkRequestData(dataList.get(0), "a", 100, 400, false);
+ checkRequestData(dataList.get(1), "d", 700, 1000, false);
+ checkRequestData(dataList.get(2), "f", 10000, 11000, false);
+ }
+
+ public void testFireNextSingle() throws Exception {
+ TestsResult result = checkSingleQueue("fireNextQueueSingle");
+ List<RequestData> dataList = result.getDataList();
+
+ for (RequestData requestData : dataList) {
+ System.out.println(" " + requestData);
+ }
+
+ System.out.println();
+ assertEquals(7, dataList.size());
+ checkRequestData(dataList.get(0), "a", 100, 400, false);
+ checkRequestData(dataList.get(1), "b", 300, 600, false);
+ checkRequestData(dataList.get(2), "c", 400, 700, false);
+ checkRequestData(dataList.get(3), "d", 500, 800, false);
+ checkRequestData(dataList.get(4), "e", 900, 1200, false);
+ checkRequestData(dataList.get(5), "f", 10000, 11000, false);
+ checkRequestData(dataList.get(6), "g", 10100, 11600, false);
+ }
+
+ public void testFireNewSingle() throws Exception {
+ TestsResult result = checkSingleQueue("fireNewQueueSingle");
+ List<RequestData> dataList = result.getDataList();
+
+ for (RequestData requestData : dataList) {
+ System.out.println(" " + requestData);
+ }
+
+ System.out.println();
+ assertEquals(7, dataList.size());
+ checkRequestData(dataList.get(0), "b", 100, 400, false);
+ checkRequestData(dataList.get(1), "a", 100, 400, false);
+ checkRequestData(dataList.get(2), "c", 400, 700, false);
+ checkRequestData(dataList.get(3), "e", 700, 1000, false);
+ checkRequestData(dataList.get(4), "d", 700, 1000, false);
+ checkRequestData(dataList.get(5), "f", 10000, 11000, false);
+ checkRequestData(dataList.get(6), "g", 10100, 11600, false);
+ }
+
+ public void testOnSizeExceeded() throws Exception {
+ renderView("/queue-size.xhtml");
+
+ for (int i = 0; i <= 3; i++) {
+ clickOnTime(i, "form:button" + i);
+ }
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(2, dataList.size());
+
+ // dropNext is default
+ checkRequestData(dataList.get(0), "form:button0", 0, DEFAULT_REQUEST_TIME, false);
+ checkRequestData(dataList.get(1), "form:button3", DEFAULT_REQUEST_TIME, DEFAULT_REQUEST_TIME * 2, false);
+
+ NativeArray handlersData = (NativeArray) executeJavaScript("defaultExceededQueueResults");
+
+ assertEquals(2, handlersData.getLength());
+
+ ScriptableObject firstHandlerData = (ScriptableObject) handlersData.get(0, handlersData);
+ Double firstEventTime = (Double) firstHandlerData.get("_time", firstHandlerData);
+
+ assertEquals(2d, firstEventTime);
+
+ ScriptableObject secondHandlerData = (ScriptableObject) handlersData.get(1, handlersData);
+ Double secondEventTime = (Double) secondHandlerData.get("_time", secondHandlerData);
+
+ assertEquals(3d, secondEventTime);
+ }
+
+ public void testSingleSizedQueueIgnoreDupResponses() throws Exception {
+ renderView("/queue-size.xhtml");
+
+ ParametersBuilder parametersBuilder =
+ createAjaxParameters().eventsQueue("singleSizedDefaultQueue").requestDelay(0);
+
+ ajax(0, "a", parametersBuilder);
+ ajax(500, "b", parametersBuilder);
+
+ TestsResult result = getTestsResult();
+ List<RequestData> list = result.getDataList();
+
+ assertEquals(1, list.size());
+ checkRequestData(list.get(0), "a", 0, DEFAULT_REQUEST_TIME, false);
+
+ NativeArray handlersData = (NativeArray) executeJavaScript("defaultSingleSizedQueueResults");
+
+ assertEquals(1, handlersData.getLength());
+ assertEquals("a", handlersData.get(0, handlersData));
+ }
+
+ private static abstract interface SequenceGenerator<T> {
+ public abstract T next();
+ }
+
+
+ private static final class RandomSequenceGenerator implements SequenceGenerator<Integer> {
+ private Random random = new Random();
+ private int limit;
+ private int offset;
+
+ public RandomSequenceGenerator(int minimum, int maximum) {
+ super();
+ this.limit = maximum - minimum;
+ this.offset = minimum;
+ }
+
+ public Integer next() {
+ return random.nextInt(this.limit) + this.offset;
+ }
+ }
+
+
+ private static final class TableRequestIdGenerator implements SequenceGenerator<String> {
+ private static final String[] requestIds = new String[] {
+ "aaa", "bbb", "ccc", "ddd", "eee", "fff"
+ };
+ private Random random = new Random();
+ private int uniqueIdsCounter = 0;
+ private String lastValue;
+
+ public String next() {
+ String newValue = requestIds[random.nextInt(requestIds.length)];
+
+ if (!newValue.equals(lastValue)) {
+ lastValue = newValue;
+ uniqueIdsCounter++;
+ }
+
+ return newValue;
+ }
+
+ public int getUniqueIdsCounter() {
+ return uniqueIdsCounter;
+ }
+ }
+
+
+ private static final class UUIDGenerator implements SequenceGenerator<String> {
+ public String next() {
+ return UUID.randomUUID().toString();
+ }
+ }
+
+
+ ;
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueuedPollTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueuedPollTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/QueuedPollTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,153 +19,151 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.List;
import java.util.Map;
-
/**
* @author Nick Belaevski
* @since 3.3.0
*/
-
public class QueuedPollTest extends AbstractQueueComponentTest {
- /**
- * @param name
- */
- public QueuedPollTest(String name) {
- super(name);
- }
+ /**
+ * @param name
+ */
+ public QueuedPollTest(String name) {
+ super(name);
+ }
- private void setFlag(String name) {
- Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
- requestMap.put(name, Boolean.TRUE);
- }
-
- public void testQueuedDefaultPollRequestDelay() throws Exception {
- setFlag("queuedDefaultPollEnabled");
- renderView("/queue-poll.xhtml");
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(1, dataList.size());
- checkRequestData(dataList.get(0), "firstForm:queuedDefaultPoll", 600, 1600, false);
- }
-
- public void testQueuedPollRequestDelay() throws Exception {
- setFlag("queuedDelayedPollEnabled");
- renderView("/queue-poll.xhtml");
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(1, dataList.size());
- checkRequestData(dataList.get(0), "firstForm:queuedDelayedPoll", 300, 1300, false);
- }
-
- public void testDelayedQueueDefaultPollRequestDelay() throws Exception {
- setFlag("delayedQueueDefaultPollEnabled");
- renderView("/queue-poll.xhtml");
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(1, dataList.size());
- checkRequestData(dataList.get(0), "secondForm:delayedQueueDefaultPoll", 1500, 2500, false);
- }
-
- public void testDelayedQueuePollRequestDelay() throws Exception {
- setFlag("delayedQueueDelayedPollEnabled");
- renderView("/queue-poll.xhtml");
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(1, dataList.size());
- checkRequestData(dataList.get(0), "secondForm:delayedQueueDelayedPoll", 2400, 3400, false);
- }
-
- public void testUnqueuedDefaultPollRequestDelay() throws Exception {
- setFlag("unqueuedDefaultPollEnabled");
- renderView("/queue-poll.xhtml");
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(1, dataList.size());
- checkRequestData(dataList.get(0), "thirdForm:unqueuedDefaultPoll", 700, 1700, false);
- }
-
- public void testunQueuedPollRequestDelay() throws Exception {
- setFlag("unqueuedDelayedPollEnabled");
- renderView("/queue-poll.xhtml");
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
-
- assertEquals(1, dataList.size());
- checkRequestData(dataList.get(0), "thirdForm:unqueuedDelayedPoll", 950, 1950, false);
- }
-
- public void testDropNextDroppedPoll() throws Exception {
- setFlag("renderDropNext");
- renderView("/queue-poll-drop.xhtml");
-
- ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("dropNextQueue").
- requestDelay(0);
-
- ajax(0, "a", parametersBuilder.similarityGroupingId(1).requestTime(3000));
-
- //poll has 2000 interval, so ajax request at 2100 will make queue drop it from list
- ajax(2500, "b", parametersBuilder.similarityGroupingId(2).requestTime(500));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
- assertEquals(3, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 0, 3000, false);
- checkRequestData(dataList.get(1), "b", 3000, 3500, false);
-
- //poll has been kicked from queue at 2500, requeued in 2000
- checkRequestData(dataList.get(2), "firstForm:poll", 2500 + 2000, 2500 + 2000 + 1000 /* default request time */,
- false);
- }
-
- public void testDropNextDroppedPollSingle() throws Exception {
- setFlag("renderDropNextSingle");
- renderView("/queue-poll-drop.xhtml");
-
- ajax(0, "a", createAjaxParameters().requestTime(3000).requestDelay(0).eventsQueue("dropNextQueueSingle"));
-
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
- assertEquals(2, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 0, 3000, false);
- checkRequestData(dataList.get(1), "thirdForm:poll", 4000, 5000, false);
- }
-
- public void testDropNewDroppedPoll() throws Exception {
- setFlag("renderDropNew");
- renderView("/queue-poll-drop.xhtml");
+ private void setFlag(String name) {
+ Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
- ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("dropNewQueue").
- requestDelay(0);
+ requestMap.put(name, Boolean.TRUE);
+ }
- ajax(0, "a", parametersBuilder.similarityGroupingId(1).requestTime(3000));
-
- //poll has 2500 interval, so ajax request at 2000 will make queue drop it from the list
- ajax(2000, "b", parametersBuilder.similarityGroupingId(2).requestTime(500));
+ public void testQueuedDefaultPollRequestDelay() throws Exception {
+ setFlag("queuedDefaultPollEnabled");
+ renderView("/queue-poll.xhtml");
- TestsResult result = getTestsResult();
- List<RequestData> dataList = result.getDataList();
- assertEquals(3, dataList.size());
-
- checkRequestData(dataList.get(0), "a", 0, 3000, false);
- checkRequestData(dataList.get(1), "b", 3000, 3500, false);
- checkRequestData(dataList.get(2), "secondForm:poll", 5000, 6000, false);
- }
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(1, dataList.size());
+ checkRequestData(dataList.get(0), "firstForm:queuedDefaultPoll", 600, 1600, false);
+ }
+
+ public void testQueuedPollRequestDelay() throws Exception {
+ setFlag("queuedDelayedPollEnabled");
+ renderView("/queue-poll.xhtml");
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(1, dataList.size());
+ checkRequestData(dataList.get(0), "firstForm:queuedDelayedPoll", 300, 1300, false);
+ }
+
+ public void testDelayedQueueDefaultPollRequestDelay() throws Exception {
+ setFlag("delayedQueueDefaultPollEnabled");
+ renderView("/queue-poll.xhtml");
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(1, dataList.size());
+ checkRequestData(dataList.get(0), "secondForm:delayedQueueDefaultPoll", 1500, 2500, false);
+ }
+
+ public void testDelayedQueuePollRequestDelay() throws Exception {
+ setFlag("delayedQueueDelayedPollEnabled");
+ renderView("/queue-poll.xhtml");
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(1, dataList.size());
+ checkRequestData(dataList.get(0), "secondForm:delayedQueueDelayedPoll", 2400, 3400, false);
+ }
+
+ public void testUnqueuedDefaultPollRequestDelay() throws Exception {
+ setFlag("unqueuedDefaultPollEnabled");
+ renderView("/queue-poll.xhtml");
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(1, dataList.size());
+ checkRequestData(dataList.get(0), "thirdForm:unqueuedDefaultPoll", 700, 1700, false);
+ }
+
+ public void testunQueuedPollRequestDelay() throws Exception {
+ setFlag("unqueuedDelayedPollEnabled");
+ renderView("/queue-poll.xhtml");
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(1, dataList.size());
+ checkRequestData(dataList.get(0), "thirdForm:unqueuedDelayedPoll", 950, 1950, false);
+ }
+
+ public void testDropNextDroppedPoll() throws Exception {
+ setFlag("renderDropNext");
+ renderView("/queue-poll-drop.xhtml");
+
+ ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("dropNextQueue").requestDelay(0);
+
+ ajax(0, "a", parametersBuilder.similarityGroupingId(1).requestTime(3000));
+
+ // poll has 2000 interval, so ajax request at 2100 will make queue drop it from list
+ ajax(2500, "b", parametersBuilder.similarityGroupingId(2).requestTime(500));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(3, dataList.size());
+ checkRequestData(dataList.get(0), "a", 0, 3000, false);
+ checkRequestData(dataList.get(1), "b", 3000, 3500, false);
+
+ // poll has been kicked from queue at 2500, requeued in 2000
+ checkRequestData(dataList.get(2), "firstForm:poll", 2500 + 2000, 2500 + 2000 + 1000 /* default request time */,
+ false);
+ }
+
+ public void testDropNextDroppedPollSingle() throws Exception {
+ setFlag("renderDropNextSingle");
+ renderView("/queue-poll-drop.xhtml");
+ ajax(0, "a", createAjaxParameters().requestTime(3000).requestDelay(0).eventsQueue("dropNextQueueSingle"));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(2, dataList.size());
+ checkRequestData(dataList.get(0), "a", 0, 3000, false);
+ checkRequestData(dataList.get(1), "thirdForm:poll", 4000, 5000, false);
+ }
+
+ public void testDropNewDroppedPoll() throws Exception {
+ setFlag("renderDropNew");
+ renderView("/queue-poll-drop.xhtml");
+
+ ParametersBuilder parametersBuilder = createAjaxParameters().eventsQueue("dropNewQueue").requestDelay(0);
+
+ ajax(0, "a", parametersBuilder.similarityGroupingId(1).requestTime(3000));
+
+ // poll has 2500 interval, so ajax request at 2000 will make queue drop it from the list
+ ajax(2000, "b", parametersBuilder.similarityGroupingId(2).requestTime(500));
+
+ TestsResult result = getTestsResult();
+ List<RequestData> dataList = result.getDataList();
+
+ assertEquals(3, dataList.size());
+ checkRequestData(dataList.get(0), "a", 0, 3000, false);
+ checkRequestData(dataList.get(1), "b", 3000, 3500, false);
+ checkRequestData(dataList.get(2), "secondForm:poll", 5000, 6000, false);
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/RepeatTestCase.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/RepeatTestCase.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/RepeatTestCase.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.component;
import java.util.ArrayList;
@@ -40,207 +42,217 @@
*
*/
public class RepeatTestCase extends AbstractAjax4JsfTestCase {
+ private UIInput child;
+ private UIInput childChild;
+ private UIInput childChildFacet;
+ private int childChildFacetInvoked;
+ private int childChildInvoked;
+ private int childInvoked;
+ private UIRepeat enclosedRepeater;
+ private UIInput facetChild;
+ private int facetInvoked;
+ private UIRepeat repeater;
- private UIRepeat repeater;
-
- private UIInput child;
-
- private int childInvoked;
-
- private UIInput facetChild;
-
- private int facetInvoked;
+ /**
+ * @param name
+ */
+ public RepeatTestCase(String name) {
+ super(name);
+ }
- private UIInput childChild;
-
- private int childChildInvoked;
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
+ */
+ public void setUp() throws Exception {
+ super.setUp();
- private UIInput childChildFacet;
-
- private int childChildFacetInvoked;
+ // Create mock DataAdaptor and childs.
+ repeater = new UIRepeat();
+ child = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ childInvoked++;
+ super.processDecodes(context);
+ }
+ };
+ childInvoked = 0;
+ child.setId("child");
+ repeater.getChildren().add(child);
+ facetChild = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ facetInvoked++;
+ super.processDecodes(context);
+ }
+ };
+ facetInvoked = 0;
+ facetChild.setId("facetChild");
+ repeater.getFacets().put("facet", facetChild);
+ childChild = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ childChildInvoked++;
+ super.processDecodes(context);
+ }
+ };;
+ childChildInvoked = 0;
+ childChild.setId("childChild");
+ child.getChildren().add(childChild);
+ childChildFacet = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ childChildFacetInvoked++;
+ super.processDecodes(context);
+ }
+ };;
+ childChildFacetInvoked = 0;
+ childChildFacet.setId("childChildFacet");
+ childChild.getFacets().put("facet", childChildFacet);
+ enclosedRepeater = new UIRepeat();
+ renderKit.addRenderer(child.getFamily(), child.getRendererType(), new MockUIInputRenderer() {
+ public void decode(FacesContext context, UIComponent component) {
+ super.decode(context, component);
- private UIRepeat enclosedRepeater;
- /**
- * @param name
- */
- public RepeatTestCase(String name) {
- super(name);
- }
+ UIInput input = (UIInput) component;
+ String submittedValie = enclosedRepeater.getRowKey() + ":" + repeater.getRowKey();
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#setUp()
- */
- public void setUp() throws Exception {
- super.setUp();
- // Create mock DataAdaptor and childs.
- repeater = new UIRepeat();
- child = new UIInput(){
- public void processDecodes(FacesContext context) {
- childInvoked++;
- super.processDecodes(context);
- }
- };
- childInvoked = 0;
- child.setId("child");
- repeater.getChildren().add(child);
- facetChild = new UIInput(){
- public void processDecodes(FacesContext context) {
- facetInvoked++;
- super.processDecodes(context);
- }
- };
- facetInvoked = 0;
- facetChild.setId("facetChild");
- repeater.getFacets().put("facet", facetChild);
- childChild = new UIInput(){
- public void processDecodes(FacesContext context) {
- childChildInvoked++;
- super.processDecodes(context);
- }
- };;
- childChildInvoked = 0;
- childChild.setId("childChild");
- child.getChildren().add(childChild);
- childChildFacet = new UIInput(){
- public void processDecodes(FacesContext context) {
- childChildFacetInvoked++;
- super.processDecodes(context);
- }
- };;
- childChildFacetInvoked = 0;
- childChildFacet.setId("childChildFacet");
- childChild.getFacets().put("facet", childChildFacet);
- enclosedRepeater = new UIRepeat();
- renderKit.addRenderer(child.getFamily(), child.getRendererType(), new MockUIInputRenderer(){
- public void decode(FacesContext context, UIComponent component) {
- super.decode(context, component);
- UIInput input = (UIInput) component;
- String submittedValie = enclosedRepeater.getRowKey()+":"+repeater.getRowKey();
- input.setSubmittedValue(submittedValie);
- System.out.println("decode component "+component.getClientId(facesContext)+" with value "+submittedValie);
- }
- });
- renderKit.addRenderer(repeater.getFamily(), repeater.getRendererType(), new RepeatRenderer());
- }
+ input.setSubmittedValue(submittedValie);
+ System.out.println("decode component " + component.getClientId(facesContext) + " with value "
+ + submittedValie);
+ }
+ });
+ renderKit.addRenderer(repeater.getFamily(), repeater.getRendererType(), new RepeatRenderer());
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
- */
- public void tearDown() throws Exception {
- super.tearDown();
- repeater = null;
- child = null;
- childChild = null;
- childChildFacet = null;
- facetChild = null;
- enclosedRepeater = null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.ajax4jsf.tests.AbstractAjax4JsfTestCase#tearDown()
+ */
+ public void tearDown() throws Exception {
+ super.tearDown();
+ repeater = null;
+ child = null;
+ childChild = null;
+ childChildFacet = null;
+ facetChild = null;
+ enclosedRepeater = null;
+ }
+ private void createDataTree() {
+ enclosedRepeater.setId("data");
+ repeater.setId("adaptor");
+ repeater.setVar("row");
- private void createDataTree(){
- enclosedRepeater.setId("data");
- repeater.setId("adaptor");
- repeater.setVar("row");
- ArrayList value = new ArrayList(2);
- value.add("first");
- value.add("second");
- enclosedRepeater.setValue(value);
- enclosedRepeater.setVar("var");
- UIColumn column = new UIColumn();
- enclosedRepeater.getChildren().add(column);
- column.getChildren().add(repeater);
- facesContext.getViewRoot().getChildren().add(enclosedRepeater);
- }
-
- private void printChildMap(Map childrenState){
- System.out.println("{");
- for (Iterator iter = childrenState.keySet().iterator(); iter.hasNext();) {
- Object key = iter.next();
- System.out.println(" "+key+" : "+childrenState.get(key));
- }
- System.out.println("}");
- }
- /**
- * Test method for {@link javax.faces.component.UIData#processDecodes(javax.faces.context.FacesContext)}.
- */
- public void testProcessDecodesFacesContext() {
- createDataTree();
- repeater.setValue(new MockDataModel());
-// enclosedRepeater.setValue(new MockDataModel());
- enclosedRepeater.processDecodes(facesContext);
- enclosedRepeater.setRowIndex(1);
- repeater.setRowIndex(1);
- System.out.println("Saved child state for external repeater ");
- printChildMap(enclosedRepeater.getChildState(facesContext));
- System.out.println("Saved child state" );
- printChildMap(repeater.getChildState(facesContext));
- assertEquals("1:1", child.getSubmittedValue());
- }
+ ArrayList value = new ArrayList(2);
- /**
- * Test method for {@link javax.faces.component.UIData#processUpdates(javax.faces.context.FacesContext)}.
- */
- public void testProcessUpdatesFacesContext() {
- createDataTree();
- repeater.setValue(new MockDataModel());
-// enclosedRepeater.setValue(new MockDataModel());
- enclosedRepeater.processDecodes(facesContext);
- enclosedRepeater.processValidators(facesContext);
- enclosedRepeater.processUpdates(facesContext);
- enclosedRepeater.setRowIndex(1);
- repeater.setRowIndex(1);
- assertEquals("1:1", child.getValue());
- enclosedRepeater.setRowIndex(0);
- repeater.setRowIndex(2);
- assertEquals("0:2", child.getValue());
- }
+ value.add("first");
+ value.add("second");
+ enclosedRepeater.setValue(value);
+ enclosedRepeater.setVar("var");
- /**
- * Test method for {@link javax.faces.component.UIData#processUpdates(javax.faces.context.FacesContext)}.
- */
- public void testProcessValidatorsFacesContext() {
- createDataTree();
- repeater.setValue(new MockDataModel());
-// enclosedRepeater.setValue(new MockDataModel());
- enclosedRepeater.processDecodes(facesContext);
- enclosedRepeater.processValidators(facesContext);
- enclosedRepeater.setRowIndex(1);
- repeater.setRowIndex(1);
- assertEquals("1:1", child.getLocalValue());
- enclosedRepeater.setRowIndex(0);
- repeater.setRowIndex(2);
- assertEquals("0:2", child.getLocalValue());
- }
-
- public void testSetRowIndex() throws Exception {
- createDataTree();
- repeater.setValue(new MockDataModel());
- enclosedRepeater.setRowIndex(1);
- repeater.setRowIndex(1);
- child.setValue("1:1");
- repeater.setRowIndex(-1);
- enclosedRepeater.setRowIndex(-1);
- // -----------------------------
- enclosedRepeater.setRowIndex(0);
- repeater.setRowIndex(2);
- child.setValue("0:2");
- // -----------------------------
- repeater.setRowIndex(-1);
- enclosedRepeater.setRowIndex(-1);
- System.out.println("Saved child state for external repeater ");
- printChildMap(enclosedRepeater.getChildState(facesContext));
- System.out.println("Saved child state" );
- printChildMap(repeater.getChildState(facesContext));
- // -----------------------------
- enclosedRepeater.setRowIndex(1);
- repeater.setRowIndex(1);
- assertEquals("1:1", child.getValue());
- repeater.setRowIndex(-1);
- enclosedRepeater.setRowIndex(-1);
- // -----------------------------
- enclosedRepeater.setRowIndex(0);
- repeater.setRowIndex(2);
- assertEquals("0:2", child.getValue());
-
- }
+ UIColumn column = new UIColumn();
+
+ enclosedRepeater.getChildren().add(column);
+ column.getChildren().add(repeater);
+ facesContext.getViewRoot().getChildren().add(enclosedRepeater);
+ }
+
+ private void printChildMap(Map childrenState) {
+ System.out.println("{");
+
+ for (Iterator iter = childrenState.keySet().iterator(); iter.hasNext(); ) {
+ Object key = iter.next();
+
+ System.out.println(" " + key + " : " + childrenState.get(key));
+ }
+
+ System.out.println("}");
+ }
+
+ /**
+ * Test method for {@link javax.faces.component.UIData#processDecodes(javax.faces.context.FacesContext)}.
+ */
+ public void testProcessDecodesFacesContext() {
+ createDataTree();
+ repeater.setValue(new MockDataModel());
+
+// enclosedRepeater.setValue(new MockDataModel());
+ enclosedRepeater.processDecodes(facesContext);
+ enclosedRepeater.setRowIndex(1);
+ repeater.setRowIndex(1);
+ System.out.println("Saved child state for external repeater ");
+ printChildMap(enclosedRepeater.getChildState(facesContext));
+ System.out.println("Saved child state");
+ printChildMap(repeater.getChildState(facesContext));
+ assertEquals("1:1", child.getSubmittedValue());
+ }
+
+ /**
+ * Test method for {@link javax.faces.component.UIData#processUpdates(javax.faces.context.FacesContext)}.
+ */
+ public void testProcessUpdatesFacesContext() {
+ createDataTree();
+ repeater.setValue(new MockDataModel());
+
+// enclosedRepeater.setValue(new MockDataModel());
+ enclosedRepeater.processDecodes(facesContext);
+ enclosedRepeater.processValidators(facesContext);
+ enclosedRepeater.processUpdates(facesContext);
+ enclosedRepeater.setRowIndex(1);
+ repeater.setRowIndex(1);
+ assertEquals("1:1", child.getValue());
+ enclosedRepeater.setRowIndex(0);
+ repeater.setRowIndex(2);
+ assertEquals("0:2", child.getValue());
+ }
+
+ /**
+ * Test method for {@link javax.faces.component.UIData#processUpdates(javax.faces.context.FacesContext)}.
+ */
+ public void testProcessValidatorsFacesContext() {
+ createDataTree();
+ repeater.setValue(new MockDataModel());
+
+// enclosedRepeater.setValue(new MockDataModel());
+ enclosedRepeater.processDecodes(facesContext);
+ enclosedRepeater.processValidators(facesContext);
+ enclosedRepeater.setRowIndex(1);
+ repeater.setRowIndex(1);
+ assertEquals("1:1", child.getLocalValue());
+ enclosedRepeater.setRowIndex(0);
+ repeater.setRowIndex(2);
+ assertEquals("0:2", child.getLocalValue());
+ }
+
+ public void testSetRowIndex() throws Exception {
+ createDataTree();
+ repeater.setValue(new MockDataModel());
+ enclosedRepeater.setRowIndex(1);
+ repeater.setRowIndex(1);
+ child.setValue("1:1");
+ repeater.setRowIndex(-1);
+ enclosedRepeater.setRowIndex(-1);
+
+ // -----------------------------
+ enclosedRepeater.setRowIndex(0);
+ repeater.setRowIndex(2);
+ child.setValue("0:2");
+
+ // -----------------------------
+ repeater.setRowIndex(-1);
+ enclosedRepeater.setRowIndex(-1);
+ System.out.println("Saved child state for external repeater ");
+ printChildMap(enclosedRepeater.getChildState(facesContext));
+ System.out.println("Saved child state");
+ printChildMap(repeater.getChildState(facesContext));
+
+ // -----------------------------
+ enclosedRepeater.setRowIndex(1);
+ repeater.setRowIndex(1);
+ assertEquals("1:1", child.getValue());
+ repeater.setRowIndex(-1);
+ enclosedRepeater.setRowIndex(-1);
+
+ // -----------------------------
+ enclosedRepeater.setRowIndex(0);
+ repeater.setRowIndex(2);
+ assertEquals("0:2", child.getValue());
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/UIAjaxFormTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/UIAjaxFormTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/component/UIAjaxFormTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -18,6 +18,9 @@
* 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.component;
import java.io.Serializable;
@@ -33,100 +36,90 @@
import org.ajax4jsf.component.ActionListenerTest.Bean;
import org.ajax4jsf.event.AjaxEvent;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.richfaces.event.DataScrollerEvent;
import org.richfaces.event.DataScrollerListener;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class UIAjaxFormTest extends AbstractAjax4JsfTestCase {
+ private UIAjaxForm ajaxForm;
+ private UIInput child;
+ private int childInvoked;
+ private boolean result;
- private UIAjaxForm ajaxForm;
- private UIInput child;
- private boolean result;
- private int childInvoked;
+ public UIAjaxFormTest(String name) {
+ super(name);
+ }
- public UIAjaxFormTest(String name) {
- super(name);
- }
+ public void setUp() throws Exception {
+ super.setUp();
+ ajaxForm = (UIAjaxForm) application.createComponent(UIAjaxForm.COMPONENT_TYPE);
+ ajaxForm.setId("form");
+ child = new UIInput() {
+ public void processDecodes(FacesContext context) {
+ childInvoked++;
+ super.processDecodes(context);
+ }
+ };
+ child.setId("input");
+ child.addValidator(new TestAjaxFormValidator());
+ childInvoked = 0;
+ child.setId("child");
+ ajaxForm.getChildren().add(child);
+ facesContext.getViewRoot().getChildren().add(ajaxForm);
+ }
- public void setUp() throws Exception {
+ public void testTest() throws Exception {
+ HtmlPage page = renderView();
- super.setUp();
- ajaxForm = (UIAjaxForm) application
- .createComponent(UIAjaxForm.COMPONENT_TYPE);
- ajaxForm.setId("form");
+ // System.out.println(page.asXml());
+ }
- child = new UIInput() {
- public void processDecodes(FacesContext context) {
- childInvoked++;
- super.processDecodes(context);
- }
- };
- child.setId("input");
- child.addValidator(new TestAjaxFormValidator());
- childInvoked = 0;
- child.setId("child");
- ajaxForm.getChildren().add(child);
- facesContext.getViewRoot().getChildren().add(ajaxForm);
- }
+ public void testProcessDecodes() throws Exception {
+ facesContext.getExternalContext().getRequestParameterMap().put("form", "form");
+ ajaxForm.processDecodes(facesContext);
+ assertEquals(1, childInvoked);
- public void testTest() throws Exception {
+ // test
+ }
- HtmlPage page = renderView();
- // System.out.println(page.asXml());
- }
+ public void testProcessValidators() throws Exception {
+ result = false;
+ ajaxForm.setSubmitted(true);
+ child.setSubmittedValue(new String("test0"));
+ ajaxForm.processValidators(facesContext);
+ assertTrue(result);
+ }
- public void testProcessDecodes() throws Exception {
+ // TODO processUpdates test
+ public void testProcessUpdates() throws Exception {
+ facesContext.getExternalContext().getRequestParameterMap().put("form", "form");
+ child.setSubmittedValue(new String("test1"));
+ ajaxForm.processDecodes(facesContext);
+ ajaxForm.processValidators(facesContext);
+ ajaxForm.processUpdates(facesContext);
+ }
- facesContext.getExternalContext().getRequestParameterMap().put("form",
- "form");
- ajaxForm.processDecodes(facesContext);
- assertEquals(1, childInvoked);
- // test
- }
+ public void testBroadcast() throws Exception {
+ AjaxEvent event = new AjaxEvent(ajaxForm);
- public void testProcessValidators() throws Exception {
+ try {
+ ajaxForm.broadcast(event);
+ } catch (Exception e) {
+ fail();
+ }
+ }
- result = false;
- ajaxForm.setSubmitted(true);
- child.setSubmittedValue(new String("test0"));
- ajaxForm.processValidators(facesContext);
- assertTrue(result);
- }
+ public void tearDown() throws Exception {
+ super.tearDown();
+ ajaxForm = null;
+ child = null;
+ }
- class TestAjaxFormValidator implements Validator {
- public void validate(javax.faces.context.FacesContext context,
- UIComponent component, Object value) {
- result = true;
- }
- }
-
- // TODO processUpdates test
- public void testProcessUpdates() throws Exception {
-
- facesContext.getExternalContext().getRequestParameterMap().put("form",
- "form");
- child.setSubmittedValue(new String("test1"));
- ajaxForm.processDecodes(facesContext);
- ajaxForm.processValidators(facesContext);
- ajaxForm.processUpdates(facesContext);
- }
-
- public void testBroadcast() throws Exception {
-
- AjaxEvent event = new AjaxEvent(ajaxForm);
- try {
- ajaxForm.broadcast(event);
- } catch (Exception e) {
- fail();
- }
-
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
- ajaxForm = null;
- child = null;
- }
-
+ class TestAjaxFormValidator implements Validator {
+ public void validate(javax.faces.context.FacesContext context, UIComponent component, Object value) {
+ result = true;
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxFormRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxFormRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxFormRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.renderkit.html;
import java.util.HashSet;
@@ -28,6 +30,7 @@
import org.ajax4jsf.component.UIAjaxForm;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.apache.commons.lang.StringUtils;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
@@ -35,110 +38,119 @@
import com.gargoylesoftware.htmlunit.html.HtmlScript;
public class AjaxFormRendererTest extends AbstractAjax4JsfTestCase {
- private static final boolean IS_PAGE_AVAILABILITY_CHECK = true;
- private static Set javaScripts = new HashSet();
-
- static {
+ private static final boolean IS_PAGE_AVAILABILITY_CHECK = true;
+ private static Set javaScripts = new HashSet();
+
+ static {
javaScripts.add("org.ajax4jsf.javascript.AjaxScript");
javaScripts.add("org/ajax4jsf/javascript/scripts/form.js");
}
-
- private UIAjaxForm form1;
- private UIAjaxForm form2;
- public AjaxFormRendererTest(String name) {
- super(name);
- }
+ private UIAjaxForm form1;
+ private UIAjaxForm form2;
- public void setUp() throws Exception {
- super.setUp();
-
- form1 = (UIAjaxForm) application.createComponent(UIAjaxForm.COMPONENT_TYPE);
- form1.setId("form1");
- form1.setAjaxSubmit(true);
-
- form2 = (UIAjaxForm) application.createComponent(UIAjaxForm.COMPONENT_TYPE);
- form2.setId("form2");
- form2.setAjaxSubmit(false);
-
- facesContext.getViewRoot().getChildren().add(form1);
- facesContext.getViewRoot().getChildren().add(form2);
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- /**
+ public AjaxFormRendererTest(String name) {
+ super(name);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ form1 = (UIAjaxForm) application.createComponent(UIAjaxForm.COMPONENT_TYPE);
+ form1.setId("form1");
+ form1.setAjaxSubmit(true);
+ form2 = (UIAjaxForm) application.createComponent(UIAjaxForm.COMPONENT_TYPE);
+ form2.setId("form2");
+ form2.setAjaxSubmit(false);
+ facesContext.getViewRoot().getChildren().add(form1);
+ facesContext.getViewRoot().getChildren().add(form2);
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ /**
* Test script rendering
*
* @throws Exception
*/
public void testRenderScript() throws Exception {
- HtmlPage page = renderView();
+ HtmlPage page = renderView();
+
assertNotNull(page);
System.out.println(page.asXml());
-
- assertEquals(getCountValidScripts(page, javaScripts, IS_PAGE_AVAILABILITY_CHECK).intValue(), javaScripts.size());
+ assertEquals(getCountValidScripts(page, javaScripts, IS_PAGE_AVAILABILITY_CHECK).intValue(),
+ javaScripts.size());
}
-
+
/**
* Test rendering
*
* @throws Exception
*/
public void testRender() throws Exception {
- HtmlPage page = renderView();
+ HtmlPage page = renderView();
+
assertNotNull(page);
-
+
HtmlElement htmlForm1 = page.getHtmlElementById(form1.getClientId(facesContext));
+
assertNotNull(htmlForm1);
assertEquals("form", htmlForm1.getTagName());
-
+
String action = htmlForm1.getAttributeValue("action");
+
assertNotNull(action);
assertTrue(action.startsWith("javascript:A4J.AJAX.SubmitForm"));
-
+
HtmlElement htmlForm2 = page.getHtmlElementById(form2.getClientId(facesContext));
+
assertNotNull(htmlForm2);
assertEquals("form", htmlForm2.getTagName());
-
action = htmlForm2.getAttributeValue("action");
assertNotNull(action);
assertTrue(action.startsWith("/"));
}
-
+
/**
* Test rendering hidden inputs
*
* @throws Exception
*/
public void testRenderHiddenInputs() throws Exception {
- HtmlPage page = renderView();
+ HtmlPage page = renderView();
+
assertNotNull(page);
-
+
HtmlElement htmlForm1 = page.getHtmlElementById(form1.getClientId(facesContext));
List inputs = htmlForm1.getHtmlElementsByTagName("input");
+
assertNotNull(inputs);
+
boolean foundId = false;
boolean foundAutoscroll = false;
- for (Iterator it = inputs.iterator(); it.hasNext();) {
- HtmlElement input = (HtmlElement) it.next();
- String name = input.getAttributeValue("name");
- assertNotNull(name);
- if (!foundId && name.equals(form1.getClientId(facesContext))) {
- foundId = true;
- }
- if (!foundAutoscroll && name.equals("autoScroll")) {
- foundAutoscroll = true;
- }
+
+ for (Iterator it = inputs.iterator(); it.hasNext(); ) {
+ HtmlElement input = (HtmlElement) it.next();
+ String name = input.getAttributeValue("name");
+
+ assertNotNull(name);
+
+ if (!foundId && name.equals(form1.getClientId(facesContext))) {
+ foundId = true;
+ }
+
+ if (!foundAutoscroll && name.equals("autoScroll")) {
+ foundAutoscroll = true;
+ }
}
+
assertTrue(foundId);
assertTrue(foundAutoscroll);
-
+
HtmlElement htmlForm2 = page.getHtmlElementById(form2.getClientId(facesContext));
+
assertNotNull(htmlForm2);
assertEquals("form", htmlForm2.getTagName());
-
}
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxIncludeRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxIncludeRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxIncludeRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.renderkit.html;
import javax.faces.component.UIForm;
@@ -33,71 +35,68 @@
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class AjaxIncludeRendererTest extends AbstractAjax4JsfTestCase {
- private UIInclude include1 = null;
- private UIInclude include2 = null;
- private UIInclude include3 = null;
- private UIForm form;
+ private UIInclude include1 = null;
+ private UIInclude include2 = null;
+ private UIInclude include3 = null;
+ private UIForm form;
- public AjaxIncludeRendererTest(String name) {
- super(name);
- }
+ public AjaxIncludeRendererTest(String name) {
+ super(name);
+ }
- public void setUp() throws Exception {
- super.setUp();
-
- form = new HtmlForm();
- form.setId("form");
- facesContext.getViewRoot().getChildren().add(form);
-
- include1 = (UIInclude)application.createComponent(UIInclude.COMPONENT_TYPE);
- include1.setId("include1");
- include1.setLayout(UIInclude.LAYOUT_NONE);
-
- UIOutput output = (UIOutput) application.createComponent(UIOutput.COMPONENT_TYPE);
- output.setRendered(true);
- output.setId("output");
- output.setValue("output");
- include1.getChildren().add(output);
-
- include2 = (UIInclude)application.createComponent(UIInclude.COMPONENT_TYPE);
- include2.setId("include2");
- include2.setLayout(UIInclude.LAYOUT_BLOCK);
-
- include3 = (UIInclude)application.createComponent(UIInclude.COMPONENT_TYPE);
- include3.setId("include3");
- include3.setLayout(UIInclude.LAYOUT_INLINE);
-
- form.getChildren().add(include1);
- form.getChildren().add(include2);
- form.getChildren().add(include3);
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
-
- include1 = null;
- include2 = null;
- include3 = null;
- }
-
- public void testRender() throws Exception {
- HtmlPage page = renderView();
+ public void setUp() throws Exception {
+ super.setUp();
+ form = new HtmlForm();
+ form.setId("form");
+ facesContext.getViewRoot().getChildren().add(form);
+ include1 = (UIInclude) application.createComponent(UIInclude.COMPONENT_TYPE);
+ include1.setId("include1");
+ include1.setLayout(UIInclude.LAYOUT_NONE);
+
+ UIOutput output = (UIOutput) application.createComponent(UIOutput.COMPONENT_TYPE);
+
+ output.setRendered(true);
+ output.setId("output");
+ output.setValue("output");
+ include1.getChildren().add(output);
+ include2 = (UIInclude) application.createComponent(UIInclude.COMPONENT_TYPE);
+ include2.setId("include2");
+ include2.setLayout(UIInclude.LAYOUT_BLOCK);
+ include3 = (UIInclude) application.createComponent(UIInclude.COMPONENT_TYPE);
+ include3.setId("include3");
+ include3.setLayout(UIInclude.LAYOUT_INLINE);
+ form.getChildren().add(include1);
+ form.getChildren().add(include2);
+ form.getChildren().add(include3);
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ include1 = null;
+ include2 = null;
+ include3 = null;
+ }
+
+ public void testRender() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
System.out.println(page.asXml());
-
+
try {
- HtmlElement empty = page.getHtmlElementById(include1.getClientId(facesContext));
- assertFalse("ElementNotFoundException was not thrown", true);
- } catch (ElementNotFoundException e) {
-
- }
-
+ HtmlElement empty = page.getHtmlElementById(include1.getClientId(facesContext));
+
+ assertFalse("ElementNotFoundException was not thrown", true);
+ } catch (ElementNotFoundException e) {}
+
HtmlElement div = page.getHtmlElementById(include2.getClientId(facesContext));
+
assertNotNull(div);
assertEquals("div", div.getNodeName());
-
+
HtmlElement span = page.getHtmlElementById(include3.getClientId(facesContext));
+
assertNotNull(span);
assertEquals("span", span.getNodeName());
- }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxOutputPanelRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxOutputPanelRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxOutputPanelRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.renderkit.html;
import javax.faces.component.UIForm;
@@ -33,87 +35,78 @@
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class AjaxOutputPanelRendererTest extends AbstractAjax4JsfTestCase {
- private UIForm form = null;
- private UIAjaxOutputPanel panel1 = null;
- private UIAjaxOutputPanel panel2 = null;
- private UIAjaxOutputPanel panel3 = null;
- private UIAjaxOutputPanel panel4 = null;
- private UIOutput output = null;
+ private UIForm form = null;
+ private UIOutput output = null;
+ private UIAjaxOutputPanel panel1 = null;
+ private UIAjaxOutputPanel panel2 = null;
+ private UIAjaxOutputPanel panel3 = null;
+ private UIAjaxOutputPanel panel4 = null;
- public AjaxOutputPanelRendererTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
-
- form = new HtmlForm();
- form.setId("form");
- facesContext.getViewRoot().getChildren().add(form);
-
- panel1 = (UIAjaxOutputPanel)application.createComponent(UIAjaxOutputPanel.COMPONENT_TYPE);
- panel1.setId("panel1");
- panel1.setLayout("none");
- form.getChildren().add(panel1);
-
- panel2 = (UIAjaxOutputPanel)application.createComponent(UIAjaxOutputPanel.COMPONENT_TYPE);
- panel2.setId("panel2");
- panel2.setLayout("block");
- form.getChildren().add(panel2);
-
- panel3 = (UIAjaxOutputPanel)application.createComponent(UIAjaxOutputPanel.COMPONENT_TYPE);
- panel3.setId("panel3");
- panel3.setLayout("inline");
- form.getChildren().add(panel3);
-
- panel4 = (UIAjaxOutputPanel)application.createComponent(UIAjaxOutputPanel.COMPONENT_TYPE);
- panel4.setId("panel4");
- panel4.setLayout("none");
-
- output = (UIOutput) application.createComponent(UIOutput.COMPONENT_TYPE);
- output.setId("output");
- output.setValue("output");
- output.setTransient(true);
- panel4.getChildren().add(output);
-
- form.getChildren().add(panel4);
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
-
- output = null;
- panel1 = null;
- panel2 = null;
- panel3 = null;
- form = null;
- }
-
- public void testRender() throws Exception{
- HtmlPage page = renderView();
+ public AjaxOutputPanelRendererTest(String name) {
+ super(name);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ form = new HtmlForm();
+ form.setId("form");
+ facesContext.getViewRoot().getChildren().add(form);
+ panel1 = (UIAjaxOutputPanel) application.createComponent(UIAjaxOutputPanel.COMPONENT_TYPE);
+ panel1.setId("panel1");
+ panel1.setLayout("none");
+ form.getChildren().add(panel1);
+ panel2 = (UIAjaxOutputPanel) application.createComponent(UIAjaxOutputPanel.COMPONENT_TYPE);
+ panel2.setId("panel2");
+ panel2.setLayout("block");
+ form.getChildren().add(panel2);
+ panel3 = (UIAjaxOutputPanel) application.createComponent(UIAjaxOutputPanel.COMPONENT_TYPE);
+ panel3.setId("panel3");
+ panel3.setLayout("inline");
+ form.getChildren().add(panel3);
+ panel4 = (UIAjaxOutputPanel) application.createComponent(UIAjaxOutputPanel.COMPONENT_TYPE);
+ panel4.setId("panel4");
+ panel4.setLayout("none");
+ output = (UIOutput) application.createComponent(UIOutput.COMPONENT_TYPE);
+ output.setId("output");
+ output.setValue("output");
+ output.setTransient(true);
+ panel4.getChildren().add(output);
+ form.getChildren().add(panel4);
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ output = null;
+ panel1 = null;
+ panel2 = null;
+ panel3 = null;
+ form = null;
+ }
+
+ public void testRender() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
System.out.println(page.asXml());
-
+
try {
- HtmlElement empty = page.getHtmlElementById(panel1.getClientId(facesContext));
- assertFalse("ElementNotFoundException was not thrown", true);
- } catch (ElementNotFoundException e) {
-
- }
-
+ HtmlElement empty = page.getHtmlElementById(panel1.getClientId(facesContext));
+
+ assertFalse("ElementNotFoundException was not thrown", true);
+ } catch (ElementNotFoundException e) {}
+
HtmlElement div = page.getHtmlElementById(panel2.getClientId(facesContext));
+
assertNotNull(div);
assertEquals("div", div.getNodeName());
-
+
HtmlElement span = page.getHtmlElementById(panel3.getClientId(facesContext));
+
assertNotNull(span);
assertEquals("span", span.getNodeName());
-
span = page.getHtmlElementById(output.getClientId(facesContext));
assertNotNull(span);
assertEquals("span", span.getNodeName());
-
assertFalse(output.isTransient());
- }
-
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxPageRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxPageRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxPageRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,9 +19,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.renderkit.html;
import java.io.IOException;
+
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
@@ -36,92 +39,98 @@
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
-public class AjaxPageRendererTest extends AbstractAjax4JsfTestCase{
-
- private org.ajax4jsf.component.html.HtmlPage ajaxPage = null;
- private static Set<String> javaScripts = new HashSet<String>();
+public class AjaxPageRendererTest extends AbstractAjax4JsfTestCase {
+ private static Set<String> javaScripts = new HashSet<String>();
+ private static final boolean IS_PAGE_AVAILABILITY_CHECK = true;
- static {
- javaScripts.add("org.ajax4jsf.javascript.AjaxScript");
- }
+ static {
+ javaScripts.add("org.ajax4jsf.javascript.AjaxScript");
+ }
- private static final boolean IS_PAGE_AVAILABILITY_CHECK = true;
+ private org.ajax4jsf.component.html.HtmlPage ajaxPage = null;
- public AjaxPageRendererTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
-
- ajaxPage = (org.ajax4jsf.component.html.HtmlPage) application.createComponent(org.ajax4jsf.component.html.HtmlPage.COMPONENT_TYPE);
- ajaxPage.setId("page");
-
- UIOutput head = new UIOutput();
- head.setValue("HEAD");
- ajaxPage.getFacets().put("head", head);
-
- UIOutput content = new UIOutput();
- content.setValue("content");
- ajaxPage.getChildren().add(content);
-
- ajaxPage.setFormat("xhtml");
- ajaxPage.setPageTitle("title");
-
- facesContext.getViewRoot().setLocale(new Locale("be", "BY"));
-
- facesContext.getViewRoot().getChildren().add(ajaxPage);
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
- }
+ public AjaxPageRendererTest(String name) {
+ super(name);
+ }
- public void testRender() throws Exception {
- HtmlPage page = renderView();
- assertNotNull(page);
- System.out.println(page.asXml());
-
- HtmlElement html = (HtmlElement)page.getFirstChild();
- assertNotNull(html);
- assertEquals("html", html.getTagName());
-
- String lang = html.getAttributeValue("lang");
- assertNotNull(lang);
- assertEquals(lang, "be_BY");
-
- HtmlElement title = (HtmlElement) html.getHtmlElementsByTagName("title").get(0);
- assertNotNull(title);
-
- assertEquals("title", title.getFirstChild().asText());
-
- HtmlElement meta = (HtmlElement) html.getHtmlElementsByTagName("meta").get(0);
-
- assertNotNull(meta);
- String httpEquiv = meta.getAttributeValue("http-equiv");
- assertEquals(httpEquiv, "Content-Type");
-
- String content = meta.getAttributeValue("content");
- assertEquals(content, "application/xhtml+xml");
- }
-
- public void testRenderScript() throws Exception {
- HtmlPage page = renderView();
+ public void setUp() throws Exception {
+ super.setUp();
+ ajaxPage = (org.ajax4jsf.component.html.HtmlPage) application.createComponent(
+ org.ajax4jsf.component.html.HtmlPage.COMPONENT_TYPE);
+ ajaxPage.setId("page");
+
+ UIOutput head = new UIOutput();
+
+ head.setValue("HEAD");
+ ajaxPage.getFacets().put("head", head);
+
+ UIOutput content = new UIOutput();
+
+ content.setValue("content");
+ ajaxPage.getChildren().add(content);
+ ajaxPage.setFormat("xhtml");
+ ajaxPage.setPageTitle("title");
+ facesContext.getViewRoot().setLocale(new Locale("be", "BY"));
+ facesContext.getViewRoot().getChildren().add(ajaxPage);
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testRender() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
- assertEquals(getCountValidScripts(page, javaScripts, IS_PAGE_AVAILABILITY_CHECK).intValue(), javaScripts.size());
- }
+ System.out.println(page.asXml());
- @Override
- protected void encodeDocumentProlog(FacesContext context,
- UIViewRoot viewRoot, ResponseWriter writer) throws IOException {
-
- //do nothing as a4j:page encodes full page structure
- }
+ HtmlElement html = (HtmlElement) page.getFirstChild();
- @Override
- protected void encodeDocumentEpilog(FacesContext context,
- UIViewRoot viewRoot, ResponseWriter writer) throws IOException {
+ assertNotNull(html);
+ assertEquals("html", html.getTagName());
- //do nothing as a4j:page encodes full page structure
- }
+ String lang = html.getAttributeValue("lang");
+
+ assertNotNull(lang);
+ assertEquals(lang, "be_BY");
+
+ HtmlElement title = (HtmlElement) html.getHtmlElementsByTagName("title").get(0);
+
+ assertNotNull(title);
+ assertEquals("title", title.getFirstChild().asText());
+
+ HtmlElement meta = (HtmlElement) html.getHtmlElementsByTagName("meta").get(0);
+
+ assertNotNull(meta);
+
+ String httpEquiv = meta.getAttributeValue("http-equiv");
+
+ assertEquals(httpEquiv, "Content-Type");
+
+ String content = meta.getAttributeValue("content");
+
+ assertEquals(content, "application/xhtml+xml");
+ }
+
+ public void testRenderScript() throws Exception {
+ HtmlPage page = renderView();
+
+ assertNotNull(page);
+ assertEquals(getCountValidScripts(page, javaScripts, IS_PAGE_AVAILABILITY_CHECK).intValue(),
+ javaScripts.size());
+ }
+
+ @Override
+ protected void encodeDocumentProlog(FacesContext context, UIViewRoot viewRoot, ResponseWriter writer)
+ throws IOException {
+
+ // do nothing as a4j:page encodes full page structure
+ }
+
+ @Override
+ protected void encodeDocumentEpilog(FacesContext context, UIViewRoot viewRoot, ResponseWriter writer)
+ throws IOException {
+
+ // do nothing as a4j:page encodes full page structure
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxPushRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxPushRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxPushRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.renderkit.html;
import java.util.HashSet;
@@ -31,6 +33,7 @@
import org.ajax4jsf.component.UIPush;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.apache.commons.lang.StringUtils;
import com.gargoylesoftware.htmlunit.html.DomText;
@@ -39,102 +42,111 @@
import com.gargoylesoftware.htmlunit.html.HtmlScript;
public class AjaxPushRendererTest extends AbstractAjax4JsfTestCase {
-
- private static Set<String> javaScripts = new HashSet<String>();
- private static final boolean IS_PAGE_AVAILABILITY_CHECK = true;
+ private static Set<String> javaScripts = new HashSet<String>();
+ private static final boolean IS_PAGE_AVAILABILITY_CHECK = true;
- static {
- javaScripts.add("org.ajax4jsf.javascript.AjaxScript");
- }
- private UIForm form = null;
- private UIPush push1 = null;
- private UIPush push2 = null;
+ static {
+ javaScripts.add("org.ajax4jsf.javascript.AjaxScript");
+ }
- public AjaxPushRendererTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
-
- form = new HtmlForm();
- form.setId("form");
- facesContext.getViewRoot().getChildren().add(form);
-
- push1 = (UIPush) application.createComponent(UIPush.COMPONENT_TYPE);
- push1.setId("push1");
- push1.setEnabled(true);
- form.getChildren().add(push1);
-
- push2 = (UIPush) application.createComponent(UIPush.COMPONENT_TYPE);
- push2.setId("push2");
- push2.setEnabled(false);
- form.getChildren().add(push2);
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
-
- push1 = null;
- push2 = null;
- form = null;
- }
-
- public void testRender() throws Exception {
- HtmlPage page = renderView();
+ private UIForm form = null;
+ private UIPush push1 = null;
+ private UIPush push2 = null;
+
+ public AjaxPushRendererTest(String name) {
+ super(name);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ form = new HtmlForm();
+ form.setId("form");
+ facesContext.getViewRoot().getChildren().add(form);
+ push1 = (UIPush) application.createComponent(UIPush.COMPONENT_TYPE);
+ push1.setId("push1");
+ push1.setEnabled(true);
+ form.getChildren().add(push1);
+ push2 = (UIPush) application.createComponent(UIPush.COMPONENT_TYPE);
+ push2.setId("push2");
+ push2.setEnabled(false);
+ form.getChildren().add(push2);
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ push1 = null;
+ push2 = null;
+ form = null;
+ }
+
+ public void testRender() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
System.out.println(page.asXml());
-
+
HtmlElement span1 = page.getHtmlElementById(push1.getClientId(facesContext));
+
assertNotNull(span1);
assertEquals("span", span1.getTagName());
+
String style = span1.getAttributeValue("style");
+
assertNotNull(style);
assertTrue(style.matches("display\\s*\\:\\s*none\\s*\\;\\s*"));
-
+
HtmlElement span2 = page.getHtmlElementById(push2.getClientId(facesContext));
+
assertNotNull(span2);
assertEquals("span", span2.getTagName());
style = span2.getAttributeValue("style");
assertNotNull(style);
assertTrue(style.matches("display\\s*\\:\\s*none\\s*\\;\\s*"));
- }
+ }
- public void testRenderScript() throws Exception {
- HtmlPage page = renderView();
+ public void testRenderScript() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
-
+
List scripts = page.getDocumentElement().getHtmlElementsByTagName("script");
- assertEquals(getCountValidScripts(page, javaScripts, IS_PAGE_AVAILABILITY_CHECK).intValue(), javaScripts.size());
-
+
+ assertEquals(getCountValidScripts(page, javaScripts, IS_PAGE_AVAILABILITY_CHECK).intValue(),
+ javaScripts.size());
+
HtmlElement span1 = page.getHtmlElementById(push1.getClientId(facesContext));
+
assertNotNull(span1);
scripts = span1.getHtmlElementsByTagName("script");
+
int i = 0;
- for (Iterator it = scripts.iterator(); it.hasNext();) {
- HtmlScript item = (HtmlScript) it.next();
- DomText text = (DomText) item.getFirstChild();
-
- assertNotNull(text);
- assertTrue(text.asText().contains("A4J.AJAX.Push"));
-
- i++;
+
+ for (Iterator it = scripts.iterator(); it.hasNext(); ) {
+ HtmlScript item = (HtmlScript) it.next();
+ DomText text = (DomText) item.getFirstChild();
+
+ assertNotNull(text);
+ assertTrue(text.asText().contains("A4J.AJAX.Push"));
+ i++;
}
+
assertEquals(1, i);
-
+
HtmlElement span2 = page.getHtmlElementById(push2.getClientId(facesContext));
+
assertNotNull(span2);
scripts = span2.getHtmlElementsByTagName("script");
i = 0;
- for (Iterator it = scripts.iterator(); it.hasNext();) {
- HtmlScript item = (HtmlScript) it.next();
- DomText text = (DomText) item.getFirstChild();
-
- assertNotNull(text);
- assertTrue(text.asText().contains("A4J.AJAX.StopPush"));
-
- i++;
+
+ for (Iterator it = scripts.iterator(); it.hasNext(); ) {
+ HtmlScript item = (HtmlScript) it.next();
+ DomText text = (DomText) item.getFirstChild();
+
+ assertNotNull(text);
+ assertTrue(text.asText().contains("A4J.AJAX.StopPush"));
+ i++;
}
+
assertEquals(1, i);
- }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxStatusRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxStatusRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/AjaxStatusRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.renderkit.html;
import java.util.Iterator;
@@ -34,120 +36,134 @@
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class AjaxStatusRendererTest extends AbstractAjax4JsfTestCase {
- private UIForm form = null;
- private UIAjaxStatus status1 = null;
- private UIAjaxStatus status2 = null;
-
- public AjaxStatusRendererTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
-
- application.addComponent("org.ajax4jsf.AjaxStatus", "org.ajax4jsf.component.html.HtmlAjaxStatus");
-
- form = new HtmlForm();
- form.setId("form");
- facesContext.getViewRoot().getChildren().add(form);
-
- status1 = (UIAjaxStatus)application.createComponent(UIAjaxStatus.COMPONENT_TYPE);
- status1.setId("status1");
- status1.setStartStyle("color: red;");
- status1.setStartStyleClass("A B C D");
- status1.setStopStyle("color: green;");
- status1.setStopStyleClass("X Y Z");
- status1.setStartText("startText");
- status1.setStopText("stopText");
- status1.getAttributes().put("layout", "block");
-
- status2 = (UIAjaxStatus)application.createComponent(UIAjaxStatus.COMPONENT_TYPE);
- status2.setId("status2");
- status2.setStartStyle("color: red;");
- status2.setStartStyleClass("A B C D");
- status2.setStopStyle("color: green;");
- status2.setStopStyleClass("X Y Z");
- status2.getAttributes().put("layout", "inline");
-
- UIGraphic startImage = new UIGraphic();
- startImage.setValue("start.png");
- startImage.getAttributes().put("alt", "alt");
- status2.getFacets().put("start", startImage);
-
- UIGraphic stopGraphic = new UIGraphic();
- stopGraphic.setValue("stop.png");
- stopGraphic.getAttributes().put("alt", "alt");
- status2.getFacets().put("stop", stopGraphic);
-
- form.getChildren().add(status1);
- form.getChildren().add(status2);
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
-
- status1 = null;
- status2 = null;
- form = null;
- }
-
- /**
+ private UIForm form = null;
+ private UIAjaxStatus status1 = null;
+ private UIAjaxStatus status2 = null;
+
+ public AjaxStatusRendererTest(String name) {
+ super(name);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ application.addComponent("org.ajax4jsf.AjaxStatus", "org.ajax4jsf.component.html.HtmlAjaxStatus");
+ form = new HtmlForm();
+ form.setId("form");
+ facesContext.getViewRoot().getChildren().add(form);
+ status1 = (UIAjaxStatus) application.createComponent(UIAjaxStatus.COMPONENT_TYPE);
+ status1.setId("status1");
+ status1.setStartStyle("color: red;");
+ status1.setStartStyleClass("A B C D");
+ status1.setStopStyle("color: green;");
+ status1.setStopStyleClass("X Y Z");
+ status1.setStartText("startText");
+ status1.setStopText("stopText");
+ status1.getAttributes().put("layout", "block");
+ status2 = (UIAjaxStatus) application.createComponent(UIAjaxStatus.COMPONENT_TYPE);
+ status2.setId("status2");
+ status2.setStartStyle("color: red;");
+ status2.setStartStyleClass("A B C D");
+ status2.setStopStyle("color: green;");
+ status2.setStopStyleClass("X Y Z");
+ status2.getAttributes().put("layout", "inline");
+
+ UIGraphic startImage = new UIGraphic();
+
+ startImage.setValue("start.png");
+ startImage.getAttributes().put("alt", "alt");
+ status2.getFacets().put("start", startImage);
+
+ UIGraphic stopGraphic = new UIGraphic();
+
+ stopGraphic.setValue("stop.png");
+ stopGraphic.getAttributes().put("alt", "alt");
+ status2.getFacets().put("stop", stopGraphic);
+ form.getChildren().add(status1);
+ form.getChildren().add(status2);
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ status1 = null;
+ status2 = null;
+ form = null;
+ }
+
+ /**
* Test rendering
*
* @throws Exception
*/
public void testRender() throws Exception {
- HtmlPage page = renderView();
+ HtmlPage page = renderView();
+
assertNotNull(page);
-
+
HtmlElement div = page.getHtmlElementById(status1.getClientId(facesContext));
+
assertNotNull(div);
assertEquals("div", div.getNodeName());
-
+
Iterator childIterator = div.getChildIterator();
int i = 0;
+
while (childIterator.hasNext()) {
- i++;
- HtmlElement element = (HtmlElement) childIterator.next();
- assertEquals("div", element.getNodeName());
+ i++;
+
+ HtmlElement element = (HtmlElement) childIterator.next();
+
+ assertEquals("div", element.getNodeName());
}
+
assertEquals(2, i);
-
+
HtmlElement div1 = page.getHtmlElementById(status1.getClientId(facesContext) + ".start");
+
assertNotNull(div1);
+
String style1 = div1.getAttributeValue("style");
+
assertNotNull(style1);
assertTrue(style1.contains("color: red;"));
+
String class1 = div1.getAttributeValue("class");
+
assertNotNull(class1);
assertEquals(class1, "A B C D");
-
+
HtmlElement div2 = page.getHtmlElementById(status1.getClientId(facesContext) + ".stop");
+
assertNotNull(div2);
+
String style2 = div2.getAttributeValue("style");
+
assertNotNull(style2);
assertTrue(style2.contains("color: green;"));
+
String class2 = div2.getAttributeValue("class");
+
assertNotNull(class2);
assertEquals(class2, "X Y Z");
-
form.getChildren().remove(0);
page = renderView();
System.out.println(page.asXml());
-
+
HtmlElement span = (HtmlElement) div.getNextSibling();
+
assertNotNull(span);
assertEquals("span", span.getNodeName());
-
childIterator = span.getChildIterator();
i = 0;
+
while (childIterator.hasNext()) {
- i++;
- HtmlElement element = (HtmlElement) childIterator.next();
- assertEquals("span", element.getNodeName());
- assertEquals("img", element.getFirstChild().getNodeName());
+ i++;
+
+ HtmlElement element = (HtmlElement) childIterator.next();
+
+ assertEquals("span", element.getNodeName());
+ assertEquals("img", element.getFirstChild().getNodeName());
}
+
assertEquals(2, i);
}
-
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/HtmlCommandLinkRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/HtmlCommandLinkRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/HtmlCommandLinkRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.renderkit.html;
import java.util.HashSet;
@@ -31,6 +33,7 @@
import javax.faces.component.html.HtmlForm;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+
import org.apache.commons.lang.StringUtils;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
@@ -38,102 +41,108 @@
import com.gargoylesoftware.htmlunit.html.HtmlScript;
public class HtmlCommandLinkRendererTest extends AbstractAjax4JsfTestCase {
- /** Set with required javascripts for Editor */
- private static Set<String> javaScripts = new HashSet<String>();
- static {
- javaScripts.add("org/ajax4jsf/javascript/scripts/form.js");
- }
-
- private UIForm form = null;
- private HtmlCommandLink link1 = null;
- private HtmlCommandLink link2 = null;
+ /** Set with required javascripts for Editor */
+ private static Set<String> javaScripts = new HashSet<String>();
- public HtmlCommandLinkRendererTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
-
- facesContext.getRenderKit().addRenderer(HtmlCommandLink.COMPONENT_FAMILY, "org.ajax4jsf.Link", new HtmlCommandLinkRenderer());
-
- form = new HtmlForm();
- form.setId("form");
- facesContext.getViewRoot().getChildren().add(form);
-
- link1 = (HtmlCommandLink) application.createComponent(HtmlCommandLink.COMPONENT_TYPE);
- link1.setId("link1");
- link1.setValue("link1");
- link1.getAttributes().put("disabled", Boolean.FALSE);
- link1.setRendererType("org.ajax4jsf.Link");
- form.getChildren().add(link1);
-
- link2 = (HtmlCommandLink) application.createComponent(HtmlCommandLink.COMPONENT_TYPE);
- link2.setId("link2");
- link2.setValue("link2");
- link2.getAttributes().put("disabled", Boolean.TRUE);
- link2.setRendererType("org.ajax4jsf.Link");
- form.getChildren().add(link2);
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
-
- link1 = null;
- link2 = null;
- form = null;
- }
-
- public void testRendered() throws Exception {
- HtmlPage page = renderView();
+ static {
+ javaScripts.add("org/ajax4jsf/javascript/scripts/form.js");
+ }
+
+ private UIForm form = null;
+ private HtmlCommandLink link1 = null;
+ private HtmlCommandLink link2 = null;
+
+ public HtmlCommandLinkRendererTest(String name) {
+ super(name);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ facesContext.getRenderKit().addRenderer(HtmlCommandLink.COMPONENT_FAMILY, "org.ajax4jsf.Link",
+ new HtmlCommandLinkRenderer());
+ form = new HtmlForm();
+ form.setId("form");
+ facesContext.getViewRoot().getChildren().add(form);
+ link1 = (HtmlCommandLink) application.createComponent(HtmlCommandLink.COMPONENT_TYPE);
+ link1.setId("link1");
+ link1.setValue("link1");
+ link1.getAttributes().put("disabled", Boolean.FALSE);
+ link1.setRendererType("org.ajax4jsf.Link");
+ form.getChildren().add(link1);
+ link2 = (HtmlCommandLink) application.createComponent(HtmlCommandLink.COMPONENT_TYPE);
+ link2.setId("link2");
+ link2.setValue("link2");
+ link2.getAttributes().put("disabled", Boolean.TRUE);
+ link2.setRendererType("org.ajax4jsf.Link");
+ form.getChildren().add(link2);
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ link1 = null;
+ link2 = null;
+ form = null;
+ }
+
+ public void testRendered() throws Exception {
+ HtmlPage page = renderView();
+
assertNotNull(page);
System.out.println(page.asXml());
-
+
HtmlElement href = page.getHtmlElementById(link1.getClientId(facesContext));
+
assertNotNull(href);
assertEquals("a", href.getTagName());
-
+
String onclick = href.getAttributeValue("onclick");
+
assertNotNull(onclick);
assertTrue(onclick.contains(AjaxFormRenderer.FORM_SUBMIT_FUNCTION_NAME));
-
+
HtmlElement span = page.getHtmlElementById(link2.getClientId(facesContext));
+
assertNotNull(span);
assertEquals("span", span.getTagName());
-
+
String disabled = span.getAttributeValue("disabled");
+
assertNotNull(disabled);
assertEquals("disabled", disabled);
- }
-
- /**
- * Method to test if required scripts is present on page
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- public void testLinkScripts() throws Exception {
- HtmlPage page = renderView();
- assertNotNull(page);
-
- List scripts = page.getDocumentHtmlElement().getHtmlElementsByTagName(
- "script");
+ }
- for (Iterator it = scripts.iterator(); it.hasNext();) {
- HtmlScript item = (HtmlScript) it.next();
- String srcAttr = item.getSrcAttribute();
- if (StringUtils.isNotBlank(srcAttr)) {
- boolean found = false;
- for (Iterator srcIt = javaScripts.iterator(); srcIt.hasNext();) {
- String src = (String) srcIt.next();
- found = srcAttr.contains(src);
- if (found) {
- break;
- }
- }
- assertTrue(found);
- }
- }
- }
+ /**
+ * Method to test if required scripts is present on page
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ public void testLinkScripts() throws Exception {
+ HtmlPage page = renderView();
+ assertNotNull(page);
+
+ List scripts = page.getDocumentHtmlElement().getHtmlElementsByTagName("script");
+
+ for (Iterator it = scripts.iterator(); it.hasNext(); ) {
+ HtmlScript item = (HtmlScript) it.next();
+ String srcAttr = item.getSrcAttribute();
+
+ if (StringUtils.isNotBlank(srcAttr)) {
+ boolean found = false;
+
+ for (Iterator srcIt = javaScripts.iterator(); srcIt.hasNext(); ) {
+ String src = (String) srcIt.next();
+
+ found = srcAttr.contains(src);
+
+ if (found) {
+ break;
+ }
+ }
+
+ assertTrue(found);
+ }
+ }
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/MediaOutputRendererTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/MediaOutputRendererTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/renderkit/html/MediaOutputRendererTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.renderkit.html;
import javax.faces.FacesException;
@@ -33,109 +35,114 @@
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class MediaOutputRendererTest extends AbstractAjax4JsfTestCase {
- UIForm form = null;
- UIMediaOutput media1 = null;
- UIMediaOutput media2 = null;
- UIMediaOutput media3 = null;
- UIMediaOutput media4 = null;
- UIMediaOutput media5 = null;
+ UIForm form = null;
+ UIMediaOutput media1 = null;
+ UIMediaOutput media2 = null;
+ UIMediaOutput media3 = null;
+ UIMediaOutput media4 = null;
+ UIMediaOutput media5 = null;
- public MediaOutputRendererTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
-
- application.addComponent("org.ajax4jsf.MMedia", "org.ajax4jsf.component.html.MediaOutput");
-
- form = new HtmlForm();
- form.setId("form");
- facesContext.getViewRoot().getChildren().add(form);
-
- media1 = (UIMediaOutput)application.createComponent(UIMediaOutput.COMPONENT_TYPE);
- media1.setId("media1");
- media1.setElement("a");
- media1.setUriAttribute("href");
- form.getChildren().add(media1);
-
- media2 = (UIMediaOutput)application.createComponent(UIMediaOutput.COMPONENT_TYPE);
- media2.setId("media2");
- media2.setElement("img");
- media2.setUriAttribute("src");
- media2.getAttributes().put("alt", "Generated value");
- form.getChildren().add(media2);
-
- media3 = (UIMediaOutput)application.createComponent(UIMediaOutput.COMPONENT_TYPE);
- media3.setId("media3");
- media3.setElement("object");
- media3.setUriAttribute("data");
- form.getChildren().add(media3);
-
- media4 = (UIMediaOutput)application.createComponent(UIMediaOutput.COMPONENT_TYPE);
- media4.setId("media4");
- media4.setElement("a");
- UIParameter param = new UIParameter();
- param.setName("name");
- param.setValue("value");
- media4.getChildren().add(param);
- form.getChildren().add(media4);
-
- media5 = (UIMediaOutput)application.createComponent(UIMediaOutput.COMPONENT_TYPE);
- media5.setId("media5");
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
-
- media1 = null;
- media2 = null;
- media3 = null;
- media4 = null;
- media5 = null;
- form = null;
- }
-
- public void testRender() throws Exception {
- HtmlPage page = renderView();
- assertNotNull(page);
- System.out.println(page.asXml());
-
- HtmlElement a = page.getHtmlElementById(media1.getClientId(facesContext));
- assertNotNull(a);
- assertEquals("a", a.getTagName());
- String href = a.getAttributeValue("href");
- assertNotNull(href);
-
- HtmlElement img = page.getHtmlElementById(media2.getClientId(facesContext));
- assertNotNull(img);
- assertEquals("img", img.getTagName());
- String src = img.getAttributeValue("src");
- assertNotNull(src);
-
- HtmlElement object = page.getHtmlElementById(media3.getClientId(facesContext));
- assertNotNull(object);
- assertEquals("object", object.getTagName());
- String data = object.getAttributeValue("data");
- assertNotNull(data);
-
- // Rendering without uriAttribute
- HtmlElement a2 = page.getHtmlElementById(media4.getClientId(facesContext));
- assertNotNull(a2);
- assertEquals("a", a2.getTagName());
- String href2 = a2.getAttributeValue("href");
- assertNotNull(href2);
- assertTrue(href2.endsWith("name=value"));
- }
-
- public void testRenderWithoutElement() throws Exception {
- form.getChildren().add(media5);
- try {
- renderView();
- assertTrue("'element' is undefined but exception was not thrown", false);
- } catch (FacesException e) {
-
- }
- }
+ public MediaOutputRendererTest(String name) {
+ super(name);
+ }
+ public void setUp() throws Exception {
+ super.setUp();
+ application.addComponent("org.ajax4jsf.MMedia", "org.ajax4jsf.component.html.MediaOutput");
+ form = new HtmlForm();
+ form.setId("form");
+ facesContext.getViewRoot().getChildren().add(form);
+ media1 = (UIMediaOutput) application.createComponent(UIMediaOutput.COMPONENT_TYPE);
+ media1.setId("media1");
+ media1.setElement("a");
+ media1.setUriAttribute("href");
+ form.getChildren().add(media1);
+ media2 = (UIMediaOutput) application.createComponent(UIMediaOutput.COMPONENT_TYPE);
+ media2.setId("media2");
+ media2.setElement("img");
+ media2.setUriAttribute("src");
+ media2.getAttributes().put("alt", "Generated value");
+ form.getChildren().add(media2);
+ media3 = (UIMediaOutput) application.createComponent(UIMediaOutput.COMPONENT_TYPE);
+ media3.setId("media3");
+ media3.setElement("object");
+ media3.setUriAttribute("data");
+ form.getChildren().add(media3);
+ media4 = (UIMediaOutput) application.createComponent(UIMediaOutput.COMPONENT_TYPE);
+ media4.setId("media4");
+ media4.setElement("a");
+
+ UIParameter param = new UIParameter();
+
+ param.setName("name");
+ param.setValue("value");
+ media4.getChildren().add(param);
+ form.getChildren().add(media4);
+ media5 = (UIMediaOutput) application.createComponent(UIMediaOutput.COMPONENT_TYPE);
+ media5.setId("media5");
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ media1 = null;
+ media2 = null;
+ media3 = null;
+ media4 = null;
+ media5 = null;
+ form = null;
+ }
+
+ public void testRender() throws Exception {
+ HtmlPage page = renderView();
+
+ assertNotNull(page);
+ System.out.println(page.asXml());
+
+ HtmlElement a = page.getHtmlElementById(media1.getClientId(facesContext));
+
+ assertNotNull(a);
+ assertEquals("a", a.getTagName());
+
+ String href = a.getAttributeValue("href");
+
+ assertNotNull(href);
+
+ HtmlElement img = page.getHtmlElementById(media2.getClientId(facesContext));
+
+ assertNotNull(img);
+ assertEquals("img", img.getTagName());
+
+ String src = img.getAttributeValue("src");
+
+ assertNotNull(src);
+
+ HtmlElement object = page.getHtmlElementById(media3.getClientId(facesContext));
+
+ assertNotNull(object);
+ assertEquals("object", object.getTagName());
+
+ String data = object.getAttributeValue("data");
+
+ assertNotNull(data);
+
+ // Rendering without uriAttribute
+ HtmlElement a2 = page.getHtmlElementById(media4.getClientId(facesContext));
+
+ assertNotNull(a2);
+ assertEquals("a", a2.getTagName());
+
+ String href2 = a2.getAttributeValue("href");
+
+ assertNotNull(href2);
+ assertTrue(href2.endsWith("name=value"));
+ }
+
+ public void testRenderWithoutElement() throws Exception {
+ form.getChildren().add(media5);
+
+ try {
+ renderView();
+ assertTrue("'element' is undefined but exception was not thrown", false);
+ } catch (FacesException e) {}
+ }
}
Modified: root/ui/trunk/components/core/src/test/java/org/ajax4jsf/taglib/html/KeepAliveTagsTest.java
===================================================================
--- root/ui/trunk/components/core/src/test/java/org/ajax4jsf/taglib/html/KeepAliveTagsTest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/core/src/test/java/org/ajax4jsf/taglib/html/KeepAliveTagsTest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+
+
package org.ajax4jsf.taglib.html;
import java.util.Map;
@@ -49,97 +51,87 @@
* @author Nick Belaevski
* @since 3.2.2
*/
-
public class KeepAliveTagsTest extends AbstractAjax4JsfTestCase {
-
- public KeepAliveTagsTest(String name) {
- super(name);
- }
+ public KeepAliveTagsTest(String name) {
+ super(name);
+ }
- private void setupBean(String beanName, Object bean) {
- externalContext.getRequestMap().put(beanName, bean);
- }
-
- private TagSupport setupTag(String beanName, Object bean, boolean ajaxOnly) {
- setupBean(beanName, bean);
-
- MockPageContext pageContext = new MockPageContext();
-
- KeepAliveTag tag = new KeepAliveTag();
- tag.setAjaxOnly(new MockValueExpression(ajaxOnly));
- tag.setPageContext(pageContext);
- tag.setBeanName(beanName);
-
- return tag;
- }
-
- private TagHandler setupTagHandler(final String beanName, Object bean, final boolean ajaxOnly) {
- setupBean(beanName, bean);
+ private void setupBean(String beanName, Object bean) {
+ externalContext.getRequestMap().put(beanName, bean);
+ }
- KeepAliveHandler handler = new KeepAliveHandler(new TagConfig() {
+ private TagSupport setupTag(String beanName, Object bean, boolean ajaxOnly) {
+ setupBean(beanName, bean);
- private Tag tag;
- private String tagId;
-
- {
- tagId = "_tagId0";
- Location location = new Location("cdr", 1, 2);
- String ns = "urn:unk";
- tag = new Tag(location,
- ns, "tag", null,
- new TagAttributes(new TagAttribute[] {
- new TagAttribute(location, "", "beanName", null, beanName),
- new TagAttribute(location, "", "ajaxOnly", null, String.valueOf(ajaxOnly))
- }));
- }
-
- public FaceletHandler getNextHandler() {
- return null;
- }
+ MockPageContext pageContext = new MockPageContext();
+ KeepAliveTag tag = new KeepAliveTag();
- public Tag getTag() {
- return tag;
- }
+ tag.setAjaxOnly(new MockValueExpression(ajaxOnly));
+ tag.setPageContext(pageContext);
+ tag.setBeanName(beanName);
- public String getTagId() {
- return null;
- }
-
- });
-
- return handler;
- }
-
- public void testJSPTag() throws Exception {
- Map<String, Object> attributes = facesContext.getViewRoot().getAttributes();
-
- Object ajaxBean = new Object();
- TagSupport ajaxTag = setupTag("coolBean", ajaxBean, true);
-
- ajaxTag.doStartTag();
- assertSame(ajaxBean, attributes.get(AjaxPhaseListener.AJAX_BEAN_PREFIX + "coolBean"));
+ return tag;
+ }
- Object bean = new Object();
- TagSupport tag = setupTag("beBean", bean, false);
-
- tag.doStartTag();
- assertSame(bean, attributes.get(AjaxPhaseListener.VIEW_BEAN_PREFIX + "beBean"));
- }
-
- public void testFaceletsTag() throws Exception {
- FaceletContext ctx = new MockFaceletContext(facesContext);
- Map<String, Object> attributes = facesContext.getViewRoot().getAttributes();
-
- Object ajaxBean = new Object();
- TagHandler ajaxTag = setupTagHandler("ajaxAliveBean", ajaxBean, true);
-
- ajaxTag.apply(ctx , null);
- assertSame(ajaxBean, attributes.get(AjaxPhaseListener.AJAX_BEAN_PREFIX + "ajaxAliveBean"));
+ private TagHandler setupTagHandler(final String beanName, Object bean, final boolean ajaxOnly) {
+ setupBean(beanName, bean);
- Object bean = new Object();
- TagHandler tag = setupTagHandler("thatBean", bean, false);
-
- tag.apply(ctx, null);
- assertSame(bean, attributes.get(AjaxPhaseListener.VIEW_BEAN_PREFIX + "thatBean"));
- }
+ KeepAliveHandler handler = new KeepAliveHandler(new TagConfig() {
+ private Tag tag;
+ private String tagId;
+ {
+ tagId = "_tagId0";
+
+ Location location = new Location("cdr", 1, 2);
+ String ns = "urn:unk";
+
+ tag = new Tag(location, ns, "tag", null,
+ new TagAttributes(new TagAttribute[] {
+ new TagAttribute(location, "", "beanName", null, beanName),
+ new TagAttribute(location, "", "ajaxOnly", null, String.valueOf(ajaxOnly))}));
+ }
+ public FaceletHandler getNextHandler() {
+ return null;
+ }
+ public Tag getTag() {
+ return tag;
+ }
+ public String getTagId() {
+ return null;
+ }
+ });
+
+ return handler;
+ }
+
+ public void testJSPTag() throws Exception {
+ Map<String, Object> attributes = facesContext.getViewRoot().getAttributes();
+ Object ajaxBean = new Object();
+ TagSupport ajaxTag = setupTag("coolBean", ajaxBean, true);
+
+ ajaxTag.doStartTag();
+ assertSame(ajaxBean, attributes.get(AjaxPhaseListener.AJAX_BEAN_PREFIX + "coolBean"));
+
+ Object bean = new Object();
+ TagSupport tag = setupTag("beBean", bean, false);
+
+ tag.doStartTag();
+ assertSame(bean, attributes.get(AjaxPhaseListener.VIEW_BEAN_PREFIX + "beBean"));
+ }
+
+ public void testFaceletsTag() throws Exception {
+ FaceletContext ctx = new MockFaceletContext(facesContext);
+ Map<String, Object> attributes = facesContext.getViewRoot().getAttributes();
+ Object ajaxBean = new Object();
+ TagHandler ajaxTag = setupTagHandler("ajaxAliveBean", ajaxBean, true);
+
+ ajaxTag.apply(ctx, null);
+ assertSame(ajaxBean, attributes.get(AjaxPhaseListener.AJAX_BEAN_PREFIX + "ajaxAliveBean"));
+
+ Object bean = new Object();
+ TagHandler tag = setupTagHandler("thatBean", bean, false);
+
+ tag.apply(ctx, null);
+ assertSame(bean, attributes.get(AjaxPhaseListener.VIEW_BEAN_PREFIX + "thatBean"));
+ }
}
Modified: root/ui/trunk/components/tree/tree/api/src/main/java/ITest.java
===================================================================
--- root/ui/trunk/components/tree/tree/api/src/main/java/ITest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/tree/tree/api/src/main/java/ITest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -1,4 +1 @@
-
-public interface ITest {
-
-}
+public interface ITest {}
Modified: root/ui/trunk/components/tree/tree/ui/src/main/java/UITest.java
===================================================================
--- root/ui/trunk/components/tree/tree/ui/src/main/java/UITest.java 2009-11-02 10:55:43 UTC (rev 15804)
+++ root/ui/trunk/components/tree/tree/ui/src/main/java/UITest.java 2009-11-02 11:26:36 UTC (rev 15805)
@@ -1,4 +1 @@
-
-public class UITest {
-
-}
+public class UITest {}
15 years, 10 months