001/* 002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * bstefanescu 011 */ 012package org.nuxeo.ecm.platform.rendering.api; 013 014import java.io.IOException; 015import java.io.OutputStream; 016import java.io.OutputStreamWriter; 017import java.io.Writer; 018import java.nio.charset.Charset; 019import java.util.HashMap; 020import java.util.Map; 021 022/** 023 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 024 */ 025public class View { 026 027 protected RenderingEngine renderingEngine; 028 029 protected String name; 030 031 protected Object object; 032 033 protected Map<String, Object> args; 034 035 public View(RenderingEngine renderingEngine, String name) { 036 this(renderingEngine, name, null); 037 } 038 039 public View(RenderingEngine renderingEngine, String name, Object object) { 040 this.renderingEngine = renderingEngine; 041 this.name = name; 042 this.args = new HashMap<String, Object>(); 043 forObject(object); 044 } 045 046 public String getName() { 047 return name; 048 } 049 050 /** 051 * @return the object 052 */ 053 public Object getObject() { 054 return object; 055 } 056 057 /** 058 * @return the renderingEngine 059 */ 060 public RenderingEngine getRenderingEngine() { 061 return renderingEngine; 062 } 063 064 public View forObject(Object object) { 065 this.object = object; 066 args.put("This", object); 067 return this; 068 } 069 070 public View arg(String key, Object value) { 071 args.put(key, value); 072 return this; 073 } 074 075 public View args(Map<String, Object> args) { 076 this.args.putAll(args); 077 return this; 078 } 079 080 public void render(OutputStream out) throws RenderingException { 081 render(new OutputStreamWriter(out)); 082 } 083 084 public void render(OutputStream out, String charset) throws RenderingException { 085 try { 086 render(new OutputStreamWriter(out, charset)); 087 } catch (RenderingException e) { 088 throw e; 089 } catch (IOException e) { 090 throw new RenderingException(e); 091 } 092 } 093 094 public void render(OutputStream out, Charset charset) throws RenderingException { 095 render(new OutputStreamWriter(out, charset)); 096 } 097 098 public void render(Writer writer) throws RenderingException { 099 try { 100 renderingEngine.render(name, args, writer); 101 } finally { 102 try { 103 writer.flush(); 104 } catch (IOException e) { 105 throw new RenderingException(e); 106 } 107 } 108 } 109 110 @Override 111 public String toString() { 112 return object != null ? object.getClass().getName() + "#" + name : name; 113 } 114 115}