All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.google.gwt.dev.codeserver.HtmlWriter Maven / Gradle / Ivy

There is a newer version: 2.10.0
Show newest version
// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.gwt.dev.codeserver;

import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Writes HTML to a stream.
 *
 * @author [email protected] (Brian Slesinsky)
 */
class HtmlWriter {
  private static final Set ALLOWED_TAGS =
      Collections.unmodifiableSet(new HashSet(Arrays.asList(
          "html", "head", "title", "style",
          "body", "h1", "h2", "h3", "h4", "h5", "h6", "a", "pre", "span",
          "table", "tr", "td")));
  private static final Set ALLOWED_ATTS =
      Collections.unmodifiableSet(new HashSet(Arrays.asList(
          "class=", "href=")));

  private final Writer out;

  HtmlWriter(Writer out) {
    this.out = out;
  }

  HtmlWriter startTag(String tag) throws IOException {
    checkTag(tag);
    out.write('<');
    out.write(tag);
    out.write('>');
    return this;
  }

  HtmlWriter startTag(String tag, String att, String value) throws IOException {
    checkTag(tag);
    out.write('<');
    out.write(tag);
    writeAtt(att, value);
    out.write('>');
    return this;
  }

  HtmlWriter endTag(String tag) throws IOException {
    checkTag(tag);
    out.write("');
    return this;
  }

  /**
   * Writes plain text (escaped).
   */
  HtmlWriter text(String plainText) throws IOException {
    for (char c : plainText.toCharArray()) {
      text(c);
    }
    return this;
  }

  /**
   * Writes plain text (escaped).
   */
  void text(char c) throws IOException {
    switch(c) {
      case '<':
        out.write("<");
        break;
      case '>':
        out.write(">");
        break;
      case '&':
        out.write("&");
        break;
      case '"':
        out.write(""");
        break;
      default:
        out.write(c);
    }
  }

  /**
   * Writes a newline.
   */
  void nl() throws IOException {
    out.append('\n');
  }

  private void writeAtt(String att, String value) throws IOException {
    checkAtt(att);
    out.write(' ');
    out.write(att);
    out.write('"');
    text(value);
    out.write('"');
  }

  private void checkTag(String tag) {
    if (!ALLOWED_TAGS.contains(tag)) {
      throw new IllegalArgumentException("unknown tag: " + tag);
    }
  }

  private void checkAtt(String att) {
    if (!ALLOWED_ATTS.contains(att)) {
      throw new IllegalArgumentException("unknown att: " + att);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy