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
059public abstract class Escaper {
060  // TODO(dbeaumont): evaluate custom implementations, considering package private constructor.
061  /** Constructor for use by subclasses. */
062  protected Escaper() {}
063
064  /**
065   * Returns the escaped form of a given literal string.
066   *
067   * <p>Note that this method may treat input characters differently depending on the specific
068   * escaper implementation.
069   *
070   * <ul>
071   *   <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>
072   *       correctly, including surrogate character pairs. If the input is badly formed the escaper
073   *       should throw {@link IllegalArgumentException}.
074   *   <li>{@link CharEscaper} handles Java characters independently and does not verify the input
075   *       for well formed characters. A {@code CharEscaper} should not be used in situations where
076   *       input is not guaranteed to be restricted to the Basic Multilingual Plane (BMP).
077   * </ul>
078   *
079   * @param string the literal string to be escaped
080   * @return the escaped form of {@code string}
081   * @throws NullPointerException if {@code string} is null
082   * @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be
083   *     escaped for any other reason
084   */
085  public abstract String escape(String string);
086
087  private final Function<String, String> asFunction =
088      new Function<String, String>() {
089        @Override
090        public String apply(String from) {
091          return escape(from);
092        }
093      };
094
095  /** Returns a {@link Function} that invokes {@link #escape(String)} on this escaper. */
096  public final Function<String, String> asFunction() {
097    return asFunction;
098  }
099}