| Home >> All >> com >> arranger >> jarl >> [ test Javadoc ] |
Source code: com/arranger/jarl/test/XMLPreProcessor.java
1 package com.arranger.jarl.test; 2 3 import junit.framework.TestCase; 4 import org.w3c.dom.Document; 5 6 import java.io.File; 7 import java.util.regex.Pattern; 8 import java.util.regex.Matcher; 9 import java.util.Stack; 10 import java.util.Set; 11 import java.util.HashSet; 12 13 import com.arranger.jarl.util.StringTools; 14 import com.arranger.jarl.util.IOUtil; 15 16 /** 17 * XMLPreProcessor created on Mar 3, 2003 18 */ 19 public class XMLPreProcessor extends TestCase { 20 21 public void testInclude() throws Exception { 22 23 String result = processText(new File("src/com/arranger/jarl/test/testDoc.xml"), new Stack()); 24 System.out.println(result); 25 26 } 27 28 protected String processText(File file, Stack stack) throws Exception { 29 if (stack.contains(file)) { 30 throw new Exception("Recursive include of a file"); 31 } 32 stack.push(file); 33 34 String text = IOUtil.toString(file.getAbsolutePath()); 35 36 //look for <xml:include file=' 37 Pattern pattern = Pattern.compile("<xml:include\\s+file=.+>"); 38 Matcher matcher = pattern.matcher(text); 39 40 StringBuffer buffer = new StringBuffer(); 41 while (matcher.find()) { 42 String includeDirective = matcher.group(); 43 String replacementText = replaceText(includeDirective, stack); 44 matcher.appendReplacement(buffer, replacementText); 45 } 46 matcher.appendTail(buffer); 47 stack.pop(); 48 return buffer.toString(); 49 } 50 51 protected String replaceText(String includeDirective, Stack stack) throws Exception { 52 Pattern pattern = Pattern.compile("[a-zA-Z]+\\.xml"); 53 Matcher matcher = pattern.matcher(includeDirective); 54 if (matcher.find()) { 55 String includedFile = matcher.group(); 56 57 if (!(includedFile.startsWith("/") || ":".equals(includedFile.substring(1, 2)))) { 58 //fix up the included file 59 File parentFile = (File)stack.peek(); 60 includedFile = StringTools.appendPath(parentFile.getParent(), includedFile); 61 } 62 63 return processText(new File(includedFile), stack); 64 } else { 65 return null; 66 } 67 } 68 }