package moreservlets.filters;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

/** Filter that replaces all occurrences of a given
 *  string with a replacement. This is an abstract class:
 *  you <I>must</I> override the getTargetString and
 *  getReplacementString methods in a subclass. The
 *  first of these methods specifies the string in
 *  the response that should be replaced. The second
 *  of these specifies the string that should replace
 *  each occurrence of the target string.
 *  <P>
 *  Taken from More Servlets and JavaServer Pages
 *  from Prentice Hall and Sun Microsystems Press,
 *  http://www.moreservlets.com/.
 *  &copy; 2002 Marty Hall; may be freely used or adapted.
 */

public abstract class ReplaceFilter implements Filter {
  private FilterConfig config;

  public void doFilter(ServletRequest request,
                       ServletResponse response,
                       FilterChain chain)
      throws ServletException, IOException {
    CharArrayWrapper responseWrapper =
      new CharArrayWrapper((HttpServletResponse)response);
    // Invoke resource, accumulating output in the wrapper.
    chain.doFilter(request,responseWrapper);
    // Turn entire output into one big String.
    String responseString = responseWrapper.toString();
    // In output, replace all occurrences of target string
    // with replacement string.
    responseString =
      FilterUtils.replace(responseString,
                          getTargetString(),
                          getReplacementString());
    PrintWriter out = response.getWriter();
    out.write(responseString);
  }

  /** Store the FilterConfig object in case subclasses
   *  want it.
   */

  public void init(FilterConfig config)
      throws ServletException {
    this.config = config;
  }

  protected FilterConfig getFilterConfig() {
    return(config);
  }

  public void destroy() {}

  /** The string that needs replacement.
   *  Override this method in your subclass.
   */

  public abstract String getTargetString();

  /** The string that replaces the target.
   *  Override this method in your subclass.
   */

  public abstract String getReplacementString();
}
