/**
   * Generates an XML database schema from JDBC metadata.
   *
   * @throws Exception a generic exception.
   */
  public void generateXML() throws Exception {
    // Load the database Driver.
    Class.forName(dbDriver);
    log("DB driver sucessfuly instantiated");

    Connection con = null;
    try {
      // Attempt to connect to a database.
      Properties p = new Properties();
      p.setProperty("user", dbUser);
      p.setProperty("password", dbPassword);
      p.setProperty(
          "oracle.jdbc.mapDateToTimestamp", "false"); // workaround for change in 11g JDBC driver
      con = DriverManager.getConnection(dbUrl, p);
      log("DB connection established");

      Platform platform = PlatformFactory.getPlatformFor(dbType);

      // Get the database Metadata.
      DatabaseMetaData dbMetaData = con.getMetaData();

      databaseNode = doc.createElement("database");
      databaseNode.setAttribute("name", "kuali");
      // JHK added naming method
      databaseNode.setAttribute("defaultJavaNamingMethod", "nochange");

      if (processTables) {
        List<String> tableList = platform.getTableNames(dbMetaData, dbSchema);
        // ensure all are upper case before exporting
        tableList = upperCaseList(tableList);
        // ensure sorting is consistent (not DB-dependent)
        Collections.sort(tableList);
        for (String curTable : tableList) {
          if (!tableNameRegexPattern.matcher(curTable).matches()) {
            log("Skipping table: " + curTable);
            continue;
          }
          if (StringUtils.isNotBlank(tableNameExcludeRegex)
              && tableNameExcludeRegexPattern.matcher(curTable).matches()) {
            log("Skipping table: " + curTable);
            continue;
          }
          log("Processing table: " + curTable);

          Element table = doc.createElement("table");
          table.setAttribute("name", curTable.toUpperCase());

          // Add Columns.
          // TableMap tblMap = dbMap.getTable(curTable);

          List columns = getColumns(dbMetaData, curTable);
          List<String> primKeys = platform.getPrimaryKeys(dbMetaData, dbSchema, curTable);
          Map<String, Object[]> foreignKeys = getForeignKeys(dbMetaData, curTable);

          // Set the primary keys.
          primaryKeys = new HashMap<String, String>();

          for (int k = 0; k < primKeys.size(); k++) {
            String curPrimaryKey = (String) primKeys.get(k);
            primaryKeys.put(curPrimaryKey, curPrimaryKey);
          }

          for (int j = 0; j < columns.size(); j++) {
            List col = (List) columns.get(j);
            String name = (String) col.get(0);
            Integer jdbcType = ((Integer) col.get(1));
            int size = ((Integer) col.get(2)).intValue();
            int scale = ((Integer) col.get(5)).intValue();

            // From DatabaseMetaData.java
            //
            // Indicates column might not allow NULL values. Huh?
            // Might? Boy, that's a definitive answer.
            /* int columnNoNulls = 0; */

            // Indicates column definitely allows NULL values.
            /* int columnNullable = 1; */

            // Indicates NULLABILITY of column is unknown.
            /* int columnNullableUnknown = 2; */

            Integer nullType = (Integer) col.get(3);
            String defValue = (String) col.get(4);

            Element column = doc.createElement("column");
            column.setAttribute("name", name);

            ;
            column.setAttribute("type", platform.getTorqueColumnType(jdbcType));
            //							TypeMap.getTorqueType( type ).getName() );

            if (size > 0
                && (jdbcType.intValue() == Types.CHAR
                    || jdbcType.intValue() == Types.VARCHAR
                    || jdbcType.intValue() == Types.DECIMAL
                    || jdbcType.intValue() == Types.NUMERIC)) {
              column.setAttribute("size", String.valueOf(size));
            }

            if (scale > 0
                && (jdbcType.intValue() == Types.DECIMAL || jdbcType.intValue() == Types.NUMERIC)) {
              column.setAttribute("scale", String.valueOf(scale));
            }

            if (primaryKeys.containsKey(name)) {
              column.setAttribute("primaryKey", "true");
              // JHK: protect MySQL from excessively long column in the PK
              // System.out.println( curTable + "." + name + " / " + size );
              if (column.getAttribute("size") != null && size > 765) {
                log(
                    "updating column "
                        + curTable
                        + "."
                        + name
                        + " length from "
                        + size
                        + " to 255");
                column.setAttribute("size", "255");
              }
            } else {
              if (nullType.intValue() == DatabaseMetaData.columnNoNulls) {
                column.setAttribute("required", "true");
              }
            }

            if (StringUtils.isNotEmpty(defValue)) {
              defValue =
                  platform.getColumnDefaultValue(platform.getTorqueColumnType(jdbcType), defValue);
              if (StringUtils.isNotEmpty(defValue)) {
                column.setAttribute("default", defValue);
              }
            }
            table.appendChild(column);
          }

          List<String> foreignKeyNames = new ArrayList<String>(foreignKeys.keySet());
          Collections.sort(foreignKeyNames);
          // Foreign keys for this table.
          for (String fkName : foreignKeyNames) {
            Element fk = doc.createElement("foreign-key");
            fk.setAttribute("name", fkName.toUpperCase());
            Object[] forKey = foreignKeys.get(fkName);
            String foreignKeyTable = (String) forKey[0];
            List refs = (List) forKey[1];
            fk.setAttribute("foreignTable", foreignKeyTable.toUpperCase());
            String onDelete = (String) forKey[2];
            // gmcgrego - just adding onDelete if it's cascade so as not to affect kfs behavior
            if (onDelete == "cascade") {
              fk.setAttribute("onDelete", onDelete);
            }
            for (int m = 0; m < refs.size(); m++) {
              Element ref = doc.createElement("reference");
              String[] refData = (String[]) refs.get(m);
              ref.setAttribute("local", refData[0]);
              ref.setAttribute("foreign", refData[1]);
              fk.appendChild(ref);
            }
            table.appendChild(fk);
          }

          List<TableIndex> indexes = getIndexes(dbMetaData, curTable);
          Collections.sort(
              indexes,
              new Comparator<TableIndex>() {
                public int compare(TableIndex o1, TableIndex o2) {
                  return o1.name.compareTo(o2.name);
                }
              });
          for (TableIndex idx : indexes) {
            if (foreignKeyNames.contains(idx.name)) {
              log(idx.name + " is also a foreign key, skipping");
              continue;
            }
            String tagName = idx.unique ? "unique" : "index";
            Element index = doc.createElement(tagName);
            index.setAttribute("name", idx.name.toUpperCase());
            for (String colName : idx.columns) {
              Element col = doc.createElement(tagName + "-column");
              col.setAttribute("name", colName);
              index.appendChild(col);
            }
            table.appendChild(index);
          }

          databaseNode.appendChild(table);
        }
      }
      if (processViews) {
        log("Getting view list...");
        List<String> viewNames = platform.getViewNames(dbMetaData, dbSchema);
        log("Found " + viewNames.size() + " views.");
        viewNames = upperCaseList(viewNames);
        Collections.sort(viewNames);
        for (String viewName : viewNames) {
          if (!tableNameRegexPattern.matcher(viewName).matches()) {
            log("Skipping view: " + viewName);
            continue;
          }
          Element view = doc.createElement("view");
          view.setAttribute("name", viewName.toUpperCase());
          /*
           * <view name="" viewdefinition="" />
           *
           */
          String definition =
              platform.getViewDefinition(dbMetaData.getConnection(), dbSchema, viewName);
          definition = definition.replaceAll("\0", "");
          view.setAttribute("viewdefinition", definition);
          databaseNode.appendChild(view);
        }
      }

      if (processSequences) {
        log("Getting sequence list...");
        List<String> sequenceNames = platform.getSequenceNames(dbMetaData, dbSchema);
        log("Found " + sequenceNames.size() + " sequences.");
        sequenceNames = upperCaseList(sequenceNames);
        Collections.sort(sequenceNames);
        for (String sequenceName : sequenceNames) {
          if (!tableNameRegexPattern.matcher(sequenceName).matches()) {
            log("Skipping sequence: " + sequenceName);
            continue;
          }
          Element sequence = doc.createElement("sequence");
          sequence.setAttribute("name", sequenceName.toUpperCase());
          /*
           * <view name="" nextval="" />
           *
           */
          Long nextVal =
              platform.getSequenceNextVal(dbMetaData.getConnection(), dbSchema, sequenceName);
          sequence.setAttribute("nextval", nextVal.toString());

          databaseNode.appendChild(sequence);
        }
        doc.appendChild(databaseNode);
      }
    } finally {
      if (con != null) {
        con.close();
        con = null;
      }
    }
  }
Esempio n. 2
0
  public boolean performTest(String arg) {
    boolean passed = true;
    try {
      Writer writer = new Writer(false);
      DOMParser parser = new DOMParser();
      if (!arg.equals("delete2") && !arg.equals("insert2")) {
        if (fStdOut) System.out.println("\n*************** Test == " + arg + " ***************");
        for (int i = 0; i < tests.length; i++) {
          if (fStdOut) System.out.println("\n\nTest[" + i + "]");
          if (fStdOut) System.out.println("\nBefore " + arg + ": document=" + tests[i] + ":");
          parser.parse(new InputSource(new StringReader(tests[i])));
          DocumentImpl document = (DocumentImpl) parser.getDocument();
          Range range = document.createRange();
          Node root = document.getDocumentElement();
          boolean surround = false;
          Node surroundNode = document.createElement(SURROUND);
          if (arg.equals("surround")) {
            surround = true;
          }

          if (i == 0) {
            range.setStart(root.getFirstChild(), 1);
            range.setEndBefore(root.getLastChild());
            if (surround) range.setEnd(root.getLastChild(), 1);

          } else if (i == 1) {
            Node n1 = root.getFirstChild().getNextSibling().getFirstChild();
            range.setStart(n1, 1);
            range.setEnd(root.getLastChild(), 1);
            if (surround) range.setEnd(n1, 2);
          } else if (i == 2) {
            range.setStart(root.getFirstChild(), 1);
            Node n2 = root.getFirstChild().getNextSibling().getFirstChild();
            range.setEnd(n2, 1);
            if (surround) range.setEndBefore(root.getLastChild());
          } else if (i == 3) {
            Node n3 = root.getFirstChild().getFirstChild();
            range.setStart(n3, 1);
            range.setEnd(root.getLastChild().getFirstChild(), 1);
            if (surround) {
              range.selectNode(root.getFirstChild().getNextSibling());
            }
          } else if (i == 4) {
            Node n4 = root.getFirstChild().getFirstChild().getNextSibling().getFirstChild();
            range.setStartAfter(n4);
            range.setEndAfter(root.getLastChild().getFirstChild());
            if (surround) {
              range.selectNodeContents(root.getFirstChild().getNextSibling());
            }
          }

          if (fStdOut) System.out.println("range.toString=" + range.toString());
          DocumentFragment frag = null;

          if (arg.equals("surround")) {
            try {
              if (fStdOut) System.out.println("surroundNode=" + surroundNode);
              range.surroundContents(surroundNode);
            } catch (org.w3c.dom.ranges.RangeException e) {
              if (fStdOut) System.out.println(e);
            }
            String result = toString(document);
            if (fStdOut) System.out.println("After surround: document=" + result + ":");
            if (!result.equals(surroundResult[i])) {
              if (fStdOut) System.out.println("Should be: document=" + surroundResult[i] + ":");
              passed = false;
              if (fStdOut) System.out.println("Test FAILED!");
              if (fStdOut) System.out.println("*** Surround document Test[" + i + "] FAILED!");
            }
          }

          if (arg.equals("insert")) {
            range.insertNode(document.createTextNode(INSERT));
            String result = toString(document);
            if (fStdOut) System.out.println("After  insert: document=" + result + ":");
            if (!result.equals(insertResult[i])) {
              if (fStdOut) System.out.println("Should be: document=" + insertResult[i] + ":");
              passed = false;
              if (fStdOut) System.out.println("Test FAILED!");
              if (fStdOut) System.out.println("*** Insert document Test[" + i + "] FAILED!");
            }

          } else if (arg.equals("delete")) {
            range.deleteContents();
            String result = toString(document);
            if (fStdOut) System.out.println("After delete:" + result + ":");
            if (!result.equals(deleteResult[i])) {
              if (fStdOut) System.out.println("Should be: document=" + deleteResult[i] + ":");
              passed = false;
              if (fStdOut) System.out.println("Test FAILED!");
              if (fStdOut) System.out.println("*** Delete document Test[" + i + "] FAILED!");
            }
          } else if (arg.equals("extract")) {
            frag = range.extractContents();
            // range.insertNode(document.createTextNode("^"));
            String result = toString(document);
            if (fStdOut) System.out.println("After extract: document=" + result + ":");
            if (!result.equals(deleteResult[i])) {
              if (fStdOut) System.out.println("Should be: document=" + deleteResult[i] + ":");
              passed = false;
              if (fStdOut) System.out.println("*** Extract document Test[" + i + "] FAILED!");
            }
            String fragResult = toString(frag);
            if (fStdOut) System.out.println("After extract: fragment=" + fragResult + ":");
            if (!fragResult.equals(extractResult[i])) {
              if (fStdOut) System.out.println("Should be: fragment=" + extractResult[i] + ":");
              passed = false;
              if (fStdOut) System.out.println("*** Extract Fragment Test[" + i + "] FAILED!");
            }
          } else if (arg.equals("clone")) {
            frag = range.cloneContents();
            String fragResult = toString(frag);
            if (fStdOut) System.out.println("After clone: fragment=" + fragResult);
            if (!fragResult.equals(extractResult[i])) {
              if (fStdOut) System.out.println("Should be: fragment=" + extractResult[i] + ":");
              passed = false;
              if (fStdOut) System.out.println("*** Clone Fragment Test[" + i + "] FAILED!");
            }
          }
        }

      } else if (arg.equals("insert2")) {
        if (fStdOut) System.out.println("\n*************** Test == " + arg + " ***************");
        for (int i = 0; i < 4; i++) {

          if (fStdOut) System.out.println("\n\nTest[" + i + "]");
          if (fStdOut) System.out.println("\nBefore " + arg + ": document=" + INSERT2 + ":");
          parser.parse(new InputSource(new StringReader(INSERT2)));
          DocumentImpl document = (DocumentImpl) parser.getDocument();
          Node root = document.getDocumentElement();
          Range range = document.createRange();
          range.setStart(root.getFirstChild(), 11);
          range.setEnd(root.getFirstChild(), 18);
          Range rangei = document.createRange();
          if (i == 0) {
            rangei.setStart(root.getFirstChild(), 10);
            rangei.setEnd(root.getFirstChild(), 10);
          }
          if (i == 1) {
            rangei.setStart(root.getFirstChild(), 11);
            rangei.setEnd(root.getFirstChild(), 11);
          }
          if (i == 2) {
            rangei.setStart(root.getFirstChild(), 12);
            rangei.setEnd(root.getFirstChild(), 12);
          }
          if (i == 3) {
            rangei.setStart(root.getFirstChild(), 17);
            rangei.setEnd(root.getFirstChild(), 17);
          }
          // if (fStdOut) System.out.println("range: start1=="+range.getStartContainer());
          // root.insertBefore(document.createTextNode("YES!"), root.getFirstChild());
          // if (fStdOut) System.out.println("range: start2=="+range.getStartContainer());

          if (DEBUG)
            if (fStdOut) System.out.println("before insert start=" + range.getStartOffset());
          if (DEBUG) if (fStdOut) System.out.println("before insert end=" + range.getEndOffset());
          rangei.insertNode(document.createTextNode(INSERTED_TEXT));
          if (DEBUG)
            if (fStdOut) System.out.println("after insert start=" + range.getStartOffset());
          if (DEBUG) if (fStdOut) System.out.println("after insert end=" + range.getEndOffset());

          String result = toString(document);
          if (fStdOut) System.out.println("After insert2: document=" + result + ":");
          if (!result.equals(rangeInsertResult[i])) {
            if (fStdOut) System.out.println("Should be: document=" + rangeInsertResult[i] + ":");
            passed = false;
            if (fStdOut) System.out.println("Test FAILED!");
            if (fStdOut) System.out.println("*** Delete Ranges document Test[" + i + "] FAILED!");
          }
        }
      } else if (arg.equals("delete2")) {
        //
        // Range Deletion, acting upon another range.
        //

        if (fStdOut) System.out.println("\n*************** Test == " + arg + " ***************");
        for (int i = 0; i < rangeDelete.length; i++) {
          if (fStdOut) System.out.println("\n\nTest[" + i + "]");
          if (fStdOut) System.out.println("\nBefore " + arg + ": document=" + rangeDelete[i] + ":");
          parser.parse(new InputSource(new StringReader(rangeDelete[i])));
          DocumentImpl document = (DocumentImpl) parser.getDocument();
          Range range = document.createRange();
          Range ranged = document.createRange();
          Node root = document.getDocumentElement();
          boolean surround = false;
          Node surroundNode = document.createElement(SURROUND);
          if (arg.equals("surround")) {
            surround = true;
          }

          if (i == 0) {
            ranged.setStart(root.getFirstChild(), 5);
            ranged.setEnd(root.getFirstChild(), 14);

            range.setStart(root.getFirstChild(), 11);
            range.setEnd(root.getFirstChild(), 19);
          } else if (i == 1) {
            ranged.setStart(root.getFirstChild(), 5);
            ranged.setEnd(root.getFirstChild(), 22);

            range.setStart(root.getFirstChild(), 11);
            range.setEnd(root.getFirstChild(), 21);
          } else if (i == 2) {
            ranged.setStart(root.getFirstChild(), 5);
            ranged.setEnd(root.getFirstChild().getNextSibling().getFirstChild(), 1);

            range.setStart(root.getFirstChild(), 11);

            range.setEndAfter(root.getFirstChild().getNextSibling().getFirstChild());
          } else if (i == 3) {
            ranged.setStart(root.getFirstChild(), 5);
            ranged.setEnd(root.getFirstChild(), 11);

            range.setStart(root.getFirstChild(), 11);
            range.setEnd(root.getFirstChild(), 21);
          } else if (i == 4) {
            ranged.selectNode(root.getFirstChild().getNextSibling());

            range.setStart(root.getFirstChild().getNextSibling().getFirstChild(), 6);
            range.setEnd(root.getFirstChild().getNextSibling().getFirstChild(), 15);
          }

          DocumentFragment frag = null;

          if (arg.equals("delete2")) {
            if (DEBUG) {
              if (fStdOut) System.out.println("BEFORE deleteContents()");
              if (fStdOut) System.out.println("ranged: startc=" + ranged.getStartContainer());
              if (fStdOut) System.out.println("ranged: starto=" + ranged.getStartOffset());
              if (fStdOut) System.out.println("ranged:   endc=" + ranged.getEndContainer());
              if (fStdOut) System.out.println("ranged:   endo=" + ranged.getEndOffset());

              if (fStdOut) System.out.println("range: startc=" + range.getStartContainer());
              if (fStdOut) System.out.println("range: starto=" + range.getStartOffset());
              if (fStdOut) System.out.println("range:   endc=" + range.getEndContainer());
              if (fStdOut) System.out.println("range:   endo=" + range.getEndOffset());
            }
            ranged.deleteContents();
            String result = null;
            if (DEBUG) {
              if (fStdOut) System.out.println("AFTER deleteContents()");
              result = toString(document);
              if (fStdOut) System.out.println("ranged: startc=" + ranged.getStartContainer());
              if (fStdOut) System.out.println("ranged: starto=" + ranged.getStartOffset());
              if (fStdOut) System.out.println("ranged:   endc=" + ranged.getEndContainer());
              if (fStdOut) System.out.println("ranged:   endo=" + ranged.getEndOffset());

              if (fStdOut) System.out.println("range: startc=" + range.getStartContainer());
              if (fStdOut) System.out.println("range: starto=" + range.getStartOffset());
              if (fStdOut) System.out.println("range:   endc=" + range.getEndContainer());
              if (fStdOut) System.out.println("range:   endo=" + range.getEndOffset());
            }

            ranged.insertNode(document.createTextNode("^"));

            result = toString(document);
            if (fStdOut) System.out.println("After delete2: document=" + result + ":");
            if (!result.equals(rangeDeleteResult[i])) {
              if (fStdOut) System.out.println("Should be: document=" + rangeDeleteResult[i] + ":");
              passed = false;
              if (fStdOut) System.out.println("Test FAILED!");
              if (fStdOut) System.out.println("*** Delete Ranges document Test[" + i + "] FAILED!");
            }
          }
        }
      }

    } catch (org.xml.sax.SAXParseException spe) {
      passed = false;
    } catch (org.xml.sax.SAXException se) {
      if (se.getException() != null) se.getException().printStackTrace(System.err);
      else se.printStackTrace(System.err);
      passed = false;
    } catch (Exception e) {
      e.printStackTrace(System.err);
      passed = false;
    }
    if (!passed) if (fStdOut) System.out.println("*** The " + arg + " Test FAILED! ***");

    return passed;
  }