1 /* 2 * Copyright 2001,2004 The Apache Software Foundation. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package org.apache.commons.scaffold.text; 18 19 import java.util.Map; 20 21 /** 22 * Merge utilities. 23 * 24 * @author Ted Husted 25 * @version $Revision: 155464 $ $Date: 2005-02-26 13:26:54 +0000 (Sat, 26 Feb 2005) $ 26 */ 27 public class Merge { 28 29 30 /** 31 * The token markers for replacement variables, i.e. ${a1} 32 */ 33 public static String TOKEN_PREFIX= "${"; 34 public static String TOKEN_SUFFIX = "}"; 35 private static int TOKEN_PREFIX_LEN = TOKEN_PREFIX.length(); 36 private static int TOKEN_SUFFIX_LEN = TOKEN_SUFFIX.length(); 37 38 39 /** 40 * Merge a Map of tokens with a template in a StringBuffer. 41 * The parameters are marked by ${key} where (String) Map.get(key)!=null. 42 * The merged content is returned in the same StringBuffer. 43 * Tokens cannot be nested. Unmatched tokens are ignored. 44 * 45 * @param content The text containing merge tokens to be replaced. 46 * @return int Number of replacements made 47 */ 48 public static int keys(StringBuffer content, Map tokens) { 49 50 String t = content.toString(); 51 int start = t.length(); 52 int count = 0; 53 54 while ((start = t.lastIndexOf(TOKEN_PREFIX,start-1)) != -1) { 55 56 int end = t.indexOf(TOKEN_SUFFIX,start); 57 String key = t.substring(start+TOKEN_PREFIX_LEN,end); 58 String value = (String) tokens.get(key); 59 if (value!=null) { 60 content.replace(start,end+TOKEN_SUFFIX_LEN,value); 61 count++; 62 } 63 } 64 return count; 65 } 66 } 67 68 /* 69 70 71 <forward name="bookmark" path = "/do/item/View?key=${key}"/> 72 73 form implements Bookmark; 74 75 forward = findForward("bookmark"); 76 77 if (forward!=null) { 78 79 StringBuffer bmPath = new StringBuffer( forward.getPath() ); 80 81 merge(bmPath,describe(form)); 82 83 Bookmark bmForm = (Bookmark) form; 84 bmForm.setBookmark(bookmark.toString()); 85 86 } 87 88 ... 89 90 if (isBookmark()) 91 return getBookmarkForward(); 92 return findForward("continue"); 93 94 95 */