package JDBCTest;

import java.sql.*;

/**
 *  Description of the Class
 *
 * @author     Danny Ayers
 * @created    25 February 2001
 *
 * extended by Jos Aerts (July 2001)
 */
public class JDBCToXML {

  public final static String PROLOG = "<?xml version=\"1.0\"?>\n\n";
  public final static String OPEN_START = "<";
  public final static String SIMPLE_CLOSE = "/>";
  public final static String OPEN_END = "</";
  public final static String CLOSE = ">";
  public final static String NEWLINE = "\n";
//  public final static String INDENT = "\t";
  public final static String INDENT = "  ";
  
  private String docname = new String("document");
  private String recordname = new String("record");
  private String doctypeline;
  private boolean asAttribute = false;
  
  public void setRecordName(String s) {
    recordname = s;
  }
  
  public void setDocumentName(String s) {
    docname = s;
  }

  public void setDoctype(boolean external, String dtd) {
    doctypeline = "<!DOCTYPE " + docname + " ";
    doctypeline += external ? "SYSTEM" : "PUBLIC ";
    doctypeline += " \"" + dtd + "\">\n";
  }

  public void setAsAttribute(boolean aa) {
    asAttribute = aa;
  }

  public String getXML(ResultSet rs) {

    StringBuffer xml = new StringBuffer(PROLOG + doctypeline);
    xml.append(NEWLINE + OPEN_START + docname + CLOSE);
    String data;

    try {
      ResultSetMetaData rsmeta = rs.getMetaData();
      int nfields = rsmeta.getColumnCount();
      if (asAttribute == true) {
      // The following gives records like : <entry ENAME="SMITH SAL="800"/>
        while (rs.next()) {
          xml.append(NEWLINE + INDENT + OPEN_START + recordname + " ");
          for (int i = 1; i < nfields + 1; i++) {
            xml.append(rsmeta.getColumnName(i) + "=\"");
            data = XMLUtil.encodeChars(rs.getObject(i).toString());
            xml.append(data + "\" ");
          }
          xml.append(SIMPLE_CLOSE);
        }
      } else {
      // ALTERNATIVE introduced by J.Aerts
      // the following gives records like : <entry><ENAME>Smith</ENAME><SAL>800</SAL></entry>
        while (rs.next()) {
          xml.append(NEWLINE + INDENT + OPEN_START + recordname + CLOSE);
          for (int i = 1; i < nfields + 1; i++) {
            xml.append(NEWLINE + INDENT + INDENT + OPEN_START + rsmeta.getColumnName(i) + CLOSE);
            data = XMLUtil.encodeChars(rs.getObject(i).toString());
            xml.append(data + OPEN_END + rsmeta.getColumnName(i) + CLOSE);
          }
        xml.append(NEWLINE + INDENT + OPEN_END + recordname + CLOSE);
        }
      // END OF ALTERNATIVE
      }
      xml.append(NEWLINE + OPEN_END + docname + CLOSE);
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Could not get the results out of the resultset");
    }

    return xml.toString();
  }

}
