/*
 * Relational_2.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.dac.connector.IBIRelationalObjectFinder;
import com.sap.ip.bi.sdk.samples.servlet.MinimalServletContainer;

/**
 * Accessing metadata 2 - 
 *
 * Demonstrates three different ways to retrieve relational metadata:
 * 
 * 1. via connection-level methods
 * 2. via ObjectFinder methods
 * 3. via JMI methods
 *
 * View the HTML rendered by this servlet in the following file:
 * [SDK archive]/docs/examples/relational_2.result.html
 *
 * @author  SAP
 * @version 3.50
 * @since   3.50
 */
public class Relational_2 extends HttpServlet {
  private final static 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 {

    String sep = "";

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

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

    try {

      // ********************************************************
      // Connect to a data source.
      // ********************************************************
      IBIConnection connection = Helpers.connectToJDBCDatasource(out);
      IBIRelational rel = connection.getRelational();

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

      //************************************************
      // Retrieve metadata via 
      // connection-level methods: getCatalog(), getSchema(), 
      // getTable().
      // These methods allow you to browse metadata objects such 
      // as schemas and tables.
      // Typically, the retrieved objects are used then as an 
      // entry point to further "navigate" to objects that are
      // contained in these name-space-like objects.
      //************************************************ 
      out.println("<h3>Accessing metadata via connection-level methods</h3>");

      // the list of catalogs contained in the connected resource
      List catalogs = rel.getCatalog();
      out.println("<h4>Retrieving catalogs with rel.getCatalog()</h4>");
      out.println("<p>");
      sep = "";
      int count = 0;
      for (int i = 0; i < catalogs.size(); i++) {
        count++;
        Catalog catalog = (Catalog) catalogs.get(i);
        out.print(
          sep + "\"<span class=\"code\">" + catalog.getName() + "</span>\"");
        if ("".equals(catalog.getName())) {
          out.print(" (dummy catalog)");
        }
        sep = ", ";
      }
      if (count == 0
        || (count == 1 && "".equals(((Catalog) catalogs.get(0)).getName()))) {
        out.println("<br>(catalogs not supported in this data source)");
      }
      out.println("<p>");

      // the list of schemas contained in the connected resource
      List schemas = rel.getSchema();
      out.println("<h4>Retrieving schemas with rel.getSchema()</h4>");
      out.println("<p>");
      sep = "";
      count = 0;
      for (int i = 0; i < schemas.size(); i++) {
        count++;
        Schema schema = (Schema) schemas.get(i);
        out.print(
          sep + "\"<span class=\"code\">" + schema.getName() + "</span>\"");
        if ("".equals(schema.getName())) {
          out.print(" (dummy schema)");
        }
        sep = ", ";
      }
      if (count == 0
        || (count == 1 && "".equals(((Schema) schemas.get(0)).getName()))) {
        out.println("<br>(schemas not supported in this data source)");
      }
      out.println("<p>");

      //*********************************************************     
      // Retrieve metadata via ObjectFinder methods -
      // these methods provide the ability to retrieve a specific 
      // object or a set of objects.
      //*********************************************************     

      IBIRelationalObjectFinder finder = rel.getObjectFinder();
      out.println("<hr><h3>Accessing metadata via object finder methods</h3>");

      // retrieve a specific table
      Table table =
        (Table) finder.findTable((String) null, (String) null, "%").get(0);
      out.println(
        "<h4>Find method findCube(String catalogName,String schemaName, String tableNamePattern)</h4>");
      out.println("<p>Found cube: " + table.getName() + "</p>");
      out.println("<p>");

      //*********************************************************
      // Retrieve metadata via CWM-based JMI interfaces -
      // starting from the top-level objects of the Relational 
      // Metadata Model, such as Table, you can the use the 
      // JMI interfaces provided by each object to "navigate" to 
      // associated objects. 
      // The following code passage shows how to retrieve from a 
      // given table its associated columns and the schema and 
      // catalog to which it belongs.
      //*********************************************************

      out.println("<hr><h3>Accessing metadata via JMI methods</h3>");

      // retrieve from a given table its schema and catalog
      String tableName = table.getName();
      out.println(
        "<h4>Retrieving schema and catalog of table \""
          + tableName
          + "\"</h4>");
      Schema schema = (Schema) table.getNamespace();
      if (schema != null) {
        out.println(
          "<p>Schema of " + tableName + ": \"" + schema.getName() + "\"</p>");
        Catalog catalog = (Catalog) schema.getNamespace();
        out.println(
          "<p>Catalog of "
            + tableName
            + ":"
            + " \""
            + catalog.getName()
            + " \""
            + "</p>");
      }
      out.println("<p>");

      // retrieve from a given table its list of columns
      out.println("<h4>Iterating the list of columns of a table</h4>");
      Iterator itColumns = table.getFeature().iterator();
      sep = "";
      while (itColumns.hasNext()) {
        Column column = (Column) itColumns.next();
        out.println(sep + "\"" + column.getName() + "\"");
        sep = ", ";
      }
      out.println("<p>");

    } 
    // 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_2(), args[0]);
    } else {
      MinimalServletContainer.executeServlet(new Relational_2(), System.out);
    }

  }

}