001 package com.nativelibs4java.velocity;
002
003 import com.google.common.base.Function;
004 import java.io.BufferedReader;
005 import java.io.File;
006 import java.io.FileReader;
007 import java.io.FileWriter;
008 import java.io.IOException;
009 import java.io.PrintWriter;
010 import java.io.StringWriter;
011 import java.util.regex.Matcher;
012 import java.util.regex.Pattern;
013
014 public class Utils {
015
016
017 protected static String processComments(String source, Function<String, String> processor) {
018 Pattern p = Pattern.compile("(?m)(?s)/\\*\\*?.*?\\*/");
019 Matcher m = p.matcher(source);
020 StringBuffer sb = new StringBuffer();
021 while (m.find()) {
022 String comment = m.group();
023 String replacement = processor.apply(comment);
024 m.appendReplacement(sb, "");
025 sb.append(replacement);
026 }
027 m.appendTail(sb);
028 return sb.toString();
029 }
030
031 protected static String quoteSharpsInComments(String source) {
032 return processComments(source, new Function<String, String>() {
033 public String apply(String f) {
034 return f.replaceAll("#", "\\\\#");
035 }
036 });
037 }
038
039 protected static String unquoteSharpsInComments(String source) {
040 return processComments(source, new Function<String, String>() {
041 public String apply(String f) {
042 return f.replaceAll("\\\\#", "#");
043 }
044 });
045 }
046
047 static String readTextFile(File file) throws IOException {
048 BufferedReader sourceIn = new BufferedReader(new FileReader(file));
049 StringWriter sourceOut = new StringWriter();
050 PrintWriter sourcePOut = new PrintWriter(sourceOut);
051 String line;
052 while ((line = sourceIn.readLine()) != null) {
053 sourcePOut.println(line);
054 }
055 return sourceOut.toString();
056 }
057
058 static void writeTextFile(File file, String text) throws IOException {
059 FileWriter f = new FileWriter(file);
060 f.write(unquoteSharpsInComments(text));
061 f.close();
062 }
063 }