001 /*
002 * Copyright 2001,2004 The Apache Software Foundation.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package org.apache.commons.scaffold.text;
018
019 import java.util.Map;
020
021 /**
022 * Merge utilities.
023 *
024 * @author Ted Husted
025 * @version $Revision: 155464 $ $Date: 2005-02-26 13:26:54 +0000 (Sat, 26 Feb 2005) $
026 */
027 public class Merge {
028
029
030 /**
031 * The token markers for replacement variables, i.e. ${a1}
032 */
033 public static String TOKEN_PREFIX= "${";
034 public static String TOKEN_SUFFIX = "}";
035 private static int TOKEN_PREFIX_LEN = TOKEN_PREFIX.length();
036 private static int TOKEN_SUFFIX_LEN = TOKEN_SUFFIX.length();
037
038
039 /**
040 * Merge a Map of tokens with a template in a StringBuffer.
041 * The parameters are marked by ${key} where (String) Map.get(key)!=null.
042 * The merged content is returned in the same StringBuffer.
043 * Tokens cannot be nested. Unmatched tokens are ignored.
044 *
045 * @param content The text containing merge tokens to be replaced.
046 * @return int Number of replacements made
047 */
048 public static int keys(StringBuffer content, Map tokens) {
049
050 String t = content.toString();
051 int start = t.length();
052 int count = 0;
053
054 while ((start = t.lastIndexOf(TOKEN_PREFIX,start-1)) != -1) {
055
056 int end = t.indexOf(TOKEN_SUFFIX,start);
057 String key = t.substring(start+TOKEN_PREFIX_LEN,end);
058 String value = (String) tokens.get(key);
059 if (value!=null) {
060 content.replace(start,end+TOKEN_SUFFIX_LEN,value);
061 count++;
062 }
063 }
064 return count;
065 }
066 }
067
068 /*
069
070
071 <forward name="bookmark" path = "/do/item/View?key=${key}"/>
072
073 form implements Bookmark;
074
075 forward = findForward("bookmark");
076
077 if (forward!=null) {
078
079 StringBuffer bmPath = new StringBuffer( forward.getPath() );
080
081 merge(bmPath,describe(form));
082
083 Bookmark bmForm = (Bookmark) form;
084 bmForm.setBookmark(bookmark.toString());
085
086 }
087
088 ...
089
090 if (isBookmark())
091 return getBookmarkForward();
092 return findForward("continue");
093
094
095 */