001/** 002 * GRANITE DATA SERVICES 003 * Copyright (C) 2006-2014 GRANITE DATA SERVICES S.A.S. 004 * 005 * This file is part of the Granite Data Services Platform. 006 * 007 * Granite Data Services is free software; you can redistribute it and/or 008 * modify it under the terms of the GNU Lesser General Public 009 * License as published by the Free Software Foundation; either 010 * version 2.1 of the License, or (at your option) any later version. 011 * 012 * Granite Data Services is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 015 * General Public License for more details. 016 * 017 * You should have received a copy of the GNU Lesser General Public 018 * License along with this library; if not, write to the Free Software 019 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 020 * USA, or see <http://www.gnu.org/licenses/>. 021 */ 022package org.granite.generator.gsp; 023 024import java.util.List; 025 026import org.granite.generator.gsp.token.Comment; 027import org.granite.generator.gsp.token.Expression; 028import org.granite.generator.gsp.token.Scriplet; 029import org.granite.generator.gsp.token.TemplateText; 030import org.granite.generator.gsp.token.Token; 031 032/** 033 * @author Franck WOLFF 034 */ 035public class GroovyRenderer implements Renderer { 036 037 private String source = null; 038 039 @Override 040 public String renderSource(List<Token> tokens) { 041 return renderSource(tokens, null); 042 } 043 044 @Override 045 public String renderSource(List<Token> tokens, String out) { 046 StringBuilder sb = new StringBuilder(1024); 047 048 for (Token token : tokens) { 049 if (token instanceof TemplateText) { 050 String content = token.getContent(); 051 052 if (content.length() > 0) { 053 int iLast = content.length() - 1; 054 sb.append("print(\""); 055 056 for (int i = 0; i < content.length(); i++) { 057 char c = content.charAt(i); 058 059 switch (c) { 060 case '\\': 061 sb.append("\\\\"); 062 break; 063 case '"' : 064 sb.append("\\\""); 065 break; 066 case '\n': 067 sb.append("\\n\");\n"); 068 if (i < iLast) 069 sb.append("print(\""); 070 break; 071 case '\f': 072 sb.append("\\f"); 073 break; 074 default : 075 sb.append(c); 076 break; 077 } 078 } 079 080 if (content.charAt(iLast) != '\n') 081 sb.append("\");\n"); 082 } 083 } 084 else if (token instanceof Expression) 085 sb.append("print(").append(token.getContent()).append(");\n"); 086 else if (token instanceof Scriplet) 087 sb.append(token.getContent()).append('\n'); 088 else if (!(token instanceof Comment)) 089 throw new UnsupportedOperationException("Unsupported token (not implemented): " + token); 090 } 091 092 source = sb.toString(); 093 094 return source; 095 } 096 097 @Override 098 public String getSource() { 099 return source; 100 } 101}