001    /**
002     * Copyright 2004-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.student.contract.writer;
017    
018    /**
019     *
020     * @author nwright
021     */
022    public class StringQuoter {
023    
024        public static String quote(String value) {
025            if (value == null) {
026                return null;
027            }
028            StringBuffer buf = new StringBuffer(value.length() + 3);
029            buf.append('"');
030            boolean lastCharWasEscape = false;
031            for (int i = 0; i < value.length(); i++) {
032                char c = value.charAt(i);
033                switch (c) {
034                    case '"':
035                        if (!lastCharWasEscape) {
036                            buf.append('\\');
037                        }
038                        lastCharWasEscape = false;
039                        break;
040                    case '\\':
041                        if (!lastCharWasEscape) {
042                            buf.append('\\');
043                        }
044                        lastCharWasEscape = true;
045                        break;
046                    case '\n':
047                    case '\r':
048                        buf.append('"');
049                        buf.append("\n");
050                        buf.append("\t + ");
051                        buf.append('"');
052                        lastCharWasEscape = false;
053                        continue;
054                    default:
055                        lastCharWasEscape = false;
056                }
057                buf.append(c);
058            }
059            buf.append('"');
060            return buf.toString();
061        }
062    }