OptionsRenderer implements Renderer { @Override public void render(final String path, final Request request) throws IOException { Matcher matcher = OPTIONS_PATTERN.matcher((String) path); if (null != matcher && matcher.find()) { boolean done = false; String match = matcher.group(1); ListAttribute fallbacks = (ListAttribute) TilesAccess .getCurrentContainer(request) .getAttributeContext(request) .getAttribute(match); if (null == fallbacks) { throw new IllegalStateException("A matching list-attribute name=\"" + match + "\" must be defined."); } else if (fallbacks.getValue().isEmpty()) { throw new IllegalStateException( "list-attribute name=\"" + match + "\" must have minimum one attribute"); } for (Attribute option : (List<Attribute>) fallbacks.getValue()) { String template = path.replaceFirst(Pattern.quote(matcher.group()), (String) option.getValue()); done = renderAttempt(template, request); if (done) { break; } } if (!done) { throw new IOException("None of the options existed for " + path); } } else { renderer.render(path, request); } } OptionsRenderer(final ApplicationContext applicationContext, final Renderer renderer); @Override boolean isRenderable(final String path, final Request request); @Override void render(final String path, final Request request); static final String CACHE_LIFE_PROPERTY; static final long DEFAULT_CACHE_LIFE; static final Pattern OPTIONS_PATTERN; }
@Test public void testWrite() throws IOException { StringWriter writer = new StringWriter(); Request request = createMock(Request.class); requestScope.put(TilesAccess.CURRENT_CONTAINER_ATTRIBUTE_NAME, container); expect(request.getContext(matches("request"))).andReturn(requestScope).anyTimes(); expect(request.getApplicationContext()).andReturn(context); expect(request.getWriter()).andReturn(writer); replay(request); container .getAttributeContext(request) .putAttribute("test-fallback", new ListAttribute(){{ add(new Attribute("Result")); }}); OptionsRenderer renderer = new OptionsRenderer(context, new StringRenderer()); renderer.render("{options[test-fallback]}", request); writer.close(); assertEquals("Not written 'Result'", "Result", writer.toString()); verify(request); }