mojarra-2.0.3.orig/0000755000000000000000000000000011413023352010766 5ustar mojarra-2.0.3.orig/nbproject/0000755000000000000000000000000011412443310012753 5ustar mojarra-2.0.3.orig/nbproject/project.xml0000644000000000000000000001024211412443310015142 0ustar org.netbeans.modules.ant.freeform mojarra-2.0.3-SNAPSHOT mojarra-2.0.3-SNAPSHOT . MacRoman java jsf-api/src/main/java MacRoman java jsf-ri/src/main/java MacRoman java jsf-ri/test MacRoman main clean build.javadocs.dist test clean main jsf-api/src/main/java jsf-ri/src/main/java jsf-ri/test build.xml jsf-api/src/main/java jsf-ri/src/main/java jsf-ri/test dependencies/jars/el-api-1.0.jar:dependencies/jars/jsp-api-2.1.jar:dependencies/jars/jstl-1.2.jar:dependencies/jars/validation-api-1.0.0.GA.jar:dependencies/jars/servlet-api-3.0.20100224.jar:dependencies/jars/groovy-all-1.6.4.jar:dependencies/jars/junit-3.8.1.jar:lib/cactus-1.7.1-javaee5.jar:lib/jsf-extensions-test-time.jar 1.5 mojarra-2.0.3.orig/jsf-ri/0000755000000000000000000000000011413023172012160 5ustar mojarra-2.0.3.orig/jsf-ri/build/0000755000000000000000000000000011413023142013254 5ustar mojarra-2.0.3.orig/jsf-ri/impl.iml0000644000000000000000000024266311412443372013650 0ustar mojarra-2.0.3.orig/jsf-ri/resources/0000755000000000000000000000000011412443622014177 5ustar mojarra-2.0.3.orig/jsf-ri/resources/mojarra.js0000644000000000000000000001350311412443622016172 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2008 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @project JSF Ajax Library @version 2.0 @description This is the standard implementation of the JSF Ajax Library. */ /** * Register with OpenAjax */ if (typeof OpenAjax !== "undefined" && typeof OpenAjax.hub.registerLibrary !== "undefined") { OpenAjax.hub.registerLibrary("mojarra", "www.sun.com", "1.0", null); } /** * @name mojarra * @namespace */ /* * Create our top level namespaces - mojarra */ var mojarra = mojarra || {}; /** * This function deletes any hidden parameters added * to the form by checking for a variable called 'adp' * defined on the form. If present, this variable will * contain all the params added by 'apf'. * * @param f - the target form */ mojarra.dpf = function dpf(f) { var adp = f.adp; if (adp !== null) { for (var i = 0; i < adp.length; i++) { f.removeChild(adp[i]); } } }; /* * This function adds any parameters specified by the * parameter 'pvp' to the form represented by param 'f'. * Any parameters added will be stored in a variable * called 'adp' and stored on the form. * * @param f - the target form * @param pvp - associative array of parameter * key/value pairs to be added to the form as hidden input * fields. */ mojarra.apf = function apf(f, pvp) { var adp = new Array(); f.adp = adp; var i = 0; for (var k in pvp) { if (pvp.hasOwnProperty(k)) { var p = document.createElement("input"); p.type = "hidden"; p.name = k; p.value = pvp[k]; f.appendChild(p); adp[i++] = p; } } }; /* * This is called by command link and command button. It provides * the form it is nested in, the parameters that need to be * added and finally, the target of the action. This function * will delete any parameters added after the form * has been submitted to handle DOM caching issues. * * @param f - the target form * @param pvp - associative array of parameter * key/value pairs to be added to the form as hidden input * fields. * @param t - the target of the form submission */ mojarra.jsfcljs = function jsfcljs(f, pvp, t) { mojarra.apf(f, pvp); var ft = f.target; if (t) { f.target = t; } f.submit(); f.target = ft; mojarra.dpf(f); }; /* * This is called by functions that need access to their calling * context, in the form of this and event * objects. * * @param f the function to execute * @param t this of the calling function * @param e event of the calling function * @return object that f returns */ mojarra.jsfcbk = function jsfcbk(f, t, e) { return f.call(t,e); }; /* * This is called by the AjaxBehaviorRenderer script to * trigger a jsf.ajax.request() call. * * @param s the source element or id * @param e event of the calling function * @param n name of the behavior event that has fired * @param ex execute list * @param re render list * @param op options object */ mojarra.ab = function ab(s, e, n, ex, re, op) { if (!op) { op = {}; } if (n) { op["javax.faces.behavior.event"] = n; } if (ex) { op["execute"] = ex; } if (re) { op["render"] = re; } jsf.ajax.request(s, e, op); }mojarra-2.0.3.orig/jsf-ri/resources/empty-faces-config.xml0000644000000000000000000000421011412443622020376 0ustar mojarra-2.0.3.orig/jsf-ri/resources/jsf-ri-config.xml0000644000000000000000000002730311412443622017363 0ustar com.sun.faces.application.ApplicationFactoryImpl com.sun.faces.context.ExceptionHandlerFactoryImpl com.sun.faces.component.visit.VisitContextFactoryImpl com.sun.faces.context.FacesContextFactoryImpl com.sun.faces.context.PartialViewContextFactoryImpl com.sun.faces.lifecycle.LifecycleFactoryImpl com.sun.faces.renderkit.RenderKitFactoryImpl com.sun.faces.application.view.ViewDeclarationLanguageFactoryImpl com.sun.faces.facelets.tag.jsf.TagHandlerDelegateFactoryImpl com.sun.faces.context.ExternalContextFactoryImpl com.sun.faces.application.ActionListenerImpl com.sun.faces.application.NavigationHandlerImpl com.sun.faces.application.StateManagerImpl com.sun.faces.application.view.MultiViewHandler com.sun.faces.application.resource.ResourceHandlerImpl javax.faces.BigDecimal javax.faces.convert.BigDecimalConverter javax.faces.BigInteger javax.faces.convert.BigIntegerConverter javax.faces.Boolean javax.faces.convert.BooleanConverter javax.faces.Byte javax.faces.convert.ByteConverter javax.faces.Character javax.faces.convert.CharacterConverter javax.faces.DateTime javax.faces.convert.DateTimeConverter javax.faces.Double javax.faces.convert.DoubleConverter javax.faces.Float javax.faces.convert.FloatConverter javax.faces.Integer javax.faces.convert.IntegerConverter javax.faces.Long javax.faces.convert.LongConverter javax.faces.Number javax.faces.convert.NumberConverter javax.faces.Short javax.faces.convert.ShortConverter java.math.BigDecimal javax.faces.convert.BigDecimalConverter java.math.BigInteger javax.faces.convert.BigIntegerConverter java.lang.Boolean javax.faces.convert.BooleanConverter java.lang.Byte javax.faces.convert.ByteConverter java.lang.Character javax.faces.convert.CharacterConverter java.lang.Double javax.faces.convert.DoubleConverter java.lang.Float javax.faces.convert.FloatConverter java.lang.Integer javax.faces.convert.IntegerConverter java.lang.Long javax.faces.convert.LongConverter java.lang.Short javax.faces.convert.ShortConverter java.lang.Enum javax.faces.convert.EnumConverter com.sun.faces.lifecycle.ELResolverInitPhaseListener javax.faces.behavior.Ajax javax.faces.component.behavior.AjaxBehavior javax.faces.Bean javax.faces.validator.BeanValidator javax.faces.DoubleRange javax.faces.validator.DoubleRangeValidator javax.faces.Length javax.faces.validator.LengthValidator javax.faces.LongRange javax.faces.validator.LongRangeValidator javax.faces.RegularExpression javax.faces.validator.RegexValidator javax.faces.Required javax.faces.validator.RequiredValidator com.sun.faces.ext.validator.CreditCardValidator com.sun.faces.ext.validator.CreditCardValidator com.sun.faces.ext.focus com.sun.faces.ext.component.UIFocus facelets.ui.Repeat com.sun.faces.facelets.component.UIRepeat facelets.ui.ComponentRef com.sun.faces.facelets.tag.ui.ComponentRef facelets.ui.Debug com.sun.faces.facelets.tag.ui.UIDebug javax.faces.Composite com.sun.faces.facelets.tag.jsf.CompositeComponentImpl javax.faces.ComponentResourceContainer com.sun.faces.component.ComponentResourceContainer HTML_BASIC FocusFamily com.sun.faces.ext.render.FocusHTMLRenderer com.sun.faces.ext.render.FocusHTMLRenderer facelets facelets.ui.Repeat com.sun.faces.facelets.component.RepeatRenderer javax.faces.behavior.Ajax com.sun.faces.renderkit.html_basic.AjaxBehaviorRenderer mojarra-2.0.3.orig/jsf-ri/lib/0000755000000000000000000000000011412443620012731 5ustar mojarra-2.0.3.orig/jsf-ri/test/0000755000000000000000000000000011412443352013144 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/0000755000000000000000000000000011412443346013725 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/0000755000000000000000000000000011412443346014532 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/0000755000000000000000000000000011412443352015610 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/SystemEventListener1.java0000644000000000000000000000503111412443352022527 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces; import javax.faces.event.SystemEventListener; import javax.faces.event.SystemEvent; import javax.faces.event.AbortProcessingException; import javax.faces.component.UIOutput; import javax.faces.context.FacesContext; public class SystemEventListener1 implements SystemEventListener { public void processEvent(SystemEvent event) throws AbortProcessingException { FacesContext ctx = FacesContext.getCurrentInstance(); ctx.getAttributes().put("SystemEventListener1", Boolean.TRUE); } public boolean isListenerForSource(Object source) { return (source instanceof UIOutput); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/convert/0000755000000000000000000000000011412443350017266 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/convert/TestConverters.java0000644000000000000000000011376111412443350023134 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestConverters.java package com.sun.faces.convert; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.component.UIInput; import javax.faces.component.UISelectItem; import javax.faces.component.UISelectMany; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContextFactory; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.DateTimeConverter; import javax.faces.convert.NumberConverter; import javax.servlet.ServletConfig; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.cactus.TestingUtil; import com.sun.faces.util.Util; import com.sun.faces.application.ApplicationImpl; import org.apache.cactus.WebRequest; import org.apache.cactus.server.AbstractServletContextWrapper; /** * Test encode and decode methods in Renderer classes. *

* Lifetime And Scope

*/ public class TestConverters extends JspFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // private FacesContextFactory facesContextFactory = null; // Attribute Instance Variables // Relationship Instance Variables protected Application application; // // Constructors and Initializers // public TestConverters() { super("TestConverters"); } public TestConverters(String name) { super(name); } // // Class methods // // // Methods from TestCase // public void setUp() { super.setUp(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = aFactory.getApplication(); UIViewRoot viewRoot = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); viewRoot.setViewId("viewId"); viewRoot.setLocale(Locale.US); getFacesContext().setViewRoot(viewRoot); } public void beginConverters(WebRequest theRequest) { } public void testConverters() { try { // create a dummy root for the tree. UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setId("root"); testDateConverter(root); testNumberConverter(root); testConverterInheritance(root); testBooleanConverter(root); testConverterInheritance(root); //assertTrue(verifyExpectedOutput()); testDoubleConverter(root); } catch (Throwable t) { t.printStackTrace(); assertTrue(false); return; } } public static class TestBean extends Object { boolean[] booleans = null; public TestBean() { super(); } public boolean[] getBooleans() { return booleans; } public void setBooleans(boolean[] newBooleans) { booleans = newBooleans; } byte[] bytes = null; public byte[] getBytes() { return bytes; } public void setBytes(byte[] newBytes) { bytes = newBytes; } char[] chars = null; public char[] getChars() { return chars; } public void setChars(char[] newChars) { chars = newChars; } short[] shorts = null; public short[] getShorts() { return shorts; } public void setShorts(short[] newShorts) { shorts = newShorts; } int[] ints = null; public int[] getInts() { return ints; } public void setInts(int[] newInts) { ints = newInts; } long[] longs = null; public long[] getLongs() { return longs; } public void setLongs(long[] newLongs) { longs = newLongs; } float[] floats = null; public float[] getFloats() { return floats; } public void setFloats(float[] newFloats) { floats = newFloats; } double[] doubles = null; public double[] getDoubles() { return doubles; } public void setDoubles(double[] newDoubles) { doubles = newDoubles; } String[] strings = null; public String[] getStrings() { return strings; } public void setStrings(String[] newStrings) { strings = newStrings; } Date[] dates = null; public Date[] getDates() { return dates; } public void setDates(Date[] newDates) { dates = newDates; } Number[] numbers = null; public Number[] getNumbers() { return numbers; } public void setNumbers(Number[] newNumbers) { numbers = newNumbers; } List stringList = null; public List getStringList() { return stringList; } public void setStringList(List newStringList) { stringList = newStringList; } } public void beginUISelectMany(WebRequest theRequest) { // primitives theRequest.addParameter("bool", "false"); theRequest.addParameter("bool", "true"); theRequest.addParameter("bool", "false"); theRequest.addParameter("bool2", "false"); theRequest.addParameter("byte", Byte.toString(Byte.MIN_VALUE)); theRequest.addParameter("byte", Byte.toString(Byte.MAX_VALUE)); theRequest.addParameter("byte", "1"); theRequest.addParameter("char", "Q"); theRequest.addParameter("char", "A"); theRequest.addParameter("char", "z"); theRequest.addParameter("short", Short.toString(Short.MIN_VALUE)); theRequest.addParameter("short", Short.toString(Short.MAX_VALUE)); theRequest.addParameter("short", Short.toString((short) (Byte.MAX_VALUE + 1))); theRequest.addParameter("int", Integer.toString(Integer.MIN_VALUE)); theRequest.addParameter("int", Integer.toString(Integer.MAX_VALUE)); theRequest.addParameter("int", Integer.toString(Short.MAX_VALUE + 1)); theRequest.addParameter("float", Float.toString(Float.MIN_VALUE)); theRequest.addParameter("float", Float.toString(Float.MAX_VALUE)); theRequest.addParameter("float", Float.toString(Integer.MAX_VALUE + 1)); theRequest.addParameter("long", Long.toString(Long.MIN_VALUE)); theRequest.addParameter("long", Long.toString(Long.MAX_VALUE)); theRequest.addParameter("long", Long.toString(Integer.MAX_VALUE + 1)); theRequest.addParameter("double", Double.toString(Double.MIN_VALUE)); theRequest.addParameter("double", Double.toString(Double.MAX_VALUE)); theRequest.addParameter("double", Double.toString(Long.MAX_VALUE + 1)); // Objects theRequest.addParameter("str", "value1"); theRequest.addParameter("str", "value2"); theRequest.addParameter("str", "value3"); theRequest.addParameter("str2", ""); theRequest.addParameter("date", "Jan 1, 1967"); theRequest.addParameter("date", "May 26, 2003"); theRequest.addParameter("date", "Aug 19, 1946"); theRequest.addParameter("num", "12%"); theRequest.addParameter("num", "3.14"); theRequest.addParameter("num", "49.99"); theRequest.addParameter("stringList", "value1"); theRequest.addParameter("stringList", "value2"); theRequest.addParameter("stringList", "value3"); } public void testUISelectMany() throws Exception { // create the test bean TestBean bean = new TestBean(); getFacesContext().getExternalContext().getRequestMap().put("bean", bean); // create a dummy root for the tree. UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setId("root"); root.setLocale(Locale.US); getFacesContext().setViewRoot(root); // test model type of boolean [] UISelectMany booleanv = new UISelectMany(); booleanv.setId("bool"); booleanv.setRendererType("javax.faces.Checkbox"); booleanv.setValueExpression("value", (getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(), "#{bean.booleans}", Boolean.class))); root.getChildren().add(booleanv); booleanv.getChildren().add(newUISelectItem(Boolean.TRUE)); booleanv.getChildren().add(newUISelectItem(Boolean.FALSE)); booleanv.decode(getFacesContext()); booleanv.validate(getFacesContext()); booleanv.updateModel(getFacesContext()); assertNotNull(bean.getBooleans()); assertTrue(bean.getBooleans()[0] == false); assertTrue(bean.getBooleans()[1] == true); assertTrue(bean.getBooleans()[2] == false); // test model type of boolean [] booleanv = new UISelectMany(); booleanv.setId("bool2"); booleanv.setRendererType("javax.faces.Checkbox"); booleanv.setValueExpression("value", (getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.booleans}", Object.class))); root.getChildren().add(booleanv); booleanv.getChildren().add(newUISelectItem(Boolean.TRUE)); booleanv.getChildren().add(newUISelectItem(Boolean.FALSE)); booleanv.decode(getFacesContext()); booleanv.validate(getFacesContext()); booleanv.updateModel(getFacesContext()); assertNotNull(bean.getBooleans()); assertTrue(bean.getBooleans()[0] == false); assertTrue(bean.getBooleans().length == 1); // test model type of byte [] UISelectMany bytev = new UISelectMany(); bytev.setId("byte"); bytev.setRendererType("javax.faces.Checkbox"); bytev.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(), "#{bean.bytes}", Object.class)); bytev.getChildren().add(newUISelectItem(new Byte(Byte.MIN_VALUE))); bytev.getChildren().add(newUISelectItem(new Byte(Byte.MAX_VALUE))); bytev.getChildren().add(newUISelectItem(new Byte((byte) 1))); bytev.getChildren().add(newUISelectItem(new Byte((byte) -1))); root.getChildren().add(bytev); bytev.decode(getFacesContext()); bytev.validate(getFacesContext()); bytev.updateModel(getFacesContext()); assertNotNull(bean.getBytes()); assertTrue(bean.getBytes()[0] == Byte.MIN_VALUE); assertTrue(bean.getBytes()[1] == Byte.MAX_VALUE); assertTrue(bean.getBytes()[2] == 1); // test model type of char [] UISelectMany charv = new UISelectMany(); charv.setId("char"); charv.setRendererType("javax.faces.Checkbox"); charv.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.chars}", Object.class)); root.getChildren().add(charv); charv.getChildren().add(newUISelectItem(new Character('Q'))); charv.getChildren().add(newUISelectItem(new Character('A'))); charv.getChildren().add(newUISelectItem(new Character('Z'))); charv.getChildren().add(newUISelectItem(new Character('z'))); charv.decode(getFacesContext()); charv.validate(getFacesContext()); charv.updateModel(getFacesContext()); assertNotNull(bean.getChars()); assertTrue(bean.getChars()[0] == 'Q'); assertTrue(bean.getChars()[1] == 'A'); assertTrue(bean.getChars()[2] == 'z'); // test model type of short [] UISelectMany shortv = new UISelectMany(); shortv.setId("short"); shortv.setRendererType("javax.faces.Checkbox"); shortv.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.shorts}", Object.class)); root.getChildren().add(shortv); shortv.getChildren().add( newUISelectItem(new Short((short) (Byte.MAX_VALUE + 1)))); shortv.getChildren().add(newUISelectItem(new Short((short) 100))); shortv.getChildren().add(newUISelectItem(new Short(Short.MIN_VALUE))); shortv.getChildren().add(newUISelectItem(new Short(Short.MAX_VALUE))); shortv.decode(getFacesContext()); shortv.validate(getFacesContext()); shortv.updateModel(getFacesContext()); assertNotNull(bean.getShorts()); assertTrue(bean.getShorts()[0] == Short.MIN_VALUE); assertTrue(bean.getShorts()[1] == Short.MAX_VALUE); assertTrue(bean.getShorts()[2] == Byte.MAX_VALUE + 1); // test model type of int [] UISelectMany intv = new UISelectMany(); intv.setId("int"); intv.setRendererType("javax.faces.Checkbox"); intv.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.ints}", Object.class)); root.getChildren().add(intv); intv.getChildren().add( newUISelectItem(new Integer(Short.MAX_VALUE + 1))); intv.getChildren().add(newUISelectItem(new Integer(100))); intv.getChildren().add(newUISelectItem(new Integer(Integer.MIN_VALUE))); intv.getChildren().add(newUISelectItem(new Integer(Integer.MAX_VALUE))); intv.decode(getFacesContext()); intv.validate(getFacesContext()); intv.updateModel(getFacesContext()); assertNotNull(bean.getInts()); assertTrue(bean.getInts()[0] == Integer.MIN_VALUE); assertTrue(bean.getInts()[1] == Integer.MAX_VALUE); assertTrue(bean.getInts()[2] == Short.MAX_VALUE + 1); // test model type of float [] UISelectMany floatv = new UISelectMany(); floatv.setId("float"); floatv.setRendererType("javax.faces.Checkbox"); floatv.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.floats}", Object.class)); root.getChildren().add(floatv); floatv.getChildren().add( newUISelectItem(new Float(Integer.MAX_VALUE + 1))); floatv.getChildren().add(newUISelectItem(new Float(100))); floatv.getChildren().add(newUISelectItem(new Float(Float.MIN_VALUE))); floatv.getChildren().add(newUISelectItem(new Float(Float.MAX_VALUE))); floatv.decode(getFacesContext()); floatv.validate(getFacesContext()); floatv.updateModel(getFacesContext()); assertNotNull(bean.getFloats()); assertTrue(bean.getFloats()[0] == Float.MIN_VALUE); assertTrue(bean.getFloats()[1] == Float.MAX_VALUE); assertTrue(bean.getFloats()[2] == Integer.MAX_VALUE + 1); // test model type of long [] UISelectMany longv = new UISelectMany(); longv.setId("long"); longv.setRendererType("javax.faces.Checkbox"); longv.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.longs}", Object.class)); root.getChildren().add(longv); longv.getChildren().add( newUISelectItem(new Long(Integer.MAX_VALUE + 1))); longv.getChildren().add(newUISelectItem(new Long(100))); longv.getChildren().add(newUISelectItem(new Long(Long.MIN_VALUE))); longv.getChildren().add(newUISelectItem(new Long(Long.MAX_VALUE))); longv.decode(getFacesContext()); longv.validate(getFacesContext()); longv.updateModel(getFacesContext()); assertNotNull(bean.getLongs()); assertTrue(bean.getLongs()[0] == Long.MIN_VALUE); assertTrue(bean.getLongs()[1] == Long.MAX_VALUE); assertTrue(bean.getLongs()[2] == Integer.MAX_VALUE + 1); // test model type of double [] UISelectMany doublev = new UISelectMany(); doublev.setId("double"); doublev.setRendererType("javax.faces.Checkbox"); doublev.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.doubles}", Object.class)); root.getChildren().add(doublev); doublev.getChildren().add( newUISelectItem(new Double(Long.MAX_VALUE + 1))); doublev.getChildren().add(newUISelectItem(new Double(100))); doublev.getChildren().add( newUISelectItem(new Double(Double.MIN_VALUE))); doublev.getChildren().add( newUISelectItem(new Double(Double.MAX_VALUE))); doublev.decode(getFacesContext()); doublev.validate(getFacesContext()); doublev.updateModel(getFacesContext()); assertNotNull(bean.getDoubles()); assertTrue(bean.getDoubles()[0] == Double.MIN_VALUE); assertTrue(bean.getDoubles()[1] == Double.MAX_VALUE); assertTrue(bean.getDoubles()[2] == Long.MAX_VALUE + 1); // test model type of String [] UISelectMany str = new UISelectMany(); str.setId("str"); str.setRendererType("javax.faces.Checkbox"); str.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.strings}", Object.class)); root.getChildren().add(str); str.getChildren().add(newUISelectItem("value1")); str.getChildren().add(newUISelectItem("value2")); str.getChildren().add(newUISelectItem("value3")); str.getChildren().add(newUISelectItem("value4")); str.decode(getFacesContext()); str.validate(getFacesContext()); str.updateModel(getFacesContext()); assertNotNull(bean.getStrings()); assertTrue("value1".equals(bean.getStrings()[0])); // test model type of Date [] UISelectMany date = new UISelectMany(); Converter dateConv = Util.getConverterForIdentifer( "javax.faces.DateTime", getFacesContext()); assertNotNull(dateConv); date.setConverter(dateConv); date.setId("date"); date.setRendererType("javax.faces.Checkbox"); date.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.dates}", Object.class)); root.getChildren().add(date); try { SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); df.setTimeZone(TimeZone.getTimeZone("GMT")); date.getChildren().add(newUISelectItem(df.parse("19670101"))); date.getChildren().add(newUISelectItem(df.parse("20030526"))); date.getChildren().add(newUISelectItem(df.parse("19460819"))); date.getChildren().add(newUISelectItem(df.parse("17760704"))); } catch (ParseException e) { assertTrue(e.getMessage(), false); } date.decode(getFacesContext()); date.validate(getFacesContext()); date.updateModel(getFacesContext()); assertNotNull(bean.getDates()); Object expected = null; try { SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); df.setTimeZone(TimeZone.getTimeZone("GMT")); expected = df.parse("19460819"); } catch (ParseException e) { assertTrue(e.getMessage(), false); } assertEquals("bean.getDates()[2] not as expected: ", expected, bean.getDates()[2]); // test model type of Number [] UISelectMany number = new UISelectMany(); Converter numberConv = Util.getConverterForIdentifer( "javax.faces.Number", getFacesContext()); assertNotNull(numberConv); number.setConverter(numberConv); number.setId("num"); number.setRendererType("javax.faces.Checkbox"); number.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.numbers}", Object.class)); root.getChildren().add(number); number.getChildren().add(newUISelectItem(new Double(3.14))); number.getChildren().add(newUISelectItem(new Double(49.99))); number.getChildren().add(newUISelectItem(new Long(12))); number.getChildren().add(newUISelectItem(new Double(-145.5))); number.decode(getFacesContext()); number.validate(getFacesContext()); number.updateModel(getFacesContext()); assertNotNull(bean.getNumbers()); try { DecimalFormat df = new DecimalFormat("'$'##.##", new DecimalFormatSymbols(Locale.US)); expected = df.parse("$49.99"); } catch (ParseException e) { assertTrue(e.getMessage(), false); } assertTrue(expected.equals(bean.getNumbers()[2])); // test model type of List of Strings UISelectMany stringList = new UISelectMany(); stringList.setId("stringList"); stringList.setRendererType("javax.faces.Checkbox"); stringList.setValueExpression("value", getFacesContext().getApplication().getExpressionFactory().createValueExpression(getFacesContext().getELContext(),"#{bean.stringList}", Object.class)); root.getChildren().add(stringList); stringList.getChildren().add(newUISelectItem("value1")); stringList.getChildren().add(newUISelectItem("value2")); stringList.getChildren().add(newUISelectItem("value3")); stringList.getChildren().add(newUISelectItem("value4")); stringList.decode(getFacesContext()); stringList.validate(getFacesContext()); stringList.updateModel(getFacesContext()); assertNotNull(bean.getStringList()); assertTrue(bean.getStringList().get(0).equals("value1")); assertTrue(bean.getStringList().get(1).equals("value2")); assertTrue(bean.getStringList().get(2).equals("value3")); } // // General Methods // public void testDateConverter(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Testing DateConverter"); UIInput text = new UIInput(); text.setId("my_input_date"); root.getChildren().add(text); Converter converter = null; converter = application.createConverter("javax.faces.DateTime"); // date String stringToConvert = "Jan 1, 1967"; Object obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.util.Date); String str = converter.getAsString(getFacesContext(), text, obj); // make sure we end up with the same string we started with.. assertTrue(str.equals(stringToConvert)); // time converter = application.createConverter("javax.faces.DateTime"); ((DateTimeConverter) converter).setType("time"); text = new UIInput(); text.setId("my_input_time"); stringToConvert = "10:10:10 AM"; obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.util.Date); str = converter.getAsString(getFacesContext(), text, obj); // make sure we end up with the same string we started with.. assertTrue(str.equals(stringToConvert)); // datetime converter = application.createConverter("javax.faces.DateTime"); ((DateTimeConverter) converter).setType("both"); text = new UIInput(); text.setId("my_input_datetime"); stringToConvert = "Jan 1, 1967 10:10:10 AM"; obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.util.Date); str = converter.getAsString(getFacesContext(), text, obj); // make sure we end up with the same string we started with.. assertTrue(str.equals(stringToConvert)); // test bogus type.... boolean exceptionThrown = false; try { ((DateTimeConverter)converter).setType("foobar"); obj = converter.getAsObject(getFacesContext(), text, stringToConvert); } catch (Exception e) { exceptionThrown = true; } assertTrue(exceptionThrown); // test NullPointerException (if either context or component arg is null) exceptionThrown = false; try { obj = converter.getAsObject(null, text, stringToConvert); } catch (NullPointerException npe) { exceptionThrown= true; } assertTrue(exceptionThrown); exceptionThrown = false; try { obj = converter.getAsObject(getFacesContext(), null, stringToConvert); } catch (NullPointerException npe) { exceptionThrown= true; } assertTrue(exceptionThrown); exceptionThrown = false; try { str = converter.getAsString(null, text, obj); } catch (NullPointerException npe) { exceptionThrown= true; } assertTrue(exceptionThrown); exceptionThrown = false; try { str = converter.getAsString(getFacesContext(), null, obj); } catch (NullPointerException npe) { exceptionThrown= true; } assertTrue(exceptionThrown); } public void testDateTimeConverterGMTTimeZone() throws Exception { UIInput input = new UIInput(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.ENGLISH); df.setTimeZone(TimeZone.getTimeZone("GMT")); Date now = new Date(); String formatted = df.format(now); Date parsed = df.parse(formatted); // control setup, now test the converter. Application app = getFacesContext().getApplication(); DateTimeConverter converter = (DateTimeConverter) app.createConverter("javax.faces.DateTime"); converter.setType("both"); assertNotNull(converter); assertTrue(TimeZone.getTimeZone("GMT").toString(), TimeZone.getTimeZone("GMT").equals(converter.getTimeZone())); assertTrue(formatted, formatted.equals(converter.getAsString(getFacesContext(), input, parsed))); assertTrue(parsed.toString(), parsed.equals(converter.getAsObject(getFacesContext(), input, formatted))); app.addConverter(java.util.Date.class, "javax.faces.convert.DateTimeConverter"); converter = (DateTimeConverter) app.createConverter(java.util.Date.class); converter.setType("both"); assertNotNull(converter); assertTrue(TimeZone.getTimeZone("GMT").toString(), TimeZone.getTimeZone("GMT").equals(converter.getTimeZone())); assertTrue(formatted, formatted.equals(converter.getAsString(getFacesContext(), input, parsed))); assertTrue(parsed.toString(), parsed.equals(converter.getAsObject(getFacesContext(), input, formatted))); } public void testDateTimeConverterDefaultTimeZone() throws Exception { TestingUtil.setPrivateField("passDefaultTimeZone", ApplicationImpl.class, application, Boolean.TRUE); TestingUtil.setPrivateField("systemTimeZone", ApplicationImpl.class, application, TimeZone.getDefault()); UIInput input = new UIInput(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.ENGLISH); df.setTimeZone(TimeZone.getDefault()); Date now = new Date(); String formatted = df.format(now); Date parsed = df.parse(formatted); // control setup, now test the converter. Application app = getFacesContext().getApplication(); DateTimeConverter converter = (DateTimeConverter) app.createConverter("javax.faces.DateTime"); converter.setType("both"); assertNotNull(converter); assertTrue(TimeZone.getDefault().toString(), TimeZone.getDefault().equals(converter.getTimeZone())); assertTrue(formatted, formatted.equals(converter.getAsString(getFacesContext(), input, parsed))); assertTrue(parsed.toString(), parsed.equals(converter.getAsObject(getFacesContext(), input, formatted))); app.addConverter(java.util.Date.class, "javax.faces.convert.DateTimeConverter"); converter = (DateTimeConverter) app.createConverter(java.util.Date.class); converter.setType("both"); assertNotNull(converter); assertTrue(TimeZone.getDefault().toString(), TimeZone.getDefault().equals(converter.getTimeZone())); assertTrue(formatted, formatted.equals(converter.getAsString(getFacesContext(), input, parsed))); assertTrue(parsed.toString(), parsed.equals(converter.getAsObject(getFacesContext(), input, formatted))); } public void testNumberConverter(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Tesing NumberConverter"); UIInput text = new UIInput(); text.setId("my_input_number"); root.getChildren().add(text); Converter converter = application.createConverter("javax.faces.Number"); String stringToConvert = "99.9"; Object obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.lang.Number); String str = converter.getAsString(getFacesContext(), text, obj); assertTrue(str.equals(stringToConvert)); } public void testNumberConverterSpacesNBSP() throws Exception { UIInput text = new UIInput(); NumberConverter converter = (NumberConverter) application.createConverter("javax.faces.Number"); converter.setType("currency"); converter.setLocale(Locale.FRANCE); String toConv = "12 345,68 " + '\u20aC'; Number number = (Number) converter.getAsObject(getFacesContext(), text, toConv); assertTrue(number != null); converter.setType("number"); toConv = "5" + "\u00a0" + "000" + "\u00a0" + "000,01"; number = (Number) converter.getAsObject(getFacesContext(), text, toConv); assertTrue("Number was: " + number.toString() + ", expected 5000000.01", "5000000.01".equals(number.toString())); } public void testDoubleConverter(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Tesing DoubleConverter"); Converter converter = application.createConverter("javax.faces.Double"); assertNotNull(converter); } public void testBooleanConverter(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Tesing BooleanConverter"); UIInput text = new UIInput(); text.setId("my_input_boolean"); root.getChildren().add(text); Converter converter = application.createConverter( java.lang.Boolean.class); String stringToConvert = "true"; Object obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.lang.Boolean); String str = converter.getAsString(getFacesContext(), text, obj); assertTrue(str.equals(stringToConvert)); } /** * Test to verify that a class that registers itself is properly found * using the search mechanism. The J2SE classes are used for their * inheritance hierarchy to test that converters registered to * interfaces and superclasses are properly found. *

* This test is meant for inheritance lookup only. */ public void testConverterInheritance(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Testing ConverterInheritance"); Converter converter; UIInput text = new UIInput(); text.setId("my_date_converter"); root.getChildren().add(text); //java.lang.Integer extends java.lang.Number. //Test to show that the standard converter registered to //java.lang.Integer should chosen over the inherited //java.lang.Number converter application.addConverter(java.lang.Number.class, "javax.faces.convert.NumberConverter"); converter = application.createConverter(java.lang.Integer.class); assertTrue(converter != null); assertTrue(converter instanceof javax.faces.convert.IntegerConverter); //java.sql.Date extends java.util.Date //Test to find converter registered to java.util.Date application.addConverter(java.util.Date.class, "javax.faces.convert.DateTimeConverter"); converter = null; converter = application.createConverter(java.sql.Date.class); assertTrue(converter != null); //java.util.HashSet is a subclass of java.util.AbstractSet which is //a subclass of java.util.AbstractCollection //Test to find the converter registered to java.util.AbstractCollection application.addConverter(java.util.AbstractCollection.class, "javax.faces.convert.DateTimeConverter"); converter = null; try { converter = application.createConverter(java.util.HashSet.class); } catch (javax.faces.FacesException fe) { } assertTrue(converter != null); //java.lang.String implements java.lang.CharSequence //Test to find the converter registered to java.lang.CharSequence application.addConverter(java.text.CharacterIterator.class, "javax.faces.convert.CharacterConverter"); converter = null; converter = application.createConverter( java.text.StringCharacterIterator.class); assertTrue(converter != null); //java.text.StringCharacterIterator implements //java.text.CharacterIterator which has a super-interface //java.lang.Cloneable //Test to find the converter registered to java.lang.Cloneable application.addConverter(java.lang.Cloneable.class, "javax.faces.convert.CharacterConverter"); converter = null; converter = application.createConverter( java.text.StringCharacterIterator.class); assertTrue(converter != null); } static private UISelectItem newUISelectItem(Object value) { UISelectItem item = new UISelectItem(); item.setItemValue(value); item.setItemLabel(value.toString()); return item; } } // end of class TestConverters mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestBean.java0000644000000000000000000000477311412443352020173 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces; import com.sun.faces.util.Util; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.el.ELException; public class TestBean extends com.sun.faces.cactus.TestBean { public TestBean() { } protected CustomerBean customerBean; public CustomerBean getCustomerBean() { return customerBean; } public void setCustomerBean(CustomerBean newCustomerBean) { customerBean = newCustomerBean; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/mock/0000755000000000000000000000000011412443350016537 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/mock/MockServletContext.java0000644000000000000000000003052011412443350023205 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.mock; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.FilterRegistration; import javax.servlet.Filter; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import java.util.Set; import java.util.Collections; import java.util.Map; import java.util.EventListener; // Mock Object for ServletContext (Version 2.3) public class MockServletContext implements ServletContext { // ------------------------------------------------------------ Constructors // Zero-args constructor for no associated directory public MockServletContext() { ; } // Constructor with File object for associated directory public MockServletContext(File directory) { setDirectory(directory); } // ------------------------------------------------------ Instance Variables private Hashtable attributes = new Hashtable(); private Hashtable parameters = new Hashtable(); private String name = "MockServletContext"; // -------------------------------------------------------------- Properties // The directory that is the base of our application resources private File directory = null; public File getDirectory() { return (this.directory); } public void setDirectory(File directory) { if (!directory.exists() || !directory.isDirectory()) { throw new IllegalArgumentException (directory.getAbsolutePath() + " is not an existing directory"); } this.directory = directory; } // ---------------------------------------------------------- Public Methods // Add a context innitialization parameter public void addInitParameter(String name, String value) { parameters.put(name, value); } // Set the servlet context name public void setServletContextName(String name) { this.name = name; } // -------------------------------------------------- ServletContext Methods public Object getAttribute(String name) { return (attributes.get(name)); } public Enumeration getAttributeNames() { return (attributes.keys()); } public ServletContext getContext(String uripath) { throw new UnsupportedOperationException(); } public String getContextPath() { return ('/' + name); } public String getInitParameter(String name) { return ((String) parameters.get(name)); } public Enumeration getInitParameterNames() { return (parameters.keys()); } public int getMajorVersion() { return (2); } public String getMimeType(String path) { throw new UnsupportedOperationException(); } public int getMinorVersion() { return (5); } public RequestDispatcher getNamedDispatcher(String name) { throw new UnsupportedOperationException(); } public String getRealPath(String path) { if (!path.startsWith("/") || (directory == null)) { return (null); } File file = new File(directory, path.substring(1)); if (!file.exists() || !file.isFile()) { return (null); } return (file.getAbsolutePath()); } public RequestDispatcher getRequestDispatcher(String path) { throw new UnsupportedOperationException(); } public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/") || (directory == null)) { return (null); } File file = new File(directory, path.substring(1)); if (!file.exists() || !file.isFile()) { return (null); } return (file.toURL()); } public InputStream getResourceAsStream(String path) { URL url = null; try { url = getResource(path); } catch (MalformedURLException e) { return (null); } if (url == null) { return (null); } try { return (url.openStream()); } catch (IOException e) { return (null); } } public Set getResourcePaths(String path) { return Collections.emptySet(); // PENDING(craigmcc) - Flesh out the following implementation /* if (!path.startsWith("/") || (directory == null)) { return (null); } File base = new File(directory, path.substring(1)); if (!base.exists() || !base.isDirectory()) { return (false); } Set results = new HashSet(); // PENDING(craigmcc) recursive descent search return (results); */ } public Servlet getServlet(String name) throws ServletException { throw new UnsupportedOperationException(); } public String getServletContextName() { return (name); } public String getServerInfo() { return ("MockServletContext"); } public Enumeration getServlets() { throw new UnsupportedOperationException(); } public Enumeration getServletNames() { throw new UnsupportedOperationException(); } public void log(String message) { throw new UnsupportedOperationException(); } public void log(Exception exception, String message) { throw new UnsupportedOperationException(); } public void log(String message, Throwable exception) { throw new UnsupportedOperationException(); } public void removeAttribute(String name) { attributes.remove(name); } public void setAttribute(String name, Object value) { attributes.put(name, value); } public int getEffectiveMajorVersion() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int getEffectiveMinorVersion() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean setInitParameter(String s, String s1) { return false; //To change body of implemented methods use File | Settings | File Templates. } public ServletRegistration.Dynamic addServlet(String s, String s1) { return null; //To change body of implemented methods use File | Settings | File Templates. } public ServletRegistration.Dynamic addServlet(String s, Servlet servlet) { return null; //To change body of implemented methods use File | Settings | File Templates. } public ServletRegistration.Dynamic addServlet(String s, Class aClass) { return null; //To change body of implemented methods use File | Settings | File Templates. } public T createServlet(Class tClass) throws ServletException { return null; //To change body of implemented methods use File | Settings | File Templates. } public ServletRegistration getServletRegistration(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } public Map getServletRegistrations() { return null; //To change body of implemented methods use File | Settings | File Templates. } public FilterRegistration.Dynamic addFilter(String s, String s1) { return null; //To change body of implemented methods use File | Settings | File Templates. } public FilterRegistration.Dynamic addFilter(String s, Filter filter) { return null; //To change body of implemented methods use File | Settings | File Templates. } public FilterRegistration.Dynamic addFilter(String s, Class aClass) { return null; //To change body of implemented methods use File | Settings | File Templates. } public T createFilter(Class tClass) throws ServletException { return null; //To change body of implemented methods use File | Settings | File Templates. } public FilterRegistration getFilterRegistration(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } public Map getFilterRegistrations() { return null; //To change body of implemented methods use File | Settings | File Templates. } public SessionCookieConfig getSessionCookieConfig() { return null; //To change body of implemented methods use File | Settings | File Templates. } public void setSessionTrackingModes(Set sessionTrackingModes) { //To change body of implemented methods use File | Settings | File Templates. } public Set getDefaultSessionTrackingModes() { return null; //To change body of implemented methods use File | Settings | File Templates. } public Set getEffectiveSessionTrackingModes() { return null; //To change body of implemented methods use File | Settings | File Templates. } public void addListener(String s) { //To change body of implemented methods use File | Settings | File Templates. } public void addListener(T t) { //To change body of implemented methods use File | Settings | File Templates. } public void addListener(Class aClass) { //To change body of implemented methods use File | Settings | File Templates. } public T createListener(Class tClass) throws ServletException { return null; //To change body of implemented methods use File | Settings | File Templates. } public JspConfigDescriptor getJspConfigDescriptor() { return null; //To change body of implemented methods use File | Settings | File Templates. } public ClassLoader getClassLoader() { return null; //To change body of implemented methods use File | Settings | File Templates. } public void declareRoles(String... strings) { //To change body of implemented methods use File | Settings | File Templates. } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestELResolver.java0000644000000000000000000000656111412443352021345 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces; import java.util.Arrays; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.beans.FeatureDescriptor; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.component.UIViewRoot; import javax.el.ELException; import javax.el.PropertyNotWritableException; import javax.el.PropertyNotFoundException; import javax.el.PropertyNotFoundException; import javax.el.ELContext; import javax.el.ELResolver; import com.sun.faces.el.ELConstants; import com.sun.faces.util.Util; public class TestELResolver extends ELResolver { public TestELResolver() { } public Object getValue(ELContext context,Object base, Object property) throws ELException { return null; } public void setValue(ELContext context, Object base, Object property, Object val) throws ELException { } public boolean isReadOnly(ELContext context, Object base, Object property) throws ELException{ return false; } public Class getType(ELContext context, Object base, Object property) throws ELException { return Object.class; } public Iterator getFeatureDescriptors(ELContext context, Object base) { return null; } public Class getCommonPropertyType(ELContext context, Object base) { if (base != null) { return null; } return String.class; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestOldVariableResolver.java0000644000000000000000000000530211412443352023221 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestOldVariableResolver.java package com.sun.faces; import javax.faces.el.VariableResolver; import javax.faces.el.EvaluationException; import javax.faces.context.FacesContext; public class TestOldVariableResolver extends VariableResolver { VariableResolver resolver = null; public TestOldVariableResolver(VariableResolver variableResolver) { this.resolver = variableResolver; } // // Relationship Instance Variables // // Specified by javax.faces.el.VariableResolver.resolveVariable() public Object resolveVariable(FacesContext context, String name) throws EvaluationException { if (name.equals("customVRTest2")) { return "TestOldVariableResolver"; } return resolver.resolveVariable(context, name); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestResourceBundle2_de.properties0000644000000000000000000000006411412443352024241 0ustar # Sample ResourceBundle properties file label=Abflugmojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/0000755000000000000000000000000011412443352017055 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/NonManagedBean.java0000644000000000000000000000376711412443352022532 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; public class NonManagedBean { public NonManagedBean() {}; } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/NewCustomerFormHandler.java0000644000000000000000000000663511412443352024327 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import java.util.HashMap; import java.util.List; public class NewCustomerFormHandler { public NewCustomerFormHandler() { } public String loginRequired() { return "loginRequired"; } private String minimumAge; public String getMinimumAge() { return minimumAge; } public void setMinimumAge(String minimumAge) { this.minimumAge = minimumAge; } private String maximumAge; public String getMaximumAge() { return maximumAge; } public void setMaximumAge(String maximumAge) { this.maximumAge = maximumAge; } private String nationality; public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } private List allowableValues; public List getAllowableValues() { return allowableValues; } public void setAllowableValues(List allowableValues) { this.allowableValues = allowableValues; } private String[] firstNames = { "bob", "jerry" }; public String[] getFirstNames() { return firstNames; } public void setFirstNames(String[] newNames) { firstNames = newNames; } private HashMap claimAmounts; public HashMap getClaimAmounts() { return claimAmounts; } public void setClaimAmounts(HashMap claimAmounts) { this.claimAmounts = claimAmounts; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/TestFacesConfigOrdering.java0000644000000000000000000006642311412443352024434 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2008 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Arrays; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.faces.context.FacesContext; import com.sun.faces.cactus.ServletFacesTestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Attr; /** * Test cases to validate faces-config ordering. */ public class TestFacesConfigOrdering extends ServletFacesTestCase { // ------------------------------------------------------------ Constructors public TestFacesConfigOrdering() { this("TestFacesConfigOrdering"); } public TestFacesConfigOrdering(String name) { super(name); } // ------------------------------------------------------------ Test Methods public void testDocumentOrderingWrapperInit() throws Exception { // this should test segment should fail since this document is // before and after A List docBeforeIds = new ArrayList(); Collections.addAll(docBeforeIds, "A"); List docAfterIds = new ArrayList(); Collections.addAll(docAfterIds, "A"); try { new DocumentOrderingWrapper(createDocument("MyDoc", docBeforeIds, docAfterIds)); fail("Expected DocumentOrderingWrapper to throw an exception when the wrapped document was configured to be before and after the same document."); } catch (ConfigurationException ce) { // expected } // this test segment ensures that 'empty defaults will be used if the // document has no document ID. DocumentOrderingWrapper w = new DocumentOrderingWrapper(createDocument(null, docBeforeIds, null)); assertEquals("Expected DocumentOrderingWrapper.getDocumentId() to return an empty string when no ID was specified. Received: " + w.getDocumentId(), "", w.getDocumentId()); assertTrue(Arrays.equals(new String[] { "A" }, w.getBeforeIds())); assertTrue(Arrays.equals(new String[] { }, w.getAfterIds())); docAfterIds.clear(); Collections.addAll(docAfterIds, "others"); w = new DocumentOrderingWrapper(createDocument("MyDoc", docBeforeIds, docAfterIds)); assertEquals("Expected DocumentOrderingWrapper.getDocumentId() to return MyDoc, received: " + w.getDocumentId(), "MyDoc", w.getDocumentId()); assertTrue(Arrays.equals(new String[] { "A" }, w.getBeforeIds())); assertTrue(Arrays.equals(new String[] { "others" }, w.getAfterIds())); } public void testAfterAfterOthersBeforeBeforeOthers() throws Exception { List docAAfterIds = new ArrayList(); Collections.addAll(docAAfterIds, "@others", "C"); List docCAfterIds = new ArrayList(); Collections.addAll(docCAfterIds, "@others"); List docBBeforeIds = new ArrayList(); Collections.addAll(docBBeforeIds, "@others"); List docFBeforeIds = new ArrayList(); Collections.addAll(docFBeforeIds, "B", "@others"); DocumentInfo docA = createDocument("A", null, docAAfterIds); DocumentInfo docB = createDocument("B", docBBeforeIds, null); DocumentInfo docC = createDocument("C", null, docCAfterIds); DocumentInfo docD = createDocument("D", null, null); DocumentInfo docE = createDocument("E", null, null); DocumentInfo docF = createDocument("F", docFBeforeIds, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD), new DocumentOrderingWrapper(docE), new DocumentOrderingWrapper(docF)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "F", "B", "D", "E", "C", "A" }; validate(ids, wrappers); } public void testBeforeAfterOthersSorting() throws Exception { List docAAfterIds = new ArrayList(); Collections.addAll(docAAfterIds, "@others"); List docABeforeIds = new ArrayList(); Collections.addAll(docABeforeIds, "C"); List docBBeforeIds = new ArrayList(); Collections.addAll(docBBeforeIds, "@others"); List docDAfterIds = new ArrayList(); Collections.addAll(docDAfterIds, "@others"); List docEBeforeIds = new ArrayList(); Collections.addAll(docEBeforeIds, "@others"); DocumentInfo docA = createDocument(null, docABeforeIds, docAAfterIds); // no ID here to ensure this works DocumentInfo docB = createDocument("B", docBBeforeIds, null); DocumentInfo docC = createDocument("C", null, null); DocumentInfo docD = createDocument("D", null, docDAfterIds); DocumentInfo docE = createDocument("E", docEBeforeIds, null); DocumentInfo docF = createDocument("F", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD), new DocumentOrderingWrapper(docE), new DocumentOrderingWrapper(docF)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "B", "E", "F", "", "C", "D" }; validate(ids, wrappers); } public void testAfterBeforeOthersSorting() throws Exception { List docAAfterIds = new ArrayList(); Collections.addAll(docAAfterIds, "@others"); List docBBeforeIds = new ArrayList(); Collections.addAll(docBBeforeIds, "@others"); List docDAfterIds = new ArrayList(); Collections.addAll(docDAfterIds, "@others"); List docEBeforeIds = new ArrayList(); Collections.addAll(docEBeforeIds, "@others"); List docEAfterIds = new ArrayList(); Collections.addAll(docEAfterIds, "C"); DocumentInfo docA = createDocument("A", null, docAAfterIds); DocumentInfo docB = createDocument("B", docBBeforeIds, null); DocumentInfo docC = createDocument("C", null, null); DocumentInfo docD = createDocument("D", null, docDAfterIds); DocumentInfo docE = createDocument("E", docEBeforeIds, docEAfterIds); DocumentInfo docF = createDocument("F", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD), new DocumentOrderingWrapper(docE), new DocumentOrderingWrapper(docF)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "B", "C", "E", "F", "A", "D" }; validate(ids, wrappers); } public void testSpecSimple() throws Exception { List docAAfterIds = new ArrayList(); Collections.addAll(docAAfterIds, "B"); List docCBeforeIds = new ArrayList(); Collections.addAll(docCBeforeIds, "@others"); DocumentInfo docA = createDocument("A", null, docAAfterIds); DocumentInfo docB = createDocument("B", null, null); DocumentInfo docC = createDocument("C", docCBeforeIds, null); DocumentInfo docD = createDocument("D", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "C", "B", "D", "A" }; validate(ids, wrappers); } public void testBeforeIdAfterOthers() throws Exception { List docCBeforeIds = new ArrayList(); Collections.addAll(docCBeforeIds, "B"); List docCAfterIds = new ArrayList(); Collections.addAll(docCAfterIds, "@others"); DocumentInfo docA = createDocument("A", null, null); DocumentInfo docB = createDocument("B", null, null); DocumentInfo docC = createDocument("C", docCBeforeIds, docCAfterIds); DocumentInfo docD = createDocument("D", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "A", "D", "C", "B" }; validate(ids, wrappers); } public void testAfterIdBeforeOthers() throws Exception { List docCAfterIds = new ArrayList(); Collections.addAll(docCAfterIds, "D"); List docCBeforeIds = new ArrayList(); Collections.addAll(docCBeforeIds, "@others"); DocumentInfo docA = createDocument("A", null, null); DocumentInfo docB = createDocument("B", null, null); DocumentInfo docC = createDocument("C", docCBeforeIds, docCAfterIds); DocumentInfo docD = createDocument("D", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "D", "C", "A", "B" }; validate(ids, wrappers); } public void testAllAfterSpecificIds() throws Exception { List docAAfterIds = new ArrayList(); List docBAfterIds = new ArrayList(); List docCAfterIds = new ArrayList(); Collections.addAll(docAAfterIds, "B"); Collections.addAll(docBAfterIds, "C"); Collections.addAll(docCAfterIds, "D"); DocumentInfo docA = createDocument("A", null, docAAfterIds); DocumentInfo docB = createDocument("B", null, docBAfterIds); DocumentInfo docC = createDocument("C", null, docCAfterIds); DocumentInfo docD = createDocument("D", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "D", "C", "B", "A" }; validate(ids, wrappers); } public void testAllBeforeSpecificIds() throws Exception { List docBBeforeIds = new ArrayList(); List docCBeforeIds = new ArrayList(); List docDBeforeIds = new ArrayList(); Collections.addAll(docBBeforeIds, "A"); Collections.addAll(docCBeforeIds, "B"); Collections.addAll(docDBeforeIds, "C"); DocumentInfo docA = createDocument("A", null, null); DocumentInfo docB = createDocument("B", docBBeforeIds, null); DocumentInfo docC = createDocument("C", docCBeforeIds, null); DocumentInfo docD = createDocument("D", docDBeforeIds, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "D", "C", "B", "A" }; validate(ids, wrappers); } public void testMixed1() throws Exception { List docBAfterIds = new ArrayList(); List docCBeforeIds = new ArrayList(); Collections.addAll(docBAfterIds, "C"); Collections.addAll(docCBeforeIds, "B"); DocumentInfo docA = createDocument("A", null, null); DocumentInfo docB = createDocument("B", null, docBAfterIds); DocumentInfo docC = createDocument("C", docCBeforeIds, null); DocumentInfo docD = createDocument("D", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); DocumentOrderingWrapper.sort(wrappers); String[] ids = { "A", "C", "D", "B" }; validate(ids, wrappers); } public void testCyclic1() throws Exception { List docABeforeIds = new ArrayList(); List docBBeforeIds = new ArrayList(); List docCBeforeIds = new ArrayList(); Collections.addAll(docABeforeIds, "C"); Collections.addAll(docBBeforeIds, "A"); Collections.addAll(docCBeforeIds, "B"); DocumentInfo docA = createDocument("A", docABeforeIds, null); DocumentInfo docB = createDocument("B", docBBeforeIds, null); DocumentInfo docC = createDocument("C", docCBeforeIds, null); DocumentInfo docD = createDocument("D", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); try { DocumentOrderingWrapper.sort(wrappers); fail("No exception thrown when circular document dependency is present"); } catch (ConfigurationException ce) { // expected } } public void testCyclic2() throws Exception { List docAAfterIds = new ArrayList(); List docBAfterIds = new ArrayList(); List docCAfterIds = new ArrayList(); Collections.addAll(docAAfterIds, "B"); Collections.addAll(docBAfterIds, "C"); Collections.addAll(docCAfterIds, "A"); DocumentInfo docA = createDocument("A", null, docAAfterIds); DocumentInfo docB = createDocument("B", null, docBAfterIds); DocumentInfo docC = createDocument("C", null, docCAfterIds); DocumentInfo docD = createDocument("D", null, null); List documents = new ArrayList(); Collections.addAll(documents, new DocumentOrderingWrapper(docA), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docD)); DocumentOrderingWrapper[] wrappers = documents.toArray(new DocumentOrderingWrapper[documents.size()]); try { DocumentOrderingWrapper.sort(wrappers); fail("No exception thrown when circular document dependency is present"); } catch (ConfigurationException ce) { // expected } } public void testAbsoluteDocumentOrderingAPI() throws Exception { Document d = parseDocumentAsWebInfFacesConfig(getFacesContext(), "/WEB-INF/webinfAbsolute1.xml"); FacesConfigInfo info = new FacesConfigInfo(new DocumentInfo(d, null)); assertTrue(info.isWebInfFacesConfig()); assertTrue(info.isVersionGreaterOrEqual(2.0)); assertFalse(info.isMetadataComplete()); List ordering = info.getAbsoluteOrdering(); assertNotNull(ordering); assertEquals(3, ordering.size()); assertEquals("a", ordering.get(0)); assertEquals("b", ordering.get(1)); assertEquals("c", ordering.get(2)); d = parseDocumentAsWebInfFacesConfig(getFacesContext(), "/WEB-INF/webinfAbsolute2.xml"); info = new FacesConfigInfo(new DocumentInfo(d, null)); assertTrue(info.isWebInfFacesConfig()); assertTrue(info.isVersionGreaterOrEqual(2.0)); assertTrue(info.isMetadataComplete()); ordering = info.getAbsoluteOrdering(); assertNotNull(ordering); assertEquals(4, ordering.size()); assertEquals("a", ordering.get(0)); assertEquals("b", ordering.get(1)); assertEquals("others", ordering.get(2)); assertEquals("c", ordering.get(3)); d = parseDocumentAsWebInfFacesConfig(getFacesContext(), "/WEB-INF/webinfAbsolute3.xml"); info = new FacesConfigInfo(new DocumentInfo(d, null)); assertTrue(info.isWebInfFacesConfig()); assertFalse(info.isVersionGreaterOrEqual(2.0)); assertTrue(info.isMetadataComplete()); ordering = info.getAbsoluteOrdering(); assertNull(ordering); d = parseDocument(getFacesContext(), "/WEB-INF/webinfAbsolute1.xml"); info = new FacesConfigInfo(new DocumentInfo(d, null)); assertFalse(info.isWebInfFacesConfig()); } public void testAbsoluteOrderingProcessing() throws Exception { DocumentInfo docA = createDocument("a", null, null); DocumentInfo docB = createDocument("b", null, null); DocumentInfo docC = createDocument("c", null, null); DocumentInfo docD = createDocument("d", null, null); DocumentInfo docE = createDocument("e", null, null); DocumentInfo docF = createDocument("f", null, null); List wrappers = new ArrayList(); Collections.addAll(wrappers, new DocumentOrderingWrapper(docF), new DocumentOrderingWrapper(docE), new DocumentOrderingWrapper(docD), new DocumentOrderingWrapper(docC), new DocumentOrderingWrapper(docB), new DocumentOrderingWrapper(docA)); DocumentOrderingWrapper[] documentWrappers = wrappers.toArray(new DocumentOrderingWrapper[wrappers.size()]); Document d = parseDocumentAsWebInfFacesConfig(getFacesContext(), "/WEB-INF/webinfAbsolute1.xml"); FacesConfigInfo info = new FacesConfigInfo(new DocumentInfo(d, null)); List ordering = info.getAbsoluteOrdering(); DocumentOrderingWrapper[] result = DocumentOrderingWrapper.sort(documentWrappers, ordering); assertEquals(3, result.length); assertEquals("a", result[0].getDocumentId()); assertEquals("b", result[1].getDocumentId()); assertEquals("c", result[2].getDocumentId()); d = parseDocumentAsWebInfFacesConfig(getFacesContext(), "/WEB-INF/webinfAbsolute2.xml"); info = new FacesConfigInfo(new DocumentInfo(d, null)); ordering = info.getAbsoluteOrdering(); result = DocumentOrderingWrapper.sort(documentWrappers, ordering); assertEquals(6, result.length); assertEquals("a", result[0].getDocumentId()); assertEquals("b", result[1].getDocumentId()); assertEquals("d", result[2].getDocumentId()); assertEquals("e", result[3].getDocumentId()); assertEquals("f", result[4].getDocumentId()); assertEquals("c", result[5].getDocumentId()); } // ---------------------------------------------------------- Helper Methods private void validate(String[] ids, DocumentOrderingWrapper[] wrappers) { for (int i = 0; i < wrappers.length; i++) { assertEquals("Expected ID " + ids[i] + " at index " + i + ", but received " + wrappers[i].getDocumentId(), ids[i], wrappers[i].getDocumentId()); } } private Document parseDocument(FacesContext ctx, String path) throws Exception { DocumentBuilderFactory factory = DbfFactory.getFactory(); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(ctx.getExternalContext().getResourceAsStream(path)); } private Document parseDocumentAsWebInfFacesConfig(FacesContext ctx, String path) throws Exception { Document d = parseDocument(ctx, path); Attr webInf = d.createAttribute(ConfigManager.WEB_INF_MARKER); webInf.setValue("true"); d.getDocumentElement().getAttributes().setNamedItem(webInf); return d; } private DocumentInfo createDocument(String documentId, List beforeIds, List afterIds) throws Exception { String ns = "http://java.sun.com/xml/ns/javaee"; Document document = newDocument(); Element root = document.createElementNS(ns, "faces-config"); if (documentId != null) { Element nameElement = document.createElementNS(ns, "name"); nameElement.setTextContent(documentId); root.appendChild(nameElement); } document.appendChild(root); boolean hasBefore = (beforeIds != null && !beforeIds.isEmpty()); boolean hasAfter = (afterIds != null && !afterIds.isEmpty()); boolean createOrdering = (hasBefore || hasAfter); if (createOrdering) { Element ordering = document.createElementNS(ns, "ordering"); root.appendChild(ordering); if (hasBefore) { populateIds("before", beforeIds, ns, document, ordering); } if (hasAfter) { populateIds("after", afterIds, ns, document, ordering); } } return new DocumentInfo(document, null); } private void populateIds(String elementName, List ids, String ns, Document document, Element ordering) { Element element = document.createElementNS(ns, elementName); ordering.appendChild(element); for (String id : ids) { Element append; if ("@others".equals(id)) { append = document.createElementNS(ns, "others"); } else { append = document.createElementNS(ns, "name"); append.setTextContent(id); } element.appendChild(append); } } private Document newDocument() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); return factory.newDocumentBuilder().newDocument(); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/TestFactoryInjection.java0000644000000000000000000006510011412443352024034 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import java.lang.reflect.Field; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Set; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.MalformedURLException; import java.security.Principal; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.render.RenderKit; import javax.faces.lifecycle.Lifecycle; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.application.NavigationHandler; import javax.faces.application.StateManager; import javax.faces.application.ViewHandler; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.behavior.Behavior; import javax.faces.context.FacesContext; import javax.faces.context.FacesContextFactory; import javax.faces.context.ExternalContext; import javax.faces.context.ResponseStream; import javax.faces.context.ResponseWriter; import javax.faces.context.ExternalContextFactory; import javax.faces.convert.Converter; import javax.faces.el.MethodBinding; import javax.faces.el.PropertyResolver; import javax.faces.el.ReferenceSyntaxException; import javax.faces.el.ValueBinding; import javax.faces.el.VariableResolver; import javax.faces.event.ActionListener; import javax.faces.validator.Validator; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.servlet.ServletContext; import com.sun.faces.application.InjectionApplicationFactory; import com.sun.faces.application.ApplicationFactoryImpl; import com.sun.faces.application.ApplicationAssociate; import com.sun.faces.application.ApplicationImpl; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.config.processor.FactoryConfigProcessor; import com.sun.faces.context.FacesContextFactoryImpl; import com.sun.faces.context.FacesContextImpl; import com.sun.faces.context.ExceptionHandlerFactoryImpl; import com.sun.faces.context.ExternalContextFactoryImpl; import com.sun.faces.context.InjectionFacesContextFactory; import com.sun.faces.context.ExternalContextImpl; import com.sun.faces.lifecycle.LifecycleImpl; import com.sun.faces.renderkit.RenderKitFactoryImpl; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @SuppressWarnings({"deprecation"}) public class TestFactoryInjection extends ServletFacesTestCase { // ------------------------------------------------------------ Constructors public TestFactoryInjection() { super("TestFactoryFinder"); } public TestFactoryInjection(String name) { super(name); } // ------------------------------------------------------------ Test Methods public void testFactoryFinderApplicationInjection() throws Exception { Document d = newFacesConfigDocument(); Node facesConfig = d.getFirstChild(); Element factory = createElement(d, "factory"); facesConfig.appendChild(factory); Element application = createElement(d, "application-factory"); factory.appendChild(application); application.setTextContent("com.sun.faces.application.ApplicationFactoryImpl"); // clear the factories FactoryFinder.releaseFactories(); ApplicationAssociate.clearInstance(getFacesContext().getExternalContext()); // invoke the FactoryConfigProcessor FactoryConfigProcessor fcp = new FactoryConfigProcessor(false); fcp.process((ServletContext) getFacesContext().getExternalContext().getContext(), new DocumentInfo[] { new DocumentInfo(d, null) }); // now get an Application instance from the Factory and ensure // no injection occured. ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); assertNotNull(appFactory); assertNull(appFactory.getWrapped()); Application app = appFactory.getApplication(); // reflect the 'defaultApplication' field to ensure it's null Field field = Application.class.getDeclaredField("defaultApplication"); field.setAccessible(true); assertNull(field.get(app)); // reset for the injection portion of the test FactoryFinder.releaseFactories(); ApplicationAssociate.clearInstance(getFacesContext().getExternalContext()); // add another factory to our document Element application2 = createElement(d, "application-factory"); factory.appendChild(application2); application2.setTextContent(BasicApplicationFactory.class.getName()); // process the document. This should cause the the InjectionApplicationFactory // to be put into play since there is more than one ApplicationFactory // being configured fcp.process((ServletContext) getFacesContext().getExternalContext().getContext(), new DocumentInfo[] { new DocumentInfo(d, null) }); // get the ApplicationFactory instance. The top-level factory should // be the InjectionApplicationFactory. appFactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); assertNotNull(appFactory); assertEquals(InjectionApplicationFactory.class, appFactory.getClass()); ApplicationFactory wrapped1 = appFactory.getWrapped(); assertNotNull(wrapped1); assertEquals(BasicApplicationFactory.class, wrapped1.getClass()); ApplicationFactory wrapped2 = wrapped1.getWrapped(); assertEquals(ApplicationFactoryImpl.class, wrapped2.getClass()); // no ensure that the top level application instance's defaultApplication // instance was injected with the default Application instance. // This instance should be the same as that returned by wrapped2. app = appFactory.getApplication(); assertNotNull(app); Application fieldResult = (Application) field.get(app); assertNotNull(fieldResult); assertEquals(ApplicationImpl.class, fieldResult.getClass()); // basic application doesn't implement getProjetStage(), so without // injection, this method would throw an UnsupportedOperationException, // however, if we got this far, no exception should be thrown. try { app.getProjectStage(); } catch (UnsupportedOperationException uso) { fail("Application.getProjectStage() threw an Exception; injection failed"); } } public void testFactoryFinderFacesContextInjection() throws Exception { ExternalContext extContext = getFacesContext().getExternalContext(); ServletContext sc = (ServletContext) extContext.getContext(); Document d = newFacesConfigDocument(); Node facesConfig = d.getFirstChild(); Element factory = createElement(d, "factory"); facesConfig.appendChild(factory); Element application = createElement(d, "application-factory"); factory.appendChild(application); application .setTextContent("com.sun.faces.application.ApplicationFactoryImpl"); Element facesContext = createElement(d, "faces-context-factory"); factory.appendChild(facesContext); facesContext.setTextContent(FacesContextFactoryImpl.class.getName()); Element exceptionHandler = createElement(d, "exception-handler-factory"); factory.appendChild(exceptionHandler); exceptionHandler.setTextContent(ExceptionHandlerFactoryImpl.class.getName()); Element externalContextFactory = createElement(d, "external-context-factory"); factory.appendChild(externalContextFactory); externalContextFactory.setTextContent(ExternalContextFactoryImpl.class.getName()); Element renderKitFactory = createElement(d, "render-" + "kit-factory"); factory.appendChild(renderKitFactory); renderKitFactory.setTextContent(RenderKitFactoryImpl.class.getName()); // clear the factories FactoryFinder.releaseFactories(); ApplicationAssociate.clearInstance(extContext); FacesContext.getCurrentInstance().release(); // invoke the FactoryConfigProcessor FactoryConfigProcessor fcp = new FactoryConfigProcessor(false); fcp.process(sc, new DocumentInfo[]{new DocumentInfo(d, null)}); // now get an FacesContext instance from the Factory and ensure // no injection occured. FacesContextFactory fcFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY); assertNotNull(fcFactory); assertNull(fcFactory.getWrapped()); FacesContext fc = fcFactory.getFacesContext(sc, request, response, new LifecycleImpl()); // reflect the 'defaultFacesContext' field to ensure it's null Field field = FacesContext.class.getDeclaredField("defaultFacesContext"); Field extField = ExternalContext.class.getDeclaredField("defaultExternalContext"); field.setAccessible(true); extField.setAccessible(true); assertNull(field.get(fc)); // reset for the injection portion of the test FactoryFinder.releaseFactories(); ApplicationAssociate.clearInstance(extContext); FacesContext.getCurrentInstance().release(); // add another factory to our document Element facesContext2 = createElement(d, "faces-context-factory"); factory.appendChild(facesContext2); facesContext2.setTextContent(BasicFacesContextFactory.class.getName()); // process the document. This should cause the the InjectionFacesContextFactory // to be put into play since there is more than one FacesContextFactory // being configured fcp.process(sc, new DocumentInfo[]{new DocumentInfo(d, null)}); // get the FacesContextFactory instance. The top-level factory should // be the InjectionFacesContextFactory. fcFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY); assertNotNull(fcFactory); assertEquals(InjectionFacesContextFactory.class, fcFactory.getClass()); FacesContextFactory wrapped1 = fcFactory.getWrapped(); assertNotNull(wrapped1); assertEquals(BasicFacesContextFactory.class, wrapped1.getClass()); FacesContextFactory wrapped2 = wrapped1.getWrapped(); assertEquals(FacesContextFactoryImpl.class, wrapped2.getClass()); // now ensure that the top level facescontext instance's defaultFacesContext // field was injected with the default FacesContext implementation. // Also ensure that the top level ExternalContext instance's defaultExternalContext // field was injected with the default ExternalContext implementation. fc = fcFactory.getFacesContext(sc, request, response, new LifecycleImpl()); assertNotNull(fc); FacesContext fieldResult = (FacesContext) field.get(fc); assertNotNull(fieldResult); assertEquals(FacesContextImpl.class, fieldResult.getClass()); ExternalContext extFieldResult = (ExternalContext) extField.get(fc.getExternalContext()); assertNotNull(extFieldResult); assertEquals(ExternalContextImpl.class, extFieldResult.getClass()); // basic facescontext doesn't implement getAttributes(), so without // injection, this method would throw an UnsupportedOperationException, // however, if we got this far, no exception should be thrown. try { fc.getAttributes(); } catch (UnsupportedOperationException uso) { fail("FacesContext.getAttributes() threw an Exception; injection failed"); } } // --------------------------------------------------------- Private Methods private Document newFacesConfigDocument() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); Document d = factory.newDocumentBuilder().newDocument(); Element e = createElement(d, "faces-config"); d.appendChild(e); return d; } private Element createElement(Document d, String elementName) { final String ns = "http://java.sun.com/xml/ns/javaee"; return d.createElementNS(ns, elementName); } // ---------------------------------------------------------- Nested Classes public static final class BasicExternalContextFactory extends ExternalContextFactory { private ExternalContextFactory delegate; // -------------------------------------------------------- Constructors public BasicExternalContextFactory(ExternalContextFactory delegate) { this.delegate = delegate; } // ------------------------------------------- Methods from FacesWrapper @Override public ExternalContextFactory getWrapped() { return delegate; } // --------------------------------- Methods from ExternalContextFactory public ExternalContext getExternalContext(Object context, Object request, Object response) throws FacesException { ExternalContext extContext = delegate.getExternalContext(context, request, response); return new BasicExternalContext(extContext); } } public static final class BasicExternalContext extends ExternalContext { private ExternalContext delegate; public BasicExternalContext(ExternalContext delegate) { this.delegate = delegate; } public void dispatch(String path) throws IOException { } public String encodeActionURL(String url) { return null; } public String encodeNamespace(String name) { return null; } public String encodePartialActionURL(String viewId) { return null; } public String encodeResourceURL(String url) { return null; } public Map getApplicationMap() { return null; } public String getAuthType() { return null; } public Object getContext() { return null; } public String getInitParameter(String name) { return null; } public Map getInitParameterMap() { return null; } public String getRemoteUser() { return null; } public Object getRequest() { return null; } public String getRequestContextPath() { return null; } public Map getRequestCookieMap() { return null; } public Map getRequestHeaderMap() { return null; } public Map getRequestHeaderValuesMap() { return null; } public Locale getRequestLocale() { return null; } public Iterator getRequestLocales() { return null; } public Map getRequestMap() { return null; } public Map getRequestParameterMap() { return null; } public Iterator getRequestParameterNames() { return null; } public Map getRequestParameterValuesMap() { return null; } public String getRequestPathInfo() { return null; } public String getRequestServletPath() { return null; } public URL getResource(String path) throws MalformedURLException { return null; } public InputStream getResourceAsStream(String path) { return null; } public Set getResourcePaths(String path) { return null; } public Object getResponse() { return null; } public Object getSession(boolean create) { return null; } public Map getSessionMap() { return null; } public Principal getUserPrincipal() { return null; } public boolean isUserInRole(String role) { return false; } public void log(String message) { } public void log(String message, Throwable exception) { } public void redirect(String url) throws IOException { } } public static final class BasicFacesContextFactory extends FacesContextFactory { private FacesContextFactory delegate; // -------------------------------------------------------- Constructors public BasicFacesContextFactory(FacesContextFactory delegate) { this.delegate = delegate; } // ------------------------------------------- Methods from FacesWrapper @Override public FacesContextFactory getWrapped() { return delegate; } // ------------------------------------ Methods from FacesContextFactory public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle) throws FacesException { FacesContext fcdelegate = delegate.getFacesContext(context, request, response, lifecycle); return new BasicFacesContext(fcdelegate); } } // END BasicFacesContextFactory public static final class BasicFacesContext extends FacesContext { FacesContext delegate; public BasicFacesContext(FacesContext delegate) { this.delegate = delegate; } public Application getApplication() { return null; } public Iterator getClientIdsWithMessages() { return null; } public ExternalContext getExternalContext() { return delegate.getExternalContext(); } public FacesMessage.Severity getMaximumSeverity() { return null; } public Iterator getMessages() { return null; } public Iterator getMessages(String clientId) { return null; } public RenderKit getRenderKit() { return null; } public boolean getRenderResponse() { return false; } public boolean getResponseComplete() { return false; } public ResponseStream getResponseStream() { return null; } public void setResponseStream(ResponseStream responseStream) { } public ResponseWriter getResponseWriter() { return null; } public void setResponseWriter(ResponseWriter responseWriter) { } public UIViewRoot getViewRoot() { return null; } public void setViewRoot(UIViewRoot root) { } public void addMessage(String clientId, FacesMessage message) { } public void release() { delegate.release(); } public void renderResponse() { } public void responseComplete() { } boolean validationFailed; @Override public boolean isValidationFailed() { return validationFailed; } @Override public void validationFailed() { this.validationFailed = true; } } // END BasicFacesContext public static final class BasicApplicationFactory extends ApplicationFactory { private ApplicationFactory delegate; // -------------------------------------------------------- Constructors public BasicApplicationFactory(ApplicationFactory delegate) { this.delegate = delegate; } // ------------------------------------------- Methods from FacesWrapper @Override public ApplicationFactory getWrapped() { return delegate; } // ------------------------------------- Methods from ApplicationFactory public Application getApplication() { return new BasicApplication(); } public void setApplication(Application application) { //To change body of implemented methods use File | Settings | File Templates. } } // END BasicApplicationFactory public static final class BasicApplication extends Application { public ActionListener getActionListener() { return null; } public void setActionListener(ActionListener listener) { } public Locale getDefaultLocale() { return null; } public void setDefaultLocale(Locale locale) { } public String getDefaultRenderKitId() { return null; } public void setDefaultRenderKitId(String renderKitId) { } public String getMessageBundle() { return null; } public void setMessageBundle(String bundle) { } public NavigationHandler getNavigationHandler() { return null; } public void setNavigationHandler(NavigationHandler handler) { } public PropertyResolver getPropertyResolver() { return null; } public void setPropertyResolver(PropertyResolver resolver) { } public VariableResolver getVariableResolver() { return null; } public void setVariableResolver(VariableResolver resolver) { } public ViewHandler getViewHandler() { return null; } public void setViewHandler(ViewHandler handler) { } public StateManager getStateManager() { return null; } public void setStateManager(StateManager manager) { } public void addComponent(String componentType, String componentClass) { } public UIComponent createComponent(String componentType) throws FacesException { return null; } public UIComponent createComponent(ValueBinding componentBinding, FacesContext context, String componentType) throws FacesException { return null; } public Iterator getComponentTypes() { return null; } public void addConverter(String converterId, String converterClass) { } public void addConverter(Class targetClass, String converterClass) { } public Converter createConverter(String converterId) { return null; } public Converter createConverter(Class targetClass) { return null; } public Iterator getConverterIds() { return null; } public Iterator> getConverterTypes() { return null; } public MethodBinding createMethodBinding(String ref, Class[] params) throws ReferenceSyntaxException { return null; } public Iterator getSupportedLocales() { return null; } public void setSupportedLocales(Collection locales) { } public void addValidator(String validatorId, String validatorClass) { } public Validator createValidator(String validatorId) throws FacesException { return null; } public Iterator getValidatorIds() { return null; } public void addBehavior(String behaviorId, String behaviorClass) { } public Behavior createBehavior(String behaviorId) throws FacesException { return null; } public Iterator getBehaviorIds() { return null; } public ValueBinding createValueBinding(String ref) throws ReferenceSyntaxException { return null; } } // END BasicApplication } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/StoreServletContext.java0000644000000000000000000002246011412443352023732 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import java.io.UnsupportedEncodingException; import javax.servlet.ServletContext; import javax.faces.context.ExternalContext; import java.util.Map; import java.util.Set; import java.util.Locale; import java.util.Iterator; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import com.sun.faces.RIConstants; import com.sun.faces.cactus.TestingUtil; /** *

The purpose of this class is to call the package private * getThreadLocalServletContext() method to set the ServletContext into * ThreadLocalStorage, if IS_UNIT_TEST_MODE == true.

*/ public class StoreServletContext extends Object { ExternalContext ec = null; public void setServletContext(ServletContext sc) { ec = new ServletContextAdapter(sc); ThreadLocal threadLocal = (ThreadLocal) TestingUtil.invokePrivateMethod("getThreadLocalExternalContext", RIConstants.EMPTY_CLASS_ARGS, RIConstants.EMPTY_METH_ARGS, ConfigureListener.class, null); threadLocal.set(new ServletContextAdapter(sc)); } public ExternalContext getServletContextWrapper() { return ec; } public class ServletContextAdapter extends ExternalContext { private ServletContext servletContext = null; private ApplicationMap applicationMap = null; public ServletContextAdapter(ServletContext sc) { this.servletContext = sc; } public void dispatch(String path) throws java.io.IOException { } public String encodeActionURL(String url) { return null; } public String encodeNamespace(String name) { return null; } public String encodePartialActionURL(String viewId) { return null; } public String encodeResourceURL(String url) { return null; } public Map getApplicationMap() { if (applicationMap == null) { applicationMap = new ApplicationMap(servletContext); } return applicationMap; } public String getAuthType() { return null; } public String getMimeType(String file) { return servletContext.getMimeType(file); } public Object getContext() { return servletContext; } public String getContextName() { return servletContext.getServletContextName(); } public String getInitParameter(String name) { return null; } public Map getInitParameterMap() { return null; } public String getRemoteUser() { return null; } public Object getRequest() { return null; } public void setRequest(Object request) {} public String getRequestCharacterEncoding() { return null; } public void setRequestCharacterEncoding(String requestCharacterEncoding) throws UnsupportedEncodingException { } public String getResponseCharacterEncoding() { return null; } public void setResponseCharacterEncoding(String responseCharacterEncoding) { } public void setResponseHeader(String name, String value) { } public void addResponseHeader(String name, String value) { } public String getRequestContextPath() { return null; } public Map getRequestCookieMap() { return null; } public Map getRequestHeaderMap() { return null; } public Map getRequestHeaderValuesMap() { return null; } public Locale getRequestLocale() { return null; } public Iterator getRequestLocales() { return null; } public Map getRequestMap() { return null; } public Map getRequestParameterMap() { return null; } public Iterator getRequestParameterNames() { return null; } public Map getRequestParameterValuesMap() { return null; } public String getRequestPathInfo() { return null; } public String getRequestServletPath() { return null; } public String getRequestContentType() { return null; } public int getRequestContentLength() { return -1; } public String getResponseContentType() { return null; } public java.net.URL getResource(String path) throws java.net.MalformedURLException { return null; } public java.io.InputStream getResourceAsStream(String path) { return null; } public Set getResourcePaths(String path) { return null; } public Object getResponse() { return null; } public void setResponse(Object response) {} public Object getSession(boolean create) { return null; } public Map getSessionMap() { return null; } public java.security.Principal getUserPrincipal() { return null; } public boolean isUserInRole(String role) { return false; } public void log(String message) { } public void log(String message, Throwable exception){ } public void redirect(String url) throws java.io.IOException { } } class ApplicationMap extends java.util.AbstractMap { private ServletContext servletContext = null; ApplicationMap(ServletContext servletContext) { this.servletContext = servletContext; } public Object get(Object key) { if (key == null) { throw new NullPointerException(); } return servletContext.getAttribute(key.toString()); } public Object put(Object key, Object value) { if (key == null) { throw new NullPointerException(); } String keyString = key.toString(); Object result = servletContext.getAttribute(keyString); servletContext.setAttribute(keyString, value); return (result); } public Object remove(Object key) { if (key == null) { return null; } String keyString = key.toString(); Object result = servletContext.getAttribute(keyString); servletContext.removeAttribute(keyString); return (result); } public Set entrySet() { throw new UnsupportedOperationException(); } public boolean equals(Object obj) { if (obj == null || !(obj instanceof ApplicationMap)) return false; return super.equals(obj); } public void clear() { throw new UnsupportedOperationException(); } public void putAll(Map t) { throw new UnsupportedOperationException(); } } // END ApplicationMap } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/ConfigureListenerTestCase.java0000644000000000000000000011761611412443352025017 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.EventListener; import java.util.logging.Filter; import java.util.logging.LogRecord; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.component.UIColumn; import javax.faces.component.UICommand; import javax.faces.component.UIData; import javax.faces.component.UIForm; import javax.faces.component.UIGraphic; import javax.faces.component.UIInput; import javax.faces.component.UIMessage; import javax.faces.component.UIMessages; import javax.faces.component.UINamingContainer; import javax.faces.component.UIOutput; import javax.faces.component.UIPanel; import javax.faces.component.UIParameter; import javax.faces.component.UISelectBoolean; import javax.faces.component.UISelectItem; import javax.faces.component.UISelectItems; import javax.faces.component.UISelectMany; import javax.faces.component.UISelectOne; import javax.faces.component.html.HtmlCommandButton; import javax.faces.component.html.HtmlCommandLink; import javax.faces.component.html.HtmlDataTable; import javax.faces.component.html.HtmlForm; import javax.faces.component.html.HtmlGraphicImage; import javax.faces.component.html.HtmlInputHidden; import javax.faces.component.html.HtmlInputSecret; import javax.faces.component.html.HtmlInputText; import javax.faces.component.html.HtmlInputTextarea; import javax.faces.component.html.HtmlMessage; import javax.faces.component.html.HtmlMessages; import javax.faces.component.html.HtmlOutputFormat; import javax.faces.component.html.HtmlOutputLabel; import javax.faces.component.html.HtmlOutputLink; import javax.faces.component.html.HtmlOutputText; import javax.faces.component.html.HtmlPanelGrid; import javax.faces.component.html.HtmlPanelGroup; import javax.faces.component.html.HtmlSelectBooleanCheckbox; import javax.faces.component.html.HtmlSelectManyCheckbox; import javax.faces.component.html.HtmlSelectManyListbox; import javax.faces.component.html.HtmlSelectManyMenu; import javax.faces.component.html.HtmlSelectOneListbox; import javax.faces.component.html.HtmlSelectOneMenu; import javax.faces.component.html.HtmlSelectOneRadio; import javax.faces.convert.BigDecimalConverter; import javax.faces.convert.BigIntegerConverter; import javax.faces.convert.BooleanConverter; import javax.faces.convert.ByteConverter; import javax.faces.convert.CharacterConverter; import javax.faces.convert.DateTimeConverter; import javax.faces.convert.DoubleConverter; import javax.faces.convert.FloatConverter; import javax.faces.convert.IntegerConverter; import javax.faces.convert.LongConverter; import javax.faces.convert.NumberConverter; import javax.faces.convert.ShortConverter; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import javax.faces.render.Renderer; import javax.faces.validator.DoubleRangeValidator; import javax.faces.validator.LengthValidator; import javax.faces.validator.LongRangeValidator; import javax.faces.webapp.FacesServlet; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.FilterRegistration; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter; import com.sun.faces.application.ApplicationAssociate; import junit.framework.Test; import junit.framework.TestSuite; /** *

Unit tests for ConfigureListener.

*/ public class ConfigureListenerTestCase extends ServletFacesTestCase { // ------------------------------------------------------------ Constructors // Construct a new instance of this test case. public ConfigureListenerTestCase(String name) { super(name); } public ConfigureListenerTestCase() { this("ConfigureListenerTestCase"); } // Return the tests included in this test case. public static Test suite() { return (new TestSuite(ConfigureListenerTestCase.class)); } // ------------------------------------------------- Individual Test Methods // Test a basic environment with no application configuration resources public void testBasic() throws Exception { // Perform tests on the environment checkComponentsGeneric(); checkComponentsHtml(); checkConvertersByClass(); checkConvertersById(); checkRenderers(); checkValidators(); } // Representative sample only private String rendersChildrenFalse[][] = { }; private String rendersChildrenTrue[][] = { {"javax.faces.Command", "javax.faces.Link"}, {"javax.faces.Data", "javax.faces.Table"}, {"javax.faces.Output", "javax.faces.Link"}, {"javax.faces.Panel", "javax.faces.Grid"}, {"javax.faces.Panel", "javax.faces.Group"}, {"javax.faces.Command", "javax.faces.Button"}, {"javax.faces.Form", "javax.faces.Form"} }; // Test some boolean attributes that should have been set explicitly public void testBoolean() throws Exception { RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit rk = rkFactory.getRenderKit(null, RenderKitFactory.HTML_BASIC_RENDER_KIT); // Test for isRendersChildren=false for (int i = 0; i < rendersChildrenFalse.length; i++) { Renderer r = rk.getRenderer(rendersChildrenFalse[i][0], rendersChildrenFalse[i][1]); assertEquals("(" + rendersChildrenFalse[i][0] + "," + rendersChildrenFalse[i][1] + ")", false, r.getRendersChildren()); } // Test for isRendersChildren=true for (int i = 0; i < rendersChildrenTrue.length; i++) { Renderer r = rk.getRenderer(rendersChildrenTrue[i][0], rendersChildrenTrue[i][1]); assertEquals("(" + rendersChildrenTrue[i][0] + "," + rendersChildrenTrue[i][1] + ")", true, r.getRendersChildren()); } } // Test a webapp with a default faces-config.xml resource public void testDefault() throws Exception { // Validate standard configuration checkComponentsGeneric(); checkComponentsHtml(); checkConvertersByClass(); checkConvertersById(); checkRenderers(); checkValidators(); // Validate what was actually configured checkDefaultConfiguration(); checkExtraConfiguration(false); checkEmbedConfiguration(false); } // Test a webapp with a default and extra and embedded resources public void testEmbed() throws Exception { ServletContext ctx = (ServletContext) getFacesContext().getExternalContext().getContext(); ApplicationAssociate.clearInstance(getFacesContext().getExternalContext()); ctx.removeAttribute("com.sun.faces.config.WebConfiguration"); ServletContextWrapper w = new ServletContextWrapper(ctx); ServletContextEvent sce = new ServletContextEvent(w); w.addInitParameter(FacesServlet.CONFIG_FILES_ATTR, "/WEB-INF/embed-config.xml,/WEB-INF/extra-config.xml"); FactoryFinder.releaseFactories(); ConfigureListener listener = new ConfigureListener(); // Initialize the context try { listener.contextInitialized(sce); } catch (FacesException e) { if (e.getCause() != null) { throw (Exception) e.getCause(); } else { throw e; } } // Validate standard configuration checkComponentsGeneric(); checkComponentsHtml(); checkConvertersByClass(); checkConvertersById(); checkRenderers(); checkValidators(); // Validate what was actually configured checkDefaultConfiguration(); checkExtraConfiguration(true); checkEmbedConfiguration(true); // Destroy the context listener.contextDestroyed(sce); } // Test a webapp with a default and extra faces-config.xml resources public void testExtra() throws Exception { ServletContext ctx = (ServletContext) getFacesContext().getExternalContext().getContext(); ApplicationAssociate.clearInstance(getFacesContext().getExternalContext()); ctx.removeAttribute("com.sun.faces.config.WebConfiguration"); ServletContextWrapper w = new ServletContextWrapper(ctx); ServletContextEvent sce = new ServletContextEvent(w); w.addInitParameter(FacesServlet.CONFIG_FILES_ATTR, "/WEB-INF/extra-config.xml"); FactoryFinder.releaseFactories(); ConfigureListener listener = new ConfigureListener(); // Initialize the context try { listener.contextInitialized(sce); } catch (FacesException e) { if (e.getCause() != null) { throw (Exception) e.getCause(); } else { throw e; } } // Validate standard configuration checkComponentsGeneric(); checkComponentsHtml(); checkConvertersByClass(); checkConvertersById(); checkRenderers(); checkValidators(); // Validate what was actually configured checkDefaultConfiguration(); checkExtraConfiguration(true); checkEmbedConfiguration(false); // Destroy the context listener.contextDestroyed(sce); } // --------------------------------------------------------- Support Methods // Check that all of the required generic components have been registered private void checkComponentsGeneric() throws Exception { ApplicationFactory afactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application application = afactory.getApplication(); assertTrue(application.createComponent ("javax.faces.Column") instanceof UIColumn); assertTrue(application.createComponent (UIColumn.COMPONENT_TYPE) instanceof UIColumn); assertTrue(application.createComponent ("javax.faces.Command") instanceof UICommand); assertTrue(application.createComponent (UICommand.COMPONENT_TYPE) instanceof UICommand); assertTrue(application.createComponent ("javax.faces.Data") instanceof UIData); assertTrue(application.createComponent (UIData.COMPONENT_TYPE) instanceof UIData); assertTrue(application.createComponent ("javax.faces.Form") instanceof UIForm); assertTrue(application.createComponent (UIForm.COMPONENT_TYPE) instanceof UIForm); assertTrue(application.createComponent ("javax.faces.Graphic") instanceof UIGraphic); assertTrue(application.createComponent (UIGraphic.COMPONENT_TYPE) instanceof UIGraphic); assertTrue(application.createComponent ("javax.faces.Input") instanceof UIInput); assertTrue(application.createComponent (UIInput.COMPONENT_TYPE) instanceof UIInput); assertTrue(application.createComponent ("javax.faces.Message") instanceof UIMessage); assertTrue(application.createComponent (UIMessage.COMPONENT_TYPE) instanceof UIMessage); assertTrue(application.createComponent ("javax.faces.Messages") instanceof UIMessages); assertTrue(application.createComponent (UIMessages.COMPONENT_TYPE) instanceof UIMessages); assertTrue(application.createComponent ("javax.faces.NamingContainer") instanceof UINamingContainer); assertTrue(application.createComponent (UINamingContainer.COMPONENT_TYPE) instanceof UINamingContainer); assertTrue(application.createComponent ("javax.faces.Output") instanceof UIOutput); assertTrue(application.createComponent (UIOutput.COMPONENT_TYPE) instanceof UIOutput); assertTrue(application.createComponent ("javax.faces.Panel") instanceof UIPanel); assertTrue(application.createComponent (UIPanel.COMPONENT_TYPE) instanceof UIPanel); assertTrue(application.createComponent ("javax.faces.Parameter") instanceof UIParameter); assertTrue(application.createComponent (UIParameter.COMPONENT_TYPE) instanceof UIParameter); assertTrue(application.createComponent ("javax.faces.SelectBoolean") instanceof UISelectBoolean); assertTrue(application.createComponent (UISelectBoolean.COMPONENT_TYPE) instanceof UISelectBoolean); assertTrue(application.createComponent ("javax.faces.SelectItem") instanceof UISelectItem); assertTrue(application.createComponent (UISelectItem.COMPONENT_TYPE) instanceof UISelectItem); assertTrue(application.createComponent ("javax.faces.SelectItems") instanceof UISelectItems); assertTrue(application.createComponent (UISelectItems.COMPONENT_TYPE) instanceof UISelectItems); assertTrue(application.createComponent ("javax.faces.SelectMany") instanceof UISelectMany); assertTrue(application.createComponent (UISelectMany.COMPONENT_TYPE) instanceof UISelectMany); assertTrue(application.createComponent ("javax.faces.SelectOne") instanceof UISelectOne); assertTrue(application.createComponent (UISelectOne.COMPONENT_TYPE) instanceof UISelectOne); } // Check that all of the required HTML components have been registered private void checkComponentsHtml() throws Exception { ApplicationFactory afactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application application = afactory.getApplication(); assertTrue(application.createComponent ("javax.faces.HtmlCommandButton") instanceof HtmlCommandButton); assertTrue(application.createComponent ("javax.faces.HtmlCommandLink") instanceof HtmlCommandLink); assertTrue(application.createComponent ("javax.faces.HtmlDataTable") instanceof HtmlDataTable); assertTrue(application.createComponent ("javax.faces.HtmlForm") instanceof HtmlForm); assertTrue(application.createComponent ("javax.faces.HtmlGraphicImage") instanceof HtmlGraphicImage); assertTrue(application.createComponent ("javax.faces.HtmlInputHidden") instanceof HtmlInputHidden); assertTrue(application.createComponent ("javax.faces.HtmlInputSecret") instanceof HtmlInputSecret); assertTrue(application.createComponent ("javax.faces.HtmlInputText") instanceof HtmlInputText); assertTrue(application.createComponent ("javax.faces.HtmlInputTextarea") instanceof HtmlInputTextarea); assertTrue(application.createComponent ("javax.faces.HtmlMessage") instanceof HtmlMessage); assertTrue(application.createComponent ("javax.faces.HtmlMessages") instanceof HtmlMessages); assertTrue(application.createComponent ("javax.faces.HtmlOutputFormat") instanceof HtmlOutputFormat); assertTrue(application.createComponent ("javax.faces.HtmlOutputLabel") instanceof HtmlOutputLabel); assertTrue(application.createComponent ("javax.faces.HtmlOutputLink") instanceof HtmlOutputLink); assertTrue(application.createComponent ("javax.faces.HtmlOutputText") instanceof HtmlOutputText); assertTrue(application.createComponent ("javax.faces.HtmlPanelGrid") instanceof HtmlPanelGrid); assertTrue(application.createComponent ("javax.faces.HtmlPanelGroup") instanceof HtmlPanelGroup); assertTrue( application.createComponent ("javax.faces.HtmlSelectBooleanCheckbox") instanceof HtmlSelectBooleanCheckbox); assertTrue( application.createComponent ("javax.faces.HtmlSelectManyCheckbox") instanceof HtmlSelectManyCheckbox); assertTrue( application.createComponent ("javax.faces.HtmlSelectManyListbox") instanceof HtmlSelectManyListbox); assertTrue( application.createComponent ("javax.faces.HtmlSelectManyMenu") instanceof HtmlSelectManyMenu); assertTrue( application.createComponent ("javax.faces.HtmlSelectOneListbox") instanceof HtmlSelectOneListbox); assertTrue(application.createComponent ("javax.faces.HtmlSelectOneMenu") instanceof HtmlSelectOneMenu); assertTrue( application.createComponent ("javax.faces.HtmlSelectOneRadio") instanceof HtmlSelectOneRadio); } // Check that all required by-class Converters have been registered private void checkConvertersByClass() throws Exception { ApplicationFactory afactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application application = afactory.getApplication(); assertTrue(application.createConverter (BigDecimal.class) instanceof BigDecimalConverter); assertTrue(application.createConverter (BigInteger.class) instanceof BigIntegerConverter); assertTrue(application.createConverter (Boolean.class) instanceof BooleanConverter); assertTrue(application.createConverter (Byte.class) instanceof ByteConverter); assertTrue(application.createConverter (Character.class) instanceof CharacterConverter); assertTrue(application.createConverter (Double.class) instanceof DoubleConverter); assertTrue(application.createConverter (Float.class) instanceof FloatConverter); assertTrue(application.createConverter (Integer.class) instanceof IntegerConverter); assertTrue(application.createConverter (Long.class) instanceof LongConverter); assertTrue(application.createConverter (Short.class) instanceof ShortConverter); } // Check that all required by-id Converters have been registered private void checkConvertersById() throws Exception { ApplicationFactory afactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application application = afactory.getApplication(); assertTrue(application.createConverter ("javax.faces.BigDecimal") instanceof BigDecimalConverter); assertTrue(application.createConverter ("javax.faces.BigInteger") instanceof BigIntegerConverter); assertTrue(application.createConverter ("javax.faces.Boolean") instanceof BooleanConverter); assertTrue(application.createConverter ("javax.faces.Byte") instanceof ByteConverter); assertTrue(application.createConverter ("javax.faces.Character") instanceof CharacterConverter); assertTrue(application.createConverter ("javax.faces.DateTime") instanceof DateTimeConverter); assertTrue(application.createConverter ("javax.faces.Double") instanceof DoubleConverter); assertTrue(application.createConverter ("javax.faces.Float") instanceof FloatConverter); assertTrue(application.createConverter ("javax.faces.Integer") instanceof IntegerConverter); assertTrue(application.createConverter ("javax.faces.Long") instanceof LongConverter); assertTrue(application.createConverter ("javax.faces.Number") instanceof NumberConverter); assertTrue(application.createConverter ("javax.faces.Short") instanceof ShortConverter); } // Check that the default configuration took place private void checkDefaultConfiguration() throws Exception { ApplicationFactory afactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application application = afactory.getApplication(); RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit rk = rkFactory.getRenderKit(null, RenderKitFactory.HTML_BASIC_RENDER_KIT); assertTrue(application.createComponent ("DefaultComponent") instanceof TestComponent); assertTrue(application.createConverter ("DefaultConverter") instanceof TestConverter); assertTrue(application.createValidator ("DefaultValidator") instanceof TestValidator); assertNotNull(rk.getRenderer("Test", "DefaultRenderer")); } // Check whether embed configuration occurred or did not occur private void checkEmbedConfiguration(boolean should) throws Exception { ApplicationFactory afactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application application = afactory.getApplication(); RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit rk = rkFactory.getRenderKit(null, RenderKitFactory.HTML_BASIC_RENDER_KIT); if (should) { assertTrue(application.createComponent ("EmbedComponent") instanceof TestComponent); assertTrue(application.createConverter ("EmbedConverter") instanceof TestConverter); assertTrue(application.createValidator ("EmbedValidator") instanceof TestValidator); assertNotNull(rk.getRenderer("Test", "EmbedRenderer")); } else { try { application.createComponent("EmbedComponent"); fail("Should have thrown FacesException"); } catch (FacesException e) { ; // Expected result } try { application.createConverter("EmbedConverter"); fail("Should have thrown FacesException"); } catch (FacesException e) { ; // Expected result } try { application.createValidator("EmbedValidator"); fail("Should have thrown FacesException"); } catch (FacesException e) { ; // Expected result } assertNull(rk.getRenderer("Test", "EmbedRenderer")); } } // Check whether extra configuration occurred or did not occur private void checkExtraConfiguration(boolean should) throws Exception { ApplicationFactory afactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application application = afactory.getApplication(); RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit rk = rkFactory.getRenderKit(null, RenderKitFactory.HTML_BASIC_RENDER_KIT); if (should) { assertTrue(application.createComponent ("ExtraComponent") instanceof TestComponent); assertTrue(application.createConverter ("ExtraConverter") instanceof TestConverter); assertTrue(application.createValidator ("ExtraValidator") instanceof TestValidator); assertNotNull(rk.getRenderer("Test", "ExtraRenderer")); } else { try { application.createComponent("ExtraComponent"); fail("Should have thrown FacesException"); } catch (FacesException e) { ; // Expected result } try { application.createConverter("ExtraConverter"); fail("Should have thrown FacesException"); } catch (FacesException e) { ; // Expected result } try { application.createValidator("ExtraValidator"); fail("Should have thrown FacesException"); } catch (FacesException e) { ; // Expected result } assertNull(rk.getRenderer("Test", "ExtraRenderer")); } } // Check that all required Renderers have been registered private void checkRenderers() throws Exception { RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit rk = rkFactory.getRenderKit(null, RenderKitFactory.HTML_BASIC_RENDER_KIT); assertNotNull( rk.getRenderer("javax.faces.Command", "javax.faces.Button")); assertNotNull( rk.getRenderer("javax.faces.Command", "javax.faces.Link")); assertNotNull(rk.getRenderer("javax.faces.Data", "javax.faces.Table")); assertNotNull(rk.getRenderer("javax.faces.Form", "javax.faces.Form")); assertNotNull( rk.getRenderer("javax.faces.Graphic", "javax.faces.Image")); assertNotNull( rk.getRenderer("javax.faces.Input", "javax.faces.Hidden")); assertNotNull( rk.getRenderer("javax.faces.Input", "javax.faces.Secret")); assertNotNull(rk.getRenderer("javax.faces.Input", "javax.faces.Text")); assertNotNull( rk.getRenderer("javax.faces.Input", "javax.faces.Textarea")); assertNotNull( rk.getRenderer("javax.faces.Message", "javax.faces.Message")); assertNotNull( rk.getRenderer("javax.faces.Messages", "javax.faces.Messages")); assertNotNull( rk.getRenderer("javax.faces.Output", "javax.faces.Format")); assertNotNull( rk.getRenderer("javax.faces.Output", "javax.faces.Label")); assertNotNull(rk.getRenderer("javax.faces.Output", "javax.faces.Link")); assertNotNull(rk.getRenderer("javax.faces.Output", "javax.faces.Text")); assertNotNull(rk.getRenderer("javax.faces.Panel", "javax.faces.Grid")); assertNotNull(rk.getRenderer("javax.faces.Panel", "javax.faces.Group")); assertNotNull( rk.getRenderer("javax.faces.SelectBoolean", "javax.faces.Checkbox")); assertNotNull( rk.getRenderer("javax.faces.SelectMany", "javax.faces.Checkbox")); assertNotNull( rk.getRenderer("javax.faces.SelectMany", "javax.faces.Listbox")); assertNotNull( rk.getRenderer("javax.faces.SelectMany", "javax.faces.Menu")); assertNotNull( rk.getRenderer("javax.faces.SelectOne", "javax.faces.Listbox")); assertNotNull( rk.getRenderer("javax.faces.SelectOne", "javax.faces.Menu")); assertNotNull( rk.getRenderer("javax.faces.SelectOne", "javax.faces.Radio")); } // Check that all required Validators have been registered private void checkValidators() throws Exception { ApplicationFactory afactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); Application application = afactory.getApplication(); assertTrue(application.createValidator ("javax.faces.DoubleRange") instanceof DoubleRangeValidator); assertTrue(application.createValidator ("javax.faces.Length") instanceof LengthValidator); assertTrue(application.createValidator ("javax.faces.LongRange") instanceof LongRangeValidator); } // Tests if a particular reset message got logged // See testLogOverriddenContextConfigValues private static class GotMessageFilter implements Filter { private boolean gotLogMessage = false; public boolean isLoggable(LogRecord record) { if (record.getMessage().equals("jsf.config.webconfig.configinfo.reset.enabled") && record.getParameters()[1].equals(BooleanWebContextInitParameter.ValidateFacesConfigFiles.getQualifiedName())) { gotLogMessage = true; } return true; } public boolean gotLogMessage() { return gotLogMessage; } } // ---------------------------------------------------------- Nested Classes private static final class ServletContextWrapper implements ServletContext { private ServletContext delegate; private Map initParameters; ServletContextWrapper(ServletContext delegate) { this.delegate = delegate; } void addInitParameter(String name, String value) { if (initParameters == null) { initParameters = new HashMap(); } initParameters.put(name, value); } public String getContextPath() { return delegate.getContextPath(); } public ServletContext getContext(String s) { return delegate.getContext(s); } public int getMajorVersion() { return delegate.getMajorVersion(); } public int getMinorVersion() { return delegate.getMinorVersion(); } public String getMimeType(String s) { return delegate.getMimeType(s); } public Set getResourcePaths(String s) { return delegate.getResourcePaths(s); } public URL getResource(String s) throws MalformedURLException { return delegate.getResource(s); } public InputStream getResourceAsStream(String s) { return delegate.getResourceAsStream(s); } public RequestDispatcher getRequestDispatcher(String s) { return delegate.getRequestDispatcher(s); } public RequestDispatcher getNamedDispatcher(String s) { return delegate.getNamedDispatcher(s); } public Servlet getServlet(String s) throws ServletException { return delegate.getServlet(s); } public Enumeration getServlets() { return delegate.getServlets(); } public Enumeration getServletNames() { return getServletNames(); } public void log(String s) { delegate.log(s); } public void log(Exception e, String s) { delegate.log(e, s); } public void log(String s, Throwable throwable) { delegate.log(s, throwable); } public String getRealPath(String s) { return delegate.getRealPath(s); } public String getServerInfo() { return delegate.getServerInfo(); } public String getInitParameter(String s) { String v = null; if (initParameters != null) { v = initParameters.get(s); } if (v == null) { v = delegate.getInitParameter(s); } return v; } public Enumeration getInitParameterNames() { Vector v = new Vector(); if (initParameters != null) { for (String key : initParameters.keySet()) { v.add(key); } } for (Enumeration e = delegate.getInitParameterNames(); e.hasMoreElements(); ) { v.add((String) e.nextElement()); } return v.elements(); } public Object getAttribute(String s) { return delegate.getAttribute(s); } public Enumeration getAttributeNames() { return delegate.getAttributeNames(); } public void setAttribute(String s, Object o) { delegate.setAttribute(s, o); } public void removeAttribute(String s) { delegate.removeAttribute(s); } public String getServletContextName() { return delegate.getServletContextName(); } public int getEffectiveMajorVersion() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int getEffectiveMinorVersion() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean setInitParameter(String s, String s1) { return false; //To change body of implemented methods use File | Settings | File Templates. } public ServletRegistration.Dynamic addServlet(String s, String s1) { return null; //To change body of implemented methods use File | Settings | File Templates. } public ServletRegistration.Dynamic addServlet(String s, Servlet servlet) { return null; //To change body of implemented methods use File | Settings | File Templates. } public ServletRegistration.Dynamic addServlet(String s, Class aClass) { return null; //To change body of implemented methods use File | Settings | File Templates. } public T createServlet(Class tClass) throws ServletException { return null; //To change body of implemented methods use File | Settings | File Templates. } public ServletRegistration getServletRegistration(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } public Map getServletRegistrations() { return null; //To change body of implemented methods use File | Settings | File Templates. } public FilterRegistration.Dynamic addFilter(String s, String s1) { return null; //To change body of implemented methods use File | Settings | File Templates. } public FilterRegistration.Dynamic addFilter(String s, javax.servlet.Filter filter) { return null; //To change body of implemented methods use File | Settings | File Templates. } public FilterRegistration.Dynamic addFilter(String s, Class aClass) { return null; //To change body of implemented methods use File | Settings | File Templates. } public T createFilter(Class tClass) throws ServletException { return null; //To change body of implemented methods use File | Settings | File Templates. } public FilterRegistration getFilterRegistration(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } public Map getFilterRegistrations() { return null; //To change body of implemented methods use File | Settings | File Templates. } public SessionCookieConfig getSessionCookieConfig() { return null; //To change body of implemented methods use File | Settings | File Templates. } public void setSessionTrackingModes(Set sessionTrackingModes) { //To change body of implemented methods use File | Settings | File Templates. } public Set getDefaultSessionTrackingModes() { return null; //To change body of implemented methods use File | Settings | File Templates. } public Set getEffectiveSessionTrackingModes() { return null; //To change body of implemented methods use File | Settings | File Templates. } public void addListener(String s) { //To change body of implemented methods use File | Settings | File Templates. } public void addListener(T t) { //To change body of implemented methods use File | Settings | File Templates. } public void addListener(Class aClass) { //To change body of implemented methods use File | Settings | File Templates. } public T createListener(Class tClass) throws ServletException { return null; //To change body of implemented methods use File | Settings | File Templates. } public JspConfigDescriptor getJspConfigDescriptor() { return null; //To change body of implemented methods use File | Settings | File Templates. } public ClassLoader getClassLoader() { return null; //To change body of implemented methods use File | Settings | File Templates. } public void declareRoles(String... strings) { //To change body of implemented methods use File | Settings | File Templates. } } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/TestConfigListener.java0000644000000000000000000000623611412443352023502 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import com.sun.faces.cactus.ServletFacesTestCase; import org.apache.cactus.ServletTestCase; import javax.servlet.ServletContextEvent; /** *

Unit tests for Configuration File processing.

*/ public class TestConfigListener extends ServletFacesTestCase { // ----------------------------------------------------- Instance Variables // ----------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public TestConfigListener(String name) { super(name); } // --------------------------------------------------- Overall Test Methods // ------------------------------------------------ Individual Test Methods // this method manually invokes the ContextListener contextInitialized method // multiple times to ensure the parsing logic only gets executed once // (for the same webapp). // public void testContextInitialized() { ConfigureListener cl = new ConfigureListener(); ServletContextEvent e = new ServletContextEvent( getConfig().getServletContext()); cl.contextInitialized(e); cl.contextInitialized(e); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/SimpleBean.java0000644000000000000000000000626011412443352021743 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; public class SimpleBean { private String simpleProperty; public SimpleBean() { } public String getSimpleProperty() { return simpleProperty; } public void setSimpleProperty(String simpleProperty) { this.simpleProperty = simpleProperty; } Integer intProp = null; public void setIntProperty(Integer newVal) { intProp = newVal; } public Integer getIntProperty() { return intProp; } public boolean getTrueValue() { return true; } public boolean getFalseValue() { return false; } private NonManagedBean nonManagedBean = null; public NonManagedBean getNonManagedBean() { return nonManagedBean; } public void setNonManagedBean(NonManagedBean nmb) { nonManagedBean = nmb; } private String headerClass = "column-header"; public String getHeaderClass() { return headerClass; } public void setHeaderClass(String headerClass) { this.headerClass = headerClass; } private String footerClass = "column-footer"; public String getFooterClass() { return footerClass; } public void setFooterClass(String footerClass) { this.footerClass = footerClass; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/TestManagedBeanFactory.java0000644000000000000000000013003411412443352024233 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.cactus.TestingUtil; import com.sun.faces.TestBean; import com.sun.faces.application.ApplicationAssociate; import com.sun.faces.mgbean.ManagedBeanInfo; import com.sun.faces.mgbean.BeanManager; import com.sun.faces.mgbean.BeanBuilder; import com.sun.faces.el.ELUtils; import javax.el.ValueExpression; import javax.faces.FacesException; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** *

Unit tests for Managed Bean Factory.

*/ public class TestManagedBeanFactory extends ServletFacesTestCase { public static String beanName = "com.sun.faces.TestBean"; // ----------------------------------------------------- Instance Variables TestBean testBean; // ----------------------------------------------------------- Constructors /** * Construct a new instance of this test case. */ public TestManagedBeanFactory() { super("TestManagedBeanFactory"); } /** * Construct a new instance of this test case. * * @param name Name of the test case */ public TestManagedBeanFactory(String name) { super(name); } // --------------------------------------------------- Overall Test Methods // ------------------------------------------------ Individual Test Methods // Test managed bean public void testNoProperty() throws Exception { //Testing with no properties set ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "session", null, null, null, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); assertNotNull(beanManager.create(beanName, getFacesContext())); BeanBuilder builder = beanManager.getBuilder(beanName); assertTrue(ELUtils.Scope.SESSION.toString().equals(builder.getScope())); } public void testSimpleProperty() throws Exception { ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("one", null, "one", null, null); List list = new ArrayList(1); list.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "session", null, null, list, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); //make sure bean instantiated properly. Get property back from bean. assertTrue(testBean.getOne().equals("one")); //make sure scope is stored properly BeanBuilder builder = beanManager.getBuilder(beanName); assertTrue(ELUtils.Scope.SESSION.toString().equals(builder.getScope())); } public void testPrimitiveProperty() throws Exception { List list = new ArrayList(1); boolean testBoolean = true; ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("boolProp", null, Boolean.toString(testBoolean), null, null); list.add(property); byte testByte = 100; property = new ManagedBeanInfo.ManagedProperty("byteProp", null, Byte.valueOf(testByte).toString(), null, null); list.add(property); char testChar = 'z'; property = new ManagedBeanInfo.ManagedProperty("charProp", null, Character.valueOf(testChar).toString(), null, null); list.add(property); double testDouble = 11.278D; property = new ManagedBeanInfo.ManagedProperty("doubleProp", null, Double.valueOf(testDouble).toString(), null, null); list.add(property); float testFloat = 45.789F; property = new ManagedBeanInfo.ManagedProperty("floatProp", null, Float.valueOf(testFloat).toString(), null, null); list.add(property); int testInt = 42; property = new ManagedBeanInfo.ManagedProperty("intProp", null, Integer.valueOf(testInt).toString(), null, null); list.add(property); long testLong = 3147893289L; property = new ManagedBeanInfo.ManagedProperty("longProp", null, Long.valueOf(testLong).toString(), null, null); list.add(property); short testShort = 25432; property = new ManagedBeanInfo.ManagedProperty("shortProp", null, Short.valueOf(testShort).toString(), null, null); list.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "session", null, null, list, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); //make sure bean instantiated properly. Get property back from bean. assertTrue(testBean.getBoolProp() == testBoolean); assertTrue(testBean.getByteProp() == testByte); assertTrue(testBean.getCharProp() == testChar); assertTrue(testBean.getDoubleProp() == testDouble); assertTrue(testBean.getFloatProp() == testFloat); assertTrue(testBean.getIntProp() == testInt); assertTrue(testBean.getLongProp() == testLong); assertTrue(testBean.getShortProp() == testShort); //make sure scope is stored properly BeanBuilder builder = beanManager.getBuilder(beanName); assertTrue(ELUtils.Scope.SESSION.toString().equals(builder.getScope())); } public void testSimpleNumericProperty() throws Exception { // If a property value is "" ensure numeric properties // are set to 0. List list = new ArrayList(1); boolean testBoolean = true; ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("boolProp", null, Boolean.toString(testBoolean), null, null); list.add(property); property = new ManagedBeanInfo.ManagedProperty("byteProp", null, "", null, null); list.add(property); property = new ManagedBeanInfo.ManagedProperty("charProp", null, "", null, null); list.add(property); property = new ManagedBeanInfo.ManagedProperty("doubleProp", null, "", null, null); list.add(property); property = new ManagedBeanInfo.ManagedProperty("floatProp", null, "", null, null); list.add(property); property = new ManagedBeanInfo.ManagedProperty("intProp", null, "", null, null); list.add(property); property = new ManagedBeanInfo.ManagedProperty("longProp", null, "", null, null); list.add(property); property = new ManagedBeanInfo.ManagedProperty("shortProp", null, "", null, null); list.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "session", null, null, list, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); assertTrue(testBean.getByteProp() == 0); assertTrue(testBean.getCharProp() == 0); assertTrue(testBean.getDoubleProp() == 0); assertTrue(testBean.getFloatProp() == 0); assertTrue(testBean.getIntProp() == 0); assertTrue(testBean.getLongProp() == 0); assertTrue(testBean.getShortProp() == 0); } public void testIndexProperty() throws Exception { List values = new ArrayList(2); values.add("foo"); values.add("bar"); ManagedBeanInfo.ListEntry listEntry = new ManagedBeanInfo.ListEntry(null, values); List properties = new ArrayList(2); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("indexProperties", null, null, null, listEntry); properties.add(property); property = new ManagedBeanInfo.ManagedProperty("indexPropertiesNull", null, null, null, listEntry); properties.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "request", null, null, properties, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); //make sure bean instantiated properly. Get property back from bean. ArrayList props = (ArrayList) testBean.getIndexProperties(); assertTrue(props.get(5).equals("foo")); assertTrue(props.get(6).equals("bar")); // setter shouldn't be called if bean getter returns List assertTrue(!testBean.getListSetterCalled()); // setter should be called if bean getter returned null assertTrue(testBean.getListNullSetterCalled()); //make sure scope is stored properly BeanBuilder builder = beanManager.getBuilder(beanName); assertTrue(ELUtils.Scope.REQUEST.toString().equals(builder.getScope())); } public void testMapProperty() throws Exception { Map entry = new HashMap(1, 1.0f); entry.put("name", "Justyna"); ManagedBeanInfo.MapEntry mapEntry = new ManagedBeanInfo.MapEntry(null, null, entry); List properties = new ArrayList(2); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("mapProperty", null, null, mapEntry, null); properties.add(property); property = new ManagedBeanInfo.ManagedProperty("mapPropertyNull", null, null, mapEntry, null); properties.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "request", null, null, properties, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); //make sure bean instantiated properly. Get property back from bean. HashMap mapProperty = (HashMap) testBean.getMapProperty(); assertTrue(((String) mapProperty.get("name")).equals("Justyna")); // setter shouldn't be called if bean getter returns Map assertTrue(!testBean.getMapPropertySetterCalled()); // setter should be called if bean getter returned null assertTrue(testBean.getMapPropertyNullSetterCalled()); //make sure scope is stored properly BeanBuilder builder = beanManager.getBuilder(beanName); assertTrue(ELUtils.Scope.REQUEST.toString().equals(builder.getScope())); } public void testIndexTypeProperty() throws Exception { List val = new ArrayList(1); val.add("23"); ManagedBeanInfo.ListEntry listEntry = new ManagedBeanInfo.ListEntry("java.lang.Integer", val); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("indexIntegerProperties", "java.lang.Integer", null, null, listEntry); List list = new ArrayList(1); list.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "session", null, null, list, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); //make sure bean instantiated properly. Get property back from bean. ArrayList properties = (ArrayList) testBean.getIndexIntegerProperties(); assertTrue(properties.get(1) instanceof Integer); Integer integer = new Integer("23"); assertTrue(properties.get(2).equals(integer)); } public void testMapTypeProperty() throws Exception { Map entry = new HashMap(1, 1.0f); entry.put("name", "23"); ManagedBeanInfo.MapEntry mapEntry = new ManagedBeanInfo.MapEntry("java.lang.String", "java.lang.Integer", entry); List properties = new ArrayList(1); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("mapProperty", null, null, mapEntry, null); properties.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "request", null, null, properties, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); //make sure bean instantiated properly. Get property back from bean. HashMap mapProperty = (HashMap) testBean.getMapProperty(); assertTrue(mapProperty.get("name") instanceof Integer); Integer integer = new Integer("23"); assertTrue(mapProperty.get("name").equals(integer)); } public void testValueRefProperty() throws Exception { TestBean testBean = new TestBean(); testBean.setOne("one"); getFacesContext().getExternalContext().getSessionMap().put( "TestRefBean", testBean); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("one", null, "#{TestRefBean.one}", null, null); List list = new ArrayList(1); list.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "session", null, null, list, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); //make sure bean instantiated properly. Get property back from bean. assertTrue(testBean.getOne().equals("one")); } public void testValueRefScope() throws Exception { //Testing value ref scope TestBean testBean = new TestBean(); testBean.setOne("one"); boolean exceptionThrown = false; //testing with: // valueref in application scope // managed bean in session scope getFacesContext().getExternalContext().getApplicationMap().put( "TestRefBean", testBean); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("one", null, "#{TestRefBean.one}", null, null); List list = new ArrayList(1); list.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "session", null, null, list, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); //testing with a property set assertNotNull(testBean = (TestBean) beanManager.create(beanName, getFacesContext())); //make sure bean instantiated properly. Get property back from bean. assertTrue(testBean.getOne().equals("one")); //testing with: // valueref in request scope // managed bean in application scope getFacesContext().getExternalContext().getApplicationMap() .remove("TestRefBean"); getFacesContext().getExternalContext().getRequestMap().put( "TestRefBean", testBean); bean = new ManagedBeanInfo(beanName, beanName, "application", null, null, list, null); beanManager.register(bean); exceptionThrown = false; try { //testing with a property set beanManager.create(beanName, getFacesContext()); fail("Should have thrown FacesException"); } catch (FacesException ex) { exceptionThrown = true; } assertTrue(exceptionThrown); //cleanup getFacesContext().getExternalContext().getRequestMap().remove( "TestRefBean"); //testing with: // valueref in session scope // managed bean in no scope getFacesContext().getExternalContext().getSessionMap().put( "TestRefBean", testBean); bean = new ManagedBeanInfo(beanName, beanName, "none", null, null, list, null); beanManager.register(bean); exceptionThrown = false; try { beanManager.create(beanName, getFacesContext()); fail("Should have thrown FacesException"); } catch (FacesException ex) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testViewScope() throws Exception { TestBean testBean = new TestBean(); testBean.setOne("one"); getFacesContext().getExternalContext().getRequestMap().put("TestRefBean", testBean); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("one", null, "#{TestRefBean.one}", null, null); List list = new ArrayList(1); list.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "view", null, null, list, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); try { // request scope is shorter than view scope, so creation should fail beanManager.create(beanName, getFacesContext()); assertTrue(false); } catch (Exception ignored) { } bean = new ManagedBeanInfo(beanName, beanName, "view", null, null, null, null); beanManager.getRegisteredBeans().remove(beanName); beanManager.register(bean); Object beanObject = beanManager.create(beanName, getFacesContext()); assertNotNull(beanObject); assertTrue(getFacesContext().getViewRoot().getViewMap().containsKey(beanName)); } public void testNoneScope() throws Exception { //Testing value ref scope TestBean testBean = new TestBean(); testBean.setOne("one"); boolean exceptionThrown = false; // valueref in request scope // managed bean in none scope // this should fail getFacesContext().getExternalContext().getRequestMap().put( "TestRefBean", testBean); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("one", null, "#{TestRefBean.one}", null, null); List list = new ArrayList(1); list.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "none", null, null, list, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); exceptionThrown = false; try { beanManager.create(beanName, getFacesContext()); fail("Should have thrown FacesException"); } catch (FacesException ex) { exceptionThrown = true; } assertTrue(exceptionThrown); //cleanup getFacesContext().getExternalContext().getRequestMap().remove( "TestRefBean"); // valueref in none scope // managed bean in none scope // this should pass ValueExpression valueExpression1 = ELUtils.createValueExpression("#{testBean.customerBean.name}"); exceptionThrown = false; try { valueExpression1.getValue(getFacesContext().getELContext()); } catch (FacesException ex) { exceptionThrown = true; } assertTrue(!exceptionThrown); } public void testMixedBean() throws Exception { ValueExpression vb = ELUtils.createValueExpression( "#{mixedBean}"); TestBean bean = (TestBean) vb.getValue(getFacesContext().getELContext()); assertEquals("mixed value Bobby \" \\ \\\" Orr", bean.getProp()); vb = ELUtils.createValueExpression( "#{mixedBean.prop}"); assertEquals(bean.getProp(), (String) vb.getValue(getFacesContext().getELContext())); } public void testMixedBeanNegative() throws Exception { ValueExpression vb = ELUtils.createValueExpression( "#{threeBeanSaladNegative}"); boolean exceptionThrown = false; try { TestBean bean = (TestBean) vb.getValue(getFacesContext().getELContext()); assertTrue(false); } catch (FacesException pnfe) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testMixedBeanPositive() throws Exception { ValueExpression vb = ELUtils.createValueExpression( "#{threeBeanSaladPositive}"); TestBean bean = (TestBean) vb.getValue(getFacesContext().getELContext()); assertEquals("request request session session none none", bean.getProp()); vb = ELUtils.createValueExpression( "#{threeBeanSaladPositive.prop}"); assertEquals(bean.getProp(), (String) vb.getValue(getFacesContext().getELContext())); } public void testConstructorException() { // constructor of this bean throws ann exception. Make sure the // exception is not swallowed. ValueExpression valueExpression1 = ELUtils.createValueExpression("#{exceptionBean.one}"); boolean exceptionThrown = false; try { valueExpression1.getValue(getFacesContext().getELContext()); } catch (FacesException ex) { Throwable t = ex.getCause(); exceptionThrown = true; assertTrue((t.getMessage(). indexOf("TestConstructorException Passed")) != -1); } assertTrue(exceptionThrown); } public void testIsInjectable() throws Exception { ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "session", null, null, null, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); BeanBuilder builder = beanManager.getBuilder(beanName); Boolean isInjectable = (Boolean) TestingUtil.invokePrivateMethod("scanForAnnotations", new Class[] { Class.class }, new Object[] { TestBean.class }, BeanBuilder.class, builder); assertTrue(!isInjectable); bean = new ManagedBeanInfo(beanName, "com.sun.faces.config.TestManagedBeanFactory$InjectionBean", "request", null, null, null, null); beanManager.register(bean); isInjectable = (Boolean) TestingUtil.invokePrivateMethod("scanForAnnotations", new Class[] { Class.class }, new Object[] { InjectionBean.class }, BeanBuilder.class, builder); assertTrue(isInjectable); } public void testViewScopeAnnotationCallBacks() throws Exception { BeanManager beanManager = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()).getBeanManager(); ManagedBeanInfo bean = new ManagedBeanInfo("viewBean", "com.sun.faces.config.TestManagedBeanFactory$InjectionBean", "view", null, null, null, null); beanManager.register(bean); InjectionBean injectionBean = (InjectionBean) beanManager.create("viewBean", getFacesContext()); assertTrue(injectionBean.initCalled); getFacesContext().getViewRoot().getViewMap().clear(); assertTrue(injectionBean.destroyCalled); } /** * For Issue 761. */ public void testManagedPropertyMixedVERegresssion() throws Exception { Map requestMap = getFacesContext().getExternalContext().getRequestMap(); requestMap.put("val", "String"); List properties = new ArrayList(1); ManagedBeanInfo.ManagedProperty property = new ManagedBeanInfo.ManagedProperty("modelLabel", null, "#{'this'} is a String", null, null); properties.add(property); ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "request", null, null, properties, null); BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); beanManager.register(bean); testBean = (TestBean) beanManager.create(beanName, getFacesContext()); assertTrue("this is a String", "this is a String".equals(testBean.getModelLabel())); } public void testManagedBeanCustomScope() throws Exception { BeanManager beanManager = ApplicationAssociate.getCurrentInstance().getBeanManager(); testBean = (TestBean) beanManager.create("customScopeBean", getFacesContext()); Map requestMap = getFacesContext().getExternalContext().getRequestMap(); assertTrue(testBean == requestMap.get("customScopeBean")); // invalid scope sanity check ManagedBeanInfo bean = new ManagedBeanInfo(beanName, beanName, "#{myScope", null, null, null, null); beanManager.register(bean); try { beanManager.create(beanName, getFacesContext()); fail(); } catch (Exception e) { } bean = new ManagedBeanInfo(beanName, beanName, "myScope", null, null, null, null); beanManager.register(bean); try { beanManager.create(beanName, getFacesContext()); fail(); } catch (Exception e) { } } /************* PENDING(edburns): rewrite to exercise new edge case * detection. public void testInvalidPropertyConfiguration() throws Exception { // If a ConfigManagedPropertyValue has a value that requires // converstion from String (the default type) to another type, // say Integer as an example, and the CMPV's value category // isn't set to Value, conversion will not take place. Thus, an // error should occur when creating a new instanced of the // managed bean. // no value category set bean = new ManagedBeanBean(); bean.setManagedBeanClass(beanName); bean.setManagedBeanScope("session"); boolean testBoolean = true; property = new ManagedPropertyBean(); property.setPropertyName("boolProp"); propertyv = new ConfigManagedBeanPropertyValue(); propertyv.setValue((new Boolean(testBoolean)).toString()); property.setValue(propertyv); bean.addManagedProperty(property); mbf = new ManagedBeanFactory(bean); boolean exceptionThrown = false; try { mbf.newInstance(); } catch (FacesException fe) { exceptionThrown = true; } assertTrue(exceptionThrown); // value category set to VALUE_BINDING bean = new ManagedBeanBean(); bean.setManagedBeanClass(beanName); bean.setManagedBeanScope("session"); property = new ManagedPropertyBean(); property.setPropertyName("boolProp"); propertyv = new ConfigManagedBeanPropertyValue(); propertyv.setValueCategory(ConfigManagedBeanPropertyValue.VALUE_BINDING); propertyv.setValue((new Boolean(testBoolean)).toString()); property.setValue(propertyv); bean.addManagedProperty(property); mbf = new ManagedBeanFactory(bean); exceptionThrown = false; try { mbf.newInstance(); } catch (FacesException fe) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testExceptions() throws Exception { bean = new ManagedBeanBean(); bean.setManagedBeanClass("foo"); bean.setManagedBeanScope("session"); property = new ManagedPropertyBean(); property.setPropertyName("one"); propertyv = new ConfigManagedBeanPropertyValue(); propertyv.setValue("one"); property.setValue(propertyv); boolean exceptionThrown = false; try { bean.addManagedProperty(property); } catch (FacesException fe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { property = null; bean.addManagedProperty(property); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); } ***********/ public static class InjectionBean { private boolean initCalled; private boolean destroyCalled; @PostConstruct void init() { initCalled = true; } @PreDestroy void destroy() { destroyCalled = true; } public boolean getInit() { return initCalled; } public boolean getDestroy() { return destroyCalled; } } // END ProtectedBean } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/TestComponent.java0000644000000000000000000000417411412443352022530 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import javax.faces.component.UIOutput; // Dummy component that can be instantiated public class TestComponent extends UIOutput { public String getFamily() { return "Test"; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/TestRenderer.java0000644000000000000000000000407111412443352022330 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import javax.faces.render.Renderer; // Dummy renderer that can be instantiated public class TestRenderer extends Renderer { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/TestConverter.java0000644000000000000000000000411411412443352022527 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import javax.faces.convert.IntegerConverter; // Dummy converter that can be instantiated public class TestConverter extends IntegerConverter { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/TestValidator.java0000644000000000000000000000411411412443352022505 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import javax.faces.validator.LengthValidator; // Dummy converter that can be instantiated public class TestValidator extends LengthValidator { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/ClaimConfiguration.java0000644000000000000000000000441511412443352023501 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; public class ClaimConfiguration extends Object { public ClaimConfiguration() {} protected Double waterDamageAmount = new Double(100.0); public Double getWaterDamageAmount() { return waterDamageAmount; } public void setWaterDamageAmount(Double newWaterDamageAmount) { waterDamageAmount = newWaterDamageAmount; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/config/SimplePhaseListener.java0000644000000000000000000000527111412443352023645 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.config; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; public class SimplePhaseListener implements PhaseListener { private static final String HANDLED_BEFORE_AFTER = "Handled Before After"; private boolean handledBefore = false; private boolean handledAfter = false; public SimplePhaseListener() { } public void afterPhase(PhaseEvent event) { handledAfter = true; if (handledBefore && handledAfter) { System.setProperty(HANDLED_BEFORE_AFTER, HANDLED_BEFORE_AFTER); } } public void beforePhase(PhaseEvent event) { handledBefore = true; } public PhaseId getPhaseId() { return PhaseId.APPLY_REQUEST_VALUES; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/annotation/0000755000000000000000000000000011412443352017762 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestActionListener.java0000644000000000000000000000410011412443352022231 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestActionListener.java package com.sun.faces; import com.sun.faces.application.ActionListenerImpl; public class TestActionListener extends ActionListenerImpl { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestVariableResolver.java0000644000000000000000000000526611412443352022573 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestVariableResolver.java package com.sun.faces; import javax.faces.el.VariableResolver; import javax.faces.el.EvaluationException; import javax.faces.context.FacesContext; public class TestVariableResolver extends VariableResolver { VariableResolver resolver = null; public TestVariableResolver(VariableResolver variableResolver) { this.resolver = variableResolver; } // // Relationship Instance Variables // // Specified by javax.faces.el.VariableResolver.resolveVariable() public Object resolveVariable(FacesContext context, String name) throws EvaluationException { if (name.equals("customVRTest1")) { return "TestVariableResolver"; } return resolver.resolveVariable(context, name); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestFirstConverter.java0000644000000000000000000000406411412443352022276 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestFirstConverter.java package com.sun.faces; import javax.faces.convert.NumberConverter; public class TestFirstConverter extends NumberConverter { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/AdapterPropertyResolver.java0000644000000000000000000000713211412443352023325 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // AdapterPropertyResolver.java package com.sun.faces; import javax.faces.el.EvaluationException; import javax.faces.el.PropertyNotFoundException; import javax.faces.el.PropertyResolver; public class AdapterPropertyResolver extends PropertyResolver { public AdapterPropertyResolver(PropertyResolver root) { this.root = root; } public PropertyResolver getRoot() { return root; } private PropertyResolver root; public Object getValue(Object base, Object name) throws EvaluationException, PropertyNotFoundException { return root.getValue(base, name); } public Object getValue(Object base, int index) throws EvaluationException, PropertyNotFoundException { return root.getValue(base, index); } public void setValue(Object base, Object name, Object value) throws EvaluationException, PropertyNotFoundException { root.setValue(base, name, value); } public void setValue(Object base, int index, Object value) throws EvaluationException, PropertyNotFoundException { root.setValue(base, index, value); } public boolean isReadOnly(Object base, Object name) throws PropertyNotFoundException { return root.isReadOnly(base, name); } public boolean isReadOnly(Object base, int index) throws PropertyNotFoundException { return root.isReadOnly(base, index); } public Class getType(Object base, Object name) throws PropertyNotFoundException { return root.getType(base, name); } public Class getType(Object base, int index) throws PropertyNotFoundException { return root.getType(base, index); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestSecondValidator.java0000644000000000000000000000407611412443352022403 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestSecondValidator.java package com.sun.faces; import javax.faces.validator.LongRangeValidator; public class TestSecondValidator extends LongRangeValidator { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/scripting/0000755000000000000000000000000011412443346017615 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/scripting/groovy/0000755000000000000000000000000011412443346021142 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/scripting/groovy/MojarraGroovyClassLoaderTest.java0000644000000000000000000001023211412443346027561 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.scripting.groovy; import com.sun.faces.scripting.groovy.GroovyHelperImpl; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import junit.framework.TestCase; import com.sun.faces.mock.MockExternalContext; import com.sun.faces.mock.MockFacesContext; import com.sun.faces.mock.MockHttpServletRequest; import com.sun.faces.mock.MockHttpServletResponse; import com.sun.faces.mock.MockServletContext; public class MojarraGroovyClassLoaderTest extends TestCase { private ClassLoader originalClassLoader; private MockFacesContext facesContext; @Override protected void setUp() throws Exception { this.originalClassLoader = Thread.currentThread() .getContextClassLoader(); this.facesContext = new MockFacesContext() { @Override public void release() { super.release(); setCurrentInstance(null); } }; this.facesContext.setExternalContext(new MockExternalContext( new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse()) { @Override public URL getResource(String path) throws MalformedURLException { //avoid UnsupportedOperationException if ("/WEB-INF/groovy/".equals(path)) { return new File(".").toURI().toURL(); } return null; } }); new GroovyHelperImpl().setClassLoader(); } public void testLoadingUnexistingClassResultsInClassNotFoundException() throws Exception { try { Thread.currentThread().getContextClassLoader() .loadClass("com.sun.faces.UnexistingClass"); fail("Expected ClassNotFoundException"); } catch (ClassNotFoundException e) { //expected } } @Override protected void tearDown() throws Exception { this.facesContext.release(); Thread.currentThread().setContextClassLoader(this.originalClassLoader); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestFirstValidator.java0000644000000000000000000000406611412443352022256 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestFirstValidator.java package com.sun.faces; import javax.faces.validator.LengthValidator; public class TestFirstValidator extends LengthValidator { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestSecondConverter.java0000644000000000000000000000406611412443352022424 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestSecondConverter.java package com.sun.faces; import javax.faces.convert.NumberConverter; public class TestSecondConverter extends NumberConverter { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/0000755000000000000000000000000011412443352016210 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestResourceELResolver.java0000644000000000000000000001110511412443352023443 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.el; import javax.el.ELException; import javax.el.ValueExpression; import javax.faces.application.Application; import com.sun.faces.cactus.ServletFacesTestCase; import org.apache.cactus.WebRequest; /** * Test to validate com.sun.faces.el.ResourceELREsolver */ public class TestResourceELResolver extends ServletFacesTestCase { public TestResourceELResolver() { super("TestResourceELResolver"); } public TestResourceELResolver(String name) { super(name); } @Override public void setUp() { super.setUp(); } @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------ Test Methods public void beginGetValue(WebRequest req) { req.setURL("localhost:8080", "/test", "/faces", "/foo.jsp", null); } public void testGetValue() throws Exception { // non-library expression Application app = getFacesContext().getApplication(); ValueExpression v = app.getExpressionFactory().createValueExpression(getFacesContext().getELContext(), "#{resource['duke-nv.gif']}", String.class); String res = (String) v.getValue(getFacesContext().getELContext()); assertTrue(res != null); assertTrue("/test/faces/javax.faces.resource/duke-nv.gif".equals(res)); // library expression v = app.getExpressionFactory().createValueExpression(getFacesContext().getELContext(), "#{resource['nvLibrary:duke-nv.gif']}", String.class); res = (String) v.getValue(getFacesContext().getELContext()); assertTrue(res != null); assertTrue("/test/faces/javax.faces.resource/duke-nv.gif?ln=nvLibrary".equals(res)); } public void testGetValueInvalidExpression() throws Exception { Application app = getFacesContext().getApplication(); ValueExpression v = app.getExpressionFactory().createValueExpression(getFacesContext().getELContext(), "#{resource['nvLibrary::duke-nv.gif']}", String.class); try { v.getValue(getFacesContext().getELContext()); assertTrue(false); } catch (Exception e) { if (!(e instanceof ELException)) { assertTrue(false); } } } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestMethodRef.java0000644000000000000000000001167211412443352021577 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestMethodRef.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import javax.faces.el.EvaluationException; import javax.faces.el.MethodBinding; import javax.faces.el.MethodNotFoundException; import javax.faces.el.ReferenceSyntaxException; /** * TestMethodRef is a class ...

Lifetime And Scope *

* */ public class TestMethodRef extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestMethodRef() { super("TestMethodRef"); } public TestMethodRef(String name) { super(name); } // // Class methods // // // General Methods // protected MethodBinding create(String ref, Class[] params) throws Exception { return (getFacesContext().getApplication().createMethodBinding(ref, params)); } public void testNullReference() throws Exception { try { create(null, null); fail(); } catch (NullPointerException npe) {} catch (Exception e) { fail("Should have thrown an NPE"); }; } public void testInvalidMethod() throws Exception { try { create("#{foo > 1}", null); fail(); } catch (ReferenceSyntaxException rse) {} catch (Exception e) { fail("Should have thrown a ReferenceSyntaxException"); } } public void testLiteralReference() throws Exception { try { create("some.method", null); fail(); } catch (ReferenceSyntaxException rse) {} catch (Exception e) { fail("Should have thrown a ReferenceSyntaxException"); } } public void testInvalidTrailing() throws Exception { MethodBinding mb = this.create( "#{NewCustomerFormHandler.redLectroidsMmmm}", new Class[0]); boolean exceptionThrown = false; try { mb.invoke(getFacesContext(), new Object[0]); } catch (MethodNotFoundException e) { exceptionThrown = true; } assertTrue(exceptionThrown); mb = this.create("#{nonexistentBean.redLectroidsMmmm}", new Class[0]); // page 80 of the EL Spec, since nonexistentBean is null, the target // method is never reached and should catch a PropertyNotFoundException // and rethrow as a MethodNotFoundException exceptionThrown = false; try { mb.invoke(getFacesContext(), new Object[0]); } catch (MethodNotFoundException e) { exceptionThrown = true; } catch (EvaluationException e) { //TODO remove once adaptor is fixed exceptionThrown = true; } assertTrue(exceptionThrown); } } // end of class TestMethodRef mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestPropertyResolverImpl.java0000644000000000000000000006704711412443352024121 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestPropertyResolverImpl.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.TestBean; import com.sun.faces.util.Util; import javax.faces.FacesException; import javax.faces.component.UIViewRoot; import javax.faces.context.ExternalContext; import javax.faces.el.EvaluationException; import javax.faces.el.PropertyNotFoundException; import javax.faces.el.PropertyResolver; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; /** * TestPropertyResolverImpl is a class ... *

* Lifetime And Scope

* */ public class TestPropertyResolverImpl extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables private ElBean bean = null; private PropertyResolver resolver = null; // // Constructors and Initializers // public TestPropertyResolverImpl() { super("TestFacesContext"); } public TestPropertyResolverImpl(String name) { super(name); } // // Class methods // // // Methods from TestCase // public void setUp() { super.setUp(); bean = new ElBean(); resolver = getFacesContext().getApplication().getPropertyResolver(); } public void tearDown() { resolver = null; bean = null; super.tearDown(); } // // General Methods // // Negative getValue() tests on a JavaBean base object public void testNegative() throws Exception { Object value = null; // ---------- Should Return Null ---------- value = resolver.getValue(bean, null); assertNull(value); value = resolver.getValue(null, "booleanProperty"); assertNull(value); boolean exceptionThrown = false; try { value = resolver.getValue(null, null); } catch (javax.faces.el.EvaluationException ee) { exceptionThrown = true; } exceptionThrown = false; try { value = resolver.getValue(bean.getIntArray(), -1); } catch (javax.faces.el.EvaluationException ee) { exceptionThrown = true; } exceptionThrown = false; try { value = resolver.getValue(bean.getIntArray(), 3); } catch (javax.faces.el.EvaluationException ee) { exceptionThrown = true; } exceptionThrown = false; try { value = resolver.getValue(bean.getIntList(), -1); } catch (javax.faces.el.EvaluationException ee) { exceptionThrown = true; } exceptionThrown = false; try { value = resolver.getValue(bean.getIntList(), 5); } catch (javax.faces.el.EvaluationException ee) { exceptionThrown = true; } exceptionThrown = false; // ---------- Should throw EvaluationException try { value = resolver.getValue(bean, "nullStringProperty"); fail("Should have thrown EvaluationException"); } catch (EvaluationException e) { ; // Expected result } // ---------- Should Throw PropertyNotFoundException try { value = resolver.getValue(bean, "dontExist"); fail("Should have thrown EvaluationException"); } catch (EvaluationException e) { ; // Expected result } } public void testPristine() { // PENDING - test pristine condition of a new instance } // -------------------------------------------------- Indexed Variant Tests // Positive getValue() tests for the indexed variant against an array public void testIndexedGetArray() throws Exception { Object value = null; int intArray[] = bean.getIntArray(); assertEquals(3, intArray.length); value = resolver.getValue(intArray, -1); assertNull(value); value = resolver.getValue(null, 0); assertNull(value); value = resolver.getValue(intArray, 0); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals(1, ((Integer) value).intValue()); value = resolver.getValue(intArray, 1); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals(2, ((Integer) value).intValue()); value = resolver.getValue(intArray, 2); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals(3, ((Integer) value).intValue()); } // Positive getValue() tests for the indexed variant against a List public void testIndexedGetList() throws Exception { Object value = null; List intList = bean.getIntList(); assertEquals(5, intList.size()); value = resolver.getValue(intList, -1); assertNull(value); value = resolver.getValue(null, 0); assertNull(value); value = resolver.getValue(intList, 0); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals(10, ((Integer) value).intValue()); value = resolver.getValue(intList, 1); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals(20, ((Integer) value).intValue()); value = resolver.getValue(intList, 2); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals(30, ((Integer) value).intValue()); value = resolver.getValue(intList, 3); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals(40, ((Integer) value).intValue()); value = resolver.getValue(intList, 4); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals(50, ((Integer) value).intValue()); } // Positive setValue() tests for the indexed variant against an array public void testIndexedSetArray() throws Exception { Object value = new Integer(300); int intArray[] = bean.getIntArray(); assertEquals(3, intArray.length); resolver.setValue(intArray, 0, value); assertEquals(300, intArray[0]); Object[] objArray = new Object[] {"val"}; resolver.setValue(objArray, 0, null); assertNull(objArray[0]); try { resolver.setValue(null, 0, value); fail(); } catch (PropertyNotFoundException pnfe) {} try { resolver.setValue(intArray, -1, value); fail(); } catch (PropertyNotFoundException pnfe) {} try { resolver.setValue(intArray, 100, value); fail(); } catch (PropertyNotFoundException pnfe) {} } // Positive setValue() tests for the indexed variant against a List public void testIndexedSetList() throws Exception { Object value = new Object(); List intList = bean.getIntList(); assertEquals(5, intList.size()); resolver.setValue(intList, 0, value); assertNotNull(intList.get(0)); resolver.setValue(intList, 0, null); assertNull(intList.get(0)); try { resolver.setValue(null, 0, value); fail(); } catch (PropertyNotFoundException pnfe) {} try { resolver.setValue(intList, -1, value); fail(); } catch (PropertyNotFoundException pnfe) {} try { resolver.setValue(intList, 100, value); fail(); } catch (PropertyNotFoundException pnfe) {} } // Positive getType() tests for the indexed variant against an array public void testIndexedTypeArray() throws Exception { Class type = null; int intArray[] = bean.getIntArray(); assertEquals(3, intArray.length); type = resolver.getType(intArray, 0); assertEquals(Integer.TYPE, type); try { resolver.getType(null, 0); fail(); } catch (PropertyNotFoundException pnfe) {} try { resolver.getType(intArray, -1); fail(); } catch (PropertyNotFoundException pnfe) {} try { // do we really need to check this? resolver.getType(intArray, 100); //fail(); } catch (PropertyNotFoundException pnfe) {} } // Positive getType() tests for the indexed variant against a List public void testIndexedTypeList() throws Exception { Class type = null; List intList = bean.getIntList(); assertEquals(5, intList.size()); type = resolver.getType(intList, 0); assertEquals(Integer.class, type); try { resolver.getType(null, 0); fail(); } catch (PropertyNotFoundException pnfe) {} try { resolver.getType(intList, -1); fail(); } catch (PropertyNotFoundException pnfe) {} try { resolver.getType(intList, 100); fail(); } catch (PropertyNotFoundException pnfe) {} } // --------------------------------------------------- String Variant Tests // Postitive getValue() tests on a JavaBean base object public void testStringGetBean() throws Exception { Object value = null; value = resolver.getValue(bean, "booleanProperty"); assertNotNull(value); assertTrue(value instanceof Boolean); assertEquals(true, ((Boolean) value).booleanValue()); value = resolver.getValue(bean, "byteProperty"); assertNotNull(value); assertTrue(value instanceof Byte); assertEquals((byte) 123, ((Byte) value).byteValue()); value = resolver.getValue(bean, "doubleProperty"); assertNotNull(value); assertTrue(value instanceof Double); assertEquals((double) 654.321, ((Double) value).doubleValue(), 0.005); value = resolver.getValue(bean, "floatProperty"); assertNotNull(value); assertTrue(value instanceof Float); assertEquals((float) 123.45, ((Float) value).floatValue(), 0.5); value = resolver.getValue(bean, "intProperty"); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals((int) 1234, ((Integer) value).intValue()); value = resolver.getValue(bean, "longProperty"); assertNotNull(value); assertTrue(value instanceof Long); assertEquals((long) 54321, ((Long) value).longValue()); value = resolver.getValue(bean, "nestedProperty"); assertNotNull(value); assertTrue(value instanceof ElBean); assertEquals("This is a String", ((ElBean) value).getStringProperty()); value = resolver.getValue(bean, "shortProperty"); assertNotNull(value); assertTrue(value instanceof Short); assertEquals((short) 321, ((Short) value).shortValue()); value = resolver.getValue(bean, "stringProperty"); assertNotNull(value); assertTrue(value instanceof String); assertEquals("This is a String", (String) value); } // Positive getValue() tests on a Map base object public void testStringGetMap() throws Exception { getFacesContext().getExternalContext().getRequestMap().put("testValue", this); assertTrue(this == resolver.getValue( getFacesContext().getExternalContext().getRequestMap(), "testValue")); } // Postitive setValue() tests on a JavaBean base object public void testStringSetBean() throws Exception { Object value = null; resolver.setValue(bean, "booleanProperty", Boolean.FALSE); value = resolver.getValue(bean, "booleanProperty"); assertNotNull(value); assertTrue(value instanceof Boolean); assertEquals(false, ((Boolean) value).booleanValue()); resolver.setValue(bean, "byteProperty", new Byte((byte) 124)); value = resolver.getValue(bean, "byteProperty"); assertNotNull(value); assertTrue(value instanceof Byte); assertEquals((byte) 124, ((Byte) value).byteValue()); resolver.setValue(bean, "doubleProperty", new Double(333.333)); value = resolver.getValue(bean, "doubleProperty"); assertNotNull(value); assertTrue(value instanceof Double); assertEquals((double) 333.333, ((Double) value).doubleValue(), 0.005); resolver.setValue(bean, "floatProperty", new Float(22.11)); value = resolver.getValue(bean, "floatProperty"); assertNotNull(value); assertTrue(value instanceof Float); assertEquals((float) 22.11, ((Float) value).floatValue(), 0.5); resolver.setValue(bean, "intProperty", new Integer(4321)); value = resolver.getValue(bean, "intProperty"); assertNotNull(value); assertTrue(value instanceof Integer); assertEquals((int) 4321, ((Integer) value).intValue()); resolver.setValue(bean, "longProperty", new Long(12345)); value = resolver.getValue(bean, "longProperty"); assertNotNull(value); assertTrue(value instanceof Long); assertEquals((long) 12345, ((Long) value).longValue()); resolver.setValue(bean, "nestedProperty", new ElBean()); value = resolver.getValue(bean, "nestedProperty"); assertNotNull(value); assertTrue(value instanceof ElBean); resolver.setValue(bean, "shortProperty", new Short((short) 123)); value = resolver.getValue(bean, "shortProperty"); assertNotNull(value); assertTrue(value instanceof Short); assertEquals((short) 123, ((Short) value).shortValue()); resolver.setValue(bean, "stringProperty", "That was a STRING"); value = resolver.getValue(bean, "stringProperty"); assertNotNull(value); assertTrue(value instanceof String); assertEquals("That was a STRING", (String) value); } // Positive setValue() tests on a Map base object public void testStringSetMap() throws Exception { // PENDING - insert tests here } // Postitive getValue() tests on a JavaBean base object public void testStringTypeBean() throws Exception { Class value = null; value = resolver.getType(bean, "booleanProperty"); assertNotNull(value); assertEquals(Boolean.TYPE, value); value = resolver.getType(bean, "byteProperty"); assertNotNull(value); assertEquals(Byte.TYPE, value); value = resolver.getType(bean, "doubleProperty"); assertNotNull(value); assertEquals(Double.TYPE, value); value = resolver.getType(bean, "floatProperty"); assertNotNull(value); assertEquals(Float.TYPE, value); value = resolver.getType(bean, "intProperty"); assertNotNull(value); assertEquals(Integer.TYPE, value); value = resolver.getType(bean, "longProperty"); assertNotNull(value); assertEquals(Long.TYPE, value); bean.setNestedProperty(new ElBean()); value = resolver.getType(bean, "nestedProperty"); assertNotNull(value); assertEquals(ElBean.class, value); value = resolver.getType(bean, "shortProperty"); assertNotNull(value); assertEquals(Short.TYPE, value); value = resolver.getType(bean, "stringProperty"); assertNotNull(value); assertEquals(String.class, value); } // Positive getValue() tests on a Map base object public void testStringTypeMap() throws Exception { // PENDING - insert tests here } public void testReadOnlyObject() { ExternalContext ec = getFacesContext().getExternalContext(); // these are mutable Maps assertTrue(!resolver.isReadOnly(ec.getApplicationMap(), "hello")); assertTrue(!resolver.isReadOnly(ec.getSessionMap(), "hello")); assertTrue(!resolver.isReadOnly(ec.getRequestMap(), "hello")); // these are immutable Maps assertTrue(resolver.isReadOnly(ec.getRequestParameterMap(), "hello")); assertTrue(resolver.isReadOnly(ec.getRequestParameterValuesMap(), "hello")); assertTrue(resolver.isReadOnly(ec.getRequestHeaderMap(), "hello")); assertTrue(resolver.isReadOnly(ec.getRequestHeaderValuesMap(), "hello")); assertTrue(resolver.isReadOnly(ec.getRequestCookieMap(), "hello")); assertTrue(resolver.isReadOnly(ec.getInitParameterMap(), "hello")); UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); assertTrue(resolver.isReadOnly(root, "childCount")); com.sun.faces.cactus.TestBean testBean = (com.sun.faces.cactus.TestBean) ec.getSessionMap().get("TestBean"); assertTrue(resolver.isReadOnly(testBean, "readOnly")); assertTrue(!resolver.isReadOnly(testBean, "one")); } public void testReadOnlyIndex() { // PENDING(edburns): implement readonly index tests. } public void testType() { // PENDING(edburns): implement type tests } public void testConversion() throws Exception { ElBean bean = new ElBean(); this.conversionTest(bean, "booleanProperty", null, false); this.conversionTest(bean, "booleanProperty", "5", false); this.conversionTest(bean, "booleanProperty", new Character('c'), false); this.conversionTest(bean, "booleanProperty", Boolean.TRUE, true); this.conversionTest(bean, "booleanProperty", new BigInteger("5"), false); this.conversionTest(bean, "booleanProperty", new BigDecimal("5"), false); this.conversionTest(bean, "booleanProperty", new Byte((byte) 5), false); this.conversionTest(bean, "booleanProperty", new Short((short) 5), false); this.conversionTest(bean, "booleanProperty", new Integer(5), false); this.conversionTest(bean, "booleanProperty", new Long(5), false); this.conversionTest(bean, "booleanProperty", new Float(5), false); this.conversionTest(bean, "booleanProperty", new Double(5), false); this.conversionTest(bean, "byteProperty", null, false); this.conversionTest(bean, "byteProperty", "5", false); this.conversionTest(bean, "byteProperty", new Character('c'), false); this.conversionTest(bean, "byteProperty", Boolean.TRUE, false); this.conversionTest(bean, "byteProperty", new BigInteger("5"), false); this.conversionTest(bean, "byteProperty", new BigDecimal("5"), false); this.conversionTest(bean, "byteProperty", new Byte((byte) 5), true); this.conversionTest(bean, "byteProperty", new Short((short) 5), false); this.conversionTest(bean, "byteProperty", new Integer(5), false); this.conversionTest(bean, "byteProperty", new Long(5), false); this.conversionTest(bean, "byteProperty", new Float(5), false); this.conversionTest(bean, "byteProperty", new Double(5), false); this.conversionTest(bean, "characterProperty", null, false); this.conversionTest(bean, "characterProperty", "5", false); this.conversionTest(bean, "characterProperty", new Character('c'), true); this.conversionTest(bean, "characterProperty", Boolean.TRUE, false); this.conversionTest(bean, "characterProperty", new BigInteger("5"), false); this.conversionTest(bean, "characterProperty", new BigDecimal("5"), false); this.conversionTest(bean, "characterProperty", new Byte((byte) 5), false); this.conversionTest(bean, "characterProperty", new Short((short) 5), false); this.conversionTest(bean, "characterProperty", new Integer(5), false); this.conversionTest(bean, "characterProperty", new Long(5), false); this.conversionTest(bean, "characterProperty", new Float(5), false); this.conversionTest(bean, "characterProperty", new Double(5), false); this.conversionTest(bean, "doubleProperty", null, false); this.conversionTest(bean, "doubleProperty", "5", false); this.conversionTest(bean, "doubleProperty", new Character('c'), true); this.conversionTest(bean, "doubleProperty", Boolean.TRUE, false); this.conversionTest(bean, "doubleProperty", new BigInteger("5"), false); this.conversionTest(bean, "doubleProperty", new BigDecimal("5"), false); this.conversionTest(bean, "doubleProperty", new Byte((byte) 5), true); this.conversionTest(bean, "doubleProperty", new Short((short) 5), true); this.conversionTest(bean, "doubleProperty", new Integer(5), true); this.conversionTest(bean, "doubleProperty", new Long(5), true); this.conversionTest(bean, "doubleProperty", new Float(5), true); this.conversionTest(bean, "doubleProperty", new Double(5), true); this.conversionTest(bean, "floatProperty", null, false); this.conversionTest(bean, "floatProperty", "5", false); this.conversionTest(bean, "floatProperty", new Character('c'), true); this.conversionTest(bean, "floatProperty", Boolean.TRUE, false); this.conversionTest(bean, "floatProperty", new BigInteger("5"), false); this.conversionTest(bean, "floatProperty", new BigDecimal("5"), false); this.conversionTest(bean, "floatProperty", new Byte((byte) 5), true); this.conversionTest(bean, "floatProperty", new Short((short) 5), true); this.conversionTest(bean, "floatProperty", new Integer(5), true); this.conversionTest(bean, "floatProperty", new Long(5), true); this.conversionTest(bean, "floatProperty", new Float(5), true); this.conversionTest(bean, "floatProperty", new Double(5), false); this.conversionTest(bean, "longProperty", null, false); this.conversionTest(bean, "longProperty", "5", false); this.conversionTest(bean, "longProperty", new Character('c'), true); this.conversionTest(bean, "longProperty", Boolean.TRUE, false); this.conversionTest(bean, "longProperty", new BigInteger("5"), false); this.conversionTest(bean, "longProperty", new BigDecimal("5"), false); this.conversionTest(bean, "longProperty", new Byte((byte) 5), true); this.conversionTest(bean, "longProperty", new Short((short) 5), true); this.conversionTest(bean, "longProperty", new Integer(5), true); this.conversionTest(bean, "longProperty", new Long(5), true); this.conversionTest(bean, "longProperty", new Float(5), false); this.conversionTest(bean, "longProperty", new Double(5), false); this.conversionTest(bean, "shortProperty", null, false); this.conversionTest(bean, "shortProperty", "5", false); this.conversionTest(bean, "shortProperty", new Character('c'), false); this.conversionTest(bean, "shortProperty", Boolean.TRUE, false); this.conversionTest(bean, "shortProperty", new BigInteger("5"), false); this.conversionTest(bean, "shortProperty", new BigDecimal("5"), false); this.conversionTest(bean, "shortProperty", new Byte((byte) 5), true); this.conversionTest(bean, "shortProperty", new Short((short) 5), true); this.conversionTest(bean, "shortProperty", new Integer(5), false); this.conversionTest(bean, "shortProperty", new Long(5), false); this.conversionTest(bean, "shortProperty", new Float(5), false); this.conversionTest(bean, "shortProperty", new Double(5), false); this.conversionTest(bean, "stringProperty", null, true); this.conversionTest(bean, "stringProperty", "5", true); this.conversionTest(bean, "stringProperty", new Character('c'), false); this.conversionTest(bean, "stringProperty", Boolean.TRUE, false); this.conversionTest(bean, "stringProperty", new BigInteger("5"), false); this.conversionTest(bean, "stringProperty", new BigDecimal("5"), false); this.conversionTest(bean, "stringProperty", new Byte((byte) 5), false); this.conversionTest(bean, "stringProperty", new Short((short) 5), false); this.conversionTest(bean, "stringProperty", new Integer(5), false); this.conversionTest(bean, "stringProperty", new Long(5), false); this.conversionTest(bean, "stringProperty", new Float(5), false); this.conversionTest(bean, "stringProperty", new Double(5), false); } protected void conversionTest(Object bean, String property, Object value, boolean valid) throws Exception { if (valid) { try { this.resolver.setValue(bean, property, value); } catch (Exception e) { Class type = this.resolver.getType(bean, property); throw e; // throw new Exception("Conversion to "+type+" should not have failed for type "+((value != null) ? value.getClass() : null), e); } } else { try { this.resolver.setValue(bean, property, value); fail("Conversion to "+this.resolver.getType(bean, property)+" should have failed for type "+((value != null) ? value.getClass() : null)); } catch (FacesException e) { // good, should have ended up here } } } } // end of class TestPropertyResolverImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestValueExpressionImpl_Model.java0000644000000000000000000003311011412443352025007 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestValueExpressionImpl_Model.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.TestBean; import com.sun.faces.cactus.TestBean.Inner2Bean; import com.sun.faces.cactus.TestBean.InnerBean; import javax.faces.context.FacesContext; import javax.el.ELException; import javax.el.ValueExpression; import javax.el.ELContext; /** * TestValueExpressionImpl_Model is a class ... *

* Lifetime And Scope

* */ public class TestValueExpressionImpl_Model extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables ValueExpression valueExpression = null; // // Constructors and Initializers // public TestValueExpressionImpl_Model() { super("TestValueExpressionImpl"); } public TestValueExpressionImpl_Model(String name) { super(name); } // // Class methods // // // Methods from TestCase // // // General Methods // public ValueExpression create(String ref) throws Exception { return (getFacesContext().getApplication().getExpressionFactory(). createValueExpression(getFacesContext().getELContext(),("#{" + ref + "}"), Object.class)); } public void setUp() { super.setUp(); valueExpression = null; } public void tearDown() { valueExpression = null; super.tearDown(); } public void testSet() throws Exception { FacesContext facesContext = getFacesContext(); System.out.println("Testing setValue() with model bean in session "); TestBean testBean = new TestBean(); InnerBean inner = new InnerBean(); Inner2Bean innerInner = new Inner2Bean(); Object result = null; getFacesContext().getExternalContext().getSessionMap().put("TestBean", testBean); boolean exceptionThrown = false; System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("TestBean.one"); valueExpression.setValue(getFacesContext().getELContext(), "one"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); InnerBean newInner = new InnerBean(); valueExpression = this.create("TestBean.inner"); valueExpression.setValue(getFacesContext().getELContext(), newInner); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result == newInner); // Test two levels of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("sessionScope.TestBean.inner.two"); valueExpression.setValue(getFacesContext().getELContext(), "two"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); Inner2Bean newInner2 = new Inner2Bean(); valueExpression = this.create("TestBean.inner.inner2"); valueExpression.setValue(getFacesContext().getELContext(), newInner2); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result == newInner2); System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("sessionScope.TestBean.inner.inner2"); valueExpression.setValue(getFacesContext().getELContext(), innerInner); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); // Test three levels of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("sessionScope.TestBean.inner.inner2.three"); valueExpression.setValue(getFacesContext().getELContext(), "three"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); } public void testSetNull() throws Exception { FacesContext facesContext = getFacesContext(); System.out.println( "Testing setValue() with model bean in session with null rValues"); TestBean testBean = new TestBean(); InnerBean inner = new InnerBean(); Inner2Bean innerInner = new Inner2Bean(); getFacesContext().getExternalContext().getSessionMap().put("TestBean", testBean); // Test one level of nesting valueExpression = this.create("TestBean.one"); valueExpression.setValue(getFacesContext().getELContext(), null); assertTrue(testBean.getOne() == null); System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("sessionScope.TestBean.inner"); valueExpression.setValue(getFacesContext().getELContext(), inner); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); valueExpression = this.create("sessionScope.TestBean.inner"); valueExpression.setValue(getFacesContext().getELContext(), null); assertTrue(testBean.getInner() == null); // Inner bean does not exist anymore. So this should result in an // exception. Should throw a PropertyNotFoundException according // to page 92 of the EL Spec boolean exceptionThrown = false; valueExpression = this.create("sessionScope.TestBean.inner.two"); try { valueExpression.setValue(getFacesContext().getELContext(), null); } catch (javax.el.PropertyNotFoundException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testSetWithNoCurlyBraces() throws Exception { FacesContext facesContext = getFacesContext(); System.out.println("Testing setValue() with model bean in request "); TestBean testBean = new TestBean(); InnerBean inner = new InnerBean(); Inner2Bean innerInner = new Inner2Bean(); facesContext.getExternalContext().getSessionMap().remove("TestBean"); facesContext.getExternalContext().getRequestMap().put("TestBean", testBean); // Test implicit scopes direct access to some scope objects should // throw an illegalArgumentException boolean gotException = false; try { valueExpression = this.create("header.header-one"); valueExpression.setValue(getFacesContext().getELContext(), testBean); } catch (javax.el.ELException pnf) { gotException = true; } assertTrue(gotException); // Test one level of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("TestBean.one"); valueExpression.setValue(getFacesContext().getELContext(), "one"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("requestScope.TestBean.inner"); valueExpression.setValue(getFacesContext().getELContext(), inner); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); // Test two levels of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("requestScope.TestBean.inner.two"); valueExpression.setValue(getFacesContext().getELContext(), "two"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("requestScope.TestBean.inner.inner2"); valueExpression.setValue(getFacesContext().getELContext(), innerInner); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); // Test three levels of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueExpression = this.create("requestScope.TestBean.inner.inner2.three"); valueExpression.setValue(getFacesContext().getELContext(), "three"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); } public void testGet() throws Exception { FacesContext facesContext = getFacesContext(); System.out.println("Testing getValue() with model bean in context"); assertTrue(facesContext != null); TestBean testBeanResult = null, testBean = new TestBean(); InnerBean inner = new InnerBean(); Inner2Bean inner2 = new Inner2Bean(); String result; // Init the beans testBean.setOne("one"); inner.setTwo("two"); inner2.setThree("three"); inner.setInner2(inner2); testBean.setInner(inner); assertTrue(facesContext != null); assertTrue(facesContext.getExternalContext().getSession(false) != null); facesContext.getExternalContext().getRequestMap().remove("TestBean"); facesContext.getExternalContext().getSessionMap().remove("TestBean"); facesContext.getExternalContext().getApplicationMap().put("TestBean", testBean); // Test zero levels of nesting valueExpression = this.create("applicationScope.TestBean"); testBeanResult = (TestBean) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(testBeanResult != null); assertTrue(testBeanResult == testBean); // Test one level of nesting valueExpression = this.create("applicationScope.TestBean.one"); result = (String) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result.equals("one")); valueExpression = this.create("applicationScope.TestBean.inner"); inner = (InnerBean) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(null != inner); // Test two levels of nesting valueExpression = this.create("applicationScope.TestBean.inner.two"); result = (String) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result.equals("two")); valueExpression = this.create("applicationScope.TestBean.inner.inner2"); inner2 = (Inner2Bean) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(null != inner2); // Test three levels of nesting valueExpression = this.create("applicationScope.TestBean.inner.inner2.three"); result = (String) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result.equals("three")); } public void testModelType() { /***************** PENDING(edburns): // Test model type System.out.println("Testing getModelType()"); Class classType = null; String className = null; // Test zero levels of nesting classType = facesContext.getModelType("applicationScope.TestBean"); assertTrue(classType != null); className = classType.getName(); assertTrue(className.equals(testBean.getClass().getName())); classType = facesContext.getModelType("applicationScope.TestBean.inner.pin"); assertTrue(classType != null); className = classType.getName(); assertTrue(className.equals("java.lang.Integer")); classType = facesContext.getModelType("applicationScope.TestBean.inner.result"); assertTrue(classType != null); className = classType.getName(); assertTrue(className.equals("java.lang.Boolean")); classType = facesContext.getModelType("applicationScope.TestBean.one"); assertTrue(classType != null); className = classType.getName(); assertTrue(className.equals("java.lang.String")); *********************/ } } // end of class TestValueExpressionImpl_Model mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestFacesResourceBundleELResolver.java0000644000000000000000000001734211412443352025550 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestFacesResourceBundleELResolver.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import java.beans.FeatureDescriptor; import java.util.Iterator; import java.util.Locale; import java.util.ResourceBundle; import javax.el.ELResolver; import javax.el.PropertyNotFoundException; import javax.el.PropertyNotWritableException; import javax.faces.component.UIViewRoot; public class TestFacesResourceBundleELResolver extends ServletFacesTestCase { public TestFacesResourceBundleELResolver() { super("TestFacesResourceBundleELResolver"); } public TestFacesResourceBundleELResolver(String name) { super(name); } private FacesResourceBundleELResolver resolver = null; public void setUp() { super.setUp(); UIViewRoot root = new UIViewRoot(); root.setLocale(Locale.ENGLISH); getFacesContext().setViewRoot(root); resolver = new FacesResourceBundleELResolver(); } public void testGetValuePositive() throws Exception { ResourceBundle bundle1 = (ResourceBundle) resolver.getValue(getFacesContext().getELContext(), null, "testResourceBundle"); assertNotNull(bundle1); String value = bundle1.getString("value2"); assertNotNull(value); assertEquals("Bob", value); } public void testGetValueNegative() throws Exception { ResourceBundle bundle1 = (ResourceBundle) resolver.getValue(getFacesContext().getELContext(), "hello", "testResourceBundle"); assertNull(bundle1); boolean exceptionThrown = false; try { bundle1 = (ResourceBundle) resolver.getValue(getFacesContext().getELContext(), null, null); } catch (PropertyNotFoundException e) { exceptionThrown = true; } assertTrue(exceptionThrown); bundle1 = (ResourceBundle) resolver.getValue(getFacesContext().getELContext(), null, "nonExistent"); assertNull(bundle1); } public void testGetTypePositive() throws Exception { getFacesContext().getELContext().setPropertyResolved(false); Class type = resolver.getType(getFacesContext().getELContext(), null, "testResourceBundle"); assertTrue(getFacesContext().getELContext().isPropertyResolved()); assertEquals(ResourceBundle.class, type); } public void testGetTypeNegative() throws Exception { Class result = resolver.getType(getFacesContext().getELContext(), "non-null", "testResourceBundle"); assertTrue(null == result); boolean exceptionThrown = false; try { resolver.getType(getFacesContext().getELContext(), null, null); } catch (PropertyNotFoundException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testSetValeNegative() throws Exception { boolean exceptionThrown = false; try { resolver.setValue(getFacesContext().getELContext(), null, null, null); } catch (PropertyNotFoundException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { resolver.setValue(getFacesContext().getELContext(), null, "testResourceBundle", "Value"); } catch (PropertyNotWritableException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testIsReadOnlyPositive() throws Exception { getFacesContext().getELContext().setPropertyResolved(false); boolean result = resolver.isReadOnly(getFacesContext().getELContext(), null, "testResourceBundle"); assertTrue(result); assertTrue(getFacesContext().getELContext().isPropertyResolved()); } public void testIsReadOnlyNegative() throws Exception { boolean result = resolver.isReadOnly(getFacesContext().getELContext(), "non-null Base", null); assertTrue(!result); getFacesContext().getELContext().setPropertyResolved(false); boolean exceptionThrown = false; try { resolver.isReadOnly(getFacesContext().getELContext(), null, null); } catch (PropertyNotFoundException e) { exceptionThrown = true; } assertTrue(exceptionThrown); assertFalse(getFacesContext().getELContext().isPropertyResolved()); } public void testGetFeatureDescriptorsPositive() throws Exception { Iterator iter = resolver.getFeatureDescriptors(getFacesContext().getELContext(), null); assertNotNull(iter); FeatureDescriptor cur = null; String displayName1 = "Testo Pesto", displayName2 = "Second ResourceBundle"; String var1 = "testResourceBundle", var2 = "testResourceBundle2"; boolean test = false; while (iter.hasNext()) { test = false; cur = (FeatureDescriptor) iter.next(); assertEquals(Boolean.TRUE, cur.getValue(ELResolver.RESOLVABLE_AT_DESIGN_TIME)); assertEquals(ResourceBundle.class, cur.getValue(ELResolver.TYPE)); assertTrue(!cur.isExpert()); assertTrue(!cur.isHidden()); assertTrue(cur.isPreferred()); assertNotNull(cur.getDisplayName()); test = cur.getDisplayName().equals(displayName1) || cur.getDisplayName().equals(displayName2); assertTrue(test); test = cur.getName().equals(var1) || cur.getName().equals(var2); assertTrue(test); } } }mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestValueBindingImpl.java0000644000000000000000000012132611412443352023111 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestValueBindingImpl.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.TestBean; import com.sun.faces.cactus.TestBean.Inner2Bean; import com.sun.faces.cactus.TestBean.InnerBean; import com.sun.faces.application.ApplicationImpl; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.FacesException; import javax.faces.component.StateHolder; import javax.faces.component.UIForm; import javax.faces.component.UIInput; import javax.faces.component.UIViewRoot; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.el.EvaluationException; import javax.faces.el.PropertyNotFoundException; import javax.faces.el.ValueBinding; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Locale; /** * TestValueBindingImpl is a class ...

Lifetime And Scope *

*/ public class TestValueBindingImpl extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // protected ValueBinding valueBinding; // protected ValueBindingFactory factory = new ValueBindingFactory(); // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestValueBindingImpl() { super("TestValueBindingImpl"); } public TestValueBindingImpl(String name) { super(name); } // // Class methods // // // Methods from TestCase // // // General Methods // protected ValueBinding create(String ref) throws Exception { return (getFacesContext().getApplication().createValueBinding("#{" + ref + "}")); } public void populateRequest(WebRequest theRequest) { theRequest.addHeader("ELHeader", "ELHeader"); theRequest.addHeader("multiheader", "1"); theRequest.addHeader("multiheader", "2"); theRequest.addParameter("ELParam", "ELParam"); theRequest.addParameter("multiparam", "one"); theRequest.addParameter("multiparam", "two"); theRequest.addCookie("cookie", "monster"); } public void beginELGet(WebRequest theRequest) { populateRequest(theRequest); } public void testELGet() throws Exception { TestBean testBean = new TestBean(); InnerBean newInner, oldInner = new InnerBean(); testBean.setInner(oldInner); Object result = null; ExternalContext extContext = getFacesContext().getExternalContext(); Map myMap = new HashMap(); TestBean myBean = new TestBean(); myBean.setOne("one"); myMap.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // // Get tests // valueBinding = this.create("myMap.myBean.one"); result = valueBinding.getValue(getFacesContext()); assertEquals("one", result); valueBinding = this.create("myMap[\"myBean\"].one"); result = valueBinding.getValue(getFacesContext()); assertTrue("one".equals(result)); valueBinding = this.create("myMap.myBean['one']"); result = valueBinding.getValue(getFacesContext()); assertTrue("one".equals(result)); // Simple tests, verify that bracket and dot operators work valueBinding = this.create("TestBean.inner"); getFacesContext().getExternalContext().getSessionMap().put("TestBean", testBean); result = valueBinding.getValue(getFacesContext()); assertTrue(result == oldInner); valueBinding = this.create("TestBean[\"inner\"]"); result = valueBinding.getValue(getFacesContext()); assertTrue(result == oldInner); valueBinding = this.create("TestBean[\"inner\"].customers[1]"); result = valueBinding.getValue(getFacesContext()); assertTrue(result instanceof String); assertTrue(result.equals("Jerry")); // try out the implicit objects valueBinding = this.create("sessionScope.TestBean.inner"); result = valueBinding.getValue(getFacesContext()); assertTrue(result == oldInner); valueBinding = this.create("header.ELHeader"); result = valueBinding.getValue(getFacesContext()); assertTrue(requestsHaveSameAttributeSet( (HttpServletRequest) getFacesContext().getExternalContext() .getRequest(), (HttpServletRequest) request)); assertTrue(request.getHeader("ELHeader").equals("ELHeader")); assertTrue(result.equals("ELHeader")); valueBinding = this.create("param.ELParam"); result = valueBinding.getValue(getFacesContext()); assertTrue(result.equals("ELParam")); String multiparam[] = null; valueBinding = this.create("paramValues.multiparam"); multiparam = (String[]) valueBinding.getValue(getFacesContext()); assertTrue(null != multiparam); assertTrue(2 == multiparam.length); assertTrue(multiparam[0].equals("one")); assertTrue(multiparam[1].equals("two")); valueBinding = this.create("headerValues.multiheader"); String[] multiHeader = (String[]) valueBinding .getValue(getFacesContext()); assertTrue(null != multiHeader); assertTrue(1 == multiHeader.length); assertTrue(multiHeader[0].equals("1,2")); valueBinding = this.create("initParam.testInitParam"); result = valueBinding.getValue(getFacesContext()); assertTrue(null != result); assertTrue(result.equals("testInitParam")); // PENDING(craigmcc) - Comment out this test because on my platform // the getRequestCookies() call returns null /* * valueBinding.setRef("cookie.cookie"); result = * valueBinding.getValue(getFacesContext()); assertTrue(null != result); * assertTrue(result instanceof Cookie); assertTrue(((Cookie) * result).getValue().equals("monster")); */ } public void beginELSet(WebRequest theRequest) { populateRequest(theRequest); } public void testELSet() throws Exception { TestBean testBean = new TestBean(); InnerBean newInner, oldInner = new InnerBean(); testBean.setInner(oldInner); ValueBinding valueBinding = null; Object result = null; ExternalContext extContext = getFacesContext().getExternalContext(); Map myMap = new HashMap(); TestBean myBean = new TestBean(); myMap.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // // Set tests // valueBinding = this.create("myMap.myBean.one"); valueBinding.setValue(getFacesContext(), "one"); Map map = (Map) extContext.getRequestMap().get("myMap"); assertTrue("one".equals(((TestBean) map.get("myBean")).getOne())); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // test that we can set null as the value valueBinding = this.create("myMap.myBean.prop"); valueBinding.setValue(getFacesContext(), null); map = (Map) extContext.getRequestMap().get("myMap"); assertEquals(null, ((TestBean) map.get("myBean")).getOne()); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); valueBinding = this.create("myMap[\"myBean\"].one"); valueBinding.setValue(getFacesContext(), "one"); map = (Map) extContext.getRequestMap().get("myMap"); assertTrue("one".equals(((TestBean) map.get("myBean")).getOne())); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // test that we can set the property to null valueBinding = this.create("myMap[\"myBean\"].prop"); valueBinding.setValue(getFacesContext(), null); map = (Map) extContext.getRequestMap().get("myMap"); String msg = "Default Message"; if (((TestBean) map.get("myBean")).getProp() != null) { msg = ((TestBean) map.get("myBean")).getProp().getClass().getName(); } assertEquals(msg, null, ((TestBean) map.get("myBean")).getProp()); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); valueBinding = this.create("myMap.myBean['one']"); valueBinding.setValue(getFacesContext(), "one"); map = (Map) extContext.getRequestMap().get("myMap"); assertTrue("one".equals(((TestBean) map.get("myBean")).getOne())); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // set the prop to null valueBinding = this.create("myMap.myBean['prop']"); valueBinding.setValue(getFacesContext(), null); map = (Map) extContext.getRequestMap().get("myMap"); assertEquals(null, ((TestBean) map.get("myBean")).getOne()); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); valueBinding = this.create("NonExist"); valueBinding.setValue(getFacesContext(), "value"); result = extContext.getRequestMap().get("NonExist"); assertTrue("value".equals(result)); extContext.getRequestMap().remove("NonExist"); extContext.getSessionMap().put("Key", "oldValue"); valueBinding = this.create("Key"); valueBinding.setValue(getFacesContext(), "newValue"); result = extContext.getSessionMap().get("Key"); assertTrue("newValue".equals(result)); extContext.getSessionMap().remove("Key"); newInner = new InnerBean(); valueBinding = this.create("TestBean.inner"); valueBinding.setValue(getFacesContext(), newInner); result = valueBinding.getValue(getFacesContext()); assertTrue(result == newInner); assertTrue(oldInner != newInner); oldInner = newInner; newInner = new InnerBean(); valueBinding = this.create("TestBean[\"inner\"]"); valueBinding.setValue(getFacesContext(), newInner); result = valueBinding.getValue(getFacesContext()); assertTrue(result == newInner); assertTrue(oldInner != newInner); String oldCustomer0 = null, oldCustomer1 = null, customer0 = null, customer1 = null; valueBinding = this.create("TestBean[\"inner\"].customers[0]"); oldCustomer0 = customer0 = (String) valueBinding .getValue(getFacesContext()); valueBinding = this.create("TestBean[\"inner\"].customers[1]"); oldCustomer1 = customer1 = (String) valueBinding .getValue(getFacesContext()); valueBinding = this.create("TestBean[\"inner\"].customers[0]"); valueBinding.setValue(getFacesContext(), "Jerry"); valueBinding = this.create("TestBean[\"inner\"].customers[1]"); valueBinding.setValue(getFacesContext(), "Mickey"); valueBinding = this.create("TestBean[\"inner\"].customers[0]"); customer0 = (String) valueBinding.getValue(getFacesContext()); valueBinding = this.create("TestBean[\"inner\"].customers[1]"); customer1 = (String) valueBinding.getValue(getFacesContext()); assertTrue(customer0.equals("Jerry")); assertTrue(customer1.equals("Mickey")); valueBinding = this.create("TestBean[\"inner\"].customers[0]"); assertTrue(valueBinding.getValue(getFacesContext()) != oldCustomer0); valueBinding = this.create("TestBean[\"inner\"].customers[1]"); assertTrue(valueBinding.getValue(getFacesContext()) != oldCustomer1); // put in a map to the customers Collection Inner2Bean inner2 = new Inner2Bean(); assertTrue(null == inner2.getNicknames().get("foo")); valueBinding = this.create("TestBean[\"inner\"].customers[2]"); valueBinding.setValue(getFacesContext(), inner2); valueBinding = this.create("TestBean[\"inner\"].customers[2]"); assertTrue(valueBinding.getValue(getFacesContext()) == inner2); valueBinding = this .create("TestBean[\"inner\"].customers[2].nicknames.foo"); valueBinding.setValue(getFacesContext(), "bar"); assertTrue(((String) inner2.getNicknames().get("foo")).equals("bar")); } public void testNullReference() throws Exception { try { getFacesContext().getApplication().createValueBinding(null); fail(); } catch (NullPointerException npe) {} catch (Exception e) { fail("Should have thrown an NPE"); }; } public void testLiterals() throws Exception { ValueBinding vb = null; Object result = null; ExternalContext extContext = getFacesContext().getExternalContext(); vb = getFacesContext().getApplication().createValueBinding("test"); assertEquals("test", vb.getValue(getFacesContext())); assertEquals(String.class, vb.getType(getFacesContext())); try { vb.setValue(getFacesContext(), "other"); fail("Literal's setValue(..) should have thrown a EvaluationException"); } catch (javax.faces.el.EvaluationException ee) {} } public void testReadOnly_singleCase() throws Exception { // these are mutable Maps /* * properties on these maps are mutable, but not the object itself.... * see */ valueBinding = this.create("applicationScope"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("sessionScope"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("requestScope"); assertTrue(valueBinding.isReadOnly(getFacesContext())); // these are immutable Maps valueBinding = this.create("param"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("paramValues"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("header"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("headerValues"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("cookie"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("initParam"); assertTrue(valueBinding.isReadOnly(getFacesContext())); } public void testReadOnly_multipleCase() throws Exception { // these are mutable Maps valueBinding = this.create("applicationScope.value"); valueBinding.setValue(getFacesContext(), "value"); String value = (String) valueBinding.getValue(getFacesContext()); assertTrue(!valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("sessionScope.value"); assertTrue(!valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("requestScope.value"); assertTrue(!valueBinding.isReadOnly(getFacesContext())); // these are immutable Maps valueBinding = this.create("param.value"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("paramValues.value"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("header.value"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("headerValues.value"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("cookie.value"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("initParam.value"); assertTrue(valueBinding.isReadOnly(getFacesContext())); // tree // create a dummy root for the tree. UIViewRoot page = Util.getViewHandler(getFacesContext()).createView( getFacesContext(), null); page.setId("root"); page.setViewId("newTree"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); valueBinding = this.create("view.childCount"); assertTrue(valueBinding.isReadOnly(getFacesContext())); com.sun.faces.cactus.TestBean testBean = (com.sun.faces.cactus.TestBean) getFacesContext().getExternalContext() .getSessionMap().get("TestBean"); assertTrue(null != testBean); valueBinding = this.create("TestBean.readOnly"); assertTrue(valueBinding.isReadOnly(getFacesContext())); valueBinding = this.create("TestBean.one"); assertTrue(!valueBinding.isReadOnly(getFacesContext())); InnerBean inner = new InnerBean(); testBean.setInner(inner); valueBinding = this.create("TestBean[\"inner\"].customers[1]"); assertTrue(!valueBinding.isReadOnly(getFacesContext())); } public void testGetType_singleCase() throws Exception { // these are mutable Maps valueBinding = this.create("applicationScope"); assertTrue(valueBinding.getType(getFacesContext()) == null); valueBinding = this.create("sessionScope"); assertTrue(valueBinding.getType(getFacesContext()) == null); valueBinding = this.create("requestScope"); assertTrue(valueBinding.getType(getFacesContext()) == null); // these are immutable Maps valueBinding = this.create("param"); assertTrue(valueBinding.getType(getFacesContext()) == null); valueBinding = this.create("paramValues"); assertTrue(valueBinding.getType(getFacesContext()) == null); valueBinding = this.create("header"); assertTrue(valueBinding.getType(getFacesContext()) == null); valueBinding = this.create("headerValues"); assertTrue(valueBinding.getType(getFacesContext()) == null); valueBinding = this.create("cookie"); assertTrue(valueBinding.getType(getFacesContext()) == null); valueBinding = this.create("initParam"); assertTrue(valueBinding.getType(getFacesContext()) == null); } public void beginGetType_multipleCase(WebRequest theRequest) { populateRequest(theRequest); } public void testGetType_multipleCase() throws Exception { String property = "testvalueBindingImpl_property"; getFacesContext().getExternalContext().getApplicationMap().put( property, property); getFacesContext().getExternalContext().getSessionMap().put(property, property); getFacesContext().getExternalContext().getRequestMap().put(property, property); // these are mutable Maps valueBinding = this.create("applicationScope." + property); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); valueBinding = this.create("sessionScope." + property); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); valueBinding = this.create("requestScope." + property); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); // these are immutable Maps valueBinding = this.create("param." + "ELParam"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); valueBinding = this.create("paramValues.multiparam"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); valueBinding = this.create("header.ELHeader"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); valueBinding = this.create("headerValues.multiheader"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); // assertTrue(java.util.Enumeration.class.isAssignableFrom(valueBinding // .getType(getFacesContext()))); // PENDING(craigmcc) - Comment out this test because on my platform // the getRequestCookies() call returns null /* * valueBinding = this.create("cookie.cookie"); * assertTrue(valueBinding.getType(getFacesContext()).getName().equals("javax.servlet.http.Cookie")); */ valueBinding = this .create("initParam['javax.faces.STATE_SAVING_METHOD']"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); // tree // create a dummy root for the tree. UIViewRoot page = Util.getViewHandler(getFacesContext()).createView( getFacesContext(), null); page.setId("root"); page.setViewId("newTree"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); valueBinding = this.create("view"); Class c = valueBinding.getType(getFacesContext()); assertTrue(c == null); com.sun.faces.cactus.TestBean testBean = (com.sun.faces.cactus.TestBean) getFacesContext().getExternalContext() .getSessionMap().get("TestBean"); assertTrue(null != testBean); valueBinding = this.create("TestBean.readOnly"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.String")); valueBinding = this.create("TestBean.one"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.String")); InnerBean inner = new InnerBean(); testBean.setInner(inner); valueBinding = this.create("TestBean[\"inner\"].customers[1]"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); valueBinding = this.create("TestBean[\"inner\"]"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "com.sun.faces.cactus.TestBean$InnerBean")); int[] intArray = { 1, 2, 3 }; getFacesContext().getExternalContext().getRequestMap().put("intArray", intArray); valueBinding = this.create("requestScope.intArray"); assertTrue(valueBinding.getType(getFacesContext()).getName().equals( "java.lang.Object")); // assertTrue(valueBinding.getType(getFacesContext()).getName().equals( // "[I")); } public void testGetScopePositive() throws Exception { TestBean testBean = new TestBean(); getFacesContext().getExternalContext().getApplicationMap().put( "TestApplicationBean", testBean); valueBinding = this.create("TestApplicationBean"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope("TestApplicationBean", null)); valueBinding = this.create("TestApplicationBean.one"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope("TestApplicationBean.one", null)); valueBinding = this.create("TestApplicationBean.inner.two"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope( "TestApplicationBean.inner.two", null)); valueBinding = this.create("applicationScope.TestApplicationBean"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope( "applicationScope.TestApplicationBean", null)); valueBinding = this .create("applicationScope.TestApplicationBean.inner.two"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope( "applicationScope.TestApplicationBean.inner.two", null)); getFacesContext().getExternalContext().getSessionMap().put( "TestSessionBean", testBean); valueBinding = this.create("TestSessionBean"); assertEquals(ELUtils.Scope.SESSION, ELUtils.getScope("TestSessionBean", null)); valueBinding = this.create("TestSessionBean.one"); assertEquals(ELUtils.Scope.SESSION, ELUtils.getScope("TestSessionBean.one", null)); valueBinding = this.create("TestSessionBean.inner.two"); assertEquals(ELUtils.Scope.SESSION, ELUtils .getScope("TestSessionBean.inner.two", null)); valueBinding = this.create("sessionScope.TestSessionBean"); assertEquals(ELUtils.Scope.SESSION, ELUtils.getScope("sessionScope.TestSessionBean", null)); valueBinding = this.create("sessionScope.TestSessionBean.inner.two"); assertEquals(ELUtils.Scope.SESSION, ELUtils.getScope( "sessionScope.TestSessionBean.inner.two", null)); getFacesContext().getExternalContext().getRequestMap().put( "TestRequestBean", testBean); valueBinding = this.create("TestRequestBean"); assertEquals(ELUtils.Scope.REQUEST, ELUtils.getScope("TestRequestBean", null)); valueBinding = this.create("TestRequestBean.one"); assertEquals(ELUtils.Scope.REQUEST, ELUtils.getScope("TestRequestBean.one", null)); valueBinding = this.create("TestRequestBean.inner.two"); assertEquals(ELUtils.Scope.REQUEST, ELUtils .getScope("TestRequestBean.inner.two", null)); valueBinding = this.create("requestScope.TestRequestBean"); assertEquals(ELUtils.Scope.REQUEST, ELUtils.getScope("requestScope.TestRequestBean", null)); valueBinding = this.create("requestScope.TestRequestBean.inner.two"); assertEquals(ELUtils.Scope.REQUEST, ELUtils.getScope( "requestScope.TestRequestBean.inner.two", null)); valueBinding = this.create("TestNoneBean"); assertEquals(null, ELUtils.getScope("TestNoneBean", null)); valueBinding = this.create("TestNoneBean.one"); assertEquals(null, ELUtils.getScope("TestNoneBean.one", null)); valueBinding = this.create("TestNoneBean.inner.two"); assertEquals(null, ELUtils.getScope("TestNoneBean.inner.two", null)); } public void testGetScopeNegative() throws Exception { ValueBinding valueBinding = null; String property = null; /* property = "[]"; valueBinding = this.factory.createValueBinding(property); assertNull(Util.getScope(property, null)); property = "]["; assertNull(Util.getScope(property, null)); property = ""; assertNull(Util.getScope(property, null)); property = null; assertNull(Util.getScope(property, null)); property = "foo.sessionScope"; assertNull(Util.getScope(property, null)); */ } // negative test for case when valueRef is merely // one of the reserved scope names. public void testReservedScopeIdentifiers() throws Exception { boolean exceptionThrown = false; try { valueBinding = this.create("applicationScope"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("sessionScope"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("requestScope"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("facesContext"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("cookie"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("header"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("headerValues"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("initParam"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("param"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("paramValues"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("view"); valueBinding.setValue(getFacesContext(), "value"); } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testInvalidExpression() throws Exception { boolean exceptionThrown = false; try { valueBinding = this.create(""); valueBinding.getValue(getFacesContext()); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("!"); valueBinding.getValue(getFacesContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create(".."); valueBinding.getValue(getFacesContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create(".foo"); valueBinding.getValue(getFacesContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("()"); valueBinding.getValue(getFacesContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("[]"); valueBinding.getValue(getFacesContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("applicationScope}"); valueBinding.getValue(getFacesContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(!exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("applicationScope >= sessionScope"); valueBinding.getValue(getFacesContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueBinding = this.create("foo applicationScope"); valueBinding.getValue(getFacesContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testStateHolderSmall() throws Exception { StateHolderSaver saver = null; ValueBinding binding = getFacesContext().getApplication() .createValueBinding("#{TestBean.indexProperties[0]}"); assertEquals("ValueBinding not expected value", "Justyna", (String) binding.getValue(getFacesContext())); saver = new StateHolderSaver(getFacesContext(), binding); binding = null; binding = (ValueBinding) saver.restore(getFacesContext()); assertEquals("ValueBinding not expected value", "Justyna", (String) binding.getValue(getFacesContext())); } public void testStateHolderMedium() throws Exception { UIViewRoot root = null; UIForm form = null; UIInput input = null; Object state = null; getFacesContext().setViewRoot( root = Util.getViewHandler(getFacesContext()).createView( getFacesContext(), null)); getFacesContext().getViewRoot().setLocale(Locale.US); root.getChildren().add(form = new UIForm()); form.getChildren().add(input = new UIInput()); input.setValueBinding("buckaroo", getFacesContext().getApplication() .createValueBinding("#{TestBean.indexProperties[0]}")); state = root.processSaveState(getFacesContext()); // synthesize the tree structure getFacesContext().setViewRoot( root = Util.getViewHandler(getFacesContext()).createView( getFacesContext(), null)); getFacesContext().getViewRoot().setLocale(Locale.US); root.getChildren().add(form = new UIForm()); form.getChildren().add(input = new UIInput()); root.processRestoreState(getFacesContext(), state); assertEquals("ValueBinding not expected value", "Justyna", (String) input.getValueBinding("buckaroo").getValue( getFacesContext())); } public void testGetExpressionString() throws Exception { ApplicationImpl app = (ApplicationImpl) getFacesContext() .getApplication(); String ref = null; ValueBinding vb = null; ref = "#{NewCustomerFormHandler.minimumAge}"; vb = app.createValueBinding(ref); assertEquals(ref, vb.getExpressionString()); ref = "minimum age is #{NewCustomerFormHandler.minimumAge}"; vb = app.createValueBinding(ref); assertEquals(ref, vb.getExpressionString()); } class StateHolderSaver extends Object implements Serializable { protected String className = null; protected Object savedState = null; public StateHolderSaver(FacesContext context, Object toSave) { className = toSave.getClass().getName(); if (toSave instanceof StateHolder) { // do not save an attached object that is marked transient. if (!((StateHolder) toSave).isTransient()) { savedState = ((StateHolder) toSave).saveState(context); } else { className = null; } } } /** * @return the restored {@link StateHolder}instance. */ public Object restore(FacesContext context) throws IllegalStateException { Object result = null; Class toRestoreClass = null; if (className == null) { return null; } try { toRestoreClass = loadClass(className, this); } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage()); } if (null != toRestoreClass) { try { result = toRestoreClass.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException(e.getMessage()); } catch (IllegalAccessException a) { throw new IllegalStateException(a.getMessage()); } } if (null != result && null != savedState && result instanceof StateHolder) { // don't need to check transient, since that was done on // the saving side. ((StateHolder) result).restoreState(context, savedState); } return result; } private Class loadClass(String name, Object fallbackClass) throws ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = fallbackClass.getClass().getClassLoader(); } return loader.loadClass(name); } } } // end of class TestValueBindingImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestNestedELResolver.java0000644000000000000000000002060511412443352023103 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2009 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.el; import java.beans.FeatureDescriptor; import java.lang.reflect.Field; import java.util.Collections; import java.util.Iterator; import javax.el.ELContext; import javax.el.ELResolver; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpSession; import junit.framework.TestCase; import com.sun.faces.RIConstants; import com.sun.faces.application.ApplicationAssociate; import com.sun.faces.application.ApplicationImpl; import com.sun.faces.mock.MockELContext; import com.sun.faces.mock.MockExternalContext; import com.sun.faces.mock.MockFacesContext; import com.sun.faces.mock.MockHttpServletRequest; import com.sun.faces.mock.MockHttpServletResponse; import com.sun.faces.mock.MockHttpSession; import com.sun.faces.mock.MockServletContext; /** * Tests needs to be run with assertions enabled (-ea:com.sun.faces.el.ChainAwareVariableResolver) */ public class TestNestedELResolver extends TestCase { private static final String UNPREFIXED_VALUE = "unprefixedValue"; private static final String UNPREFIXED_KEY = "unprefixedKey"; private static final String PREFIXED_VALUE = "prefixedValue"; private static final String PREFIX = "test:"; private static final String PREFIXED_KEY = PREFIX + "value"; private ELContext elContext; public void setUp() throws Exception { FacesContext facesContext = createStubbedFacesContext(); this.elContext = facesContext.getELContext(); facesContext.getExternalContext().getApplicationMap() .put(PREFIXED_KEY, PREFIXED_VALUE); facesContext.getExternalContext().getApplicationMap() .put(UNPREFIXED_KEY, UNPREFIXED_VALUE); } public void testShouldResolveVariableWhenNestedELResolverCallCanNotResolve() throws Exception { assertEquals(UNPREFIXED_VALUE, this.elContext.getELResolver().getValue(this.elContext, null, UNPREFIXED_KEY)); } public void testShouldResolveVariableViaNestedELResolverCall() throws Exception { assertEquals(PREFIXED_VALUE, this.elContext.getELResolver().getValue(this.elContext, null, PREFIXED_KEY)); } ///wish I could use FacesTester ;-) private FacesContext createStubbedFacesContext() throws Exception { ServletContext context = new MockServletContext(); ((MockServletContext) context).addInitParameter("javax.faces.DISABLE_FACELET_JSF_VIEWHANDLER", "true"); HttpSession session = new MockHttpSession(context); ServletRequest request = new MockHttpServletRequest(session); ServletResponse response = new MockHttpServletResponse(); ExternalContext externalContect = new MockExternalContext(context, request, response); MockFacesContext mockFacesContext = new MockFacesContext(externalContect); mockFacesContext.setApplication(new ApplicationImpl()); ApplicationAssociate associate = getApplicationAssociate( mockFacesContext); associate .setELResolversFromFacesConfig(Collections.singletonList( new NestedELResolver(PREFIX))); associate.setLegacyVariableResolver(new ChainAwareVariableResolver()); FacesCompositeELResolver facesCompositeELResolver = new FacesCompositeELResolver( FacesCompositeELResolver.ELResolverChainType.Faces); ELUtils.buildFacesResolver(facesCompositeELResolver, associate); ELContext elContext = mockFacesContext.getELContext(); setELResolverOnElContext(facesCompositeELResolver, elContext); return mockFacesContext; } private ApplicationAssociate getApplicationAssociate(MockFacesContext mockFacesContext) { return (ApplicationAssociate) mockFacesContext.getExternalContext() .getApplicationMap() .get(RIConstants.FACES_PREFIX + "ApplicationAssociate"); } //there should be a better way for doing this when using mocks/stubs private void setELResolverOnElContext(FacesCompositeELResolver facesCompositeELResolver, ELContext elContext) throws Exception { Field field = elContext.getClass().getDeclaredField("resolver"); boolean accessible = field.isAccessible(); try { field.setAccessible(true); field.set(elContext, facesCompositeELResolver); } finally { field.setAccessible(accessible); } } /* * Uses ElContext.getElResolver().getValue() inside its own getValue() */ public static class NestedELResolver extends ELResolver { private final String prefix; public NestedELResolver(String prefix) { this.prefix = prefix; } @Override public Class getCommonPropertyType(ELContext arg0, Object arg1) { return null; } @Override public Iterator getFeatureDescriptors(ELContext arg0, Object arg1) { return null; } @Override public Class getType(ELContext arg0, Object arg1, Object arg2) { return null; } @Override public Object getValue(ELContext context, Object base, Object property) { if (context.getContext(NestedELResolver.class) != Boolean.TRUE) { context.putContext(NestedELResolver.class, Boolean.TRUE); try { Object value = context.getELResolver() .getValue(context, base, this.prefix + property); context.setPropertyResolved(value != null); return value; } finally { context.putContext(NestedELResolver.class, Boolean.FALSE); } } return null; } @Override public boolean isReadOnly(ELContext arg0, Object arg1, Object arg2) { return false; } @Override public void setValue(ELContext arg0, Object arg1, Object arg2, Object arg3) { } } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestValueExpressionImpl.java0000644000000000000000000013253211412443352023677 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestValueExpressionImpl.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.TestBean; import com.sun.faces.CustomerBean; import com.sun.faces.cactus.TestBean.Inner2Bean; import com.sun.faces.cactus.TestBean.InnerBean; import com.sun.faces.application.ApplicationImpl; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.component.StateHolder; import javax.faces.component.UIViewRoot; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; import javax.el.ValueExpression; import javax.el.ELException; import javax.el.PropertyNotFoundException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Locale; /** * TestValueExpressionImpl is a class ...

Lifetime And Scope *

*/ public class TestValueExpressionImpl extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // protected ValueExpression valueExpression; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestValueExpressionImpl() { super("TestValueExpressionImpl"); } public TestValueExpressionImpl(String name) { super(name); } // // Class methods // // // Methods from TestCase // // // General Methods // protected ValueExpression create(String ref) throws Exception { return (getFacesContext().getApplication().getExpressionFactory(). createValueExpression(getFacesContext().getELContext(),("#{" + ref + "}"), Object.class)); } public void populateRequest(WebRequest theRequest) { theRequest.addHeader("ELHeader", "ELHeader"); theRequest.addHeader("multiheader", "1"); theRequest.addHeader("multiheader", "2"); theRequest.addParameter("ELParam", "ELParam"); theRequest.addParameter("multiparam", "one"); theRequest.addParameter("multiparam", "two"); theRequest.addCookie("cookie", "monster"); } public void beginELGet(WebRequest theRequest) { populateRequest(theRequest); } public void testELGet() throws Exception { TestBean testBean = new TestBean(); InnerBean newInner, oldInner = new InnerBean(); testBean.setInner(oldInner); Object result = null; ExternalContext extContext = getFacesContext().getExternalContext(); Map myMap = new HashMap(); TestBean myBean = new TestBean(); myBean.setOne("one"); myMap.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // // Get tests // valueExpression = this.create("myMap.myBean.one"); result = valueExpression.getValue(getFacesContext().getELContext()); assertEquals("one", result); valueExpression = this.create("myMap[\"myBean\"].one"); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue("one".equals(result)); valueExpression = this.create("myMap.myBean['one']"); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue("one".equals(result)); // Simple tests, verify that bracket and dot operators work valueExpression = this.create("TestBean.inner"); getFacesContext().getExternalContext().getSessionMap().put("TestBean", testBean); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result == oldInner); valueExpression = this.create("TestBean[\"inner\"]"); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result == oldInner); valueExpression = this.create("TestBean[\"inner\"].customers[1]"); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result instanceof String); assertTrue(result.equals("Jerry")); // try out the implicit objects valueExpression = this.create("sessionScope.TestBean.inner"); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result == oldInner); valueExpression = this.create("header.ELHeader"); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(requestsHaveSameAttributeSet( (HttpServletRequest) getFacesContext().getExternalContext() .getRequest(), (HttpServletRequest) request)); assertTrue(request.getHeader("ELHeader").equals("ELHeader")); assertTrue(result.equals("ELHeader")); valueExpression = this.create("param.ELParam"); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result.equals("ELParam")); String multiparam[] = null; valueExpression = this.create("paramValues.multiparam"); multiparam = (String[]) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(null != multiparam); assertTrue(2 == multiparam.length); assertTrue(multiparam[0].equals("one")); assertTrue(multiparam[1].equals("two")); valueExpression = this.create("headerValues.multiheader"); String[] multiHeader = (String[]) valueExpression .getValue(getFacesContext().getELContext()); assertTrue(null != multiHeader); assertTrue(1 == multiHeader.length); assertTrue(multiHeader[0].equals("1,2")); valueExpression = this.create("initParam.testInitParam"); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(null != result); assertTrue(result.equals("testInitParam")); // PENDING(craigmcc) - Comment out this test because on my platform // the getRequestCookies() call returns null /* * valueExpression.setRef("cookie.cookie"); result = * valueExpression.getValue(getFacesContext().getELContext()); assertTrue(null != result); * assertTrue(result instanceof Cookie); assertTrue(((Cookie) * result).getValue().equals("monster")); */ } public void beginELSet(WebRequest theRequest) { populateRequest(theRequest); } public void testELSet() throws Exception { TestBean testBean = new TestBean(); InnerBean newInner, oldInner = new InnerBean(); testBean.setInner(oldInner); ValueExpression valueExpression = null; Object result = null; ExternalContext extContext = getFacesContext().getExternalContext(); Map myMap = new HashMap(); TestBean myBean = new TestBean(); myMap.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // // Set tests // valueExpression = this.create("myMap.myBean.one"); valueExpression.setValue(getFacesContext().getELContext(), "one"); Map map = (Map) extContext.getRequestMap().get("myMap"); assertTrue("one".equals(((TestBean) map.get("myBean")).getOne())); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // test that we can set null as the value valueExpression = this.create("myMap.myBean.prop"); valueExpression.setValue(getFacesContext().getELContext(), null); map = (Map) extContext.getRequestMap().get("myMap"); assertEquals(null, ((TestBean) map.get("myBean")).getOne()); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); valueExpression = this.create("myMap[\"myBean\"].one"); valueExpression.setValue(getFacesContext().getELContext(), "one"); map = (Map) extContext.getRequestMap().get("myMap"); assertTrue("one".equals(((TestBean) map.get("myBean")).getOne())); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // test that we can set the property to null valueExpression = this.create("myMap[\"myBean\"].prop"); valueExpression.setValue(getFacesContext().getELContext(), null); map = (Map) extContext.getRequestMap().get("myMap"); String msg = "Default Message"; if (((TestBean) map.get("myBean")).getProp() != null) { msg = ((TestBean) map.get("myBean")).getProp().getClass().getName(); } assertEquals(msg, null, ((TestBean) map.get("myBean")).getProp()); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); valueExpression = this.create("myMap.myBean['one']"); valueExpression.setValue(getFacesContext().getELContext(), "one"); map = (Map) extContext.getRequestMap().get("myMap"); assertTrue("one".equals(((TestBean) map.get("myBean")).getOne())); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); // set the prop to null valueExpression = this.create("myMap.myBean['prop']"); valueExpression.setValue(getFacesContext().getELContext(), null); map = (Map) extContext.getRequestMap().get("myMap"); assertEquals(null, ((TestBean) map.get("myBean")).getOne()); myBean = new TestBean(); map.put("myBean", myBean); extContext.getRequestMap().put("myMap", myMap); valueExpression = this.create("NonExist"); valueExpression.setValue(getFacesContext().getELContext(), "value"); result = extContext.getRequestMap().get("NonExist"); assertTrue("value".equals(result)); extContext.getRequestMap().remove("NonExist"); extContext.getSessionMap().put("Key", "oldValue"); valueExpression = this.create("Key"); valueExpression.setValue(getFacesContext().getELContext(), "newValue"); result = extContext.getSessionMap().get("Key"); assertTrue("newValue".equals(result)); extContext.getSessionMap().remove("Key"); newInner = new InnerBean(); valueExpression = this.create("TestBean.inner"); valueExpression.setValue(getFacesContext().getELContext(), newInner); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result == newInner); assertTrue(oldInner != newInner); oldInner = newInner; newInner = new InnerBean(); valueExpression = this.create("TestBean[\"inner\"]"); valueExpression.setValue(getFacesContext().getELContext(), newInner); result = valueExpression.getValue(getFacesContext().getELContext()); assertTrue(result == newInner); assertTrue(oldInner != newInner); String oldCustomer0 = null, oldCustomer1 = null, customer0 = null, customer1 = null; valueExpression = this.create("TestBean[\"inner\"].customers[0]"); oldCustomer0 = customer0 = (String) valueExpression .getValue(getFacesContext().getELContext()); valueExpression = this.create("TestBean[\"inner\"].customers[1]"); oldCustomer1 = customer1 = (String) valueExpression .getValue(getFacesContext().getELContext()); valueExpression = this.create("TestBean[\"inner\"].customers[0]"); valueExpression.setValue(getFacesContext().getELContext(), "Jerry"); valueExpression = this.create("TestBean[\"inner\"].customers[1]"); valueExpression.setValue(getFacesContext().getELContext(), "Mickey"); valueExpression = this.create("TestBean[\"inner\"].customers[0]"); customer0 = (String) valueExpression.getValue(getFacesContext().getELContext()); valueExpression = this.create("TestBean[\"inner\"].customers[1]"); customer1 = (String) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(customer0.equals("Jerry")); assertTrue(customer1.equals("Mickey")); valueExpression = this.create("TestBean[\"inner\"].customers[0]"); assertTrue(valueExpression.getValue(getFacesContext().getELContext()) != oldCustomer0); valueExpression = this.create("TestBean[\"inner\"].customers[1]"); assertTrue(valueExpression.getValue(getFacesContext().getELContext()) != oldCustomer1); // put in a map to the customers Collection Inner2Bean inner2 = new Inner2Bean(); assertTrue(null == inner2.getNicknames().get("foo")); valueExpression = this.create("TestBean[\"inner\"].customers[2]"); valueExpression.setValue(getFacesContext().getELContext(), inner2); valueExpression = this.create("TestBean[\"inner\"].customers[2]"); assertTrue(valueExpression.getValue(getFacesContext().getELContext()) == inner2); valueExpression = this .create("TestBean[\"inner\"].customers[2].nicknames.foo"); valueExpression.setValue(getFacesContext().getELContext(), "bar"); assertTrue(((String) inner2.getNicknames().get("foo")).equals("bar")); // ensure we can call setValue() successfully if the bean isn't already // in scope at the time of invocation Map sm = getFacesContext().getExternalContext().getSessionMap(); sm.remove("mixedBean"); valueExpression = this.create("mixedBean.prop"); valueExpression.setValue(getFacesContext().getELContext(), "passed"); assertTrue("passed".equals(valueExpression.getValue(getFacesContext().getELContext()))); request.removeAttribute("testBean2"); request.removeAttribute("customerBean"); valueExpression = this.create("testBean2.customerBean"); CustomerBean cb = new CustomerBean(); cb.setName("bill"); valueExpression.setValue(getFacesContext().getELContext(), cb); testBean = (TestBean) request.getAttribute("testBean2"); assertNull(request.getAttribute("customerBean")); assertNotNull(testBean); cb = testBean.getCustomerBean(); assertEquals("bill", cb.getName()); } public void testNullReference() throws Exception { boolean exceptionThrown = false; // no exception should be thrown as per the EL spec if expression is null. try { getFacesContext().getApplication().getExpressionFactory(). createValueExpression(getFacesContext().getELContext(),null, Object.class); } catch (NullPointerException npe) { exceptionThrown = false; } catch (ELException ee) { exceptionThrown= true; }; assertTrue(exceptionThrown); } public void testLiterals() throws Exception { ValueExpression vb = null; Object result = null; ExternalContext extContext = getFacesContext().getExternalContext(); vb = getFacesContext().getApplication().getExpressionFactory(). createValueExpression(getFacesContext().getELContext(),"test", Object.class); assertEquals("test", vb.getValue(getFacesContext().getELContext())); assertEquals(String.class, vb.getType(getFacesContext().getELContext())); try { vb.setValue(getFacesContext().getELContext(), "other"); fail("Literal's setValue(..) should have thrown a EvaluationException"); } catch (javax.el.ELException ee) {} } public void testReadOnly_singleCase() throws Exception { // these are mutable Maps /* * properties on these maps are mutable, but not the object itself.... * see */ valueExpression = this.create("applicationScope"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("sessionScope"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("requestScope"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("viewScope"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); // these are immutable Maps valueExpression = this.create("param"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("paramValues"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("header"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("headerValues"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("cookie"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("initParam"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); } public void testReadOnly_multipleCase() throws Exception { // these are mutable Maps valueExpression = this.create("applicationScope.value"); valueExpression.setValue(getFacesContext().getELContext(), "value"); String value = (String) valueExpression.getValue(getFacesContext().getELContext()); assertTrue(!valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("sessionScope.value"); assertTrue(!valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("requestScope.value"); assertTrue(!valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("viewScope.value"); assertTrue(!valueExpression.isReadOnly(getFacesContext().getELContext())); // these are immutable Maps valueExpression = this.create("param.value"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("paramValues.value"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("header.value"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("headerValues.value"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("cookie.value"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("initParam.value"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); // tree // create a dummy root for the tree. UIViewRoot page = Util.getViewHandler(getFacesContext()).createView( getFacesContext(), null); page.setId("root"); page.setViewId("newTree"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); valueExpression = this.create("view.childCount"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); com.sun.faces.cactus.TestBean testBean = (com.sun.faces.cactus.TestBean) getFacesContext().getExternalContext() .getSessionMap().get("TestBean"); assertTrue(null != testBean); valueExpression = this.create("TestBean.readOnly"); assertTrue(valueExpression.isReadOnly(getFacesContext().getELContext())); valueExpression = this.create("TestBean.one"); assertTrue(!valueExpression.isReadOnly(getFacesContext().getELContext())); InnerBean inner = new InnerBean(); testBean.setInner(inner); valueExpression = this.create("TestBean[\"inner\"].customers[1]"); assertTrue(!valueExpression.isReadOnly(getFacesContext().getELContext())); } public void testGetType_singleCase() throws Exception { // these are mutable Maps valueExpression = this.create("applicationScope"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); valueExpression = this.create("sessionScope"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); valueExpression = this.create("requestScope"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); valueExpression = this.create("viewScope"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); // these are immutable Maps valueExpression = this.create("param"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); valueExpression = this.create("paramValues"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); valueExpression = this.create("header"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); valueExpression = this.create("headerValues"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); valueExpression = this.create("cookie"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); valueExpression = this.create("initParam"); assertTrue(valueExpression.getType(getFacesContext().getELContext()) == null); } public void beginGetType_multipleCase(WebRequest theRequest) { populateRequest(theRequest); } public void testGetType_multipleCase() throws Exception { String property = "testValueExpressionImpl_property"; getFacesContext().getExternalContext().getApplicationMap().put( property, property); getFacesContext().getExternalContext().getSessionMap().put(property, property); getFacesContext().getExternalContext().getRequestMap().put(property, property); getFacesContext().getViewRoot().getViewMap().put(property, property); // these are mutable Maps valueExpression = this.create("applicationScope." + property); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); valueExpression = this.create("sessionScope." + property); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); valueExpression = this.create("requestScope." + property); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); valueExpression = this.create("viewScope." + property); valueExpression.setValue(getFacesContext().getELContext(), property); assertTrue(getFacesContext().getViewRoot().getViewMap().containsKey(property)); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); // these are immutable Maps valueExpression = this.create("param." + "ELParam"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); valueExpression = this.create("paramValues.multiparam"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); valueExpression = this.create("header.ELHeader"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); valueExpression = this.create("headerValues.multiheader"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); // assertTrue(java.util.Enumeration.class.isAssignableFrom(valueExpression // .getType(getFacesContext().getELContext()))); // PENDING(craigmcc) - Comment out this test because on my platform // the getRequestCookies() call returns null /* * valueExpression = this.create("cookie.cookie"); * assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals("javax.servlet.http.Cookie")); */ valueExpression = this .create("initParam['javax.faces.STATE_SAVING_METHOD']"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); // tree // create a dummy root for the tree. UIViewRoot page = Util.getViewHandler(getFacesContext()).createView( getFacesContext(), null); page.setId("root"); page.setViewId("newTree"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); valueExpression = this.create("view"); Class c = valueExpression.getType(getFacesContext().getELContext()); assertTrue(c == null); com.sun.faces.cactus.TestBean testBean = (com.sun.faces.cactus.TestBean) getFacesContext().getExternalContext() .getSessionMap().get("TestBean"); assertTrue(null != testBean); valueExpression = this.create("TestBean.readOnly"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.String")); valueExpression = this.create("TestBean.one"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.String")); InnerBean inner = new InnerBean(); testBean.setInner(inner); valueExpression = this.create("TestBean[\"inner\"].customers[1]"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); valueExpression = this.create("TestBean[\"inner\"]"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "com.sun.faces.cactus.TestBean$InnerBean")); int[] intArray = { 1, 2, 3 }; getFacesContext().getExternalContext().getRequestMap().put("intArray", intArray); valueExpression = this.create("requestScope.intArray"); assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( "java.lang.Object")); // assertTrue(valueExpression.getType(getFacesContext().getELContext()).getName().equals( // "[I")); } public void testGetScopePositive() throws Exception { TestBean testBean = new TestBean(); getFacesContext().getExternalContext().getApplicationMap().put( "TestApplicationBean", testBean); valueExpression = this.create("TestApplicationBean"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope("TestApplicationBean", null)); valueExpression = this.create("TestApplicationBean.one"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope("TestApplicationBean.one", null)); valueExpression = this.create("TestApplicationBean.inner.two"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope( "TestApplicationBean.inner.two", null)); valueExpression = this.create("applicationScope.TestApplicationBean"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope( "applicationScope.TestApplicationBean", null)); valueExpression = this .create("applicationScope.TestApplicationBean.inner.two"); assertEquals(ELUtils.Scope.APPLICATION, ELUtils.getScope( "applicationScope.TestApplicationBean.inner.two", null)); getFacesContext().getExternalContext().getSessionMap().put( "TestSessionBean", testBean); valueExpression = this.create("TestSessionBean"); assertEquals(ELUtils.Scope.SESSION, ELUtils.getScope("TestSessionBean", null)); valueExpression = this.create("TestSessionBean.one"); assertEquals(ELUtils.Scope.SESSION, ELUtils.getScope("TestSessionBean.one", null)); valueExpression = this.create("TestSessionBean.inner.two"); assertEquals(ELUtils.Scope.SESSION, ELUtils .getScope("TestSessionBean.inner.two", null)); valueExpression = this.create("sessionScope.TestSessionBean"); assertEquals(ELUtils.Scope.SESSION, ELUtils.getScope("sessionScope.TestSessionBean", null)); valueExpression = this.create("sessionScope.TestSessionBean.inner.two"); assertEquals(ELUtils.Scope.SESSION, ELUtils.getScope( "sessionScope.TestSessionBean.inner.two", null)); getFacesContext().getExternalContext().getRequestMap().put( "TestRequestBean", testBean); valueExpression = this.create("TestRequestBean"); assertEquals(ELUtils.Scope.REQUEST, ELUtils.getScope("TestRequestBean", null)); valueExpression = this.create("TestRequestBean.one"); assertEquals(ELUtils.Scope.REQUEST, ELUtils.getScope("TestRequestBean.one", null)); valueExpression = this.create("TestRequestBean.inner.two"); assertEquals(ELUtils.Scope.REQUEST, ELUtils .getScope("TestRequestBean.inner.two", null)); valueExpression = this.create("requestScope.TestRequestBean"); assertEquals(ELUtils.Scope.REQUEST, ELUtils.getScope("requestScope.TestRequestBean", null)); valueExpression = this.create("requestScope.TestRequestBean.inner.two"); assertEquals(ELUtils.Scope.REQUEST, ELUtils.getScope( "requestScope.TestRequestBean.inner.two", null)); assertEquals(ELUtils.Scope.VIEW, ELUtils.getScope("viewScope.foo", null)); valueExpression = this.create("TestNoneBean"); assertNull(ELUtils.getScope("TestNoneBean", null)); valueExpression = this.create("TestNoneBean.one"); assertNull(ELUtils.getScope("TestNoneBean.one", null)); valueExpression = this.create("TestNoneBean.inner.two"); assertNull(ELUtils.getScope("TestNoneBean.inner.two", null)); } public void testGetScopeNegative() throws Exception { ValueExpression valueExpression = null; String property = null; /* property = "[]"; valueExpression = this.factory.createValueExpression(property); assertNull(Util.getScope(property, null)); property = "]["; assertNull(Util.getScope(property, null)); property = ""; assertNull(Util.getScope(property, null)); property = null; assertNull(Util.getScope(property, null)); property = "foo.sessionScope"; assertNull(Util.getScope(property, null)); */ } // negative test for case when valueRef is merely // one of the reserved scope names. public void testReservedScopeIdentifiers() throws Exception { boolean exceptionThrown = false; try { valueExpression = this.create("applicationScope"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("sessionScope"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("requestScope"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("facesContext"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("cookie"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("header"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("headerValues"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("initParam"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("param"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("paramValues"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("view"); valueExpression.setValue(getFacesContext().getELContext(), "value"); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testInvalidExpression() throws Exception { boolean exceptionThrown = false; try { valueExpression = this.create(""); valueExpression.getValue(getFacesContext().getELContext()); } catch (ELException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("!"); valueExpression.getValue(getFacesContext().getELContext()); } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create(".."); valueExpression.getValue(getFacesContext().getELContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create(".foo"); valueExpression.getValue(getFacesContext().getELContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("()"); valueExpression.getValue(getFacesContext().getELContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("[]"); valueExpression.getValue(getFacesContext().getELContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("applicationScope}"); valueExpression.getValue(getFacesContext().getELContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (ELException ee) { exceptionThrown = true; } assertTrue(!exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("applicationScope >= sessionScope"); valueExpression.getValue(getFacesContext().getELContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { valueExpression = this.create("foo applicationScope"); valueExpression.getValue(getFacesContext().getELContext()); } catch (PropertyNotFoundException e) { exceptionThrown = true; } catch (ELException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); } /* public void testStateHolderSmall() throws Exception { StateHolderSaver saver = null; ValueExpression binding = getFacesContext().getApplication().getExpressionFactory(). createValueExpression("#{TestBean.indexProperties[0]}", Object.class, null); assertEquals("ValueExpression not expected value", "Justyna", (String) binding.getValue(getFacesContext().getELContext())); saver = new StateHolderSaver(getFacesContext(), binding); binding = null; binding = (ValueExpression) saver.restore(getFacesContext()); assertEquals("ValueExpression not expected value", "Justyna", (String) binding.getValue(getFacesContext().getELContext())); } public void testStateHolderMedium() throws Exception { UIViewRoot root = null; UIForm form = null; UIInput input = null; Object state = null; getFacesContext().setViewRoot( root = Util.getViewHandler(getFacesContext()).createView( getFacesContext(), null)); root.getChildren().add(form = new UIForm()); form.getChildren().add(input = new UIInput()); input.setValueExpression("buckaroo", (getFacesContext().getApplication().getExpressionFactory(). createValueExpression("#{TestBean.indexProperties[0]}", Object.class, null))); state = root.processSaveState(getFacesContext()); // synthesize the tree structure getFacesContext().setViewRoot( root = Util.getViewHandler(getFacesContext()).createView( getFacesContext(), null)); root.getChildren().add(form = new UIForm()); form.getChildren().add(input = new UIInput()); root.processRestoreState(getFacesContext(), state); assertEquals("ValueExpression not expected value", "Justyna", (String) input.createValueExpression("buckaroo").getValue( getFacesContext().getELContext())); } */ public void testGetExpressionString() throws Exception { ApplicationImpl app = (ApplicationImpl) getFacesContext() .getApplication(); String ref = null; ValueExpression vb = null; ref = "#{NewCustomerFormHandler.minimumAge}"; vb = app.getExpressionFactory().createValueExpression(getFacesContext().getELContext(),ref, Object.class); assertEquals(ref, vb.getExpressionString()); ref = "minimum age is #{NewCustomerFormHandler.minimumAge}"; vb = app.getExpressionFactory().createValueExpression(getFacesContext().getELContext(),ref, Object.class); assertEquals(ref, vb.getExpressionString()); } class StateHolderSaver extends Object implements Serializable { protected String className = null; protected Object savedState = null; public StateHolderSaver(FacesContext context, Object toSave) { className = toSave.getClass().getName(); if (toSave instanceof StateHolder) { // do not save an attached object that is marked transient. if (!((StateHolder) toSave).isTransient()) { savedState = ((StateHolder) toSave).saveState(context); } else { className = null; } } } /** * @return the restored {@link StateHolder}instance. */ public Object restore(FacesContext context) throws IllegalStateException { Object result = null; Class toRestoreClass = null; if (className == null) { return null; } try { toRestoreClass = loadClass(className, this); } catch (ClassNotFoundException e) { System.out.println("ClassNotFound Exception"); throw new IllegalStateException(e.getMessage()); } if (null != toRestoreClass) { try { result = toRestoreClass.newInstance(); } catch (InstantiationException e) { System.out.println("Instantiation Exception"); e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } catch (IllegalAccessException a) { System.out.println("IleegalAccess Exception"); throw new IllegalStateException(a.getMessage()); } } if (null != result && null != savedState && result instanceof StateHolder) { // don't need to check transient, since that was done on // the saving side. ((StateHolder) result).restoreState(context, savedState); } return result; } private Class loadClass(String name, Object fallbackClass) throws ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = fallbackClass.getClass().getClassLoader(); } return loader.loadClass(name); } } } // end of class TestValueExpressionImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/0000755000000000000000000000000011412443350017147 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/TestUnifiedELImpl.java0000644000000000000000000010024411412443350023301 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.context.ExternalContext; import javax.el.ValueExpression; import com.sun.faces.el.impl.beans.Factory; import com.sun.faces.cactus.ServletFacesTestCase; /** * @author jhook */ public class TestUnifiedELImpl extends ServletFacesTestCase { /** * */ public TestUnifiedELImpl() { super(); } /** * @param name */ public TestUnifiedELImpl(String name) { super(name); } protected Object evaluate(String ref) throws Exception { ValueExpression ve = this.getFacesContext().getApplication(). getExpressionFactory().createValueExpression(getFacesContext().getELContext(),ref, Object.class); return ve.getValue(this.getFacesContext().getELContext()); } public void testELEvaluation() throws Exception { /* setup our test date */ Bean1 b = this.createBean1(); getExternalContext().getRequestMap().put("bean1a", b); getExternalContext().getSessionMap().put("val1c", "session-scoped1"); getExternalContext().getRequestMap().put("val1b", "request-scoped1"); getExternalContext().getApplicationMap().put("val1d", "app-scoped1"); Map m = new HashMap(); m.put("emptyArray", new Object[0]); m.put("nonemptyArray", new Object[] { "abc" }); m.put("emptyList", new ArrayList()); { List l = new ArrayList(); l.add("hello"); m.put("nonemptyList", l); } m.put("emptyMap", new HashMap()); { Map m2 = new HashMap(); m2.put("a", "a"); m.put("nonemptyMap", m2); } m.put("emptySet", new HashSet()); { Set s = new HashSet(); s.add("hello"); m.put("nonemptySet", s); } getExternalContext().getRequestMap().put("emptyTests", m); getExternalContext().getRequestMap().put("pbean1", Factory.createBean1()); getExternalContext().getRequestMap().put("pbean2", Factory.createBean2()); getExternalContext().getRequestMap().put("pbean3", Factory.createBean3()); getExternalContext().getRequestMap().put("pbean4", Factory.createBean4()); getExternalContext().getRequestMap().put("pbean5", Factory.createBean5()); getExternalContext().getRequestMap().put("pbean6", Factory.createBean6()); getExternalContext().getRequestMap().put("pbean7", Factory.createBean7()); /* testing mixture of strings and expressions */ evaluateTest("abc", "abc"); evaluateTest("${ 3}", new Long(3)); evaluateTestFailure("a${"); evaluateTest("a${ 5 }", "a5"); evaluateTest("${ 3 }b", "3b"); evaluateTest("${ 1 }${ 2 }", "12"); evaluateTest("abc ${ 1} ${ 2} def", "abc 1 2 def"); /* testing values that end with or contain "$" */ evaluateTest("$", "$"); evaluateTest("\\$", "$"); evaluateTest("$ ", "$ "); evaluateTest("test$", "test$"); evaluateTest("$test", "$test"); evaluateTest("test$test", "test$test"); evaluateTest("test$$$", "test$$$"); evaluateTest("test$$${ 34 }", "test$$34"); evaluateTest("test$$${ 34 }$$", "test$$34$$"); evaluateTest("test$${ 34 }", "test$34"); evaluateTest("$${ 34 }", "$34"); evaluateTest("$$", "$$"); evaluateTest("test$$", "test$$"); evaluateTest("test$$test", "test$$test"); evaluateTest("${ 34 }$${ 34 }", "34$34"); /* basic literals */ evaluateTest("${1}", new Long(1)); evaluateTest("${-12}", new Long(-12)); evaluateTest("${true}", Boolean.TRUE); evaluateTest("${false}", Boolean.FALSE); evaluateTest("${null}", null); evaluateTest("${4.2}", new Double(4.2)); evaluateTest("${-21.3}", new Double(-21.3)); evaluateTest("${4.}", new Double(4.0)); evaluateTest("${.21}", new Double(0.21)); evaluateTest("${3e-1}", new Double(0.3)); evaluateTest("${.2222222222}", new Double(0.2222222222)); /* basic relationals between literals */ evaluateTest("${1 < 2}", Boolean.TRUE); evaluateTest("${1 > 2}", Boolean.FALSE); evaluateTest("${1 >= 2}", Boolean.FALSE); evaluateTest("${1 <= 2}", Boolean.TRUE); evaluateTest("${1 == 2}", Boolean.FALSE); evaluateTest("${1 != 2}", Boolean.TRUE); evaluateTest("${3 >= 3}", Boolean.TRUE); evaluateTest("${3 <= 3}", Boolean.TRUE); evaluateTest("${3 == 3}", Boolean.TRUE); evaluateTest("${3 < 3}", Boolean.FALSE); evaluateTest("${3 > 3}", Boolean.FALSE); evaluateTest("${3 != 3}", Boolean.FALSE); // PENDING (visvan) check with Kinman/Jacob /* relationals between booleans evaluateTestFailure("${false < true}"); evaluateTestFailure("${false > true}"); evaluateTest("${true >= true}", Boolean.TRUE); evaluateTest("${true <= true}", Boolean.TRUE); evaluateTest("${true == true}", Boolean.TRUE); evaluateTest("${true != true}", Boolean.FALSE); */ /* looking up objects in scopes */ evaluateTest("${requestScope.val1b}", "request-scoped1"); evaluateTest("${sessionScope.val1b}", null); evaluateTest("${applicationScope.val1b}", null); evaluateTest("${val1b}", "request-scoped1"); evaluateTest("${requestScope.val1c}", null); evaluateTest("${sessionScope.val1c}", "session-scoped1"); evaluateTest("${applicationScope.val1c}", null); evaluateTest("${val1c}", "session-scoped1"); evaluateTest("${requestScope.val1d}", null); evaluateTest("${sessionScope.val1d}", null); evaluateTest("${applicationScope.val1d}", "app-scoped1"); evaluateTest("${val1d}", "app-scoped1"); /* accessing properties */ evaluateTest("${bean1a.int1}", new Integer(b.getInt1())); evaluateTest("${bean1a.boolean1}", Boolean.valueOf(b.getBoolean1())); evaluateTest("${bean1a.string1}", b.getString1()); evaluateTest("${bean1a.bean1.int2}", b.getBean1().getInt2()); evaluateTest("${bean1a.bean1.bean2.string2}", b.getBean1().getBean2() .getString2()); evaluateTest("${bean1a.byte1}", new Byte(b.getByte1())); evaluateTest("${bean1a.char1}", new Character(b.getChar1())); evaluateTest("${bean1a.short1}", new Short(b.getShort1())); evaluateTest("${bean1a.long1}", new Long(b.getLong1())); evaluateTest("${bean1a.float1}", new Float(b.getFloat1())); evaluateTest("${bean1a.double1}", new Double(b.getDouble1())); /* test the entire relational comparison type promotion matrix */ evaluateTest("${bean1a.byte1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("${bean1a.byte1 < bean1a.char1}", Boolean.TRUE); evaluateTest("${bean1a.byte1 < bean1a.short1}", Boolean.TRUE); evaluateTest("${bean1a.byte1 < bean1a.int1}", Boolean.FALSE); evaluateTest("${bean1a.byte1 < bean1a.long1}", Boolean.TRUE); evaluateTest("${bean1a.byte1 < bean1a.float1}", Boolean.TRUE); evaluateTest("${bean1a.byte1 < bean1a.double1}", Boolean.TRUE); evaluateTest("${bean1a.char1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("${bean1a.char1 < bean1a.char1}", Boolean.FALSE); evaluateTest("${bean1a.char1 < bean1a.short1}", Boolean.FALSE); evaluateTest("${bean1a.char1 < bean1a.int1}", Boolean.FALSE); evaluateTest("${bean1a.char1 < bean1a.long1}", Boolean.FALSE); evaluateTest("${bean1a.char1 < bean1a.float1}", Boolean.FALSE); evaluateTest("${bean1a.char1 < bean1a.double1}", Boolean.FALSE); evaluateTest("${bean1a.short1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("${bean1a.short1 < bean1a.char1}", Boolean.FALSE); evaluateTest("${bean1a.short1 < bean1a.short1}", Boolean.FALSE); evaluateTest("${bean1a.short1 < bean1a.int1}", Boolean.FALSE); evaluateTest("${bean1a.short1 < bean1a.float1}", Boolean.FALSE); evaluateTest("${bean1a.short1 < bean1a.long1}", Boolean.FALSE); evaluateTest("${bean1a.short1 < bean1a.double1}", Boolean.FALSE); evaluateTest("${bean1a.int1 < bean1a.byte1}", Boolean.TRUE); evaluateTest("${bean1a.int1 < bean1a.char1}", Boolean.TRUE); evaluateTest("${bean1a.int1 < bean1a.short1}", Boolean.TRUE); evaluateTest("${bean1a.int1 < bean1a.int1}", Boolean.FALSE); evaluateTest("${bean1a.int1 < bean1a.long1}", Boolean.TRUE); evaluateTest("${bean1a.int1 < bean1a.float1}", Boolean.TRUE); evaluateTest("${bean1a.int1 < bean1a.double1}", Boolean.TRUE); evaluateTest("${bean1a.long1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("${bean1a.long1 < bean1a.char1}", Boolean.FALSE); evaluateTest("${bean1a.long1 < bean1a.short1}", Boolean.FALSE); evaluateTest("${bean1a.long1 < bean1a.int1}", Boolean.FALSE); evaluateTest("${bean1a.long1 < bean1a.long1}", Boolean.FALSE); evaluateTest("${bean1a.long1 < bean1a.float1}", Boolean.FALSE); evaluateTest("${bean1a.long1 < bean1a.double1}", Boolean.FALSE); evaluateTest("${bean1a.float1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("${bean1a.float1 < bean1a.char1}", Boolean.TRUE); evaluateTest("${bean1a.float1 < bean1a.short1}", Boolean.TRUE); evaluateTest("${bean1a.float1 < bean1a.int1}", Boolean.FALSE); evaluateTest("${bean1a.float1 < bean1a.long1}", Boolean.TRUE); evaluateTest("${bean1a.float1 < bean1a.float1}", Boolean.FALSE); evaluateTest("${bean1a.float1 < bean1a.double1}", Boolean.TRUE); evaluateTest("${bean1a.double1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("${bean1a.double1 < bean1a.char1}", Boolean.TRUE); evaluateTest("${bean1a.double1 < bean1a.short1}", Boolean.TRUE); evaluateTest("${bean1a.double1 < bean1a.int1}", Boolean.FALSE); evaluateTest("${bean1a.double1 < bean1a.long1}", Boolean.TRUE); evaluateTest("${bean1a.double1 < bean1a.float1}", Boolean.FALSE); evaluateTest("${bean1a.double1 < bean1a.double1}", Boolean.FALSE); /* test other relational comparison rules */ evaluateTest("${null == null}", Boolean.TRUE); evaluateTest("${noSuchAttribute == noSuchAttribute}", Boolean.TRUE); evaluateTest("${noSuchAttribute == null}", Boolean.TRUE); evaluateTest("${null == noSuchAttribute}", Boolean.TRUE); evaluateTest("${bean1a == null}", Boolean.FALSE); evaluateTest("${null == bean1a}", Boolean.FALSE); evaluateTest("${bean1a == bean1a}", Boolean.TRUE); evaluateTest("${bean1a > \"hello\"}", Boolean.FALSE); evaluateTestFailure("${bean1a.bean1 < 14}"); evaluateTest("${bean1a.bean1 == \"hello\"}", Boolean.FALSE); /* test String comparisons */ evaluateTest("${bean1a.string1 == \"hello\"}", Boolean.TRUE); evaluateTest("${bean1a.string1 != \"hello\"}", Boolean.FALSE); evaluateTest("${bean1a.string1 == \"goodbye\"}", Boolean.FALSE); evaluateTest("${bean1a.string1 != \"goodbye\"}", Boolean.TRUE); evaluateTest("${bean1a.string1 > \"goodbye\"}", Boolean.TRUE); evaluateTest("${\"hello\" == bean1a.string1}", Boolean.TRUE); evaluateTest("${\"goodbye\" > bean1a.string1}", Boolean.FALSE); /* test errors in property traversal */ evaluateTest("${noSuchAttribute.abc}", null); evaluateTest("${bean1a.bean2.byte1}", null); evaluateTestFailure("${bean1a.noProperty}"); evaluateTestFailure("${bean1a.noGetter}"); evaluateTestFailure("${bean1a.errorInGetter}"); evaluateTest("${bean1a.bean2.string2}", null); /* test accessing public properties from private classes */ evaluateTest("${pbean1.value}", "got the value"); evaluateTest("${pbean2.value}", "got the value"); evaluateTest("${pbean3.value}", "got the value"); evaluateTest("${pbean4.value}", "got the value"); evaluateTest("${pbean5.value}", "got the value"); evaluateTest("${pbean6.value}", "got the value"); evaluateTest("${pbean7.value}", "got the value"); /* test reserved words as identifiers */ evaluateTestFailure("${and}"); evaluateTestFailure("${or}"); evaluateTestFailure("${not}"); evaluateTestFailure("${eq}"); evaluateTestFailure("${ne}"); evaluateTestFailure("${lt}"); evaluateTestFailure("${gt}"); evaluateTestFailure("${le}"); evaluateTestFailure("${ge}"); evaluateTest("${true}", Boolean.TRUE); evaluateTest("${false}", Boolean.FALSE); evaluateTest("${null}", null); /* test reserved words as property names */ evaluateTestFailure("${bean1a.and}"); evaluateTestFailure("${bean1a.or}"); evaluateTestFailure("${bean1a.not}"); evaluateTestFailure("${bean1a.eq}"); evaluateTestFailure("${bean1a.ne}"); evaluateTestFailure("${bean1a.lt}"); evaluateTestFailure("${bean1a.gt}"); evaluateTestFailure("${bean1a.le}"); evaluateTestFailure("${bean1a.ge}"); evaluateTestFailure("${bean1a.instanceof}"); evaluateTestFailure("${bean1a.page}"); evaluateTestFailure("${bean1a.request}"); evaluateTestFailure("${bean1a.session}"); evaluateTestFailure("${bean1a.application}"); evaluateTestFailure("${bean1a.true}"); evaluateTestFailure("${bean1a.false}"); evaluateTestFailure("${bean1a.null}"); /* test arithmetic */ evaluateTest("${3+5}", new Long(8)); evaluateTest("${3-5}", new Long(-2)); evaluateTest("${3/5}", new Double(0.6)); evaluateTest("${3*5}", new Long(15)); evaluateTest("${3*5.0}", new Double(15.0)); evaluateTest("${3.0*5}", new Double(15.0)); evaluateTest("${3.0*5.0}", new Double(15.0)); evaluateTest("${225 % 17}", new Long(4)); evaluateTest("${ 1 + 2 + 3 * 5 + 6}", new Long(24)); evaluateTest("${ 1 + (2 + 3) * 5 + 6}", new Long(32)); /* test logical operators */ evaluateTest("${ true}", Boolean.TRUE); evaluateTest("${ not true}", Boolean.FALSE); evaluateTest("${ not false}", Boolean.TRUE); evaluateTest("${ not not true}", Boolean.TRUE); evaluateTest("${ not not false}", Boolean.FALSE); evaluateTest("${ true and false}", Boolean.FALSE); evaluateTest("${ true and true}", Boolean.TRUE); evaluateTest("${ false and true}", Boolean.FALSE); evaluateTest("${ false and false}", Boolean.FALSE); evaluateTest("${ true or false}", Boolean.TRUE); evaluateTest("${ true or true}", Boolean.TRUE); evaluateTest("${ false or true}", Boolean.TRUE); evaluateTest("${ false or false}", Boolean.FALSE); evaluateTest("${ false or false or false or true and false}", Boolean.FALSE); evaluateTest("${ false or false or false or true and false or true}", Boolean.TRUE); /* test indexed access operator */ evaluateTest("${ bean1a[\"double1\"] }", new Double(b.getDouble1())); evaluateTest("${ bean1a[\"double1\"].class }", Double.class); evaluateTest("${ bean1a.stringArray1[-1]}", null); evaluateTest("${ bean1a.stringArray1[0]}", b.getStringArray1()[0]); evaluateTest("${ bean1a.stringArray1[1]}", b.getStringArray1()[1]); evaluateTest("${ bean1a.stringArray1[2]}", b.getStringArray1()[2]); evaluateTest("${ bean1a.stringArray1[3]}", b.getStringArray1()[3]); evaluateTest("${ bean1a.stringArray1[4]}", null); /* Test as list accessor */ evaluateTest("${ bean1a.list1 [0] }", b.getList1().get(0)); evaluateTest("${ bean1a.list1 [1] }", b.getList1().get(1)); evaluateTest("${ bean1a.list1 [2][2] }", "string3"); /* Test as indexed property accessor */ evaluateTestFailure("${ bean1a.indexed1[-1]}"); evaluateTestFailure("${ bean1a.indexed1[0]}"); evaluateTestFailure("${ bean1a.indexed1[1]}"); evaluateTestFailure("${ bean1a.indexed1[2]}"); evaluateTestFailure("${ bean1a.indexed1[3]}"); evaluateTestFailure("${ bean1a.indexed1[4]}"); /* Test as map accessor */ evaluateTest("${ bean1a.map1.noKey }", null); evaluateTest("${ bean1a.map1.key1 }", b.getMap1().get("key1")); evaluateTest("${ bean1a.map1 [\"key1\"] }", b.getMap1().get("key1")); evaluateTest("${ bean1a.map1 [14] }", "value3"); evaluateTest("${ bean1a.map1 [2 * 7] }", "value3"); evaluateTest("${ bean1a.map1.recurse.list1[0] }", new Integer(14)); /* Test UIComponent as bean evaluateTest("${view.rendered}", Boolean.TRUE); evaluateTest("${view.attributes.rendered}", Boolean.TRUE); evaluateTest("${view.children[0].value}", "inputValue"); evaluateTest("${view.children[0].rendered}", Boolean.TRUE); */ /* test String concatenation */ evaluateTestFailure("${ \"a\" + \"bcd\" }"); evaluateTestFailure("${ \"a\" + (4*3) }"); evaluateTestFailure("${ bean1a.map1 [\"key\" + (5-4)] }"); /* test String comparisons */ evaluateTest("${ \"30\" < \"4\" }", Boolean.TRUE); evaluateTest("${ 30 < \"4\" }", Boolean.FALSE); evaluateTest("${ 30 > \"4\" }", Boolean.TRUE); evaluateTest("${ \"0004\" == \"4\" }", Boolean.FALSE); /* test relational comparison with alternate symbols */ evaluateTest("${ 4 eq 3}", Boolean.FALSE); evaluateTest("${ 4 ne 3}", Boolean.TRUE); evaluateTest("${ 4 eq 4}", Boolean.TRUE); evaluateTest("${ 4 ne 4}", Boolean.FALSE); evaluateTest("${ 4 lt 3}", Boolean.FALSE); evaluateTest("${ 4 gt 3}", Boolean.TRUE); evaluateTest("${ 4 le 3}", Boolean.FALSE); evaluateTest("${ 4 ge 3}", Boolean.TRUE); evaluateTest("${ 4 le 4}", Boolean.TRUE); evaluateTest("${ 4 ge 4}", Boolean.TRUE); /* test expressions on the left side of a value suffix */ evaluateTest("${(3).class}", Long.class); evaluateTest("${(bean1a.map1)[\"key1\"]}", "value1"); /* test String/boolean logical operators */ evaluateTest("${'true' and false}", Boolean.FALSE); evaluateTest("${'true' or true}", Boolean.TRUE); evaluateTest("${false and 'true'}", Boolean.FALSE); evaluateTest("${false or 'true'}", Boolean.TRUE); /* test empty operator */ evaluateTest("${ empty \"A\"}", Boolean.FALSE); evaluateTest("${ empty \"\" }", Boolean.TRUE); evaluateTest("${ empty null }", Boolean.TRUE); evaluateTest("${ empty false}", Boolean.FALSE); evaluateTest("${ empty 0}", Boolean.FALSE); evaluateTest("${ not empty 0}", Boolean.TRUE); evaluateTest("${ not empty empty 0}", Boolean.TRUE); evaluateTest("${ empty emptyTests.emptyArray }", Boolean.TRUE); evaluateTest("${ empty emptyTests.nonemptyArray }", Boolean.FALSE); evaluateTest("${ empty emptyTests.emptyList }", Boolean.TRUE); evaluateTest("${ empty emptyTests.nonemptyList }", Boolean.FALSE); evaluateTest("${ empty emptyTests.emptyMap }", Boolean.TRUE); evaluateTest("${ empty emptyTests.nonemptyMap }", Boolean.FALSE); evaluateTest("${ empty emptyTests.emptySet }", Boolean.TRUE); evaluateTest("${ empty emptyTests.nonemptySet }", Boolean.FALSE); /* test String arithmetic */ evaluateTest("${ \"6\" / \"3\" }", new Double(2.0)); evaluateTest("${ 3 + \"4\" }", new Long(7)); evaluateTest("${ \"4\" + 3 }", new Long(7)); evaluateTest("${ 3 + \"4.5\" }", new Double(7.5)); evaluateTest("${ \"4.5\" + 3 }", new Double(7.5)); evaluateTest("${ 3.0 + 6.0}", new Double(9.0)); evaluateTest("${ 31121.0 * 61553.0 }", new Double(1.915590913E9)); evaluateTest("${ 31121 * 61553 }", new Long(1915590913)); evaluateTest("${ 65536 * 65536 * 65536 * 32759 }", new Long("9220838762064379904")); evaluateTest("${ 9220838762064379904.0 - 9220838762064379900.0 }", new Double(0.0)); evaluateTest("${ 9220838762064379904 - 9220838762064379900 }", new Long(4)); /* test relational operators involving null */ evaluateTest("${ null == null }", Boolean.TRUE); evaluateTest("${ null != null }", Boolean.FALSE); evaluateTest("${ null > null }", Boolean.FALSE); evaluateTest("${ null < null }", Boolean.FALSE); evaluateTest("${ null >= null }", Boolean.TRUE); evaluateTest("${ null <= null }", Boolean.TRUE); evaluateTest("${ null == 3 }", Boolean.FALSE); evaluateTest("${ null != 3 }", Boolean.TRUE); evaluateTest("${ null > 3 }", Boolean.FALSE); evaluateTest("${ null < 3 }", Boolean.FALSE); evaluateTest("${ null >= 3 }", Boolean.FALSE); evaluateTest("${ null <= 3 }", Boolean.FALSE); evaluateTest("${ 3 == null }", Boolean.FALSE); evaluateTest("${ 3 != null }", Boolean.TRUE); evaluateTest("${ 3 > null }", Boolean.FALSE); evaluateTest("${ 3 < null }", Boolean.FALSE); evaluateTest("${ 3 >= null }", Boolean.FALSE); evaluateTest("${ 3 <= null }", Boolean.FALSE); evaluateTest("${ null == \"\" }", Boolean.FALSE); evaluateTest("${ null != \"\" }", Boolean.TRUE); evaluateTest("${ \"\" == null }", Boolean.FALSE); evaluateTest("${ \"\" != null }", Boolean.TRUE); /* arithmetic operators involving Strings */ evaluateTest("${ 4 + 3 }", new Long(7)); evaluateTest("${ 4.0 + 3 }", new Double(7.0)); evaluateTest("${ 4 + 3.0 }", new Double(7.0)); evaluateTest("${ 4.0 + 3.0 }", new Double(7.0)); evaluateTest("${ \"4\" + 3 }", new Long(7)); evaluateTest("${ \"4.0\" + 3 }", new Double(7.0)); evaluateTest("${ \"4\" + 3.0 }", new Double(7.0)); evaluateTest("${ \"4.0\" + 3.0 }", new Double(7.0)); evaluateTest("${ 4 + \"3\" }", new Long(7)); evaluateTest("${ 4.0 + \"3\" }", new Double(7.0)); evaluateTest("${ 4 + \"3.0\" }", new Double(7.0)); evaluateTest("${ 4.0 + \"3.0\" }", new Double(7.0)); evaluateTest("${ \"4\" + \"3\" }", new Long(7)); evaluateTest("${ \"4.0\" + \"3\" }", new Double(7.0)); evaluateTest("${ \"4\" + \"3.0\" }", new Double(7.0)); evaluateTest("${ \"4.0\" + \"3.0\" }", new Double(7.0)); evaluateTest("${ 4 - 3 }", new Long(1)); evaluateTest("${ 4.0 - 3 }", new Double(1.0)); evaluateTest("${ 4 - 3.0 }", new Double(1.0)); evaluateTest("${ 4.0 - 3.0 }", new Double(1.0)); evaluateTest("${ \"4\" - 3 }", new Long(1)); evaluateTest("${ \"4.0\" - 3 }", new Double(1.0)); evaluateTest("${ \"4\" - 3.0 }", new Double(1.0)); evaluateTest("${ \"4.0\" - 3.0 }", new Double(1.0)); evaluateTest("${ 4 - \"3\" }", new Long(1)); evaluateTest("${ 4.0 - \"3\" }", new Double(1.0)); evaluateTest("${ 4 - \"3.0\" }", new Double(1.0)); evaluateTest("${ 4.0 - \"3.0\" }", new Double(1.0)); evaluateTest("${ \"4\" - \"3\" }", new Long(1)); evaluateTest("${ \"4.0\" - \"3\" }", new Double(1.0)); evaluateTest("${ \"4\" - \"3.0\" }", new Double(1.0)); evaluateTest("${ \"4.0\" - \"3.0\" }", new Double(1.0)); evaluateTest("${ 4 * 3 }", new Long(12)); evaluateTest("${ 4.0 * 3 }", new Double(12.0)); evaluateTest("${ 4 * 3.0 }", new Double(12.0)); evaluateTest("${ 4.0 * 3.0 }", new Double(12.0)); evaluateTest("${ \"4\" * 3 }", new Long(12)); evaluateTest("${ \"4.0\" * 3 }", new Double(12.0)); evaluateTest("${ \"4\" * 3.0 }", new Double(12.0)); evaluateTest("${ \"4.0\" * 3.0 }", new Double(12.0)); evaluateTest("${ 4 * \"3\" }", new Long(12)); evaluateTest("${ 4.0 * \"3\" }", new Double(12.0)); evaluateTest("${ 4 * \"3.0\" }", new Double(12.0)); evaluateTest("${ 4.0 * \"3.0\" }", new Double(12.0)); evaluateTest("${ \"4\" * \"3\" }", new Long(12)); evaluateTest("${ \"4.0\" * \"3\" }", new Double(12.0)); evaluateTest("${ \"4\" * \"3.0\" }", new Double(12.0)); evaluateTest("${ \"4.0\" * \"3.0\" }", new Double(12.0)); evaluateTest("${ 4 / 3 }", new Double(4.0 / 3.0)); evaluateTest("${ 4.0 / 3 }", new Double(4.0 / 3.0)); evaluateTest("${ 4 / 3.0 }", new Double(4.0 / 3.0)); evaluateTest("${ 4.0 / 3.0 }", new Double(4.0 / 3.0)); evaluateTest("${ \"4\" / 3 }", new Double(4.0 / 3.0)); evaluateTest("${ \"4.0\" / 3 }", new Double(4.0 / 3.0)); evaluateTest("${ \"4\" / 3.0 }", new Double(4.0 / 3.0)); evaluateTest("${ \"4.0\" / 3.0 }", new Double(4.0 / 3.0)); evaluateTest("${ 4 / \"3\" }", new Double(4.0 / 3.0)); evaluateTest("${ 4.0 / \"3\" }", new Double(4.0 / 3.0)); evaluateTest("${ 4 / \"3.0\" }", new Double(4.0 / 3.0)); evaluateTest("${ 4.0 / \"3.0\" }", new Double(4.0 / 3.0)); evaluateTest("${ \"4\" / \"3\" }", new Double(4.0 / 3.0)); evaluateTest("${ \"4.0\" / \"3\" }", new Double(4.0 / 3.0)); evaluateTest("${ \"4\" / \"3.0\" }", new Double(4.0 / 3.0)); evaluateTest("${ \"4.0\" / \"3.0\" }", new Double(4.0 / 3.0)); evaluateTest("${ 4 % 3 }", new Long(1)); evaluateTest("${ 4.0 % 3 }", new Double(1.0)); evaluateTest("${ 4 % 3.0 }", new Double(1.0)); evaluateTest("${ 4.0 % 3.0 }", new Double(1.0)); evaluateTest("${ \"4\" % 3 }", new Long(1)); evaluateTest("${ \"4.0\" % 3 }", new Double(1.0)); evaluateTest("${ \"4\" % 3.0 }", new Double(1.0)); evaluateTest("${ \"4.0\" % 3.0 }", new Double(1.0)); evaluateTest("${ 4 % \"3\" }", new Long(1)); evaluateTest("${ 4.0 % \"3\" }", new Double(1.0)); evaluateTest("${ 4 % \"3.0\" }", new Double(1.0)); evaluateTest("${ 4.0 % \"3.0\" }", new Double(1.0)); evaluateTest("${ \"4\" % \"3\" }", new Long(1)); evaluateTest("${ \"4.0\" % \"3\" }", new Double(1.0)); evaluateTest("${ \"4\" % \"3.0\" }", new Double(1.0)); evaluateTest("${ \"4.0\" % \"3.0\" }", new Double(1.0)); evaluateTest("${ \"8\" / \"2\" }", new Double(4.0)); evaluateTest("${ \"4e2\" + \"3\" }", new Double(403)); evaluateTest("${ \"4\" + \"3e2\" }", new Double(304)); evaluateTest("${ \"4e2\" + \"3e2\" }", new Double(700)); /* unary minus operator involving Strings */ evaluateTest("${ -3 }", new Long(-3)); evaluateTest("${ -3.0 }", new Double(-3.0)); evaluateTest("${ -\"3\" }", new Long(-3)); evaluateTest("${ -\"3.0\" }", new Double(-3)); evaluateTest("${ -\"3e2\" }", new Double(-300)); } protected Bean1 createBean1() { Bean1 b1 = new Bean1(); b1.setBoolean1(true); b1.setByte1((byte) 12); b1.setShort1((short) 98); b1.setChar1('b'); b1.setInt1(4); b1.setLong1(98); b1.setFloat1((float) 12.4); b1.setDouble1(89.224); b1.setString1("hello"); b1.setStringArray1(new String[] { "string1", "string2", "string3", "string4" }); { List l = new ArrayList(); l.add(new Integer(14)); l.add("another value"); l.add(b1.getStringArray1()); b1.setList1(l); } { Map m = new HashMap(); m.put("key1", "value1"); m.put(new Integer(14), "value2"); m.put(new Long(14), "value3"); m.put("recurse", b1); b1.setMap1(m); } Bean1 b2 = new Bean1(); b2.setInt2(new Integer(-224)); b2.setString2("bean2's string"); b1.setBean1(b2); Bean1 b3 = new Bean1(); b3.setDouble1(1422.332); b3.setString2("bean3's string"); b2.setBean2(b3); return b1; } public ExternalContext getExternalContext() { return getFacesContext().getExternalContext(); } public void evaluateTestFailure(String ref) throws Exception { try { this.evaluate(ref); fail("'" + ref + "' should have thrown an exception"); } catch (Exception e) { // do nothing } } public void evaluateTest(String ref, Object expectedValue) throws Exception { Object returnedValue = this.evaluate(ref); if (returnedValue != null) { Class expectedType = expectedValue.getClass(); Class returnedType = returnedValue.getClass(); String msg = "'" + ref + "' expected [" + expectedValue + "] of type " + expectedType.getName() + ", but returned [" + returnedValue + "] of type " + returnedType.getName(); assertTrue(msg, expectedType.isAssignableFrom(returnedType)); assertEquals(msg, expectedValue, returnedValue); } else { String msg = "'" + ref + "' expected value [" + expectedValue + "], but returned [" + returnedValue + "]"; assertEquals(msg, expectedValue, returnedValue); } } }mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/PageContextImpl.jsp120000644000000000000000000002106411412443350023076 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl; import java.util.HashMap; import java.util.Map; import javax.servlet.jsp.PageContext; import java.util.Enumeration; import javax.servlet.ServletResponse; import javax.servlet.ServletRequest; import javax.servlet.jsp.JspWriter; import javax.servlet.http.HttpSession; import java.util.Collections; import javax.servlet.ServletContext; import javax.servlet.ServletConfig; import javax.servlet.Servlet; /** * *

This is a "dummy" implementation of PageContext whose only * purpose is to serve the attribute getter/setter API's. * * @author Nathan Abramson - Art Technology Group * @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: eburns $ **/ public class PageContextImpl extends PageContext { //------------------------------------- // Properties //------------------------------------- //------------------------------------- // Member variables //------------------------------------- Map mPage = Collections.synchronizedMap (new HashMap ()); Map mRequest = Collections.synchronizedMap (new HashMap ()); Map mSession = Collections.synchronizedMap (new HashMap ()); Map mApp = Collections.synchronizedMap (new HashMap ()); //------------------------------------- /** * * Constructor **/ public PageContextImpl () { } //------------------------------------- // PageContext methods //------------------------------------- public void initialize (Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needSession, int bufferSize, boolean autoFlush) { } //------------------------------------- public void release () { } //------------------------------------- public void setAttribute (String name, Object attribute) { mPage.put (name, attribute); } //------------------------------------- public void setAttribute (String name, Object attribute, int scope) { switch (scope) { case PAGE_SCOPE: mPage.put (name, attribute); break; case REQUEST_SCOPE: mRequest.put (name, attribute); break; case SESSION_SCOPE: mSession.put (name, attribute); break; case APPLICATION_SCOPE: mApp.put (name, attribute); break; default: throw new IllegalArgumentException ("Bad scope " + scope); } } //------------------------------------- public Object getAttribute (String name) { return mPage.get (name); } //------------------------------------- public Object getAttribute (String name, int scope) { switch (scope) { case PAGE_SCOPE: return mPage.get (name); case REQUEST_SCOPE: return mRequest.get (name); case SESSION_SCOPE: return mSession.get (name); case APPLICATION_SCOPE: return mApp.get (name); default: throw new IllegalArgumentException ("Bad scope " + scope); } } //------------------------------------- public Object findAttribute (String name) { if (mPage.containsKey (name)) { return mPage.get (name); } else if (mRequest.containsKey (name)) { return mRequest.get (name); } else if (mSession.containsKey (name)) { return mSession.get (name); } else if (mApp.containsKey (name)) { return mApp.get (name); } else { return null; } } //------------------------------------- public void removeAttribute (String name) { if (mPage.containsKey (name)) { mPage.remove (name); } else if (mRequest.containsKey (name)) { mRequest.remove (name); } else if (mSession.containsKey (name)) { mSession.remove (name); } else if (mApp.containsKey (name)) { mApp.remove (name); } } //------------------------------------- public void removeAttribute (String name, int scope) { switch (scope) { case PAGE_SCOPE: mPage.remove (name); break; case REQUEST_SCOPE: mRequest.remove (name); break; case SESSION_SCOPE: mSession.remove (name); break; case APPLICATION_SCOPE: mApp.remove (name); break; default: throw new IllegalArgumentException ("Bad scope " + scope); } } //------------------------------------- public int getAttributesScope (String name) { if (mPage.containsKey (name)) { return PAGE_SCOPE; } else if (mRequest.containsKey (name)) { return REQUEST_SCOPE; } else if (mSession.containsKey (name)) { return SESSION_SCOPE; } else if (mApp.containsKey (name)) { return APPLICATION_SCOPE; } else { return 0; } } //------------------------------------- public Enumeration getAttributeNamesInScope (int scope) { return null; } //------------------------------------- public JspWriter getOut () { return null; } //------------------------------------- public HttpSession getSession () { return null; } //------------------------------------- public Object getPage () { return null; } //------------------------------------- public ServletRequest getRequest () { return null; } //------------------------------------- public ServletResponse getResponse () { return null; } //------------------------------------- public Exception getException () { return null; } //------------------------------------- public ServletConfig getServletConfig () { return null; } //------------------------------------- public ServletContext getServletContext () { return null; } //------------------------------------- public void forward (String path) { } //------------------------------------- public void include (String path) { } //------------------------------------- public void handlePageException (Exception exc) { } //------------------------------------- public void handlePageException (Throwable exc) { } //------------------------------------- } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/PageContextImpl.jsp20000644000000000000000000002157611412443350023025 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl; import java.util.HashMap; import java.util.Map; import javax.servlet.jsp.PageContext; import java.util.Enumeration; import javax.servlet.ServletResponse; import javax.servlet.ServletRequest; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.el.ExpressionEvaluator; import javax.servlet.jsp.el.VariableResolver; import javax.servlet.http.HttpSession; import java.util.Collections; import javax.servlet.ServletContext; import javax.servlet.ServletConfig; import javax.servlet.Servlet; /** * *

This is a "dummy" implementation of PageContext whose only * purpose is to serve the attribute getter/setter API's. * * @author Nathan Abramson - Art Technology Group * @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: eburns $ **/ public class PageContextImpl extends PageContext { //------------------------------------- // Properties //------------------------------------- //------------------------------------- // Member variables //------------------------------------- Map mPage = Collections.synchronizedMap (new HashMap ()); Map mRequest = Collections.synchronizedMap (new HashMap ()); Map mSession = Collections.synchronizedMap (new HashMap ()); Map mApp = Collections.synchronizedMap (new HashMap ()); //------------------------------------- /** * * Constructor **/ public PageContextImpl () { } //------------------------------------- // PageContext methods //------------------------------------- public void initialize (Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needSession, int bufferSize, boolean autoFlush) { } //------------------------------------- public void release () { } //------------------------------------- public void setAttribute (String name, Object attribute) { mPage.put (name, attribute); } //------------------------------------- public void setAttribute (String name, Object attribute, int scope) { switch (scope) { case PAGE_SCOPE: mPage.put (name, attribute); break; case REQUEST_SCOPE: mRequest.put (name, attribute); break; case SESSION_SCOPE: mSession.put (name, attribute); break; case APPLICATION_SCOPE: mApp.put (name, attribute); break; default: throw new IllegalArgumentException ("Bad scope " + scope); } } //------------------------------------- public Object getAttribute (String name) { return mPage.get (name); } //------------------------------------- public Object getAttribute (String name, int scope) { switch (scope) { case PAGE_SCOPE: return mPage.get (name); case REQUEST_SCOPE: return mRequest.get (name); case SESSION_SCOPE: return mSession.get (name); case APPLICATION_SCOPE: return mApp.get (name); default: throw new IllegalArgumentException ("Bad scope " + scope); } } //------------------------------------- public Object findAttribute (String name) { if (mPage.containsKey (name)) { return mPage.get (name); } else if (mRequest.containsKey (name)) { return mRequest.get (name); } else if (mSession.containsKey (name)) { return mSession.get (name); } else if (mApp.containsKey (name)) { return mApp.get (name); } else { return null; } } //------------------------------------- public void removeAttribute (String name) { if (mPage.containsKey (name)) { mPage.remove (name); } else if (mRequest.containsKey (name)) { mRequest.remove (name); } else if (mSession.containsKey (name)) { mSession.remove (name); } else if (mApp.containsKey (name)) { mApp.remove (name); } } //------------------------------------- public void removeAttribute (String name, int scope) { switch (scope) { case PAGE_SCOPE: mPage.remove (name); break; case REQUEST_SCOPE: mRequest.remove (name); break; case SESSION_SCOPE: mSession.remove (name); break; case APPLICATION_SCOPE: mApp.remove (name); break; default: throw new IllegalArgumentException ("Bad scope " + scope); } } //------------------------------------- public int getAttributesScope (String name) { if (mPage.containsKey (name)) { return PAGE_SCOPE; } else if (mRequest.containsKey (name)) { return REQUEST_SCOPE; } else if (mSession.containsKey (name)) { return SESSION_SCOPE; } else if (mApp.containsKey (name)) { return APPLICATION_SCOPE; } else { return 0; } } //------------------------------------- public Enumeration getAttributeNamesInScope (int scope) { return null; } //------------------------------------- public JspWriter getOut () { return null; } //------------------------------------- public HttpSession getSession () { return null; } //------------------------------------- public Object getPage () { return null; } //------------------------------------- public ServletRequest getRequest () { return null; } //------------------------------------- public ServletResponse getResponse () { return null; } //------------------------------------- public Exception getException () { return null; } //------------------------------------- public ServletConfig getServletConfig () { return null; } //------------------------------------- public ServletContext getServletContext () { return null; } //------------------------------------- public void forward (String path) { } //------------------------------------- public void include (String path) { } //------------------------------------- public void handlePageException (Exception exc) { } //------------------------------------- public void handlePageException (Throwable exc) { } //------------------------------------- // Since JSP 2.0 public void include(java.lang.String relativeUrlPath, boolean flush) {} public ExpressionEvaluator getExpressionEvaluator() { return null; } public VariableResolver getVariableResolver() { return null; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/Bean2.java0000644000000000000000000000703111412443350020742 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl; /** *

This is a test bean that holds a single String * * @author Nathan Abramson - Art Technology Group * @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: ofung $ */ public class Bean2 { //------------------------------------- // Properties //------------------------------------- // property value String mValue; public String getValue() { return mValue; } public void setValue(String pValue) { mValue = pValue; } //------------------------------------- // Member variables //------------------------------------- //------------------------------------- /** * Constructor */ public Bean2(String pValue) { mValue = pValue; } //------------------------------------- public String toString() { return ("Bean2[" + mValue + "]"); } //------------------------------------- } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/Bean2Editor.java0000644000000000000000000000624411412443350022116 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl; import java.beans.PropertyEditorSupport; /** * PropertyEditor for parsing Bean2 * * @author Nathan Abramson - Art Technology Group */ public class Bean2Editor extends PropertyEditorSupport { //------------------------------------- public void setAsText(String pText) throws IllegalArgumentException { if ("badvalue".equals(pText)) { throw new IllegalArgumentException("Bad value " + pText); } else { setValue(new Bean2(pText)); } } //------------------------------------- } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/Bean1.java0000644000000000000000000002145711412443350020751 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl; import java.util.List; import java.util.Map; /** *

This is a test bean with a set of properties * * @author Nathan Abramson - Art Technology Group */ public class Bean1 { //------------------------------------- // Properties //------------------------------------- // property boolean1 boolean mBoolean1; public boolean getBoolean1() { return mBoolean1; } public void setBoolean1(boolean pBoolean1) { mBoolean1 = pBoolean1; } //------------------------------------- // property byte1 byte mByte1; public byte getByte1() { return mByte1; } public void setByte1(byte pByte1) { mByte1 = pByte1; } //------------------------------------- // property char1 char mChar1; public char getChar1() { return mChar1; } public void setChar1(char pChar1) { mChar1 = pChar1; } //------------------------------------- // property short1 short mShort1; public short getShort1() { return mShort1; } public void setShort1(short pShort1) { mShort1 = pShort1; } //------------------------------------- // property int1 int mInt1; public int getInt1() { return mInt1; } public void setInt1(int pInt1) { mInt1 = pInt1; } //------------------------------------- // property long1 long mLong1; public long getLong1() { return mLong1; } public void setLong1(long pLong1) { mLong1 = pLong1; } //------------------------------------- // property float1 float mFloat1; public float getFloat1() { return mFloat1; } public void setFloat1(float pFloat1) { mFloat1 = pFloat1; } //------------------------------------- // property double1 double mDouble1; public double getDouble1() { return mDouble1; } public void setDouble1(double pDouble1) { mDouble1 = pDouble1; } //------------------------------------- // property boolean2 Boolean mBoolean2; public Boolean getBoolean2() { return mBoolean2; } public void setBoolean2(Boolean pBoolean2) { mBoolean2 = pBoolean2; } //------------------------------------- // property byte2 Byte mByte2; public Byte getByte2() { return mByte2; } public void setByte2(Byte pByte2) { mByte2 = pByte2; } //------------------------------------- // property char2 Character mChar2; public Character getChar2() { return mChar2; } public void setChar2(Character pChar2) { mChar2 = pChar2; } //------------------------------------- // property short2 Short mShort2; public Short getShort2() { return mShort2; } public void setShort2(Short pShort2) { mShort2 = pShort2; } //------------------------------------- // property int2 Integer mInt2; public Integer getInt2() { return mInt2; } public void setInt2(Integer pInt2) { mInt2 = pInt2; } //------------------------------------- // property long2 Long mLong2; public Long getLong2() { return mLong2; } public void setLong2(Long pLong2) { mLong2 = pLong2; } //------------------------------------- // property float2 Float mFloat2; public Float getFloat2() { return mFloat2; } public void setFloat2(Float pFloat2) { mFloat2 = pFloat2; } //------------------------------------- // property double2 Double mDouble2; public Double getDouble2() { return mDouble2; } public void setDouble2(Double pDouble2) { mDouble2 = pDouble2; } //------------------------------------- // property string1 String mString1; public String getString1() { return mString1; } public void setString1(String pString1) { mString1 = pString1; } //------------------------------------- // property string2 String mString2; public String getString2() { return mString2; } public void setString2(String pString2) { mString2 = pString2; } //------------------------------------- // property bean1 Bean1 mBean1; public Bean1 getBean1() { return mBean1; } public void setBean1(Bean1 pBean1) { mBean1 = pBean1; } //------------------------------------- // property bean2 Bean1 mBean2; public Bean1 getBean2() { return mBean2; } public void setBean2(Bean1 pBean2) { mBean2 = pBean2; } //------------------------------------- // property noGetter String mNoGetter; public void setNoGetter(String pNoGetter) { mNoGetter = pNoGetter; } //------------------------------------- // property errorInGetter String mErrorInGetter; public String getErrorInGetter() { throw new NullPointerException("Error!"); } //------------------------------------- // property stringArray1 String[] mStringArray1; public String[] getStringArray1() { return mStringArray1; } public void setStringArray1(String[] pStringArray1) { mStringArray1 = pStringArray1; } //------------------------------------- // property list1 List mList1; public List getList1() { return mList1; } public void setList1(List pList1) { mList1 = pList1; } //------------------------------------- // property map1 Map mMap1; public Map getMap1() { return mMap1; } public void setMap1(Map pMap1) { mMap1 = pMap1; } //------------------------------------- // property indexed1 public String getIndexed1(int pIndex) { return mStringArray1[pIndex]; } //------------------------------------- // Member variables //------------------------------------- //------------------------------------- /** * Constructor */ public Bean1() { } //------------------------------------- } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/0000755000000000000000000000000011412443350020237 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/PublicBean1.java0000644000000000000000000000547611412443350023203 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A publicly-accessible bean * * @author Nathan Abramson - Art Technology Group */ public class PublicBean1 { public Object getValue() { return "got the value"; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/PrivateBean2b.java0000644000000000000000000000555511412443350023540 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A private implementation of a public interface * * @author Nathan Abramson - Art Technology Group */ class PrivateBean2b implements PublicInterface2 { public Object getValue() { return "got the value"; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/PublicBean1b.java0000644000000000000000000000561511412443350023340 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A public bean subclassing a private bean subclassing a public * bean * * @author Nathan Abramson - Art Technology Group * @version $Change: 181181 $$DateTime: 2001/06/26 09:55:09 $$Author: ofung $ */ public class PublicBean1b extends PrivateBean1a { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/PublicBean2a.java0000644000000000000000000000557711412443350023347 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A publicly-accessible implementation of a public interface * * @author Nathan Abramson - Art Technology Group */ public class PublicBean2a implements PublicInterface2 { public Object getValue() { return "got the value"; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/PrivateBean2c.java0000644000000000000000000000547311412443350023540 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A private subclass of a public class impelementing a public * interface * * @author Nathan Abramson - Art Technology Group */ class PrivateBean2c extends PublicBean2a { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/PrivateBean1a.java0000644000000000000000000000555111412443350023532 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A private bean subclassing a public bean * * @author Nathan Abramson - Art Technology Group * @version $Change: 181181 $$DateTime: 2001/06/26 09:55:09 $$Author: ofung $ */ class PrivateBean1a extends PublicBean1 { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/PrivateBean2d.java0000644000000000000000000000561311412443350023535 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A private subclass of a private class impelementing a public * interface * * @author Nathan Abramson - Art Technology Group * @version $Change: 181181 $$DateTime: 2001/06/26 09:55:09 $$Author: ofung $ */ class PrivateBean2d extends PrivateBean2b { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/Factory.java0000644000000000000000000000673011412443350022517 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A factory for generating the various beans * * @author Nathan Abramson - Art Technology Group * @version $Change: 181181 $$DateTime: 2001/06/26 09:55:09 $$Author: ofung $ */ public class Factory { public static PublicBean1 createBean1() { return new PublicBean1(); } public static PublicBean1 createBean2() { return new PrivateBean1a(); } public static PublicBean1 createBean3() { return new PublicBean1b(); } public static PublicInterface2 createBean4() { return new PublicBean2a(); } public static PublicInterface2 createBean5() { return new PrivateBean2b(); } public static PublicInterface2 createBean6() { return new PrivateBean2c(); } public static PublicInterface2 createBean7() { return new PrivateBean2d(); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/beans/PublicInterface2.java0000644000000000000000000000544511412443350024233 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl.beans; /** *

A publicly-accessible interface * * @author Nathan Abramson - Art Technology Group */ public interface PublicInterface2 { public Object getValue(); } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/impl/TestELImpl.java0000644000000000000000000010040111412443350021770 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.faces.el.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.context.ExternalContext; import javax.faces.el.ValueBinding; import com.sun.faces.el.impl.beans.Factory; import com.sun.faces.cactus.ServletFacesTestCase; /** * @author jhook */ public class TestELImpl extends ServletFacesTestCase { /** * */ public TestELImpl() { super(); } /** * @param name */ public TestELImpl(String name) { super(name); } protected Object evaluate(String ref) throws Exception { ValueBinding vb = this.getFacesContext().getApplication().createValueBinding(ref); return vb.getValue(this.getFacesContext()); } public void testELEvaluation() throws Exception { /* setup our test date */ Bean1 b = this.createBean1(); getExternalContext().getRequestMap().put("bean1a", b); getExternalContext().getSessionMap().put("val1c", "session-scoped1"); getExternalContext().getRequestMap().put("val1b", "request-scoped1"); getExternalContext().getApplicationMap().put("val1d", "app-scoped1"); Map m = new HashMap(); m.put("emptyArray", new Object[0]); m.put("nonemptyArray", new Object[] { "abc" }); m.put("emptyList", new ArrayList()); { List l = new ArrayList(); l.add("hello"); m.put("nonemptyList", l); } m.put("emptyMap", new HashMap()); { Map m2 = new HashMap(); m2.put("a", "a"); m.put("nonemptyMap", m2); } m.put("emptySet", new HashSet()); { Set s = new HashSet(); s.add("hello"); m.put("nonemptySet", s); } getExternalContext().getRequestMap().put("emptyTests", m); getExternalContext().getRequestMap().put("pbean1", Factory.createBean1()); getExternalContext().getRequestMap().put("pbean2", Factory.createBean2()); getExternalContext().getRequestMap().put("pbean3", Factory.createBean3()); getExternalContext().getRequestMap().put("pbean4", Factory.createBean4()); getExternalContext().getRequestMap().put("pbean5", Factory.createBean5()); getExternalContext().getRequestMap().put("pbean6", Factory.createBean6()); getExternalContext().getRequestMap().put("pbean7", Factory.createBean7()); /* testing mixture of strings and expressions */ evaluateTest("abc", "abc"); evaluateTest("#{ 3}", new Long(3)); evaluateTestFailure("a#{"); evaluateTest("a#{ 5 }", "a5"); evaluateTest("#{ 3 }b", "3b"); evaluateTest("#{ 1 }#{ 2 }", "12"); evaluateTest("abc #{ 1} #{ 2} def", "abc 1 2 def"); /* testing values that end with or contain "#" */ evaluateTest("#", "#"); evaluateTest("\\#", "#"); evaluateTest("# ", "# "); evaluateTest("test#", "test#"); evaluateTest("#test", "#test"); evaluateTest("test#test", "test#test"); evaluateTest("test###", "test###"); evaluateTest("test###{ 34 }", "test##34"); evaluateTest("test###{ 34 }##", "test##34##"); evaluateTest("test##{ 34 }", "test#34"); evaluateTest("##{ 34 }", "#34"); evaluateTest("##", "##"); evaluateTest("test##", "test##"); evaluateTest("test##test", "test##test"); evaluateTest("#{ 34 }##{ 34 }", "34#34"); /* basic literals */ evaluateTest("#{1}", new Long(1)); evaluateTest("#{-12}", new Long(-12)); evaluateTest("#{true}", Boolean.TRUE); evaluateTest("#{false}", Boolean.FALSE); evaluateTest("#{null}", null); evaluateTest("#{4.2}", new Double(4.2)); evaluateTest("#{-21.3}", new Double(-21.3)); evaluateTest("#{4.}", new Double(4.0)); evaluateTest("#{.21}", new Double(0.21)); evaluateTest("#{3e-1}", new Double(0.3)); evaluateTest("#{.2222222222}", new Double(0.2222222222)); /* basic relationals between literals */ evaluateTest("#{1 < 2}", Boolean.TRUE); evaluateTest("#{1 > 2}", Boolean.FALSE); evaluateTest("#{1 >= 2}", Boolean.FALSE); evaluateTest("#{1 <= 2}", Boolean.TRUE); evaluateTest("#{1 == 2}", Boolean.FALSE); evaluateTest("#{1 != 2}", Boolean.TRUE); evaluateTest("#{3 >= 3}", Boolean.TRUE); evaluateTest("#{3 <= 3}", Boolean.TRUE); evaluateTest("#{3 == 3}", Boolean.TRUE); evaluateTest("#{3 < 3}", Boolean.FALSE); evaluateTest("#{3 > 3}", Boolean.FALSE); evaluateTest("#{3 != 3}", Boolean.FALSE); // PENDING (visvan) check with Kinman/Jacob /* relationals between booleans evaluateTestFailure("#{false < true}"); evaluateTestFailure("#{false > true}"); evaluateTest("#{true >= true}", Boolean.TRUE); evaluateTest("#{true <= true}", Boolean.TRUE); evaluateTest("#{true == true}", Boolean.TRUE); evaluateTest("#{true != true}", Boolean.FALSE); */ /* looking up objects in scopes */ evaluateTest("#{requestScope.val1b}", "request-scoped1"); evaluateTest("#{sessionScope.val1b}", null); evaluateTest("#{applicationScope.val1b}", null); evaluateTest("#{val1b}", "request-scoped1"); evaluateTest("#{requestScope.val1c}", null); evaluateTest("#{sessionScope.val1c}", "session-scoped1"); evaluateTest("#{applicationScope.val1c}", null); evaluateTest("#{val1c}", "session-scoped1"); evaluateTest("#{requestScope.val1d}", null); evaluateTest("#{sessionScope.val1d}", null); evaluateTest("#{applicationScope.val1d}", "app-scoped1"); evaluateTest("#{val1d}", "app-scoped1"); /* accessing properties */ evaluateTest("#{bean1a.int1}", new Integer(b.getInt1())); evaluateTest("#{bean1a.boolean1}", Boolean.valueOf(b.getBoolean1())); evaluateTest("#{bean1a.string1}", b.getString1()); evaluateTest("#{bean1a.bean1.int2}", b.getBean1().getInt2()); evaluateTest("#{bean1a.bean1.bean2.string2}", b.getBean1().getBean2() .getString2()); evaluateTest("#{bean1a.byte1}", new Byte(b.getByte1())); evaluateTest("#{bean1a.char1}", new Character(b.getChar1())); evaluateTest("#{bean1a.short1}", new Short(b.getShort1())); evaluateTest("#{bean1a.long1}", new Long(b.getLong1())); evaluateTest("#{bean1a.float1}", new Float(b.getFloat1())); evaluateTest("#{bean1a.double1}", new Double(b.getDouble1())); /* test the entire relational comparison type promotion matrix */ evaluateTest("#{bean1a.byte1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("#{bean1a.byte1 < bean1a.char1}", Boolean.TRUE); evaluateTest("#{bean1a.byte1 < bean1a.short1}", Boolean.TRUE); evaluateTest("#{bean1a.byte1 < bean1a.int1}", Boolean.FALSE); evaluateTest("#{bean1a.byte1 < bean1a.long1}", Boolean.TRUE); evaluateTest("#{bean1a.byte1 < bean1a.float1}", Boolean.TRUE); evaluateTest("#{bean1a.byte1 < bean1a.double1}", Boolean.TRUE); evaluateTest("#{bean1a.char1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("#{bean1a.char1 < bean1a.char1}", Boolean.FALSE); evaluateTest("#{bean1a.char1 < bean1a.short1}", Boolean.FALSE); evaluateTest("#{bean1a.char1 < bean1a.int1}", Boolean.FALSE); evaluateTest("#{bean1a.char1 < bean1a.long1}", Boolean.FALSE); evaluateTest("#{bean1a.char1 < bean1a.float1}", Boolean.FALSE); evaluateTest("#{bean1a.char1 < bean1a.double1}", Boolean.FALSE); evaluateTest("#{bean1a.short1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("#{bean1a.short1 < bean1a.char1}", Boolean.FALSE); evaluateTest("#{bean1a.short1 < bean1a.short1}", Boolean.FALSE); evaluateTest("#{bean1a.short1 < bean1a.int1}", Boolean.FALSE); evaluateTest("#{bean1a.short1 < bean1a.float1}", Boolean.FALSE); evaluateTest("#{bean1a.short1 < bean1a.long1}", Boolean.FALSE); evaluateTest("#{bean1a.short1 < bean1a.double1}", Boolean.FALSE); evaluateTest("#{bean1a.int1 < bean1a.byte1}", Boolean.TRUE); evaluateTest("#{bean1a.int1 < bean1a.char1}", Boolean.TRUE); evaluateTest("#{bean1a.int1 < bean1a.short1}", Boolean.TRUE); evaluateTest("#{bean1a.int1 < bean1a.int1}", Boolean.FALSE); evaluateTest("#{bean1a.int1 < bean1a.long1}", Boolean.TRUE); evaluateTest("#{bean1a.int1 < bean1a.float1}", Boolean.TRUE); evaluateTest("#{bean1a.int1 < bean1a.double1}", Boolean.TRUE); evaluateTest("#{bean1a.long1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("#{bean1a.long1 < bean1a.char1}", Boolean.FALSE); evaluateTest("#{bean1a.long1 < bean1a.short1}", Boolean.FALSE); evaluateTest("#{bean1a.long1 < bean1a.int1}", Boolean.FALSE); evaluateTest("#{bean1a.long1 < bean1a.long1}", Boolean.FALSE); evaluateTest("#{bean1a.long1 < bean1a.float1}", Boolean.FALSE); evaluateTest("#{bean1a.long1 < bean1a.double1}", Boolean.FALSE); evaluateTest("#{bean1a.float1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("#{bean1a.float1 < bean1a.char1}", Boolean.TRUE); evaluateTest("#{bean1a.float1 < bean1a.short1}", Boolean.TRUE); evaluateTest("#{bean1a.float1 < bean1a.int1}", Boolean.FALSE); evaluateTest("#{bean1a.float1 < bean1a.long1}", Boolean.TRUE); evaluateTest("#{bean1a.float1 < bean1a.float1}", Boolean.FALSE); evaluateTest("#{bean1a.float1 < bean1a.double1}", Boolean.TRUE); evaluateTest("#{bean1a.double1 < bean1a.byte1}", Boolean.FALSE); evaluateTest("#{bean1a.double1 < bean1a.char1}", Boolean.TRUE); evaluateTest("#{bean1a.double1 < bean1a.short1}", Boolean.TRUE); evaluateTest("#{bean1a.double1 < bean1a.int1}", Boolean.FALSE); evaluateTest("#{bean1a.double1 < bean1a.long1}", Boolean.TRUE); evaluateTest("#{bean1a.double1 < bean1a.float1}", Boolean.FALSE); evaluateTest("#{bean1a.double1 < bean1a.double1}", Boolean.FALSE); /* test other relational comparison rules */ evaluateTest("#{null == null}", Boolean.TRUE); evaluateTest("#{noSuchAttribute == noSuchAttribute}", Boolean.TRUE); evaluateTest("#{noSuchAttribute == null}", Boolean.TRUE); evaluateTest("#{null == noSuchAttribute}", Boolean.TRUE); evaluateTest("#{bean1a == null}", Boolean.FALSE); evaluateTest("#{null == bean1a}", Boolean.FALSE); evaluateTest("#{bean1a == bean1a}", Boolean.TRUE); // JSF1.2 BI: This test used to fail with JSF 1.1 EL. With unified EL // the first portion of the expression is coerced to a string, so // the expression evaluates to true. evaluateTest("#{bean1a > \"hello\"}", Boolean.FALSE); evaluateTestFailure("#{bean1a.bean1 < 14}"); evaluateTest("#{bean1a.bean1 == \"hello\"}", Boolean.FALSE); /* test String comparisons */ evaluateTest("#{bean1a.string1 == \"hello\"}", Boolean.TRUE); evaluateTest("#{bean1a.string1 != \"hello\"}", Boolean.FALSE); evaluateTest("#{bean1a.string1 == \"goodbye\"}", Boolean.FALSE); evaluateTest("#{bean1a.string1 != \"goodbye\"}", Boolean.TRUE); evaluateTest("#{bean1a.string1 > \"goodbye\"}", Boolean.TRUE); evaluateTest("#{\"hello\" == bean1a.string1}", Boolean.TRUE); evaluateTest("#{\"goodbye\" > bean1a.string1}", Boolean.FALSE); /* test errors in property traversal */ evaluateTest("#{noSuchAttribute.abc}", null); evaluateTest("#{bean1a.bean2.byte1}", null); evaluateTestFailure("#{bean1a.noProperty}"); evaluateTestFailure("#{bean1a.noGetter}"); evaluateTestFailure("#{bean1a.errorInGetter}"); evaluateTest("#{bean1a.bean2.string2}", null); /* test accessing public properties from private classes */ evaluateTest("#{pbean1.value}", "got the value"); evaluateTest("#{pbean2.value}", "got the value"); evaluateTest("#{pbean3.value}", "got the value"); evaluateTest("#{pbean4.value}", "got the value"); evaluateTest("#{pbean5.value}", "got the value"); evaluateTest("#{pbean6.value}", "got the value"); evaluateTest("#{pbean7.value}", "got the value"); /* test reserved words as identifiers */ evaluateTestFailure("#{and}"); evaluateTestFailure("#{or}"); evaluateTestFailure("#{not}"); evaluateTestFailure("#{eq}"); evaluateTestFailure("#{ne}"); evaluateTestFailure("#{lt}"); evaluateTestFailure("#{gt}"); evaluateTestFailure("#{le}"); evaluateTestFailure("#{ge}"); evaluateTest("#{true}", Boolean.TRUE); evaluateTest("#{false}", Boolean.FALSE); evaluateTest("#{null}", null); /* test reserved words as property names */ evaluateTestFailure("#{bean1a.and}"); evaluateTestFailure("#{bean1a.or}"); evaluateTestFailure("#{bean1a.not}"); evaluateTestFailure("#{bean1a.eq}"); evaluateTestFailure("#{bean1a.ne}"); evaluateTestFailure("#{bean1a.lt}"); evaluateTestFailure("#{bean1a.gt}"); evaluateTestFailure("#{bean1a.le}"); evaluateTestFailure("#{bean1a.ge}"); evaluateTestFailure("#{bean1a.instanceof}"); evaluateTestFailure("#{bean1a.page}"); evaluateTestFailure("#{bean1a.request}"); evaluateTestFailure("#{bean1a.session}"); evaluateTestFailure("#{bean1a.application}"); evaluateTestFailure("#{bean1a.true}"); evaluateTestFailure("#{bean1a.false}"); evaluateTestFailure("#{bean1a.null}"); /* test arithmetic */ evaluateTest("#{3+5}", new Long(8)); evaluateTest("#{3-5}", new Long(-2)); evaluateTest("#{3/5}", new Double(0.6)); evaluateTest("#{3*5}", new Long(15)); evaluateTest("#{3*5.0}", new Double(15.0)); evaluateTest("#{3.0*5}", new Double(15.0)); evaluateTest("#{3.0*5.0}", new Double(15.0)); evaluateTest("#{225 % 17}", new Long(4)); evaluateTest("#{ 1 + 2 + 3 * 5 + 6}", new Long(24)); evaluateTest("#{ 1 + (2 + 3) * 5 + 6}", new Long(32)); /* test logical operators */ evaluateTest("#{ true}", Boolean.TRUE); evaluateTest("#{ not true}", Boolean.FALSE); evaluateTest("#{ not false}", Boolean.TRUE); evaluateTest("#{ not not true}", Boolean.TRUE); evaluateTest("#{ not not false}", Boolean.FALSE); evaluateTest("#{ true and false}", Boolean.FALSE); evaluateTest("#{ true and true}", Boolean.TRUE); evaluateTest("#{ false and true}", Boolean.FALSE); evaluateTest("#{ false and false}", Boolean.FALSE); evaluateTest("#{ true or false}", Boolean.TRUE); evaluateTest("#{ true or true}", Boolean.TRUE); evaluateTest("#{ false or true}", Boolean.TRUE); evaluateTest("#{ false or false}", Boolean.FALSE); evaluateTest("#{ false or false or false or true and false}", Boolean.FALSE); evaluateTest("#{ false or false or false or true and false or true}", Boolean.TRUE); /* test indexed access operator */ evaluateTest("#{ bean1a[\"double1\"] }", new Double(b.getDouble1())); evaluateTest("#{ bean1a[\"double1\"].class }", Double.class); evaluateTest("#{ bean1a.stringArray1[-1]}", null); evaluateTest("#{ bean1a.stringArray1[0]}", b.getStringArray1()[0]); evaluateTest("#{ bean1a.stringArray1[1]}", b.getStringArray1()[1]); evaluateTest("#{ bean1a.stringArray1[2]}", b.getStringArray1()[2]); evaluateTest("#{ bean1a.stringArray1[3]}", b.getStringArray1()[3]); evaluateTest("#{ bean1a.stringArray1[4]}", null); /* Test as list accessor */ evaluateTest("#{ bean1a.list1 [0] }", b.getList1().get(0)); evaluateTest("#{ bean1a.list1 [1] }", b.getList1().get(1)); evaluateTest("#{ bean1a.list1 [2][2] }", "string3"); /* Test as indexed property accessor */ evaluateTestFailure("#{ bean1a.indexed1[-1]}"); evaluateTestFailure("#{ bean1a.indexed1[0]}"); evaluateTestFailure("#{ bean1a.indexed1[1]}"); evaluateTestFailure("#{ bean1a.indexed1[2]}"); evaluateTestFailure("#{ bean1a.indexed1[3]}"); evaluateTestFailure("#{ bean1a.indexed1[4]}"); /* Test as map accessor */ evaluateTest("#{ bean1a.map1.noKey }", null); evaluateTest("#{ bean1a.map1.key1 }", b.getMap1().get("key1")); evaluateTest("#{ bean1a.map1 [\"key1\"] }", b.getMap1().get("key1")); evaluateTest("#{ bean1a.map1 [14] }", "value3"); evaluateTest("#{ bean1a.map1 [2 * 7] }", "value3"); evaluateTest("#{ bean1a.map1.recurse.list1[0] }", new Integer(14)); /* Test UIComponent as bean evaluateTest("#{view.rendered}", Boolean.TRUE); evaluateTest("#{view.attributes.rendered}", Boolean.TRUE); evaluateTest("#{view.children[0].value}", "inputValue"); evaluateTest("#{view.children[0].rendered}", Boolean.TRUE); */ /* test String concatenation */ evaluateTestFailure("#{ \"a\" + \"bcd\" }"); evaluateTestFailure("#{ \"a\" + (4*3) }"); evaluateTestFailure("#{ bean1a.map1 [\"key\" + (5-4)] }"); /* test String comparisons */ evaluateTest("#{ \"30\" < \"4\" }", Boolean.TRUE); evaluateTest("#{ 30 < \"4\" }", Boolean.FALSE); evaluateTest("#{ 30 > \"4\" }", Boolean.TRUE); evaluateTest("#{ \"0004\" == \"4\" }", Boolean.FALSE); /* test relational comparison with alternate symbols */ evaluateTest("#{ 4 eq 3}", Boolean.FALSE); evaluateTest("#{ 4 ne 3}", Boolean.TRUE); evaluateTest("#{ 4 eq 4}", Boolean.TRUE); evaluateTest("#{ 4 ne 4}", Boolean.FALSE); evaluateTest("#{ 4 lt 3}", Boolean.FALSE); evaluateTest("#{ 4 gt 3}", Boolean.TRUE); evaluateTest("#{ 4 le 3}", Boolean.FALSE); evaluateTest("#{ 4 ge 3}", Boolean.TRUE); evaluateTest("#{ 4 le 4}", Boolean.TRUE); evaluateTest("#{ 4 ge 4}", Boolean.TRUE); /* test expressions on the left side of a value suffix */ evaluateTest("#{(3).class}", Long.class); evaluateTest("#{(bean1a.map1)[\"key1\"]}", "value1"); /* test String/boolean logical operators */ evaluateTest("#{'true' and false}", Boolean.FALSE); evaluateTest("#{'true' or true}", Boolean.TRUE); evaluateTest("#{false and 'true'}", Boolean.FALSE); evaluateTest("#{false or 'true'}", Boolean.TRUE); /* test empty operator */ evaluateTest("#{ empty \"A\"}", Boolean.FALSE); evaluateTest("#{ empty \"\" }", Boolean.TRUE); evaluateTest("#{ empty null }", Boolean.TRUE); evaluateTest("#{ empty false}", Boolean.FALSE); evaluateTest("#{ empty 0}", Boolean.FALSE); evaluateTest("#{ not empty 0}", Boolean.TRUE); evaluateTest("#{ not empty empty 0}", Boolean.TRUE); evaluateTest("#{ empty emptyTests.emptyArray }", Boolean.TRUE); evaluateTest("#{ empty emptyTests.nonemptyArray }", Boolean.FALSE); evaluateTest("#{ empty emptyTests.emptyList }", Boolean.TRUE); evaluateTest("#{ empty emptyTests.nonemptyList }", Boolean.FALSE); evaluateTest("#{ empty emptyTests.emptyMap }", Boolean.TRUE); evaluateTest("#{ empty emptyTests.nonemptyMap }", Boolean.FALSE); evaluateTest("#{ empty emptyTests.emptySet }", Boolean.TRUE); evaluateTest("#{ empty emptyTests.nonemptySet }", Boolean.FALSE); /* test String arithmetic */ evaluateTest("#{ \"6\" / \"3\" }", new Double(2.0)); evaluateTest("#{ 3 + \"4\" }", new Long(7)); evaluateTest("#{ \"4\" + 3 }", new Long(7)); evaluateTest("#{ 3 + \"4.5\" }", new Double(7.5)); evaluateTest("#{ \"4.5\" + 3 }", new Double(7.5)); evaluateTest("#{ 3.0 + 6.0}", new Double(9.0)); evaluateTest("#{ 31121.0 * 61553.0 }", new Double(1.915590913E9)); evaluateTest("#{ 31121 * 61553 }", new Long(1915590913)); evaluateTest("#{ 65536 * 65536 * 65536 * 32759 }", new Long("9220838762064379904")); evaluateTest("#{ 9220838762064379904.0 - 9220838762064379900.0 }", new Double(0.0)); evaluateTest("#{ 9220838762064379904 - 9220838762064379900 }", new Long(4)); /* test relational operators involving null */ evaluateTest("#{ null == null }", Boolean.TRUE); evaluateTest("#{ null != null }", Boolean.FALSE); evaluateTest("#{ null > null }", Boolean.FALSE); evaluateTest("#{ null < null }", Boolean.FALSE); evaluateTest("#{ null >= null }", Boolean.TRUE); evaluateTest("#{ null <= null }", Boolean.TRUE); evaluateTest("#{ null == 3 }", Boolean.FALSE); evaluateTest("#{ null != 3 }", Boolean.TRUE); evaluateTest("#{ null > 3 }", Boolean.FALSE); evaluateTest("#{ null < 3 }", Boolean.FALSE); evaluateTest("#{ null >= 3 }", Boolean.FALSE); evaluateTest("#{ null <= 3 }", Boolean.FALSE); evaluateTest("#{ 3 == null }", Boolean.FALSE); evaluateTest("#{ 3 != null }", Boolean.TRUE); evaluateTest("#{ 3 > null }", Boolean.FALSE); evaluateTest("#{ 3 < null }", Boolean.FALSE); evaluateTest("#{ 3 >= null }", Boolean.FALSE); evaluateTest("#{ 3 <= null }", Boolean.FALSE); evaluateTest("#{ null == \"\" }", Boolean.FALSE); evaluateTest("#{ null != \"\" }", Boolean.TRUE); evaluateTest("#{ \"\" == null }", Boolean.FALSE); evaluateTest("#{ \"\" != null }", Boolean.TRUE); /* arithmetic operators involving Strings */ evaluateTest("#{ 4 + 3 }", new Long(7)); evaluateTest("#{ 4.0 + 3 }", new Double(7.0)); evaluateTest("#{ 4 + 3.0 }", new Double(7.0)); evaluateTest("#{ 4.0 + 3.0 }", new Double(7.0)); evaluateTest("#{ \"4\" + 3 }", new Long(7)); evaluateTest("#{ \"4.0\" + 3 }", new Double(7.0)); evaluateTest("#{ \"4\" + 3.0 }", new Double(7.0)); evaluateTest("#{ \"4.0\" + 3.0 }", new Double(7.0)); evaluateTest("#{ 4 + \"3\" }", new Long(7)); evaluateTest("#{ 4.0 + \"3\" }", new Double(7.0)); evaluateTest("#{ 4 + \"3.0\" }", new Double(7.0)); evaluateTest("#{ 4.0 + \"3.0\" }", new Double(7.0)); evaluateTest("#{ \"4\" + \"3\" }", new Long(7)); evaluateTest("#{ \"4.0\" + \"3\" }", new Double(7.0)); evaluateTest("#{ \"4\" + \"3.0\" }", new Double(7.0)); evaluateTest("#{ \"4.0\" + \"3.0\" }", new Double(7.0)); evaluateTest("#{ 4 - 3 }", new Long(1)); evaluateTest("#{ 4.0 - 3 }", new Double(1.0)); evaluateTest("#{ 4 - 3.0 }", new Double(1.0)); evaluateTest("#{ 4.0 - 3.0 }", new Double(1.0)); evaluateTest("#{ \"4\" - 3 }", new Long(1)); evaluateTest("#{ \"4.0\" - 3 }", new Double(1.0)); evaluateTest("#{ \"4\" - 3.0 }", new Double(1.0)); evaluateTest("#{ \"4.0\" - 3.0 }", new Double(1.0)); evaluateTest("#{ 4 - \"3\" }", new Long(1)); evaluateTest("#{ 4.0 - \"3\" }", new Double(1.0)); evaluateTest("#{ 4 - \"3.0\" }", new Double(1.0)); evaluateTest("#{ 4.0 - \"3.0\" }", new Double(1.0)); evaluateTest("#{ \"4\" - \"3\" }", new Long(1)); evaluateTest("#{ \"4.0\" - \"3\" }", new Double(1.0)); evaluateTest("#{ \"4\" - \"3.0\" }", new Double(1.0)); evaluateTest("#{ \"4.0\" - \"3.0\" }", new Double(1.0)); evaluateTest("#{ 4 * 3 }", new Long(12)); evaluateTest("#{ 4.0 * 3 }", new Double(12.0)); evaluateTest("#{ 4 * 3.0 }", new Double(12.0)); evaluateTest("#{ 4.0 * 3.0 }", new Double(12.0)); evaluateTest("#{ \"4\" * 3 }", new Long(12)); evaluateTest("#{ \"4.0\" * 3 }", new Double(12.0)); evaluateTest("#{ \"4\" * 3.0 }", new Double(12.0)); evaluateTest("#{ \"4.0\" * 3.0 }", new Double(12.0)); evaluateTest("#{ 4 * \"3\" }", new Long(12)); evaluateTest("#{ 4.0 * \"3\" }", new Double(12.0)); evaluateTest("#{ 4 * \"3.0\" }", new Double(12.0)); evaluateTest("#{ 4.0 * \"3.0\" }", new Double(12.0)); evaluateTest("#{ \"4\" * \"3\" }", new Long(12)); evaluateTest("#{ \"4.0\" * \"3\" }", new Double(12.0)); evaluateTest("#{ \"4\" * \"3.0\" }", new Double(12.0)); evaluateTest("#{ \"4.0\" * \"3.0\" }", new Double(12.0)); evaluateTest("#{ 4 / 3 }", new Double(4.0 / 3.0)); evaluateTest("#{ 4.0 / 3 }", new Double(4.0 / 3.0)); evaluateTest("#{ 4 / 3.0 }", new Double(4.0 / 3.0)); evaluateTest("#{ 4.0 / 3.0 }", new Double(4.0 / 3.0)); evaluateTest("#{ \"4\" / 3 }", new Double(4.0 / 3.0)); evaluateTest("#{ \"4.0\" / 3 }", new Double(4.0 / 3.0)); evaluateTest("#{ \"4\" / 3.0 }", new Double(4.0 / 3.0)); evaluateTest("#{ \"4.0\" / 3.0 }", new Double(4.0 / 3.0)); evaluateTest("#{ 4 / \"3\" }", new Double(4.0 / 3.0)); evaluateTest("#{ 4.0 / \"3\" }", new Double(4.0 / 3.0)); evaluateTest("#{ 4 / \"3.0\" }", new Double(4.0 / 3.0)); evaluateTest("#{ 4.0 / \"3.0\" }", new Double(4.0 / 3.0)); evaluateTest("#{ \"4\" / \"3\" }", new Double(4.0 / 3.0)); evaluateTest("#{ \"4.0\" / \"3\" }", new Double(4.0 / 3.0)); evaluateTest("#{ \"4\" / \"3.0\" }", new Double(4.0 / 3.0)); evaluateTest("#{ \"4.0\" / \"3.0\" }", new Double(4.0 / 3.0)); evaluateTest("#{ 4 % 3 }", new Long(1)); evaluateTest("#{ 4.0 % 3 }", new Double(1.0)); evaluateTest("#{ 4 % 3.0 }", new Double(1.0)); evaluateTest("#{ 4.0 % 3.0 }", new Double(1.0)); evaluateTest("#{ \"4\" % 3 }", new Long(1)); evaluateTest("#{ \"4.0\" % 3 }", new Double(1.0)); evaluateTest("#{ \"4\" % 3.0 }", new Double(1.0)); evaluateTest("#{ \"4.0\" % 3.0 }", new Double(1.0)); evaluateTest("#{ 4 % \"3\" }", new Long(1)); evaluateTest("#{ 4.0 % \"3\" }", new Double(1.0)); evaluateTest("#{ 4 % \"3.0\" }", new Double(1.0)); evaluateTest("#{ 4.0 % \"3.0\" }", new Double(1.0)); evaluateTest("#{ \"4\" % \"3\" }", new Long(1)); evaluateTest("#{ \"4.0\" % \"3\" }", new Double(1.0)); evaluateTest("#{ \"4\" % \"3.0\" }", new Double(1.0)); evaluateTest("#{ \"4.0\" % \"3.0\" }", new Double(1.0)); evaluateTest("#{ \"8\" / \"2\" }", new Double(4.0)); evaluateTest("#{ \"4e2\" + \"3\" }", new Double(403)); evaluateTest("#{ \"4\" + \"3e2\" }", new Double(304)); evaluateTest("#{ \"4e2\" + \"3e2\" }", new Double(700)); /* unary minus operator involving Strings */ evaluateTest("#{ -3 }", new Long(-3)); evaluateTest("#{ -3.0 }", new Double(-3.0)); evaluateTest("#{ -\"3\" }", new Long(-3)); evaluateTest("#{ -\"3.0\" }", new Double(-3)); evaluateTest("#{ -\"3e2\" }", new Double(-300)); } protected Bean1 createBean1() { Bean1 b1 = new Bean1(); b1.setBoolean1(true); b1.setByte1((byte) 12); b1.setShort1((short) 98); b1.setChar1('b'); b1.setInt1(4); b1.setLong1(98); b1.setFloat1((float) 12.4); b1.setDouble1(89.224); b1.setString1("hello"); b1.setStringArray1(new String[] { "string1", "string2", "string3", "string4" }); { List l = new ArrayList(); l.add(new Integer(14)); l.add("another value"); l.add(b1.getStringArray1()); b1.setList1(l); } { Map m = new HashMap(); m.put("key1", "value1"); m.put(new Integer(14), "value2"); m.put(new Long(14), "value3"); m.put("recurse", b1); b1.setMap1(m); } Bean1 b2 = new Bean1(); b2.setInt2(new Integer(-224)); b2.setString2("bean2's string"); b1.setBean1(b2); Bean1 b3 = new Bean1(); b3.setDouble1(1422.332); b3.setString2("bean3's string"); b2.setBean2(b3); return b1; } public ExternalContext getExternalContext() { return getFacesContext().getExternalContext(); } public void evaluateTestFailure(String ref) throws Exception { try { this.evaluate(ref); fail("'" + ref + "' should have thrown an exception"); } catch (Exception e) { // do nothing } } public void evaluateTest(String ref, Object expectedValue) throws Exception { Object returnedValue = this.evaluate(ref); if (returnedValue != null) { Class expectedType = expectedValue.getClass(); Class returnedType = returnedValue.getClass(); String msg = "'" + ref + "' expected [" + expectedValue + "] of type " + expectedType.getName() + ", but returned [" + returnedValue + "] of type " + returnedType.getName(); assertTrue(msg, expectedType.isAssignableFrom(returnedType)); assertEquals(msg, expectedValue, returnedValue); } else { String msg = "'" + ref + "' expected value [" + expectedValue + "], but returned [" + returnedValue + "]"; assertEquals(msg, expectedValue, returnedValue); } } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestValueBindingImpl_Model.java0000644000000000000000000003161311412443352024230 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestValueBindingImpl_Model.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.TestBean; import com.sun.faces.cactus.TestBean.Inner2Bean; import com.sun.faces.cactus.TestBean.InnerBean; import javax.faces.context.FacesContext; import javax.faces.el.PropertyNotFoundException; import javax.faces.el.ValueBinding; /** * TestValueBindingImpl_Model is a class ... *

* Lifetime And Scope

* */ public class TestValueBindingImpl_Model extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables ValueBinding valueBinding = null; // // Constructors and Initializers // public TestValueBindingImpl_Model() { super("TestValueBindingImpl"); } public TestValueBindingImpl_Model(String name) { super(name); } // // Class methods // // // Methods from TestCase // // // General Methods // public ValueBinding create(String ref) throws Exception { return (getFacesContext().getApplication().createValueBinding("#{" + ref + "}")); } public void setUp() { super.setUp(); valueBinding = null; } public void tearDown() { valueBinding = null; super.tearDown(); } public void testSet() throws Exception { FacesContext facesContext = getFacesContext(); System.out.println("Testing setValue() with model bean in session "); TestBean testBean = new TestBean(); InnerBean inner = new InnerBean(); Inner2Bean innerInner = new Inner2Bean(); Object result = null; getFacesContext().getExternalContext().getSessionMap().put("TestBean", testBean); boolean exceptionThrown = false; System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("TestBean.one"); valueBinding.setValue(getFacesContext(), "one"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); InnerBean newInner = new InnerBean(); valueBinding = this.create("TestBean.inner"); valueBinding.setValue(getFacesContext(), newInner); result = valueBinding.getValue(getFacesContext()); assertTrue(result == newInner); // Test two levels of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("sessionScope.TestBean.inner.two"); valueBinding.setValue(getFacesContext(), "two"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); Inner2Bean newInner2 = new Inner2Bean(); valueBinding = this.create("TestBean.inner.inner2"); valueBinding.setValue(getFacesContext(), newInner2); result = valueBinding.getValue(getFacesContext()); assertTrue(result == newInner2); System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("sessionScope.TestBean.inner.inner2"); valueBinding.setValue(getFacesContext(), innerInner); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); // Test three levels of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("sessionScope.TestBean.inner.inner2.three"); valueBinding.setValue(getFacesContext(), "three"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); } public void testSetNull() throws Exception { FacesContext facesContext = getFacesContext(); System.out.println( "Testing setValue() with model bean in session with null rValues"); TestBean testBean = new TestBean(); InnerBean inner = new InnerBean(); Inner2Bean innerInner = new Inner2Bean(); getFacesContext().getExternalContext().getSessionMap().put("TestBean", testBean); // Test one level of nesting valueBinding = this.create("TestBean.one"); valueBinding.setValue(getFacesContext(), null); assertTrue(testBean.getOne() == null); System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("sessionScope.TestBean.inner"); valueBinding.setValue(getFacesContext(), inner); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); valueBinding = this.create("sessionScope.TestBean.inner"); valueBinding.setValue(getFacesContext(), null); assertTrue(testBean.getInner() == null); // Inner bean does not exist anymore. So this should result in an // exception. boolean exceptionThrown = false; valueBinding = this.create("sessionScope.TestBean.inner.two"); try { valueBinding.setValue(getFacesContext(), null); } catch (javax.faces.el.EvaluationException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testSetWithNoCurlyBraces() throws Exception { FacesContext facesContext = getFacesContext(); System.out.println("Testing setValue() with model bean in request "); TestBean testBean = new TestBean(); InnerBean inner = new InnerBean(); Inner2Bean innerInner = new Inner2Bean(); facesContext.getExternalContext().getSessionMap().remove("TestBean"); facesContext.getExternalContext().getRequestMap().put("TestBean", testBean); // Test implicit scopes direct access to some scope objects should // throw an illegalArgumentException boolean gotException = false; try { valueBinding = this.create("header.header-one"); valueBinding.setValue(getFacesContext(), testBean); } catch (javax.faces.el.EvaluationException pnf) { gotException = true; } assertTrue(gotException); // Test one level of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("TestBean.one"); valueBinding.setValue(getFacesContext(), "one"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("requestScope.TestBean.inner"); valueBinding.setValue(getFacesContext(), inner); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); // Test two levels of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("requestScope.TestBean.inner.two"); valueBinding.setValue(getFacesContext(), "two"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("requestScope.TestBean.inner.inner2"); valueBinding.setValue(getFacesContext(), innerInner); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); // Test three levels of nesting System.setProperty(TestBean.PROP, TestBean.FALSE); valueBinding = this.create("requestScope.TestBean.inner.inner2.three"); valueBinding.setValue(getFacesContext(), "three"); assertTrue(System.getProperty(TestBean.PROP).equals(TestBean.TRUE)); } public void testGet() throws Exception { FacesContext facesContext = getFacesContext(); System.out.println("Testing getValue() with model bean in context"); assertTrue(facesContext != null); TestBean testBeanResult = null, testBean = new TestBean(); InnerBean inner = new InnerBean(); Inner2Bean inner2 = new Inner2Bean(); String result; // Init the beans testBean.setOne("one"); inner.setTwo("two"); inner2.setThree("three"); inner.setInner2(inner2); testBean.setInner(inner); assertTrue(facesContext != null); assertTrue(facesContext.getExternalContext().getSession(false) != null); facesContext.getExternalContext().getRequestMap().remove("TestBean"); facesContext.getExternalContext().getSessionMap().remove("TestBean"); facesContext.getExternalContext().getApplicationMap().put("TestBean", testBean); // Test zero levels of nesting valueBinding = this.create("applicationScope.TestBean"); testBeanResult = (TestBean) valueBinding.getValue(getFacesContext()); assertTrue(testBeanResult != null); assertTrue(testBeanResult == testBean); // Test one level of nesting valueBinding = this.create("applicationScope.TestBean.one"); result = (String) valueBinding.getValue(getFacesContext()); assertTrue(result.equals("one")); valueBinding = this.create("applicationScope.TestBean.inner"); inner = (InnerBean) valueBinding.getValue(getFacesContext()); assertTrue(null != inner); // Test two levels of nesting valueBinding = this.create("applicationScope.TestBean.inner.two"); result = (String) valueBinding.getValue(getFacesContext()); assertTrue(result.equals("two")); valueBinding = this.create("applicationScope.TestBean.inner.inner2"); inner2 = (Inner2Bean) valueBinding.getValue(getFacesContext()); assertTrue(null != inner2); // Test three levels of nesting valueBinding = this.create("applicationScope.TestBean.inner.inner2.three"); result = (String) valueBinding.getValue(getFacesContext()); assertTrue(result.equals("three")); } public void testModelType() { /***************** PENDING(edburns): // Test model type System.out.println("Testing getModelType()"); Class classType = null; String className = null; // Test zero levels of nesting classType = facesContext.getModelType("applicationScope.TestBean"); assertTrue(classType != null); className = classType.getName(); assertTrue(className.equals(testBean.getClass().getName())); classType = facesContext.getModelType("applicationScope.TestBean.inner.pin"); assertTrue(classType != null); className = classType.getName(); assertTrue(className.equals("java.lang.Integer")); classType = facesContext.getModelType("applicationScope.TestBean.inner.result"); assertTrue(classType != null); className = classType.getName(); assertTrue(className.equals("java.lang.Boolean")); classType = facesContext.getModelType("applicationScope.TestBean.one"); assertTrue(classType != null); className = classType.getName(); assertTrue(className.equals("java.lang.String")); *********************/ } } // end of class TestValueBindingImpl_Model mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/ElBean.java0000644000000000000000000001541311412443352020205 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.el; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; // JavaBean for simple expression evaluation tests public class ElBean { public ElBean() { } public ElBean(String stringProperty) { this.stringProperty = stringProperty; } private boolean booleanProperty = true; public boolean getBooleanProperty() { return (this.booleanProperty); } public void setBooleanProperty(boolean booleanProperty) { this.booleanProperty = booleanProperty; } private byte byteProperty = 123; public byte getByteProperty() { return (this.byteProperty); } public void setByteProperty(byte byteProperty) { this.byteProperty = byteProperty; } private char characterProperty = 'c'; public char getCharacterProperty() { return this.characterProperty; } public void setCharacterProperty(char c) { this.characterProperty = c; } private double doubleProperty = 654.321; public double getDoubleProperty() { return (this.doubleProperty); } public void setDoubleProperty(double doubleProperty) { this.doubleProperty = doubleProperty; } private float floatProperty = (float) 123.45; public float getFloatProperty() { return (this.floatProperty); } public void setFloatProperty(float floatProperty) { this.floatProperty = floatProperty; } private int intArray[] = {1, 2, 3}; public int[] getIntArray() { return (this.intArray); } public void setIntArray(int intArray[]) { this.intArray = intArray; } private List intList = null; public List getIntList() { if (intList == null) { intList = new ArrayList(); intList.add(new Integer(10)); intList.add(new Integer(20)); intList.add(new Integer(30)); intList.add(new Integer(40)); intList.add(new Integer(50)); } return (intList); } public void setIntList(List intList) { this.intList = intList; } private int intProperty = 1234; public int getIntProperty() { return (this.intProperty); } public void setIntProperty(int intProperty) { this.intProperty = intProperty; } private long longProperty = 54321; public long getLongProperty() { return (this.longProperty); } public void setLongProperty(long longProperty) { this.longProperty = longProperty; } private ElBean nestedArray[] = null; public ElBean[] getNestedArray() { if (nestedArray == null) { nestedArray = new ElBean[2]; nestedArray[0] = new ElBean("Nested0"); nestedArray[1] = new ElBean("Nested1"); } return (this.nestedArray); } public void setNestedArray(ElBean nestedArray[]) { this.nestedArray = nestedArray; } private List nestedList = null; public List getNestedList() { if (nestedList == null) { nestedList = new ArrayList(); nestedList.add(new ElBean("list0")); nestedList.add(new ElBean("list1")); nestedList.add(new ElBean("list2")); nestedList.add(new ElBean("list3")); } return (this.nestedList); } public void setNestedList(List nestedList) { this.nestedList = nestedList; } private Map nestedMap = null; public Map getNestedMap() { if (nestedMap == null) { nestedMap = new HashMap(); nestedMap.put("map0", new ElBean("map0")); nestedMap.put("map1", new ElBean("map1")); nestedMap.put("map2", new ElBean("map2")); } return (this.nestedMap); } public void setNestedMap(Map nestedMap) { this.nestedMap = nestedMap; } private ElBean nestedProperty = null; public ElBean getNestedProperty() { if (nestedProperty == null) { nestedProperty = new ElBean(); } return (this.nestedProperty); } public void setNestedProperty(ElBean nestedProperty) { this.nestedProperty = nestedProperty; } private short shortProperty = 321; public short getShortProperty() { return (this.shortProperty); } public void setShortProperty(short shortProperty) { this.shortProperty = shortProperty; } private String stringProperty = "This is a String"; public String getStringProperty() { return (this.stringProperty); } public void setStringProperty(String stringProperty) { this.stringProperty = stringProperty; } private String nullString = null; public String getNullStringProperty() { return ("String length is:" + nullString.length()); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestMethodExpressionImpl.java0000644000000000000000000001152411412443352024040 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestMethodRef.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import javax.el.MethodExpression; import javax.el.ELException; import javax.el.MethodNotFoundException; import javax.faces.el.PropertyNotFoundException; /** * TestMethodRef is a class ...

Lifetime And Scope *

* */ public class TestMethodExpressionImpl extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestMethodExpressionImpl() { super("TestMethodExpression"); } public TestMethodExpressionImpl(String name) { super(name); } // // Class methods // // // General Methods // protected MethodExpression create(String ref, Class[] params) throws Exception { return (getFacesContext().getApplication().getExpressionFactory(). createMethodExpression(getFacesContext().getELContext(),ref, null, params)); } public void testNullReference() throws Exception { try { create(null, null); fail(); } catch (NullPointerException npe) {} catch (Exception e) { fail("Should have thrown an NPE"); }; } public void testInvalidMethod() throws Exception { try { create("${foo > 1}", null); fail(); } catch (ELException ee) { fail("Should have thrown a NullPointerException"); } catch (NullPointerException npe) { } } public void testLiteralReference() throws Exception { boolean exceptionThrown = false; try { create("some.method", null); } catch (NullPointerException ee) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testInvalidTrailing() throws Exception { MethodExpression mb = this.create( "#{NewCustomerFormHandler.redLectroidsMmmm}", new Class[0]); boolean exceptionThrown = false; try { mb.invoke(getFacesContext().getELContext(), new Object[0]); } catch (MethodNotFoundException me) { exceptionThrown = true; } assertTrue(exceptionThrown); mb = this.create("#{nonexistentBean.redLectroidsMmmm}", new Class[0]); exceptionThrown = false; try { mb.invoke(getFacesContext().getELContext(), new Object[0]); } catch (PropertyNotFoundException ne) { exceptionThrown = true; } catch (ELException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } } // end of class TestMethodRef mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/el/TestVariableResolverImpl.java0000644000000000000000000002473611412443352024020 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestVariableResolverImpl.java package com.sun.faces.el; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.TestBean; import com.sun.faces.mgbean.ManagedBeanInfo; import com.sun.faces.mgbean.BeanManager; import com.sun.faces.cactus.TestBean.InnerBean; import com.sun.faces.application.ApplicationImpl; import com.sun.faces.application.ApplicationAssociate; import com.sun.faces.util.Util; import javax.faces.FactoryFinder; import javax.faces.application.ApplicationFactory; import javax.faces.component.UIViewRoot; import javax.faces.el.VariableResolver; import java.util.Locale; /** * TestVariableResolverImpl is a class ... *

* Lifetime And Scope

* */ public class TestVariableResolverImpl extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestVariableResolverImpl() { super("TestFacesContext"); } public TestVariableResolverImpl(String name) { super(name); } // // Class methods // // // Methods from TestCase // // // General Methods // public void testScopedLookup() { TestBean testBean = new TestBean(); InnerBean newInner, oldInner = new InnerBean(); testBean.setInner(oldInner); VariableResolver variableResolver = getFacesContext().getApplication().getVariableResolver(); Object result = null; getFacesContext().getExternalContext().getSessionMap().remove( "TestBean"); // // Get tests // // application getFacesContext().getExternalContext().getApplicationMap().put( "TestBean", testBean); result = variableResolver.resolveVariable(getFacesContext(), "TestBean"); assertTrue(result == testBean); getFacesContext().getExternalContext().getApplicationMap().remove( "TestBean"); // session getFacesContext().getExternalContext().getSessionMap().put("TestBean", testBean); result = variableResolver.resolveVariable(getFacesContext(), "TestBean"); assertTrue(result == testBean); getFacesContext().getExternalContext().getSessionMap().remove( "TestBean"); // session getFacesContext().getExternalContext().getRequestMap().put("TestBean", testBean); result = variableResolver.resolveVariable(getFacesContext(), "TestBean"); assertTrue(result == testBean); getFacesContext().getExternalContext().getRequestMap().remove( "TestBean"); } public void testImplicitObjects() { VariableResolver variableResolver = getFacesContext().getApplication().getVariableResolver(); Object result = null; // // test scope maps // // ApplicationMap assertTrue(variableResolver.resolveVariable(getFacesContext(), "applicationScope") == getFacesContext().getExternalContext().getApplicationMap()); // SessionMap assertTrue(variableResolver.resolveVariable(getFacesContext(), "sessionScope") == getFacesContext().getExternalContext().getSessionMap()); // RequestMap assertTrue(variableResolver.resolveVariable(getFacesContext(), "requestScope") == getFacesContext().getExternalContext().getRequestMap()); // // test request objects // // cookie assertTrue(variableResolver.resolveVariable(getFacesContext(), "cookie") == getFacesContext().getExternalContext().getRequestCookieMap()); // header assertTrue(variableResolver.resolveVariable(getFacesContext(), "header") == getFacesContext().getExternalContext().getRequestHeaderMap()); // headerValues assertTrue( variableResolver.resolveVariable(getFacesContext(), "headerValues") == getFacesContext().getExternalContext().getRequestHeaderValuesMap()); // parameter assertTrue(variableResolver.resolveVariable(getFacesContext(), "param") == getFacesContext().getExternalContext() .getRequestParameterMap()); // parameterValues assertTrue( variableResolver.resolveVariable(getFacesContext(), "paramValues") == getFacesContext().getExternalContext() .getRequestParameterValuesMap()); // // misc // // initParameter assertTrue(variableResolver.resolveVariable(getFacesContext(), "initParam") == getFacesContext().getExternalContext().getInitParameterMap()); // facesContext assertTrue(variableResolver.resolveVariable(getFacesContext(), "facesContext") == getFacesContext()); // tree // create a dummy root for the tree. UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setId("root"); page.setViewId("newTree"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); assertTrue(variableResolver.resolveVariable(getFacesContext(), "view") == getFacesContext().getViewRoot()); } // Negative tests (should throw exceptions) public void testNegative() throws Exception { VariableResolver variableResolver = getFacesContext().getApplication().getVariableResolver(); Object value = null; // ---------- NullPointerException Returns ---------- try { value = variableResolver.resolveVariable(getFacesContext(), null); fail("Should have thrown NullPointerException"); } catch (NullPointerException e) { ; // Expected result } try { value = variableResolver.resolveVariable(null, "foo"); fail("Should have thrown NullPointerException"); } catch (NullPointerException e) { ; // Expected result } try { value = variableResolver.resolveVariable(null, null); fail("Should have thrown NullPointerException"); } catch (NullPointerException e) { ; // Expected result } } /** * This test verifies that if the variable resolver does not find a * managed bean it tries to instantiate it if it was added to the * application's managed bean factory list. */ public void testManagedBean() throws Exception { String beanName = "com.sun.faces.TestBean"; ManagedBeanInfo beanInfo = new ManagedBeanInfo(beanName, beanName, "session", null, null, null, null); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); ApplicationImpl application = (ApplicationImpl) aFactory.getApplication(); ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance(); BeanManager manager = associate.getBeanManager(); manager.register(beanInfo); VariableResolver variableResolver = application.getVariableResolver(); Object result = variableResolver.resolveVariable(getFacesContext(), beanName); assertTrue(result instanceof TestBean); } } // end of class TestVariableResolverImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/ext/0000755000000000000000000000000011412443346016413 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/ext/validator/0000755000000000000000000000000011412443346020400 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestForm.java0000644000000000000000000000417311412443352020223 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces; import javax.faces.component.html.HtmlForm; public class TestForm extends HtmlForm { public static final String COMPONENT_TYPE = "javax.faces.TestForm"; public TestForm() { super(); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/0000755000000000000000000000000011412443352017052 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/TlvTestCase.java0000644000000000000000000000662311412443352022125 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.taglib; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; public class TlvTestCase extends TestCase { // ------------------------------------------------------ Instance Variables public TlvTestCase(String name) { super(name); } // ---------------------------------------------------- Overall Test Methods // Set up instance variables required by this test case. public void setUp() { } // Return the tests included in this test case. public static Test suite() { return (new TestSuite(TlvTestCase.class)); } // Tear down instance variables required by this test case. public void tearDown() { } // ------------------------------------------------- Individual Test Methods public void testDesignTime() { java.beans.Beans.setDesignTime(true); TestHtmlBasicValidator hbv = new TestHtmlBasicValidator(); org.xml.sax.helpers.DefaultHandler handler = hbv.getSAXHandler(); assertTrue(null == handler); java.beans.Beans.setDesignTime(false); handler = hbv.getSAXHandler(); assertTrue(null != handler); java.beans.Beans.setDesignTime(true); TestCoreValidator cv = new TestCoreValidator(); handler = cv.getSAXHandler(); assertTrue(null == handler); java.beans.Beans.setDesignTime(false); handler = cv.getSAXHandler(); assertTrue(null != handler); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/TestHtmlBasicValidator.java0000644000000000000000000000427211412443352024276 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.taglib; import com.sun.faces.taglib.html_basic.HtmlBasicValidator; import org.xml.sax.helpers.DefaultHandler; public class TestHtmlBasicValidator extends HtmlBasicValidator { public DefaultHandler getSAXHandler() { return super.getSAXHandler(); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/html_basic/0000755000000000000000000000000011412443352021157 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/jsf_core/0000755000000000000000000000000011412443352020644 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/jsf_core/TestValidatorTags.java0000644000000000000000000002352011412443352025115 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestValidatorTags.java package com.sun.faces.taglib.jsf_core; import java.util.Iterator; import java.util.Locale; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.lifecycle.ApplyRequestValuesPhase; import com.sun.faces.lifecycle.Phase; import com.sun.faces.lifecycle.ProcessValidationsPhase; import com.sun.faces.lifecycle.RenderResponsePhase; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; /** * TestValidatorTags is a class ... *

* Lifetime And Scope

* */ public class TestValidatorTags extends JspFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/TestValidatorTags.jsp"; public static final String OUTOFBOUNDS1_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "outOfBounds1"; public static final String OUTOFBOUNDS1_VALUE = "3.1415"; public static final String INBOUNDS1_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "inBounds1"; public static final String INBOUNDS1_VALUE = "10.25"; public static final String OUTOFBOUNDS2_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "outOfBounds2"; public static final String OUTOFBOUNDS2_VALUE = "fox"; public static final String INBOUNDS2_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "inBounds2"; public static final String INBOUNDS2_VALUE = "alligator22"; public static final String OUTOFBOUNDS3_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "outOfBounds3"; public static final String OUTOFBOUNDS3_VALUE = "30000"; public static final String INBOUNDS3_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "inBounds3"; public static final String INBOUNDS3_VALUE = "1100"; public static final String REQUIRED1_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "required1"; public static final String REQUIRED1_VALUE = "required"; public static final String REQUIRED2_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "required2"; public static final String REQUIRED2_VALUE = "required"; public boolean sendResponseToFile() { return false; } // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestValidatorTags() { super("TestValidatorTags"); } public TestValidatorTags(String name) { super(name); } // // Class methods // // // General Methods // public void beginValidators(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); theRequest.addParameter(OUTOFBOUNDS1_ID, OUTOFBOUNDS1_VALUE); theRequest.addParameter(INBOUNDS1_ID, INBOUNDS1_VALUE); theRequest.addParameter(OUTOFBOUNDS2_ID, OUTOFBOUNDS2_VALUE); theRequest.addParameter(INBOUNDS2_ID, INBOUNDS2_VALUE); theRequest.addParameter(OUTOFBOUNDS3_ID, OUTOFBOUNDS3_VALUE); theRequest.addParameter(INBOUNDS3_ID, INBOUNDS3_VALUE); theRequest.addParameter(REQUIRED1_ID, ""); theRequest.addParameter(REQUIRED2_ID, ""); theRequest.addParameter("validatorForm", "validatorForm"); } public void setUp() { super.setUp(); } public void testValidators() { // Verify the parmeters are as expected String paramVal = (String) (getFacesContext().getExternalContext() .getRequestParameterMap()).get(OUTOFBOUNDS1_ID); assertTrue(OUTOFBOUNDS1_VALUE.equals(paramVal)); // assertTrue(OUTOFBOUNDS1_VALUE.equals(getFacesContext().getServletRequest().getParameter(OUTOFBOUNDS1_ID))); boolean result = false; String value = null; Phase renderResponse = new RenderResponsePhase(), processValidations = new ProcessValidationsPhase(), applyRequestValues = new ApplyRequestValuesPhase(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), TEST_URI); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); // This builds the tree, and usefaces saves it in the session renderResponse.execute(getFacesContext()); assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); // This causes the components to be set to valid applyRequestValues.execute(getFacesContext()); assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); // process the validations processValidations.execute(getFacesContext()); // We know there are validation errors on the page assertTrue(getFacesContext().getRenderResponse()); // verify the messages have been added correctly. UIComponent comp = null; Iterator messages = null; assertTrue(null != (messages = getFacesContext().getMessages())); assertTrue(messages.hasNext()); // check the messages for each component in the page assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent( OUTOFBOUNDS1_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent(INBOUNDS1_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(!messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent( OUTOFBOUNDS2_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent(INBOUNDS2_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(!messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent( OUTOFBOUNDS3_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent(INBOUNDS3_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(!messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent(REQUIRED1_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent(REQUIRED2_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(messages.hasNext()); } } // end of class TestValidatorTags mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/jsf_core/TestCoreTagsVBEnabled.java0000644000000000000000000002100411412443352025556 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.taglib.jsf_core; import java.util.Iterator; import java.util.Locale; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.lifecycle.ApplyRequestValuesPhase; import com.sun.faces.lifecycle.Phase; import com.sun.faces.lifecycle.ProcessValidationsPhase; import com.sun.faces.lifecycle.RenderResponsePhase; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; /** * TestValidatorTags is a class ... *

* Lifetime And Scope

* */ public class TestCoreTagsVBEnabled extends JspFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/TestCoreTagVBEnabled.jsp"; public static final String LONGRANGE_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "longRange"; public static final String LONGRANGE_VALUE = "115"; public static final String INTRANGE_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "intRange"; public static final String INTRANGE_VALUE = "NorthAmerica"; public static final String DOUBLERANGE_ID = "validatorForm" + NamingContainer.SEPARATOR_CHAR + "doubleRange"; public static final String DOUBLERANGE_VALUE = "1500"; public boolean sendResponseToFile() { return false; } // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestCoreTagsVBEnabled() { super("TestValidatorTags"); } public TestCoreTagsVBEnabled(String name) { super(name); } // // Class methods // // // General Methods // public void beginValidators(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); theRequest.addParameter(LONGRANGE_ID, LONGRANGE_VALUE); theRequest.addParameter(INTRANGE_ID, INTRANGE_VALUE); theRequest.addParameter(DOUBLERANGE_ID, DOUBLERANGE_VALUE); theRequest.addParameter("validatorForm", "validatorForm"); } public void setUp() { super.setUp(); (getFacesContext().getExternalContext().getRequestMap()).put("intMin", new Integer( 1)); (getFacesContext().getExternalContext().getRequestMap()).put("intMax", new Integer( 10)); (getFacesContext().getExternalContext().getRequestMap()).put("longMin", new Long( 100)); (getFacesContext().getExternalContext().getRequestMap()).put("longMax", new Long( 110)); (getFacesContext().getExternalContext().getRequestMap()).put( "doubleMin", new Double(1.0)); (getFacesContext().getExternalContext().getRequestMap()).put( "doubleMax", new Double(10.0)); } public void testValidators() { System.out.println("Test VBEnabled attributes on core Validator tags"); // Verify the parmeters are as expected String paramVal = (String) (getFacesContext().getExternalContext() .getRequestParameterMap()).get(LONGRANGE_ID); assertTrue(LONGRANGE_VALUE.equals(paramVal)); String paramVal1 = (String) (getFacesContext().getExternalContext() .getRequestParameterMap()).get(DOUBLERANGE_ID); assertTrue(DOUBLERANGE_VALUE.equals(paramVal1)); String paramVal2 = (String) (getFacesContext().getExternalContext() .getRequestParameterMap()).get(INTRANGE_ID); assertTrue(INTRANGE_VALUE.equals(paramVal2)); boolean result = false; String value = null; Phase renderResponse = new RenderResponsePhase(), processValidations = new ProcessValidationsPhase(), applyRequestValues = new ApplyRequestValuesPhase(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setLocale(Locale.US); page.setViewId(TEST_URI); getFacesContext().setViewRoot(page); // This builds the tree, and usefaces saves it in the session renderResponse.execute(getFacesContext()); assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); // This causes the components to be set to valid applyRequestValues.execute(getFacesContext()); assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); // process the validations processValidations.execute(getFacesContext()); // We know there are validation errors on the page assertTrue(getFacesContext().getRenderResponse()); System.out.println("Verifying results..."); // verify the messages have been added correctly. UIComponent comp = null; Iterator messages = null; assertTrue(null != (messages = getFacesContext().getMessages())); assertTrue(messages.hasNext()); // check the messages for each component in the page assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent(LONGRANGE_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent(INTRANGE_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(messages.hasNext()); assertTrue(null != (comp = getFacesContext().getViewRoot().findComponent( DOUBLERANGE_ID))); assertTrue( null != (messages = getFacesContext().getMessages(comp.getClientId(getFacesContext())))); assertTrue(messages.hasNext()); } } // end of class TestValidatorTags mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/jsf_core/TestViewTag.java0000644000000000000000000001652611412443352023727 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestViewTag.java package com.sun.faces.taglib.jsf_core; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.lifecycle.Phase; import com.sun.faces.lifecycle.RenderResponsePhase; import com.sun.faces.util.Util; import com.sun.faces.cactus.TestingUtil; import org.apache.cactus.JspTestCase; import org.apache.cactus.WebRequest; import javax.faces.FacesException; import javax.faces.component.UIViewRoot; import javax.servlet.ServletRequest; import javax.servlet.jsp.jstl.core.Config; import java.util.Locale; /** * TestViewTag is a class ... *

* Lifetime And Scope

* */ public class TestViewTag extends JspFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/TestViewTag.jsp"; public static final String TEST_URI2 = "/TestViewTag2.jsp"; // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestViewTag() { super("TestViewTag"); } public TestViewTag(String name) { super(name); } // // Class methods // // // General Methods // public void beginViewTag(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); } public void testViewTag() { boolean result = false; String value = null; Locale expectedLocale = new Locale("ps", "PS"); Phase renderResponse = new RenderResponsePhase(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setId("root"); page.setLocale(Locale.US); page.setViewId(TEST_URI); page.setLocale(Locale.CANADA_FRENCH); getFacesContext().setViewRoot(page); Config.set((ServletRequest) getFacesContext().getExternalContext().getRequest(), Config.FMT_LOCALE, Locale.CANADA_FRENCH); try { renderResponse.execute(getFacesContext()); } catch (FacesException fe) { System.out.println(fe.getMessage()); if (null != fe.getCause()) { fe.getCause().printStackTrace(); } else { fe.printStackTrace(); } } assertEquals("locale not as expected", expectedLocale, page.getLocale()); assertEquals("locale not as expected", expectedLocale, Config.get((ServletRequest) getFacesContext().getExternalContext(). getRequest(), Config.FMT_LOCALE)); } public void beginViewTagVB(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI2, null); } public void testViewTagVB() { boolean result = false; String value = null; Locale expectedLocale = new Locale("ps", "PS", "Traditional"); request.setAttribute("locale", expectedLocale); Phase renderResponse = new RenderResponsePhase(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setId("root"); page.setLocale(Locale.US); page.setViewId(TEST_URI2); getFacesContext().setViewRoot(page); try { renderResponse.execute(getFacesContext()); } catch (FacesException fe) { System.out.println(fe.getMessage()); if (null != fe.getCause()) { fe.getCause().printStackTrace(); } else { fe.printStackTrace(); } } assertEquals("locale not as expected", expectedLocale, page.getLocale()); } public void testGetLocaleFromString() { ViewTag viewTag = new ViewTag(); Locale locale = (Locale) TestingUtil.invokePrivateMethod("getLocaleFromString", new Class[] { String.class }, new Object[] { "fr-FR" }, ViewTag.class, viewTag); assertTrue(locale.equals(new Locale("fr", "FR"))); locale = (Locale) TestingUtil.invokePrivateMethod("getLocaleFromString", new Class[] { String.class }, new Object[] { "fr_FR" }, ViewTag.class, viewTag); assertTrue(locale.equals(new Locale("fr", "FR"))); locale = (Locale) TestingUtil.invokePrivateMethod("getLocaleFromString", new Class[] {String.class}, new Object[] {"fr"}, ViewTag.class, viewTag); assertTrue(locale.equals(new Locale("fr", ""))); locale = (Locale) TestingUtil.invokePrivateMethod("getLocaleFromString", new Class[] {String.class}, new Object[] {"testLocale"}, ViewTag.class, viewTag); assertTrue(locale.equals(Locale.getDefault())); } } // end of class TestViewTag mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/jsf_core/TestLoadBundleTag.java0000644000000000000000000001647611412443352025032 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestLoadBundleTag.java package com.sun.faces.taglib.jsf_core; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import javax.faces.component.UIViewRoot; import javax.faces.application.Application; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import java.util.Map; import java.util.Locale; public class TestLoadBundleTag extends ServletFacesTestCase { // // Protected Constants // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestLoadBundleTag() { super("TestLoadBundleTag.java"); } public TestLoadBundleTag(String name) { super(name); } // // Class methods // // // General Methods // public void testLoadBundle() throws Exception { getFacesContext().setViewRoot(Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null)); getFacesContext().getViewRoot().setLocale(Locale.US); LoadBundleTag tag = new LoadBundleTag(); ExpressionFactory factory = getFacesContext().getApplication().getExpressionFactory(); ValueExpression expr = factory.createValueExpression(getFacesContext().getELContext(), "com.sun.faces.TestMessages",String.class); tag.setBasename(expr); tag.setVar("messages"); tag.doStartTag(); assertEquals("Didn't get expected value", ((Map) getFacesContext().getExternalContext() .getRequestMap() .get("messages")).get("buckaroo"), "banzai"); assertEquals("Didn't get expected value", ((Map) getFacesContext().getExternalContext() .getRequestMap() .get("messages")).get("john"), "bigboote"); assertEquals("???notpresent???", ((Map) getFacesContext().getExternalContext() .getRequestMap() .get("messages")).get("notpresent")); } //test out full Map contract implementation of LoadBundleTag public void testLoadBundleMap() throws Exception { boolean gotException = false; Object key = "buckaroo"; Object value = "banzai"; ExpressionFactory factory = getFacesContext().getApplication().getExpressionFactory(); ValueExpression expr = factory.createValueExpression(getFacesContext().getELContext(), "com.sun.faces.TestMessages",String.class); getFacesContext().setViewRoot(Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null)); getFacesContext().getViewRoot().setLocale(Locale.US); LoadBundleTag tag = new LoadBundleTag(); tag.setBasename(expr); tag.setVar("messages"); tag.doStartTag(); Map testMap = (Map) getFacesContext().getExternalContext() .getRequestMap() .get("messages"); LoadBundleTag tag2 = new LoadBundleTag(); tag2.setBasename(expr); tag2.setVar("messages2"); tag2.doStartTag(); Map testMap2 = (Map) getFacesContext().getExternalContext() .getRequestMap() .get("messages2"); try { testMap.clear(); } catch (UnsupportedOperationException ex) { gotException = true; } assertTrue("Map.clear() should not be supported for immutable Map", gotException); gotException = false; assertTrue("key not in Map", testMap.containsKey(key)); assertTrue("value not in Map", testMap.containsValue(value)); assertTrue("entrySet not correct for Map", testMap.entrySet().equals(testMap2.entrySet())); assertTrue("Same maps are not equal", testMap.equals(testMap2)); assertEquals("value not in Map", testMap.get(key), value); //two equal sets should have same hashcode assertTrue("HashCode not valid", testMap.hashCode() == testMap2.hashCode()); assertFalse("Map should not be empty", testMap.isEmpty()); assertTrue("keySet not valid", testMap.keySet().contains(key)); try { testMap.put(key, value); } catch (UnsupportedOperationException ex) { gotException = true; } assertTrue("Map.put() should not be supported for immutable Map", gotException); gotException = false; try { testMap.putAll(new java.util.HashMap()); } catch (UnsupportedOperationException ex) { gotException = true; } assertTrue("Map.putAll() should not be supported for immutable Map", gotException); gotException = false; try { testMap.remove(key); } catch (UnsupportedOperationException ex) { gotException = true; } assertTrue("Map.remove() should not be supported for immutable Map", gotException); gotException = false; assertTrue("Map size incorrect", testMap.size() == 4); assertTrue("values from Map incorrect", testMap.values().contains(value)); } } // end of class TestLoadBundleTag mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/taglib/TestCoreValidator.java0000644000000000000000000000425111412443352023315 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.taglib; import com.sun.faces.taglib.jsf_core.CoreValidator; import org.xml.sax.helpers.DefaultHandler; public class TestCoreValidator extends CoreValidator { public DefaultHandler getSAXHandler() { return super.getSAXHandler(); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/0000755000000000000000000000000011412443350020111 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/PropertyResolverTestImpl.java0000644000000000000000000000471311412443350026011 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import com.sun.faces.TestPropertyResolver; import javax.faces.el.PropertyResolver; public class PropertyResolverTestImpl extends TestPropertyResolver{ PropertyResolver root = null; public PropertyResolverTestImpl(PropertyResolver root) { super(root); this.root = root; } public Object getValue(Object base, Object property) { if (property.equals("customPRTest2")) { return "PropertyResolverTestImpl"; } return root.getValue(base, property); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestAdapters.java0000644000000000000000000005634011412443350023367 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import javax.el.ELContext; import javax.el.MethodExpression; import javax.el.MethodInfo; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.el.EvaluationException; import javax.faces.el.MethodBinding; import javax.faces.el.MethodNotFoundException; import javax.faces.el.ValueBinding; import javax.faces.el.PropertyNotFoundException; import com.sun.faces.cactus.ServletFacesTestCase; /** * This test case will validate the various adapter classes * found in jsf-api/template-src */ @SuppressWarnings("deprecation") public class TestAdapters extends ServletFacesTestCase { ExpressionFactory factory; public TestAdapters() { super("TestAdapters"); } public TestAdapters(String name) { super(name); } @Override public void setUp() { try { factory = (ExpressionFactory) Class.forName("com.sun.el.ExpressionFactoryImpl").newInstance(); } catch (Exception e) { System.out.println(e); } super.setUp(); } @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------ Test Methods public void testMEMBAdapterTest() throws Exception { // Phase 1 // - validate NPEs are thrown as expected TestMethodBinding binding = new TestMethodBinding("#{simple.invoke}", Double.class, new MySimpleBean()); MethodExpressionMethodBindingAdapter meAdapter = new MethodExpressionMethodBindingAdapter(binding); FacesContext fContext = getFacesContext(); ExternalContext extContext = fContext.getExternalContext(); TestMethodExpression methodExpr = new TestMethodExpression("invoke", "#{foo.invoke}", Double.class, new Class[] { String.class }, new MySimpleBean()); TestMethodExpression falseExpr = new TestMethodExpression("invoke", "#{foo.invoke}", String.class, new Class[] { String.class }, new MySimpleBean()); extContext.getRequestMap().put("simple", new MySimpleBean()); // Phase 1 // - validate NPEs are thrown as expected try { meAdapter.getMethodInfo(null); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } try { meAdapter.invoke(null, new Object[] { "1.4" }); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } // Phase 2 // - validate methods with correct input MethodInfo info = meAdapter.getMethodInfo(fContext.getELContext()); assertTrue(Double.class.equals(info.getReturnType())); Object obj = meAdapter.invoke(fContext.getELContext(), new Object[] { "1.3" }); assertTrue (obj instanceof Double); assertTrue ("1.3".equals(obj.toString())); // Phase 3 // - validate the equals() method assertTrue(!meAdapter.equals(null)); // if the reference is to the same object, it should return true assertTrue(meAdapter.equals(meAdapter)); // if the argument passed is another MethodExpressionMethodBindingAdapter // with the same binding, it should return true MethodExpressionMethodBindingAdapter meTrue = new MethodExpressionMethodBindingAdapter(binding); MethodExpressionMethodBindingAdapter meFalse = new MethodExpressionMethodBindingAdapter(new TestMethodBinding("#{foo.invoke}", String.class, new MySimpleBean())); assertTrue(meAdapter.equals(meTrue)); assertTrue(!meAdapter.equals(meFalse)); // if a MethodBinding is provided, then a little more work will // be performed - ensure this works if (factory != null) { ApplicationAssociate.getInstance(extContext).setExpressionFactory(factory); assertTrue(meAdapter.equals(methodExpr)); assertTrue(!meAdapter.equals(falseExpr)); } } public void testMBMEAdapterTest() throws Exception { TestMethodExpression expression = new TestMethodExpression("invoke", "#{simple.invoke}", Double.class, new Class[] { String.class }, new MySimpleBean()); MethodBindingMethodExpressionAdapter mbAdapter = new MethodBindingMethodExpressionAdapter(expression); FacesContext fContext = getFacesContext(); ExternalContext extContext = fContext.getExternalContext(); TestMethodBinding methodBinding = new TestMethodBinding("#{foo.invoke}", Double.class, new MySimpleBean()); TestMethodBinding falseBinding = new TestMethodBinding("#{foo.invoke}", String.class, new MySimpleBean()); extContext.getRequestMap().put("foo", new MySimpleBean()); // Phase 1 // - validate NPEs are thrown as expected try { mbAdapter.getType(null); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } try { mbAdapter.invoke(null, new Object[]{ "" }); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } // Phase 2 // - validate methods with correct input assertTrue(Double.class.equals(mbAdapter.getType(fContext))); Object obj = mbAdapter.invoke(fContext, new Object[] { "1.3" }); assertTrue (obj instanceof Double); assertTrue ("1.3".equals(obj.toString())); // Phase 3 // - validate the equals() method assertTrue(!mbAdapter.equals(null)); // if the reference is to the same object, it should return true assertTrue(mbAdapter.equals(mbAdapter)); // if the argument passed is another MethodExpressionMethodBindingAdapter // with the same binding, it should return true MethodBindingMethodExpressionAdapter mbTrue = new MethodBindingMethodExpressionAdapter(expression); MethodBindingMethodExpressionAdapter mbFalse = new MethodBindingMethodExpressionAdapter(new TestMethodExpression("invoke", "#{foo.invoke}", String.class, new Class[] { Double.class }, new MySimpleBean())); assertTrue(mbAdapter.equals(mbTrue)); assertTrue(!mbAdapter.equals(mbFalse)); // if a MethodBinding is provided, then a little more work will // be performed - ensure this works if (factory != null) { ApplicationAssociate.getInstance(extContext).setExpressionFactory(factory); assertTrue(mbAdapter.equals(methodBinding)); assertTrue(!mbAdapter.equals(falseBinding)); } } public void testVEVBAdapterTest() throws Exception { TestValueBinding binding = new TestValueBinding("#{simple.double}", new MySimpleBean(), Double.class); ValueExpressionValueBindingAdapter veAdapter = new ValueExpressionValueBindingAdapter(binding); FacesContext fContext = getFacesContext(); ELContext elContext = fContext.getELContext(); // Phase 1 // - validate NPEs are thrown as expected try { veAdapter.getType(null); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } try { veAdapter.getValue(null); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } try { veAdapter.setValue(null, "string"); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } try { veAdapter.isReadOnly(null); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } // Phase 2 // - validate methods with correct input assertTrue(Double.class.equals(veAdapter.getType(elContext))); assertTrue(Double.valueOf("1.5").equals(veAdapter.getValue(elContext))); assertTrue(veAdapter.isReadOnly(elContext)); // Phase 3 // - validate the equals() method assertTrue(veAdapter.equals(veAdapter)); ValueExpressionValueBindingAdapter trueAdapter = new ValueExpressionValueBindingAdapter(binding); ValueExpressionValueBindingAdapter falseAdapter = new ValueExpressionValueBindingAdapter( new TestValueBinding("#{simple.double}", new MySimpleBean(), String.class)); assertTrue(veAdapter.equals(trueAdapter)); assertTrue(!veAdapter.equals(falseAdapter)); ValueExpression trueVE = new TestValueExpression("#{ping.double}", Double.class, new MySimpleBean()); ValueExpression falseVE = new TestValueExpression("#{foo.double}", String.class, new MySimpleBean()); assertTrue(veAdapter.equals(trueVE)); assertTrue(!veAdapter.equals(falseVE)); } public void testVBVEAdapterTest() throws Exception { ValueExpression expression = new TestValueExpression("#{simple.double}", Double.class, new MySimpleBean()); ValueBindingValueExpressionAdapter vbAdapter = new ValueBindingValueExpressionAdapter(expression); FacesContext fContext = getFacesContext(); // Phase 1 // - validate NPEs are thrown as expected try { vbAdapter.getType(null); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } try { vbAdapter.getValue(null); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } try { vbAdapter.isReadOnly(null); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } try { vbAdapter.setValue(null, "string"); assertTrue(false); } catch (Exception e) { if (!(e instanceof NullPointerException)) { assertTrue(false); } } // Phase 2 // - validate methods with correct input assertTrue(Double.class.equals(vbAdapter.getType(fContext))); assertTrue(new Double(1.5).equals(vbAdapter.getValue(fContext))); assertTrue(vbAdapter.isReadOnly(fContext)); // Phase 3 // - validate the equals() method assertTrue(vbAdapter.equals(vbAdapter)); ValueBindingValueExpressionAdapter trueAdapter = new ValueBindingValueExpressionAdapter(expression); ValueBindingValueExpressionAdapter falseAdapter = new ValueBindingValueExpressionAdapter( new TestValueExpression("#{foo.double}", String.class, new MySimpleBean())); assertTrue(vbAdapter.equals(trueAdapter)); assertTrue(!vbAdapter.equals(falseAdapter)); ValueBinding trueVB = new TestValueBinding("#{ping.double}", new MySimpleBean(), Double.class); ValueBinding falseVB = new TestValueBinding("#{foo.double}", new MySimpleBean(), String.class); assertTrue(vbAdapter.equals(trueVB)); assertTrue(!vbAdapter.equals(falseVB)); } // ----------------------------------------------------------- Inner Classes private static class MySimpleBean { Double value = 1.5; public Double getDouble() { return value; } public Double invoke(String value) { return Double.valueOf(value); } public String invoked(String value) { return value; } } private static class TestValueExpression extends ValueExpression { private String expr; private Class returnType; private MySimpleBean bean; public TestValueExpression(String expr, Class returnType, MySimpleBean bean) { this.expr = expr; this.returnType = returnType; this.bean = bean; } public Object getValue(ELContext elContext) { if (elContext == null) { throw new NullPointerException(); } return bean.getDouble(); } public void setValue(ELContext elContext, Object object) { if (elContext == null) { throw new NullPointerException(); } } public boolean isReadOnly(ELContext elContext) { if (elContext == null) { throw new NullPointerException(); } return true; } public Class getType(ELContext elContext) { if (elContext == null) { throw new NullPointerException(); } return returnType; } public Class getExpectedType() { return returnType; } public String getExpressionString() { return expr; } public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof TestValueExpression) { TestValueExpression v = (TestValueExpression) object; return v.getExpressionString().equals(expr) && v.getExpectedType().equals(returnType); } return false; } public int hashCode() { return (expr.hashCode() ^ returnType.hashCode()); } public boolean isLiteralText() { return false; } } private static class TestValueBinding extends ValueBinding { String expr; MySimpleBean bean; Class returnType; public TestValueBinding(String expr, MySimpleBean bean, Class returnType) { this.expr = expr; this.bean = bean; this.returnType = returnType; } public Object getValue(FacesContext context) throws EvaluationException, PropertyNotFoundException { if (context == null) { throw new NullPointerException(); } return bean.getDouble(); } public void setValue(FacesContext context, Object value) throws EvaluationException, PropertyNotFoundException { if (context == null) { throw new NullPointerException(); } } public boolean isReadOnly(FacesContext context) throws EvaluationException, PropertyNotFoundException { if (context == null) { throw new NullPointerException(); } return true; } public Class getType(FacesContext context) throws EvaluationException, PropertyNotFoundException { if (context == null) { throw new NullPointerException(); } return returnType; } } private static class TestMethodBinding extends MethodBinding { String exprString; Class returnType; MySimpleBean bean; public TestMethodBinding(String exprString, Class returnType, MySimpleBean bean) { this.exprString = exprString; this.returnType = returnType; this.bean = bean; } public Object invoke(FacesContext context, Object[] params) throws EvaluationException, MethodNotFoundException { if (context == null) { throw new NullPointerException(); } return bean.invoke((String) params[0]); } public Class getType(FacesContext context) throws MethodNotFoundException { if (context == null) { throw new NullPointerException(); } return returnType; } @Override public String getExpressionString() { return exprString; } } private static class TestMethodExpression extends MethodExpression { private String methodName; private String exprString; private Class returnType; private Class[] params; private MySimpleBean bean; private MethodInfo info; public TestMethodExpression(String methodName, String exprString, Class returnType, Class[] params, MySimpleBean bean) { this.methodName = methodName; this.exprString = exprString; this.returnType = returnType; this.params = params; this.bean = bean; info = new MethodInfo(methodName, returnType, params); } public MethodInfo getMethodInfo(ELContext elContext) { if (elContext == null) { throw new NullPointerException(); } return info; } public Object invoke(ELContext elContext, Object[] objects) { if (elContext == null) { throw new NullPointerException(); } return bean.invoke((String) objects[0]); } public String getExpressionString() { return exprString; } public boolean equals(Object object) { return this == object || object instanceof TestMethodExpression && (exprString.equals( ((TestMethodExpression) object).getExpressionString())); } public int hashCode() { return exprString.hashCode(); } public boolean isLiteralText() { return false; } } } // END TestAdaptersmojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestApplicationFactoryImpl.java0000644000000000000000000001061011412443350026227 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestApplicationFactoryImpl.java package com.sun.faces.application; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.config.ConfigureListener; import javax.faces.application.Application; /** * TestApplicationFactoryImpl is a class ... *

* Lifetime And Scope

*/ public class TestApplicationFactoryImpl extends JspFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // private ApplicationFactoryImpl applicationFactory = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestApplicationFactoryImpl() { super("TestApplicationFactoryImpl"); } public TestApplicationFactoryImpl(String name) { super(name); } // // Class methods // // // General Methods // public void testFactory() { applicationFactory = new ApplicationFactoryImpl(); ApplicationAssociate.clearInstance(getFacesContext().getExternalContext()); // 1. Verify "getApplication" returns the same Application instance // if called multiple times. // Application application1 = applicationFactory.getApplication(); Application application2 = applicationFactory.getApplication(); assertTrue(application1 == application2); // 2. Verify "setApplication" adds instances.. / // and "getApplication" returns the same instance // ApplicationAssociate.clearInstance(getFacesContext().getExternalContext()); Application application3 = new ApplicationImpl(); applicationFactory.setApplication(application3); Application application4 = applicationFactory.getApplication(); assertTrue(application3 == application4); } public void testSpecCompliance() { applicationFactory = new ApplicationFactoryImpl(); ApplicationAssociate.clearInstance(getFacesContext().getExternalContext()); assertTrue(null != applicationFactory.getApplication()); } public void testExceptions() { applicationFactory = new ApplicationFactoryImpl(); // 1. Verify NullPointer exception which occurs when attempting // to add a null Application // boolean thrown = false; try { applicationFactory.setApplication(null); } catch (NullPointerException e) { thrown = true; } assertTrue(thrown); } } // end of class TestApplicationFactoryImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/VariableResolverTestImpl.java0000644000000000000000000000426111412443350025710 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import com.sun.faces.TestVariableResolver; import javax.faces.el.VariableResolver; public class VariableResolverTestImpl extends TestVariableResolver { public VariableResolverTestImpl(VariableResolver root) { super(root); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestHASDeprStateManagerImpl.java0000644000000000000000000001375111412443350026167 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import org.apache.cactus.WebRequest; import org.apache.cactus.server.ServletConfigWrapper; import com.sun.faces.RIConstants; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import javax.faces.FacesException; import javax.faces.application.StateManager; import javax.faces.application.ViewHandler; import javax.faces.application.StateManager.SerializedView; import javax.faces.component.UIComponent; import javax.faces.component.UIGraphic; import javax.faces.component.UIInput; import javax.faces.component.UIOutput; import javax.faces.component.UIViewRoot; import javax.faces.component.UIForm; import javax.faces.component.UIPanel; import javax.faces.context.FacesContext; import javax.faces.render.RenderKitFactory; import javax.servlet.http.HttpSession; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; /** * This class tests the StateManagerImpl class with deprecated * methods only - does not contain any of the replacement methods (such * as saveView). */ public class TestHASDeprStateManagerImpl extends ServletFacesTestCase { public static final String TEST_URI = "/greeting.jsp"; public String getExpectedOutputFilename() { return "TestViewHandlerImpl_correct"; } public static final String ignore[] = { }; public String[] getLinesToIgnore() { return ignore; } public boolean sendResponseToFile() { return true; } // // Constructors/Initializers // public TestHASDeprStateManagerImpl() { super("TestHASDeprStateManagerImpl"); } public TestHASDeprStateManagerImpl(String name) { super(name); } private Application application = null; public void setUp() { super.setUp(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = (ApplicationImpl) aFactory.getApplication(); application.setViewHandler(new ViewHandlerImpl()); application.setStateManager(new DeprStateManagerImpl()); } // // Test Methods // public void beginRender(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); } public void testRender() { UIViewRoot newView = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), TEST_URI); newView.setLocale(Locale.US); getFacesContext().setViewRoot(newView); try { ViewHandler viewHandler = Util.getViewHandler(getFacesContext()); viewHandler.renderView(getFacesContext(), getFacesContext().getViewRoot()); } catch (IOException e) { System.out.println("ViewHandler IOException:" + e); } catch (FacesException fe) { System.out.println("ViewHandler FacesException: " + fe); } assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(verifyExpectedOutput()); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestApplicationImpl_Config.java0000644000000000000000000005077611412443350026205 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestApplicationImpl_Config.java package com.sun.faces.application; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.TestComponent; import com.sun.faces.TestConverter; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.application.ApplicationFactory; import javax.faces.application.NavigationHandler; import javax.faces.application.StateManager; import javax.faces.application.ViewHandler; import javax.faces.component.UIComponent; import javax.faces.convert.Converter; import javax.faces.el.PropertyResolver; import javax.faces.el.VariableResolver; import javax.faces.event.ActionListener; import javax.faces.validator.LengthValidator; import javax.faces.validator.Validator; import java.util.Iterator; import java.util.Locale; /** * TestApplicationImpl_Config is a class ... *

* Lifetime And Scope

*/ public class TestApplicationImpl_Config extends ServletFacesTestCase { // // Protected Constants // public static String standardComponentTypes[] = { "javax.faces.Column", "javax.faces.Command", "javax.faces.Data", "javax.faces.Form", "javax.faces.Graphic", "javax.faces.Input", "javax.faces.Message", "javax.faces.Messages", "javax.faces.NamingContainer", "javax.faces.Output", "javax.faces.Panel", "javax.faces.Parameter", "javax.faces.SelectBoolean", "javax.faces.SelectItem", "javax.faces.SelectItems", "javax.faces.SelectMany", "javax.faces.SelectOne", "javax.faces.ViewRoot", "javax.faces.HtmlCommandButton", "javax.faces.HtmlCommandLink", "javax.faces.HtmlDataTable", "javax.faces.HtmlForm", "javax.faces.HtmlGraphicImage", "javax.faces.HtmlInputHidden", "javax.faces.HtmlInputSecret", "javax.faces.HtmlInputText", "javax.faces.HtmlInputTextarea", "javax.faces.HtmlMessage", "javax.faces.HtmlMessages", "javax.faces.HtmlOutputFormat", "javax.faces.HtmlOutputLabel", "javax.faces.HtmlOutputLink", "javax.faces.HtmlOutputText", "javax.faces.HtmlPanelGrid", "javax.faces.HtmlPanelGroup", "javax.faces.HtmlSelectBooleanCheckbox", "javax.faces.HtmlSelectManyCheckbox", "javax.faces.HtmlSelectManyListbox", "javax.faces.HtmlSelectManyMenu", "javax.faces.HtmlSelectOneListbox", "javax.faces.HtmlSelectOneMenu", "javax.faces.HtmlSelectOneRadio" }; public static Class standardComponentClasses[] = { javax.faces.component.UIColumn.class, javax.faces.component.UICommand.class, javax.faces.component.UIData.class, javax.faces.component.UIForm.class, javax.faces.component.UIGraphic.class, javax.faces.component.UIInput.class, javax.faces.component.UIMessage.class, javax.faces.component.UIMessages.class, javax.faces.component.UINamingContainer.class, javax.faces.component.UIOutput.class, javax.faces.component.UIPanel.class, javax.faces.component.UIParameter.class, javax.faces.component.UISelectBoolean.class, javax.faces.component.UISelectItem.class, javax.faces.component.UISelectItems.class, javax.faces.component.UISelectMany.class, javax.faces.component.UISelectOne.class, javax.faces.component.UIViewRoot.class, javax.faces.component.html.HtmlCommandButton.class, javax.faces.component.html.HtmlCommandLink.class, javax.faces.component.html.HtmlDataTable.class, javax.faces.component.html.HtmlForm.class, javax.faces.component.html.HtmlGraphicImage.class, javax.faces.component.html.HtmlInputHidden.class, javax.faces.component.html.HtmlInputSecret.class, javax.faces.component.html.HtmlInputText.class, javax.faces.component.html.HtmlInputTextarea.class, javax.faces.component.html.HtmlMessage.class, javax.faces.component.html.HtmlMessages.class, javax.faces.component.html.HtmlOutputFormat.class, javax.faces.component.html.HtmlOutputLabel.class, javax.faces.component.html.HtmlOutputLink.class, javax.faces.component.html.HtmlOutputText.class, javax.faces.component.html.HtmlPanelGrid.class, javax.faces.component.html.HtmlPanelGroup.class, javax.faces.component.html.HtmlSelectBooleanCheckbox.class, javax.faces.component.html.HtmlSelectManyCheckbox.class, javax.faces.component.html.HtmlSelectManyListbox.class, javax.faces.component.html.HtmlSelectManyMenu.class, javax.faces.component.html.HtmlSelectOneListbox.class, javax.faces.component.html.HtmlSelectOneMenu.class, javax.faces.component.html.HtmlSelectOneRadio.class }; public static String standardConverterIds[] = { "javax.faces.BigDecimal", "javax.faces.BigInteger", "javax.faces.Boolean", "javax.faces.Byte", "javax.faces.Character", "javax.faces.DateTime", "javax.faces.Double", "javax.faces.Float", "javax.faces.Integer", "javax.faces.Long", "javax.faces.Number", "javax.faces.Short" }; public static Class standardConverterClasses[] = { javax.faces.convert.BigDecimalConverter.class, javax.faces.convert.BigIntegerConverter.class, javax.faces.convert.BooleanConverter.class, javax.faces.convert.ByteConverter.class, javax.faces.convert.CharacterConverter.class, javax.faces.convert.DateTimeConverter.class, javax.faces.convert.DoubleConverter.class, javax.faces.convert.FloatConverter.class, javax.faces.convert.IntegerConverter.class, javax.faces.convert.LongConverter.class, javax.faces.convert.NumberConverter.class, javax.faces.convert.ShortConverter.class }; public static Class standardConverterByIdClasses[] = { java.math.BigDecimal.class, java.math.BigInteger.class, java.lang.Boolean.class, java.lang.Byte.class, java.lang.Character.class, null, java.lang.Double.class, java.lang.Float.class, java.lang.Integer.class, java.lang.Long.class, null, java.lang.Short.class }; public static Class standardConverterPrimitiveClasses[] = { null, null, java.lang.Boolean.TYPE, java.lang.Byte.TYPE, java.lang.Character.TYPE, null, java.lang.Double.TYPE, java.lang.Float.TYPE, java.lang.Integer.TYPE, java.lang.Long.TYPE, null, java.lang.Short.TYPE }; // // Class Variables // // // Instance Variables // private ApplicationImpl application = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestApplicationImpl_Config() { super("TestApplicationImpl_Config"); } public TestApplicationImpl_Config(String name) { super(name); } // // Class methods // // // General Methods // public void setUp() { super.setUp(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = (ApplicationImpl) aFactory.getApplication(); } //**** //**** NOTE: We should add a test for finding a faces-config.xml file under //**** WEB-INF/classes/META-INF. //**** // // Test Config related methods // public void testComponentPositive() { TestComponent newTestComponent = null, testComponent = new TestComponent(); UIComponent uic = null; // runtime addition application.addComponent(testComponent.getComponentType(), "com.sun.faces.TestComponent"); assertTrue( null != (newTestComponent = (TestComponent) application.createComponent(testComponent.getComponentType()))); assertTrue(newTestComponent != testComponent); // built-in components for (int i = 0, len = standardComponentTypes.length; i < len; i++) { assertTrue(null != (uic = application.createComponent( standardComponentTypes[i]))); assertTrue( standardComponentClasses[i].isAssignableFrom(uic.getClass())); } } public void testComponentNegative() { boolean exceptionThrown = false; // componentType/componentClass with non-existent class try { application.addComponent("William", "BillyBoy"); application.createComponent("William"); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); // non-existent mapping exceptionThrown = false; try { application.createComponent("Joebob"); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testGetComponentTypes() { Iterator iter = application.getComponentTypes(); assertTrue(null != iter); assertTrue(isSubset(standardComponentTypes, iter)); } public void testConverterPositive() { TestConverter newTestConverter = null, testConverter = new TestConverter(); Converter conv = null; // runtime addition application.addConverter(testConverter.getConverterId(), "com.sun.faces.TestConverter"); assertTrue( null != (newTestConverter = (TestConverter) application.createConverter(testConverter.getConverterId()))); assertTrue(newTestConverter != testConverter); // built-in components // by-id for (int i = 0, len = standardConverterIds.length; i < len; i++) { assertTrue(null != (conv = application.createConverter( standardConverterIds[i]))); assertTrue( standardConverterClasses[i].isAssignableFrom(conv.getClass())); } // by-class for (int i = 0, len = standardConverterByIdClasses.length; i < len; i++) { // skip entries for which by-class registation doesn't make sense. if (null == standardConverterByIdClasses[i]) { continue; } assertTrue("null != " + standardConverterByIdClasses[i].toString(), null != (conv = application.createConverter( standardConverterByIdClasses[i]))); assertTrue( standardConverterClasses[i].isAssignableFrom(conv.getClass())); } // primitive classes for (int i = 0, len = standardConverterPrimitiveClasses.length; i < len; i++) { if (null == standardConverterPrimitiveClasses[i]) { continue; } assertTrue( "null != " + standardConverterPrimitiveClasses[i].toString(), null != (conv = application.createConverter( standardConverterPrimitiveClasses[i]))); assertTrue( standardConverterClasses[i].isAssignableFrom(conv.getClass())); } } public void testConverterNegative() { boolean exceptionThrown = false; // componentType/componentClass with non-existent class try { application.addConverter("William", "BillyBoy"); application.createConverter("William"); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); // non-existent mapping exceptionThrown = false; try { application.createConverter("Joebob"); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testGetConverterIds() { Iterator iter = application.getConverterIds(); assertTrue(null != iter); assertTrue(isSubset(standardConverterIds, iter)); } public void testValidatorPositive() { Validator newTestValidator = null, testValidator = new LengthValidator(); Validator val = null; // runtime addition application.addValidator("Billybob", "javax.faces.validator.LengthValidator"); assertTrue(null != (newTestValidator = application.createValidator("Billybob"))); assertTrue(newTestValidator != testValidator); // test standard components assertTrue( null != (val = application.createValidator("javax.faces.DoubleRange"))); assertTrue(val instanceof Validator); assertTrue( null != (val = application.createValidator("javax.faces.Length"))); assertTrue(val instanceof Validator); assertTrue( null != (val = application.createValidator("javax.faces.LongRange"))); assertTrue(val instanceof Validator); } public void testValidatorNegative() { boolean exceptionThrown = false; // componentType/componentClass with non-existent class try { application.addValidator("William", "BillyBoy"); application.createValidator("William"); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); // non-existent mapping exceptionThrown = false; try { application.createValidator("Joebob"); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testGetValidatorIds() { Iterator iter = application.getValidatorIds(); assertTrue(null != iter); String standardValidatorIds[] = { "javax.faces.DoubleRange", "javax.faces.Length", "javax.faces.LongRange" }; assertTrue(isSubset(standardValidatorIds, iter)); } public void testUpdateRuntimeComponents() { loadFromInitParam("/runtime-components.xml"); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = (ApplicationImpl) aFactory.getApplication(); ActionListener actionListener = null; NavigationHandler navHandler = null; PropertyResolver propResolver = null; VariableResolver varResolver = null; ViewHandler viewHandler = null; StateManager stateManager = null; assertTrue(null != (actionListener = application.getActionListener())); assertTrue(actionListener instanceof com.sun.faces.TestActionListener); assertTrue(null != (navHandler = application.getNavigationHandler())); assertTrue(navHandler instanceof com.sun.faces.TestNavigationHandler); // JSF1.2 BI: application.getPropertyResolver() no longer returns the // head of the PropertyResolver. Instead returns the head of the // ELResolver stack wrapped in a PropertyResolver.This also applies to // VariableResolver assertTrue(null != (propResolver = application.getPropertyResolver())); assertTrue( application.getPropertyResolver() instanceof javax.faces.el.PropertyResolver); assertTrue(null != (varResolver = application.getVariableResolver())); assertTrue(varResolver instanceof javax.faces.el.VariableResolver); assertTrue(null != (viewHandler = application.getViewHandler())); assertTrue(viewHandler instanceof javax.faces.application.ViewHandler); assertTrue(null != (stateManager = application.getStateManager())); assertTrue( stateManager instanceof javax.faces.application.StateManager); System.out.println("DEFAULT:" + application.getDefaultRenderKitId()); assertEquals("WackyRenderKit", application.getDefaultRenderKitId()); } public void testLocaleConfigPositive() { loadFromInitParam("/locale-config.xml"); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = (ApplicationImpl) aFactory.getApplication(); Locale locale; assertNotNull("Can't get default locale from Application", locale = application.getDefaultLocale()); assertEquals(Locale.US, locale); Iterator iter; int j = 0, len = 0; boolean found = false; String[][] expected = { {"de", "DE"}, {"en", "US"}, {"fr", "FR"}, {"ps", "PS"} }; len = expected.length; iter = application.getSupportedLocales(); System.out.println("actual supported locales: "); while (iter.hasNext()) { System.out.println(iter.next().toString()); } // test that the supported locales are a superset of the // expected locales for (j = 0; j < len; j++) { assertNotNull("Can't get supportedLocales from Application", iter = application.getSupportedLocales()); found = false; while (iter.hasNext()) { locale = (Locale) iter.next(); if (expected[j][0].equals(locale.getLanguage()) && expected[j][1].equals(locale.getCountry())) { found = true; } } assertTrue("Can't find expected locale " + expected[j][0] + "_" + expected[j][1] + " in supported-locales list", found); } } public void testLocaleConfigNegative2() { boolean exceptionThrown = false; try { loadFromInitParam("/locale-config2.xml"); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } } // end of class TestApplicationImpl_Config mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestActionListenerImpl.java0000644000000000000000000001454311412443350025370 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestActionListenerImpl.java package com.sun.faces.application; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import javax.faces.FacesException; import javax.faces.component.UICommand; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.faces.el.MethodBinding; import javax.faces.el.MethodNotFoundException; import javax.faces.event.ActionEvent; import java.util.Locale; /** * * TestActionListenerImpl is a class ... * * Lifetime And Scope

* */ /** * This class tests the ActionListenerImpl class * functionality. It uses the xml configuration file: * web/test/WEB-INF/faces-navigation.xml. */ public class TestActionListenerImpl extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestActionListenerImpl() { super("TestActionListenerImpl"); } public TestActionListenerImpl(String name) { super(name); } // // Class methods // // // Methods from TestCase // // // General Methods // public void testProcessAction() { loadFromInitParam("/WEB-INF/faces-navigation.xml"); FacesContext context = getFacesContext(); System.out.println("Testing With Action Literal Set..."); UICommand command = new UICommand(); command.setAction( context.getApplication().createMethodBinding( "#{newCustomer.loginRequired}", null)); UIViewRoot page = Util.getViewHandler(context).createView(context, null); page.setViewId("/login.jsp"); page.setLocale(Locale.US); context.setViewRoot(page); ActionListenerImpl actionListener = new ActionListenerImpl(); ActionEvent actionEvent = new ActionEvent(command); actionListener.processAction(actionEvent); String newViewId = context.getViewRoot().getViewId(); assertTrue(newViewId.equals("/must-login-first.jsp")); System.out.println("Testing With Action Set..."); command = new UICommand(); MethodBinding binding = context.getApplication().createMethodBinding("#{userBean.login}", null); command.setAction(binding); UserBean user = new UserBean(); context.getExternalContext().getSessionMap().put("userBean", user); assertTrue( user == context.getExternalContext().getSessionMap().get("userBean")); page = Util.getViewHandler(context).createView(context, null); page.setViewId("/login.jsp"); page.setLocale(Locale.US); context.setViewRoot(page); actionEvent = new ActionEvent(command); actionListener.processAction(actionEvent); newViewId = context.getViewRoot().getViewId(); // expected outcome should be view id corresponding to "page/outcome" search.. assertTrue(newViewId.equals("/home.jsp")); } public void testIllegalArgException() { boolean exceptionThrown = false; FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(context, null); page.setViewId("/login.jsp"); context.setViewRoot(page); UserBean user = new UserBean(); context.getExternalContext().getApplicationMap().put("UserBean", user); assertTrue( user == context.getExternalContext().getApplicationMap().get("UserBean")); UICommand command = new UICommand(); MethodBinding binding = context.getApplication().createMethodBinding("#{UserBean.noMeth}", null); command.setAction(binding); ActionEvent actionEvent = new ActionEvent(command); ActionListenerImpl actionListener = new ActionListenerImpl(); try { actionListener.processAction(actionEvent); } catch (FacesException e) { assertTrue(e.getCause() instanceof MethodNotFoundException); exceptionThrown = true; } assertTrue(exceptionThrown); } public static class UserBean extends Object { public String login() { return ("success"); } } } // end of class TestActionListenerImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestApplicationImpl.java0000644000000000000000000010460511412443350024707 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestApplicationImpl.java package com.sun.faces.application; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.List; import java.util.Date; import java.util.ArrayList; import java.io.IOException; import java.net.URL; import javax.el.ELException; import javax.el.ValueExpression; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.view.facelets.ResourceResolver; import javax.faces.render.RenderKitFactory; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.application.NavigationHandler; import javax.faces.application.StateManager; import javax.faces.application.ResourceDependencies; import javax.faces.application.ResourceDependency; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.UIInput; import javax.faces.component.UIOutput; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; import javax.faces.context.ExternalContext; import javax.faces.convert.Converter; import javax.faces.convert.IntegerConverter; import javax.faces.el.PropertyResolver; import javax.faces.el.ReferenceSyntaxException; import javax.faces.el.ValueBinding; import javax.faces.el.VariableResolver; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import javax.faces.event.ListenerFor; import javax.faces.event.PostAddToViewEvent; import javax.faces.event.ComponentSystemEventListener; import javax.faces.event.ComponentSystemEvent; import javax.faces.event.AbortProcessingException; import javax.faces.event.ListenersFor; import javax.faces.event.PreRenderComponentEvent; import com.sun.faces.RIConstants; import com.sun.faces.TestComponent; import com.sun.faces.TestForm; import com.sun.faces.facelets.FaceletFactory; import com.sun.faces.facelets.Facelet; import com.sun.faces.facelets.impl.DefaultFaceletFactory; import com.sun.faces.config.WebConfiguration; import static com.sun.faces.config.WebConfiguration.WebContextInitParameter.*; import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.DisableFaceletJSFViewHandler; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.cactus.TestingUtil; /** * TestApplicationImpl is a class ... *

* Lifetime And Scope

*/ public class TestApplicationImpl extends JspFacesTestCase { // // Protected Constants // public static final String HANDLED_ACTIONEVENT1 = "handledValueEvent1"; public static final String HANDLED_ACTIONEVENT2 = "handledValueEvent2"; // // Class Variables // // // Instance Variables // private ApplicationImpl application = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestApplicationImpl() { super("TestApplicationImpl"); } public TestApplicationImpl(String name) { super(name); } // // Class methods // // // General Methods // public void setUp() { super.setUp(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = (ApplicationImpl) aFactory.getApplication(); } public void testAccessors() { assertTrue(application.getELResolver() != null); assertTrue(application.getExpressionFactory() != null); // 1. Verify "getActionListener" returns the same ActionListener // instance if called multiple times. // ActionListener actionListener1 = new ValidActionListener(); application.setActionListener(actionListener1); ActionListener actionListener2 = application.getActionListener(); ActionListener actionListener3 = application.getActionListener(); assertTrue((actionListener1 == actionListener2) && (actionListener1 == actionListener3)); // 2. Verify "getNavigationHandler" returns the same NavigationHandler // instance if called multiple times. // NavigationHandler navigationHandler1 = new NavigationHandlerImpl(); application.setNavigationHandler(navigationHandler1); NavigationHandler navigationHandler2 = application.getNavigationHandler(); NavigationHandler navigationHandler3 = application.getNavigationHandler(); assertTrue((navigationHandler1 == navigationHandler2) && (navigationHandler1 == navigationHandler3)); // 3. Verify "getPropertyResolver" returns the same PropertyResolver // instance if called multiple times. // PropertyResolver propertyResolver1 = application.getPropertyResolver(); PropertyResolver propertyResolver2 = application.getPropertyResolver(); PropertyResolver propertyResolver3 = application.getPropertyResolver(); assertTrue((propertyResolver1 == propertyResolver2) && (propertyResolver1 == propertyResolver3)); // 4. Verify "getVariableResolver" returns the same VariableResolver // instance if called multiple times. // VariableResolver variableResolver1 = application.getVariableResolver(); VariableResolver variableResolver2 = application.getVariableResolver(); VariableResolver variableResolver3 = application.getVariableResolver(); assertTrue((variableResolver1 == variableResolver2) && (variableResolver1 == variableResolver3)); // 5. Verify "getStateManager" returns the same StateManager // instance if called multiple times. // StateManager stateManager1 = new StateManagerImpl(); application.setStateManager(stateManager1); StateManager stateManager2 = application.getStateManager(); StateManager stateManager3 = application.getStateManager(); assertTrue((stateManager1 == stateManager2) && (stateManager1 == stateManager3)); } public void testExceptions() { boolean thrown; // 1. Verify NullPointer exception which occurs when attempting // to set a null ActionListener // thrown = false; try { application.setActionListener(null); } catch (NullPointerException e) { thrown = true; } assertTrue(thrown); // 3. Verify NullPointer exception which occurs when attempting // to set a null NavigationHandler // thrown = false; try { application.setNavigationHandler(null); } catch (NullPointerException e) { thrown = true; } assertTrue(thrown); // 4. Verify NPE occurs when attempting to set // a null PropertyResolver thrown = false; try { application.setPropertyResolver(null); } catch (NullPointerException npe) { thrown = true; } assertTrue(thrown); // 5. Verify NPE occurs when attempting to set // a null VariableResolver thrown = false; try { application.setVariableResolver(null); } catch (NullPointerException npe) { thrown = true; } assertTrue(thrown); // 5. Verify ISE occurs when attempting to set // a VariableResolver after a request has been processed ApplicationAssociate associate = ApplicationAssociate.getInstance( getFacesContext().getExternalContext()); associate.setRequestServiced(); thrown = false; try { application.setVariableResolver(application.getVariableResolver()); } catch (IllegalStateException e) { thrown = true; } assertTrue(thrown); // 6. Verify ISE occurs when attempting to set // a PropertyResolver after a request has been processed thrown = false; try { application.setPropertyResolver(application.getPropertyResolver()); } catch (IllegalStateException e) { thrown = true; } assertTrue(thrown); // 7. Verify NullPointer exception which occurs when attempting // to get a ValueBinding with a null ref // thrown = false; try { application.createValueBinding(null); } catch (Exception e) { thrown = true; } assertTrue(thrown); // 8.Verify NullPointerException occurs when attempting to pass a // null VariableResolver // thrown = false; try { application.setVariableResolver(null); } catch (NullPointerException e) { thrown = true; } assertTrue(thrown); // 9. Verify NullPointer exception which occurs when attempting // to set a null StateManager // thrown = false; try { application.setStateManager(null); } catch (NullPointerException e) { thrown = true; } assertTrue(thrown); thrown = false; try { application.createValueBinding("improperexpression"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("improper expression"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("improper\texpression"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("improper\rexpression"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("improper\nexpression"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("#improperexpression"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("#{improperexpression"); } catch (ReferenceSyntaxException e) { thrown = true; } assertTrue(thrown); thrown = false; try { application.createValueBinding("improperexpression}"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("{improperexpression}"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("improperexpression}#"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("#{proper[\"a key\"]}"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); try { application.createValueBinding("#{proper[\"a { } key\"]}"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); try { application.createValueBinding("bean.a{indentifer"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("bean['invalid'"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("bean[[\"invalid\"]].foo"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); thrown = false; try { application.createValueBinding("#{bean[\"[a\"]}"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); try { application.createValueBinding("#{bean[\".a\"]}"); } catch (ReferenceSyntaxException e) { thrown = true; } assertFalse(thrown); } public class InvalidActionListener implements ActionListener { public void processAction(ActionEvent event) { System.setProperty(HANDLED_ACTIONEVENT1, HANDLED_ACTIONEVENT1); } } public class ValidActionListener implements ActionListener { public void processAction(ActionEvent event) { System.setProperty(HANDLED_ACTIONEVENT2, HANDLED_ACTIONEVENT2); } } // // Test Config related methods // public void testAddComponentPositive() { TestComponent newTestComponent = null, testComponent = new TestComponent(); application.addComponent(testComponent.getComponentType(), "com.sun.faces.TestComponent"); assertTrue( null != (newTestComponent = (TestComponent) application.createComponent(testComponent.getComponentType()))); assertTrue(newTestComponent != testComponent); } public void testCreateComponentExtension() { application.addComponent(TestForm.COMPONENT_TYPE, TestForm.class.getName()); UIComponent c = application.createComponent(TestForm.COMPONENT_TYPE); assertTrue(c != null); } public void testGetComponentWithRefNegative() { ValueBinding valueBinding = null; boolean exceptionThrown = false; UIComponent result = null; getFacesContext().getExternalContext().getSessionMap().put("TAIBean", this); assertTrue(null != (valueBinding = application.createValueBinding( "#{sessionScope.TAIBean}"))); try { result = application.createComponent(valueBinding, getFacesContext(), "notreached"); assertTrue(false); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testGetComponentExpressionRefNegative() throws ELException{ ValueExpression valueBinding = null; boolean exceptionThrown = false; UIComponent result = null; getFacesContext().getExternalContext().getSessionMap().put("TAIBean", this); assertTrue(null != (valueBinding = application.getExpressionFactory().createValueExpression( getFacesContext().getELContext(), "#{sessionScope.TAIBean}", Object.class))); try { result = application.createComponent(valueBinding, getFacesContext(), "notreached"); assertTrue(false); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); // make sure FacesException is thrown when a bogus ValueExpression is // passed to createComponent. JSF RI Issue 162 assertTrue(null != (valueBinding = application.getExpressionFactory().createValueExpression( getFacesContext().getELContext(), "#{a.b}", Object.class))); try { result = application.createComponent(valueBinding, getFacesContext(), "notreached"); assertTrue(false); } catch (FacesException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testSetViewHandlerException() throws Exception { // RELEASE_PENDING - FIX. There seems to be a problem // with the test framework exposing two different applicationassociate // instances. As such, the flag denoting that a request has // been processed is never flagged and thus this test fails. /* ViewHandler handler = new ViewHandlerImpl(); UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setViewId("/view"); root.setId("id"); root.setLocale(Locale.US); getFacesContext().setViewRoot(root); boolean exceptionThrown = false; try { application.setViewHandler(handler); } catch (IllegalStateException ise) { exceptionThrown = true; } assertTrue(!exceptionThrown); try { handler.renderView(getFacesContext(), getFacesContext().getViewRoot()); application.setViewHandler(handler); } catch (IllegalStateException ise) { exceptionThrown = true; } assertTrue(exceptionThrown); // and test setting the StateManager too. exceptionThrown = false; try { application.setStateManager(new StateManagerImpl()); } catch (IllegalStateException ise) { exceptionThrown = true; } assertTrue(exceptionThrown); */ } // Ensure ApplicationImpl.setDefaultLocale(null) throws NPE public void testSetDefaultLocaleNPE() throws Exception { try { application.setDefaultLocale(null); assertTrue(false); } catch (NullPointerException npe) { ; // we're ok } } public void testResourceBundle() throws Exception { ResourceBundle rb = null; UIViewRoot root = new UIViewRoot(); root.setLocale(Locale.ENGLISH); getFacesContext().setViewRoot(root); // negative test, non-existant rb rb = application.getResourceBundle(getFacesContext(), "bogusName"); assertNull(rb); // basic test, existing rb rb = application.getResourceBundle(getFacesContext(), "testResourceBundle"); assertNotNull(rb); String value = rb.getString("value1"); assertEquals("Jerry", value); // switch locale to German getFacesContext().getViewRoot().setLocale(Locale.GERMAN); rb = application.getResourceBundle(getFacesContext(), "testResourceBundle"); assertNotNull(rb); value = rb.getString("value1"); assertEquals("Bernhard", value); // switch to a different rb rb = application.getResourceBundle(getFacesContext(), "testResourceBundle2"); assertNotNull(rb); value = rb.getString("label"); assertEquals("Abflug", value); } public void testLegacyPropertyResolversWithUnifiedEL() { ValueExpression ve1 = application.getExpressionFactory(). createValueExpression(getFacesContext().getELContext(), "#{mixedBean.customPRTest1}", Object.class); Object result = ve1.getValue(getFacesContext().getELContext()); assertTrue(result.equals("TestPropertyResolver")); ValueExpression ve2 = application.getExpressionFactory(). createValueExpression(getFacesContext().getELContext(), "#{mixedBean.customPRTest2}", Object.class); result = ve2.getValue(getFacesContext().getELContext()); assertTrue(result.equals("PropertyResolverTestImpl")); } public void testLegacyVariableResolversWithUnifiedEL() { ValueExpression ve1 = application.getExpressionFactory(). createValueExpression(getFacesContext().getELContext(), "#{customVRTest1}", Object.class); Object result = ve1.getValue(getFacesContext().getELContext()); assertTrue(result.equals("TestVariableResolver")); ValueExpression ve2 = application.getExpressionFactory(). createValueExpression(getFacesContext().getELContext(), "#{customVRTest2}", Object.class); result = ve2.getValue(getFacesContext().getELContext()); assertTrue(result.equals("TestOldVariableResolver")); } public void testConverterUpdate() { FacesContext context = getFacesContext(); Application app = context.getApplication(); Converter intConverter = application.createConverter("javax.faces.Integer"); Converter intConverter2 = application.createConverter(Integer.TYPE); Converter intConverter3 = application.createConverter(Integer.class); assertTrue(IntegerConverter.class.equals(intConverter.getClass()) && IntegerConverter.class.equals(intConverter2.getClass()) && IntegerConverter.class.equals(intConverter3.getClass())); app.addConverter("javax.faces.Integer", CustomIntConverter.class.getName()); intConverter = application.createConverter("javax.faces.Integer"); intConverter2 = application.createConverter(Integer.TYPE); intConverter3 = application.createConverter(Integer.class); assertTrue(CustomIntConverter.class.equals(intConverter.getClass()) && CustomIntConverter.class.equals(intConverter2.getClass()) && CustomIntConverter.class.equals(intConverter3.getClass())); app.addConverter(Integer.TYPE, IntegerConverter.class.getName()); intConverter = application.createConverter("javax.faces.Integer"); intConverter2 = application.createConverter(Integer.TYPE); intConverter3 = application.createConverter(Integer.class); assertTrue(IntegerConverter.class.equals(intConverter.getClass()) && IntegerConverter.class.equals(intConverter2.getClass()) && IntegerConverter.class.equals(intConverter3.getClass())); app.addConverter(Integer.class, CustomIntConverter.class.getName()); intConverter = application.createConverter("javax.faces.Integer"); intConverter2 = application.createConverter(Integer.TYPE); intConverter3 = application.createConverter(Integer.class); assertTrue(CustomIntConverter.class.equals(intConverter.getClass()) && CustomIntConverter.class.equals(intConverter2.getClass()) && CustomIntConverter.class.equals(intConverter3.getClass())); // reset to the standard converter app.addConverter("javax.faces.Integer", IntegerConverter.class.getName()); } public void testComponentAnnotatations() throws Exception { Application application = getFacesContext().getApplication(); application.addComponent("CustomInput", CustomOutput.class.getName()); CustomOutput c = (CustomOutput) application.createComponent("CustomInput"); CustomOutput c2 = (CustomOutput) application.createComponent("CustomInput"); UIViewRoot root = getFacesContext().getViewRoot(); root.getChildren().add(c); root.getChildren().add(c2); assertTrue(c.getEvent() instanceof PostAddToViewEvent); assertTrue(c2.getEvent() instanceof PostAddToViewEvent); List headComponents = root.getComponentResources(getFacesContext(), "head"); System.out.println(headComponents.toString()); assertTrue(headComponents.size() == 1); assertTrue(headComponents.get(0) instanceof UIOutput); assertTrue("test".equals(headComponents.get(0).getAttributes().get("library"))); List bodyComponents = root.getComponentResources(getFacesContext(), "body"); assertTrue(bodyComponents.size() == 1); assertTrue(bodyComponents.get(0) instanceof UIOutput); assertTrue("test.js".equals(bodyComponents.get(0).getAttributes().get("name"))); assertTrue("body".equals(bodyComponents.get(0).getAttributes().get("target"))); application.addComponent("CustomInput2", CustomOutput2.class.getName()); CustomOutput2 c3 = (CustomOutput2) application.createComponent("CustomInput2"); root.getChildren().add(c3); assertTrue(c3.getEvent() instanceof PostAddToViewEvent); c3.reset(); c3.encodeAll(getFacesContext()); assertTrue(c3.getEvent() instanceof PreRenderComponentEvent); } public void testEvaluateExpressionGet() { FacesContext ctx = getFacesContext(); ExternalContext extCtx = ctx.getExternalContext(); Application app = getFacesContext().getApplication(); extCtx.getRequestMap().put("date", new Date()); Date d = app.evaluateExpressionGet(ctx, "#{requestScope.date}", Date.class); assertNotNull(d); extCtx.getRequestMap().put("list", new ArrayList()); List l = app.evaluateExpressionGet(ctx, "#{requestScope.list}", List.class); assertNotNull(l); Object o = app.evaluateExpressionGet(ctx, "#{requestScope.list}", Object.class); assertNotNull(o); } public void testDecoratedFaceletFactory() { FacesContext ctx = getFacesContext(); WebConfiguration webConfig = WebConfiguration.getInstance(ctx.getExternalContext()); webConfig.overrideContextInitParameter(FaceletFactory, "com.sun.faces.application.TestApplicationImpl$CustomFaceletFactory"); ctx.getExternalContext().getApplicationMap().remove("com.sun.faces.ApplicationAssociate"); webConfig.overrideContextInitParameter(DisableFaceletJSFViewHandler, false); ApplicationImpl impl = new ApplicationImpl(); ApplicationAssociate associate = ApplicationAssociate.getInstance(ctx.getExternalContext()); assertEquals(CustomFaceletFactory.class.getName(), CustomFaceletFactory.class.getName(), associate.getFaceletFactory().getClass().getName()); assertEquals(DefaultFaceletFactory.class.getName(), DefaultFaceletFactory.class.getName(), ((CustomFaceletFactory) associate.getFaceletFactory()).getDelegate().getClass().getName()); } public void testOverrideFaceletFactory() { FacesContext ctx = getFacesContext(); WebConfiguration webConfig = WebConfiguration.getInstance(ctx.getExternalContext()); webConfig.overrideContextInitParameter(FaceletFactory, "com.sun.faces.application.TestApplicationImpl$CustomFaceletFactory2"); ctx.getExternalContext().getApplicationMap().remove("com.sun.faces.ApplicationAssociate"); webConfig.overrideContextInitParameter(DisableFaceletJSFViewHandler, false); ApplicationImpl impl = new ApplicationImpl(); ApplicationAssociate associate = ApplicationAssociate.getInstance(ctx.getExternalContext()); assertEquals(CustomFaceletFactory2.class.getName(), CustomFaceletFactory2.class.getName(), associate.getFaceletFactory().getClass().getName()); } // ---------------------------------------------------------- Public Methods public static void clearResourceBundlesFromAssociate(ApplicationImpl application) { ApplicationAssociate associate = (ApplicationAssociate) TestingUtil.invokePrivateMethod("getAssociate", RIConstants.EMPTY_CLASS_ARGS, RIConstants.EMPTY_METH_ARGS, ApplicationImpl.class, application); if (null != associate) { Map resourceBundles = (Map) TestingUtil.getPrivateField("resourceBundles", ApplicationAssociate.class, associate); if (null != resourceBundles) { resourceBundles.clear(); } } } // ----------------------------------------------------------- Inner Classes public static final class CustomFaceletFactory2 extends FaceletFactory { public Facelet getFacelet(String uri) throws IOException { return null; } public Facelet getFacelet(URL url) throws IOException { return null; } public Facelet getMetadataFacelet(String uri) throws IOException { return null; } public Facelet getMetadataFacelet(URL url) throws IOException { return null; } public ResourceResolver getResourceResolver() { return null; } public long getRefreshPeriod() { return 0; } } public static final class CustomFaceletFactory extends FaceletFactory { private FaceletFactory delegate; public CustomFaceletFactory(FaceletFactory delegate) { this.delegate = delegate; } public Facelet getFacelet(String uri) throws IOException { return delegate.getFacelet(uri); } public Facelet getFacelet(URL url) throws IOException { return delegate.getFacelet(url); } public Facelet getMetadataFacelet(String uri) throws IOException { return delegate.getMetadataFacelet(uri); } public Facelet getMetadataFacelet(URL url) throws IOException { return delegate.getMetadataFacelet(url); } public ResourceResolver getResourceResolver() { return delegate.getResourceResolver(); } public long getRefreshPeriod() { return delegate.getRefreshPeriod(); } public FaceletFactory getDelegate() { return delegate; } } public static class CustomIntConverter implements Converter { private IntegerConverter delegate = new IntegerConverter(); public Object getAsObject(FacesContext context, UIComponent component, String value) { return delegate.getAsObject(context, component, value); } public String getAsString(FacesContext context, UIComponent component, Object value) { return delegate.getAsString(context, component, value); } } @ListenerFor(systemEventClass=PostAddToViewEvent.class, sourceClass= CustomOutput.class) @ResourceDependencies({ @ResourceDependency(name="#{'test.js'}",library="test",target="#{'body'}"), @ResourceDependency(name="test.css",library="#{'test'}") }) public static final class CustomOutput extends UIOutput implements ComponentSystemEventListener { private boolean processEventInvoked; private ComponentSystemEvent event; public void processEvent(ComponentSystemEvent event) throws AbortProcessingException { processEventInvoked = true; this.event = event; } public void reset() { processEventInvoked = false; event = null; } public boolean isProcessEventInvoked() { return processEventInvoked; } public ComponentSystemEvent getEvent() { return event; } } @ListenersFor({ @ListenerFor(systemEventClass = PostAddToViewEvent.class, sourceClass = CustomOutput.class), @ListenerFor(systemEventClass = PreRenderComponentEvent.class, sourceClass = CustomOutput.class) }) public static final class CustomOutput2 extends UIOutput implements ComponentSystemEventListener { private boolean processEventInvoked; private ComponentSystemEvent event; public void processEvent(ComponentSystemEvent event) throws AbortProcessingException { processEventInvoked = true; this.event = event; } public void reset() { processEventInvoked = false; event = null; } public boolean isProcessEventInvoked() { return processEventInvoked; } public ComponentSystemEvent getEvent() { return event; } } } // end of class TestApplicationImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/resource/0000755000000000000000000000000011412443350021740 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/resource/TestResourceImpl.java0000644000000000000000000004575311412443350026072 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application.resource; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.ObjectOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; import java.util.Date; import java.util.Map; import java.util.ArrayList; import java.util.List; import javax.faces.application.Resource; import javax.faces.application.ResourceHandler; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.cactus.TestingUtil; import com.sun.faces.util.Util; import com.sun.faces.util.RequestStateManager; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; import javax.faces.context.FacesContext; import org.apache.cactus.WebRequest; /** * Test class for com.sun.faces.application.resource.ResourceImpl */ public class TestResourceImpl extends ServletFacesTestCase { /* 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 TimeZone GMT = TimeZone.getTimeZone("GMT"); public TestResourceImpl() { super("TestResourceImpl"); } public TestResourceImpl(String name) { super(name); } @Override public void setUp() { super.setUp(); } @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------ Test Methods public void beginToURIPrefixMapping(WebRequest req) { req.setURL("localhost:8080", "/test", "/faces", "/foo.jsp", null); } public void testToURIPrefixMapping() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue (handler != null); Resource resource = handler.createResource("duke-nv.gif"); assertTrue (resource != null); String expectedURI = "/test/faces/javax.faces.resource/duke-nv.gif"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke-nv.gif", "nvLibrary"); assertTrue(resource != null); expectedURI = "/test/faces/javax.faces.resource/duke-nv.gif?ln=nvLibrary"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke.gif"); assertTrue(resource != null); expectedURI = "/test/faces/javax.faces.resource/duke.gif?v=1_1"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke.gif", "nvLibrary"); assertTrue(resource != null); expectedURI = "/test/faces/javax.faces.resource/duke.gif?ln=nvLibrary&v=1_1"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke.gif", "vLibrary"); assertTrue(resource != null); expectedURI = "/test/faces/javax.faces.resource/duke.gif?ln=vLibrary&v=2_01_1"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke-nv.gif", "vLibrary"); assertTrue(resource != null); expectedURI = "/test/faces/javax.faces.resource/duke-nv.gif?ln=vLibrary&v=2_0"; assertTrue(expectedURI.equals(resource.getRequestPath())); } public void beginToURIExtensionMapping(WebRequest req) { req.setURL("localhost:8080", "/test", "/foo.faces", null, null); } public void testToURIExtensionMapping() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue (handler != null); Resource resource = handler.createResource("duke-nv.gif"); assertTrue (resource != null); String expectedURI = "/test/javax.faces.resource/duke-nv.gif.faces"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke-nv.gif", "nvLibrary"); assertTrue(resource != null); expectedURI = "/test/javax.faces.resource/duke-nv.gif.faces?ln=nvLibrary"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke.gif"); assertTrue(resource != null); expectedURI = "/test/javax.faces.resource/duke.gif.faces?v=1_1"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke.gif", "nvLibrary"); assertTrue(resource != null); expectedURI = "/test/javax.faces.resource/duke.gif.faces?ln=nvLibrary&v=1_1"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke.gif", "vLibrary"); assertTrue(resource != null); expectedURI = "/test/javax.faces.resource/duke.gif.faces?ln=vLibrary&v=2_01_1"; assertTrue(expectedURI.equals(resource.getRequestPath())); resource = handler.createResource("duke-nv.gif", "vLibrary"); assertTrue(resource != null); expectedURI = "/test/javax.faces.resource/duke-nv.gif.faces?ln=vLibrary&v=2_0"; assertTrue(expectedURI.equals(resource.getRequestPath())); } public void testWebppResourceGetInputStream() throws Exception { // validate the behavior of getInputStream() for a webapp-based resource ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue (handler != null); // step 1 - non-versioned byte[] controlBytes = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke-nv.gif")); Resource resource = handler.createResource("duke-nv.gif"); assertTrue(resource != null); InputStream in = resource.getInputStream(); assertTrue(in != null); byte[] underTest = getBytes(in); assertTrue(Arrays.equals(controlBytes, underTest)); // step 2 - versioned controlBytes = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke.gif/1_1.gif")); resource = handler.createResource("duke.gif"); assertTrue(resource != null); in = resource.getInputStream(); assertTrue(in != null); underTest = getBytes(in); assertTrue(Arrays.equals(controlBytes, underTest)); } public void testEqualsOnResourceAndRelatedClasses() throws Exception { // validate the behavior of getInputStream() for a webapp-based resource ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue (handler != null); Object x = handler.createResource("duke-nv.gif", "nvLibrary", "image/gif"), y = handler.createResource("duke-nv.gif", "nvLibrary", "image/gif"), z = handler.createResource("duke-nv.gif", "nvLibrary", "image/gif"); this.verifyEqualsContractPositive(x, y, z); y = handler.createResource("simple.css"); assertFalse(x.equals(y)); VersionInfo viA = new VersionInfo("1.0", null), viB = new VersionInfo("1.0", null), viC = new VersionInfo("1.0", null); this.verifyEqualsContractPositive(viA, viB, viC); ResourceHelper helper = new ClasspathResourceHelper(); FacesContext context = this.getFacesContext(); LibraryInfo liA = helper.findLibrary("vLibrary-jar", null, context), liB = helper.findLibrary("vLibrary-jar", null, context), liC = helper.findLibrary("vLibrary-jar", null, context); this.verifyEqualsContractPositive(liA, liB, liC); liB = helper.findLibrary("vLibrary", null, context); assertFalse(liA.equals(liB)); } public void testJarResourceGetInputStream() throws Exception { // validate the behavior of getInputStream() for a webapp-based resource ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue (handler != null); // step 1 - non-versioned byte[] controlBytes = getBytes(Util.getCurrentLoader(this.getClass()).getResource("META-INF/resources/duke-jar-nv.gif")); Resource resource = handler.createResource("duke-jar-nv.gif"); assertTrue(resource != null); InputStream in = resource.getInputStream(); assertTrue(in != null); byte[] underTest = getBytes(in); assertTrue(Arrays.equals(controlBytes, underTest)); // step 2 - versioned /* controlBytes = getBytes(Util.getCurrentLoader(this.getClass()).getResource("META-INF/resources/duke-jar.gif/1_1.gif")); resource = handler.createResource("duke-jar.gif"); assertTrue(resource != null); in = resource.getInputStream(); assertTrue(in != null); underTest = getBytes(in); assertTrue(Arrays.equals(controlBytes, underTest)); */ } public void testGetContentType() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue (handler != null); // non-versioned resource containing one path element Resource resource = handler.createResource("duke-jar.gif"); assertTrue(resource != null); assertTrue("image/gif".equals(resource.getContentType())); // versioned resource containing one path element resource = handler.createResource("duke.gif"); assertTrue(resource != null); assertTrue("image/gif".equals(resource.getContentType())); // non-versioned resource containing multiple path elements resource = handler.createResource("images/duke-nv.gif", "nvLibrary"); assertTrue(resource != null); assertTrue("image/gif".equals(resource.getContentType())); } public void testDefaultHeaders() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); RequestStateManager.set(getFacesContext(), RequestStateManager.RESOURCE_REQUEST, Boolean.TRUE); Resource resource = handler.createResource("duke-jar.gif"); assertTrue(resource != null); Map headers = resource.getResponseHeaders(); assertTrue(headers != null); assertTrue(headers.size() == 3); assertTrue(headers.get("Expires") != null); assertTrue(headers.get("ETag") != null); assertTrue(headers.get("Last-Modified") != null); // now assert that an empty map is returned if we're not servicing // a resource request RequestStateManager.set(getFacesContext(), RequestStateManager.RESOURCE_REQUEST, Boolean.FALSE); headers = resource.getResponseHeaders(); assertTrue(headers.isEmpty()); } @SuppressWarnings({"deprecation"}) public void testUserAgentNeedsUpdate1() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); // no If-Modified-Since request header, so this should always // return true Resource resource = handler.createResource("duke-nv.gif"); assertTrue(resource.userAgentNeedsUpdate(getFacesContext())); // set the creation date of the ResourceHandler back in time so that // if the header was present it would return true - the lack of the header // should result in true being returned in this case Date date = new Date(); date.setYear(1980); long origTime = (Long) TestingUtil.invokePrivateMethod("getCreationTime", null, null, ResourceHandlerImpl.class, handler); TestingUtil.invokePrivateMethod("setCreationTime", new Class[] { Long.TYPE }, new Object[] { date.getTime() }, ResourceHandlerImpl.class, handler); assertTrue(resource.userAgentNeedsUpdate(getFacesContext())); TestingUtil.invokePrivateMethod("setCreationTime", new Class[] { Long.TYPE }, new Object[] { origTime }, ResourceHandlerImpl.class, handler); } public void beginUserAgentNeedsUpdate2(WebRequest req) { long curTime = System.currentTimeMillis(), threeHoursAgo = curTime - 10800000L; facesService.setModificationTime("resources/duke-nv.gif", threeHoursAgo); facesService.setModificationTime("resources/nvLibrary/duke-nv.gif", threeHoursAgo); SimpleDateFormat format = new SimpleDateFormat(RFC1123_DATE_PATTERN, Locale.US); format.setTimeZone(GMT); Date headerValue = new Date(curTime); req.addHeader("If-Modified-Since", format.format(headerValue)); } public void testUserAgentNeedsUpdate2() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); // If-Modified-Since request header, so this should always // return true Resource resource = handler.createResource("duke-nv.gif"); assertTrue(!resource.userAgentNeedsUpdate(getFacesContext())); } public void testResourceImplSerialization() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); Resource resource = handler.createResource("duke-nv.gif"); byte[] serializedBytes = serialize(resource); resource = (Resource) deserialize(serializedBytes); assertNotNull(resource); assertNull(resource.getLibraryName()); assertEquals("duke-nv.gif", "duke-nv.gif", resource.getResourceName()); assertEquals("image/gif", "image/gif", resource.getContentType()); resource = handler.createResource("duke-nv.gif", "nvLibrary"); serializedBytes = serialize(resource); resource = (Resource) deserialize(serializedBytes); assertNotNull(resource); assertEquals("nvLibrary", "nvLibrary", resource.getLibraryName()); assertEquals("duke-nv.gif", "duke-nv.gif", resource.getResourceName()); assertEquals("image/gif", "image/gif", resource.getContentType()); } /** * Added for issue 1274. */ public void testResourceELEval() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertNotNull(handler); Resource resource = handler.createResource("simple-with-el.css"); assertNotNull(resource); byte[] bytes = getBytes(resource.getInputStream()); ByteArrayInputStream bai = new ByteArrayInputStream(bytes); BufferedReader reader = new BufferedReader(new InputStreamReader(bai)); List lines = new ArrayList(); for (String l = reader.readLine(); l != null; l = reader.readLine()) { String t = l.trim(); if (t.length() > 0) { lines.add(t); } } assertEquals(4, lines.size()); final String[] expectedLines = { "# /test", "# /test", "h2 { color: red }", "# /test}" }; for (int i = 0, len = expectedLines.length; i < len; i++) { assertEquals(expectedLines[i], expectedLines[i], lines.get(i)); } } // ---------------------------------------------------------- Helper Methods private byte[] serialize(Object object) throws Exception { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(bytesOut); oout.writeObject(object); oout.flush(); oout.close(); return bytesOut.toByteArray(); } private Object deserialize(byte[] bytes) throws Exception { ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes); ObjectInputStream in = new ObjectInputStream(bytesIn); return in.readObject(); } private byte[] getBytes(URL url) throws Exception { URLConnection c = url.openConnection(); c.setUseCaches(false); InputStream in = c.getInputStream(); return getBytes(in); } private byte[] getBytes(InputStream in) throws Exception { ByteArrayOutputStream o = new ByteArrayOutputStream(); for (int i = in.read(); i != -1; i = in.read()) { o.write(i); } in.close(); return o.toByteArray(); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/resource/TestResourceHandlerImpl.java0000644000000000000000000012653111412443350027362 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application.resource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; import java.util.zip.GZIPOutputStream; import javax.faces.application.Resource; import javax.faces.application.ResourceHandler; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.config.WebConfiguration; import com.sun.faces.util.Util; import com.sun.faces.application.ApplicationAssociate; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.faces.application.Application; import org.apache.cactus.WebRequest; import org.apache.cactus.WebResponse; /** * Tests com.sun.faces.application.resource.ResourceHandlerImpl */ public class TestResourceHandlerImpl extends ServletFacesTestCase { /* 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 TimeZone GMT = TimeZone.getTimeZone("GMT"); public TestResourceHandlerImpl() { super("TestResourceHandlerImpl"); } public TestResourceHandlerImpl(String name) { super(name); } @Override public void setUp() { super.setUp(); } @Override public void tearDown() { super.tearDown(); } // ------------------------------------------------------------ Test Methods public void testAjaxIsAvailable() { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); assertTrue(handler instanceof ResourceHandlerImpl); assertNotNull(handler.createResource("jsf.js", "javax.faces")); } public void testAjaxCompression() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); Resource resource = handler.createResource("jsf-uncompressed.js", "javax.faces"); InputStream stream = resource.getInputStream(); int origSize = getBytes(stream).length; resource = handler.createResource("jsf.js", "javax.faces"); stream = resource.getInputStream(); int compSize = getBytes(stream).length; // If we're not getting 30% compression, something's gone horribly wrong. assertTrue("compressed file less than 30% smaller: orig "+origSize+" comp: "+compSize, origSize * 0.7 > compSize); } public void testCreateResource() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); assertTrue(handler instanceof ResourceHandlerImpl); Resource resource = handler.createResource("duke-nv.gif"); assertTrue(resource != null); assertTrue(resource.getLibraryName() == null); assertTrue("duke-nv.gif".equals(resource.getResourceName())); assertTrue("image/gif".equals(resource.getContentType())); resource = handler.createResource("duke-nv.gif", "nvLibrary"); assertTrue(resource != null); assertTrue("nvLibrary".equals(resource.getLibraryName())); assertTrue("duke-nv.gif".equals(resource.getResourceName())); assertTrue("image/gif".equals(resource.getContentType())); resource = handler.createResource("images/duke-nv.gif", "nvLibrary"); assertTrue(resource != null); assertTrue("nvLibrary".equals(resource.getLibraryName())); assertTrue("images/duke-nv.gif".equals(resource.getResourceName())); assertTrue("image/gif".equals(resource.getContentType())); resource = handler.createResource("duke-nv.gif", "nvLibrary", "text/xml"); assertTrue(resource != null); assertTrue("nvLibrary".equals(resource.getLibraryName())); assertTrue("duke-nv.gif".equals(resource.getResourceName())); assertTrue("text/xml".equals(resource.getContentType())); resource = handler.createResource("duke-nv.gif", "nvLibrary", null); assertTrue(resource != null); assertTrue("nvLibrary".equals(resource.getLibraryName())); assertTrue("duke-nv.gif".equals(resource.getResourceName())); assertTrue("image/gif".equals(resource.getContentType())); resource = handler.createResource("foo.jpg"); assertTrue(resource == null); resource = handler.createResource("duke-nv.gif", "nonExistant"); assertTrue(resource == null); } public void beginIsResourceRequestPrefixMapped(WebRequest req) { req.setURL("localhost:8080", "/test", "/faces/", "/javax.faces.resource/duke-nv.gif", null); } public void testIsResourceRequestPrefixMapped() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); assertTrue(handler.isResourceRequest(getFacesContext())); } public void beginIsResourceRequestExtensionMapped(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); } public void testIsResourceRequestExtensionMapped() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); assertTrue(handler.isResourceRequest(getFacesContext())); } //////////////////////////////////////////////////////////////////////////// public void beginHandleResourceRequestExcludesPrefixMapped1(WebRequest req) { req.setURL("localhost:8080", "/test", "/faces/", "/javax.faces.resource/test.jsp", null); } public void testHandleResourceRequestExcludesPrefixMapped1() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequestExcludesPrefixMapped1(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// public void beginHandleResourceRequestExcludesPrefixMapped2(WebRequest req) { req.setURL("localhost:8080", "/test", "/faces/", "/javax.faces.resource/test.properties", null); } public void testHandleResourceRequestExcludesPrefixMapped2() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequestExcludesPrefixMapped2(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// public void beginHandleResourceRequestExcludesPrefixMapped3(WebRequest req) { req.setURL("localhost:8080", "/test", "/faces/", "/javax.faces.resource/test.xhtml", null); } public void testHandleResourceRequestExcludesPrefixMapped3() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequestExcludesPrefixMapped3(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// public void beginHandleResourceRequestExcludesPrefixMapped4(WebRequest req) { req.setURL("localhost:8080", "/test", "/faces/", "/javax.faces.resource/test.class", null); } public void testHandleResourceRequestExcludesPrefixMapped4() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequestExcludesPrefixMapped4(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// public void beginHandleResourceRequestExcludeExtensionMapped1(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.jsp.faces", null, null); } public void testHandleResourceRequestExcludeExtensionMapped1() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequestExcludesExtensionMapped1(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// public void beginHandleResourceRequestExcludeExtensionMapped2(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.properties.faces", null, null); } public void testHandleResourceRequestExcludeExtensionMapped2() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequestExcludesExtensionMapped2(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// public void beginHandleResourceRequestExcludeExtensionMapped3(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.xhtml.faces", null, null); } public void testHandleResourceRequestExcludeExtensionMapped3() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequestExcludesExtensionMapped3(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// public void beginHandleResourceRequestExcludeExtensionMapped4(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.class.faces", null, null); } public void testHandleResourceRequestExcludeExtensionMapped4() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequestExcludesExtensionMapped4(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// // The next 5 tests validate a user specified exclude. // In this case, .gif is excluded as a valid resource request. // This should cause the default exclusions of .jsp, .class, .xhtml, and // .properties to now be considered valid //////////////////////////////////////////////////////////////////////////// public void beginUserSpecifiedResourceExclude1(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); } public void testUserSpecifiedResourceExclude1() throws Exception { // documenting this once - this is hack in order to support dynamic init // parameters. Unfortunately, the config object (which one can obtain // the ServletContextWrapper from isn't available at the time the // 'begin' methods are invoked. So instead, leverage the knowledge that // the init parameters are checked when the ResourceHandlerImpl is constructed // and set the init parameters in the context before constructing. WebConfiguration webconfig = WebConfiguration.getInstance(getFacesContext().getExternalContext()); webconfig.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.ResourceExcludes, ".gif"); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); try { handler.handleResourceRequest(getFacesContext()); } finally { app.setResourceHandler(oldResourceHandler); } } public void endUserSpecifiedResourceExclude1(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //////////////////////////////////////////////////////////////////////////// public void beginUserSpecifiedResourceExclude2(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/com.sun.faces.application.ApplicationImpl.class.faces", null, null); } public void testUserSpecifiedResourceExclude2() throws Exception { WebConfiguration webconfig = WebConfiguration.getInstance(getFacesContext().getExternalContext()); webconfig.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.ResourceExcludes, ".gif"); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); try { assertTrue(handler.isResourceRequest(getFacesContext())); } finally { app.setResourceHandler(oldResourceHandler); } } public void endUserSpecifiedResourceExclude2(WebResponse res) { assertTrue(res.getStatusCode() == 200); } //////////////////////////////////////////////////////////////////////////// public void beginUserSpecifiedResourceExclude3(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/com.sun.faces.LogStrings.properties.faces", null, null); } public void testUserSpecifiedResourceExclude3() throws Exception { WebConfiguration webconfig = WebConfiguration.getInstance(getFacesContext().getExternalContext()); webconfig.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.ResourceExcludes, ".gif"); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); try { assertTrue(handler.isResourceRequest(getFacesContext())); } finally { app.setResourceHandler(oldResourceHandler); } } public void endUserSpecifiedResourceExclude3(WebResponse res) { assertTrue(res.getStatusCode() == 200); } //========================================================================== // Validate a resource streamed from the docroot of a webapp // public void beginHandleResourceRequest1(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); } public void testHandleResourceRequest1() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke-nv.gif")); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); } //========================================================================== // Validate a resource streamed from a JAR // public void beginHandleResourceRequest2(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); req.addParameter("ln", "nvLibrary-jar"); } public void testHandleResourceRequest2() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); HttpServletResponse response = (HttpServletResponse) getFacesContext() .getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(Util.getCurrentLoader(this) .getResource("META-INF/resources/nvLibrary-jar/duke-nv.gif")); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); } //========================================================================== // Validate a 304 is returned when a request contains the If-Modified-Since // request header and the resource hasn't changed on the server side. // public void beginHandleResourceRequest3(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); long curTime = System.currentTimeMillis(), threeHoursAgo = curTime - 10800000L; facesService.setModificationTime("resources/duke-nv.gif", threeHoursAgo); facesService.setModificationTime("resources/nvLibrary/duke-nv.gif", threeHoursAgo); SimpleDateFormat format = new SimpleDateFormat(RFC1123_DATE_PATTERN, Locale.US); format.setTimeZone(GMT); Date headerValue = new Date(curTime); req.addParameter("ln", "nvLibrary"); req.addHeader("If-Modified-Since", format.format(headerValue)); } public void testHandleResourceRequest3() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequest3(WebResponse res) { assertTrue(res.getStatusCode() == 304); } //========================================================================== // Validate a 404 is returned when a request for a non existant resource // is made // public void beginHandleResourceRequest4(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-v.gif.faces", null, null); req.addParameter("ln", "nvLibrary"); } public void testHandleResourceRequest4() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequest4(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //========================================================================== // Validate a 404 is returned when a request for an excluded resource is made // public void beginHandleResourceRequest5(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.class.faces", null, null); req.addParameter("ln", "nvLibrary"); } public void testHandleResourceRequest5() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequest5(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //========================================================================== // Validate a resource streamed from the docroot of a webapp is compressed // public void beginHandleResourceRequest6(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); req.addHeader("accept-encoding", "deflate"); req.addHeader("accept-encoding", "gzip"); } public void testHandleResourceRequest6() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif"); ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); associate.setResourceManager(new ResourceManager(associate.getResourceCache())); ResourceHandler handler = new ResourceHandlerImpl(); app.setResourceHandler(handler); HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke-nv.gif"), true); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); try { assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); assertTrue(response.containsHeader("content-encoding")); } finally { app.setResourceHandler(oldResourceHandler); } } //========================================================================== // Validate a resource streamed from a JAR is compressed // public void beginHandleResourceRequest7(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); req.addParameter("ln", "nvLibrary-jar"); req.addHeader("accept-encoding", "gzip,deflate"); } public void testHandleResourceRequest7() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif"); ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); associate.setResourceManager(new ResourceManager(associate.getResourceCache())); ResourceHandler handler = new ResourceHandlerImpl(); app.setResourceHandler(handler); HttpServletResponse response = (HttpServletResponse) getFacesContext() .getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(Util.getCurrentLoader(this) .getResource("META-INF/resources/nvLibrary-jar/duke-nv.gif"), true); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); try { assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); assertTrue(response.containsHeader("content-encoding")); } finally { app.setResourceHandler(oldResourceHandler); } } //========================================================================== // Validate a resource streamed from the docroot of a webapp isn't compressed // when the client doesn't send the accept-encoding request header // public void beginHandleResourceRequest8(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); } public void testHandleResourceRequest8() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif"); ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()); associate.setResourceManager(new ResourceManager(associate.getResourceCache())); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke-nv.gif")); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); try { assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); assertTrue(!response.containsHeader("content-encoding")); } finally { app.setResourceHandler(oldResourceHandler); } } //========================================================================== // Validate a resource streamed from a JAR isn't compressed // when the client doesn't send the accept-encoding request header // public void beginHandleResourceRequest9(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); req.addParameter("ln", "nvLibrary-jar"); } public void testHandleResourceRequest9() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif"); ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()); associate.setResourceManager(new ResourceManager(associate.getResourceCache())); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); HttpServletResponse response = (HttpServletResponse) getFacesContext() .getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(getFacesContext() .getExternalContext().getResource("/resources/nvLibrary/duke-nv.gif")); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); try { assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); assertTrue(!response.containsHeader("content-encoding")); } finally { app.setResourceHandler(oldResourceHandler); } } //========================================================================== // Validate an accept-encoding of gzip;q=0 means non-compressed content // is sent to the user-agent // public void beginHandleResourceRequest10(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); req.addHeader("accept-encoding", "gzip;q=0, deflate"); } public void testHandleResourceRequest10() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif"); ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()); associate.setResourceManager(new ResourceManager(associate.getResourceCache())); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke-nv.gif"), false); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); try { assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); assertTrue(!response.containsHeader("content-encoding")); } finally { app.setResourceHandler(oldResourceHandler); } } //========================================================================== // Validate an accept-encoding of that doesn't include gzip, and includes // *;q=0 will not send compressed content to the user-agent // is sent to the user-agent // public void beginHandleResourceRequest11(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); req.addHeader("accept-encoding", "deflate"); req.addHeader("accept-encoding", "*;q=0"); } public void testHandleResourceRequest11() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif"); ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()); associate.setResourceManager(new ResourceManager(associate.getResourceCache())); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke-nv.gif"), false); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); try { assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); assertTrue(!response.containsHeader("content-encoding")); } finally { app.setResourceHandler(oldResourceHandler); } } //========================================================================== // Validate an accept-encoding of that doesn't include gzip, and includes // * will send compressed content // public void beginHandleResourceRequest12(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); req.addHeader("accept-encoding", "identity;q=1.0"); req.addHeader("accept-encoding", "*;q=0.5"); req.addHeader("accept-encoding", "deflate;q=1.0"); } public void testHandleResourceRequest12() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif"); ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()); associate.setResourceManager(new ResourceManager(associate.getResourceCache())); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke-nv.gif"), true); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); try { assertTrue(Arrays.equals(control, test)); assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); assertTrue(response.containsHeader("content-encoding")); } finally { app.setResourceHandler(oldResourceHandler); } } //========================================================================== // Validate an accept-encoding of that doesn't include gzip will not send // compressed content. // public void beginHandleResourceRequest13(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/duke-nv.gif.faces", null, null); req.addHeader("accept-encoding", "identity;q=0.5, deflate;q=1.0"); } public void testHandleResourceRequest13() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif"); ApplicationAssociate associate = ApplicationAssociate.getInstance(getFacesContext().getExternalContext()); associate.setResourceManager(new ResourceManager(associate.getResourceCache())); ResourceHandler handler = new ResourceHandlerImpl(); Application app = getFacesContext().getApplication(); ResourceHandler oldResourceHandler = app.getResourceHandler(); app.setResourceHandler(handler); HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse(); TestResponseWrapper wrapper = new TestResponseWrapper(response); getFacesContext().getExternalContext().setResponse(wrapper); byte[] control = getBytes(getFacesContext().getExternalContext().getResource("/resources/duke-nv.gif"), false); handler.handleResourceRequest(getFacesContext()); byte[] test = wrapper.getBytes(); assertTrue(Arrays.equals(control, test)); try { assertTrue(response.containsHeader("content-length")); assertTrue(response.containsHeader("last-modified")); assertTrue(response.containsHeader("expires")); assertTrue(response.containsHeader("etag")); assertTrue(response.containsHeader("content-type")); assertTrue(!response.containsHeader("content-encoding")); } finally { app.setResourceHandler(oldResourceHandler); } } //========================================================================== // Validate the fix for issue 1162. // public void beginHandleResourceRequest14(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/web.xml.faces", null, "ln=../WEB-INF"); } public void testHandleResourceRequest14() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequest14(WebResponse res) { assertTrue(res.getStatusCode() == 404); } //========================================================================== // Validate the fix for issue 1162. // public void beginHandleResourceRequest15(WebRequest req) { req.setURL("localhost:8080", "/test", "/javax.faces.resource/web.xml.faces", null, "ln=nvLibrary/../../WEB-INF"); } public void testHandleResourceRequest15() throws Exception { ResourceHandler handler = getFacesContext().getApplication().getResourceHandler(); assertTrue(handler != null); handler.handleResourceRequest(getFacesContext()); } public void endHandleResourceRequest15(WebResponse res) { assertTrue(res.getStatusCode() == 404); } // ---------------------------------------------------------- Helper Methods private byte[] getBytes(URL url) throws Exception { return getBytes(url, false); } private byte[] getBytes(URL url, boolean compress) throws Exception { URLConnection c = url.openConnection(); c.setUseCaches(false); InputStream in = c.getInputStream(); return ((compress) ? getCompressedBytes(in) : getBytes(in)); } private byte[] getBytes(InputStream in) throws Exception { ByteArrayOutputStream o = new ByteArrayOutputStream(); for (int i = in.read(); i != -1; i = in.read()) { o.write(i); } in.close(); return o.toByteArray(); } private byte[] getCompressedBytes(InputStream in) throws Exception { ByteArrayOutputStream o = new ByteArrayOutputStream(); GZIPOutputStream compress = new GZIPOutputStream(o); for (int i = in.read(); i != -1; i = in.read()) { compress.write(i); } compress.flush(); compress.close(); return o.toByteArray(); } // ----------------------------------------------------------- Inner Classes private static class TestResponseWrapper extends HttpServletResponseWrapper { private TestServletOutputStream out; public byte[] getBytes() { return out.getBytes(); } public TestResponseWrapper(HttpServletResponse httpServletResponse) { super(httpServletResponse); } public ServletOutputStream getOutputStream() throws IOException { out = new TestServletOutputStream(super.getOutputStream()); return out; } private class TestServletOutputStream extends ServletOutputStream { private ServletOutputStream wrapped; private ByteArrayOutputStream out = new ByteArrayOutputStream(); public TestServletOutputStream(ServletOutputStream wrapped) { this.wrapped = wrapped; } public void write(int b) throws IOException { wrapped.write(b); out.write(b); } public void write(byte b[]) throws IOException { wrapped.write(b); out.write(b); } public void write(byte b[], int off, int len) throws IOException { wrapped.write(b, off, len); out.write(b, off, len); } public void flush() throws IOException { wrapped.flush(); out.flush(); } public void close() throws IOException { wrapped.close(); out.close(); } public byte[] getBytes() { return out.toByteArray(); } } } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/resource/TestResourceManager.java0000644000000000000000000004752711412443350026544 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application.resource; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.faces.context.ExternalContext; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.config.WebConfiguration; /** * Validate the ResourceManager. * * @since 2.0 */ public class TestResourceManager extends ServletFacesTestCase { ResourceManager manager; public TestResourceManager() { super("TestResourceManager"); } public TestResourceManager(String name) { super(name); } @Override public void setUp() { super.setUp(); manager = new ResourceManager(null); } @Override public void tearDown() { super.tearDown(); manager = null; } // ------------------------------------------------------------ Test Methods public void testWebappNonVersionedResource() throws Exception { ResourceInfo resource = manager.findResource(null, "duke-nv.gif", "image/gif", getFacesContext()); assertTrue(resource != null); assertTrue(resource.getLibraryInfo() == null); assertTrue(resource.getHelper() instanceof WebappResourceHelper); assertTrue(resource.getVersion() == null); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("duke-nv.gif".equals(resource.getName())); assertTrue("/resources/duke-nv.gif".equals(resource.getPath())); } public void testWebappVersionedResource() throws Exception { ResourceInfo resource = manager.findResource(null, "duke.gif", "image/gif", getFacesContext()); assertTrue(resource != null); assertTrue(resource.getLibraryInfo() == null); assertTrue(resource.getHelper() instanceof WebappResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("1_1".equals(resource.getVersion().toString())); assertTrue("duke.gif".equals(resource.getName())); assertTrue("/resources/duke.gif/1_1.gif".equals(resource.getPath())); } public void testWebappNonVersionedLibraryVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("nvLibrary", "duke.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("nvLibrary".equals(resource.getLibraryInfo().getName())); assertTrue(resource.getLibraryInfo().getVersion() == null); assertTrue(resource.getLibraryInfo().getHelper() instanceof WebappResourceHelper); assertTrue("/resources/nvLibrary".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof WebappResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("1_1".equals(resource.getVersion().toString())); assertTrue("duke.gif".equals(resource.getName())); assertTrue("/resources/nvLibrary/duke.gif/1_1.gif".equals(resource.getPath())); } public void testWebappNonVersionedLibraryNonVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("nvLibrary", "duke-nv.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("nvLibrary".equals(resource.getLibraryInfo().getName())); assertTrue(resource.getLibraryInfo().getVersion() == null); assertTrue(resource.getLibraryInfo().getHelper() instanceof WebappResourceHelper); assertTrue("/resources/nvLibrary".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof WebappResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue(resource.getVersion() == null); assertTrue("duke-nv.gif".equals(resource.getName())); assertTrue("/resources/nvLibrary/duke-nv.gif".equals(resource.getPath())); } public void testWebappVersionedLibraryNonVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("vLibrary", "duke-nv.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("vLibrary".equals(resource.getLibraryInfo().getName())); assertTrue("2_0".equals(resource.getLibraryInfo().getVersion().toString())); assertTrue(resource.getLibraryInfo().getHelper() instanceof WebappResourceHelper); assertTrue("/resources/vLibrary/2_0".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof WebappResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue(resource.getVersion() == null); assertTrue("duke-nv.gif".equals(resource.getName())); assertTrue("/resources/vLibrary/2_0/duke-nv.gif".equals(resource.getPath())); } public void testWebappVersionedLibraryVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("vLibrary", "duke.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("vLibrary".equals(resource.getLibraryInfo().getName())); assertTrue("2_0".equals(resource.getLibraryInfo().getVersion().toString())); assertTrue(resource.getLibraryInfo().getHelper() instanceof WebappResourceHelper); assertTrue("/resources/vLibrary/2_0".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof WebappResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("1_1".equals(resource.getVersion().toString())); assertTrue("duke.gif".equals(resource.getName())); assertTrue("/resources/vLibrary/2_0/duke.gif/1_1.gif".equals(resource.getPath())); } public void testWebappPathResource() throws Exception { ResourceInfo resource = manager.findResource("nvLibrary", "images/duke-nv.gif", "image/gif", getFacesContext()); assertTrue(resource != null); assertTrue("images/duke-nv.gif".equals(resource.getName())); assertTrue(resource.getHelper() instanceof WebappResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("/resources/nvLibrary/images/duke-nv.gif".equals(resource.getPath())); } public void testJarNonVersionedResources() throws Exception { ResourceInfo resource = manager.findResource(null, "duke-jar-nv.gif", "image/gif", getFacesContext()); assertTrue(resource != null); assertTrue(resource.getLibraryInfo() == null); assertTrue(resource.getHelper() instanceof ClasspathResourceHelper); assertTrue(resource.getVersion() == null); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("duke-jar-nv.gif".equals(resource.getName())); assertTrue("META-INF/resources/duke-jar-nv.gif".equals(resource.getPath())); } /* public void testJarVersionedResource() throws Exception { ResourceInfo resource = manager.findResource(null, "duke-jar.gif", "image/gif", getFacesContext()); assertTrue(resource != null); assertTrue(resource.getLibraryInfo() == null); assertTrue(resource.getHelper() instanceof ClasspathResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("1_1".equals(resource.getVersion().toString())); assertTrue("duke-jar.gif".equals(resource.getName())); assertTrue("META-INF/resources/duke-jar.gif/1_1.gif".equals(resource.getPath())); } */ /* public void testJarNonVersionedLibraryVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("nvLibrary-jar", "duke.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("nvLibrary-jar".equals(resource.getLibraryInfo().getName())); assertTrue(resource.getLibraryInfo().getVersion() == null); assertTrue(resource.getLibraryInfo().getHelper() instanceof ClasspathResourceHelper); assertTrue("META-INF/resources/nvLibrary-jar".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof ClasspathResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("1_1".equals(resource.getVersion().toString())); assertTrue("duke.gif".equals(resource.getName())); assertTrue("META-INF/resources/nvLibrary-jar/duke.gif/1_1.gif".equals(resource.getPath())); } */ public void testJarNonVersionedLibraryNonVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("nvLibrary-jar", "duke-nv.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("nvLibrary-jar".equals(resource.getLibraryInfo().getName())); assertTrue(resource.getLibraryInfo().getVersion() == null); assertTrue(resource.getLibraryInfo().getHelper() instanceof ClasspathResourceHelper); assertTrue("META-INF/resources/nvLibrary-jar".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof ClasspathResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue(resource.getVersion() == null); assertTrue("duke-nv.gif".equals(resource.getName())); assertTrue("META-INF/resources/nvLibrary-jar/duke-nv.gif".equals(resource.getPath())); } /* public void testJarVersionedLibraryNonVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("vLibrary-jar", "duke-nv.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("vLibrary-jar".equals(resource.getLibraryInfo().getName())); assertTrue("2_0".equals(resource.getLibraryInfo().getVersion().toString())); assertTrue(resource.getLibraryInfo().getHelper() instanceof ClasspathResourceHelper); assertTrue("META-INF/resources/vLibrary-jar/2_0".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof ClasspathResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue(resource.getVersion() == null); assertTrue("duke-nv.gif".equals(resource.getName())); assertTrue("META-INF/resources/vLibrary-jar/2_0/duke-nv.gif".equals(resource.getPath())); } */ /* public void testJarVersionedLibraryVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("vLibrary-jar", "duke.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("vLibrary-jar".equals(resource.getLibraryInfo().getName())); assertTrue("2_0".equals(resource.getLibraryInfo().getVersion().toString())); assertTrue(resource.getLibraryInfo().getHelper() instanceof ClasspathResourceHelper); assertTrue("META-INF/resources/vLibrary-jar/2_0".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof ClasspathResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("1_1".equals(resource.getVersion().toString())); assertTrue("duke.gif".equals(resource.getName())); assertTrue("META-INF/resources/vLibrary-jar/2_0/duke.gif/1_1.gif".equals(resource.getPath())); } */ public void testNoExtensionVersionedResource() throws Exception { ResourceInfo resource = manager.findResource("vLibrary", "duke2.gif", "image/gif", getFacesContext()); assertTrue(resource != null); // validate the library assertTrue(resource.getLibraryInfo() != null); assertTrue("vLibrary".equals(resource.getLibraryInfo().getName())); assertTrue("2_0".equals(resource.getLibraryInfo().getVersion().toString())); assertTrue(resource.getLibraryInfo().getHelper() instanceof WebappResourceHelper); assertTrue("/resources/vLibrary/2_0".equals(resource.getLibraryInfo().getPath())); // validate the resource assertTrue(resource.getHelper() instanceof WebappResourceHelper); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); assertTrue("1_1".equals(resource.getVersion().toString())); assertTrue(resource.getVersion().getExtension() == null); assertTrue("duke2.gif".equals(resource.getName())); assertTrue("/resources/vLibrary/2_0/duke2.gif/1_1".equals(resource.getPath())); } public void testInvalidLibraryName() throws Exception { assertTrue(manager.findResource("noSuchLibrary", "duke.gif", "image/gif", getFacesContext()) == null); } public void testInvalidResourceName() throws Exception { assertTrue(manager.findResource(null, "duke.fig", null, getFacesContext()) == null); assertTrue(manager.findResource("nvLibrary", "duke.fig", null, getFacesContext()) == null); } public void testResourceInfoCompression() throws Exception { WebConfiguration config = WebConfiguration.getInstance(); config.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.CompressableMimeTypes, "image/gif,text/css,text/plain"); // create a new ResourceManager so that the mime type configuration is picked up ResourceManager manager = new ResourceManager(null); ResourceInfo resource = manager.findResource("nvLibrary", "images/duke-nv.gif", "image/gif", getFacesContext()); assertTrue(resource != null); assertTrue(resource.isCompressable()); assertTrue(compressionPathIsValid(resource)); // ensure compression disabled for a content type that is null resource = manager.findResource("nvLibrary", "images/duke-nv.gif", "text/javascript", getFacesContext()); assertTrue(resource != null); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); // if a resource is compressable, but the compressed result is larger // than the original resource, the returned ResourceInfo shouldn't // be marked as compressable and getCompressedPath() will be null resource = manager.findResource(null, "simple.txt", "text/plain", getFacesContext()); assertTrue(resource != null); assertTrue(!resource.isCompressable()); assertTrue(resource.getCompressedPath() == null); // if a resource is compressable, but the compressed result is larger // than the original resource, the returned ResourceInfo should be // marked compressable. However, since css files may have EL expressions // embedded within, the the resource will be marked as supporting such. resource = manager.findResource(null, "simple.css", "text/plain", getFacesContext()); assertTrue(resource != null); assertTrue(resource.isCompressable()); assertTrue(resource.supportsEL()); assertTrue(resource.getCompressedPath() == null); } public void testELEvalDisabledIfNoExpressionEvaluated() throws Exception { ResourceManager manager = new ResourceManager(null); ResourceInfo resource = manager.findResource(null, "simple.css", "text/css", getFacesContext()); assertNotNull(resource); assertTrue(resource.supportsEL()); ResourceImpl resImpl = new ResourceImpl(resource, "text/css", 0, 0); InputStream in = resImpl.getInputStream(); for (int i = in.read(); i != -1; i = in.read()) { } try { in.close(); } catch (Exception ioe) { fail(ioe.toString()); } assertTrue(!resource.supportsEL()); resource = manager.findResource(null, "simple-with-el.css", "text/css", getFacesContext()); assertNotNull(resource); assertTrue(resource.supportsEL()); resImpl = new ResourceImpl(resource, "text/css", 0, 0); in = resImpl.getInputStream(); for (int i = in.read(); i != -1; i = in.read()) { } try { in.close(); } catch (Exception ioe) { fail(ioe.toString()); } assertTrue(resource.supportsEL()); } // --------------------------------------------------------- Private Methods private boolean compressionPathIsValid(ResourceInfo resource) throws IOException { ExternalContext extContext = getFacesContext().getExternalContext(); File tempDir = (File) extContext.getApplicationMap().get("javax.servlet.context.tempdir"); File expected = new File(tempDir, "/jsf-compressed" + File.separatorChar + resource.getPath()); return expected.getCanonicalPath().equals(resource.getCompressedPath()); } } // END TestResourceManager mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestStateManagerImpl.java0000644000000000000000000002726111412443350025021 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import java.io.StringWriter; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.Matcher; import javax.faces.component.UIComponent; import javax.faces.component.UIGraphic; import javax.faces.component.UIInput; import javax.faces.component.UIOutput; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.application.StateManager; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.cactus.TestingUtil; import com.sun.faces.renderkit.ServerSideStateHelper; import com.sun.faces.renderkit.RenderKitImpl; import com.sun.faces.renderkit.html_basic.HtmlResponseWriter; import com.sun.faces.util.Util; import com.sun.faces.config.WebConfiguration; import static com.sun.faces.config.WebConfiguration.WebContextInitParameter.StateSavingMethod; import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.AutoCompleteOffOnViewState; import com.sun.faces.context.FacesContextImpl; import org.apache.cactus.WebRequest; /** * This class tests the StateManagerImpl class * functionality. */ public class TestStateManagerImpl extends ServletFacesTestCase { // // Constructors/Initializers // public TestStateManagerImpl() { super("TestStateManagerImpl"); } public TestStateManagerImpl(String name) { super(name); } // ------------------------------------------------------------ Test Methods // Verify saveSerializedView() throws IllegalStateException // if duplicate component id's are detected on non-transient // components. public void testDuplicateIdDetection() throws Exception { FacesContext context = getFacesContext(); // construct a view UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(context, null); root.setViewId("/test"); root.setId("root"); root.setLocale(Locale.US); UIComponent comp1 = new UIInput(); comp1.setId("comp1"); UIComponent comp2 = new UIOutput(); comp2.setId("comp2"); UIComponent comp3 = new UIGraphic(); comp3.setId("comp3"); UIComponent facet1 = new UIOutput(); facet1.setId("comp4"); UIComponent facet2 = new UIOutput(); facet2.setId("comp2"); comp2.getFacets().put("facet1", facet1); comp2.getFacets().put("facet2", facet2); root.getChildren().add(comp1); root.getChildren().add(comp2); root.getChildren().add(comp3); context.setViewRoot(root); StateManagerImpl stateManager = (StateManagerImpl) context.getApplication() .getStateManager(); boolean exceptionThrown = false; try { stateManager.saveView(context); } catch (IllegalStateException ise) { exceptionThrown = true; } assertTrue(exceptionThrown); // multiple componentns with a null ID should not // trigger an exception // construct a view root = Util.getViewHandler(getFacesContext()).createView(context, null); root.setViewId("/test"); root.setId("root"); root.setLocale(Locale.US); comp1 = new UIInput(); comp1.setId("comp1"); comp2 = new UIOutput(); comp2.setId(null); comp3 = new UIGraphic(); comp3.setId(null); facet1 = new UIOutput(); facet1.setId("comp4"); facet2 = new UIOutput(); facet2.setId("comp2"); comp2.getFacets().put("facet1", facet1); comp2.getFacets().put("facet2", facet2); root.getChildren().add(comp1); root.getChildren().add(comp2); root.getChildren().add(comp3); context.setViewRoot(root); exceptionThrown = false; try { stateManager.saveView(context); } catch (IllegalStateException ise) { exceptionThrown = true; } assertTrue(!exceptionThrown); // transient components with duplicate ids should // trigger an error condition // construct a view root = Util.getViewHandler(getFacesContext()).createView(context, null); root.setViewId("/test"); root.setId("root"); root.setLocale(Locale.US); comp1 = new UIInput(); comp1.setId("comp1"); comp1.setTransient(true); comp2 = new UIOutput(); comp2.setId("comp1"); comp2.setTransient(true); comp3 = new UIGraphic(); comp3.setId("comp3"); facet1 = new UIOutput(); facet1.setId("comp4"); facet2 = new UIOutput(); facet2.setId("comp2"); comp2.getFacets().put("facet1", facet1); comp2.getFacets().put("facet2", facet2); root.getChildren().add(comp1); root.getChildren().add(comp2); root.getChildren().add(comp3); context.setViewRoot(root); exceptionThrown = false; try { stateManager.saveView(context); } catch (IllegalStateException ise) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void beginMultiWindowSaveServer(WebRequest theRequest) { theRequest.addParameter("javax.faces.ViewState", "j_id1:j_id2"); } public void testMultiWindowSaveServer() throws Exception { StateManagerImpl wrapper = new StateManagerImpl() { public boolean isSavingStateInClient(FacesContext context) { return false; } }; FacesContext ctx = getFacesContext(); ctx.getApplication().setStateManager(wrapper); // construct a view initView(ctx); UIViewRoot root = ctx.getViewRoot(); root.getAttributes().put("checkThisValue", "checkThisValue"); getFacesContext().setResponseWriter(new HtmlResponseWriter(new StringWriter(), "text/html", "UTF-8")); Object viewState = wrapper.saveView(getFacesContext()); wrapper.writeState(getFacesContext(), viewState); // See that the Logical View and Actual View maps are correctly created Map sessionMap = ctx.getExternalContext().getSessionMap(); assertTrue(sessionMap.containsKey(ServerSideStateHelper.LOGICAL_VIEW_MAP)); assertTrue(((Map)sessionMap.get(ServerSideStateHelper.LOGICAL_VIEW_MAP)).containsKey("j_id1")); UIViewRoot newRoot = wrapper.restoreView(ctx, "test", "HTML_BASIC"); assertNotNull(newRoot); assertEquals(root.getAttributes().get("checkThisValue"), newRoot.getAttributes().get("checkThisValue")); } public void testGetViewStateServer() { // this exercise ResponseStateManager.getViewState() as well FacesContext ctx = getFacesContext(); initView(ctx); String control = "j_id1:j_id2"; String result = ctx.getApplication().getStateManager().getViewState(ctx); assertEquals(control, result); } public void testGetViewStateClient() throws Exception { // this exercise ResponseStateManager.getViewState() as well FacesContext ctx = getFacesContext(); WebConfiguration webConfig = WebConfiguration.getInstance(ctx.getExternalContext()); webConfig.overrideContextInitParameter(StateSavingMethod, StateManager.STATE_SAVING_METHOD_CLIENT); webConfig.overrideContextInitParameter(AutoCompleteOffOnViewState, false); // recreate the RenderKit so the change is picked up. RenderKit rk = new RenderKitImpl(); TestingUtil.setPrivateField("lastRk", FacesContextImpl.class, ctx, rk); TestingUtil.setPrivateField("lastRkId", FacesContextImpl.class, ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT); initView(ctx); StringWriter capture = new StringWriter(); ResponseWriter writer = new HtmlResponseWriter(capture, "text/html", "UTF-8"); ctx.setResponseWriter(writer); StateManager manager = ctx.getApplication().getStateManager(); Object state = ctx.getApplication().getStateManager().saveView(ctx); manager.writeState(ctx, state); String rawResult = capture.toString(); Pattern p = Pattern.compile("\\bvalue=\"(.+)\""); Matcher m = p.matcher(rawResult); assertTrue(m.find()); String control = m.group(1); String result = ctx.getApplication().getStateManager().getViewState(ctx); assertEquals(control, result); } // --------------------------------------------------------- Private Methods private void initView(FacesContext ctx) { UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(ctx, null); root.setViewId("/test"); root.setId("root"); root.setLocale(Locale.US); UIComponent comp1 = new UIInput(); comp1.setId("comp1"); UIComponent comp2 = new UIOutput(); comp2.setId("comp2"); UIComponent comp3 = new UIGraphic(); comp3.setId("comp3"); UIComponent facet1 = new UIOutput(); facet1.setId("comp4"); comp2.getFacets().put("facet1", facet1); root.getChildren().add(comp1); root.getChildren().add(comp2); root.getChildren().add(comp3); ctx.setViewRoot(root); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestApplicationEvents.java0000644000000000000000000005275011412443350025255 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2009 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import java.util.List; import javax.faces.application.Application; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.component.UIOutput; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.ComponentSystemEvent; import javax.faces.event.ComponentSystemEventListener; import javax.faces.event.FacesListener; import javax.faces.event.SystemEvent; import javax.faces.event.SystemEventListener; import javax.faces.event.SystemEventListenerHolder; import javax.faces.event.PostConstructApplicationEvent; import com.sun.faces.CustomSystemEvent; import com.sun.faces.cactus.ServletFacesTestCase; /** * @since 2.0.0 */ public class TestApplicationEvents extends ServletFacesTestCase { // ------------------------------------------------------------ Constructors public TestApplicationEvents() { super("TestApplicationEvents"); } public TestApplicationEvents(String name) { super(name); } // ------------------------------------------------------------ Test Methods //////////////////////////////////////////////////////////////////////////// // ensure NPEs are thrown per the docs public void testEventsNPEs() { Application application = getFacesContext().getApplication(); SystemEventListener listener = new TestListener(); // ----------------------------------------------------------- Subscribe try { application.subscribeToEvent(null, UIViewRoot.class, listener); assertTrue(false); } catch (NullPointerException npe) { } catch (Exception e) { assertTrue(false); } try { application.subscribeToEvent(TestApplicationEvents.TestSystemEvent.class, UIViewRoot.class, null); assert(false); } catch (NullPointerException ignored) { } catch (Exception e) { assertTrue(false); } // --------------------------------------------------------- Unsubscribe try { application.subscribeToEvent(null, UIViewRoot.class, listener); assertTrue(false); } catch (NullPointerException ignored) { } catch (Exception e) { assertTrue(false); } try { application.subscribeToEvent(TestApplicationEvents.TestSystemEvent.class, UIViewRoot.class, null); assertTrue(false); } catch (NullPointerException ignored) { } catch (Exception e) { assertTrue(false); } // ------------------------------------------------------------- Publish try { application.publishEvent(getFacesContext(), null, new UIViewRoot()); assertTrue(false); } catch (NullPointerException ignored) { } catch (Exception e) { assertTrue(false); } try { application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent.class, null); assertTrue(false); } catch (NullPointerException ignored) { } catch (Exception e) { assertTrue(false); } try { application.publishEvent(null, TestApplicationEvents.TestSystemEvent.class, new UIViewRoot()); assertTrue(false); } catch (NullPointerException ignored) { } catch (Exception e) { assertTrue(false); } } //////////////////////////////////////////////////////////////////////////// // Ensure component level listeners are invoked when // Application.publishEvent() is called. public void testEvents1() { TestComponentListener listener = new TestComponentListener(); Application application = getFacesContext().getApplication(); UIInput input = new UIInput(); input.subscribeToEvent(TestApplicationEvents.TestSystemEvent3.class, listener); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent3.class, input); assertTrue(listener.getPassedEvent() instanceof TestApplicationEvents.TestSystemEvent3); // new UIInput without any subs should result in no invocation listener.reset(); UIInput input2 = new UIInput(); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent3.class, input2); assertTrue(!listener.wasProcessEventInvoked()); // unsub'd event should result in no invocations input.unsubscribeFromEvent(TestApplicationEvents.TestSystemEvent3.class, listener); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent3.class, input); assertTrue(!listener.wasProcessEventInvoked()); } //////////////////////////////////////////////////////////////////////////// // Test Application subscribeToEvent() and unsubscribeToEvent() with // a specific source. public void testEvents2() { TestListener listener = new TestListener(UIViewRoot.class); Application application = getFacesContext().getApplication(); application.subscribeToEvent(TestApplicationEvents.TestSystemEvent.class, UIViewRoot.class, listener); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent.class, getFacesContext().getViewRoot()); assertTrue(listener.getPassedSource() == getFacesContext().getViewRoot()); assertTrue(listener.getPassedSystemEvent() instanceof TestSystemEvent); assertTrue(listener.getPassedSystemEvent().getSource() == getFacesContext().getViewRoot()); // event is setup for UIViewRoot sources, so a UIInput source shouldn't // trigger the listener UIInput input = new UIInput(); listener.reset(); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent.class, input); assertTrue(listener.getPassedSource() == null); assertTrue(listener.getPassedSystemEvent() == null); // passing a custom UIViewRoot should result in the listener being // triggered and the event being created listener.reset(); CustomViewRoot root = new CustomViewRoot(); application.subscribeToEvent(TestApplicationEvents.TestSystemEvent.class, CustomViewRoot.class, listener); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent.class, root); assertTrue(listener.getPassedSource() == root); assertTrue(listener.getPassedSystemEvent() instanceof TestSystemEvent); assertTrue(listener.getPassedSystemEvent().getSource() == root); // unsubscript and verify a publish doesn't trigger the listener application.unsubscribeFromEvent(TestApplicationEvents.TestSystemEvent.class, CustomViewRoot.class, listener); listener.reset(); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent.class, root); assertTrue(!listener.wasIsListenerForSourceInvoked()); assertTrue(!listener.wasProcessEventInvoked()); application.unsubscribeFromEvent(TestApplicationEvents.TestSystemEvent.class, UIViewRoot.class, listener); listener.reset(); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent.class, root); assertTrue(!listener.wasIsListenerForSourceInvoked()); assertTrue(!listener.wasProcessEventInvoked()); // verify multiple events for a single source works listener = new TestListener(UIViewRoot.class); application.subscribeToEvent(TestApplicationEvents.TestSystemEvent2.class, UIViewRoot.class, listener); application.subscribeToEvent(TestApplicationEvents.TestSystemEvent3.class, UIViewRoot.class, listener); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent2.class, getFacesContext().getViewRoot()); assertTrue(listener.getPassedSource() == getFacesContext().getViewRoot()); assertTrue(listener.getPassedSystemEvent() instanceof TestSystemEvent2); assertTrue(listener.getPassedSystemEvent().getSource() == getFacesContext().getViewRoot()); listener.reset(); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent3.class, getFacesContext().getViewRoot()); assertTrue(listener.getPassedSource() == getFacesContext().getViewRoot()); assertTrue(listener.getPassedSystemEvent() instanceof TestSystemEvent3); assertTrue(listener.getPassedSystemEvent().getSource() == getFacesContext().getViewRoot()); application.unsubscribeFromEvent(TestApplicationEvents.TestSystemEvent2.class, UIViewRoot.class, listener); application.unsubscribeFromEvent(TestApplicationEvents.TestSystemEvent3.class, UIViewRoot.class, listener); // verify subscription for source that is an Abstract type works or // doesn't work depending on how the event is published. TestListener abstractListener = new TestListener(Application.class); application.subscribeToEvent(PostConstructApplicationEvent.class, Application.class, abstractListener); abstractListener.reset(); application.publishEvent(getFacesContext(), PostConstructApplicationEvent.class, Application.class, application); assertTrue(abstractListener.getPassedSource() == application); assertTrue(abstractListener.getPassedSystemEvent() instanceof PostConstructApplicationEvent); assertTrue(abstractListener.getPassedSystemEvent().getSource() == application); // verify that the event isn't published when the base type isn't // provided with publish abstractListener.reset(); application.publishEvent(getFacesContext(), PostConstructApplicationEvent.class, application); assertTrue(abstractListener.getPassedSource() == null); assertTrue(abstractListener.getPassedSystemEvent() == null); // cleanup application.unsubscribeFromEvent(PostConstructApplicationEvent.class, Application.class, abstractListener); } //////////////////////////////////////////////////////////////////////////// // Test Application subscribeToEvent() and unsubscribeToEvent() without // a specific source. public void testEvents3() { TestListener listener = new TestListener(UIComponent.class); Application application = getFacesContext().getApplication(); application.subscribeToEvent(TestApplicationEvents.TestSystemEvent2.class, listener); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent2.class, getFacesContext().getViewRoot()); assertTrue(listener.getPassedSource() == getFacesContext().getViewRoot()); assertTrue(listener.getPassedSystemEvent() instanceof TestSystemEvent2); assertTrue(listener.getPassedSystemEvent().getSource() == getFacesContext().getViewRoot()); // any UIComponent source should work listener.reset(); UIInput input = new UIInput(); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent2.class, input); assertTrue(listener.getPassedSource() == input); assertTrue(listener.getPassedSystemEvent() instanceof TestSystemEvent2); assertTrue(listener.getPassedSystemEvent().getSource() == input); // non UIComponent SystemEventListenerHolder shouldn't result in the // listener being used listener.reset(); TestSystemEventListenerHolder holder = new TestSystemEventListenerHolder(); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent2.class, holder); assertTrue(listener.getPassedSource() == holder); assertTrue(!listener.wasProcessEventInvoked()); assertTrue(listener.getPassedSystemEvent() == null); // unsubscribe listener.reset(); application.unsubscribeFromEvent(TestApplicationEvents.TestSystemEvent2.class, listener); application.publishEvent(getFacesContext(), TestApplicationEvents.TestSystemEvent2.class, input); assertTrue(!listener.wasIsListenerForSourceInvoked()); assertTrue(!listener.wasProcessEventInvoked()); } public void testListenersFromConfig() { FacesContext ctx = getFacesContext(); Application app = ctx.getApplication(); // SystemEventListener1 is only interested in UIOutput sources, while // SystemEventListener2 is interested in any events. app.publishEvent(getFacesContext(), CustomSystemEvent.class, new UIInput()); assertNull(ctx.getAttributes().remove("SystemEventListener1")); assertNotNull(ctx.getAttributes().remove("SystemEventListener2")); app.publishEvent(getFacesContext(), CustomSystemEvent.class, new UIOutput()); assertNotNull(ctx.getAttributes().remove("SystemEventListener1")); assertNotNull(ctx.getAttributes().remove("SystemEventListener2")); } // ----------------------------------------------------------- Inner Classes private static final class TestComponentListener implements ComponentSystemEventListener { private SystemEvent passedEvent; boolean processEventInvoked; // -------------------------------------------------------- Constructors public TestComponentListener() { } // --------------------------- Methods from ComponentSystemEventListener public void processEvent(ComponentSystemEvent event) throws AbortProcessingException { passedEvent = event; processEventInvoked = true; } // ------------------------------------------------------ Public Methods public void reset() { passedEvent = null; processEventInvoked = false; } public boolean wasProcessEventInvoked() { return processEventInvoked; } public SystemEvent getPassedEvent() { return passedEvent; } } // END TestComponentListener private static final class TestListener implements SystemEventListener { private Class sourceFor; private Object passedSource; private SystemEvent passedEvent; boolean processEventInvoked; private boolean forSourceInvoked; // -------------------------------------------------------- Constructors public TestListener() { } public TestListener(Class sourceFor) { this.sourceFor = sourceFor; } // ------------------------------------- Methods for SystemEventListener public void processEvent(SystemEvent event) throws AbortProcessingException { processEventInvoked = true; passedEvent = event; } public boolean isListenerForSource(Object source) { forSourceInvoked = true; passedSource = source; if (sourceFor == null) { return (source != null); } else { return sourceFor.isInstance(source); } } // ------------------------------------------------------ Public Methods public Object getPassedSource() { return passedSource; } public SystemEvent getPassedSystemEvent() { return passedEvent; } public boolean wasProcessEventInvoked() { return processEventInvoked; } public boolean wasIsListenerForSourceInvoked() { return forSourceInvoked; } public void reset() { passedSource = null; passedEvent = null; processEventInvoked = false; forSourceInvoked = false; } public void setSourceFor(Class sourceFor) { this.sourceFor = sourceFor; } } // END TestListener public class CustomViewRoot extends UIViewRoot { } // END CustomViewRoot public static final class TestSystemEvent extends SystemEvent { private static final long serialVersionUID = -1623739732540866805L; // -------------------------------------------------------- Constructors public TestSystemEvent(UIViewRoot root) { super(root); } // -------------------------------------------- Methods from SystemEvent @Override public boolean isAppropriateListener(FacesListener listener) { return (listener instanceof TestListener); } @Override public void processListener(FacesListener listener) { super.processListener(listener); } } // END TestSystemEvent public static final class TestSystemEvent2 extends SystemEvent { private static final long serialVersionUID = -5903799319964180305L; // -------------------------------------------------------- Constructors public TestSystemEvent2(UIComponent root) { super(root); } } // END TestSystemEvent2 private static final class TestSystemEventListenerHolder implements SystemEventListenerHolder { public List getListenersForEventClass(Class facesEventClass) { return null; } } // END TestSystemEventListenerHolder public static final class TestSystemEvent3 extends ComponentSystemEvent { private static final long serialVersionUID = 6317143707337743522L; public TestSystemEvent3(UIComponent component) { super(component); } } // END TestSystemEvent3 } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/NavigationHandlerTestImpl.java0000644000000000000000000000400411412443350026031 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; public class NavigationHandlerTestImpl extends NavigationHandlerImpl { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/NavBean.java0000644000000000000000000000422511412443350022271 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2009 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import java.util.concurrent.atomic.AtomicInteger; public class NavBean { private static AtomicInteger integer = new AtomicInteger(0); public int getIncrement() { return integer.incrementAndGet(); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestViewHandlerImpl.java0000644000000000000000000005725611412443350024665 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestViewHandlerImpl.java package com.sun.faces.application; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.event.PhaseId; import javax.faces.application.StateManager; import javax.faces.application.StateManager.SerializedView; import javax.faces.application.ViewHandler; import javax.faces.component.UIForm; import javax.faces.component.UIInput; import javax.faces.component.UIPanel; import javax.faces.component.UIViewRoot; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.lifecycle.Lifecycle; import javax.faces.lifecycle.LifecycleFactory; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.StringWriter; import java.util.Locale; import java.util.Map; import com.sun.faces.application.view.FaceletViewHandlingStrategy; import com.sun.faces.cactus.TestingUtil; import com.sun.faces.config.WebConfiguration; import com.sun.faces.util.TestUtil; import org.apache.cactus.WebRequest; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.context.ExternalContextImpl; import com.sun.faces.context.FacesContextImpl; import com.sun.faces.renderkit.RenderKitUtils; import com.sun.faces.util.Util; import com.sun.faces.util.RequestStateManager; /** * TestViewHandlerImpl is a class ... *

* Lifetime And Scope

* */ public class TestViewHandlerImpl extends JspFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/greeting.jsp"; public String getExpectedOutputFilename() { return "TestViewHandlerImpl_correct"; } public static final String ignore[] = { }; public String[] getLinesToIgnore() { return ignore; } public boolean sendResponseToFile() { return true; } // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestViewHandlerImpl() { super("TestViewHandlerImpl"); } public TestViewHandlerImpl(String name) { super(name); } // // Class methods // // // General Methods // public void beginRender(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); } public void beginRender2(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/somepath/greeting.jsf", null, null); } public void beginTransient(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); theRequest.addParameter("javax.faces.ViewState", "j_id1:j_id2"); } public void beginCalculateLocaleLang(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/somepath/greeting.jsf", null, null); theRequest.addHeader("Accept-Language", "es-ES,tg-AF,tk-IQ,en-US"); } public void beginCalculateLocaleExact(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/somepath/greeting.jsf", null, null); theRequest.addHeader("Accept-Language", "tg-AF,tk-IQ,ps-PS,en-US"); } public void beginCalculateLocaleLowerCase(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/somepath/greeting.jsf", null, null); theRequest.addHeader("Accept-Language", "tg-af,tk-iq,ps-ps"); } public void beginCalculateLocaleNoMatch(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/somepath/greeting.jsf", null, null); theRequest.addHeader("Accept-Language", "es-ES,tg-AF,tk-IQ"); } public void beginCalculateLocaleFindDefault(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/somepath/greeting.jsf", null, null); theRequest.addHeader("Accept-Language", "en,fr"); } public void beginRestoreViewNegative(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", null, null); } public void testGetActionURL() { LifecycleFactory factory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); Lifecycle lifecycle = factory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE); // wrap the request so we can control the return value of getServletPath TestRequest testRequest = new TestRequest(request); ExternalContext extContext = new ExternalContextImpl( config.getServletContext(), testRequest, response); FacesContext facesContext = new FacesContextImpl(extContext, lifecycle); String contextPath = request.getContextPath(); ViewHandlerImpl handler = new ViewHandlerImpl(); // if getServletPath() returns "" then the viewId path returned should // be the same as what was passed, prefixed by the context path. //testRequest.setServletPath(""); //testRequest.setAttribute("com.sun.faces.INVOCATION_PATH", null); //String path = handler.getActionURL(facesContext, "/test.jsp"); //System.out.println("VIEW ID PATH 1: " + path); //assertEquals(contextPath + "/test.jsp", path); // if getServletPath() returns a path prefix, then the viewId path // returned must have that path prefixed. testRequest.setServletPath("/faces"); testRequest.setPathInfo("/path/test.jsp"); RequestStateManager.remove(facesContext, RequestStateManager.INVOCATION_PATH); String path = handler.getActionURL(facesContext, "/path/test.jsp"); System.out.println("VIEW ID PATH 2: " + path); String expected = contextPath + "/faces/path/test.jsp"; assertEquals("Expected: " + expected + ", recieved: " + path, expected, path); // if getServletPath() returns a path indicating extension mapping // and the viewId passed has no extension, append the extension // to the provided viewId testRequest.setServletPath("/path/firstRequest.jsf"); testRequest.setPathInfo(null); RequestStateManager.remove(facesContext, RequestStateManager.INVOCATION_PATH); path = handler.getActionURL(facesContext, "/path/test"); System.out.println("VIEW ID PATH 3: " + path); expected = contextPath + "/path/test"; assertEquals("Expected: " + expected + ", recieved: " + path, expected, path); // if getServletPath() returns a path indicating extension mapping // and the viewId passed has an extension, replace the extension with // the extension defined in the deployment descriptor testRequest.setServletPath("/path/firstRequest.jsf"); testRequest.setPathInfo(null); RequestStateManager.remove(facesContext, RequestStateManager.INVOCATION_PATH); path = handler.getActionURL(facesContext, "/path/t.est.jsp"); System.out.println("VIEW ID PATH 4: " + path); expected = contextPath + "/path/t.est.jsf"; assertEquals("Expected: " + expected + ", recieved: " + path, expected, path); // if path info is null, the impl must check to see if // there is an exact match on the servlet path, if so, return // the servlet path testRequest.setServletPath("/faces"); testRequest.setPathInfo(null); RequestStateManager.remove(facesContext, RequestStateManager.INVOCATION_PATH); path = handler.getActionURL(facesContext, "/path/t.est"); System.out.println("VIEW ID PATH 5: " + path); expected = contextPath + "/faces/path/t.est"; assertEquals("Expected: " + expected + ", recieved: " + path, expected, path); } public void testFullAndPartialStateConfiguration() throws Exception { WebConfiguration webConfig = WebConfiguration.getInstance(); webConfig.overrideContextInitParameter(WebConfiguration.BooleanWebContextInitParameter.PartialStateSaving, true); ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance(); ApplicationStateInfo info = new ApplicationStateInfo(); TestingUtil.setPrivateField("applicationStateInfo", ApplicationAssociate.class, associate, info); FaceletViewHandlingStrategy strat = new FaceletViewHandlingStrategy(); getFacesContext().getViewRoot().setViewId("/index.xhtml"); assertNotNull(strat.getStateManagementStrategy(getFacesContext(), "/index.xhmtl")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); getFacesContext().getViewRoot().setViewId("/index2.xhtml"); assertNotNull(strat.getStateManagementStrategy(getFacesContext(), "/index2.xhtml")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); // --------------------------------------------- webConfig.overrideContextInitParameter(WebConfiguration.BooleanWebContextInitParameter.PartialStateSaving, false); info = new ApplicationStateInfo(); TestingUtil.setPrivateField("applicationStateInfo", ApplicationAssociate.class, associate, info); getFacesContext().getViewRoot().setViewId("/index.xhtml"); assertNull(strat.getStateManagementStrategy(getFacesContext(), "/index.xhmtl")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); getFacesContext().getViewRoot().setViewId("/index2.xhtml"); assertNull(strat.getStateManagementStrategy(getFacesContext(), "/index2.xhtml")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); // --------------------------------------------- webConfig.overrideContextInitParameter(WebConfiguration.BooleanWebContextInitParameter.PartialStateSaving, true); webConfig.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.FullStateSavingViewIds, "/index.xhtml"); info = new ApplicationStateInfo(); TestingUtil.setPrivateField("applicationStateInfo", ApplicationAssociate.class, associate, info); getFacesContext().getViewRoot().setViewId("/index.xhtml"); assertNull(strat.getStateManagementStrategy(getFacesContext(), "/index.xhtml")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); getFacesContext().getViewRoot().setViewId("/index2.xhtml"); assertNotNull(strat.getStateManagementStrategy(getFacesContext(), "/index2.xhtml")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); // --------------------------------------------- webConfig.overrideContextInitParameter(WebConfiguration.BooleanWebContextInitParameter.PartialStateSaving, true); webConfig.overrideContextInitParameter(WebConfiguration.WebContextInitParameter.FullStateSavingViewIds, "/index.xhtml,/index2.xhtml"); info = new ApplicationStateInfo(); TestingUtil.setPrivateField("applicationStateInfo", ApplicationAssociate.class, associate, info); getFacesContext().getViewRoot().setViewId("/index.xhtml"); assertNull(strat.getStateManagementStrategy(getFacesContext(), "/index.xhtml")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); getFacesContext().getViewRoot().setViewId("/index2.xhtml"); assertNull(strat.getStateManagementStrategy(getFacesContext(), "/index2.xhtml")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); getFacesContext().getViewRoot().setViewId("/index3.xhtml"); assertNotNull(strat.getStateManagementStrategy(getFacesContext(), "/index3.xhtml")); assertNotNull(getFacesContext().getAttributes().remove("com.sun.faces.context.StateContext_KEY")); } public void testGetActionURLExceptions() throws Exception { boolean exceptionThrown = false; ViewHandler handler = Util.getViewHandler(getFacesContext()); try { handler.getActionURL(null, "/test.jsp"); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { handler.getActionURL(getFacesContext(), null); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { handler.getActionURL(getFacesContext(), "test.jsp"); } catch (IllegalArgumentException iae) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testGetResourceURL() throws Exception { LifecycleFactory factory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); Lifecycle lifecycle = factory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE); ExternalContext extContext = new ExternalContextImpl(config.getServletContext(), request, response); FacesContext context = new FacesContextImpl(extContext, lifecycle); // Validate correct calculations assertEquals(request.getContextPath() + "/index.jsp", Util.getViewHandler(getFacesContext()). getResourceURL(context, "/index.jsp")); assertEquals("index.jsp", Util.getViewHandler(getFacesContext()). getResourceURL(context, "index.jsp")); } public void testRender() { getFacesContext().setCurrentPhaseId(PhaseId.RENDER_RESPONSE); UIViewRoot newView = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), TEST_URI); //newView.setViewId(TEST_URI); getFacesContext().setViewRoot(newView); try { ViewHandler viewHandler = Util.getViewHandler(getFacesContext()); viewHandler.renderView(getFacesContext(), getFacesContext().getViewRoot()); } catch (IOException e) { System.out.println("ViewHandler IOException:" + e); } catch (FacesException fe) { System.out.println("ViewHandler FacesException: " + fe); } assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(verifyExpectedOutput()); } /* public void testRender2() { // Change the viewID to end with .jsf and make sure that // the implementation changes .jsf to .jsp and properly dispatches // the message. UIViewRoot newView = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); newView.setViewId(TEST_URI); getFacesContext().setViewRoot(newView); newView.setViewId("/faces/greeting.jsf"); getFacesContext().setViewRoot(newView); try { ViewHandler viewHandler = Util.getViewHandler(getFacesContext()); viewHandler.renderView(getFacesContext(), getFacesContext().getViewRoot()); } catch (IOException ioe) { System.out.println("ViewHandler IOException: " + ioe); } catch (FacesException fe) { System.out.println("ViewHandler FacesException: " + fe); } assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(verifyExpectedOutput()); } */ public void testCalculateLocaleLang() { System.out.println("Testing calculateLocale - Language Match case"); ViewHandler handler = new ViewHandlerImpl(); Locale locale = handler.calculateLocale(getFacesContext()); assertTrue(locale.equals(Locale.ENGLISH)); } public void testCalculateLocaleExact() { System.out.println("Testing calculateLocale - Exact Match case "); ViewHandler handler = new ViewHandlerImpl(); Locale locale = handler.calculateLocale(getFacesContext()); assertTrue(locale.equals(new Locale("ps", "PS"))); } public void testCalculateLocaleNoMatch() { System.out.println("Testing calculateLocale - No Match case"); ViewHandler handler = new ViewHandlerImpl(); Locale locale = handler.calculateLocale(getFacesContext()); assertTrue(locale.equals(Locale.US)); } public void testCalculateLocaleFindDefault() { System.out.println("Testing calculateLocale - find default"); ViewHandler handler = new ViewHandlerImpl(); Locale locale = handler.calculateLocale(getFacesContext()); assertEquals(Locale.ENGLISH.toString(), locale.toString()); } public void testCalculateLocaleLowerCase() { System.out.println("Testing calculateLocale - case sensitivity"); ViewHandler handler = new ViewHandlerImpl(); Locale locale = handler.calculateLocale(getFacesContext()); assertTrue(locale.equals(new Locale("ps", "PS"))); } public void testTransient() { // precreate tree and set it in session and make sure the tree is // restored from session. UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setViewId(TEST_URI); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName = new UIInput(); userName.setId("userName"); userName.setTransient(true); root.getChildren().add(basicForm); basicForm.getChildren().add(userName); UIPanel panel1 = new UIPanel(); panel1.setId("panel1"); basicForm.getChildren().add(panel1); UIInput userName1 = new UIInput(); userName1.setId("userName1"); userName1.setTransient(true); panel1.getChildren().add(userName1); UIInput userName2 = new UIInput(); userName2.setId("userName2"); panel1.getChildren().add(userName2); UIInput userName3 = new UIInput(); userName3.setTransient(true); panel1.getFacets().put("userName3", userName3); UIInput userName4 = new UIInput(); panel1.getFacets().put("userName4", userName4); HttpSession session = (HttpSession) getFacesContext().getExternalContext().getSession(false); session.setAttribute(TEST_URI, root); getFacesContext().setViewRoot(root); StateManager stateManager = getFacesContext().getApplication().getStateManager(); SerializedView viewState = stateManager.saveSerializedView(getFacesContext()); assertTrue(null != viewState); try { RenderKit curKit = RenderKitUtils.getCurrentRenderKit(getFacesContext()); StringWriter writer = new StringWriter(); ResponseWriter responseWriter = curKit.createResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(responseWriter); stateManager.writeState(getFacesContext(), viewState); root = stateManager.restoreView(getFacesContext(), TEST_URI, RenderKitFactory.HTML_BASIC_RENDER_KIT); getFacesContext().setViewRoot(root); } catch (Throwable ioe) { ioe.printStackTrace(); fail(); } // make sure that the transient property is not persisted. basicForm = (UIForm) (getFacesContext().getViewRoot()).findComponent( "basicForm"); assertTrue(basicForm != null); userName = (UIInput) basicForm.findComponent("userName"); assertTrue(userName == null); panel1 = (UIPanel) basicForm.findComponent("panel1"); assertTrue(panel1 != null); userName1 = (UIInput) panel1.findComponent("userName1"); assertTrue(userName1 == null); userName2 = (UIInput) panel1.findComponent("userName2"); assertTrue(userName2 != null); // make sure facets work correctly when marked transient. Map facetList = panel1.getFacets(); assertTrue(!(facetList.containsKey("userName3"))); assertTrue(facetList.containsKey("userName4")); } public void testRestoreViewNegative() throws Exception { // make sure the returned view is null if the viewId is the same // as the servlet mapping. assertNull(Util.getViewHandler(getFacesContext()).restoreView(getFacesContext(), "/faces")); } private class TestRequest extends HttpServletRequestWrapper { String servletPath; String pathInfo; public TestRequest(HttpServletRequest request) { super(request); } public String getServletPath() { return servletPath; } public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getPathInfo() { return pathInfo; } public void setPathInfo(String pathInfo) { this.pathInfo = pathInfo; } } } // end of class TestViewHandlerImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestNavigationHandler.java0000644000000000000000000004343011412443350025215 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestNavigationHandler.java package com.sun.faces.application; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import com.sun.faces.config.DbfFactory; import javax.faces.FactoryFinder; import javax.faces.event.SystemEventListener; import javax.faces.event.SystemEvent; import javax.faces.event.AbortProcessingException; import javax.faces.event.PreDestroyViewMapEvent; import javax.faces.application.*; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.util.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; /** * This class test the NavigationHandlerImpl functionality. * It uses two xml files: * 1) faces-navigation.xml --> contains the navigation cases themselves. * 2) navigation-cases.xml --> contains the test cases including expected * view identifier outcomes for this test to validate against. * Both files exist under web/test/WEB-INF. *

* Lifetime And Scope

* */ public class TestNavigationHandler extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // private List testResultList = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestNavigationHandler() { super("TestNavigationHandler"); } public TestNavigationHandler(String name) { super(name); } // // Class methods // // // Methods from TestCase // public void setUp() { super.setUp(); loadConfigFile(); } // // General Methods // private void loadConfigFile() { loadFromInitParam("/WEB-INF/faces-navigation.xml"); } private void loadTestResultList() throws Exception { DocumentBuilderFactory f = DbfFactory.getFactory(); f.setNamespaceAware(false); f.setValidating(false); DocumentBuilder builder = f.newDocumentBuilder(); Document d = builder.parse(config.getServletContext().getResourceAsStream("/WEB-INF/navigation-cases.xml")); NodeList navigationRules = d.getDocumentElement() .getElementsByTagName("test"); for (int i = 0; i < navigationRules.getLength(); i++) { Node test = navigationRules.item(i); NamedNodeMap attributes = test.getAttributes(); Node fromViewId = attributes.getNamedItem("fromViewId"); Node fromAction = attributes.getNamedItem("fromAction"); Node fromOutput = attributes.getNamedItem("fromOutcome"); Node toViewId = attributes.getNamedItem("toViewId"); createAndAccrueTestResult(((fromViewId != null) ? fromViewId.getTextContent().trim() : null), ((fromAction != null) ? fromAction.getTextContent().trim() : null), ((fromOutput != null) ? fromOutput.getTextContent().trim() : null), ((toViewId != null) ? toViewId.getTextContent().trim() : null)); } } public void createAndAccrueTestResult(String fromViewId, String fromAction, String fromOutcome, String toViewId) { if (testResultList == null) { testResultList = new ArrayList(); } TestResult testResult = new TestResult(); testResult.fromViewId = fromViewId; testResult.fromAction = fromAction; testResult.fromOutcome = fromOutcome; testResult.toViewId = toViewId; testResultList.add(testResult); } public void testNavigationHandler() { Application application = getFacesContext().getApplication(); ViewMapDestroyedListener listener = new ViewMapDestroyedListener(); application.subscribeToEvent(PreDestroyViewMapEvent.class, UIViewRoot.class, listener); try { loadTestResultList(); } catch (Exception e) { throw new RuntimeException(e); } NavigationHandlerImpl navHandler = (NavigationHandlerImpl) application.getNavigationHandler(); FacesContext context = getFacesContext(); String newViewId; UIViewRoot page; boolean gotException = false; for (int i = 0; i < testResultList.size(); i++) { TestResult testResult = (TestResult) testResultList.get(i); System.out.println("Testing from-view-id=" + testResult.fromViewId + " from-action=" + testResult.fromAction + " from-outcome=" + testResult.fromOutcome); page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setViewId(testResult.fromViewId); page.setLocale(Locale.US); page.getViewMap(); // cause the map to be created context.setViewRoot(page); listener.reset(); try { navHandler.handleNavigation(context, testResult.fromAction, testResult.fromOutcome); } catch (Exception e) { // exception is valid only if context or fromoutcome is null. assertTrue(testResult.fromOutcome == null); gotException = true; } if (!gotException) { if (!testResult.fromViewId.equals(testResult.toViewId) && testResult.fromOutcome != null) { assertTrue(listener.getPassedEvent() instanceof PreDestroyViewMapEvent); } else { assertTrue(!listener.wasProcessEventInvoked()); assertTrue(listener.getPassedEvent() == null); } listener.reset(); newViewId = context.getViewRoot().getViewId(); if (testResult.fromOutcome == null) { listener.reset(); System.out.println( "assertTrue(" + newViewId + ".equals(" + testResult.fromViewId + "))"); assertTrue(newViewId.equals(testResult.fromViewId)); } else { listener.reset(); System.out.println( "assertTrue(" + newViewId + ".equals(" + testResult.toViewId + "))"); assertTrue(newViewId.equals(testResult.toViewId)); } } } application.unsubscribeFromEvent(PreDestroyViewMapEvent.class, UIViewRoot.class, listener); } public void testSimilarFromViewId() { ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); Application application = aFactory.getApplication(); NavigationHandler navHandler = application.getNavigationHandler(); UIViewRoot root = application.getViewHandler().createView(getFacesContext(), "/dir1/dir2/dir3/test.jsp"); root.setLocale(Locale.US); getFacesContext().setViewRoot(root); try { navHandler.handleNavigation(getFacesContext(), null, "home"); } catch (Exception e) { e.printStackTrace(); assert(false); } String newViewId = getFacesContext().getViewRoot().getViewId(); assertTrue("newViewId is: " + newViewId, "/dir1/dir2/dir3/home.jsp".equals(newViewId)); } // This tests that the same element value existing in a seperate // navigation rule, gets combined with the other rules with the same . // Specifically, it will to make sure that after loading, there are the correct number of // cases with the common ; public void testSeperateRule() { int cnt = 0; ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); Application application = aFactory.getApplication(); assertTrue(application instanceof ApplicationImpl); ConfigurableNavigationHandler handler = (ConfigurableNavigationHandler) application.getNavigationHandler(); Map caseListMap = handler.getNavigationCases(); Iterator iter = caseListMap.keySet().iterator(); while (iter.hasNext()) { String fromViewId = (String) iter.next(); if (fromViewId.equals("/login.jsp")) { Set caseSet = (Set) caseListMap.get(fromViewId); for (NavigationCase navCase : caseSet) { if (navCase.getFromViewId().equals("/login.jsp")) { cnt++; } } } } assertTrue(cnt == 6); } public void testWrappedNavigationHandler() { Application app = getFacesContext().getApplication(); ConfigurableNavigationHandler impl = new NavigationHandlerImpl(); NavigationHandler parent = new WrapperNavigationHandler(impl); parent.handleNavigation(getFacesContext(), "", ""); int cnt = 0; Map caseListMap = impl.getNavigationCases(); Iterator iter = caseListMap.keySet().iterator(); while (iter.hasNext()) { String fromViewId = (String) iter.next(); if (fromViewId.equals("/login.jsp")) { Set caseSet = (Set) caseListMap.get(fromViewId); for (NavigationCase navCase : caseSet) { if (navCase.getFromViewId().equals("/login.jsp")) { cnt++; } } } } assertTrue(cnt == 6); } public void testRedirectParameters() { Application app = getFacesContext().getApplication(); UIViewRoot root = (UIViewRoot) app.createComponent(UIViewRoot.COMPONENT_TYPE); root.setViewId("/page1.xhtml"); getFacesContext().setViewRoot(root); ConfigurableNavigationHandler cnh = (ConfigurableNavigationHandler) getFacesContext().getApplication().getNavigationHandler(); NavigationCase c1 = cnh.getNavigationCase(getFacesContext(), null, "redirectOutcome1"); Map> parameters = c1.getParameters(); assertNotNull(parameters); assertEquals(2, parameters.size()); List fooParams = parameters.get("foo"); assertNotNull(fooParams); assertEquals(2, fooParams.size()); assertEquals("bar", fooParams.get(0)); assertEquals("bar2", fooParams.get(1)); List foo2Params = parameters.get("foo2"); assertEquals(1, foo2Params.size()); assertEquals("bar3", foo2Params.get(0)); assertTrue(c1.isIncludeViewParams()); NavigationCase c2 = cnh.getNavigationCase(getFacesContext(), null, "redirectOutcome2"); parameters = c2.getParameters(); assertNull(parameters); assertFalse(c2.isIncludeViewParams()); // ensure implicit navigation outcomes that include query strings // are properly parsed. NavigationCase c3 = cnh.getNavigationCase(getFacesContext(), null, "test?foo=rab&foo=rab2&foo2=rab3&faces-redirect=true&includeViewParams=true&"); assertNotNull(c3); parameters = c3.getParameters(); assertNotNull(parameters); assertTrue(c3.isRedirect()); assertTrue(c3.isIncludeViewParams()); assertEquals(2, parameters.size()); fooParams = parameters.get("foo"); assertNotNull(fooParams); assertEquals(2, fooParams.size()); assertEquals("rab", fooParams.get(0)); assertEquals("rab2", fooParams.get(1)); foo2Params = parameters.get("foo2"); assertEquals(1, foo2Params.size()); assertEquals("rab3", foo2Params.get(0)); // ensure implicit navigation outcomes that include query strings // separated with & are properly parsed. NavigationCase c4 = cnh.getNavigationCase(getFacesContext(), null, "test?foo=rab&foo=rab2&foo2=rab3&faces-redirect=true&includeViewParams=true&"); assertNotNull(c4); parameters = c4.getParameters(); assertNotNull(parameters); assertTrue(c4.isRedirect()); assertTrue(c4.isIncludeViewParams()); assertEquals(2, parameters.size()); fooParams = parameters.get("foo"); assertNotNull(fooParams); assertEquals(2, fooParams.size()); assertEquals("rab", fooParams.get(0)); assertEquals("rab2", fooParams.get(1)); foo2Params = parameters.get("foo2"); assertEquals(1, foo2Params.size()); assertEquals("rab3", foo2Params.get(0)); // ensure invalid query string correctly handled NavigationCase c5 = cnh.getNavigationCase(getFacesContext(), null, "test?"); assertNotNull(c5); assertNull(c5.getParameters()); assertFalse(c5.isRedirect()); assertFalse(c5.isIncludeViewParams()); // ensure redirect parameter el evaluation is performed more than once NavigationCase ncase = cnh.getNavigationCase(getFacesContext(), null, "redirectOutcome3"); String url = getFacesContext().getExternalContext().encodeRedirectURL("/path.xhtml", ncase.getParameters()); System.out.println("URL: " + url); assertTrue(url.contains("param=1")); url = getFacesContext().getExternalContext().encodeRedirectURL("/path.xhtml", ncase.getParameters()); assertTrue(url.contains("param=2")); } // ---------------------------------------------------------- Nested Classes private static final class WrapperNavigationHandler extends NavigationHandler { private NavigationHandler delegate; public WrapperNavigationHandler(NavigationHandler delegate) { this.delegate = delegate; } public void handleNavigation(FacesContext context, String fromAction, String outcome) { delegate.handleNavigation(context, fromAction, outcome); } } class TestResult extends Object { public String fromViewId = null; public String fromAction = null; public String fromOutcome = null; public String toViewId = null; } private static final class ViewMapDestroyedListener implements SystemEventListener { private SystemEvent event; private boolean processEventInvoked; public void processEvent(SystemEvent event) throws AbortProcessingException { this.processEventInvoked = true; this.event = event; } public boolean isListenerForSource(Object source) { return (source instanceof UIViewRoot); } public SystemEvent getPassedEvent() { return event; } public boolean wasProcessEventInvoked() { return processEventInvoked; } public void reset() { processEventInvoked = false; event = null; } } } // end of class TestNavigationHandler mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/DeprStateManagerImpl.java0000644000000000000000000005002211412443350024763 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // DeprStateManagerImpl.java package com.sun.faces.application; import com.sun.faces.RIConstants; import com.sun.faces.renderkit.RenderKitUtils; import com.sun.faces.util.TreeStructure; import com.sun.faces.util.LRUMap; import com.sun.faces.util.MessageUtils; import com.sun.faces.util.RequestStateManager; import javax.faces.application.StateManager; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.render.ResponseStateManager; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.faces.component.NamingContainer; import javax.faces.component.UINamingContainer; /** * DeprStateManagerImpl is a test class which implements * deprecated methods only. */ public class DeprStateManagerImpl extends StateManager { private static final String NUMBER_OF_VIEWS_IN_SESSION = RIConstants.FACES_PREFIX + "NUMBER_OF_VIEWS_IN_SESSION"; private static final int DEFAULT_NUMBER_OF_VIEWS_IN_SESSION = 15; private static final String NUMBER_OF_VIEWS_IN_LOGICAL_VIEW_IN_SESSION = RIConstants.FACES_PREFIX + "NUMBER_OF_VIEWS_IN_LOGICAL_VIEW_IN_SESSION"; private static final int DEFAULT_NUMBER_OF_VIEWS_IN_LOGICAL_VIEW_IN_SESSION = 15; private static final String LOGICAL_VIEW_MAP = RIConstants.FACES_PREFIX + "logicalViewMap"; /** * Number of views in logical view to be saved in session. */ int noOfViews = 0; int noOfViewsInLogicalView = 0; public SerializedView saveSerializedView(FacesContext context) throws IllegalStateException{ SerializedView result = null; Object treeStructure = null; Object componentState = null; // irrespective of method to save the tree, if the root is transient // no state information needs to be persisted. UIViewRoot viewRoot = context.getViewRoot(); if (viewRoot.isTransient()) { return result; } // honor the requirement to check for id uniqueness checkIdUniqueness(context, viewRoot, new HashSet()); result = new SerializedView(treeStructure = getTreeStructureToSave(context), componentState = getComponentStateToSave(context)); if (!isSavingStateInClient(context)) { // // Server Side state saving is handled stored in two nested LRU maps // in the session. // // The first map is called the LOGICAL_VIEW_MAP. A logical view // is a top level view that may have one or more actual views inside // of it. This will be the case when you have a frameset, or an // application that has multiple windows operating at the same time. // The LOGICAL_VIEW_MAP map contains // an entry for each logical view, up to the limit specified by the // numberOfViewsParameter. Each entry in the LOGICAL_VIEW_MAP // is an LRU Map, configured with the numberOfViewsInLogicalView // parameter. // // The motivation for this is to allow better memory tuning for // apps that need this multi-window behavior. String id = null, idInActualMap = null, idInLogicalMap = (String) RequestStateManager.get(context, RequestStateManager.LOGICAL_VIEW_MAP); LRUMap logicalMap = null, actualMap = null; int logicalMapSize = getNumberOfViewsParameter(context), actualMapSize = getNumberOfViewsInLogicalViewParameter(context); Object stateArray[] = { treeStructure, componentState }; Map sessionMap = context.getExternalContext().getSessionMap(); synchronized (this) { if (null == (logicalMap = (LRUMap) sessionMap.get(LOGICAL_VIEW_MAP))) { logicalMap = new LRUMap(logicalMapSize); sessionMap.put(LOGICAL_VIEW_MAP, logicalMap); } assert(null != logicalMap); if (null == idInLogicalMap) { idInLogicalMap = createUniqueRequestId(); } assert(null != idInLogicalMap); idInActualMap = createUniqueRequestId(); if (null == (actualMap = (LRUMap) logicalMap.get(idInLogicalMap))) { actualMap = new LRUMap(actualMapSize); logicalMap.put(idInLogicalMap, actualMap); } id = idInLogicalMap + ':' + idInActualMap; result = new SerializedView(id, null); actualMap.put(idInActualMap, stateArray); } } return result; } char requestIdSerial = 0; private String createUniqueRequestId() { if (requestIdSerial++ == Character.MAX_VALUE) { requestIdSerial = 0; } return UIViewRoot.UNIQUE_ID_PREFIX + ((int) requestIdSerial); } protected void checkIdUniqueness(FacesContext context, UIComponent component, Set componentIds) throws IllegalStateException{ UIComponent kid; // deal with children that are marked transient. Iterator kids = component.getChildren().iterator(); String id; while (kids.hasNext()) { kid = (UIComponent) kids.next(); // check for id uniqueness id = kid.getClientId(context); if (id != null && !componentIds.add(id)) { throw new IllegalStateException(MessageUtils.getExceptionMessageString( MessageUtils.DUPLICATE_COMPONENT_ID_ERROR_ID, new Object[]{id})); } checkIdUniqueness(context, kid, componentIds); } // deal with facets that are marked transient. kids = component.getFacets().values().iterator(); while (kids.hasNext()) { kid = (UIComponent) kids.next(); // check for id uniqueness id = kid.getClientId(context); if (id != null && !componentIds.add(id)) { throw new IllegalStateException(MessageUtils.getExceptionMessageString( MessageUtils.DUPLICATE_COMPONENT_ID_ERROR_ID, new Object[]{id})); } checkIdUniqueness(context, kid, componentIds); } } protected Object getComponentStateToSave(FacesContext context) { return context.getViewRoot().processSaveState(context); } protected Object getTreeStructureToSave(FacesContext context) { TreeStructure structRoot = null; UIComponent viewRoot = context.getViewRoot(); if (!(viewRoot.isTransient())) { structRoot = new TreeStructure(viewRoot); buildTreeStructureToSave(context, viewRoot, structRoot, null); } return structRoot; } public UIViewRoot restoreView(FacesContext context, String viewId, String renderKitId) { if (null == renderKitId) { String message = MessageUtils.getExceptionMessageString (MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "renderKitId"); throw new IllegalArgumentException(message); } UIViewRoot viewRoot = null; if (isSavingStateInClient(context)) { // restore view from response. viewRoot = restoreTreeStructure(context, viewId, renderKitId); if (viewRoot != null) { restoreComponentState(context, viewRoot, renderKitId); } else { } } else { // restore tree from session. // The ResponseStateManager implementation may be using the new methods or // deprecated methods. We need to know which one to call. Object id = null; ResponseStateManager rsm = RenderKitUtils.getResponseStateManager(context, renderKitId); id = rsm.getTreeStructureToRestore(context, viewId); if (null != id) { String idString = (String) id, idInLogicalMap = null, idInActualMap = null; int sep = idString.indexOf(':'); assert(-1 != sep); assert(sep < idString.length()); idInLogicalMap = idString.substring(0, sep); idInActualMap = idString.substring(sep + 1); ExternalContext externalCtx = context.getExternalContext(); Object sessionObj = externalCtx.getSession(false); // stop evaluating if the session is not available if (sessionObj == null) { return null; } Map logicalMap = null, actualMap = null, sessionMap = externalCtx.getSessionMap(); TreeStructure structRoot = null; Object [] stateArray = null; synchronized (sessionObj) { logicalMap = (Map) sessionMap.get(LOGICAL_VIEW_MAP); if (logicalMap != null) { actualMap = (Map) logicalMap.get(idInLogicalMap); if (actualMap != null) { RequestStateManager.set(context, RequestStateManager.LOGICAL_VIEW_MAP, idInLogicalMap); stateArray = (Object []) actualMap.get(idInActualMap); } } } if (stateArray == null) { return null; } structRoot = (TreeStructure)stateArray[0]; viewRoot = (UIViewRoot) structRoot.createComponent(); restoreComponentTreeStructure(structRoot, viewRoot); viewRoot.processRestoreState(context, stateArray[1]); } } return viewRoot; } protected void restoreComponentState(FacesContext context, UIViewRoot root, String renderKitId) { if (null == renderKitId) { String message = MessageUtils.getExceptionMessageString (MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "renderKitId"); throw new IllegalArgumentException(message); } Object state = null; ResponseStateManager rsm = RenderKitUtils.getResponseStateManager(context, renderKitId); state = rsm.getComponentStateToRestore(context); root.processRestoreState(context, state); } protected UIViewRoot restoreTreeStructure(FacesContext context, String viewId, String renderKitId) { if (null == renderKitId) { String message = MessageUtils.getExceptionMessageString (MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "renderKitId"); throw new IllegalArgumentException(message); } UIComponent viewRoot = null; TreeStructure structRoot = null; ResponseStateManager rsm = RenderKitUtils.getResponseStateManager(context, renderKitId); structRoot = (TreeStructure)rsm.getTreeStructureToRestore(context, viewId); if (structRoot == null) { return null; } viewRoot = structRoot.createComponent(); restoreComponentTreeStructure(structRoot, viewRoot); return ((UIViewRoot) viewRoot); } public void writeState(FacesContext context, SerializedView state) throws IOException { String renderKitId = context.getViewRoot().getRenderKitId(); ResponseStateManager rsm = RenderKitUtils.getResponseStateManager(context, renderKitId); rsm.writeState(context, state); } /** * Builds a hierarchy of TreeStrucure objects simulating the component * tree hierarchy. */ public void buildTreeStructureToSave(FacesContext context, UIComponent component, TreeStructure treeStructure, Set componentIds) { // traverse the component hierarchy and save the tree structure // information for every component. // Set for catching duplicate IDs if (null == componentIds) { componentIds = new HashSet(); } // save the structure info of the children of the component // being processed. Iterator kids = component.getChildren().iterator(); String id; while (kids.hasNext()) { UIComponent kid = (UIComponent) kids.next(); // check for id uniqueness id = kid.getClientId(context); if (id != null && !componentIds.add(id)) { throw new IllegalStateException(MessageUtils.getExceptionMessageString( MessageUtils.DUPLICATE_COMPONENT_ID_ERROR_ID, new Object[]{id})); } // if a component is marked transient do not persist its state as // well as its children. if (!kid.isTransient()) { TreeStructure treeStructureChild = new TreeStructure(kid); treeStructure.addChild(treeStructureChild); buildTreeStructureToSave(context, kid, treeStructureChild, componentIds); } } // save structure info of the facets of the component currenly being // processed. Iterator facets = component.getFacets().keySet().iterator(); while (facets.hasNext()) { String facetName = (String) facets.next(); UIComponent facetComponent = (UIComponent) component.getFacets(). get(facetName); // check for id uniqueness id = facetComponent.getClientId(context); if (id != null && !componentIds.add(id)) { throw new IllegalStateException(MessageUtils.getExceptionMessageString( MessageUtils.DUPLICATE_COMPONENT_ID_ERROR_ID, new Object[]{id})); } // if a facet is marked transient do not persist its state as well as // its children. if (!(facetComponent.isTransient())) { TreeStructure treeStructureFacet = new TreeStructure(facetComponent); treeStructure.addFacet(facetName, treeStructureFacet); // process children of facet. buildTreeStructureToSave(context, facetComponent, treeStructureFacet, componentIds); } } } /** * Reconstitutes the component tree from TreeStructure hierarchy */ public void restoreComponentTreeStructure(TreeStructure treeStructure, UIComponent component) { // traverse the tree strucure hierarchy and restore component // structure. // restore the structure of the children of the component being processed. Iterator kids = treeStructure.getChildren(); while (kids.hasNext()) { TreeStructure kid = (TreeStructure) kids.next(); UIComponent child = kid.createComponent(); component.getChildren().add(child); restoreComponentTreeStructure(kid, child); } // process facets Iterator facets = treeStructure.getFacetNames(); while (facets.hasNext()) { String facetName = (String) facets.next(); TreeStructure facetTreeStructure = treeStructure.getTreeStructureForFacet(facetName); UIComponent facetComponent = facetTreeStructure.createComponent(); component.getFacets().put(facetName, facetComponent); restoreComponentTreeStructure(facetTreeStructure, facetComponent); } } /** * Returns the UIViewRoot corresponding the * viewId by restoring the view structure and state. */ protected UIViewRoot restoreSerializedView(FacesContext context, SerializedView sv, String viewId) { if ( sv == null) { return null; } TreeStructure structRoot = (TreeStructure) sv.getStructure(); if (structRoot == null) { return null; } UIComponent viewRoot = structRoot.createComponent(); if (viewRoot != null) { restoreComponentTreeStructure(structRoot, viewRoot); Object state = sv.getState(); viewRoot.processRestoreState(context, state); } return ((UIViewRoot)viewRoot); } /** * Returns the value of ServletContextInitParameter that specifies the * maximum number of logical views to be saved in session. If none is specified * returns DEFAULT_NUMBER_OF_VIEWS_IN_SESSION. */ protected int getNumberOfViewsParameter(FacesContext context) { if (noOfViews != 0) { return noOfViews; } noOfViews = DEFAULT_NUMBER_OF_VIEWS_IN_SESSION; String noOfViewsStr = context.getExternalContext(). getInitParameter(NUMBER_OF_VIEWS_IN_SESSION); if (noOfViewsStr != null) { try { noOfViews = Integer.valueOf(noOfViewsStr).intValue(); } catch (NumberFormatException nfe) { } } return noOfViews; } /** * Returns the value of ServletContextInitParameter that specifies the * maximum number of views to be saved in this logical view. If none is specified * returns DEFAULT_NUMBER_OF_VIEWS_IN_LOGICAL_VIEW_IN_SESSION. */ protected int getNumberOfViewsInLogicalViewParameter(FacesContext context) { if (noOfViewsInLogicalView != 0) { return noOfViewsInLogicalView; } noOfViewsInLogicalView = DEFAULT_NUMBER_OF_VIEWS_IN_LOGICAL_VIEW_IN_SESSION; String noOfViewsStr = context.getExternalContext(). getInitParameter(NUMBER_OF_VIEWS_IN_LOGICAL_VIEW_IN_SESSION); if (noOfViewsStr != null) { try { noOfViewsInLogicalView = Integer.valueOf(noOfViewsStr).intValue(); } catch (NumberFormatException nfe) { } } return noOfViewsInLogicalView; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestFacesMessage.java0000644000000000000000000001241211412443350024142 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestFacesMessage.java package com.sun.faces.application; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import java.io.*; import javax.faces.application.FacesMessage; /** * * TestFacesMessage is a class ... * * Lifetime And Scope

* */ /** * This class tests the FacesMessage class * functionality. It uses the xml configuration file: * web/test/WEB-INF/faces-navigation.xml. */ public class TestFacesMessage extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestFacesMessage() { super("TestFacesMessage"); } public TestFacesMessage(String name) { super(name); } // // Class methods // // // Methods from TestCase // // // General Methods // public void testSerializeable() { FacesMessage message = null; // Case 0 (nothing) message = new FacesMessage(); persistAndCheck(message); // Case 1 (summary) message = new FacesMessage("This is a bad error."); persistAndCheck(message); // Case 2 (summary & detail) message = new FacesMessage("This is a bad error.", "This is a really bad error."); persistAndCheck(message); // Case 3 (severity, summary & detail) message = new FacesMessage(FacesMessage.SEVERITY_FATAL, "This is a bad error.", "This is a really bad error."); persistAndCheck(message); } private void persistAndCheck(FacesMessage message) { FacesMessage message1 = null; String mSummary, mSummary1 = null; String mDetail, mDetail1 = null; String severity, severity1 = null; ByteArrayOutputStream bos = null; ByteArrayInputStream bis = null; mSummary = message.getSummary(); mDetail = message.getDetail(); severity = message.getSeverity().toString(); try { bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(message); oos.close(); byte[] bytes = bos.toByteArray(); InputStream in = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(in); message1 = (FacesMessage)ois.readObject(); ois.close(); mSummary1 = message1.getSummary(); mDetail1 = message1.getDetail(); severity1 = message1.getSeverity().toString(); if (null != mSummary1) { assertTrue(mSummary1.equals(mSummary)); } else { assertTrue(mSummary == null); } if (null != mDetail1) { assertTrue(mDetail1.equals(mDetail)); } else { assertTrue(mDetail == null); } if (null != severity1) { assertTrue(severity1.equals(severity)); } else { assertTrue(severity == null); } } catch (Exception e) { e.printStackTrace(); assertTrue(false); } } } // end of class TestFacesMessage mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestJSF2NavigationHandler.java0000644000000000000000000002644211412443350025646 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestNavigationHandler.java package com.sun.faces.application; import javax.faces.application.NavigationCase; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import com.sun.faces.config.DbfFactory; import javax.faces.FactoryFinder; import javax.faces.event.SystemEventListener; import javax.faces.event.SystemEvent; import javax.faces.event.AbortProcessingException; import javax.faces.event.PreDestroyViewMapEvent; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.application.NavigationHandler; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.util.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; /** * This class test the NavigationHandlerImpl functionality. * It uses two xml files: * 1) faces-navigation.xml --> contains the navigation cases themselves. * 2) navigation-cases.xml --> contains the test cases including expected * view identifier outcomes for this test to validate against. * Both files exist under web/test/WEB-INF. *

* Lifetime And Scope

* */ public class TestJSF2NavigationHandler extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // private List testResultList = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestJSF2NavigationHandler() { super("TestJSF2NavigationHandler"); } public TestJSF2NavigationHandler(String name) { super(name); } // // Class methods // // // Methods from TestCase // public void setUp() { super.setUp(); loadConfigFile(); } // // General Methods // private void loadConfigFile() { loadFromInitParam("/WEB-INF/faces-navigation-2.xml"); } private void loadTestResultList() throws Exception { DocumentBuilderFactory f = DbfFactory.getFactory(); f.setNamespaceAware(false); f.setValidating(false); DocumentBuilder builder = f.newDocumentBuilder(); Document d = builder.parse(config.getServletContext().getResourceAsStream("/WEB-INF/navigation-cases-2.xml")); NodeList navigationRules = d.getDocumentElement() .getElementsByTagName("test"); for (int i = 0; i < navigationRules.getLength(); i++) { Node test = navigationRules.item(i); NamedNodeMap attributes = test.getAttributes(); Node fromViewId = attributes.getNamedItem("fromViewId"); Node fromAction = attributes.getNamedItem("fromAction"); Node fromOutput = attributes.getNamedItem("fromOutcome"); Node condition = attributes.getNamedItem("if"); Node toViewId = attributes.getNamedItem("toViewId"); createAndAccrueTestResult(((fromViewId != null) ? fromViewId.getTextContent().trim() : null), ((fromAction != null) ? fromAction.getTextContent().trim() : null), ((fromOutput != null) ? fromOutput.getTextContent().trim() : null), ((condition != null) ? condition.getTextContent().trim() : null), ((toViewId != null) ? toViewId.getTextContent().trim() : null)); } } public void createAndAccrueTestResult(String fromViewId, String fromAction, String fromOutcome, String condition, String toViewId) { if (testResultList == null) { testResultList = new ArrayList(); } TestResult testResult = new TestResult(); testResult.fromViewId = fromViewId; testResult.fromAction = fromAction; testResult.fromOutcome = fromOutcome; testResult.condition = condition; testResult.toViewId = toViewId; testResultList.add(testResult); } public void testNavigationHandler() { Application application = getFacesContext().getApplication(); ViewMapDestroyedListener listener = new ViewMapDestroyedListener(); application.subscribeToEvent(PreDestroyViewMapEvent.class, UIViewRoot.class, listener); try { loadTestResultList(); } catch (Exception e) { throw new RuntimeException(e); } NavigationHandlerImpl navHandler = (NavigationHandlerImpl) application.getNavigationHandler(); FacesContext context = getFacesContext(); String newViewId; UIViewRoot page; boolean gotException = false; for (int i = 0; i < testResultList.size(); i++) { TestResult testResult = (TestResult) testResultList.get(i); Boolean conditionResult = null; if (testResult.condition != null) { conditionResult = (Boolean) application.getExpressionFactory() .createValueExpression(context.getELContext(), testResult.condition, Boolean.class).getValue(context.getELContext()); } System.out.println("Testing from-view-id=" + testResult.fromViewId + " from-action=" + testResult.fromAction + " from-outcome=" + testResult.fromOutcome + " if=" + testResult.condition); page = Util.getViewHandler(context).createView(context, null); page.setViewId(testResult.fromViewId); page.setLocale(Locale.US); page.getViewMap(); // cause the map to be created context.setViewRoot(page); listener.reset(); try { navHandler.handleNavigation(context, testResult.fromAction, testResult.fromOutcome); } catch (Exception e) { // exception is valid only if context or fromoutcome is null. assertTrue(testResult.fromOutcome == null); gotException = true; } if (!gotException) { // test assumption: if the from and to change, it's because the outcome was not-null or a condition was evaluated if (!testResult.fromViewId.equals(testResult.toViewId) && (testResult.fromOutcome != null || testResult.condition != null) && (testResult.condition == null || conditionResult != null)) { assertTrue(listener.getPassedEvent() instanceof PreDestroyViewMapEvent); } else { assertTrue(!listener.wasProcessEventInvoked()); assertTrue(listener.getPassedEvent() == null); } listener.reset(); newViewId = context.getViewRoot().getViewId(); if (testResult.fromOutcome == null && testResult.condition == null) { listener.reset(); System.out.println( "assertTrue(" + newViewId + ".equals(" + testResult.fromViewId + "))"); assertTrue(newViewId.equals(testResult.fromViewId)); } // test assumption: if condition is false, we advance to some other view else if (testResult.condition != null && conditionResult == false) { listener.reset(); System.out.println( "assertTrue(!" + newViewId + ".equals(" + testResult.toViewId + "))"); assertTrue(!newViewId.equals(testResult.toViewId)); } else { listener.reset(); System.out.println( "assertTrue(" + newViewId + ".equals(" + testResult.toViewId + "))"); assertTrue(newViewId.equals(testResult.toViewId)); } } } application.unsubscribeFromEvent(PreDestroyViewMapEvent.class, UIViewRoot.class, listener); } class TestResult extends Object { public String fromViewId = null; public String fromAction = null; public String fromOutcome = null; public String condition = null; public String toViewId = null; } private static final class ViewMapDestroyedListener implements SystemEventListener { private SystemEvent event; private boolean processEventInvoked; public void processEvent(SystemEvent event) throws AbortProcessingException { this.processEventInvoked = true; this.event = event; } public boolean isListenerForSource(Object source) { return (source instanceof UIViewRoot); } public SystemEvent getPassedEvent() { return event; } public boolean wasProcessEventInvoked() { return processEventInvoked; } public void reset() { processEventInvoked = false; event = null; } } } // end of class TestNavigationHandler mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/ViewHandlerTestImpl.java0000644000000000000000000000377011412443350024655 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; public class ViewHandlerTestImpl extends ViewHandlerImpl { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestInjection.java0000644000000000000000000001545611412443350023551 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.faces.FactoryFinder; import javax.faces.application.ApplicationFactory; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.spi.InjectionProvider; public class TestInjection extends ServletFacesTestCase { public TestInjection() { super("TestInjection"); } public TestInjection(String name) { super(name); } public void setUp() { super.setUp(); } // ------------------------------------------------------------ Test Methods /** * Validate PostConstruct/PreDestroy annotations are property * invoked on protected, package private, and private methods. * @throws Exception if an error occurs */ public void testInjection() throws Exception { ProtectedBean protectedBean = new ProtectedBean(); PackagePrivateBean packagePrivateBean = new PackagePrivateBean(); PrivateBean privateBean = new PrivateBean(); ConcreteBean concreteBean = new ConcreteBean(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); aFactory.getApplication(); // bootstraps the ApplicationAssociate ApplicationAssociate associate = ApplicationAssociate .getInstance(getFacesContext().getExternalContext()); assertNotNull(associate); InjectionProvider injectionProvider = associate.getInjectionProvider(); assertNotNull(injectionProvider); try { injectionProvider.inject(protectedBean); injectionProvider.invokePostConstruct(protectedBean); injectionProvider.invokePreDestroy(protectedBean); injectionProvider.inject(packagePrivateBean); injectionProvider.invokePostConstruct(packagePrivateBean); injectionProvider.invokePreDestroy(packagePrivateBean); injectionProvider.inject(privateBean); injectionProvider.invokePostConstruct(privateBean); injectionProvider.invokePreDestroy(privateBean); injectionProvider.inject(concreteBean); injectionProvider.invokePostConstruct(concreteBean); injectionProvider.invokePreDestroy(concreteBean); } catch (Exception e) { System.out.println(e); e.printStackTrace(); assertTrue(false); } assertTrue(protectedBean.getInit()); assertTrue(protectedBean.getDestroy()); assertTrue(packagePrivateBean.getInit()); assertTrue(packagePrivateBean.getDestroy()); assertTrue(privateBean.getInit()); assertTrue(privateBean.getDestroy()); assertTrue(concreteBean.getInit()); assertTrue(concreteBean.getDestroy()); } // ----------------------------------------------------------- Inner Classes private static class ProtectedBean { private boolean initCalled; private boolean destroyCalled; @PostConstruct void init() { initCalled = true; } @PreDestroy void destroy() { destroyCalled = true; } public boolean getInit() { return initCalled; } public boolean getDestroy() { return destroyCalled; } } // END ProtectedBean private static class PackagePrivateBean { private boolean initCalled; private boolean destroyCalled; @PostConstruct void init() { initCalled = true; } @PreDestroy void destroy() { destroyCalled = true; } public boolean getInit() { return initCalled; } public boolean getDestroy() { return destroyCalled; } } // END PackagePrivateBean private static class PrivateBean { private boolean initCalled; private boolean destroyCalled; @PostConstruct void init() { initCalled = true; } @PreDestroy void destroy() { destroyCalled = true; } public boolean getInit() { return initCalled; } public boolean getDestroy() { return destroyCalled; } } // END PrivateBean private static abstract class BaseBean { protected boolean initCalled; protected boolean destroyCalled; @PostConstruct void init() { initCalled = true; } } private static class ConcreteBean extends BaseBean { @PreDestroy void destroy() { destroyCalled = true; } public boolean getInit() { return initCalled; } public boolean getDestroy() { return destroyCalled; } } } // END TestInjectionmojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/ActionListenerTestImpl.java0000644000000000000000000000377611412443350025376 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; public class ActionListenerTestImpl extends ActionListenerImpl { } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/application/TestHAStateManagerImpl.java0000644000000000000000000001301011412443350025215 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.application; import org.apache.cactus.server.ServletConfigWrapper; import com.sun.faces.RIConstants; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import javax.faces.application.StateManager; import javax.faces.application.ViewHandler; import javax.faces.component.UIComponent; import javax.faces.component.UIGraphic; import javax.faces.component.UIInput; import javax.faces.component.UIOutput; import javax.faces.component.UIViewRoot; import javax.faces.component.UIForm; import javax.faces.component.UIPanel; import javax.faces.context.FacesContext; import javax.faces.render.RenderKitFactory; import javax.servlet.http.HttpSession; import javax.faces.application.StateManager.SerializedView; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import java.util.ArrayList; /** * This class tests the StateManagerImpl class * functionality. */ public class TestHAStateManagerImpl extends ServletFacesTestCase { public static final String TEST_URI = "/test.jsp"; // // Constructors/Initializers // public TestHAStateManagerImpl() { super("TestStateManagerImpl"); } public TestHAStateManagerImpl(String name) { super(name); } private Application application = null; public void setUp() { super.setUp(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = (ApplicationImpl) aFactory.getApplication(); application.setViewHandler(new ViewHandlerImpl()); application.setStateManager(new StateManagerImpl()); } // // Test Methods // public void testHighAvailabilityStateSaving1() { // precreate tree and set it in session and make sure the tree is // restored from session. UIViewRoot root = application.getViewHandler().createView(getFacesContext(), null); root.setViewId(TEST_URI); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName = new UIInput(); userName.setId("userName"); userName.setTransient(true); root.getChildren().add(basicForm); basicForm.getChildren().add(userName); UIPanel panel1 = new UIPanel(); panel1.setId("panel1"); basicForm.getChildren().add(panel1); UIInput userName1 = new UIInput(); userName1.setId("userName1"); panel1.getChildren().add(userName1); getFacesContext().setViewRoot(root); StateManager stateManager = getFacesContext().getApplication().getStateManager(); stateManager.saveSerializedView(getFacesContext()); // make sure that the value of viewId attribute in session is an // instance of SerializedView. Object result = session.getAttribute(TEST_URI); assertTrue(result instanceof SerializedView); root = stateManager.restoreView(getFacesContext(), TEST_URI, RenderKitFactory.HTML_BASIC_RENDER_KIT); assertTrue(root != null); basicForm = (UIForm) root.findComponent("basicForm"); assertTrue(basicForm != null); userName = (UIInput) basicForm.findComponent("userName"); assertTrue(userName == null); panel1 = (UIPanel) basicForm.findComponent("panel1"); assertTrue(panel1 != null); userName1 = (UIInput) panel1.findComponent("userName1"); assertTrue(userName1 != null); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/CustomerBean.java0000644000000000000000000000707211412443352021050 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces; /** *

JavaBean represented the data for an individual customer.

*/ public class CustomerBean implements java.io.Serializable { public CustomerBean() { this(null, null, null, 0.0); } public CustomerBean(String accountId, String name, String symbol, double totalSales) { System.out.println("Created CustomerBean"); this.accountId = accountId; this.name = name; this.symbol = symbol; this.totalSales = totalSales; } private String accountId = null; public String getAccountId() { return (this.accountId); } public void setAccountId(String accountId) { this.accountId = accountId; } private String name = null; public String getName() { return (this.name); } public void setName(String name) { this.name = name; } private String symbol = null; public String getSymbol() { return (this.symbol); } public void setSymbol(String symbol) { this.symbol = symbol; } private double totalSales = 0.0; public double getTotalSales() { return (this.totalSales); } public void setTotalSales(double totalSales) { this.totalSales = totalSales; } public String toString() { StringBuffer sb = new StringBuffer("CustomerBean[accountId="); sb.append(accountId); sb.append(",name="); sb.append(name); sb.append(",symbol="); sb.append(symbol); sb.append(",totalSales="); sb.append(totalSales); sb.append("]"); return (sb.toString()); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/TestResourceBundle_de.properties0000644000000000000000000000012611412443352024156 0ustar # Sample ResourceBundle properties file value1=Bernhard value2=Joerg value3=Beate Uhsemojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/0000755000000000000000000000000011412443352016565 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/TestUtil_local.java0000644000000000000000000000571711412443352022371 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestUtil_local.java package com.sun.faces.util; import junit.framework.TestCase; import java.util.Locale; /** * TestUtil_local.java is a class ... *

* Lifetime And Scope

* */ public class TestUtil_local extends TestCase { // // Protected Constants // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestUtil_local() { super("TestUtil_local.java"); } public TestUtil_local(String name) { super(name); } // // Class methods // // // General Methods // public void testGetLocaleFromString() { Locale result = null; // positive tests assertNotNull(result = Util.getLocaleFromString("ps")); assertNotNull(result = Util.getLocaleFromString("tg_AF")); assertNotNull(result = Util.getLocaleFromString("tk_IQ-Traditional")); assertNotNull(result = Util.getLocaleFromString("tk-IQ_Traditional")); } } // end of class TestUtil_local mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/TestUtil.java0000644000000000000000000004004711412443352021212 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestUtil.java package com.sun.faces.util; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.renderkit.Attribute; import com.sun.faces.renderkit.AttributeManager; import com.sun.faces.renderkit.RenderKitUtils; import javax.faces.FactoryFinder; import javax.faces.component.UIInput; import javax.faces.component.UISelectItems; import javax.faces.component.UISelectOne; import javax.faces.component.UISelectMany; import javax.faces.component.html.HtmlInputText; import javax.faces.context.ResponseWriter; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import javax.el.ValueExpression; import javax.el.ExpressionFactory; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeSet; import java.util.List; import java.util.Arrays; /** * Currently tests RenderKitUtils. */ public class TestUtil extends ServletFacesTestCase { // -------------------------------------------------------------- Test Setup public TestUtil() { super("TestUtil"); } public TestUtil(String name) { super(name); } // ------------------------------------------------------------ Test Methods public void testRenderPassthruAttributes() { try { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); StringWriter sw = new StringWriter(); ResponseWriter writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(writer); Attribute[] attrs = AttributeManager.getAttributes(AttributeManager.Key.INPUTTEXT); UIInput input = new UIInput(); input.setId("testRenderPassthruAttributes"); input.getAttributes().put("notPresent", "notPresent"); input.getAttributes().put("onblur", "javascript:f.blur()"); writer.startElement("input", input); RenderKitUtils.renderPassThruAttributes(getFacesContext(), writer, input, attrs); writer.endElement("input"); String expectedResult = " onblur=\"javascript:f.blur()\""; assertTrue(sw.toString().contains(expectedResult)); // verify no passthru attributes returns empty string sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(writer); input.getAttributes().remove("onblur"); writer.startElement("input", input); RenderKitUtils.renderPassThruAttributes(getFacesContext(),writer, input, attrs); writer.endElement("input"); assertTrue(sw.toString().equals("")); } catch (IOException e) { assertTrue(false); } } public void testRenderPassthruAttributesFromConcreteHtmlComponent() { try { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); StringWriter sw = new StringWriter(); ResponseWriter writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(writer); Attribute[] attrs = AttributeManager.getAttributes(AttributeManager.Key.INPUTTEXT); HtmlInputText input = new HtmlInputText(); input.setId("testRenderPassthruAttributes"); input.setSize(12); writer.startElement("input", input); RenderKitUtils.renderPassThruAttributes(getFacesContext(),writer, input, attrs); writer.endElement("input"); String expectedResult = " size=\"12\""; assertTrue(sw.toString().contains(expectedResult)); // test that setting the values to the default value causes // the attributes to not be rendered. sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); input.setSize(Integer.MIN_VALUE); writer.startElement("input", input); RenderKitUtils.renderPassThruAttributes(getFacesContext(),writer, input, attrs); writer.endElement("input"); expectedResult = ""; assertEquals(expectedResult, sw.toString()); sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); input.setReadonly(false); writer.startElement("input", input); RenderKitUtils.renderPassThruAttributes(getFacesContext(), writer, input, attrs); writer.endElement("input"); assertEquals(expectedResult, sw.toString()); } catch (IOException e) { assertTrue(false); } } public void testRenderBooleanPassthruAttributes() { try { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); StringWriter sw = new StringWriter(); ResponseWriter writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(writer); UIInput input = new UIInput(); input.setId("testBooleanRenderPassthruAttributes"); input.getAttributes().put("disabled", "true"); input.getAttributes().put("readonly", "false"); writer.startElement("input", input); RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer, input); writer.endElement("input"); String expectedResult = " disabled=\"disabled\""; assertTrue(sw.toString().contains(expectedResult)); // verify no passthru attributes returns empty string sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(writer); input.getAttributes().remove("disabled"); input.getAttributes().remove("readonly"); writer.startElement("input", input); RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer, input); writer.endElement("input"); assertTrue("".equals(sw.toString())); } catch (IOException e) { assertTrue(false); } } public void testGetSelectItems() { SelectItem item1 = new SelectItem("value", "label"); SelectItem item2 = new SelectItem("value2", "label2"); SelectItem[] itemsArray = { item1, item2 }; Collection itemsCollection = new ArrayList(2); itemsCollection.add(item1); itemsCollection.add(item2); Map selectItemMap = new LinkedHashMap(2); selectItemMap.put("label", "value"); selectItemMap.put("label2", "value2"); // test arrays UISelectItems items = new UISelectItems(); items.setValue(itemsArray); UISelectOne selectOne = new UISelectOne(); selectOne.getChildren().add(items); Iterator iterator = RenderKitUtils.getSelectItems(getFacesContext(), selectOne); assertTrue(item1.equals(iterator.next())); assertTrue(item2.equals(iterator.next())); items.setValue(itemsCollection); iterator = RenderKitUtils.getSelectItems(getFacesContext(), selectOne); assertTrue(item1.equals(iterator.next())); assertTrue(item2.equals(iterator.next())); items.setValue(selectItemMap); iterator = RenderKitUtils.getSelectItems(getFacesContext(), selectOne); SelectItem i = (SelectItem) iterator.next(); assertTrue(item1.getLabel().equals(i.getLabel()) && item1.getValue().equals(i.getValue())); i = (SelectItem) iterator.next(); assertTrue(item2.getLabel().equals(i.getLabel()) && item2.getValue().equals(i.getValue())); } public void testGetSelectItemsFromCollection() { UISelectMany many = new UISelectMany(); UISelectItems items = new UISelectItems(); FacesContext ctx = getFacesContext(); items.getAttributes().put("var", "item"); items.setValueExpression("itemValue", createValueExpression(ctx, "#{item.id}", Integer.TYPE)); items.setValueExpression("itemLabel", createValueExpression(ctx, "#{item.label}", String.class)); items.setValueExpression("itemDescription", createValueExpression(ctx, "#{item.description}", String.class)); items.setValueExpression("itemLabelEscaped", createValueExpression(ctx, "#{item.escaped}", Boolean.TYPE)); items.setValueExpression("itemDisabled", createValueExpression(ctx, "#{item.disabled}", Boolean.TYPE)); many.getChildren().add(items); Collection c = new TreeSet(); ModelObject[] models = { new ModelObject(1, "item1", "Item One", false, false), new ModelObject(2, "item2", "Item Two", true, false), new ModelObject(3, "item3", "Item Three", false, true) }; c.addAll(Arrays.asList(models)); items.setValue(c); Iterator selectItems = RenderKitUtils.getSelectItems(ctx, many); int idx = 0; while (selectItems.hasNext()) { compare(models[idx], selectItems.next()); idx++; } } // --------------------------------------------------------- Private Methods private void compare(ModelObject model, SelectItem item) { assertEquals(model.getId(), item.getValue()); assertEquals(model.getLabel(), item.getLabel()); assertEquals(model.getDescription(), item.getDescription()); assertEquals(model.isEscaped(), item.isEscape()); assertEquals(model.isDisabled(), item.isDisabled()); } private ValueExpression createValueExpression(FacesContext ctx, String expression, Class expectedType) { ExpressionFactory factory = ctx.getApplication().getExpressionFactory(); return (factory.createValueExpression(ctx.getELContext(), expression, expectedType)); } // ---------------------------------------------------------- Nested Classes public static class ModelObject implements Comparable { private int id; private String label; private String description; private boolean disabled; private boolean escaped; public ModelObject(int id, String label, String description, boolean disabled, boolean escaped) { this.id = id; this.label = label; this.description = description; this.disabled = disabled; this.escaped = escaped; } public int getId() { return id; } public String getLabel() { return label; } public String getDescription() { return description; } public boolean isDisabled() { return disabled; } public boolean isEscaped() { return escaped; } // --------------------------------------------- Methods from Comparable public int compareTo(Object o) { ModelObject provided = (ModelObject) o; if (this.id < provided.id) { return -1; } if (this.id == provided.id) { return 0; } return 1; } } } // end of class TestUtil mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/TreeStructure.java0000644000000000000000000001275711412443352022264 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import javax.faces.FacesException; import javax.faces.component.UIComponent; /** * TreeStructure is a class that represents the structure of a UIComponent * instance. This class plays a key role in saving and restoring the structure * of the component tree. */ public class TreeStructure implements java.io.Serializable { private static final long serialVersionUID = 8320767450484935667L; ArrayList children = null; HashMap facets = null; String className = null; String id = null; public TreeStructure() { } public TreeStructure(UIComponent component) { Util.notNull("component", component); this.id = component.getId(); className = component.getClass().getName(); } /** * Returns the className of the UIComponent that this TreeStructure * represents. */ public String getClazzName() { return className; } /** * Returns the iterator over className of the children that are attached to * the UIComponent that this TreeStructure represents. */ public Iterator getChildren() { if (children != null) { return (children.iterator()); } else { return (Collections.EMPTY_LIST.iterator()); } } /** * Returns the iterator over className of the facets that are attached to * the UIComponent that this TreeStructure represents. */ public Iterator getFacetNames() { if (facets != null) { return (facets.keySet().iterator()); } else { return (Collections.EMPTY_LIST.iterator()); } } /** * Adds treeStruct as a child of this TreeStructure instance. */ public void addChild(TreeStructure treeStruct) { Util.notNull("treeStruct", treeStruct); if (children == null) { children = new ArrayList(); } children.add(treeStruct); } /** * Adds treeStruct as a facet belonging to this TreeStructure instance. */ public void addFacet(String facetName, TreeStructure treeStruct) { Util.notNull("facetName", facetName); Util.notNull("treeStruct", treeStruct); if (facets == null) { facets = new HashMap(); } facets.put(facetName, treeStruct); } /** * Returns a TreeStructure representing a facetName by looking up * the facet list */ public TreeStructure getTreeStructureForFacet(String facetName) { Util.notNull("facetName", facetName); if (facets != null) { return ((facets.get(facetName))); } else { return null; } } /** * Creates and returns the UIComponent that this TreeStructure * represents using the structure information available. */ public UIComponent createComponent() { UIComponent component = null; // create the UIComponent based on the className stored. try { Class clazz = Util.loadClass(className, this); component = ((UIComponent) clazz.newInstance()); } catch (Exception e) { Object params[] = {className}; throw new FacesException(MessageUtils.getExceptionMessageString( MessageUtils.MISSING_CLASS_ERROR_MESSAGE_ID, params)); } assert (component != null); component.setId(id); return component; } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/TestLRUMap_local.java0000644000000000000000000000773511412443352022556 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.util; import java.util.Arrays; import java.util.List; import java.util.Collections; import junit.framework.TestCase; /** * Validate LRU functionality of LRUMap */ public class TestLRUMap_local extends TestCase { // ------------------------------------------------------------ Constructors public TestLRUMap_local() { super("TestLRUMap_local"); } public TestLRUMap_local(String name) { super(name); } // ------------------------------------------------------------ Test Methods /** * Ensure that LRUMap works as advertised. */ public void testLRUMap() { LRUMap map = new LRUMap(5); map.put("one", "one"); map.put("two", "two"); map.put("three", "three"); // order should be "three", "two", "one" String[] control = { "three", "two", "one" }; int count = 3; display(control.clone(), map); for (String s : map.keySet()) { assertEquals(control[--count], s); } map.put("four", "four"); map.put("five", "five"); map.put("three", "three"); map.put("six", "six"); control = new String[] { "six", "three", "five", "four", "two" }; count = 5; display(control.clone(), map); for (String s: map.keySet()) { assertEquals(control[--count], s); } } // --------------------------------------------------------- Private Methods private static void display(String[] expected, LRUMap actual) { System.out.println("Expected order:"); List revControl = Arrays.asList(expected); Collections.reverse(revControl); for (String s: revControl) { System.out.print(s + ' '); } System.out.println('\n'); System.out.println("Actual order:"); for (String s: actual.keySet()) { System.out.print(s + ' '); } System.out.println(); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/MultiThreadTestRunner.java0000644000000000000000000000776711412443352023725 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // MultiThreadTestRunner.java package com.sun.faces.util; import java.util.Random; import java.util.List; import java.util.ArrayList; import java.util.BitSet; import java.io.PrintStream; /** * MultiThreadTestRunner.java is a class ... *

* Lifetime And Scope

* */ public class MultiThreadTestRunner extends Object { // // Protected Constants // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables private Thread [] threads; private Object [] outcomes; // // Constructors and Initializers // public MultiThreadTestRunner(Thread [] yourThreads, Object [] yourOutcomes) { threads = yourThreads; outcomes = yourOutcomes; if (null == threads || null == outcomes) { throw new IllegalArgumentException(); } } /** * @return true iff one of the threads has failed. */ public boolean runThreadsAndOutputResults(PrintStream out) throws Exception { int i; if (outcomes.length != threads.length) { throw new IllegalArgumentException(); } for (i = 0; i < threads.length; i++) { outcomes[i] = null; } for (i = 0; i < threads.length; i++) { threads[i].start(); } BitSet printed = new BitSet(threads.length); boolean foundFailedThread = false; // wait for all threads to complete while (true) { boolean foundIncompleteThread = false; for (i = 0; i < threads.length; i++) { if (null == outcomes[i]) { foundIncompleteThread = true; break; } else { // print out the outcome for this thread if (!printed.get(i)) { printed.set(i); out.print(threads[i].getName() + " outcome: "); if (outcomes[i] instanceof Exception) { foundFailedThread = true; out.println("Exception: " + outcomes[i] + " " + ((Exception)outcomes[i]).getMessage()); } else { out.println(outcomes[i].toString()); } out.flush(); } } } if (!foundIncompleteThread) { break; } Thread.sleep(1000); } return foundFailedThread; } } // end of class MultiThreadTestRunner mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/TestUtil_messages.java0000644000000000000000000003315411412443352023102 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestUtil_messages.java package com.sun.faces.util; import javax.faces.component.UIViewRoot; import java.util.Locale; import com.sun.faces.cactus.ServletFacesTestCase; /** * TestUtil_messages.java is a class ... *

* Lifetime And Scope

* */ public class TestUtil_messages extends ServletFacesTestCase { // // Protected Constants // // Class Variables // // // Instance Variables // // README - Add message info to this array as {message key, "number of params"} // If message has no parameters entry should be {message key, "0"} public String[][] messageInfo = { {MessageUtils.CONVERSION_ERROR_MESSAGE_ID, "2"}, {MessageUtils.MODEL_UPDATE_ERROR_MESSAGE_ID, "2"}, {MessageUtils.FACES_CONTEXT_CONSTRUCTION_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_COMPONENT_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_REQUEST_VIEW_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_RESPONSE_VIEW_ERROR_MESSAGE_ID, "0"}, {MessageUtils.REQUEST_VIEW_ALREADY_SET_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_MESSAGE_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "1"}, {MessageUtils.NAMED_OBJECT_NOT_FOUND_ERROR_MESSAGE_ID, "1"}, {MessageUtils.NULL_RESPONSE_STREAM_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_RESPONSE_WRITER_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_EVENT_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_HANDLER_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_CONTEXT_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NULL_LOCALE_ERROR_MESSAGE_ID, "0"}, {MessageUtils.SUPPORTS_COMPONENT_ERROR_MESSAGE_ID, "1"}, {MessageUtils.MISSING_RESOURCE_ERROR_MESSAGE_ID, "0"}, {MessageUtils.MISSING_CLASS_ERROR_MESSAGE_ID, "1"}, {MessageUtils.COMPONENT_NOT_FOUND_ERROR_MESSAGE_ID, "1"}, {MessageUtils.LIFECYCLE_ID_ALREADY_ADDED_ID, "1"}, {MessageUtils.LIFECYCLE_ID_NOT_FOUND_ERROR_MESSAGE_ID, "1"}, {MessageUtils.PHASE_ID_OUT_OF_BOUNDS_ERROR_MESSAGE_ID, "1"}, {MessageUtils.CANT_CREATE_LIFECYCLE_ERROR_MESSAGE_ID, "1"}, {MessageUtils.ILLEGAL_MODEL_REFERENCE_ID, "1"}, {MessageUtils.ATTRIBUTE_NOT_SUPORTED_ERROR_MESSAGE_ID, "2"}, {MessageUtils.FILE_NOT_FOUND_ERROR_MESSAGE_ID, "1"}, {MessageUtils.CANT_PARSE_FILE_ERROR_MESSAGE_ID, "1"}, {MessageUtils.CANT_INSTANTIATE_CLASS_ERROR_MESSAGE_ID, "1"}, {MessageUtils.ILLEGAL_CHARACTERS_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NOT_NESTED_IN_FACES_TAG_ERROR_MESSAGE_ID, "1"}, {MessageUtils.NULL_BODY_CONTENT_ERROR_MESSAGE_ID, "1"}, {MessageUtils.SAVING_STATE_ERROR_MESSAGE_ID, "0"}, {MessageUtils.RENDERER_NOT_FOUND_ERROR_MESSAGE_ID, "1"}, {MessageUtils.MAXIMUM_EVENTS_REACHED_ERROR_MESSAGE_ID, "1"}, {MessageUtils.NULL_CONFIGURATION_ERROR_MESSAGE_ID, "0"}, {MessageUtils.ERROR_OPENING_FILE_ERROR_MESSAGE_ID, "1"}, {MessageUtils.ERROR_REGISTERING_DTD_ERROR_MESSAGE_ID, "1"}, {MessageUtils.INVALID_INIT_PARAM_ERROR_MESSAGE_ID, "0"}, {MessageUtils.ERROR_SETTING_BEAN_PROPERTY_ERROR_MESSAGE_ID, "1"}, {MessageUtils.ERROR_GETTING_VALUE_BINDING_ERROR_MESSAGE_ID, "1"}, {MessageUtils.ERROR_GETTING_VALUEREF_VALUE_ERROR_MESSAGE_ID, "1"}, {MessageUtils.CANT_INTROSPECT_CLASS_ERROR_MESSAGE_ID, "1"}, {MessageUtils.CANT_CONVERT_VALUE_ERROR_MESSAGE_ID, "2"}, {MessageUtils.INVALID_SCOPE_LIFESPAN_ERROR_MESSAGE_ID, "4"}, {MessageUtils.NAVIGATION_INVALID_QUERY_STRING_ID, "1"}, {MessageUtils.ENCODING_ERROR_MESSAGE_ID, "0"}, {MessageUtils.ILLEGAL_IDENTIFIER_LVALUE_MODE_ID, "1"}, {MessageUtils.VALIDATION_ID_ERROR_ID, "1"}, {MessageUtils.VALIDATION_EL_ERROR_ID, "1"}, {MessageUtils.VALIDATION_COMMAND_ERROR_ID, "1"}, {MessageUtils.CONTENT_TYPE_ERROR_MESSAGE_ID, "0"}, {MessageUtils.COMPONENT_NOT_FOUND_IN_VIEW_WARNING_ID, "1"}, {MessageUtils.ILLEGAL_ATTEMPT_SETTING_APPLICATION_ARTIFACT_ID, "1"}, {MessageUtils.INVALID_MESSAGE_SEVERITY_IN_CONFIG_ID, "1"}, {MessageUtils.CANT_CLOSE_INPUT_STREAM_ID, "0"}, {MessageUtils.DUPLICATE_COMPONENT_ID_ERROR_ID, "1"}, {MessageUtils.FACES_SERVLET_MAPPING_CANNOT_BE_DETERMINED_ID, "1"}, {MessageUtils.ILLEGAL_VIEW_ID_ID, "1"}, {MessageUtils.INVALID_EXPRESSION_ID, "1"}, {MessageUtils.NULL_FORVALUE_ID, "1"}, {MessageUtils.EMPTY_PARAMETER_ID, "0"}, {MessageUtils.ASSERTION_FAILED_ID, "0"}, {MessageUtils.OBJECT_CREATION_ERROR_ID, "0"}, {MessageUtils.CYCLIC_REFERENCE_ERROR_ID, "2"}, {MessageUtils.NO_DTD_FOUND_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_CANNOT_SET_LIST_ARRAY_PROPERTY_ID, "2"}, {MessageUtils.MANAGED_BEAN_EXISTING_VALUE_NOT_LIST_ID, "2"}, {MessageUtils.MANAGED_BEAN_TYPE_CONVERSION_ERROR_ID, "4"}, {MessageUtils.APPLICATION_ASSOCIATE_CTOR_WRONG_CALLSTACK_ID, "0"}, {MessageUtils.APPLICATION_ASSOCIATE_EXISTS_ID, "0"}, {MessageUtils.OBJECT_IS_READONLY, "1"}, {MessageUtils.INCORRECT_JSP_VERSION_ID, "1"}, {MessageUtils.EL_OUT_OF_BOUNDS_ERROR_ID, "1"}, {MessageUtils.EL_PROPERTY_TYPE_ERROR_ID, "1"}, {MessageUtils.EL_SIZE_OUT_OF_BOUNDS_ERROR_ID,"2"}, {MessageUtils.EVAL_ATTR_UNEXPECTED_TYPE, "3"}, {MessageUtils.RESTORE_VIEW_ERROR_MESSAGE_ID, "1"}, {MessageUtils.VALUE_NOT_SELECT_ITEM_ID, "2"}, {MessageUtils.CHILD_NOT_OF_EXPECTED_TYPE_ID, "4"}, {MessageUtils.COMMAND_LINK_NO_FORM_MESSAGE_ID, "0"}, {MessageUtils.FACES_CONTEXT_NOT_FOUND_ID, "0"}, {MessageUtils.NOT_NESTED_IN_TYPE_TAG_ERROR_MESSAGE_ID, "2"}, {MessageUtils.CANT_WRITE_ID_ATTRIBUTE_ERROR_MESSAGE_ID, "1"}, {MessageUtils.NOT_NESTED_IN_UICOMPONENT_TAG_ERROR_MESSAGE_ID, "0"}, {MessageUtils.NO_COMPONENT_ASSOCIATED_WITH_UICOMPONENT_TAG_MESSAGE_ID, "0"}, {MessageUtils.FACES_SERVLET_MAPPING_INCORRECT_ID, "0"}, {MessageUtils.JS_RESOURCE_WRITING_ERROR_ID, "0"}, {MessageUtils.CANNOT_CONVERT_ID, "2"}, {MessageUtils.CANNOT_VALIDATE_ID, "2"}, {MessageUtils.ERROR_PROCESSING_CONFIG_ID, "0"}, {MessageUtils.MANAGED_BEAN_CLASS_NOT_FOUND_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_CLASS_DEPENDENCY_NOT_FOUND_ERROR_ID, "3"}, {MessageUtils.MANAGED_BEAN_CLASS_IS_NOT_PUBLIC_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_CLASS_IS_ABSTRACT_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_CLASS_NO_PUBLIC_NOARG_CTOR_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_INJECTION_ERROR_ID, "1"}, {MessageUtils.MANAGED_BEAN_LIST_PROPERTY_CONFIG_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_AS_LIST_CONFIG_ERROR_ID, "1"}, {MessageUtils.MANAGED_BEAN_AS_MAP_CONFIG_ERROR_ID, "1"}, {MessageUtils.MANAGED_BEAN_MAP_PROPERTY_CONFIG_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_MAP_PROPERTY_INCORRECT_SETTER_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_MAP_PROPERTY_INCORRECT_GETTER_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_DEFINED_PROPERTY_CLASS_NOT_COMPATIBLE_ERROR_ID, "3"}, {MessageUtils.MANAGED_BEAN_INTROSPECTION_ERROR_ID, "1"}, {MessageUtils.MANAGED_BEAN_PROPERTY_DOES_NOT_EXIST_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_PROPERTY_HAS_NO_SETTER_ID, "2"}, {MessageUtils.MANAGED_BEAN_PROPERTY_INCORRECT_ARGS_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_LIST_SETTER_DOES_NOT_ACCEPT_LIST_OR_ARRAY_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_LIST_GETTER_DOES_NOT_RETURN_LIST_OR_ARRAY_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_LIST_GETTER_ARRAY_NO_SETTER_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_UNABLE_TO_SET_PROPERTY_ERROR_ID, "2"}, {MessageUtils.MANAGED_BEAN_PROBLEMS_ERROR_ID, "1"}, {MessageUtils.MANAGED_BEAN_PROBLEMS_STARTUP_ERROR_ID, "1"}, {MessageUtils.MANAGED_BEAN_UNKNOWN_PROCESSING_ERROR_ID, "1"}, {MessageUtils.MANAGED_BEAN_PROPERTY_UNKNOWN_PROCESSING_ERROR_ID, "1"}, {MessageUtils.VERIFIER_CLASS_MISSING_DEP_ID, "3"}, {MessageUtils.VERIFIER_CLASS_NOT_FOUND_ID, "2"}, {MessageUtils.VERIFIER_CTOR_NOT_PUBLIC_ID, "2"}, {MessageUtils.VERIFIER_NO_DEF_CTOR_ID, "2"}, {MessageUtils.VERIFIER_WRONG_TYPE_ID, "3"}, {MessageUtils.COMMAND_NOT_NESTED_WITHIN_FORM_ID, "0"}, {MessageUtils.NAVIGATION_NO_MATCHING_OUTCOME_ID, "2"}, {MessageUtils.NAVIGATION_NO_MATCHING_OUTCOME_ACTION_ID, "3"}, {MessageUtils.NO_RESOURCE_TARGET_AVAILABLE, "1"}, {MessageUtils.INVALID_RESOURCE_FORMAT_ERROR, "1"}, {MessageUtils.INVALID_RESOURCE_FORMAT_NO_LIBRARY_NAME_ERROR, "1"}, {MessageUtils.INVALID_RESOURCE_FORMAT_COLON_ERROR, "1"}, {MessageUtils.ARGUMENTS_NOT_LEGAL_CC_ATTRS_EXPR, "0"}, {MessageUtils.PARTIAL_STATE_ERROR_RESTORING_ID, "2"}, {MessageUtils.MISSING_COMPONENT_ATTRIBUTE_VALUE, "1"}, {MessageUtils.MISSING_COMPONENT_FACET, "1"}, {MessageUtils.MISSING_COMPONENT_METADATA, "1" } }; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestUtil_messages() { super("TestUtil_messages.java"); } public TestUtil_messages(String name) { super(name); } // // Methods from TestCase public void setUp() { super.setUp(); UIViewRoot viewRoot = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); viewRoot.setViewId("viewId"); viewRoot.setLocale(Locale.US); getFacesContext().setViewRoot(viewRoot); } // // Class methods // // // General Methods // public void testVerifyMessages() { Locale[] localesToTest = new Locale[] { new Locale("en", "US"), new Locale("fr", ""), new Locale("de", ""), new Locale("es", ""), new Locale("ja", ""), new Locale("ko", ""), new Locale("pt", "BR"), new Locale("zh", "CN"), new Locale("zh", "TW"), }; for (Locale locale : localesToTest) { System.out.println("Verifying messages for locale: " + locale.toString()); getFacesContext().getViewRoot().setLocale(locale); verifyParamsInMessages(messageInfo); } } private void verifyParamsInMessages(String[][] messageInfo) { int numParams = 0; for (int i = 0; i < messageInfo.length; i++) { System.out.println("Testing message: " + messageInfo[i][0]); try { numParams = Integer.parseInt(messageInfo[i][1]); } catch (NumberFormatException e) { System.out.println("Invalid param number specifier!"); assertTrue(false); } if (numParams == 0) { String message = MessageUtils.getExceptionMessageString(messageInfo[i][0]); assertTrue(messageInfo[i][0] + " was null", message != null); } else if (numParams > 0) { Object[] params = generateParams(numParams); String message = MessageUtils.getExceptionMessageString(messageInfo[i][0], params); assertTrue(message != null); for (int j = 0; j < params.length; j++) { assertTrue(messageInfo[i][0] + " unable to finder marker for param " + j,message.indexOf((String) params[j]) != -1); } } } } private Object[] generateParams(int numParams) { Object[] params = new String[numParams]; for (int i = 0; i < numParams; i++) { params[i] = "param_" + i; } return params; } } // end of class TestUtil_messages mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/TestMessageFactoryImpl.java0000644000000000000000000001406711412443352024036 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestMessageFactoryImpl.java package com.sun.faces.util; import com.sun.faces.cactus.ServletFacesTestCase; import javax.faces.FacesException; import javax.faces.application.FacesMessage; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import java.util.Locale; /** * TestMessageFactoryImpl is a class ... *

* Lifetime And Scope

* */ public class TestMessageFactoryImpl extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestMessageFactoryImpl() { super("TestMessageFactoryImpl"); } public TestMessageFactoryImpl(String name) { super(name); } // // Class methods // // // Methods from TestCase // public void setUp() { super.setUp(); UIViewRoot viewRoot = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); viewRoot.setViewId("viewId"); viewRoot.setLocale(Locale.US); getFacesContext().setViewRoot(viewRoot); } // // General Methods // public void testGetMethods() { boolean gotException = false; FacesMessage msg = null; FacesContext facesContext = getFacesContext(); assert (facesContext != null); System.out.println("Testing get methods"); try { msg = MessageFactory.getMessage((FacesContext) null, (String) null); } catch (NullPointerException fe) { gotException = true; } assertTrue(gotException); gotException = false; msg = null; // if msgId doesn't exist in the resource, null must be returned try { msg = MessageFactory.getMessage(facesContext, "MSG01", "param1"); assertTrue(null == msg); } catch (FacesException fe) { assertTrue(false); } Object[] params1 = {"JavaServerFaces"}; msg = MessageFactory.getMessage(facesContext, "MSG0001", params1); assertTrue(msg != null); assertTrue( (msg.getSummary()).equals( "'JavaServerFaces' is not a valid number.")); msg = MessageFactory.getMessage(facesContext, "MSG0003", "userId"); assertTrue(msg != null); assertTrue( (msg.getSummary()).equals("'userId' field cannot be empty.")); msg = MessageFactory.getMessage(facesContext, "MSG0004", "userId", "1000", "10000"); assertTrue(msg != null); assertTrue( (msg.getSummary()).equals( "'userId' out of range. Value should be between '1000' and '10000'.")); } public void testFindCatalog() { boolean gotException = false; FacesMessage msg = null; // if no locale is set, it should use the fall back, // JSFMessages.xml msg = MessageFactory.getMessage(getFacesContext(), "MSG0003", "userId"); assertTrue(msg != null); assertTrue( (msg.getSummary()).equals("'userId' field cannot be empty.")); // passing an invalid locale should use fall back. Locale en_locale = new Locale("eng", "us"); getFacesContext().getViewRoot().setLocale(en_locale); System.out.println("Testing get methods"); try { msg = MessageFactory.getMessage(getFacesContext(), "MSG0003", "userId"); } catch (Exception fe) { gotException = true; } assertTrue(!gotException); gotException = false; msg = null; en_locale = new Locale("en", "us"); getFacesContext().getViewRoot().setLocale(en_locale); msg = MessageFactory.getMessage(getFacesContext(), "MSG0003", "userId"); assertTrue(msg != null); assertTrue( (msg.getSummary()).equals("'userId' field cannot be empty.")); msg = null; } } // end of class TestMessageListImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/util/TestHtmlUtils.java0000644000000000000000000001572611412443352022230 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestHtmlUtils.java package com.sun.faces.util; import java.io.IOException; import java.io.StringWriter; import junit.framework.TestCase; /** * TestHtmlUtils is a class ... */ public class TestHtmlUtils extends TestCase { public void testWriteURL() throws IOException { //Test url with no params testURLEncoding("http://www.google.com", "http://www.google.com", "http://www.google.com"); //Test URL with one param testURLEncoding("http://www.google.com?joe=10", "http://www.google.com?joe=10", "http://www.google.com?joe=10"); //Test URL with two params testURLEncoding("http://www.google.com?joe=10&fred=20", "http://www.google.com?joe=10&fred=20", "http://www.google.com?joe=10&fred=20"); //Test URL with & entity encoded testURLEncoding("/index.jsf?joe=10&fred=20", "/index.jsf?joe=10&fred=20", "/index.jsf?joe=10&fred=20"); //Test URL with two params and second & close to end of string testURLEncoding("/index.jsf?joe=10&f=20", "/index.jsf?joe=10&f=20", "/index.jsf?joe=10&f=20"); //Test URL with misplaced & expected behavior but not necissarily right. testURLEncoding("/index.jsf?joe=10&f=20&", "/index.jsf?joe=10&f=20&", "/index.jsf?joe=10&f=20&"); //Test URL with encoded entity at end of URL expected behavior but not necissarily right. testURLEncoding("/index.jsf?joe=10&f=20&", "/index.jsf?joe=10&f=20&", "/index.jsf?joe=10&f=20&"); } public void testControlCharacters() throws IOException { final char[] controlCharacters = new char[32]; for (int i = 0; i < 32; i++) { controlCharacters[i] = (char) i; } String[] stringValues = new String[32]; for (int i = 0; i < 32; i++) { stringValues[i] = "b" + controlCharacters[i] + "b"; } final String[] largeStringValues = new String[32]; for (int i = 0; i < 32; i++) { largeStringValues[i] = (stringValues[i] + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); } for (int i = 0; i < 32; i++) { char[] textBuffer = new char[1024]; char[] buffer = new char[1024]; StringWriter writer = new StringWriter(); HtmlUtils.writeAttribute(writer, false, false, buffer, stringValues[i], textBuffer, false); if (i == 9 || i == 10 || i == 12 || i == 13) { assertTrue(writer.toString().length() == 3); } else { assertTrue(writer.toString().length() == 2); } } for (int i = 0; i < 32; i++) { char[] textBuffer = new char[1024]; char[] buffer = new char[1024]; StringWriter writer = new StringWriter(); HtmlUtils.writeAttribute(writer, false, false, buffer, largeStringValues[i], textBuffer, false); if (i == 9 || i == 10 || i == 12 || i == 13) { assertTrue(writer.toString().length() == 34); } else { assertTrue(writer.toString().length() == 33); } } for (int i = 0; i < 32; i++) { char[] textBuffer = new char[1024]; char[] buffer = new char[1024]; StringWriter writer = new StringWriter(); HtmlUtils.writeText(writer, false, false, buffer, stringValues[i], textBuffer); if (i == 9 || i == 10 || i == 12 || i == 13) { assertTrue(writer.toString().length() == 3); } else { assertTrue(writer.toString().length() == 2); } } for (int i = 0; i < 32; i++) { char[] textBuffer = new char[1024]; char[] buffer = new char[1024]; StringWriter writer = new StringWriter(); HtmlUtils.writeText(writer, false, false, buffer, largeStringValues[i], textBuffer); if (i == 9 || i == 10 || i == 12 || i == 13) { assertTrue(writer.toString().length() == 34); } else { assertTrue(writer.toString().length() == 33); } } } private void testURLEncoding(String urlToEncode, String expectedHTML, String expectedXML) throws IOException { char[] textBuffer = new char[1024]; StringWriter xmlWriter = new StringWriter(); HtmlUtils.writeURL(xmlWriter, urlToEncode, textBuffer, "UTF-8"); System.out.println("XML: " + xmlWriter.toString()); assertEquals(xmlWriter.toString(), expectedXML); StringWriter htmlWriter = new StringWriter(); HtmlUtils.writeURL(htmlWriter, urlToEncode, textBuffer, "UTF-8"); System.out.println("HTML: " + htmlWriter.toString()); assertEquals(htmlWriter.toString(), expectedHTML); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/io/0000755000000000000000000000000011412443352016217 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/io/TestIO.java0000644000000000000000000001453411412443352020240 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.io; import com.sun.faces.application.ViewHandlerResponseWrapper; import com.sun.faces.cactus.ServletFacesTestCase; import javax.servlet.ServletOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.StringWriter; public class TestIO extends ServletFacesTestCase { public TestIO() { super("TestIO"); } public TestIO(String name) { super(name); } // ------------------------------------------------------------ Test Methods public void testBase64Streams() throws Exception { // create a string over 2048 bytes in length String testString = "This is a test String"; for (int i = testString.length(); i < 6000; i++) { testString += 'a'; } StringWriter writer = new StringWriter(); Base64OutputStreamWriter sw = new Base64OutputStreamWriter(2048, writer); ObjectOutputStream os = new ObjectOutputStream(sw); os.writeObject(testString); os.flush(); os.close(); sw.finish(); String encodedString = writer.toString(); // no take the encodedString and reverse the operation Base64InputStream bin = new Base64InputStream(encodedString); ObjectInputStream input = new ObjectInputStream(bin); String result = (String) input.readObject(); input.close(); assertTrue(result != null); assertTrue(result.length() == testString.length()); assertTrue(testString.equals(result)); } public void testViewHandlerResponseWrapperStreamIO() throws Exception { ViewHandlerResponseWrapper w1 = new ViewHandlerResponseWrapper(getResponse()); ServletOutputStream os = w1.getOutputStream(); os.write('1'); try { w1.getWriter(); assertTrue(false); } catch (IllegalStateException ise) { // expected } os.flush(); os.close(); PrintWriter writer = null; try { writer = w1.getWriter(); } catch (IllegalStateException ise) { assertTrue(false); } // we've closed the stream - and should have a fake // writer. Ensure writing to it doesn't impact the result; writer.print("Some junk"); StringWriter buf = new StringWriter(); w1.flushToWriter(buf, "ISO-8859-1"); assertTrue(!buf.toString().contains("Some junk")); // ensure that the content that was written to the stream is // present assertTrue("1".equals(buf.toString())); w1 = new ViewHandlerResponseWrapper(getResponse()); os = w1.getOutputStream(); // flushBuffer should commit the response so getWriter() // should throw no Exception w1.flushBuffer(); try { w1.getWriter(); } catch (IllegalStateException ise) { assertTrue(false); } } public void testViewHandlerResponseWrapperCharIO() throws Exception { ViewHandlerResponseWrapper w1 = new ViewHandlerResponseWrapper(getResponse()); PrintWriter pw = w1.getWriter(); pw.write("some stuff"); try { w1.getOutputStream(); assertTrue(false); } catch (IllegalStateException ise) { // expected } pw.flush(); pw.close(); ServletOutputStream os = null; try { os = w1.getOutputStream(); } catch (IllegalStateException ise) { assertTrue(false); } // we've closed the stream - and should have a fake // writer. Ensure writing to it doesn't impact the result; os.write('1'); StringWriter buf = new StringWriter(); w1.flushToWriter(buf, "ISO-8859-1"); assertTrue(!buf.toString().contains("1")); // ensure that the content that was written to the stream is // present assertTrue("some stuff".equals(buf.toString())); w1 = new ViewHandlerResponseWrapper(getResponse()); pw = w1.getWriter(); // flushBuffer should commit the response so getWriter() // should throw no Exception w1.flushBuffer(); try { w1.getOutputStream(); } catch (IllegalStateException ise) { assertTrue(false); } } } // END TestIOmojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/0000755000000000000000000000000011412443346017552 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestRestoreViewFromPage.java0000644000000000000000000001574611412443346025171 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestRestoreViewFromPage.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.CompareFiles; import com.sun.faces.cactus.FileOutputResponseWriter; import com.sun.faces.cactus.ServletFacesTestCase; import org.apache.cactus.WebRequest; import javax.faces.render.RenderKitFactory; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * TestRestoreViewFromPage is a class ... *

* Lifetime And Scope

* */ public class TestRestoreViewFromPage extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // public static final String TEST_URI = "/greeting.jsp"; public static final String RESTORE_VIEW_OUTPUT_FILE = FileOutputResponseWriter.FACES_RESPONSE_ROOT + "RestoreView_output"; public static final String RESTORE_VIEW_CORRECT_FILE = FileOutputResponseWriter.FACES_RESPONSE_ROOT + "RestoreView_correct"; public static final String ignore[] = { "value=[Ljava.lang.Object;@14a18d" }; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestRestoreViewFromPage() { super("TestRestoreViewFromPage"); } public TestRestoreViewFromPage(String name) { super(name); } // // Class methods // // // General Methods // public void beginRestoreViewFromPage(WebRequest theRequest) { theRequest.setURL("localhost:8080", null, null, TEST_URI, null); theRequest.addParameter("javax.faces.ViewState", "rO0ABXNyACBjb20uc3VuLmZhY2VzLnV0aWwuVHJlZVN0cnVjdHVyZRRmG0QclWAgAgAETAAIY2hpbGRyZW50ABVMamF2YS91dGlsL0FycmF5TGlzdDtMAAljbGFzc05hbWV0ABJMamF2YS9sYW5nL1N0cmluZztMAAZmYWNldHN0ABNMamF2YS91dGlsL0hhc2hNYXA7TAACaWRxAH4AAnhwc3IAE2phdmEudXRpbC5BcnJheUxpc3R4gdIdmcdhnQMAAUkABHNpemV4cAAAAAF3BAAAAApzcQB+AABzcQB+AAUAAAACdwQAAAAKc3EAfgAAcHQAJmphdmF4LmZhY2VzLmNvbXBvbmVudC5iYXNlLlVJSW5wdXRCYXNlcHQABnVzZXJOb3NxAH4AAHB0AChqYXZheC5mYWNlcy5jb21wb25lbnQuYmFzZS5VSUNvbW1hbmRCYXNlcHQABnN1Ym1pdHh0ACVqYXZheC5mYWNlcy5jb21wb25lbnQuYmFzZS5VSUZvcm1CYXNlcHQACWhlbGxvRm9ybXh0AClqYXZheC5mYWNlcy5jb21wb25lbnQuYmFzZS5VSVZpZXdSb290QmFzZXB0AARyb290dXIAE1tMamF2YS5sYW5nLk9iamVjdDuQzlifEHMpbAIAAHhwAAAAAnVxAH4AEwAAAAJ0ABlERUZBVUxUW3NlcF0vZ3JlZXRpbmcuanNwdXEAfgATAAAABnEAfgAScHEAfgAXcHBwdXEAfgATAAAAAXVxAH4AEwAAAAJ1cQB+ABMAAAAGcQB+ABBwcQB+ABp0AARGb3JtcHNyABFqYXZhLnV0aWwuSGFzaE1hcAUH2sHDFmDRAwACRgAKbG9hZEZhY3RvckkACXRocmVzaG9sZHhwP0AAAAAAABB3CAAAABAAAAACdAAYY29tLnN1bi5mYWNlcy5Gb3JtTnVtYmVyc3IAEWphdmEubGFuZy5JbnRlZ2VyEuKgpPeBhzgCAAFJAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cAAAAAB0AARuYW1ldAAJaGVsbG9Gb3JteHVxAH4AEwAAAAJ1cQB+ABMAAAACdXEAfgATAAAAAnVxAH4AEwAAAAR0AA5mYWxzZVtzZXBddHJ1ZXBwcHVxAH4AEwAAAAJ1cQB+ABMAAAADcHQABk5VTUJFUnB1cQB+ABMAAAAGdAAQaGVsbG9Gb3JtX3VzZXJOb3BxAH4ALHQABFRleHRwcHVxAH4AEwAAAAB1cQB+ABMAAAACdXEAfgATAAAAAnVxAH4AEwAAAAJ0AA1udWxsW3NlcF1udWxsdXEAfgATAAAAB3BwcHBwdXIAK1tMamF2YXguZmFjZXMuYXBwbGljYXRpb24uU3RhdGVIb2xkZXJTYXZlcjus7jOyrNsurwIAAHhwAAAAAHB1cQB+ABMAAAACdXEAfgATAAAAA3B0AAZTdWJtaXRwdXEAfgATAAAABnQAEGhlbGxvRm9ybV9zdWJtaXRwcQB+ADp0AAZCdXR0b25wc3EAfgAcP0AAAAAAABB3CAAAABAAAAABdAAEdHlwZXQABnN1Ym1pdHh1cQB+ABMAAAAAc3IAEGphdmEudXRpbC5Mb2NhbGV++BFgnDD57AMABEkACGhhc2hjb2RlTAAHY291bnRyeXEAfgACTAAIbGFuZ3VhZ2VxAH4AAkwAB3ZhcmlhbnRxAH4AAnhw/////3QAAlVTdAACZW50AAB4"); } public void testRestoreViewFromPage() { Phase restoreView = new RestoreViewPhase(); try { restoreView.execute(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(false); } assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(null != getFacesContext().getViewRoot()); assertTrue(RenderKitFactory.HTML_BASIC_RENDER_KIT.equals( getFacesContext().getViewRoot().getRenderKitId())); assertTrue( getFacesContext().getViewRoot().getLocale().equals(Locale.US)); CompareFiles cf = new CompareFiles(); try { FileOutputStream os = new FileOutputStream( RESTORE_VIEW_OUTPUT_FILE); PrintStream ps = new PrintStream(os); com.sun.faces.util.DebugUtil.printTree( getFacesContext().getViewRoot(), ps); List ignoreList = new ArrayList(); for (int i = 0; i < ignore.length; i++) { ignoreList.add(ignore[i]); } boolean status = cf.filesIdentical(RESTORE_VIEW_OUTPUT_FILE, RESTORE_VIEW_CORRECT_FILE, ignoreList); assertTrue(status); // PENDING (visvan) test case to verify nothing is persisted if the root // is marked transient for both client tand server case. } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } // end of class TestRestoreViewFromPage mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestSaveStateInPage.java0000644000000000000000000002174011412443346024244 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestSaveStateInPage.java package com.sun.faces.lifecycle; import javax.faces.component.UIComponent; import javax.faces.component.UIComponentBase; import javax.faces.component.UIForm; import javax.faces.component.UIInput; import javax.faces.component.UIPanel; import javax.faces.component.UIViewRoot; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Locale; import org.apache.cactus.WebRequest; import com.sun.faces.application.StateManagerImpl; import com.sun.faces.application.ViewHandlerImpl; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.cactus.TestingUtil; import com.sun.faces.util.Util; /** * TestSaveStateInPage is a class ... *

* Lifetime And Scope

* */ public class TestSaveStateInPage extends JspFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/greeting.jsp"; public String getExpectedOutputFilename() { return "SaveState_correct"; } public static final String ignore[] = { "

" }; public String[] getLinesToIgnore() { return ignore; } public boolean sendResponseToFile() { return true; } // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestSaveStateInPage() { super("TestRenderResponsePhase"); } public TestSaveStateInPage(String name) { super(name); } // // Class methods // // // General Methods // public void beginSaveStateInPage(WebRequest theRequest) { theRequest.setURL("localhost:8080", null, null, TEST_URI, null); } public void testSaveStateInPage() { boolean result = false; UIComponentBase root = null; String value = null; Phase renderResponse = new RenderResponsePhase(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setId("root"); page.setLocale(Locale.US); page.setViewId(TEST_URI); getFacesContext().setViewRoot(page); renderResponse.execute(getFacesContext()); assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(verifyExpectedOutput()); } public void testSaveStateInClient() { // PENDING (visvan) add test case to make sure no state is saved when // root is marked transient. // precreate tree and set it in session and make sure the tree is // restored from session. //getFacesContext().setViewRoot(null); UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setLocale(Locale.US); root.setViewId(TEST_URI); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName = new UIInput(); userName.setId("userName"); userName.setTransient(true); root.getChildren().add(basicForm); basicForm.getChildren().add(userName); UIPanel panel1 = new UIPanel(); panel1.setId("panel1"); basicForm.getChildren().add(panel1); UIInput userName1 = new UIInput(); userName1.setId("userName1"); userName1.setTransient(true); panel1.getChildren().add(userName1); UIInput userName2 = new UIInput(); userName2.setId("userName2"); panel1.getChildren().add(userName2); UIInput userName3 = new UIInput(); userName3.setTransient(true); panel1.getFacets().put("userName3", userName3); UIInput userName4 = new UIInput(); panel1.getFacets().put("userName4", userName4); getFacesContext().setViewRoot(root); ViewHandlerImpl viewHandler = new ViewHandlerImpl(); StateManagerImpl stateManager = new StateManagerImpl(); // TreeStructure structRoot = // new TreeStructure(((UIComponent) getFacesContext().getViewRoot())); // stateManager.buildTreeStructureToSave(getFacesContext(), // ((UIComponent) root), // structRoot, null); // // // make sure restored tree structure is correct // UIViewRoot viewRoot = (UIViewRoot) structRoot.createComponent(); // assertTrue(null != viewRoot); // stateManager.restoreComponentTreeStructure(structRoot, // ((UIComponent) viewRoot)); List structureList = new ArrayList(); TestingUtil.invokePrivateMethod("captureChild", new Class[] {List.class, Integer.TYPE, UIComponent.class}, new Object[] { structureList, 0, root }, StateManagerImpl.class, stateManager); Object[] structArray = structureList.toArray(); UIViewRoot viewRoot = (UIViewRoot) TestingUtil.invokePrivateMethod("restoreTree", new Class[] { Object[].class }, new Object[] { structArray }, StateManagerImpl.class, stateManager); UIComponent component = (UIComponent) viewRoot.getChildren().get(0); assertTrue(component instanceof UIForm); assertTrue(component.getId().equals("basicForm")); UIForm uiform = (UIForm) component; component = (UIComponent) uiform.getChildren().get(0); assertTrue(component instanceof UIPanel); assertTrue(component.getId().equals("panel1")); UIPanel uipanel = (UIPanel) component; component = (UIComponent) uipanel.getChildren().get(0); assertTrue(component instanceof UIInput); assertTrue(component.getId().equals("userName2")); // make sure that the transient property is not persisted as well as the // namespace is preserved. basicForm = (UIForm) viewRoot.findComponent("basicForm"); assertTrue(basicForm != null); userName = (UIInput) basicForm.findComponent("userName"); assertTrue(userName == null); panel1 = (UIPanel) basicForm.findComponent("panel1"); assertTrue(panel1 != null); userName1 = (UIInput) panel1.findComponent("userName1"); assertTrue(userName1 == null); userName2 = (UIInput) panel1.findComponent("userName2"); assertTrue(userName2 != null); // make sure facets work correctly when marked transient. Map facetList = panel1.getFacets(); assertTrue(!(facetList.containsKey("userName3"))); assertTrue(facetList.containsKey("userName4")); } } // end of class TestRenderResponsePhase mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestLifecycleImpl.java0000644000000000000000000004260111412443346024001 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestLifecycleImpl.java package com.sun.faces.lifecycle; import javax.faces.component.UIForm; import javax.faces.component.UIInput; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.faces.context.ExceptionHandler; import javax.faces.context.ExceptionHandlerFactory; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; import javax.faces.webapp.PreJsf2ExceptionHandlerFactory; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.util.Util; import com.sun.faces.context.ExceptionHandlerImpl; import org.apache.cactus.WebRequest; import java.util.Locale; /** * TestLifecycleImpl is a class ... *

* Lifetime And Scope

* */ public class TestLifecycleImpl extends JspFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/TestLifecycleImpl.html"; // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables protected static LifecycleImpl sharedLifecycleImpl = null; protected static PhaseListenerImpl sharedListener = null; // // Constructors and Initializers // public TestLifecycleImpl() { super("TestLifecycleImpl"); } public TestLifecycleImpl(String name) { super(name); } // // Class methods // // // General Methods // protected LifecycleImpl getSharedLifecycleImpl() { if (null == sharedLifecycleImpl) { sharedLifecycleImpl = new LifecycleImpl(); } return sharedLifecycleImpl; } protected PhaseListenerImpl getSharedPhaseListenerImpl() { return sharedListener; } protected void initWebRequest(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); theRequest.addParameter("javax.faces.ViewState", "H4sIAAAAAAAAAFvzloG1hIElPjPFsAAAhLx/NgwAAAA="); } public void setUp() { super.setUp(); FacesContext context = getFacesContext(); UIViewRoot root = Util.getViewHandler(context).createView(context, null); root.setLocale(Locale.US); root.setViewId(TEST_URI); context.setViewRoot(root); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName = new UIInput(); userName.setId("userName"); root.getChildren().add(basicForm); basicForm.getChildren().add(userName); // here we do what the StateManager does to save the state in // the server. Util.getStateManager(context).saveSerializedView(context); } public void beginAnyPhaseWithListenerAndValidationFailure(WebRequest theRequest) { initWebRequest(theRequest); } public void testAnyPhaseWithListenerAndValidationFailure() { LifecycleImpl life = getSharedLifecycleImpl(); final int[] phaseCalled = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int i; for (i = 1; i < phaseCalled.length; i++) { phaseCalled[i] = 0; } sharedListener = new PhaseListenerImpl(phaseCalled, PhaseId.ANY_PHASE, PhaseId.PROCESS_VALIDATIONS); life.addPhaseListener(sharedListener); try { life.execute(getFacesContext()); life.render(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } for (i = 1; i < phaseCalled.length; i++) { // i is restore_view, apply_request, process_val, or render_resp if (((1 <= i) && (i <= 3)) || (i == 6)) { assertTrue( "Expected 2 for phase " + i + ", got " + phaseCalled[i] + ".", phaseCalled[i] == 2); } else { assertTrue("For phase: " + PhaseId.VALUES.get(i) + " expected no calls, got " + phaseCalled[i] + ".", phaseCalled[i] == 0); } } } public void beginAnyPhaseWithListener(WebRequest theRequest) { initWebRequest(theRequest); } public void testAnyPhaseWithListener() { LifecycleImpl life = getSharedLifecycleImpl(); final int[] phaseCalled = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int i; for (i = 1; i < phaseCalled.length; i++) { phaseCalled[i] = 0; } life.removePhaseListener(sharedListener); sharedListener = new PhaseListenerImpl(phaseCalled, PhaseId.ANY_PHASE, null); life.addPhaseListener(sharedListener); try { life.execute(getFacesContext()); life.render(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } for (i = 1; i < phaseCalled.length; i++) { assertTrue(phaseCalled[i] == 2); } } public void beginAnyPhaseWithoutListener(WebRequest theRequest) { initWebRequest(theRequest); } public void testAnyPhaseWithoutListener() { assertTrue(null != sharedListener); LifecycleImpl life = getSharedLifecycleImpl(); final int[] phaseCalled = sharedListener.getPhaseCalled(); int i; life.removePhaseListener(sharedListener); try { life.execute(getFacesContext()); life.render(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } // make sure the listener wasn't called for (i = 1; i < phaseCalled.length; i++) { assertTrue(phaseCalled[i] == 2); } } public void beginValidateWithListener(WebRequest theRequest) { initWebRequest(theRequest); } public void testValidateWithListener() { LifecycleImpl life = getSharedLifecycleImpl(); final int[] phaseCalled = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int i; for (i = 1; i < phaseCalled.length; i++) { phaseCalled[i] = 0; } sharedListener = new PhaseListenerImpl(phaseCalled, PhaseId.PROCESS_VALIDATIONS, null); life.addPhaseListener(sharedListener); try { life.execute(getFacesContext()); life.render(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } for (i = 1; i < phaseCalled.length; i++) { if (PhaseId.PROCESS_VALIDATIONS.getOrdinal() == i) { assertTrue(phaseCalled[i] == 2); } else { assertTrue(phaseCalled[i] == 0); } } } public void beginValidateWithoutListener(WebRequest theRequest) { initWebRequest(theRequest); } public void testValidateWithoutListener() { assertTrue(null != sharedListener); LifecycleImpl life = getSharedLifecycleImpl(); final int[] phaseCalled = sharedListener.getPhaseCalled(); int i; life.removePhaseListener(sharedListener); try { life.execute(getFacesContext()); life.render(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } // make sure the listener wasn't called for (i = 1; i < phaseCalled.length; i++) { if (PhaseId.PROCESS_VALIDATIONS.getOrdinal() == i) { assertTrue(phaseCalled[i] == 2); } else { assertTrue(phaseCalled[i] == 0); } } } public void beginBeforeListenerExceptionJsf12(WebRequest theRequest) { initWebRequest(theRequest); } public void testBeforeListenerExceptionJsf12() { ExceptionHandlerFactory f = new PreJsf2ExceptionHandlerFactory(); testBeforeListenerException(f.getExceptionHandler(), false); } public void beginBeforeListenerExceptionJsf20(WebRequest theRequest) { initWebRequest(theRequest); } public void testBeforeListenerExceptionJsf20() { testBeforeListenerException(new ExceptionHandlerImpl(), true); } public void testBeforeListenerException(ExceptionHandler handler, boolean expectException) { assertTrue(null != sharedListener); getFacesContext().setExceptionHandler(handler); LifecycleImpl life = getSharedLifecycleImpl(); int[] phaseCalledA = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int[] phaseCalledB = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int[] phaseCalledC = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int i; for (i = 1; i < phaseCalledA.length; i++) { phaseCalledA[i] = 0; phaseCalledB[i] = 0; phaseCalledC[i] = 0; } life.removePhaseListener(sharedListener); PhaseListenerImpl a = new PhaseListenerImpl(phaseCalledA, PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS), b = new PhaseListenerImpl(phaseCalledB, PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS), c = new PhaseListenerImpl(phaseCalledC, PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS); b.setThrowExceptionOnBefore(true); life.addPhaseListener(a); life.addPhaseListener(b); life.addPhaseListener(c); try { life.execute(getFacesContext()); life.render(getFacesContext()); if (expectException) { assertTrue(false); } } catch (Throwable e) { if (!expectException) { assertTrue(false); e.printStackTrace(); } } // verify before and after for "a" were called. assertEquals(2, phaseCalledA[PhaseId.APPLY_REQUEST_VALUES.getOrdinal()]); // verify before for "b" was called, but the after was not assertEquals(1, phaseCalledB[PhaseId.APPLY_REQUEST_VALUES.getOrdinal()]); // verify that neither before nor after for "c" were called assertEquals(0, phaseCalledC[PhaseId.APPLY_REQUEST_VALUES.getOrdinal()]); life.removePhaseListener(a); life.removePhaseListener(b); life.removePhaseListener(c); } public void beginAfterListenerExceptionJsf12(WebRequest theRequest) { initWebRequest(theRequest); } public void testAfterListenerExceptionJsf12() { ExceptionHandlerFactory f = new PreJsf2ExceptionHandlerFactory(); testAfterListenerException(f.getExceptionHandler(), false); } public void beginAfterListenerExceptionJsf20(WebRequest theRequest) { initWebRequest(theRequest); } public void testAfterListenerExceptionJsf20() { testAfterListenerException(new ExceptionHandlerImpl(), true); } public void testAfterListenerException(ExceptionHandler handler, boolean expectException) { assertTrue(null != sharedListener); getFacesContext().setExceptionHandler(handler); LifecycleImpl life = getSharedLifecycleImpl(); int[] phaseCalledA = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int[] phaseCalledB = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int[] phaseCalledC = new int[PhaseId.RENDER_RESPONSE.getOrdinal() + 1]; int i; for (i = 1; i < phaseCalledA.length; i++) { phaseCalledA[i] = 0; phaseCalledB[i] = 0; phaseCalledC[i] = 0; } life.removePhaseListener(sharedListener); PhaseListenerImpl a = new PhaseListenerImpl(phaseCalledA, PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS), b = new PhaseListenerImpl(phaseCalledB, PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS), c = new PhaseListenerImpl(phaseCalledC, PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS); b.setThrowExceptionOnAfter(true); life.addPhaseListener(a); life.addPhaseListener(b); life.addPhaseListener(c); try { life.execute(getFacesContext()); life.render(getFacesContext()); if (expectException) { assertTrue(false); } } catch (Throwable e) { if (!expectException) { assertTrue(false); e.printStackTrace(); } } // verify before and after for "a" were called. assertEquals(1, phaseCalledA[PhaseId.APPLY_REQUEST_VALUES.getOrdinal()]); // verify before for "b" was called, but the after was not assertEquals(2, phaseCalledB[PhaseId.APPLY_REQUEST_VALUES.getOrdinal()]); // verify that neither before nor after for "c" were called assertEquals(2, phaseCalledC[PhaseId.APPLY_REQUEST_VALUES.getOrdinal()]); life.removePhaseListener(a); life.removePhaseListener(b); life.removePhaseListener(c); } class PhaseListenerImpl implements PhaseListener { int[] phaseCalled = null; PhaseId phaseId = null; PhaseId callRenderResponseBeforeThisPhase = null; public int[] getPhaseCalled() { return phaseCalled; } boolean throwExceptionOnBefore = false; boolean throwExceptionOnAfter = false; public void setThrowExceptionOnBefore(boolean newValue) { throwExceptionOnBefore = newValue; } public void setThrowExceptionOnAfter(boolean newValue) { throwExceptionOnAfter = newValue; } public PhaseListenerImpl(int[] newPhaseCalled, PhaseId newPhaseId, PhaseId yourCallRenderResponseBeforeThisPhase) { phaseCalled = newPhaseCalled; phaseId = newPhaseId; callRenderResponseBeforeThisPhase = yourCallRenderResponseBeforeThisPhase; } public void afterPhase(PhaseEvent event) { phaseCalled[event.getPhaseId().getOrdinal()] = phaseCalled[event.getPhaseId().getOrdinal()] + 1; if (throwExceptionOnAfter) { throw new IllegalStateException("throwing exception on after " + event.getPhaseId().toString()); } } public void beforePhase(PhaseEvent event) { phaseCalled[event.getPhaseId().getOrdinal()] = phaseCalled[event.getPhaseId().getOrdinal()] + 1; if (callRenderResponseBeforeThisPhase == event.getPhaseId()) { FacesContext.getCurrentInstance().renderResponse(); } if (throwExceptionOnBefore) { throw new IllegalStateException("throwing exception on before " + event.getPhaseId().toString()); } } public PhaseId getPhaseId() { return phaseId; } } } // end of class TestLifecycleImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestProcessValidationsPhase.java0000644000000000000000000001341011412443346026051 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestProcessValidationsPhase.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.ServletFacesTestCase; import org.apache.cactus.WebRequest; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIForm; import javax.faces.component.UIViewRoot; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import javax.faces.validator.Validator; import java.util.Iterator; /** * TestProcessValidationsPhase is a class ... *

* Lifetime And Scope

* */ public class TestProcessValidationsPhase extends ServletFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/components.jsp"; public static final String DID_VALIDATE = "didValidate"; public static UIInput userName = null; // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestProcessValidationsPhase() { super("TestProcessValidationsPhase"); } public TestProcessValidationsPhase(String name) { super(name); } // // Class methods // // // General Methods // public void beginCallback(WebRequest theRequest) { theRequest.setURL("localhost:8080", null, null, TEST_URI, null); theRequest.addParameter( "basicForm" + NamingContainer.SEPARATOR_CHAR + "userName", "jerry"); theRequest.addParameter("basicForm", "basicForm"); } public void testCallback() { UIComponent root = null; userName = null; String value = null; Phase applyValues = new ApplyRequestValuesPhase(), processValidations = new ProcessValidationsPhase(); root = getFacesContext().getApplication().getViewHandler().createView(getFacesContext(), TEST_URI); getFacesContext().setViewRoot((UIViewRoot) root); getFacesContext().renderResponse(); assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(null != getFacesContext().getViewRoot()); root = getFacesContext().getViewRoot(); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName1 = new UIInput(); userName1.setId("userName"); root.getChildren().add(basicForm); basicForm.getChildren().add(userName1); // clear the property System.setProperty(DID_VALIDATE, EMPTY); try { userName = (UIInput) root.findComponent( "basicForm" + NamingContainer.SEPARATOR_CHAR + "userName"); } catch (Throwable e) { System.out.println(e.getMessage()); assertTrue("Can't find userName in tree", false); } // add the validator Validator validator = new Validator() { public Iterator getAttributeNames() { return null; } public void validate(FacesContext context, UIComponent component, Object value) { assertTrue(component == userName); System.setProperty(DID_VALIDATE, DID_VALIDATE); return; } }; userName.addValidator(validator); assertTrue(userName.isValid()); applyValues.execute(getFacesContext()); assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); processValidations.execute(getFacesContext()); assertTrue(!System.getProperty(DID_VALIDATE).equals(EMPTY)); assertTrue(userName.isValid()); assertTrue(null == userName.getSubmittedValue()); assertTrue("jerry".equals(userName.getValue())); System.setProperty(DID_VALIDATE, EMPTY); } } // end of class TestProcessValidationsPhase mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestLifecycleFactoryImpl.java0000644000000000000000000001122211412443346025324 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestLifecycleFactoryImpl.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.ServletFacesTestCase; import org.apache.cactus.ServletTestCase; import javax.faces.lifecycle.Lifecycle; import javax.faces.lifecycle.LifecycleFactory; import java.util.Iterator; /** * TestLifecycleFactoryImpl is a class ... *

* Lifetime And Scope

* */ public class TestLifecycleFactoryImpl extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestLifecycleFactoryImpl() { super("TestLifecycleFactoryImpl"); } public TestLifecycleFactoryImpl(String name) { super(name); } // // Class methods // // // General Methods // public void testDefault() { LifecycleFactoryImpl factory = new LifecycleFactoryImpl(); Lifecycle life = null, life2 = null; assertTrue(factory != null); // Make sure the default instance exists life = factory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE); assertTrue(null != life); // Make sure multiple requests for the same name give the same // instance. life2 = factory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE); assertTrue(life == life2); } public void testIdIterator() { LifecycleFactoryImpl factory = new LifecycleFactoryImpl(); String l1 = "l1", l2 = "l2", l3 = "l3"; LifecycleImpl life1 = new LifecycleImpl(), life2 = new LifecycleImpl(), life3 = new LifecycleImpl(); int i = 0; Iterator iter = null; factory.addLifecycle(l1, life1); factory.addLifecycle(l2, life2); factory.addLifecycle(l3, life3); iter = factory.getLifecycleIds(); while (iter.hasNext()) { iter.next(); i++; } assertTrue(4 == i); } public void testIllegalArgumentException() { LifecycleFactoryImpl factory = new LifecycleFactoryImpl(); Lifecycle life = null; assertTrue(factory != null); boolean exceptionThrown = false; // Try to get an IllegalArgumentException try { LifecycleImpl lifecycle = new LifecycleImpl(); factory.addLifecycle("bogusId", lifecycle); factory.addLifecycle("bogusId", lifecycle); } catch (IllegalArgumentException e) { exceptionThrown = true; } catch (UnsupportedOperationException e) { assertTrue(false); } assertTrue(exceptionThrown); } } // end of class TestLifecycleFactoryImpl mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestLifecycleImpl_initial.java0000644000000000000000000001050411412443346025507 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestLifecycleImpl_initial.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.JspFacesTestCase; import org.apache.cactus.WebRequest; import javax.faces.FacesException; import javax.faces.application.ViewHandler; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletRequest; /** * TestLifecycleImpl_initial is a class ... *

* Lifetime And Scope

* */ public class TestLifecycleImpl_initial extends JspFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/greeting.jsp"; public String getExpectedOutputFilename() { return "TestLifecycleImpl_initial_correct"; } public static final String ignore[] = { }; public String[] getLinesToIgnore() { return ignore; } public boolean sendResponseToFile() { return true; } // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestLifecycleImpl_initial() { super("TestLifecycleImpl_initial"); } public TestLifecycleImpl_initial(String name) { super(name); } // // Class methods // // // General Methods // protected void initWebRequest(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); } public void beginExecuteInitial(WebRequest theRequest) { initWebRequest(theRequest); } public void testExecuteInitial() { boolean result = false; LifecycleImpl life = new LifecycleImpl(); Object oldRequest = facesService.wrapRequestToHideParameters(); ViewHandler vh = getFacesContext().getApplication().getViewHandler(); getFacesContext().setViewRoot(vh.createView(getFacesContext(), "/greeting.jsp")); try { life.execute(getFacesContext()); facesService.unwrapRequestToShowParameters(oldRequest); life.render(getFacesContext()); } catch (FacesException e) { System.err.println("Root Cause: " + e.getCause()); if (null != e.getCause()) { e.getCause().printStackTrace(); } else { e.printStackTrace(); } assertTrue(e.getMessage(), false); } assertTrue(verifyExpectedOutput()); } } // end of class TestLifecycleImpl_initial mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestInvokeApplicationPhase.java0000644000000000000000000000701611412443346025661 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestInvokeApplicationPhase.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.component.UIInput; import javax.faces.component.UIViewRoot; import java.util.Locale; /** * TestInvokeApplicationPhase is a class ... *

* Lifetime And Scope

* */ public class TestInvokeApplicationPhase extends ServletFacesTestCase { // // Protected Constants // public static final String DID_COMMAND = "didCommand"; public static final String DID_FORM = "didForm"; // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestInvokeApplicationPhase() { super("TestInvokeApplicationPhase"); } public TestInvokeApplicationPhase(String name) { super(name); } // // Class methods // // // General Methods // public void testInvokeNormal() { } public void testInvokeNoOp() { UIInput root = new UIInput(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setViewId("default.xul"); page.setLocale(Locale.US); Phase invokeApplicationPhase = new InvokeApplicationPhase(); getFacesContext().setViewRoot(page); invokeApplicationPhase.execute(getFacesContext()); assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); } } // end of class TestInvokeApplicationPhase mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestProcessEvents.java0000644000000000000000000002643411412443346024071 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestProcessEvents.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.component.UICommand; import javax.faces.component.UIInput; import javax.faces.component.UIViewRoot; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import javax.faces.event.ValueChangeEvent; import javax.faces.event.ValueChangeListener; import java.util.HashMap; import java.util.Locale; /** * TestProcessEvents is a class ... *

* Lifetime And Scope

* */ public class TestProcessEvents extends ServletFacesTestCase { // // Protected Constants // public static final String HANDLED_VALUEEVENT1 = "handledValueEvent1"; public static final String HANDLED_VALUEEVENT2 = "handledValueEvent2"; public static final String HANDLED_ACTIONEVENT1 = "handledActionEvent1"; // // Class Variables // // // Instance Variables // // keeps track of total number of events processed // per event source component public HashMap eventsProcessed = null; public String limit = null; public int eventLimit = 100; // some default; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestProcessEvents() { super("TestProcessEvents"); } public TestProcessEvents(String name) { super(name); } // // Class methods // // // General Methods // public void setUp() { super.setUp(); UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setLocale(Locale.US); getFacesContext().setViewRoot(root); } public void tearDown() { super.tearDown(); } // tests one component - one value change listener public void testSingleValueChange() { // for keeping track of events processed limit.. // eventsProcessed = new HashMap(); UIInput userName = new UIInput(); getFacesContext().getViewRoot().getChildren().add(userName); // clear the property System.setProperty(HANDLED_VALUEEVENT1, EMPTY); // add valueChangeListener to the component ValueChange1 valueChange1 = new ValueChange1(); userName.addValueChangeListener(valueChange1); // add value change event (containing the component) to the queue userName.queueEvent(new ValueChangeEvent(userName, "foo", "bar")); getFacesContext().getViewRoot().processValidators(getFacesContext()); assertTrue(!System.getProperty(HANDLED_VALUEEVENT1).equals(EMPTY)); } // tests one component - multiple value change listeners public void testMultipleValueChange() { // for keeping track of events processed limit.. // eventsProcessed = new HashMap(); UIInput userName = new UIInput(); getFacesContext().getViewRoot().getChildren().add(userName); // clear the property System.setProperty(HANDLED_VALUEEVENT1, EMPTY); System.setProperty(HANDLED_VALUEEVENT2, EMPTY); // add valueChangeListener to the component ValueChange1 valueChange1 = new ValueChange1(); ValueChange2 valueChange2 = new ValueChange2(); userName.addValueChangeListener(valueChange1); userName.addValueChangeListener(valueChange2); // add value change event (containing the component) to the queue userName.queueEvent(new ValueChangeEvent(userName, "foo", "bar")); getFacesContext().getViewRoot().processValidators(getFacesContext()); assertTrue(!System.getProperty(HANDLED_VALUEEVENT1).equals(EMPTY)); assertTrue(!System.getProperty(HANDLED_VALUEEVENT2).equals(EMPTY)); } /** * ******************** * PENDING() perhaps reactivate this if the EG wants event loop detection. *

*

* // tests event recursion - infinite loop * // ValueChangeEvent will fire back the same event it received.. *

* public void testValueChangeRecursion() * { * // for keeping track of events processed limit.. * // * eventsProcessed = new HashMap(); *

* UIInput userName = new UIInput(); *

* // add valueChangeListener to the component *

* ValueChangeRecursion valueChange = new ValueChangeRecursion(); * userName.addValueChangeListener(valueChange); *

* // add value change event (containing the component) to the queue *

* userName.queueEvent(new ValueChangeEvent( * userName, "foo", "bar")); *

* PhaseId phaseId = PhaseId.PROCESS_VALIDATIONS; * boolean exceptionthrown = false; * try { * processEvents(getFacesContext(), phaseId); * } catch (Throwable e) { * System.out.println(e.getMessage()); * exceptionthrown = true; * } *

* assertTrue(exceptionthrown); * } * ************************ */ // tests one component - one action listener public void beginSignleAction(WebRequest theRequest) { theRequest.addParameter("button1", "button1"); } public void testSingleAction() { // for keeping track of events processed limit.. // eventsProcessed = new HashMap(); UICommand button = new UICommand(); button.setId("button1"); getFacesContext().getViewRoot().getChildren().add(button); // clear the property System.setProperty(HANDLED_ACTIONEVENT1, EMPTY); // add actionListener to the component Action1 action1 = new Action1(); button.addActionListener(action1); button.setImmediate(true); // add action event (containing the component) to the queue button.queueEvent(new ActionEvent(button)); getFacesContext().getViewRoot().processDecodes(getFacesContext()); assertTrue(!System.getProperty(HANDLED_ACTIONEVENT1).equals(EMPTY)); } /** * *********************** * PENDING() perhaps reactivate this if the EG wants event loop detection. *

* // tests event recursion - infinite loop * // ActionEvent will fire back the same event it received.. *

* public void testActionRecursion() * { * // for keeping track of events processed limit.. * // * eventsProcessed = new HashMap(); *

* UICommandSub button = new UICommandSub(); * // make sure we have no listeners. * List[] listeners = button.getListeners(); * for (int i = 0, len = listeners.length; i < len; i++) { * if (null != listeners[i]) { * listeners[i].clear(); * } * } *

* // add actionListener to the component * ActionRecursion action = new ActionRecursion(); * button.addActionListener(action); *

* // add action event (containing the component) to the queue *

* button.queueEvent(new ActionEvent(button)); *

* PhaseId phaseId = PhaseId.APPLY_REQUEST_VALUES; * boolean exceptionthrown = false; * try { * processEvents(getFacesContext(), phaseId); * } catch (Throwable t) { * System.out.println("Action Exception:"+t.getMessage()); * exceptionthrown = true; * } *

* assertTrue(exceptionthrown); * } *

* private boolean limitReached(UIComponent source, HashMap eventsProcessed) { * if (!eventsProcessed.containsKey(source)) { * eventsProcessed.put(source, new Integer(1)); * return false; * } *

* int count = ((Integer)eventsProcessed.get(source)).intValue()+1; * if (limit != null) { * eventLimit = new Integer(limit).intValue(); * } * if (count > eventLimit) { * return true; * } *

* eventsProcessed.put(source, new Integer(count)); * return false; * } * ******************** */ public class ValueChange1 implements ValueChangeListener { public void processValueChange(ValueChangeEvent event) { System.setProperty(HANDLED_VALUEEVENT1, HANDLED_VALUEEVENT1); } } public class ValueChange2 implements ValueChangeListener { public void processValueChange(ValueChangeEvent event) { System.setProperty(HANDLED_VALUEEVENT2, HANDLED_VALUEEVENT2); } } /** * *********** * PENDING() perhaps reactivate this if the EG wants event loop detection. *

* // event recursion case - fires same event it received.. *

* public class ValueChangeRecursion implements ValueChangeListener { * public void processValueChange(ValueChangeEvent event) { * getFacesContext().addFacesEvent(new ValueChangeEvent( * event.getComponent(), "foo", "bar")); * } * } * ************* */ public class Action1 implements ActionListener { public void processAction(ActionEvent event) { System.setProperty(HANDLED_ACTIONEVENT1, HANDLED_ACTIONEVENT1); } } /************** * PENDING() perhaps reactivate this if the EG wants event loop detection. // event recursion case - fires same event it received.. public class ActionRecursion implements ActionListener { public void processAction(ActionEvent event) { getFacesContext().addFacesEvent(new ActionEvent( event.getComponent())); } } *****************/ } // end of class TestProcessEvents mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestRenderResponsePhase.java0000644000000000000000000001500711412443346025177 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestRenderResponsePhase.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.FileOutputResponseWrapper; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.FacesException; import javax.faces.application.Application; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.PreRenderViewEvent; import javax.faces.event.SystemEvent; import javax.faces.event.SystemEventListener; import java.io.File; import java.util.Locale; /** * TestRenderResponsePhase is a class ... *

* Lifetime And Scope

* */ public class TestRenderResponsePhase extends JspFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/TestRenderResponsePhase.jsp"; public String getExpectedOutputFilename() { return "RenderResponse_correct"; } public static final String ignore[] = { }; public String[] getLinesToIgnore() { return ignore; } public boolean sendResponseToFile() { return true; } // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestRenderResponsePhase() { super("TestRenderResponsePhase"); } public TestRenderResponsePhase(String name) { super(name); } // // Class methods // // // General Methods // public void beginHtmlBasicRenderKit(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); } public void testHtmlBasicRenderKit() { Phase renderResponse = new RenderResponsePhase(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setId("root"); page.setViewId(TEST_URI); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); try { renderResponse.execute(getFacesContext()); } catch (FacesException fe) { System.out.println(fe.getMessage()); if (null != fe.getCause()) { fe.getCause().printStackTrace(); } else { fe.printStackTrace(); } } assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(verifyExpectedOutput()); } public void beginShortCircuitRenderResponse(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/faces", TEST_URI, null); } public void testShortCircuitRenderResponse() { SystemEventListener listener = new TestListener(getFacesContext()); Application application = getFacesContext().getApplication(); application.subscribeToEvent(PreRenderViewEvent.class, listener); Phase renderResponse = new RenderResponsePhase(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setId("root"); page.setViewId(TEST_URI); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); try { renderResponse.execute(getFacesContext()); } catch (FacesException fe) { System.out.println(fe.getMessage()); if (null != fe.getCause()) { fe.getCause().printStackTrace(); } else { fe.printStackTrace(); } } assertTrue(getFacesContext().getResponseComplete()); File renderedOutputFile = new File(FileOutputResponseWrapper.FACES_RESPONSE_FILENAME); assertTrue(renderedOutputFile.length() == 0); } private static final class TestListener implements SystemEventListener { private FacesContext context = null; private Class sourceFor; private Object passedSource; private boolean forSourceInvoked; public TestListener(FacesContext context) { this.context = context; } public void processEvent(SystemEvent event) throws AbortProcessingException { context.responseComplete(); } public boolean isListenerForSource(Object source) { forSourceInvoked = true; passedSource = source; if (sourceFor == null) { return (source != null); } else { return sourceFor.isInstance(source); } } } } // end of class TestRenderResponsePhase mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestPhase.java0000644000000000000000000001131711412443346022320 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestPhase.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIForm; import javax.faces.component.UIInput; import javax.faces.component.UIViewRoot; import java.util.Locale; /** * TestPhase is a class ... *

* Lifetime And Scope

* */ public class TestPhase extends ServletFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/components.jsp"; // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestPhase() { super("TestPhase"); } public TestPhase(String name) { super(name); } // // Class methods // // // General Methods // public void beginExecute(WebRequest theRequest) { theRequest.setURL("localhost:8080", null, null, TEST_URI, null); theRequest.addParameter( "basicForm" + NamingContainer.SEPARATOR_CHAR + "userName", "jerry"); } public void testExecute() { Phase restoreView = new RestoreViewPhase(); Object oldRequest = facesService.wrapRequestToHideParameters(); try { restoreView.execute(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(false); } facesService.unwrapRequestToShowParameters(oldRequest); assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(null != getFacesContext().getViewRoot()); // 2. Add components to tree // UIComponent root = getFacesContext().getViewRoot(); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName = new UIInput(); userName.setId("userName"); root.getChildren().add(basicForm); basicForm.getChildren().add(userName); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.getChildren().add(basicForm); page.setViewId("root"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); Phase applyValues = new ApplyRequestValuesPhase(); try { applyValues.execute(getFacesContext()); } catch (Throwable e) { System.out.println("Throwable: " + e.getMessage()); e.printStackTrace(); assertTrue(false); } assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); } } // end of class TestPhase mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestApplyRequestValuesPhase.java0000644000000000000000000002111711412443346026056 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestApplyRequestValuesPhase.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.ServletFacesTestCase; import org.apache.cactus.WebRequest; import javax.faces.component.NamingContainer; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.UIForm; import javax.faces.component.UIInput; import javax.faces.component.UICommand; /** * TestApplyRequestValuesPhase is a class ... *

* Lifetime And Scope

* */ public class TestApplyRequestValuesPhase extends ServletFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/components.jsp"; // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestApplyRequestValuesPhase() { super("TestApplyRequestValuesPhase"); } public TestApplyRequestValuesPhase(String name) { super(name); } // // Class methods // // // General Methods // public void beginCallback(WebRequest theRequest) { theRequest.setURL("localhost:8080", null, null, TEST_URI, null); theRequest.addParameter( "basicForm" + NamingContainer.SEPARATOR_CHAR + "userName", "jerry"); theRequest.addParameter( "basicForm" + NamingContainer.SEPARATOR_CHAR + "testCmd", "submit"); theRequest.addParameter( "basicForm" + NamingContainer.SEPARATOR_CHAR + "testInt", "10"); theRequest.addParameter("basicForm", "basicForm"); } public void testCallback() { UIComponent root = null; String value = null; Phase restoreView = new RestoreViewPhase(), applyValues = new ApplyRequestValuesPhase(); // 1. Set the root of the view ... // root = getFacesContext().getApplication().getViewHandler().createView(getFacesContext(), TEST_URI); getFacesContext().setViewRoot((UIViewRoot) root); getFacesContext().renderResponse(); assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(null != getFacesContext().getViewRoot()); // 2. Add components to tree // root = getFacesContext().getViewRoot(); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName = new UIInput(); userName.setId("userName"); root.getChildren().add(basicForm); basicForm.getChildren().add(userName); // 3. Apply values // applyValues.execute(getFacesContext()); assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); root = getFacesContext().getViewRoot(); try { userName = (UIInput) basicForm.findComponent("userName"); } catch (Throwable e) { System.out.println(e.getMessage()); assertTrue("Can't find userName in tree", false); } assertTrue(null != userName); assertTrue(null != (value = (String) userName.getSubmittedValue())); assertTrue(value.equals("jerry")); testImmediate(basicForm); } public void testImmediate(UIForm basicForm) { Phase restoreView = new RestoreViewPhase(), applyValues = new ApplyRequestValuesPhase(); // add a UICommand with "immediate" attribute set UICommand testCmd = new UICommand(); testCmd.setId("testCmd"); testCmd.setImmediate(true); basicForm.getChildren().add(testCmd); //verify immediate attribute works correctly. System.out.println("Testing 'immediate' attribute on UIInput and UICommand"); UIInput testInt = new UIInput(); testInt.setConverter(new javax.faces.convert.IntegerConverter()); testInt.setRequired(true); testInt.setId("testInt"); testInt.setImmediate(true); basicForm.getChildren().add(testInt); // 3. Apply values // Integer testNumber = new Integer(10); applyValues.execute(getFacesContext()); assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); UIComponent root = getFacesContext().getViewRoot(); try { testInt = (UIInput) basicForm.findComponent("testInt"); } catch (Throwable e) { System.out.println(e.getMessage()); assertTrue("Can't find testInt in tree", false); } //make sure the value is converted and validated after Apply request // values phase. assertTrue(null != testInt); assertTrue(null != testInt.getLocalValue()); assertTrue(testInt.isValid()); assertTrue(testNumber.equals((Integer) testInt.getValue())); testInt.setValue(null); // immediate "false" on command button but set on UIInput testCmd.setImmediate(false); applyValues.execute(getFacesContext()); assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); root = getFacesContext().getViewRoot(); try { testInt = (UIInput) basicForm.findComponent("testInt"); } catch (Throwable e) { System.out.println(e.getMessage()); assertTrue("Can't find testInt in tree", false); } //make sure the value is converted and validated after Apply request // values phase. assertTrue(null != testInt); assertTrue(null != testInt.getLocalValue()); assertTrue(testInt.isValid()); assertTrue(testNumber.equals((Integer) testInt.getValue())); testInt.setValue(null); // immediate "true" on command and not set on UIInput. testInt.setImmediate(false); testCmd.setImmediate(true); applyValues.execute(getFacesContext()); assertTrue((getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); root = getFacesContext().getViewRoot(); try { testInt = (UIInput) basicForm.findComponent("testInt"); } catch (Throwable e) { System.out.println(e.getMessage()); assertTrue("Can't find testInt in tree", false); } //make sure the value is converted and validated after Apply request // values phase. assertTrue(null != testInt); assertTrue(null == testInt.getValue()); assertTrue(testInt.isValid()); } } // end of class TestApplyRequestValuesPhase mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestUpdateModelValuesPhase.java0000644000000000000000000002621211412443346025624 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestUpdateModelValuesPhase.java package com.sun.faces.lifecycle; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.context.ExceptionHandlerImpl; import com.sun.faces.el.ELUtils; import com.sun.faces.util.Util; import javax.faces.component.UIForm; import javax.faces.component.UIInput; import javax.faces.component.UIViewRoot; import java.util.Locale; /** * TestUpdateModelValuesPhase is a class ... *

* Lifetime And Scope

* */ public class TestUpdateModelValuesPhase extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestUpdateModelValuesPhase() { super("TestUpdateModelValuesPhase"); } public TestUpdateModelValuesPhase(String name) { super(name); } // // Class methods // // // General Methods // public void testUpdateNormal() { //DebugUtil.waitForDebugger(); UIForm form = null; TestUIInput userName = null; TestUIInput userName1 = null; TestUIInput userName2 = null; com.sun.faces.cactus.TestBean testBean = (com.sun.faces.cactus.TestBean) (getFacesContext().getExternalContext().getSessionMap()).get( "TestBean"); String value = null; Phase updateModelValues = new UpdateModelValuesPhase(); form = new UIForm(); form.setId("form"); form.setSubmitted(true); userName = new TestUIInput(); userName.setId("userName"); userName.setValue("one"); userName.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.one}")); userName.testSetValid(true); form.getChildren().add(userName); userName1 = new TestUIInput(); userName1.setId("userName1"); userName1.setValue("one"); userName1.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.one}")); userName1.testSetValid(true); form.getChildren().add(userName1); userName2 = new TestUIInput(); userName2.setId("userName2"); userName2.setValue("one"); userName2.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.one}")); userName2.testSetValid(true); form.getChildren().add(userName2); UIViewRoot viewRoot = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); viewRoot.setLocale(Locale.US); viewRoot.getChildren().add(form); viewRoot.setViewId("updateModel.xul"); getFacesContext().setViewRoot(viewRoot); try { updateModelValues.execute(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(false); } assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); Object localvalue = userName.getLocalValue(); assertTrue(localvalue == null); assertTrue(testBean.getOne().equals("one")); assertTrue(!getFacesContext().getMessages().hasNext()); } public void testUpdateFailed() { UIForm form = null; TestUIInput userName = null; TestUIInput userName1 = null; TestUIInput userName2 = null; TestUIInput userName3 = null; String value = null; Phase updateModelValues = new UpdateModelValuesPhase(); form = new UIForm(); form.setId("form"); form.setSubmitted(true); userName = new TestUIInput(); userName.setId("userName"); userName.setValue("one"); userName.testSetValid(true); userName.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.two}")); form.getChildren().add(userName); userName1 = new TestUIInput(); userName1.setId("userName1"); userName1.setValue("one"); userName1.testSetValid(true); userName1.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.one}")); form.getChildren().add(userName1); userName2 = new TestUIInput(); userName2.setId("userName2"); userName2.setValue("one"); userName2.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.one}")); userName2.testSetValid(true); form.getChildren().add(userName2); userName3 = new TestUIInput(); userName3.setId("userName3"); userName3.setValue("four"); userName3.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.four}")); userName3.testSetValid(true); form.getChildren().add(userName3); UIViewRoot viewRoot = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); viewRoot.setLocale(Locale.US); viewRoot.getChildren().add(form); viewRoot.setViewId("updateModel.xul"); getFacesContext().setViewRoot(viewRoot); // This stage will go to render, since there was at least one error // during component updates... try { updateModelValues.execute(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(false); } getFacesContext().getExceptionHandler().handle(); assertTrue(getFacesContext().getRenderResponse()); assertTrue(true == (getFacesContext().getMessages().hasNext())); //assertions for our default update failed message assertTrue(true == (getFacesContext().getMessages("form:userName3").hasNext())); java.util.Iterator iter = getFacesContext().getMessages("form:userName3"); javax.faces.application.FacesMessage msg = null; javax.faces.application.FacesMessage expectedMsg = com.sun.faces.util.MessageFactory.getMessage(getFacesContext(), "javax.faces.component.UIInput.UPDATE", new Object[] {com.sun.faces.util.MessageFactory.getLabel(getFacesContext(), userName3)}); while (iter.hasNext()) { msg = (javax.faces.application.FacesMessage)iter.next(); } assertTrue(msg.getSummary().equals(expectedMsg.getSummary())); } public void testUpdateFailed2() { UIForm form = null; TestUIInput userName = null; TestUIInput userName1 = null; TestUIInput userName2 = null; TestUIInput userName3 = null; String value = null; Phase updateModelValues = new UpdateModelValuesPhase(); form = new UIForm(); form.setId("form"); form.setSubmitted(true); userName = new TestUIInput(); userName.setId("userName"); userName.setValue("one"); userName.testSetValid(true); userName.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.two}")); form.getChildren().add(userName); userName1 = new TestUIInput(); userName1.setId("userName1"); userName1.setValue("one"); userName1.testSetValid(true); userName1.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.one}")); form.getChildren().add(userName1); userName2 = new TestUIInput(); userName2.setId("userName2"); userName2.setValue("one"); userName2.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.one}")); userName2.testSetValid(true); form.getChildren().add(userName2); userName3 = new TestUIInput(); userName3.setId("userName3"); userName3.setValue("four"); userName3.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.four}")); userName3.testSetValid(true); form.getChildren().add(userName3); UIViewRoot viewRoot = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); viewRoot.setLocale(Locale.US); viewRoot.getChildren().add(form); viewRoot.setViewId("updateModel.xul"); getFacesContext().setViewRoot(viewRoot); getFacesContext().setExceptionHandler(new ExceptionHandlerImpl()); // This stage will go to render, since there was at least one error // during component updates... try { updateModelValues.execute(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(false); } boolean exceptionThrown = false; try { getFacesContext().getExceptionHandler().handle(); } catch (Throwable t) { exceptionThrown = true; } assertTrue(exceptionThrown); assertTrue(false == (getFacesContext().getMessages().hasNext())); } public static class TestUIInput extends UIInput { public void testSetValid(boolean validState) { this.setValid(validState); } } } // end of class TestUpdateModelValuesPhase mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/lifecycle/TestRestoreViewPhase.java0000644000000000000000000002672411412443346024527 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.lifecycle; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import com.sun.faces.renderkit.ServerSideStateHelper; import org.apache.cactus.WebRequest; import javax.faces.application.ViewExpiredException; import javax.faces.component.UICommand; import javax.faces.component.UIForm; import javax.faces.component.UIInput; import javax.faces.component.UIPanel; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.faces.render.RenderKitFactory; import javax.servlet.http.HttpSession; import java.util.Locale; /** * TestReconstituteComponentTreePhase is a class ... *

* Lifetime And Scope

* */ public class TestRestoreViewPhase extends ServletFacesTestCase { // // Protected Constants // public static final String TEST_URI = "/components.jsp"; // // Class Variables // // // Instance Variables // // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestRestoreViewPhase() { super("TestRestoreViewPhase"); } public TestRestoreViewPhase(String name) { super(name); } // // Class methods // // // General Methods // public void beginReconstituteRequestSubmit(WebRequest theRequest) { theRequest.setURL("localhost:8080", null, null, TEST_URI, null); theRequest.addParameter("javax.faces.ViewState", "j_id1:j_id2"); } public void beginRegisterListeners(WebRequest theRequest) { theRequest.setURL("localhost:8080", null, null, TEST_URI, null); theRequest.addParameter("javax.faces.ViewState", "j_id1:j_id2"); } public void testReconstituteRequestSubmit() { // precreate tree and set it in session and make sure the tree is // restored from session. FacesContext context = getFacesContext(); UIViewRoot root = Util.getViewHandler(context).createView(context, null); root.setViewId(TEST_URI); root.setLocale(Locale.US); context.setViewRoot(root); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName = new UIInput(); userName.setId("userName"); root.getChildren().add(basicForm); basicForm.getChildren().add(userName); Locale locale = new Locale("France", "french"); root.setLocale(locale); // here we do what the StateManager does to save the state in // the server. Util.getStateManager(context).saveView(context); //context.setViewRoot(null); Phase restoreView = new RestoreViewPhase(); try { restoreView.execute(getFacesContext()); } catch (Throwable e) { e.printStackTrace(); assertTrue(false); } assertTrue(!(getFacesContext().getRenderResponse()) && !(getFacesContext().getResponseComplete())); assertTrue(null != getFacesContext().getViewRoot()); assertTrue(RenderKitFactory.HTML_BASIC_RENDER_KIT.equals(getFacesContext() .getViewRoot().getRenderKitId())); assertTrue(locale == getFacesContext().getViewRoot().getLocale()); assertTrue( getFacesContext().getViewRoot().getViewId().equals(TEST_URI)); root = getFacesContext().getViewRoot(); // components should exist. assertTrue(root.getChildCount() == 1); assertTrue(basicForm.getId().equals(root.findComponent("basicForm").getId())); assertTrue(userName.getId().equals(basicForm.findComponent("userName").getId())); //getFacesContext().setViewRoot(null); } /** * This method will test the registerActionListeners method. * It will first create a simple tree consisting of a couple of UICommand * components added to a facet; Then the ReconstituteComponentTree.execute * method is run; And finally, an assertion is done to ensure that default action * listeners have been registered on the UICommand components; */ public void testRegisterListeners() { // precreate tree and set it in session and make sure the tree is // restored from session. FacesContext context = getFacesContext(); UIViewRoot root = Util.getViewHandler(context).createView(context, null); root.setLocale(Locale.US); root.setViewId(TEST_URI); context.setViewRoot(root); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); root.getChildren().add(basicForm); UIPanel panel = new UIPanel(); basicForm.getChildren().add(panel); UIPanel commandPanel = new UIPanel(); commandPanel.setId("commandPanel"); UICommand command1 = new UICommand(); UICommand command2 = new UICommand(); commandPanel.getChildren().add(command1); commandPanel.getChildren().add(command2); panel.getFacets().put("commandPanel", commandPanel); // here we do what the StateManager does to save the state in // the server. Util.getStateManager(context).saveView(context); //context.setViewRoot(null); Phase restoreView = new RestoreViewPhase(); try { restoreView.execute(context); } catch (Throwable e) { e.printStackTrace(); assertTrue(false); } assertTrue(!(context.getRenderResponse()) && !(context.getResponseComplete())); assertTrue(context.getViewRoot() != null); // Now test with no facets... Listeners should still be registered on UICommand // components.... // //context.setViewRoot(null); root = Util.getViewHandler(context).createView(context, null); root.setViewId(TEST_URI); root.setLocale(Locale.US); context.setViewRoot(root); basicForm = new UIForm(); basicForm.setId("basicForm"); root.getChildren().add(basicForm); command1 = new UICommand(); command2 = new UICommand(); basicForm.getChildren().add(command1); basicForm.getChildren().add(command2); // here we do what the StateManager does to save the state in // the server. context.getExternalContext().getSessionMap().remove(ServerSideStateHelper.STATEMANAGED_SERIAL_ID_KEY); Util.getStateManager(context).saveView(context); //context.setViewRoot(null); restoreView = new RestoreViewPhase(); try { restoreView.execute(context); } catch (Throwable e) { assertTrue(false); } assertTrue(!(context.getRenderResponse()) && !(context.getResponseComplete())); //context.setViewRoot(null); } public void beginRestoreViewExpired(WebRequest theRequest) { theRequest.setURL("localhost:8080", null, null, TEST_URI, null); theRequest.addParameter("javax.faces.ViewState", "j_id1:j_id2"); } public void testRestoreViewExpired() { // precreate tree and set it in session and make sure the tree is // restored from session. FacesContext context = getFacesContext(); UIViewRoot root = Util.getViewHandler(context).createView(context, null); root.setLocale(Locale.US); root.setViewId(TEST_URI); context.setViewRoot(root); UIForm basicForm = new UIForm(); basicForm.setId("basicForm"); UIInput userName = new UIInput(); userName.setId("userName"); root.getChildren().add(basicForm); basicForm.getChildren().add(userName); Locale locale = new Locale("France", "french"); root.setLocale(locale); // here we do what the StateManager does to save the state in // the server. Util.getStateManager(context).saveView(context); //context.setViewRoot(null); // invalidate the session before we attempt to restore ((HttpSession)context.getExternalContext().getSession(true)).invalidate(); Phase restoreView = new RestoreViewPhase(); boolean exceptionThrown = false; try { restoreView.execute(context); } catch (ViewExpiredException e) { exceptionThrown = true; assertTrue(e.getViewId().equals(TEST_URI)); String expected = "viewId:"+e.getViewId()+" - View "+e.getViewId()+" could not be restored."; assertTrue(e.getMessage().equals(expected)); } assertTrue(exceptionThrown); } } // end of class TestRestoreViewPhase mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/0000755000000000000000000000000011412443346017602 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/TestRenderKit.java0000644000000000000000000005077211412443346023207 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestRenderKit.java package com.sun.faces.renderkit; import com.sun.faces.cactus.FileOutputResponseWriter; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.renderkit.html_basic.FormRenderer; import com.sun.faces.renderkit.html_basic.TextRenderer; import com.sun.faces.renderkit.html_basic.HiddenRenderer; import com.sun.faces.config.WebConfiguration; import com.sun.faces.config.ConfigManager; import com.sun.faces.config.DbfFactory; import com.sun.faces.config.DocumentInfo; import com.sun.faces.config.processor.ConfigProcessor; import com.sun.faces.config.processor.FactoryConfigProcessor; import com.sun.faces.config.processor.ApplicationConfigProcessor; import com.sun.faces.config.processor.RenderKitConfigProcessor; import com.sun.faces.util.Util; import javax.faces.FactoryFinder; import javax.faces.context.ResponseStream; import javax.faces.context.ResponseWriter; import javax.faces.context.FacesContext; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import javax.faces.render.Renderer; import javax.faces.render.RenderKitWrapper; import javax.servlet.ServletResponse; import javax.servlet.ServletContext; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringWriter; import java.util.Iterator; import java.net.URL; import org.apache.cactus.WebRequest; import org.w3c.dom.Document; /** * TestRenderKit is a class ... *

* Lifetime And Scope

* */ public class TestRenderKit extends ServletFacesTestCase { // // Protected Constants // public static final String OUTPUT_FILENAME = FileOutputResponseWriter.FACES_RESPONSE_ROOT + "TestRenderKit_out"; public static final String CORRECT_OUTPUT_FILENAME = FileOutputResponseWriter.FACES_RESPONSE_ROOT + "TestRenderKit_correct"; // // Class Variables // // // Instance Variables // private RenderKit renderKit = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestRenderKit() { super("TestRenderKit"); } public TestRenderKit(String name) { super(name); } // // Class methods // // // General Methods // public void testGetRenderer() { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); // 1. Verify "getRenderer()" returns a Renderer instance // Renderer renderer = renderKit.getRenderer("javax.faces.Form", "javax.faces.Form"); assertTrue(renderer instanceof FormRenderer); // 2. Verify "getRenderer()" returns null // renderer = renderKit.getRenderer("Foo", "Bar"); assertTrue(renderer == null); // 3. Verify NPE // boolean exceptionThrown = false; try { renderer = renderKit.getRenderer(null, null); } catch (NullPointerException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testAddRenderer() { boolean bool = false; FormRenderer formRenderer = new FormRenderer(); TextRenderer textRenderer = new TextRenderer(); RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); // Test to see if addRenderer replaces the renderer if given // the same rendererType. // renderKit.addRenderer("Form", "Form", formRenderer); assertTrue( renderKit.getRenderer("Form", "Form") instanceof FormRenderer); renderKit.addRenderer("Form", "Form", textRenderer); assertTrue( renderKit.getRenderer("Form", "Form") instanceof TextRenderer); bool = false; try { renderKit.addRenderer("BlahFamily", null, formRenderer); } catch (NullPointerException e) { bool = true; } assertTrue(bool); bool = false; try { renderKit.addRenderer(null, "BlahRenderer", formRenderer); } catch (NullPointerException e) { bool = true; } assertTrue(bool); bool = false; try { renderKit.addRenderer("BlahFamily", "BlahRenderer", null); } catch (NullPointerException e) { bool = true; } assertTrue(bool); } public void testCreateResponseStream() throws Exception { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ByteArrayOutputStream out = new ByteArrayOutputStream(); ResponseStream stream = renderKit.createResponseStream(out); stream.write('a'); stream.write((byte) 'b'); stream.write(new byte[]{(byte) 'c', (byte) 'd', (byte) 'e'}, 1, 2); stream.flush(); String result = out.toString(); assertTrue(result.equals("abde")); try { stream.close(); } catch (IOException ioe) { ; // ignore } } public void testCreateResponseWriter() throws Exception { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); // use an invalid encoding try { renderKit.createResponseWriter(new StringWriter(), null, "foo"); fail("IllegalArgumentException Should Have Been Thrown!"); } catch (IllegalArgumentException iae) { } ResponseWriter writer = null; // see that the proper content type is picked up based on the // contentTypeList param writer = renderKit.createResponseWriter(new StringWriter(), "application/xhtml+xml,text/html", "ISO-8859-1"); assertEquals(writer.getContentType(), "application/xhtml+xml"); writer = renderKit.createResponseWriter(new StringWriter(), "text/html,application/xhtml+xml", "ISO-8859-1"); assertEquals(writer.getContentType(), "text/html"); // see that IAE is thrown if the content type isn't known try { writer = renderKit.createResponseWriter(new StringWriter(), "application/pdf", "ISO-8859-1"); fail("IllegalArgumentException Should Have Been Thrown!"); } catch (IllegalArgumentException iae) { } } public void beginCreateResponseWriterAllMedia(WebRequest theRequest) { theRequest.addHeader("Accept", "*/*"); } public void testCreateResponseWriterAllMedia() throws Exception { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ResponseWriter writer = null; // see that the proper content type is picked up based on the // accept header writer = renderKit.createResponseWriter(new StringWriter(), null, "ISO-8859-1"); assertEquals(writer.getContentType(), "text/html"); //Ensure we correctly support */* in content type ranges writer = renderKit.createResponseWriter(new StringWriter(), "application/xhtml+xml,*/*", "ISO-8859-1"); assertEquals(writer.getContentType(), "application/xhtml+xml"); writer = renderKit.createResponseWriter(new StringWriter(), "text/css,*/*", "ISO-8859-1"); assertEquals(writer.getContentType(), "text/html"); writer = renderKit.createResponseWriter(new StringWriter(), "*/*", "ISO-8859-1"); assertEquals(writer.getContentType(), "text/html"); } public void beginCreateResponseWriter1(WebRequest theRequest) { theRequest.addHeader("Accept", "text/html; q=0.2, application/xhtml+xml; q=0.8, application/xml; q=0.5, */*"); } public void testCreateResponseWriter1() throws Exception { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ResponseWriter writer = null; // see that the proper content type is picked up based on the // accept header writer = renderKit.createResponseWriter(new StringWriter(), null, "ISO-8859-1"); assertEquals(writer.getContentType(), "application/xhtml+xml"); } public void beginCreateResponseWriter2(WebRequest theRequest) { theRequest.addHeader("Accept", "text/html; q=0.2, application/xhtml+xml; q=0.8, application/xml; q=0.9, */*"); } public void testCreateResponseWriter2() throws Exception { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ResponseWriter writer = null; // see that the proper content type is picked up based on the // accept header writer = renderKit.createResponseWriter(new StringWriter(), null, "ISO-8859-1"); assertEquals(writer.getContentType(), "application/xhtml+xml"); } public void beginCreateResponseWriter3(WebRequest theRequest) { theRequest.addHeader("Accept", "text/html, application/xhtml+xml; q=0.8, application/xml; q=0.9, */*"); } public void testCreateResponseWriter3() throws Exception { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ResponseWriter writer = null; // see that the proper content type is picked up based on the // accept header writer = renderKit.createResponseWriter(new StringWriter(), null, "ISO-8859-1"); assertEquals(writer.getContentType(), "text/html"); } public void beginCreateResponseWriter4(WebRequest theRequest) { theRequest.addHeader("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*"); theRequest.addHeader("Accept", "text/html; level=1"); } public void testCreateResponseWriter4() throws Exception { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ResponseWriter writer = null; // see that the proper content type is picked up based on the // accept header writer = renderKit.createResponseWriter(new StringWriter(), null, "ISO-8859-1"); assertEquals(writer.getContentType(), "text/html"); } // Response has unsupported content type.. public void testCreateResponseWriter5() throws Exception { ((ServletResponse)getFacesContext().getExternalContext().getResponse()).setContentType("image/png"); RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ResponseWriter writer = null; // see that the proper content type is picked up based on the // accept header writer = renderKit.createResponseWriter(new StringWriter(), null, "ISO-8859-1"); assertEquals(writer.getContentType(), "text/html"); } // Added for issue 807 public void beginCreateResponseWriter6(WebRequest theRequest) { theRequest.addHeader("Accept", "text/"); } public void testCreateResponseWriter6() throws Exception { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ResponseWriter writer = null; // see that the proper content type is picked up based on the // accept header writer = renderKit .createResponseWriter(new StringWriter(), null, "ISO-8859-1"); assertEquals(writer.getContentType(), "text/html"); } public void testGetComponentFamilies() { RenderKitImpl rk = new RenderKitImpl(); Iterator empty = rk.getComponentFamilies(); assertNotNull(empty); assertTrue(!empty.hasNext()); rk.addRenderer("family", "rendererType", new HiddenRenderer()); Iterator notEmpty = rk.getComponentFamilies(); assertNotNull(notEmpty); assertTrue(notEmpty.hasNext()); } public void testGetRendererTypes() { RenderKitImpl rk = new RenderKitImpl(); rk.addRenderer("family", "rendererType", new HiddenRenderer()); Iterator empty = rk.getRendererTypes("non-exist"); assertNotNull(empty); assertTrue(!empty.hasNext()); Iterator notEmpty = rk.getRendererTypes("family"); assertNotNull(notEmpty); assertTrue(notEmpty.hasNext()); } // Added for issue 1106 public void beginCreateResponseWriter7(WebRequest theRequest) { theRequest.addHeader("Accept", "*/*"); } public void testCreateResponseWriter7() throws Exception { WebConfiguration webConfig = WebConfiguration.getInstance(); webConfig.overrideContextInitParameter(WebConfiguration.BooleanWebContextInitParameter.PreferXHTMLContentType, true); RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); ResponseWriter writer = null; // see that the proper content type is picked up based on the // accept header writer = renderKit.createResponseWriter(new StringWriter(), null, "ISO-8859-1"); assertEquals(writer.getContentType(), "application/xhtml+xml"); webConfig.overrideContextInitParameter(WebConfiguration.BooleanWebContextInitParameter.PreferXHTMLContentType, true); } public void testRenderKitDecoration() throws Exception { FacesContext ctx = getFacesContext(); ServletContext servletContext = (ServletContext) ctx.getExternalContext().getContext(); FactoryFinder.releaseFactories(); servletContext.removeAttribute("com.sun.faces.ApplicationAssociate"); ConfigManager config = ConfigManager.getInstance(); DocumentBuilderFactory factory = DbfFactory.getFactory(); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); ClassLoader loader = Util.getCurrentLoader(this); URL runtime = loader.getResource("com/sun/faces/jsf-ri-runtime.xml"); URL renderkit = servletContext.getResource("/WEB-INF/renderkit1.xml"); Document defaultDoc = builder.parse(loader.getResourceAsStream("com/sun/faces/jsf-ri-runtime.xml")); Document renderKitDoc = builder.parse(servletContext.getResourceAsStream("/WEB-INF/renderkit1.xml")); ConfigProcessor[] configProcessors = { new FactoryConfigProcessor(), new ApplicationConfigProcessor(), new RenderKitConfigProcessor(), }; for (int i = 0; i < configProcessors.length; i++) { ConfigProcessor p = configProcessors[i]; if ((i + 1) < configProcessors.length) { p.setNext(configProcessors[i + 1]); } } configProcessors[0].process(servletContext, new DocumentInfo[] { new DocumentInfo(defaultDoc, runtime), new DocumentInfo(renderKitDoc, renderkit) }); RenderKitFactory rkf = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit rk = rkf.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); assertEquals(rk.getClass().getName(), DecoratingRenderKit.class.getName()); assertEquals(RenderKitImpl.class.getName(), ((RenderKitWrapper) rk).getWrapped().getClass().getName()); } // ---------------------------------------------------------- Nested Classes public static class DecoratingRenderKit extends RenderKitWrapper { private RenderKit delegate; public DecoratingRenderKit(RenderKit delegate) { this.delegate = delegate; } public RenderKit getWrapped() { return delegate; } } } // end of class TestRenderKit mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/TestRenderKitUtils.java0000644000000000000000000000751511412443346024225 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.renderkit; import com.sun.faces.cactus.ServletFacesTestCase; import com.sun.faces.util.Util; import javax.faces.component.UICommand; import javax.faces.component.html.HtmlCommandLink; import javax.faces.context.ResponseWriter; import javax.faces.render.RenderKit; import java.io.StringWriter; import java.util.Collections; public class TestRenderKitUtils extends ServletFacesTestCase { // ------------------------------------------------------------ Constructors public TestRenderKitUtils() { super(); } public TestRenderKitUtils(String name) { super(name); } // ------------------------------------------------------------ Test Methods public void testOnClickBackslashEscaping() throws Exception { String input = "return confirm('foo\\');"; String expectedResult ="return confirm(\\'foo\\\\\\');"; HtmlCommandLink link = new HtmlCommandLink(); link.setOnclick(input); StringWriter capture = new StringWriter(); ResponseWriter current = getFacesContext().getResponseWriter(); if (current == null) { RenderKit renderKit = RenderKitUtils.getCurrentRenderKit(getFacesContext()); current = renderKit.createResponseWriter(capture, null, null); getFacesContext().setResponseWriter(current); } else { getFacesContext().setResponseWriter(current.cloneWithWriter(capture)); } getFacesContext().getResponseWriter().startElement("link", link); RenderKitUtils.renderOnclick(getFacesContext(), link, null, "form", true); getFacesContext().getResponseWriter().endElement("link"); String actualResult = capture.toString(); assertTrue(actualResult.contains(expectedResult)); } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/TestRenderKitFactory.java0000644000000000000000000001456711412443346024541 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestRenderKitFactory.java package com.sun.faces.renderkit; import com.sun.faces.cactus.ServletFacesTestCase; import javax.faces.FactoryFinder; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import java.util.Iterator; /** * TestRenderKitFactory is a class ... *

* Lifetime And Scope

* */ public class TestRenderKitFactory extends ServletFacesTestCase { // // Protected Constants // // // Class Variables // // // Instance Variables // private RenderKitFactoryImpl renderKitFactory = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestRenderKitFactory() { super("TestRenderKitFactory"); } public TestRenderKitFactory(String name) { super(name); } // // Class methods // // // General Methods // public void testFactory() { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); // 1. Verify "getRenderKit" returns the same RenderKit instance // if called multiple times with the same identifier. // RenderKit renderKit1 = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); RenderKit renderKit2 = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); assertTrue(renderKit1 == renderKit2); // 2. Verify "addRenderKit" adds instances.. / // renderKitFactory.addRenderKit("Foo", renderKit1); renderKitFactory.addRenderKit("Bar", renderKit2); // Verify renderkit instance replaced with last identifier.. // renderKitFactory.addRenderKit("BarBar", renderKit2); RenderKit rkit = renderKitFactory.getRenderKit(getFacesContext(), "BarBar"); assertTrue(rkit != null); assertTrue(rkit == renderKit2); // 3. Verify "getRenderKit" returns null if // RenderKit not found for renderkitid... // RenderKit renderKit4 = renderKitFactory.getRenderKit(getFacesContext(), "Gamma"); assertTrue(renderKit4 == null); } public void testDefaultExists() { RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); // 1. Verify "default" renderkit.. // RenderKit renderKit; String id = null; Iterator iter = renderKitFactory.getRenderKitIds(); boolean exists = false; while (iter.hasNext()) { id = (String) iter.next(); if (id.equals(RenderKitFactory.HTML_BASIC_RENDER_KIT)) { exists = true; break; } } assertTrue(exists); } public void testExceptions() { renderKitFactory = new RenderKitFactoryImpl(); RenderKit rKit = null; rKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); // Verify NPE for "addRenderKit" // boolean exceptionThrown = false; try { renderKitFactory.addRenderKit(null, rKit); exceptionThrown = false; } catch (NullPointerException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { renderKitFactory.addRenderKit("foo", null); exceptionThrown = false; } catch (NullPointerException e1) { exceptionThrown = true; } assertTrue(exceptionThrown); // Verify null parameter exception for "getRenderKit" // exceptionThrown = false; try { rKit = renderKitFactory.getRenderKit(null, null); } catch (NullPointerException e2) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { rKit = renderKitFactory.getRenderKit(getFacesContext(), null); } catch (NullPointerException e4) { exceptionThrown = true; } assertTrue(exceptionThrown); } } // end of class TestRenderKitFactory mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/html_basic/0000755000000000000000000000000011412443346021707 5ustar mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/html_basic/TestHtmlResponseWriter.java0000644000000000000000000005403611412443346027242 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestHtmlResponseWriter.java package com.sun.faces.renderkit.html_basic; import javax.faces.FactoryFinder; import javax.faces.component.UIInput; import javax.faces.component.UIOutput; import javax.faces.context.ResponseWriter; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import java.io.IOException; import java.io.StringWriter; import java.util.Arrays; import com.sun.faces.cactus.ServletFacesTestCase; /** * TestHtmlResponseWriter.java is a class ... *

* Lifetime And Scope

*/ public class TestHtmlResponseWriter extends ServletFacesTestCase // ServletTestCase { // // Protected Constants // // Class Variables // // // Instance Variables // private ResponseWriter writer = null; private RenderKit renderKit = null; private StringWriter sw = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestHtmlResponseWriter() { super("TestHtmlResponseWriter.java"); } public TestHtmlResponseWriter(String name) { super(name); } // // Class methods // // // General Methods // public void setUp() { super.setUp(); RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); renderKit = renderKitFactory.getRenderKit(getFacesContext(), RenderKitFactory.HTML_BASIC_RENDER_KIT); sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); } public void testContentType() { assertTrue(writer.getContentType().equals("text/html")); // Test Invalid Encoding try { writer = renderKit.createResponseWriter(sw, "foobar", "ISO-8859-1"); fail("IllegalArgumentException Should Have been Thrown!"); } catch (IllegalArgumentException e) { } } public void testEncoding() { assertTrue(writer.getCharacterEncoding().equals("ISO-8859-1")); // Test Invalid Encoding try { writer = renderKit.createResponseWriter(sw, "text/html", "foobar"); fail("IllegalArgumentException Should Have been Thrown!"); } catch (IllegalArgumentException e) { } } // Test "startElement method including the automatic closure of a // previous "start element" // public void testStartElement() { try { writer.startElement("input", new UIInput()); assertTrue(sw.toString().equals("")); writer.startElement("frame", new UIInput()); writer.endElement("frame"); assertTrue(sw.toString().equals("")); writer.endElement("frame"); assertTrue(sw.toString().equals("")); sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); writer.startElement("br", null); writer.endElement("br"); assertTrue(sw.toString().equals("
")); } catch (IOException e) { assertTrue(false); } } // Test "writeAttribute" method // public void testWriteAttribute() { try { UIInput in = new UIInput(); writer.startElement("input", in); writer.writeAttribute("type", "text", "type"); writer.writeAttribute("readonly", Boolean.TRUE, "readonly"); writer.writeAttribute("disabled", Boolean.FALSE, "disabled"); writer.writeAttribute("greaterthan", ">", "greaterthan"); writer.endElement("input"); assertTrue(sw.toString().equals("")); } catch (IOException e) { assertTrue(false); } } // // Test "writeURIAttribute" method // public void testWriteURIAttribute() { try { writer.startElement("input", new UIInput()); writer.writeAttribute("type", "image", "type"); writer.writeURIAttribute("src", "/mygif/foo.gif", "src"); writer.endElement("input"); assertTrue(sw.toString().equals("")); // // test URL encoding // sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); writer.startElement("foo", new UIInput()); writer.writeURIAttribute("player", "Bobby Orr", "player"); writer.endElement("input"); assertTrue(sw.toString().equals("")); // // test no URL encoding (javascript) // sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); writer.startElement("foo", new UIInput()); writer.writeURIAttribute("player", "javascript:Bobby Orr", null); writer.endElement("foo"); assertTrue( sw.toString().equals("")); } catch (IOException e) { assertTrue(false); } } public void testWriteCdata() { sw = new StringWriter(); try { writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); writer.startElement("cdata", new UIOutput()); // should be ignored writer.writeAttribute("id", "value", "id"); // should be ignored writer.writeURIAttribute("id", "value", "id"); // should be ignored writer.writeComment("comment"); // should be present in the StringWriter writer.writeText("Text between the cdata section", null); writer.endElement("cdata"); assertTrue( sw.toString().equals("")); } catch (IOException e) { assertTrue(false); } // cdata with script sw = new StringWriter(); try { writer = renderKit.createResponseWriter(sw, "application/xhtml+xml", "UTF-8"); writer.startElement("cdata", new UIOutput()); writer.startElement("script", new UIOutput()); writer.writeText("alert('hello');", null); writer.endElement("script"); writer.endElement("cdata"); assertTrue("alert('hello');]]>".equals(sw.toString())); } catch (IOException e) { assertTrue(false); } } public void testWriteComment() { try { writer.writeComment("This is a comment"); assertTrue(sw.toString().equals("")); } catch (IOException e) { assertTrue(false); } } public void testWriteScriptElement() throws Exception { StringWriter sw = new StringWriter(); StringWriter swx = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); ResponseWriter xmlWriter = renderKit.createResponseWriter(swx, "application/xhtml+xml", "UTF-8"); UIOutput output = new UIOutput(); writer.startElement("script", output); writer.writeURIAttribute("src", "http://foo.net/some.js", "src"); writer.writeAttribute("type", "text/javascript", "type"); writer.writeAttribute("language", "Javascript", "language"); writer.endElement("script"); String result = sw.toString(); System.out.println(result); assertTrue((!result.contains(""))); xmlWriter.startElement("script", output); xmlWriter.writeAttribute("src", "http://foo.net/some.js", "src"); xmlWriter.writeAttribute("type", "text/javascript", "type"); xmlWriter.writeAttribute("language", "Javascript", "language"); xmlWriter.endElement("script"); result = swx.toString(); System.out.println(result); assertTrue((!result.contains("<[CDATA[") && !result.contains("]]>"))); sw = new StringWriter(); swx = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); xmlWriter = renderKit.createResponseWriter(swx, "application/xhtml+xml", "UTF-8"); output = new UIOutput(); writer.startElement("script", output); writer.writeAttribute("type", "text/javascript", "type"); writer.writeAttribute("language", "Javascript", "language"); writer.writeText("", null); writer.endElement("script"); result = sw.toString(); String expected = ""; System.out.println("1:" + result); assertTrue(expected.equals(result)); xmlWriter.startElement("script", output); xmlWriter.writeAttribute("type", "text/javascript", "type"); xmlWriter.writeAttribute("language", "Javascript", "language"); xmlWriter.writeText("//", null); xmlWriter.endElement("script"); result = swx.toString(); expected = ""; System.out.println("2:" + result); assertTrue(expected.equals(result)); swx = new StringWriter(); xmlWriter = renderKit.createResponseWriter(swx, "application/xhtml+xml", "UTF-8"); xmlWriter.startElement("ajax", output); xmlWriter.startElement("cdata", output); xmlWriter.startElement("script", output); xmlWriter.writeAttribute("type", "text/javascript", "type"); xmlWriter.writeAttribute("language", "Javascript", "language"); xmlWriter.writeText("if (true && true) { alert('foo'); }", null); xmlWriter.endElement("script"); xmlWriter.endElement("cdata"); xmlWriter.endElement("ajax"); result = swx.toString(); expected = "if (true && true) { alert('foo'); }]]>"; System.out.println("3:" + result); assertTrue(expected.equals(result)); } public void testWriteStyleElement() throws Exception { StringWriter sw = new StringWriter(); StringWriter swx = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); ResponseWriter xmlWriter = renderKit.createResponseWriter(swx, "application/xhtml+xml", "UTF-8"); UIOutput output = new UIOutput(); writer.startElement("style", output); writer.writeAttribute("src", "http://foo.net/some.css", "src"); writer.writeAttribute("type", "text/css", "type"); writer.endElement("style"); String result = sw.toString(); System.out.println(result); assertTrue((!result.contains(""))); xmlWriter.startElement("style", output); xmlWriter.writeAttribute("src", "http://foo.net/some.css", "src"); xmlWriter.writeAttribute("type", "text/css", "type"); xmlWriter.endElement("style"); result = swx.toString(); System.out.println(result); assertTrue((!result.contains(""))); sw = new StringWriter(); swx = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); xmlWriter = renderKit.createResponseWriter(swx, "application/xhtml+xml", "UTF-8"); writer.startElement("style", output); writer.writeAttribute("type", "text/css", "type"); writer.write(".h1 { color: red }"); writer.endElement("style"); result = sw.toString(); System.out.println(result); assertTrue((result.contains(""))); xmlWriter.startElement("style", output); xmlWriter.writeAttribute("type", "text/css", "type"); xmlWriter.write(".h1 { color: red }"); xmlWriter.endElement("style"); result = swx.toString(); System.out.println(result); assertTrue((result.contains(""))); sw = new StringWriter(); swx = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); xmlWriter = renderKit.createResponseWriter(swx, "application/xhtml+xml", "UTF-8"); writer.startElement("style", output); writer.writeAttribute("type", "text/css", "type"); writer.write(""); writer.endElement("style"); result = sw.toString(); System.out.println("3:" +result); String expected = ""; assertTrue(expected.equals(result)); xmlWriter.startElement("style", output); xmlWriter.writeAttribute("type", "text/css", "type"); xmlWriter.write(""); xmlWriter.endElement("style"); result = swx.toString(); System.out.println("4:" +result); expected = ""; assertTrue(expected.equals(result)); } // // Test variations of the writeText method.. // public void testWriteText() { try { //---------------------------- // test Object param flavor... //---------------------------- StringBuffer sb = new StringBuffer("Some & Text"); writer.writeText(sb, null); assertTrue(sw.toString().equals("Some & Text")); //----------------------------------------- // test char[], offset, len param flavor... //----------------------------------------- sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); char[] carr1 = {'a', 'b', 'c', 'd', 'e'}; writer.writeText(carr1, 0, 2); assertTrue(sw.toString().equals("ab")); sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "ISO-8859-1"); writer.writeText(carr1, 0, 0); assertTrue(sw.toString().equals("")); boolean exceptionThrown = false; try { writer.writeText(carr1, -1, 3); } catch (IndexOutOfBoundsException iob) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.writeText(carr1, 10, 3); } catch (IndexOutOfBoundsException iob) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.writeText(carr1, 2, -1); } catch (IndexOutOfBoundsException iob) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.writeText(carr1, 2, 10); } catch (IndexOutOfBoundsException iob) { exceptionThrown = true; } assertTrue(exceptionThrown); } catch (IOException e) { assertTrue(false); } } /** * Added for issue 704. */ public void testWriteDecRefRegressionTest() throws Exception { Character c = '\u4300'; String test = c.toString(); sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "UTF-8"); writer.writeText(test, "value"); assertTrue("䌀", "䌀".equals(sw.toString())); } /** * Added for issue 705. */ public void testAttributesSumGreaterThan1024RegresssionTest() throws Exception { StringBuilder value = new StringBuilder(); for (int i = 0; i < 2111; i++) { value.append(i); } sw = new StringWriter(); writer = renderKit.createResponseWriter(sw, "text/html", "UTF-8"); writer.startElement("input", null); writer.writeAttribute("onclick", value.toString(), "onclick"); writer.writeAttribute("onclick", value.toString(), "onclick"); writer.endElement("input"); StringBuilder control = new StringBuilder(); control.append(""); assertTrue(sw.toString(), control.toString().trim().equals(sw.toString().trim())); } // // Test Null Argument Exceptions // public void testNullArgExceptions() { boolean exceptionThrown = false; try { writer.startElement(null, null); } catch (IOException e) { assertTrue(false); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.endElement(null); } catch (IOException e) { assertTrue(false); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.writeAttribute("foo", null, null); } catch (IOException e) { assertTrue(false); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(!exceptionThrown); exceptionThrown = false; try { writer.writeAttribute(null, "bar", null); } catch (IOException e) { assertTrue(false); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.writeURIAttribute("foo", null, null); } catch (IOException e) { assertTrue(false); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.writeURIAttribute(null, "bar", null); } catch (IOException e) { assertTrue(false); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.writeComment(null); } catch (IOException e) { assertTrue(false); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { writer.writeText(null, null); } catch (IOException e) { assertTrue(false); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); } } // end of class TestHtmlResponseWriter mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/html_basic/MenuRendererTestCase.java0000644000000000000000000001313211412443346026601 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2008 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ package com.sun.faces.renderkit.html_basic; import java.util.Set; import java.util.Collection; import java.util.HashSet; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.Queue; import java.util.LinkedList; import java.util.Date; import java.util.concurrent.CopyOnWriteArraySet; import javax.faces.FacesException; import com.sun.faces.cactus.ServletFacesTestCase; public class MenuRendererTestCase extends ServletFacesTestCase { // ----------------------------------------------------------- Setup Methods public MenuRendererTestCase() { super("MenuRendererTestCase.java"); } public MenuRendererTestCase(String name) { super(name); } // ------------------------------------------------------------ Test Methods public void testCreateCollection() { TestMenuRenderer r = new TestMenuRenderer(); // null instance using interface for the fallback should // result in a null return assertNull(r.createCollection(null, Set.class)); Collection c = r.createCollection(new HashSet(), ArrayList.class); assertNotNull(c); assertTrue(c instanceof HashSet); assertTrue(c.isEmpty()); } public void testCloneValue() { TestMenuRenderer r = new TestMenuRenderer(); Collection clonableCollection = new ArrayList(); clonableCollection.add("foo"); Collection cloned = r.cloneValue(clonableCollection); assertNotNull(cloned); assertTrue(cloned.isEmpty()); Collection nonClonableCollection = new CopyOnWriteArraySet(); assertNull(r.cloneValue(nonClonableCollection)); } public void testBestGuess() { TestMenuRenderer r = new TestMenuRenderer(); assertTrue(r.bestGuess(Set.class, 1) instanceof HashSet); assertTrue(r.bestGuess(List.class, 1) instanceof ArrayList); assertTrue(r.bestGuess(SortedSet.class, 1) instanceof TreeSet); assertTrue(r.bestGuess(Queue.class, 1) instanceof LinkedList); assertTrue(r.bestGuess(Collection.class, 1) instanceof ArrayList); } public void testCreateCollectionFromHint() { TestMenuRenderer r = new TestMenuRenderer(); assertTrue(r.createCollectionFromHint("java.util.ArrayList") instanceof ArrayList); assertTrue(r.createCollectionFromHint(LinkedList.class) instanceof LinkedList); try { r.createCollectionFromHint(java.util.Set.class); assertTrue(false); } catch (FacesException fe) { // expected } try { r.createCollectionFromHint(new Date()); assertTrue(false); } catch (FacesException fe) { // expected } } // ---------------------------------------------------------- Nested Classes private static final class TestMenuRenderer extends MenuRenderer { @Override public Collection createCollection(Collection collection, Class fallBackType) { return super.createCollection(collection, fallBackType); } @Override public Collection createCollectionFromHint(Object collectionTypeHint) { return super.createCollectionFromHint(collectionTypeHint); } @Override public Collection bestGuess(Class type, int initialSize) { return super.bestGuess(type, initialSize); } @Override protected Collection cloneValue(Object value) { return super.cloneValue(value); } } } mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/html_basic/TestRenderers_4.java0000644000000000000000000002136311412443346025573 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ /** * (C) Copyright International Business Machines Corp., 2001,2002 * The source code for this program is not published or otherwise * divested of its trade secrets, irrespective of what has been * deposited with the U. S. Copyright Office. */ // TestRenderers_4.java package com.sun.faces.renderkit.html_basic; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.RIConstants; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.component.UIComponent; import javax.faces.component.UIOutput; import javax.faces.component.UIPanel; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContextFactory; import java.io.IOException; import java.util.Locale; /** * Test encode and decode methods in Renderer classes. *

* Lifetime And Scope

*/ public class TestRenderers_4 extends JspFacesTestCase { // // Protected Constants // public boolean sendWriterToFile() { return true; } public String getExpectedOutputFilename() { return "CorrectRenderersResponse_4"; } // // Class Variables // // // Instance Variables // private FacesContextFactory facesContextFactory = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestRenderers_4() { super("TestRenderers_4"); } public TestRenderers_4(String name) { super(name); } // // Class methods // // // Methods from TestCase // public void setUp() { super.setUp(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setViewId("viewId"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); Object view = Util.getStateManager(getFacesContext()).saveSerializedView(getFacesContext()); getFacesContext().getExternalContext().getRequestMap().put(RIConstants.SAVED_STATE, view); assertTrue(null != getFacesContext().getResponseWriter()); } public void beginRenderers(WebRequest theRequest) { } public void testRenderers() { try { // create a dummy root for the tree. UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setLocale(Locale.US); root.setId("root"); testGridRenderer(root); root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setId("root"); root.setLocale(Locale.US); testGridRendererWithNonRenderedChildren(root); getFacesContext().getResponseWriter().close(); assertTrue(verifyExpectedOutput()); } catch (Throwable t) { t.printStackTrace(); assertTrue(false); return; } } public void testGridRenderer(UIComponent root) throws IOException { System.out.println("Testing GridRenderer"); GridRenderer gridRenderer = null; UIPanel panel = null, headerGroup = null, footerGroup = null; UIOutput header1 = null, header2 = null, footer1 = null, footer2 = null, body1 = null, body2 = null; panel = new UIPanel(); root.getChildren().add(panel); headerGroup = new UIPanel(); headerGroup.setId("header"); headerGroup.setRendererType("javax.faces.Group"); header1 = new UIOutput(); header1.setValue("header1 "); headerGroup.getChildren().add(header1); header2 = new UIOutput(); header2.setValue("header2 "); headerGroup.getChildren().add(header2); panel.getFacets().put("header", headerGroup); footerGroup = new UIPanel(); footerGroup.setId("footer"); footerGroup.setRendererType("javax.faces.Group"); footer1 = new UIOutput(); footer1.setValue("footer1 "); footerGroup.getChildren().add(footer1); footer2 = new UIOutput(); footer2.setValue("footer2 "); footerGroup.getChildren().add(footer2); panel.getFacets().put("footer", footerGroup); body1 = new UIOutput(); body1.setValue("body1"); panel.getChildren().add(body1); body2 = new UIOutput(); body2.setValue("body2"); panel.getChildren().add(body2); gridRenderer = new GridRenderer(); System.out.println(" Testing encodeBegin method... "); gridRenderer.encodeBegin(getFacesContext(), panel); gridRenderer.encodeChildren(getFacesContext(), panel); gridRenderer.encodeEnd(getFacesContext(), panel); } public void testGridRendererWithNonRenderedChildren(UIComponent root) throws IOException { System.out.println("Testing GridRenderer"); GridRenderer gridRenderer = null; UIPanel panel = null, headerGroup = null, footerGroup = null; UIOutput header1 = null, header2 = null, footer1 = null, footer2 = null, body1 = null, body2 = null; panel = new UIPanel(); root.getChildren().add(panel); // the header should not be rendered headerGroup = new UIPanel(); headerGroup.setRendered(false); headerGroup.setId("header"); headerGroup.setRendererType("javax.faces.Group"); header1 = new UIOutput(); header1.setValue("header1 "); headerGroup.getChildren().add(header1); header2 = new UIOutput(); header2.setValue("header2 "); headerGroup.getChildren().add(header2); panel.getFacets().put("header", headerGroup); footerGroup = new UIPanel(); footerGroup.setId("footer"); footerGroup.setRendererType("javax.faces.Group"); footer1 = new UIOutput(); footer1.setValue("footer1 "); footerGroup.getChildren().add(footer1); footer2 = new UIOutput(); footer2.setValue("footer2 "); footerGroup.getChildren().add(footer2); panel.getFacets().put("footer", footerGroup); // this child should not be rendered body1 = new UIOutput(); body1.setRendered(false); body1.setValue("body1"); panel.getChildren().add(body1); body2 = new UIOutput(); body2.setValue("body2"); panel.getChildren().add(body2); gridRenderer = new GridRenderer(); System.out.println(" Testing encodeBegin method... "); gridRenderer.encodeBegin(getFacesContext(), panel); gridRenderer.encodeChildren(getFacesContext(), panel); gridRenderer.encodeEnd(getFacesContext(), panel); } } // end of class TestRenderers_4 mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/html_basic/TestRenderers_3.java0000644000000000000000000004407111412443346025573 0ustar /* * 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ /** * (C) Copyright International Business Machines Corp., 2001,2002 * The source code for this program is not published or otherwise * divested of its trade secrets, irrespective of what has been * deposited with the U. S. Copyright Office. */ // TestRenderers_3.java package com.sun.faces.renderkit.html_basic; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.RIConstants; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.component.UICommand; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.component.UISelectItems; import javax.faces.component.UISelectMany; import javax.faces.component.UISelectOne; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContextFactory; import javax.faces.convert.Converter; import javax.faces.convert.NumberConverter; import javax.faces.model.SelectItem; import javax.faces.model.SelectItemGroup; import java.io.IOException; import java.text.DateFormat; import java.text.NumberFormat; import java.util.Date; import java.util.TimeZone; import java.util.Locale; /** * Test encode and decode methods in Renderer classes. *

* Lifetime And Scope

*/ public class TestRenderers_3 extends JspFacesTestCase { // // Instance Variables // private Application application; // // Protected Constants // public static String DATE_STR = "Jan 12, 1952"; public static String NUMBER_STR = "47%"; public boolean sendWriterToFile() { return true; } public String getExpectedOutputFilename() { return "CorrectRenderersResponse_3"; } // // Class Variables // // // Instance Variables // private FacesContextFactory facesContextFactory = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestRenderers_3() { super("TestRenderers_3"); } public TestRenderers_3(String name) { super(name); } // // Class methods // // // Methods from TestCase // public void setUp() { super.setUp(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = aFactory.getApplication(); UIViewRoot xmlTree = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); xmlTree.setViewId("viewId"); xmlTree.setLocale(Locale.US); xmlTree.getChildren().add(new UICommand()); getFacesContext().setViewRoot(xmlTree); Object view = Util.getStateManager(getFacesContext()).saveSerializedView(getFacesContext()); getFacesContext().getExternalContext().getRequestMap().put(RIConstants.SAVED_STATE, view); assertTrue(null != getFacesContext().getResponseWriter()); } public void beginRenderers(WebRequest theRequest) { theRequest.addParameter("myMenu", "Blue"); theRequest.addParameter("myListbox", "Blue"); theRequest.addParameter("myCheckboxlist", "Blue"); theRequest.addParameter("myOnemenu", "Blue"); // parameters to test hidden renderer theRequest.addParameter("myNumberHidden", NUMBER_STR); theRequest.addParameter("myInputDateHidden", DATE_STR); } public void testRenderers() { try { // create a dummy root for the tree. UIViewRoot root = getFacesContext().getViewRoot(); root.setId("root"); testSelectManyMenuRenderer(root); testSelectManyListboxRenderer(root); testSelectManyCheckboxListRenderer(root); testSelectOneMenuRenderer(root); testHiddenRenderer(root); assertTrue(verifyExpectedOutput()); } catch (Throwable t) { t.printStackTrace(); assertTrue(false); return; } } public void testSelectManyListboxRenderer(UIComponent root) throws IOException { System.out.println("Testing SelectManyListboxRenderer"); UISelectMany selectMany = new UISelectMany(); UISelectItems uiSelectItems = new UISelectItems(); selectMany.setValue(null); selectMany.setId("myListbox"); SelectItem item1 = new SelectItem("Red", "Red", null); SelectItem item2 = new SelectItem("Blue", "Blue", null); SelectItem item3 = new SelectItem("Green", "Green", null); SelectItem item4 = new SelectItem("Yellow", "Yellow", null); SelectItem[] itemsArray = {item3, item4}; SelectItemGroup itemGroup = new SelectItemGroup("group", null, true, itemsArray); SelectItem[] selectItems = {item1, item2, itemGroup}; Object selectedValues[] = null; uiSelectItems.setValue(selectItems); uiSelectItems.setId("manyListitems"); selectMany.getChildren().add(uiSelectItems); root.getChildren().add(selectMany); ListboxRenderer selectManyListboxRenderer = new ListboxRenderer(); // test decode method System.out.println(" Testing decode method... "); selectManyListboxRenderer.decode(getFacesContext(), selectMany); selectedValues = (Object[]) selectMany.getSubmittedValue(); assertTrue(null != selectedValues); assertTrue(1 == selectedValues.length); assertTrue(((String) selectedValues[0]).equals("Blue")); // test convert method Object[] convertedValues = (Object[]) selectManyListboxRenderer.getConvertedValue( getFacesContext(), selectMany, selectMany.getSubmittedValue()); assertTrue(null != convertedValues); assertTrue(1 == convertedValues.length); assertTrue(((String) convertedValues[0]).equals("Blue")); // test encode method System.out.println(" Testing encode method... "); selectManyListboxRenderer.encodeBegin(getFacesContext(), selectMany); selectManyListboxRenderer.encodeEnd(getFacesContext(), selectMany); getFacesContext().getResponseWriter().writeText("\n", null); getFacesContext().getResponseWriter().flush(); } public void testSelectManyCheckboxListRenderer(UIComponent root) throws IOException { System.out.println("Testing SelectManyCheckboxListRenderer"); UISelectMany selectMany = new UISelectMany(); selectMany.getAttributes().put("enabledClass", "enabledClass"); selectMany.getAttributes().put("disabledClass", "disabledClass"); selectMany.getAttributes().put("styleClass", "styleClass"); selectMany.getAttributes().put("tabindex", new Integer(5)); selectMany.getAttributes().put("title", "title"); UISelectItems uiSelectItems = new UISelectItems(); selectMany.setValue(null); selectMany.setId("myCheckboxlist"); SelectItem item1 = new SelectItem("Red", "Red", null); item1.setDisabled(true); SelectItem item2 = new SelectItem("Blue", "Blue", null); SelectItem item3 = new SelectItem("Green", "Green", null); SelectItem item4 = new SelectItem("Yellow", "Yellow", null); SelectItem[] itemsArray = {item3, item4}; SelectItemGroup itemGroup = new SelectItemGroup("group", null, true, itemsArray); SelectItem[] selectItems = {item1, item2, itemGroup}; Object selectedValues[] = null; uiSelectItems.setValue(selectItems); selectMany.getChildren().add(uiSelectItems); root.getChildren().add(selectMany); SelectManyCheckboxListRenderer selectManyCheckboxListRenderer = new SelectManyCheckboxListRenderer(); // test decode method System.out.println(" Testing decode method... "); selectManyCheckboxListRenderer.decode(getFacesContext(), selectMany); selectedValues = (Object[]) selectMany.getSubmittedValue(); assertTrue(null != selectedValues); assertTrue(1 == selectedValues.length); assertTrue(((String) selectedValues[0]).equals("Blue")); // test convert method Object[] convertedValues = (Object[]) selectManyCheckboxListRenderer.getConvertedValue( getFacesContext(), selectMany, selectMany.getSubmittedValue()); assertTrue(null != convertedValues); assertTrue(1 == convertedValues.length); assertTrue(((String) convertedValues[0]).equals("Blue")); // test encode method System.out.println(" Testing encode method... "); selectManyCheckboxListRenderer.encodeBegin(getFacesContext(), selectMany); selectManyCheckboxListRenderer.encodeEnd(getFacesContext(), selectMany); getFacesContext().getResponseWriter().writeText("\n", null); getFacesContext().getResponseWriter().flush(); } public void testSelectManyMenuRenderer(UIComponent root) throws IOException { System.out.println("Testing SelectManyMenuRenderer"); UISelectMany selectMany = new UISelectMany(); UISelectItems uiSelectItems = new UISelectItems(); selectMany.setValue(null); selectMany.setId("myMenu"); SelectItem item1 = new SelectItem("Red", "Red", null); SelectItem item2 = new SelectItem("Blue", "Blue", null); SelectItem item3 = new SelectItem("Green", "Green", null); SelectItem item4 = new SelectItem("Yellow", "Yellow", null); SelectItem[] selectItems = {item1, item2, item3, item4}; Object selectedValues[] = null; uiSelectItems.setValue(selectItems); uiSelectItems.setId("manyMenuitems"); selectMany.getChildren().add(uiSelectItems); root.getChildren().add(selectMany); MenuRenderer selectManyMenuRenderer = new MenuRenderer(); // test decode method System.out.println(" Testing decode method... "); selectManyMenuRenderer.decode(getFacesContext(), selectMany); selectedValues = (Object[]) selectMany.getSubmittedValue(); assertTrue(null != selectedValues); assertTrue(1 == selectedValues.length); assertTrue(((String) selectedValues[0]).equals("Blue")); // test convert method Object[] convertedValues = (Object[]) selectManyMenuRenderer.getConvertedValue( getFacesContext(), selectMany, selectMany.getSubmittedValue()); assertTrue(null != convertedValues); assertTrue(1 == convertedValues.length); assertTrue(((String) convertedValues[0]).equals("Blue")); // test encode method System.out.println(" Testing encode method... "); selectManyMenuRenderer.encodeBegin(getFacesContext(), selectMany); selectManyMenuRenderer.encodeEnd(getFacesContext(), selectMany); getFacesContext().getResponseWriter().writeText("\n", null); getFacesContext().getResponseWriter().flush(); } public void testSelectOneMenuRenderer(UIComponent root) throws IOException { System.out.println("Testing SelectOneMenuRenderer"); UISelectOne selectOne = new UISelectOne(); UISelectItems uiSelectItems = new UISelectItems(); selectOne.setValue(null); selectOne.setId("myOnemenu"); SelectItem item1 = new SelectItem("Red", "Red", null); SelectItem item2 = new SelectItem("Blue", "Blue", null); SelectItem item3 = new SelectItem("Green", "Green", null); SelectItem item4 = new SelectItem("Yellow", "Yellow", null); SelectItem[] selectItems = {item1, item2, item3, item4}; String selectedValue = null; uiSelectItems.setValue(selectItems); uiSelectItems.setId("manySelectOneitems"); selectOne.getChildren().add(uiSelectItems); root.getChildren().add(selectOne); MenuRenderer selectOneMenuRenderer = new MenuRenderer(); // test decode method System.out.println(" Testing decode method... "); selectOneMenuRenderer.decode(getFacesContext(), selectOne); assertTrue("Blue".equals(selectOne.getSubmittedValue())); // test convert method Object value = selectOneMenuRenderer.getConvertedValue( getFacesContext(), selectOne, selectOne.getSubmittedValue()); assertTrue("Blue".equals(value)); // test encode method System.out.println(" Testing encode method... "); selectOneMenuRenderer.encodeBegin(getFacesContext(), selectOne); selectOneMenuRenderer.encodeEnd(getFacesContext(), selectOne); getFacesContext().getResponseWriter().writeText("\n", null); getFacesContext().getResponseWriter().flush(); } public void testHiddenRenderer(UIComponent root) throws IOException { System.out.println("Testing Input_DateRenderer"); UIInput input1 = new UIInput(); input1.setValue(null); input1.setId("myInputDateHidden"); Converter converter = application.createConverter( "javax.faces.DateTime"); input1.setConverter(converter); input1.getAttributes().put("dateStyle", "medium"); root.getChildren().add(input1); HiddenRenderer hiddenRenderer = new HiddenRenderer(); DateFormat dateformatter = DateFormat.getDateInstance(DateFormat.MEDIUM, getFacesContext().getViewRoot() .getLocale()); dateformatter.setTimeZone(TimeZone.getTimeZone("GMT")); // test hidden renderer with converter set to date // test decode method System.out.println(" Testing decode method..."); hiddenRenderer.decode(getFacesContext(), input1); Date date = (Date) hiddenRenderer.getConvertedValue(getFacesContext(), input1, input1.getSubmittedValue()); assertTrue(null != date); assertTrue(DATE_STR.equals(dateformatter.format(date))); // test encode method System.out.println(" Testing encode method..."); hiddenRenderer.encodeBegin(getFacesContext(), input1); hiddenRenderer.encodeEnd(getFacesContext(), input1); getFacesContext().getResponseWriter().flush(); // test hidden renderer with converter set to number UIInput input2 = new UIInput(); input2.setValue(null); input2.setId("myNumberHidden"); converter = application.createConverter("javax.faces.Number"); ((NumberConverter) converter).setType("percent"); input2.setConverter(converter); root.getChildren().add(input2); NumberFormat numberformatter = NumberFormat.getPercentInstance(getFacesContext(). getViewRoot().getLocale()); // test decode method System.out.println(" Testing decode method..."); hiddenRenderer.decode(getFacesContext(), input2); Number number = (Number) hiddenRenderer.getConvertedValue( getFacesContext(), input2, input2.getSubmittedValue()); assertTrue(null != number); System.out.println("NUMBER_STR:" + NUMBER_STR); System.out.println("NUMBERFORMATTER:" + numberformatter.format(number)); assertTrue(NUMBER_STR.equals(numberformatter.format(number))); // test encode method System.out.println(" Testing encode method..."); hiddenRenderer.encodeBegin(getFacesContext(), input2); hiddenRenderer.encodeEnd(getFacesContext(), input2); getFacesContext().getResponseWriter().flush(); } } // end of class TestRenderers_3 mojarra-2.0.3.orig/jsf-ri/test/com/sun/faces/renderkit/html_basic/TestRenderers_2.java0000644000000000000000000015522511412443346025576 0ustar /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 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 * may not use this file except in compliance with the License. You can obtain * 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 * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * 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 * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * 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. */ // TestRenderers_2.java package com.sun.faces.renderkit.html_basic; import com.sun.faces.cactus.JspFacesTestCase; import com.sun.faces.RIConstants; import com.sun.faces.el.ELUtils; import com.sun.faces.util.Util; import org.apache.cactus.WebRequest; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.application.FacesMessage; import javax.faces.component.UICommand; import javax.faces.component.UIComponent; import javax.faces.component.UIGraphic; import javax.faces.component.UIInput; import javax.faces.component.UIMessage; import javax.faces.component.UIMessages; import javax.faces.component.UIOutput; import javax.faces.component.UIParameter; import javax.faces.component.UISelectBoolean; import javax.faces.component.UISelectItems; import javax.faces.component.UISelectOne; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContextFactory; import javax.faces.context.ResponseWriter; import javax.faces.convert.Converter; import javax.faces.model.SelectItem; import java.io.IOException; import java.io.StringWriter; import java.util.Locale; /** * Test encode and decode methods in Renderer classes. *

* Lifetime And Scope

*/ public class TestRenderers_2 extends JspFacesTestCase { // // Instance Variables // private Application application; // // Protected Constants // public static String DATE_STR = "Jan 12, 1952"; public static String DATE_STR_LONG = "Sat, Jan 12, 1952 AD at 12:31:31 PM"; public static String TIME_STR = "12:31:31 PM"; public static String NUMBER_STR = "47%"; public static String NUMBER_STR_PATTERN = "1999.8765432"; public boolean sendWriterToFile() { return true; } public String getExpectedOutputFilename() { return "CorrectRenderersResponse_2"; } public static final String ignore[] = { }; // // Class Variables // // // Instance Variables // private FacesContextFactory facesContextFactory = null; // Attribute Instance Variables // Relationship Instance Variables // // Constructors and Initializers // public TestRenderers_2() { super("TestRenderers_2"); } public TestRenderers_2(String name) { super(name); } // // Class methods // // // Methods from TestCase // public void setUp() { super.setUp(); ApplicationFactory aFactory = (ApplicationFactory) FactoryFinder.getFactory( FactoryFinder.APPLICATION_FACTORY); application = aFactory.getApplication(); UIViewRoot page = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); page.setViewId("viewId"); page.setLocale(Locale.US); getFacesContext().setViewRoot(page); Object view = Util.getStateManager(getFacesContext()).saveSerializedView(getFacesContext()); getFacesContext().getExternalContext().getRequestMap().put(RIConstants.SAVED_STATE, view); assertTrue(null != getFacesContext().getResponseWriter()); } public void beginRenderers(WebRequest theRequest) { // for CheckboxRenderer theRequest.addParameter("myCheckboxOn", "on"); theRequest.addParameter("myCheckboxYes", "yes"); theRequest.addParameter("myCheckboxTrue", "true"); // for LinkRenderer theRequest.addParameter("action", "command"); theRequest.addParameter("myCommand", "LinkRenderer"); // for Listbox theRequest.addParameter("myListbox", "100"); // for TextEntry_Secret theRequest.addParameter("mySecret", "secret"); // for Text theRequest.addParameter("myInputText", "text"); theRequest.addParameter("myOutputText", "text"); theRequest.addParameter("myTextarea", "TextareaRenderer"); theRequest.addParameter("myGraphicImage", "graphicimage"); theRequest.addParameter("myOutputMessage", "outputmessage"); } public void testRenderers() throws Exception { // create a dummy root for the tree. UIViewRoot root = Util.getViewHandler(getFacesContext()).createView(getFacesContext(), null); root.setId("root"); root.setLocale(Locale.US); testCheckboxRenderer(root); // PENDING (visvan) revisit this test case once HyperLinkRenderer // is fixed. // testLinkRenderer(root); getFacesContext().getResponseWriter().startDocument(); testListboxRenderer(root); testSecretRenderer(root); testInputTextRenderer(root); testOutputTextRenderer(root); testTextareaRenderer(root); testGraphicImageRenderer(root); testOutputMessageRenderer(root); testMessageRenderer(root); testMessagesRenderer(root); getFacesContext().getResponseWriter().endDocument(); assertTrue(verifyExpectedOutput()); } // // General Methods // public void testCheckboxRenderer(UIComponent root) throws IOException { System.out.println("Testing CheckboxRenderer"); UISelectBoolean selectBoolean = new UISelectBoolean(); selectBoolean.setValue(null); selectBoolean.setId("myCheckbox"); root.getChildren().add(selectBoolean); CheckboxRenderer checkboxRenderer = new CheckboxRenderer(); // First test no parameter coming in - (the checkbox // is not checked) // test decode method System.out.println(" Testing decode method - no parameter"); checkboxRenderer.decode(getFacesContext(), selectBoolean); assertEquals("false", selectBoolean.getSubmittedValue().toString()); Object value = checkboxRenderer.getConvertedValue(getFacesContext(), selectBoolean, selectBoolean.getSubmittedValue()); assertEquals(Boolean.FALSE, value); // Test parameter coming in - (the checkbox has been checked) // test decode method System.out.println(" Testing decode method - parameter (on)"); selectBoolean = new UISelectBoolean(); selectBoolean.setId("myCheckboxOn"); selectBoolean.setValue(null); checkboxRenderer.decode(getFacesContext(), selectBoolean); assertEquals("true", selectBoolean.getSubmittedValue().toString()); value = checkboxRenderer.getConvertedValue(getFacesContext(), selectBoolean, selectBoolean.getSubmittedValue()); assertEquals(Boolean.TRUE, value); // test decode method System.out.println(" Testing decode method - parameter (yes)"); selectBoolean = new UISelectBoolean(); selectBoolean.setId("myCheckboxYes"); selectBoolean.setValue(null); checkboxRenderer.decode(getFacesContext(), selectBoolean); assertEquals("true", selectBoolean.getSubmittedValue().toString()); value = checkboxRenderer.getConvertedValue(getFacesContext(), selectBoolean, selectBoolean.getSubmittedValue()); assertEquals(Boolean.TRUE, value); // test decode method System.out.println(" Testing decode method - parameter (true)"); selectBoolean = new UISelectBoolean(); selectBoolean.setId("myCheckboxTrue"); selectBoolean.setValue(null); checkboxRenderer.decode(getFacesContext(), selectBoolean); assertEquals("true", selectBoolean.getSubmittedValue().toString()); value = checkboxRenderer.getConvertedValue(getFacesContext(), selectBoolean, selectBoolean.getSubmittedValue()); assertEquals(Boolean.TRUE, value); // test decode method System.out.println(" Testing decode method - parameter (true)"); selectBoolean = new UISelectBoolean(); selectBoolean.setId("myCheckboxTrue"); selectBoolean.setValue(null); checkboxRenderer.decode(getFacesContext(), selectBoolean); assertEquals("true", selectBoolean.getSubmittedValue().toString()); value = checkboxRenderer.getConvertedValue(getFacesContext(), selectBoolean, selectBoolean.getSubmittedValue()); assertEquals(Boolean.TRUE, value); // test decode method with checkbox disabled. System.out.println(" Testing decode method - parameter (yes)"); selectBoolean = new UISelectBoolean(); selectBoolean.setId("mycheckboxDisabled"); selectBoolean.getAttributes().put("disabled", "true"); selectBoolean.setValue(Boolean.TRUE); checkboxRenderer.decode(getFacesContext(), selectBoolean); // make sure the value wasn't set to false. Bug id 4883159 assertTrue(!"false".equals(selectBoolean.getSubmittedValue())); selectBoolean.getAttributes().remove("disabled"); // test encode method System.out.println(" Testing encode method - rendering checked"); selectBoolean = new UISelectBoolean(); selectBoolean.setId("myCheckbox"); selectBoolean.setSelected(true); checkboxRenderer.encodeBegin(getFacesContext(), selectBoolean); checkboxRenderer.encodeEnd(getFacesContext(), selectBoolean); getFacesContext().getResponseWriter().writeText("\n", null); System.out.println(" Testing encode method - rendering unchecked"); selectBoolean.setSelected(false); checkboxRenderer.encodeBegin(getFacesContext(), selectBoolean); checkboxRenderer.encodeEnd(getFacesContext(), selectBoolean); getFacesContext().getResponseWriter().writeText("\n", null); System.out.println( " Testing encode method - rendering unchecked with label"); checkboxRenderer.encodeBegin(getFacesContext(), selectBoolean); checkboxRenderer.encodeEnd(getFacesContext(), selectBoolean); getFacesContext().getResponseWriter().writeText("\n", null); } public void testLinkRenderer(UIComponent root) throws IOException { System.out.println("Testing LinkRenderer"); UICommand command = new UICommand(); command.setId("myCommand"); command.setRendererType("Link"); root.getChildren().add(command); LinkRenderer hyperlinkRenderer = new CommandLinkRenderer(); System.out.println(" Testing decode method..."); hyperlinkRenderer.decode(getFacesContext(), command); // Verify command event was set for the application.. System.out.println( " Testing added application event (commandEvent).."); // PENDING FIX /* Iterator iter = getFacesContext().getFacesEvents(); assertTrue(iter.hasNext()); */ // Test encode method System.out.println(" Testing encode method..."); hyperlinkRenderer.encodeBegin(getFacesContext(), command); hyperlinkRenderer.encodeEnd(getFacesContext(), command); getFacesContext().getResponseWriter().writeText("\n", null); } public void testListboxRenderer(UIComponent root) throws IOException { System.out.println("Testing ListboxRenderer"); UISelectOne selectOne = new UISelectOne(); UISelectItems uiSelectItems = new UISelectItems(); selectOne.setValue(null); selectOne.setId("myListbox"); SelectItem item1 = new SelectItem(new Long(100), "Long1", null); SelectItem item2 = new SelectItem(new Long(101), "Long2", null); SelectItem item3 = new SelectItem(new Long(102), "Long3", null); SelectItem item4 = new SelectItem(new Long(103), "Long4", null); SelectItem[] selectItems = {item1, item2, item3, item4}; uiSelectItems.setValue(selectItems); uiSelectItems.setId("items"); Converter converter = application.createConverter("javax.faces.Number"); selectOne.setConverter(converter); selectOne.getChildren().add(uiSelectItems); root.getChildren().add(selectOne); ListboxRenderer listboxRenderer = new ListboxRenderer(); // test decode method System.out.println(" Testing decode method... "); listboxRenderer.decode(getFacesContext(), selectOne); assertTrue("100".equals(selectOne.getSubmittedValue())); // test convert method Object value = listboxRenderer.getConvertedValue(getFacesContext(), selectOne, selectOne.getSubmittedValue()); assertTrue(value.equals(new Long(100))); // test encode method System.out.println(" Testing encode method... "); //selectOne.setId("myListbox"); listboxRenderer.encodeBegin(getFacesContext(), selectOne); listboxRenderer.encodeEnd(getFacesContext(), selectOne); getFacesContext().getResponseWriter().writeText("\n", null); } public void testSecretRenderer(UIComponent root) throws IOException { System.out.println("Testing SecretRenderer"); UIInput textEntry = new UIInput(); textEntry.setValue(null); textEntry.setId("mySecret"); root.getChildren().add(textEntry); SecretRenderer secretRenderer = new SecretRenderer(); // test decode method System.out.println(" Testing decode method..."); secretRenderer.decode(getFacesContext(), textEntry); assertTrue("secret".equals(textEntry.getSubmittedValue())); // test convert method Object value = secretRenderer.getConvertedValue(getFacesContext(), textEntry, textEntry.getSubmittedValue()); assertTrue("secret".equals(value)); // test encode method System.out.println(" Testing encode method..."); secretRenderer.encodeBegin(getFacesContext(), textEntry); secretRenderer.encodeEnd(getFacesContext(), textEntry); getFacesContext().getResponseWriter().writeText("\n", null); } public void testInputTextRenderer(UIComponent root) throws IOException { System.out.println("Testing InputTextRenderer"); UIInput text = new UIInput(); text.setValue(null); text.setId("myInputText"); root.getChildren().add(text); TextRenderer textRenderer = new TextRenderer(); // test decode method System.out.println(" Testing decode method..."); textRenderer.decode(getFacesContext(), text); assertTrue("text".equals(text.getSubmittedValue())); // test convert method Object value = textRenderer.getConvertedValue(getFacesContext(), text, text.getSubmittedValue()); assertTrue("text".equals(value)); // test encode method System.out.println(" Testing encode method..."); textRenderer.encodeBegin(getFacesContext(), text); textRenderer.encodeEnd(getFacesContext(), text); } public void testOutputTextRenderer(UIComponent root) throws IOException { System.out.println("Testing OutputTextRenderer"); UIOutput text = new UIOutput(); text.setValue(null); text.setId("myOutputText"); root.getChildren().add(text); TextRenderer textRenderer = new TextRenderer(); // test decode method System.out.println(" Testing decode method..."); textRenderer.decode(getFacesContext(), text); // test encode method System.out.println(" Testing encode method..."); textRenderer.encodeBegin(getFacesContext(), text); textRenderer.encodeEnd(getFacesContext(), text); } public void testGraphicImageRenderer(UIComponent root) throws IOException { System.out.println("Testing GraphicImageRenderer"); UIGraphic img = new UIGraphic(); img.setUrl("/nonModelReferenceImage.gif"); img.setId("myGraphicImage"); img.getAttributes().put("ismap", new Boolean(true)); img.getAttributes().put("usemap", "usemap"); root.getChildren().add(img); ImageRenderer imageRenderer = new ImageRenderer(); // test decode method System.out.println(" Testing decode method..."); imageRenderer.decode(getFacesContext(), img); // test encode method System.out.println(" Testing encode method..."); imageRenderer.encodeBegin(getFacesContext(), img); imageRenderer.encodeEnd(getFacesContext(), img); System.out.println(" Testing graphic support of modelReference..."); root.getChildren().remove(img); img = new UIGraphic(); img.getAttributes().put("ismap", new Boolean(true)); img.getAttributes().put("usemap", "usemap"); root.getChildren().add(img); com.sun.faces.cactus.TestBean testBean = (com.sun.faces.cactus.TestBean) (ELUtils.createValueExpression("#{TestBean}")).getValue(getFacesContext().getELContext()); assertTrue(null != testBean); // set in FacesTestCaseService testBean.setImagePath("/foo/modelReferenceImage.gif"); img.setValueExpression("value", ELUtils.createValueExpression("#{TestBean.imagePath}")); imageRenderer.encodeBegin(getFacesContext(), img); imageRenderer.encodeEnd(getFacesContext(), img); } public void testOutputMessageRenderer(UIComponent root) throws IOException { System.out.println("Testing OutputMessageRenderer"); UIOutput output = new UIOutput(); output.setId("myOutputMessage"); output.setValue("My name is {0} {1}"); UIParameter param1, param2 = null; param1 = new UIParameter(); param1.setId("p1"); param2 = new UIParameter(); param2.setId("p2"); param1.setValue("Bobby"); param2.setValue("Orr"); output.getChildren().add(param1); output.getChildren().add(param2); root.getChildren().add(output); OutputMessageRenderer outputMessageRenderer = new OutputMessageRenderer(); // test encode method System.out.println(" Testing encode method..."); outputMessageRenderer.encodeBegin(getFacesContext(), output); outputMessageRenderer.encodeEnd(getFacesContext(), output); } public void testMessageRenderer(UIComponent root) throws IOException { System.out.println("Testing MessageRenderer"); UIMessage message = new UIMessage(); message.setId("myMessage_0"); message.setFor("myMessage_0"); root.getChildren().add(message); ResponseWriter originalWriter = getFacesContext().getResponseWriter(); UIViewRoot originalRoot = getFacesContext().getViewRoot(); getFacesContext().setViewRoot((UIViewRoot) root); // setup a new HtmlResponseWriter using a StringWriter. // This allows us to capture the output and check for // correctness without using a goldenfile. StringWriter writer = new StringWriter(); HtmlResponseWriter htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); MessageRenderer messageRenderer = new MessageRenderer(); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_INFO, "global message summary_0", "global message detail_0")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); String result = writer.toString(); try { writer.close(); } catch (IOException ioe) { ; // ignore } root.getChildren().remove(message); message = new UIMessage(); message.setId("myMessage_1"); message.setFor("myMessage_1"); message.getAttributes().put("warnClass", "warnClass"); message.getAttributes().put("errorClass", "errorClass"); message.getAttributes().put("infoClass", "infoClass"); message.getAttributes().put("fatalClass", "fatalClass"); message.setShowDetail(true); message.setShowSummary(true); root.getChildren().add(message); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messageRenderer = new MessageRenderer(); //add a styleClass so span is rendered message.getAttributes().put("styleClass", "styleClass"); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_WARN, "global message summary_1", "global message detail_1")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); result = writer.toString(); //Span should have class attribute for styleClass //Summary and detail should be in body of span separated by space assertTrue( result.indexOf( " global message summary_1 global message detail_1") != -1); try { writer.close(); } catch (IOException ioe) { ; // ignore } root.getChildren().remove(message); message = new UIMessage(); message.setId("myMessage_2"); message.setFor("myMessage_2"); message.getAttributes().put("warnClass", "warnClass"); message.getAttributes().put("errorClass", "errorClass"); message.getAttributes().put("infoClass", "infoClass"); message.getAttributes().put("fatalClass", "fatalClass"); message.setShowDetail(true); message.setShowSummary(true); root.getChildren().add(message); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messageRenderer = new MessageRenderer(); //add a styleClass so span is rendered message.getAttributes().put("style", "style"); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_ERROR, "global message summary_2", "global message detail_2")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); result = writer.toString(); //Span should have style attribute //Summary and detail should be in body of span separated by space assertTrue( result.indexOf( " global message summary_2 global message detail_2") != -1); try { writer.close(); } catch (IOException ioe) { ; // ignore } root.getChildren().remove(message); message = new UIMessage(); message.setId("myMessage_3"); message.setFor("myMessage_3"); message.getAttributes().put("warnClass", "warnClass"); message.getAttributes().put("errorClass", "errorClass"); message.getAttributes().put("infoClass", "infoClass"); message.getAttributes().put("fatalClass", "fatalClass"); message.setShowDetail(true); message.setShowSummary(true); root.getChildren().add(message); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messageRenderer = new MessageRenderer(); //add a styleClass so span is rendered message.getAttributes().put("styleClass", "styleClass"); message.getAttributes().put("style", "style"); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_FATAL, "global message summary_3", "global message detail_3")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); result = writer.toString(); //Span should have class attribute for styleClass and style attribute //Summary and detail should be in body of span separated by space assertTrue( result.indexOf( " global message summary_3 global message detail_3") != -1); try { writer.close(); } catch (IOException ioe) { ; // ignore } root.getChildren().remove(message); message = new UIMessage(); message.setId("myMessage_4"); message.setFor("myMessage_4"); root.getChildren().add(message); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messageRenderer = new MessageRenderer(); //add a styleClass so span is rendered message.getAttributes().put("styleClass", "styleClass"); message.getAttributes().put("style", "style"); //set tooltip criteria to true message.getAttributes().put("tooltip", new Boolean(true)); message.setShowDetail(true); message.setShowSummary(true); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_FATAL, "global message summary_4", "global message detail_4")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); result = writer.toString(); //Span should containt class for styleClass, style, // and title for tooltip attributes //Summary should go in the title attribute and only the // detail displayed in the body of the span assertTrue( result.indexOf( " global message detail_4") != -1); try { writer.close(); } catch (IOException ioe) { ; // ignore } root.getChildren().remove(message); message = new UIMessage(); message.setId("myMessage_5"); message.setFor("myMessage_5"); root.getChildren().add(message); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messageRenderer = new MessageRenderer(); //add a styleClass so span is rendered message.getAttributes().put("styleClass", "styleClass"); message.getAttributes().put("style", "style"); //set tooltip criteria to true message.getAttributes().put("tooltip", new Boolean(true)); message.setShowDetail(true); message.setShowSummary(true); message.getAttributes().put("warnClass", "warnClass"); message.getAttributes().put("errorClass", "errorClass"); message.getAttributes().put("infoClass", "infoClass"); message.getAttributes().put("fatalClass", "fatalClass"); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_FATAL, "global message summary_5", "global message detail_5")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); result = writer.toString(); //Span should containt class for styleClass, style, // and title for tooltip attributes //Summary should go in the title attribute and only the // detail displayed in the body of the span //Should be wrapped in a table assertTrue( result.indexOf( " global message detail_5") != -1); try { writer.close(); } catch (IOException ioe) { ; // ignore } // // test showSummary(false) works // root.getChildren().remove(message); message = new UIMessage(); message.setId("myMessage_6"); message.setFor("myMessage_6"); root.getChildren().add(message); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messageRenderer = new MessageRenderer(); //set tooltip criteria to true message.getAttributes().put("tooltip", new Boolean(true)); message.setShowDetail(true); message.setShowSummary(false); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_FATAL, "global message summary_6", "global message detail_6")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); result = writer.toString(); // should not contain summary. assertTrue(-1 != result.indexOf("global message detail_6")); assertEquals(-1, result.indexOf("global message summary_6")); try { writer.close(); } catch (IOException ioe) { ; // ignore } // // test showDetail(false) works // root.getChildren().remove(message); message = new UIMessage(); message.setId("myMessage_6"); message.setFor("myMessage_6"); root.getChildren().add(message); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messageRenderer = new MessageRenderer(); //set tooltip criteria to true message.getAttributes().put("tooltip", new Boolean(true)); message.setShowDetail(false); message.setShowSummary(true); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_FATAL, "global message summary_6", "global message detail_6")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); result = writer.toString(); // should not contain detail. assertEquals(-1, result.indexOf("global message detail_6")); assertTrue(-1 != result.indexOf("global message summary_6")); try { writer.close(); } catch (IOException ioe) { ; // ignore } // // test showDetail(false), showSummary(false) works // root.getChildren().remove(message); message = new UIMessage(); message.setId("myMessage_6"); message.setFor("myMessage_6"); root.getChildren().add(message); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messageRenderer = new MessageRenderer(); //set tooltip criteria to true message.getAttributes().put("tooltip", new Boolean(true)); message.setShowDetail(false); message.setShowSummary(false); // populate facescontext with some errors getFacesContext().addMessage(message.getFor(), new FacesMessage( FacesMessage.SEVERITY_FATAL, "global message summary_6", "global message detail_6")); // test encode method messageRenderer.encodeBegin(getFacesContext(), message); messageRenderer.encodeEnd(getFacesContext(), message); result = writer.toString(); // should not contain detail. assertEquals(-1, result.indexOf("global message detail_6")); assertEquals(-1, result.indexOf("global message summary_6")); try { writer.close(); } catch (IOException ioe) { ; // ignore } // restore the original ResponseWriter getFacesContext().setResponseWriter(originalWriter); getFacesContext().setViewRoot(originalRoot); } public void testMessagesRenderer(UIComponent root) throws IOException { System.out.println("Testing MessagesRenderer"); UIMessages messages = new UIMessages(); messages.setId("myMessage_0"); String myFor = "myMessage_0"; // messages.setFor("myMessage_0"); root.getChildren().add(messages); ResponseWriter originalWriter = getFacesContext().getResponseWriter(); UIViewRoot originalRoot = getFacesContext().getViewRoot(); getFacesContext().setViewRoot((UIViewRoot) root); // setup a new HtmlResponseWriter using a StringWriter. // This allows us to capture the output and check for // correctness without using a goldenfile. StringWriter writer = new StringWriter(); HtmlResponseWriter htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); MessagesRenderer messagesRenderer = new MessagesRenderer(); // populate facescontext with some errors getFacesContext().addMessage(myFor, new FacesMessage( FacesMessage.SEVERITY_INFO, "global message summary_0.0", "global message detail_0.0")); getFacesContext().addMessage(myFor, new FacesMessage( FacesMessage.SEVERITY_INFO, "global message summary_0.1", "global message detail_0.1")); // test encode method messagesRenderer.encodeBegin(getFacesContext(), messages); messagesRenderer.encodeEnd(getFacesContext(), messages); String result = writer.toString(); //no span should be rendered since none of the criteria was met assertTrue(result.indexOf("span") == -1); try { writer.close(); } catch (IOException ioe) { ; // ignore } root.getChildren().remove(messages); messages = new UIMessages(); messages.setId("myMessage_1"); myFor = "myMessage_1"; // messages.setFor("myMessage_1"); messages.setShowDetail(true); messages.setShowSummary(true); messages.getAttributes().put("warnClass", "warnClass"); messages.getAttributes().put("errorClass", "errorClass"); messages.getAttributes().put("infoClass", "infoClass"); messages.getAttributes().put("fatalClass", "fatalClass"); root.getChildren().add(messages); writer = new StringWriter(); htmlWriter = new HtmlResponseWriter(writer, "text/html", "ISO-8859-1"); getFacesContext().setResponseWriter(htmlWriter); messagesRenderer = new MessagesRenderer(); //add a styleClass so span is rendered messages.getAttributes().put("styleClass", "styleClass"); // populate facescontext with some errors getFacesContext().addMessage(myFor, new FacesMessage( FacesMessage.SEVERITY_WARN, "global message summary_1.0", "global message detail_1.0")); getFacesContext().addMessage(myFor, new FacesMessage( FacesMessage.SEVERITY_WARN, "global message summary_1.1", "global message detail_1.1")); getFacesContext().addMessage(myFor, new FacesMessage( FacesMessage.SEVERITY_WARN, "global message summary_1.1", "global message detail_1.1")); // test encode method messagesRenderer.encodeBegin(getFacesContext(), messages); messagesRenderer.encodeEnd(getFacesContext(), messages); result = writer.toString(); //Verify Html list (