001/* 002 * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Nuxeo - initial API and implementation 016 * 017 * $Id$ 018 */ 019 020package org.nuxeo.runtime.deployment.preprocessor.template; 021 022import java.io.BufferedInputStream; 023import java.io.File; 024import java.io.FileInputStream; 025import java.io.IOException; 026import java.io.InputStream; 027import java.net.URL; 028 029import org.nuxeo.common.utils.FileUtils; 030 031/** 032 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 033 */ 034public class TemplateParser { 035 036 // Utility class. 037 private TemplateParser() { 038 } 039 040 public static Template parse(File file) throws IOException { 041 InputStream in = null; 042 try { 043 in = new BufferedInputStream(new FileInputStream(file)); 044 return parse(in); 045 } finally { 046 if (in != null) { 047 in.close(); 048 } 049 } 050 } 051 052 public static Template parse(URL url) throws IOException { 053 InputStream in = null; 054 try { 055 in = new BufferedInputStream(url.openStream()); 056 return parse(in); 057 } finally { 058 if (in != null) { 059 in.close(); 060 } 061 } 062 } 063 064 public static Template parse(InputStream in) throws IOException { 065 String s = FileUtils.read(in); 066 return parse(s.toCharArray()); 067 } 068 069 public static Template parse(char[] chars) { 070 Template tpl = new Template(); 071 StringBuilder buf = new StringBuilder(); 072 StringBuilder name = new StringBuilder(); 073 074 // add the begin part 075 tpl.addPart(Template.BEGIN, null); 076 077 boolean marker = false; 078 for (int i = 0; i < chars.length; i++) { 079 char ch = chars[i]; 080 switch (ch) { 081 case '%': 082 if (i < chars.length && chars[i + 1] == '{') { 083 marker = true; 084 i++; 085 } else { 086 if (marker) { 087 name.append(ch); 088 } else { 089 buf.append(ch); 090 } 091 } 092 break; 093 case '}': 094 if (i < chars.length && chars[i + 1] == '%') { 095 marker = false; 096 i++; 097 // create a new Part: 098 tpl.addPart(name.toString(), buf.toString()); 099 name.setLength(0); 100 buf.setLength(0); 101 } else { 102 if (marker) { 103 name.append(ch); 104 } else { 105 buf.append(ch); 106 } 107 } 108 break; 109 default: 110 if (marker) { 111 name.append(ch); 112 } else { 113 buf.append(ch); 114 } 115 break; 116 } 117 } 118 119 // create the END part 120 tpl.addPart(Template.END, buf.toString()); 121 122 return tpl; 123 } 124 125}