package examples.jdbc.mssqlserver4;

import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;


/** This example applet listens on a socket and displays messages that
 * are sent to that socket. You can run this applet in a browser on any
 * machine without the security restrictions you usually encounter
 * with two-tier JDBC drivers. The Java class loads into the browser
 * from the local disk and does not do anything insecure.
 * 
 * <p>
 * The input to the socket comes from the jDriver for Microsoft SQL Server. If
 * the driver is called from an applet, <i>its</i> browser security is still
 * enforced. If you are using the JDBC driver in a standalone Java application,
 * there are no browser security issues.
 **/


class logThread extends Thread
{
  logThread(logWindow applet, Socket socket)
  {
    this.applet = applet; 
    // Socket we're listening to
    this.socket = socket;
  }

  // Runs in a separate thread
  public void run()
  {
    try
      {
        // Input stream for this socket
        InputStream is = socket.getInputStream();

        // Keep going until something bad happens, e.g. socket is
        // closed and exception raised
        while(true)
          {
            int available = is.available();

            // If there's data waiting on the socket
            if(available > 0)
              {
                byte b [] = new byte[available];

                // Read available bytes from socket
                is.read(b);

                // Create string from ASCII values
                String s = new String(b,0);

                // Add to the log window
                applet.print(s);
              }

            // Nothing to do, let's sleep a few milliseconds
            else sleep(200);
          }
      }

    // We had a problem so we may as well die (exit the run method)
    catch(Exception e) { applet.print("Connection closed."); }
  }

  // Socket we're listening to
  Socket socket = null;

  // Applet that's hosting us
  logWindow applet = null;
}

public class logWindow extends Applet implements Runnable
{
  synchronized public void init()
  {
    // Classy white background for this applet
    setBackground(Color.white);
    setLayout(new BorderLayout());

    // This is the text area were the log will go
    logArea = new TextArea(); 

    // Use small fixed width font
    logArea.setFont(new Font("Courier",Font.PLAIN,12));

    // User can type in this area
    logArea.setEditable(true);

    // The log area is resized to fill the window
    add("Center", logArea);

    // The clear button is at the bottom
    add("South", new Button("Clear"));

    String pPort = getParameter("port");

    // Parse the port number we should listen to
    if (pPort != null) port = Integer.parseInt(pPort);
          
    // Create a thread that will listen to connection requests and
    // spawn other threads to log 'em
   
    // Execute the run method in this object
    Thread listener = new Thread(this,"Listener" + this);

    // Run socket server
    listener.start();
  }

  // UI gadget that shows the log
  private TextArea logArea = null;

  // Port we're listening on
  private int port = 0;

  synchronized public boolean action(Event iEvent,Object iArgument)
  {
    // User clicked the 'clear' button
    if(iArgument.equals("Clear"))
      {
        // Empty the log
        logArea.replaceText("",0,logArea.getText().length());

        return true;
      }

    return super.action(iEvent,iArgument);
  }

  // Did I forget anything?
  synchronized public final void print(String s)
                 
  {
    // Add string to log window
    logArea.appendText(s);
  }

  public void run()
  {
    try
      {
        // Open a server socket (listener)
      ServerSocket listen = new ServerSocket(port);

        print("\n\nListening for connections on port " + port + ".\n");

        for (int connections = 0 ; true ; connections++)
          {
            // Accept incoming connection requests from clients
            Socket socket = listen.accept();
            print("\n\nConnection " + (connections + 1) + " established with " + socket + ".\n");

            // Spawn this connection on its own thread
            logThread aThread = new logThread(this,socket);

            // Start loggin' from this connection
            aThread.start();
          }
      }

    catch(IOException io) 
      { 
        print("logWindow.run - exception while listening on port " + 
              port + " " + io + "\n"); 
      }
  }
}

