1 36 package org.columba.ristretto.parser; 37 38 import java.io.IOException ; 39 import java.util.regex.Matcher ; 40 import java.util.regex.Pattern ; 41 42 import org.columba.ristretto.io.Source; 43 import org.columba.ristretto.message.Header; 44 45 50 public class HeaderParser { 51 52 private static final Pattern linePattern = Pattern.compile("([^\r\n]*)(\r?\n)|(\r\n?)"); 53 private static final Pattern keyValuePattern = Pattern.compile("([^:\\s]+): (.*)"); 54 private static final Pattern lineWrapPattern = Pattern.compile("\\s(.*)"); 55 56 private HeaderParser() { 57 } 58 69 public static Header parse( Source source ) throws ParserException { 70 Header header = new Header(); 71 Matcher lineMatcher = linePattern.matcher(source); 72 Matcher keyValueMatcher = keyValuePattern.matcher(""); 73 Matcher lineWrapMatcher = lineWrapPattern.matcher(""); 74 75 String lastKey = null; 76 String lastValue = null; 77 78 while(lineMatcher.find()) { 79 if( lineMatcher.group(1) == null) { 81 if( lastValue != null) { 83 header.append(lastKey, lastValue); 84 } 85 86 return header; 88 } 89 90 if( lineMatcher.group(1).equals("")) { 92 if( lastValue != null) { 94 header.append(lastKey, lastValue); 95 } 96 97 try { 99 source.seek(lineMatcher.end()); 100 } catch (IOException e) { 101 e.printStackTrace(); 102 } 103 104 return header; 106 } 107 108 keyValueMatcher.reset(lineMatcher.group(1)); 111 if( keyValueMatcher.matches()) { 112 if( lastValue != null) { 114 header.append(lastKey, lastValue); 115 } 116 117 lastKey = normalizeKey( keyValueMatcher.group(1) ); 119 lastValue = keyValueMatcher.group(2); 120 } else { 121 lineWrapMatcher.reset(lineMatcher.group(1)); 123 if( lineWrapMatcher.matches()) { 124 if(lastValue != null) { 125 lastValue += lineWrapMatcher.group(1); 127 } 128 } 129 130 } 131 } 132 133 if( lastValue != null) { 136 header.append(lastKey, lastValue); 137 } 138 try { 139 source.seek(source.length()-1); 141 } catch (IOException e) { 142 e.printStackTrace(); 143 } 144 145 return header; 146 } 147 148 155 public static String normalizeKey( String key ) { 156 StringBuffer normalizedKey = new StringBuffer ( key.length() ); 157 char last = key.charAt(0); 158 char act; 159 normalizedKey.append(Character.toUpperCase(key.charAt(0))); 160 161 for( int i=1; i<key.length(); i++) { 162 act = key.charAt(i); 163 if( last == '-' || (( last == 'I' || last == 'i') && act == 'd') ) { 164 normalizedKey.append(Character.toUpperCase(act)); 165 } else { 166 normalizedKey.append(Character.toLowerCase(act) ); 167 } 168 last = act; 169 } 170 171 return normalizedKey.toString(); 172 } 173 } 174
| Popular Tags
|