001/*
002 * Copyright (C) 2008 The Guava Authors
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
017package com.google.common.escape;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021import com.google.common.base.Function;
022
023/**
024 * An object that converts literal text into a format safe for inclusion in a particular context
025 * (such as an XML document). Typically (but not always), the inverse process of "unescaping" the
026 * text is performed automatically by the relevant parser.
027 *
028 * <p>For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code
029 * "Foo&lt;Bar&gt;"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the
030 * resulting XML document is parsed, the parser API will return this text as the original literal
031 * string {@code "Foo<Bar>"}.
032 *
033 * <p>An {@code Escaper} instance is required to be stateless, and safe when used concurrently by
034 * multiple threads.
035 *
036 * <p>Because, in general, escaping operates on the code points of a string and not on its
037 * individual {@code char} values, it is not safe to assume that {@code escape(s)} is equivalent to
038 * {@code escape(s.substring(0, n)) + escape(s.substing(n))} for arbitrary {@code n}. This is
039 * because of the possibility of splitting a surrogate pair. The only case in which it is safe to
040 * escape strings and concatenate the results is if you can rule out this possibility, either by
041 * splitting an existing long string into short strings adaptively around {@linkplain
042 * Character#isHighSurrogate surrogate} {@linkplain Character#isLowSurrogate pairs}, or by starting
043 * with short strings already known to be free of unpaired surrogates.
044 *
045 * <p>The two primary implementations of this interface are {@link CharEscaper} and {@link
046 * UnicodeEscaper}. They are heavily optimized for performance and greatly simplify the task of
047 * implementing new escapers. It is strongly recommended that when implementing a new escaper you
048 * extend one of these classes. If you find that you are unable to achieve the desired behavior
049 * using either of these classes, please contact the Java libraries team for advice.
050 *
051 * <p>Several popular escapers are defined as constants in classes like {@link
052 * com.google.common.html.HtmlEscapers}, {@link com.google.common.xml.XmlEscapers}, and {@link
053 * SourceCodeEscapers}. To create your own escapers, use {@link CharEscaperBuilder}, or extend
054 * {@code CharEscaper} or {@code UnicodeEscaper}.
055 *
056 * @author David Beaumont
057 * @since 15.0
058 */
059@Beta
060@GwtCompatible
061public abstract class Escaper {
062  // TODO(user): evaluate custom implementations, considering package private constructor.
063  /** Constructor for use by subclasses. */
064  protected Escaper() {}
065
066  /**
067   * Returns the escaped form of a given literal string.
068   *
069   * <p>Note that this method may treat input characters differently depending on the specific
070   * escaper implementation.
071   *
072   * <ul>
073   * <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>
074   *     correctly, including surrogate character pairs. If the input is badly formed the escaper
075   *     should throw {@link IllegalArgumentException}.
076   * <li>{@link CharEscaper} handles Java characters independently and does not verify the input for
077   *     well formed characters. A {@code CharEscaper} should not be used in situations where input
078   *     is not guaranteed to be restricted to the Basic Multilingual Plane (BMP).
079   * </ul>
080   *
081   * @param string the literal string to be escaped
082   * @return the escaped form of {@code string}
083   * @throws NullPointerException if {@code string} is null
084   * @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be
085   *         escaped for any other reason
086   */
087  public abstract String escape(String string);
088
089  private final Function<String, String> asFunction =
090      new Function<String, String>() {
091        @Override
092        public String apply(String from) {
093          return escape(from);
094        }
095      };
096
097  /**
098   * Returns a {@link Function} that invokes {@link #escape(String)} on this escaper.
099   */
100  public final Function<String, String> asFunction() {
101    return asFunction;
102  }
103}