View Javadoc

1   /**
2    * This file Copyright (c) 2010-2013 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.templating.jsp;
35  
36  import static org.mockito.Mockito.*;
37  
38  import info.magnolia.cms.beans.config.ServerConfiguration;
39  import info.magnolia.cms.core.AggregationState;
40  import info.magnolia.cms.i18n.DefaultI18nContentSupport;
41  import info.magnolia.cms.i18n.DefaultMessagesManager;
42  import info.magnolia.cms.i18n.I18nContentSupport;
43  import info.magnolia.cms.i18n.MessagesManager;
44  import info.magnolia.cms.security.MgnlUser;
45  import info.magnolia.context.ContextFactory;
46  import info.magnolia.context.MgnlContext;
47  import info.magnolia.context.SystemContext;
48  import info.magnolia.context.WebContext;
49  import info.magnolia.jcr.node2bean.Node2BeanProcessor;
50  import info.magnolia.jcr.node2bean.Node2BeanTransformer;
51  import info.magnolia.jcr.node2bean.TypeMapping;
52  import info.magnolia.jcr.node2bean.impl.Node2BeanProcessorImpl;
53  import info.magnolia.jcr.node2bean.impl.Node2BeanTransformerImpl;
54  import info.magnolia.jcr.node2bean.impl.TypeMappingImpl;
55  import info.magnolia.module.ModuleRegistry;
56  import info.magnolia.module.ModuleRegistryImpl;
57  import info.magnolia.rendering.context.AggregationStateBasedRenderingContext;
58  import info.magnolia.rendering.context.RenderingContext;
59  import info.magnolia.rendering.engine.OutputProvider;
60  import info.magnolia.rendering.engine.RenderingEngine;
61  import info.magnolia.rendering.renderer.registry.ConfiguredRendererManager;
62  import info.magnolia.rendering.template.TemplateAvailability;
63  import info.magnolia.rendering.template.assignment.MetaDataBasedTemplateDefinitionAssignment;
64  import info.magnolia.rendering.template.assignment.TemplateDefinitionAssignment;
65  import info.magnolia.rendering.template.configured.ConfiguredTemplateAvailability;
66  import info.magnolia.rendering.template.configured.ConfiguredTemplateDefinition;
67  import info.magnolia.rendering.template.registry.TemplateDefinitionProvider;
68  import info.magnolia.rendering.template.registry.TemplateDefinitionRegistry;
69  import info.magnolia.test.ComponentsTestUtil;
70  import info.magnolia.test.mock.MockContext;
71  import info.magnolia.test.mock.MockHierarchyManager;
72  import info.magnolia.test.mock.MockUtil;
73  import info.magnolia.test.mock.jcr.MockSession;
74  
75  import java.io.File;
76  import java.io.IOException;
77  import java.io.OutputStream;
78  import java.io.StringWriter;
79  import java.net.URL;
80  import java.net.URLDecoder;
81  import java.util.Hashtable;
82  import java.util.Locale;
83  
84  import javax.servlet.http.HttpServletRequest;
85  import javax.servlet.http.HttpServletResponse;
86  
87  import net.sourceforge.openutils.testing4web.TestServletOptions;
88  
89  import org.apache.commons.lang.StringUtils;
90  import org.junit.After;
91  import org.junit.Assert;
92  import org.junit.Before;
93  
94  import com.meterware.httpunit.HttpUnitOptions;
95  import com.meterware.servletunit.ServletRunner;
96  
97  
98  /**
99   * @version $Id$
100  *
101  */
102 public abstract class AbstractTagTestCase {
103 
104     // Global variable
105     protected static final String CONTEXT = "/test-context";
106     protected ServletRunner runner;
107     private WebContext ctx;
108     private MockHierarchyManager session;
109     private HttpServletRequest req;
110     private HttpServletResponse res;
111     private AggregationState aggState;
112     protected RenderingContext renderingContext;
113 
114     @Before
115     public void setUp() throws Exception {
116         // need to pass a web.xml file to setup servletunit working directory
117         final ClassLoader classLoader = getClass().getClassLoader();
118         final URL webXmlUrl = classLoader.getResource("WEB-INF/web.xml");
119         if (webXmlUrl == null) {
120             Assert.fail("Could not find WEB-INF/web.xml");
121         }
122         final String path = URLDecoder.decode(webXmlUrl.getFile(), "UTF-8");
123 
124         HttpUnitOptions.setDefaultCharacterSet("utf-8");
125         System.setProperty("file.encoding", "utf-8");
126 
127         // check we can write in jasper's scratch directory
128         final File jspScratchDir = new File("target/jsp-test-scratch-dir");
129         final String jspScratchDirAbs = jspScratchDir.getAbsolutePath();
130         if (!jspScratchDir.exists()) {
131             Assert.assertTrue("Can't create path " + jspScratchDirAbs + ", aborting test", jspScratchDir.mkdirs());
132         }
133         final File checkFile = new File(jspScratchDir, "empty");
134         Assert.assertTrue("Can't write check file: " + checkFile + ", aborting test", checkFile.createNewFile());
135         Assert.assertTrue("Can't remove check file:" + checkFile + ", aborting test", checkFile.delete());
136 
137         // start servletRunner
138         final Hashtable<String, String> params = new Hashtable<String, String>();
139         params.put("javaEncoding", "utf-8");
140         params.put("development", "true");
141         params.put("keepgenerated", "false");
142         params.put("modificationTestInterval", "1000");
143         params.put("scratchdir", jspScratchDirAbs);
144         params.put("engineOptionsClass", TestServletOptions.class.getName());
145         runner = new ServletRunner(new File(path), CONTEXT);
146         runner.registerServlet("*.jsp", "org.apache.jasper.servlet.JspServlet", params);
147         // setup context
148         session = MockUtil.createAndSetHierarchyManager("website", StringUtils.join(new String[]{
149                 "/foo/bar.@type=mgnl:page",
150                 "/foo/bar.title=Bar title",
151                 "/foo/bar/0.text=hello root 1",
152                 "/foo/bar.mgnl\\:template=testPageTemplate",
153                 "/foo/bar/paragraphs.@type=mgnl:area",
154                 "/foo/bar/paragraphs/0.@type=mgnl:component",
155                 "/foo/bar/paragraphs/0.@uuid=100",
156                 "/foo/bar/paragraphs/1.@type=mgnl:component",
157                 "/foo/bar/paragraphs/1.@uuid=101",
158                 "/foo/bar/paragraphs/1.text=hello 1",
159                 "/foo/bar/paragraphs/1.mgnl\\:template=testParagraph1",
160                 "/foo/bar/paragraphs/1/image.@type=mgnl:resource",
161                 "/foo/bar/paragraphs/1/image.jcr:data=binary:12345",
162                 "/foo/bar/paragraphs/1/image.extension=jpg",
163                 "/foo/bar/paragraphs/1/image.fileName=file",
164 
165         }, "\n"));
166         aggState = new AggregationState();
167         // let's make sure we render stuff on an author instance
168         aggState.setPreviewMode(false);
169         final ServerConfiguration serverCfg = new ServerConfiguration();
170         serverCfg.setAdmin(true);
171 
172         ComponentsTestUtil.setImplementation(TemplateAvailability.class, ConfiguredTemplateAvailability.class);
173         ComponentsTestUtil.setImplementation(ModuleRegistry.class, ModuleRegistryImpl.class);
174         ComponentsTestUtil.setImplementation(ConfiguredRendererManager.class, ConfiguredRendererManager.class);
175 
176         ConfiguredTemplateDefinition testParagraph0 = new ConfiguredTemplateDefinition();
177         testParagraph0.setName("testParagraph0");
178         testParagraph0.setTitle("Test Paragraph 0");
179         ConfiguredTemplateDefinition testParagraph1 = new ConfiguredTemplateDefinition();
180         testParagraph1.setName("testParagraph1");
181         testParagraph1.setTitle("Test Paragraph 1");
182         testParagraph1.setDialog("testDialog");
183         ConfiguredTemplateDefinition testParagraph2 = new ConfiguredTemplateDefinition();
184         testParagraph2.setName("testParagraph2");
185         testParagraph2.setTitle("Test Paragraph 2");
186 
187         final TemplateDefinitionProvider p0provider = mock(TemplateDefinitionProvider.class);
188         final TemplateDefinitionProvider p1provider = mock(TemplateDefinitionProvider.class);
189         final TemplateDefinitionProvider p2provider = mock(TemplateDefinitionProvider.class);
190 
191         when(p0provider.getTemplateDefinition()).thenReturn(testParagraph0);
192         when(p0provider.getId()).thenReturn(testParagraph0.getName());
193         when(p1provider.getTemplateDefinition()).thenReturn(testParagraph1);
194         when(p1provider.getId()).thenReturn(testParagraph1.getName());
195         when(p2provider.getTemplateDefinition()).thenReturn(testParagraph2);
196         when(p2provider.getId()).thenReturn(testParagraph2.getName());
197 
198         ComponentsTestUtil.setInstance(ServerConfiguration.class, serverCfg);
199         // register some default components used internally
200         ComponentsTestUtil.setImplementation(MessagesManager.class, DefaultMessagesManager.class);
201         ComponentsTestUtil.setImplementation(I18nContentSupport.class, DefaultI18nContentSupport.class);
202         ComponentsTestUtil.setImplementation(ContextFactory.class,ContextFactory.class);
203         ComponentsTestUtil.setImplementation(TemplateDefinitionAssignment.class, MetaDataBasedTemplateDefinitionAssignment.class);
204         // configure node2bean because its processor is injected into DefaultMessagesManager constructor
205         ComponentsTestUtil.setImplementation(Node2BeanProcessor.class, Node2BeanProcessorImpl.class);
206         ComponentsTestUtil.setImplementation(TypeMapping.class, TypeMappingImpl.class);
207         ComponentsTestUtil.setImplementation(Node2BeanTransformer.class, Node2BeanTransformerImpl.class);
208 
209         MockContext systemContext = new MockContext();
210         systemContext.addSession("website", session.getJcrSession());
211         ComponentsTestUtil.setInstance(SystemContext.class, systemContext);
212 
213         aggState.setCurrentContentNode(session.getContent("/foo/bar/paragraphs/1").getJCRNode());
214         renderingContext = new AggregationStateBasedRenderingContext(aggState, null);
215         final RenderingEngine renderingEngine = mock(RenderingEngine.class);
216         when(renderingEngine.getRenderingContext()).thenReturn(renderingContext);
217 
218         ComponentsTestUtil.setInstance(RenderingEngine.class, renderingEngine);
219 
220         final TemplateDefinitionRegistry tdr = new TemplateDefinitionRegistry();
221         tdr.register(p0provider);
222         tdr.register(p1provider);
223         tdr.register(p2provider);
224 
225         ComponentsTestUtil.setInstance(TemplateDefinitionRegistry.class, tdr);
226 
227         req = mock(HttpServletRequest.class);
228 
229         res = mock(HttpServletResponse.class);
230         when(res.getWriter()).thenReturn(null);
231         when(res.isCommitted()).thenReturn(true);
232 
233         ctx = mock(WebContext.class);
234         when(ctx.getAggregationState()).thenReturn(aggState);
235         when(ctx.getLocale()).thenReturn(Locale.US);
236         when(ctx.getResponse()).thenReturn(res);
237         when(ctx.getRequest()).thenReturn(req);
238         MgnlUser mockUser = mock(MgnlUser.class);
239         when(mockUser.getLanguage()).thenReturn("en");
240         when(ctx.getUser()).thenReturn(mockUser);
241         when(ctx.getContextPath()).thenReturn("contextPath");
242         when(ctx.getHierarchyManager("website")).thenReturn(session);
243         when(ctx.getJCRSession("website")).thenReturn(session.getJcrSession());
244 
245         setupExpectations(ctx, req);
246 
247         MgnlContext.setInstance(ctx);
248 
249     }
250 
251     @After
252     public void tearDown() throws Exception {
253         MgnlContext.setInstance(null);
254         ComponentsTestUtil.clear();
255     }
256 
257     /**
258      * Hook method - overwrite if you want to set up special expectations.
259      */
260     protected void setupExpectations(WebContext ctx, HttpServletRequest req) {
261         // no specific expectations here
262     }
263 
264     public void setRenderableDefinition(ConfiguredTemplateDefinition renderableDefinition) throws Exception {
265         renderingContext.push(aggState.getCurrentContentNode(), renderableDefinition, new OutputProvider() {
266 
267             @Override
268             public OutputStream getOutputStream() throws IOException {
269                 return null;
270             }
271 
272             @Override
273             public Appendable getAppendable() throws IOException {
274                 return new StringWriter();
275             }
276         });
277     }
278 
279     protected MockSession getSession() {
280         return (MockSession) session.getJcrSession();
281     }
282 }