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