/*
 * Relational_1.java
 * 
 * Copyright 2004-2006 by SAP AG. All Rights Reserved.
 * SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, and other SAP 
 * products and services mentioned herein as well as their respective logos 
 * are trademarks or registered trademarks of SAP AG in Germany and in several 
 * other countries all over the world. All other product and service names 
 * mentioned are the trademarks of their respective companies. Data contained 
 * in this document serves informational purposes only. National product 
 * specifications may vary.
 *
 * These materials are subject to change without notice. These materials are 
 * provided by SAP AG and its affiliated companies ("SAP Group") for 
 * informational purposes only, without representation or warranty of any kind, 
 * and SAP Group shall not be liable for errors or omissions with respect to 
 * the materials. The only warranties for SAP Group products and services are 
 * those that are set forth in the express warranty statements accompanying 
 * such products and services, if any. Nothing herein should be construed as 
 * constituting an additional warranty.
 */
package com.sap.ip.bi.sdk.samples;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.omg.cwm.resource.relational.Catalog;
import org.omg.cwm.resource.relational.Column;
import org.omg.cwm.resource.relational.Schema;
import org.omg.cwm.resource.relational.Table;

import com.sap.exception.IBaseException;
import com.sap.ip.bi.sdk.dac.connector.IBIConnection;
import com.sap.ip.bi.sdk.dac.connector.IBIRelational;
import com.sap.ip.bi.sdk.samples.servlet.MinimalServletContainer;

/**
 * Accessing metadata -
 *
 * Illustrates the process of retrieving relational metadata from
 * catalog to column from a JDBC data source.
 *
 * View the HTML rendered by this servlet in the following file:
 * [SDK archive]/docs/examples/relational_1.result.html
 *
 * @author  SAP
 * @version 3.50
 * @since 3.50
 */
public class Relational_1 extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html";

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

  public void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {

    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();

    out.println(Helpers.getDocTypeDefinition());
    out.println("<html>");
    out.println("<head><title>Relational_1</title>");
    out.println(Helpers.getStyleSheetDefinition());
    out.println("</head><body>");

    try {
      // ********************************************************
      // Connect to a JDBC database via the BI JDBC Connector.
      // ********************************************************
      IBIConnection connection = Helpers.connectToJDBCDatasource(out);
      IBIRelational rel = connection.getRelational();

      // create JDBC sample data where needed
      Helpers.createJDBCSampleData();

      // ********************************************************
      // Retrieve metadata.
      // ********************************************************

      // Get the collection of catalogs.
      List catalogs = rel.getCatalog();
      // Navigate list of org.omg.cwm.resource.relational.Catalog
      // instances.
      int count = 0;
      out.println("<h3>Catalogs:</h3>");
      for (Iterator i = catalogs.iterator(); i.hasNext();) {
        count++;
        Catalog catalog = (Catalog) i.next();
        out.print(
          "\"<span class=\"code\">" + catalog.getName() + "</span>\"");
        if ("".equals(catalog.getName())) {
          out.println(" (dummy catalog)");
        }
        out.println("<br>");
        if (count > 10) {
          // print only the first 10 items
          out.println("&hellip;<br>");
          break;
        }
      }
      if (count == 0
        || (count == 1
          && "".equals(((Catalog) catalogs.get(0)).getName()))) {
        out.println("(catalogs not supported in this data source)");
      }
      out.println("<p>");

      // Get the collection of schemas.
      List schemas = rel.getSchema();
      // Navigate list of org.omg.cwm.resource.relational.Schema 
      // instances.
      count = 0;
      out.println("<h3>Schemas:</h3>");
      for (Iterator i = schemas.iterator(); i.hasNext();) {
        count++;
        Schema schema = (Schema) i.next();
        out.print(
          "\"<span class=\"code\">" + schema.getName() + "</span>\"");
        if ("".equals(schema.getName())) {
          out.println(" (dummy schema)");
          ;
        }
        out.println("<br>");
        if (count > 10) {
          // print only the first 10 items
          out.println("&hellip;<br>");
          break;
        }
      }
      if (count == 0
        || (count == 1
          && "".equals(((Schema) schemas.get(0)).getName()))) {
        out.println("(schemas not supported in this data source)");
      }
      out.println("<p>");

      // Get the collection of tables.
      List tables = rel.getTable();
      // Navigate list of org.omg.cwm.resource.relational.Table 
      // instances.
      count = 0;
      out.println("<h3>Tables:</h3>");
      Table tab = null;
      out.println("<table border=\"1\">");
      out.println("<tr><td class=\"headCenter\">Table Names</td></tr>");
      int s = 0;
      for (Iterator i = tables.iterator(); i.hasNext();) {
        String style = (s & 1) == 1 ? "\"odd\"" : "\"even\"";
        s++;
        count++;
        Table table = (Table) i.next();
        if (tab == null) {
          // save the first table
          tab = table;
        }
        out.println(
          "<tr>"
            + "<td class="
            + style
            + ">\"<span class=\"code\">"
            + table.getName()
            + "</span>\"</td></tr>");
        if (count > 10) {
          // print only the first 10 items
          out.println("<tr><td class=" + style + ">&hellip;</td></tr>");
          break;
        }
      }
      out.println("</table><p>");

      // display details of the first table
      if (tab != null) {
        out.println("<h3>Schema Navigation:</h3>");
        // display the catalog/schema/columns of the first 
        // table
        String schemaName = null;
        String catalogName = null;
        String tableName =
          "\"<span class=\"code\">" + tab.getName() + "</span>\"";
        if (tab.getNamespace() != null) {
          schemaName =
            "\"<span class=\"code\">"
              + ((Schema) tab.getNamespace()).getName()
              + "</span>\"";
          if (tab.getNamespace().getNamespace() != null) {
            catalogName =
              "\"<span class=\"code\">"
                + ((Catalog) tab.getNamespace().getNamespace()).getName()
                + "</span>\"";
          }
        }
        out.println(
          "<table border=\"1\"><tr>"
            + "<td class=\"headCenter\">Catalogs</td>"
            + "<td class=\"headCenter\">Schemas</td>"
            + "<td class=\"headCenter\">Tables</td>"
            + "<td class=\"headCenter\">Columns</td>"
            + "</tr>");
        s = 0;
        count = 0;
        List cols = tab.getFeature();
        String style = "\"even\"";
        for (Iterator i = cols.iterator(); i.hasNext();) {
          s++;
          count++;
          Column col = (Column) i.next();
          out.println(
            "<tr>"
              + "<td class="
              + style
              + ">"
              + "<span class=\"code\">"
              + catalogName
              + "</span></td>"
              + "<td class="
              + style
              + ">"
              + "<span class=\"code\">"
              + schemaName
              + "</span></td>"
              + "<td class="
              + style
              + ">"
              + "<span class=\"code\">"
              + tableName
              + "</span></td>"
              + "<td class="
              + style
              + ">"
              + "<span class=\"code\">\""
              + col.getName()
              + "</span>\"</td>"
              + "</tr>");
          style = (s & 1) == 1 ? "\"odd\"" : "\"even\"";
          if (count > 10) {
            // print only the first 10 items
            out.println(
              "<tr><td colspan=\"4\" class=" + style + ">&hellip;</td></tr>");
            break;
          }
          catalogName = schemaName = tableName = "";
        }
        out.println("</table>");
      }
    } 
    // Catch errors.
    catch (Exception e) {
      // $JL-EXC$
      e.printStackTrace();
      if (e instanceof IBaseException)
        out.println("Error: " +
                ((IBaseException)e).getNestedLocalizedMessage());
      else  
        out.println("Error: " + e.getMessage());        
    }

    out.println("</body>");
    out.println("</html>");
  }

  public void destroy() {
  }

  public static void main(String[] args) {

    if (args.length == 1) {
      MinimalServletContainer.executeServlet(
        new Relational_1(),
        args[0]);
    } else {
      MinimalServletContainer.executeServlet(
        new Relational_1(),
        System.out);
    }
  }

}