import COM.ibm.db2.app.UDF;
import java.io.*;
import java.math.BigDecimal;

public class UDFBiographien extends UDF {
  // Anzahl der gefundenen Biographieeinträge
  int maxRows;

  // Table Function zum Ermitteln der Professoren-Biographien
  public void tableUDF(String inProfName, String outUrl, 
		String outSprache, BigDecimal outRanking) throws Exception {

    int intRow = 0;

    // Die Ein-Ausgabe erfolgt über das SCRATCHPAD
    byte[] scratchpad = getScratchpad();

    // Für Eingabe vom SCRATCHPAD
    ByteArrayInputStream byteArrayIn = new ByteArrayInputStream(scratchpad);
    DataInputStream dataIn = new DataInputStream(byteArrayIn);

    // Zur Ausgabe auf das SCRATCHPAD
    byte[] byteArrayRow;
    int i;
    ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(10);
    DataOutputStream dataOut = new DataOutputStream(byteArrayOut);

    // UDF realisiert das Cursor/Iterator-Konzept:
    switch (getCallType()) {
    case SQLUDF_TF_FIRST:
      // ggf. Initialisierung der UDF
      break;
    case SQLUDF_TF_OPEN:
      // An dieser Stelle erfolgt das Abfragen der Biographien
      intRow = 1;
      // wir erzeugen hier nur Zufallsdaten:
      maxRows = (int)Math.round(Math.random() * 20.0);
      dataOut.writeInt(intRow);
      byteArrayRow = byteArrayOut.toByteArray();
      for (i = 0; i < byteArrayRow.length; i++) {
        scratchpad[i] = byteArrayRow[i];
      }
      setScratchpad(scratchpad);
      break;
    case SQLUDF_TF_FETCH:
      // SCRATCHPAD auslesen
      intRow = dataIn.readInt();
      if (intRow > maxRows) {
        // end-of-file:
        setSQLstate("02000");
      } else {
        // trage den aktuellen Datensatz ein (set in UDF def.):
		    set(2, "www-db.in.tum.de/EISCD/UDFBios/" + inProfName + 
				    intRow + ".shtml");
        set(3, "Deutsch");
        set(4, new BigDecimal((double)intRow));
        intRow++;
      }
      // Daten in SCRATCHPAD abspeichern
      dataOut.writeInt(intRow);
      byteArrayRow = byteArrayOut.toByteArray();
      for (i = 0; i < byteArrayRow.length; i++) {
        scratchpad[i] = byteArrayRow[i];
      }
      setScratchpad(scratchpad);
      break;
    case SQLUDF_TF_CLOSE:
      break;
    case SQLUDF_TF_FINAL:
      break;
    }
  } // tableUDF
}
