001 /**
002 * Copyright 2005-2014 The Kuali Foundation
003 *
004 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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 package org.kuali.rice.kew.messaging;
017
018 import java.util.ArrayList;
019 import java.util.List;
020
021
022 /**
023 * A simple utility class which can handle translated a comma-seperated String
024 * into an array of String paramters and vice-versa.
025 *
026 * @author Kuali Rice Team (rice.collab@kuali.org)
027 */
028 public class ParameterTranslator {
029
030 private static final String SLASH_REGEXP = "\\\\";
031 private static final String SLASH_ESCAPE = "\\\\";
032 private static final String COMMA_REGEXP = ",";
033 private static final String COMMA_ESCAPE = "\\,";
034
035 private String untranslatedString = "";
036
037 public ParameterTranslator() {}
038
039 public ParameterTranslator(String untranslatedString) {
040 this.untranslatedString = untranslatedString;
041 }
042
043 public void addParameter(String value) {
044 if (!org.apache.commons.lang.StringUtils.isEmpty(untranslatedString)) {
045 untranslatedString += ",";
046 }
047 untranslatedString += escape(value);
048 }
049
050 private String escape(String value) {
051 if (org.apache.commons.lang.StringUtils.isEmpty(value)) {
052 return "";
053 }
054 // escape '\' and ',' with "\\" and "\,"
055 value = value.replaceAll(SLASH_REGEXP, SLASH_ESCAPE);
056 value = value.replaceAll(COMMA_REGEXP, COMMA_ESCAPE);
057 return value;
058 }
059
060 public String getUntranslatedString() {
061 return untranslatedString;
062 }
063
064 public String[] getParameters() {
065 List strings = new ArrayList();
066 boolean isEscaped = false;
067 StringBuffer buffer = null;
068 for (int index = 0; index < untranslatedString.length(); index++) {
069 char character = untranslatedString.charAt(index);
070 if (isEscaped) {
071 isEscaped = false;
072 if (buffer == null) {
073 buffer = new StringBuffer();
074 }
075 buffer.append(character);
076 } else {
077 if (character == '\\') {
078 isEscaped = true;
079 } else if (character == ',') {
080 strings.add(buffer.toString());
081 buffer = null;
082 } else {
083 if (buffer == null) {
084 buffer = new StringBuffer();
085 }
086 buffer.append(character);
087 }
088 }
089 }
090 // put whatever is left in the buffer (after the last ',') into the list of strings
091 if (buffer != null) {
092 strings.add(buffer.toString());
093 }
094 return (String[])strings.toArray(new String[0]);
095 }
096
097 }