HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Java-based Gateway Middleware for the Web"
Vol. 2, Issue 11, p. 8

	

Listing 1.
  
import java.io.*;  
import java.net.*;  

public class Gateway  
{  
  public static void main(String[] args)  
    {  
      Facilitator f = new Facilitator();  
      f.start();  
      Dispatcher d = new Dispatcher();  
      d.start();  
      Registry reg = new Registry();  
      reg.start();  
      Receptionist rec = new Receptionist();  
      rec.start();  

      System.out.println("Java-based Gateway Middleware Setup Done");  
    }  
}  

Listing 2.
  
  *  euclidean.c  - computation of Euclidean Distance between two N-dimensional 
vectors  
  *      (x1, x2, .... xn), (y1, y2, .... yn)  
  *      accepts  the dimension  and the two vectors from the standard input  
  *      computes  the distance  as   sqrt(  sqr( x1-y1)+ sqr(x2-y2) + ... )  
  *      displays the result on the standard output  
  */  

#include <stdio.h>  
#include <math.h>  

#define MAX  20  

main()   
{  
  int x[MAX];  
  int y[MAX];  
  int i, dimension, total=0;  
  double distance;  
   

  printf("Computation of Euclidean Distance between two n-dimensional 
vectors\n");  
  scanf("%d", &dimension);  

  printf(" no. of dimension = %d\n", dimension);  

  for (i=0; i<dimension; i++)  
      scanf("%d", &x[i]);  

  for (i=0; i<dimension; i++)  
      scanf("%d", &y[i]);  

  printf("  vector 1 = (%d", x[0]);  
  for (i=1; i<dimension; i++)   
       printf(", %d", x[i]);  
  printf(")\n  vector 2 = (%d", y[0]);  
  for (i=1; i<dimension; i++)  
       printf(", %d", y[i]);  
   printf(")\n");  
    
  for (i=0; i<dimension; i++) {  
      total = total + ((x[i] - y[i]) * (x[i] - y[i]));  
  }  

  distance = sqrt(total);  

  printf(" Computed distance = %lf \n", distance);  

  return(0);  
}  

Listing 3.
 
import java.applet.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
import java.net.*; 
import java.util.*; 

public class ClientApplet extends Applet implements ActionListener 
{ 
  private       int clientID; 
  private       Channel ch_client, ch_assigned_client; 
  private       String gateway_hostname; 
  private int port; 
  private       boolean quit; 
  private       String input; 
  private       TextField cmd; 
  private       TextArea result; 
  private       Button submitButton, quitButton; 
  

  public void init() { 

    int clientID; 
    String gateway_hostname; 
    Message msg; 

    Panel p1, p2, p3, p4; 
    Label header, instruction, statusLabel; 
    Font fn; 

    quit = false; 
    header = new Label("Client for the Java-based Gateway Middleware"); 
    instruction = new Label("Please enter your command :-"); 
    statusLabel = new Label("Result status"); 

    cmd = new TextField(40); 
    result = new TextArea(10, 30); 
    result.setEditable(false); 

    submitButton = new Button("Submit"); 
    quitButton = new Button("Quit"); 

    submitButton.addActionListener(this); 
    quitButton.addActionListener(this); 

    fn = new Font("TimesRoman", Font.BOLD, 24); 
    header.setFont(fn); 

    p1 = new Panel(); 
    p1.setLayout(new BorderLayout()); 
    p1.add("North", header); 
    p1.add("Center", instruction); 
    p1.add("South", cmd); 

    p4 = new Panel(); 
    p4.setLayout(new BorderLayout()); 
    p4.add("West", statusLabel); 
    p4.add("Center", result); 
  

    p2 = new Panel(); 
    p2.setLayout(new BorderLayout()); 
    p2.add("North", p1); 
    p2.add("South", p4); 

    p3 = new Panel(); 
    p3.add("West", submitButton); 
    p3.add("East", quitButton); 

    setLayout(new BorderLayout()); 
    add("North", p2); 
    add("South", p3); 

  } 
  

  public void start() { 
      Message msg; 
      int index; 

      gateway_hostname = this.getParameter("Hostname"); 
  
      // set up a temp channel to communicate with the Agate 
      ch_client = new Channel(Constant.CLIENT_PORT); 
       
      try 
        { 
          String reception; 
          reception = 
                 InetAddress.getLocalHost().getHostName(); 
   msg = new Message(); 
          msg.intention = "New Client"; 
    msg.content = reception; 
          ch_client.send(msg, gateway_hostname, Constant.RECEPTION_PORT); 
        } 
      catch (UnknownHostException e3) 
        { 
         //System.out.println(e3); 
        } 

      msg = ch_client.receive(); 
      String line = (String) msg.content; 

      System.out.println("content = "+ line); 
      clientID = Integer.parseInt((String) msg.communication); 
      port = Integer.parseInt(line); 

      output_result("Client : assigned port number is " + port+ "id = 
"+clientID); 
       
      // closing the ch_client channel 
      msg = new Message(); 
      msg.intention = "stop"; 
      ch_client.send(msg, Constant.CLIENT_PORT); 
             
      // setting up a new channel with the assigned port number 
      if (port != -1 || port != -2) 
        ch_assigned_client = new Channel(port); 
    } 
  
  

  boolean ConnectionAccepted() 
    { 
      if (port == -1) 
        { 
          //System.out.println("Client connection to Gateway rejected!"); 
          //System.out.println("Reason : Too many client connection"); 
          return false; 
        } 
      else if (port == -2) 
        { 
          //System.out.println("Client connection to Gateway rejected!"); 
          //System.out.println("Reason : Existing client connection using" + 
          //                   " current client ID detected");    
          return false; 
        } 

      else 
        { 
          //System.out.println("Client connection to Gateway accepted!"); 
          return true; 
        } 
    } 

 public void output_result(String s) 
 { 
   result.setText(s); 
   validate(); 
 } 

  public void actionPerformed(ActionEvent event) 
  { 

   String command = event.getActionCommand(); 

   if (command.equals("Submit")) { 

     input = cmd.getText(); 
     output_result("output : "+input); 
     System.out.println("input = "+input); 
     submitGateway(input); 
   } else if (command.equals("Quit")) { 
     quit = true; 
   } 

 } 
            
  public void submitGateway(String userInput) 
    { 
      int commandID, index; 
      StringTokenizer userInputTok, resultStrTok; 
      String request, argument, result, output; 
      Message msg; 
  
  

              userInputTok = new StringTokenizer(userInput, " "); 
        
              if (userInputTok.countTokens() > 0) { 

     request = userInputTok.nextToken(); 
                  index = userInput.indexOf(' '); 
                  userInput = userInput.substring(index + 1); 
     
                  if (request.equalsIgnoreCase("exec") == true) { 

                      if (userInputTok.countTokens() > 0) { 

             msg = new Message(); 
                          msg.intention = "Request"; 
                          msg.communication = Integer.toString(clientID); 
                          msg.content = userInput; 
                          ch_assigned_client.send( msg,  gateway_hostname, 
    Constant.RECEPTION_PORT); 

                          System.out.println("just send"); 
                          msg = ch_assigned_client.receive(); 

                          result = (String) msg.content; 
                          System.out.println("received "+result); 

                          index = result.indexOf(' '); 
                          commandID = Integer.parseInt(result.substring(0, 
index)); 
                          result = result.substring(index+1); 

             switch (commandID) { 
    case Constant.JOB_EXEC_OK: { 
                                 output_result(result); 
   break; 
    } 

   case Constant.JOB_AGENT_UNAVAIL:   { 
                                 //System.out.println("Error : No Service agent 
available to " + 
                                 //                   "handle the request 
job!"); 
   break; 
  } 
        
  case Constant.JOB_EXEC_UNSUPPORTED: { 
                                 //System.out.println("Error : Requested job is 
not supported " + 
                                 //                   "by Gateway!"); 
      break; 
  } 

           }  //  switch statement 
                      }  else {      //   if UserInputTok.countTokens() > 0 
           ; 
          //System.out.println("exec what?"); 

                    }  // if  request = exec   

                    else if (request.equalsIgnoreCase("quit") == true) 
                    { 
                      String reception; 
                      reception = Integer.toString(Constant.RELINQUISH_CLIENT) 
                        + " " + Integer.toString(clientID); 
         
                      //System.out.println(reception); 
         
                      msg = new Message(); 
         msg.intention = "Done"; 
        msg.content = reception; 
                      ch_assigned_client.send( msg, 
                                               gateway_hostname, 
                                               Constant.RECEPTION_PORT); 
         
                      // System.exit(1); 

                    } 
     
                  else 
                    System.out.println("bad command"); 
                } 

         }   // submitGateway() method 

} 

Listing 4.
 
import java.net.*; 
import java.util.*; 

public class Receptionist extends Thread  
{  
  private  Channel ch_reception; 
  private  PortManager client_port; 
  private  Hashtable client_table; 
  private  int assigned_id; 

  public Receptionist() 
    { 
      ch_reception = new Channel(Constant.RECEPTION_PORT); 
      client_port = new PortManager(Constant.CLIENT_START_PORT, 
                                    Constant.MAX_CLIENT_SIZE); 
      client_table = new Hashtable(); 
      assigned_id = 0; 
    }  

  public void run() 
    { 
      Message msg; 
      String command; 
  

      while (true) { 

          msg = ch_reception.receive(); 
          command = msg.intention; 
          System.out.println("Reception incoming_str : " + msg.content); 

          if (command.compareTo("New Client") == 0) { 
              new_client(msg); 
          } else if (command.compareTo("Relinquish Client") == 0) { 
              relinquish_client(msg); 
          } else if (command.compareTo("Request") == 0 ) { 
              job_request(msg); 
          } else if (command.compareTo("Result") == 0) { 
              job_result(msg); 
          } 

      } // while loop 

    } // run() method 
  

  void new_client(Message i_msg) { 
     int assigned_port, index, clientID; 
     String hostname, incoming_str; 
     Message msg; 
     CData clientdata; 
      

     incoming_str = (String) i_msg.content; 

     clientID = ++assigned_id; 
     index = incoming_str.indexOf(' '); 
     hostname = incoming_str.substring(index+1); 

     if (client_port.available()==true){ 

        if (client_table.containsKey(new Integer(clientID))==false) { 

           System.out.println("clientid="+clientID); 
           assigned_port = client_port.usePort(); 

           clientdata = new CData(hostname, assigned_port); 
           client_table.put(new Integer(clientID), clientdata); 
                 
           msg = new Message(); 
           msg.intention = "New Client"; 
           msg.communication = Integer.toString(clientID); 
           msg.content = Integer.toString(assigned_port); 

           ch_reception.send( msg, 
                  hostname, Constant.CLIENT_PORT);                

           System.out.println("Reception : Client " + clientID + 
                  " is assigned the use of port number "+ 
                  assigned_port+" client id = "+assigned_id); 

        } else { 
           msg = new Message(); 
           msg.intention = "Error"; 
           msg.content = "-2";  
           ch_reception.send( msg, 
                       hostname, Constant.CLIENT_PORT); 
           System.out.println("Registry : Client " + clientID + 
                       " request for Connection has been denied "+ 
                       "due to lack of available 
ports");                                            
        }                       
     } else {  // port available ?? 

        msg = new Message(); 
        msg.intention = "Error"; 
        msg.content = "-1";  
        ch_reception.send( msg, hostname, 
                     Constant.CLIENT_PORT); 
        System.out.println("Reception: Client " + clientID + 
                     " request for Connection has been denied" + 
                     " due to existence of another client connection" + 
                     " with the same Client ID"); 
     }       
  } // new_client() method 
  

  void relinquish_client(Message i_msg) { 

     int clientID; 
     CData clientdata; 

     clientID = Integer.parseInt((String) i_msg.communication); 
   
     clientdata = (CData) client_table.remove(new Integer(clientID)); 
     client_port.releasePort(clientdata.getPort()); 

     System.out.println("Registry : Client " + clientID + 
                " at port number " + clientdata.getPort() + 
                " has closed connection with the Agate"); 
  } 

  void job_request(Message i_msg) { 

     int clientID; 
     Message msg; 
     String incoming_str; 
  

     clientID = Integer.parseInt((String) i_msg.communication); 
     incoming_str = (String) i_msg.content; 
  

     System.out.println("Reception: " + incoming_str + 
                  " has been dispatched to the Dispatcher"); 

     msg = new Message(); 
     msg.intention = "Request"; 
     msg.communication = Integer.toString(clientID); 
     msg.content = incoming_str;  
     ch_reception.send(msg, Constant.DISPATCH_PORT); 

  }  // job_request() method 

  void job_result (Message i_msg) { 

     int clientID; 
     Message msg; 
     CData clientdata; 
     String incoming_str; 

     clientID = Integer.parseInt((String) i_msg.communication); 
     incoming_str = (String) i_msg.content; 
     
     clientdata = (CData) client_table.get(new Integer(clientID)); 
     System.out.println("Job result: "+"id="+clientID+ 
             "the rest="+incoming_str); 
     System.out.println("Job result: port sent to "+clientdata.getPort());   

     msg = new Message(); 
     msg.intention = "Done"; 
     msg.content = incoming_str;  
     ch_reception.send(msg, clientdata.getHostName(), 
               clientdata.getPort()); 
     
     System.out.println("Reception : Sending result back to" + 
               " client at port number " + clientdata.getPort() + 
                ", hostname "+  clientdata.getHostName()); 

  } // job_result() method 
  

} 

Listing 5.
 
import java.io.*; 
import java.net.*; 
import java.util.*; 

public class Dispatcher extends Thread 
{     
  private     Channel ch_dispatch; 
  private     int service_port[] = new int[Constant.MAX_PORT]; 
  private     String service_host[] = new String[Constant.MAX_PORT]; 
  private     int now, no_service; 
   
  public Dispatcher () 
    { 
      ch_dispatch = new Channel(Constant.DISPATCH_PORT); 
      now = -1; 
      no_service = -1; 
    }  
   
  public void run() 
    {         
      String line, command; 
      String incoming_str; 
      int index; 
      String in_host, in_port; 
      Message msg; 

       
      while (true) { 

          msg = ch_dispatch.receive(); 
          incoming_str = (String)msg.content; 
   System.out.println("Dispatch incoming str : " + incoming_str); 

          command = msg.intention; 

          if (command.compareTo("Request") == 0) { 
              dispatch_job(msg); 
          } else if (command.compareTo("New Service") == 0) { 
              new_service(msg); 
          } else if (command.compareTo("Relinquish Service")==0) {       
       // yet to be implemented 
          } 

      } // while loop 

  } // run() method 
  

  void dispatch_job(Message i_msg) { 

      Message msg; 
      int clientID; 
      String incoming_str; 
  

      clientID = Integer.parseInt((String) i_msg.communication); 
      incoming_str = (String) i_msg.content; 

      System.out.println(incoming_str); 
  

      if (now > -1) { 
     
          msg = new Message(); 
          msg.intention = "Dispatch"; 
          msg.communication = Integer.toString(clientID); 
          msg.content = incoming_str; 
          ch_dispatch.send(msg,service_host[now] ,service_port[now]); 
          System.out.println("Dispatch : Job sent to service agent at port 
number " + 
                      service_port[now] + ", host " + service_host[now]); 
         
          now = (now+1) % (no_service+1); 
      } else { 

          String reception; 

          reception = Integer.toString(Constant.JOB_RESULT) + " " + 
                    clientID + " " + 
                    Integer.toString(Constant.JOB_AGENT_UNAVAIL); 

          //                    "Error : No Service agent available to handle 
the " + 
          //                    "request job!|"; 

          msg = new Message(); 
          msg.intention = "Error";  
          msg.content = reception; 
          ch_dispatch.send(msg, Constant.RECEPTION_PORT);                   
       } 

  }  // dispatch_job() method 
  
  

  void new_service(Message i_msg) { 

     String in_host, in_port, incoming_str; 
     int index; 
  

     incoming_str = (String) i_msg.content; 

     index = incoming_str.indexOf(' '); 
     in_host = new String(incoming_str.substring(0, index)); 
     in_port  = new String(incoming_str.substring(index + 1)); 
        
     if (no_service == -1) 
        now++; 
     no_service++; 
        
     System.out.println("Dispatch : New service agent at port number " +  
                     in_port + ", hostname " + in_host); 
     service_port[no_service] = Integer.parseInt(in_port); 
     service_host[no_service] = in_host; 

  } // new_service() method 

} 

Listing 6.
  
import java.io.*;  
import java.net.*;  

public class Service extends Thread  
{  
  private Channel ch_service, ch_assigned_service;  
  protected  String   prog_name;  
  private       String   gateway_hostname;  
  private       int port;  
    
  public Service(String gateway_hostname)  
    {  
      this.gateway_hostname = gateway_hostname;  

      // set up a temp channel to communicate with the Gateway  
      ch_service = new Channel(Constant.SERVICE_PORT);  
        
      try          
        {  
          String service =  
            InetAddress.getLocalHost().getHostName();  
          Message msg = new Message();  
          msg.intention = "New Service";  
          msg.content = service;  
          ch_service.send(msg, gateway_hostname, Constant.REGISTRY_PORT);  
        }  
      catch (UnknownHostException e)  
        {  
   System.out.println(e);  
        }  

      Message msg = ch_service.receive();  
      String line = (String) msg.content;  
        
      port = Integer.parseInt(line);  
        
      System.out.println("Service : assigned port number is " + port);  
        
      // close the ch_service channel using the default port  
      msg.intention = "stop";  
        
      ch_service.send(msg, Constant.SERVICE_PORT);  
      // System.out.println("Service : Channel ch_service closed");  
        
      // setting up a new channel with the assigned port number  
      if (port != -1)  
        ch_assigned_service = new Channel(port);  
    }  
    
  public boolean ConnectionAccepted()  
    {  
      if (port == -1)  
        return false;  
      else  
        return true;  
    }  
    
  public void run()  
    {      
      String  request, prog_name, result;  
      int clientID, index;  
        
      while (true)  
        {  
          Message msg = ch_assigned_service.receive();  
          clientID = Integer.parseInt((String) msg.communication);  
          request = (String) msg.content;  
          System.out.println("Service incoming_str : " + request);  
     
          SpawnProcess sp = new SpawnProcess(gateway_hostname, clientID, 
request);  
          sp.start();  
          System.out.println("Service : Process " + request + " spawned!");  
 }  
    }  
    
  public static void main(String args[])  
    {  
      Service service = new Service(args[0]);  
        
      if (service.ConnectionAccepted()==true)  
        service.start();  
        
      else  
        {  
          System.out.println("Gateway Service Ports are all in use");  
          System.out.println("Please attempt a connection at a later time");  
          System.exit(1);  
        }  
    }  
}  

Listing 7.
  
import java.io.*;  
import java.net.*;  

class SpawnProcess extends Thread  
{  
  private int clientID;  
  private String prog_name;  
  private String agate_hostname;  
  private String parameters;  

  public SpawnProcess(String HostName, int ClientID, String Request)  
    {  
      int index;  

      agate_hostname = HostName;  
      clientID = ClientID;    
      index = Request.indexOf(' ');  
      if (index > 0) {  
         prog_name = Request.substring(0, index);  
         parameters = Request.substring(index + 1);  
      } else {  
         prog_name = Request;  
         parameters = null;  
      }  
      System.out.println("prog name= "+prog_name+" param="+parameters);  
    }  
    
  public void run()  
    {  
      Channel ch_ps;  
      InetAddress local;  
      String hostname;  
        
      try  
        {  
          Process p = Runtime.getRuntime().exec(prog_name);  
          System.out.println("SpawnProcess : executing with" + 
prog_name+parameters);  
     
          if (parameters != null) {  
             PrintWriter pout = new PrintWriter(p.getOutputStream());  
             pout.println(parameters);  
             pout.flush();  
             pout.close();  
          }  

          DataInputStream din = new DataInputStream(new 
BufferedInputStream(p.getInputStream()));  
     
          String result, part;  
          result = new String();  
     
          while ((part=din.readLine()) != null)  
     {  
              result = result + part + "\n";  
     }  
     
          if (result.equalsIgnoreCase("")==true)  
            result = result + part;  
     
          ch_ps = new Channel(Constant.PS_PORT);            
     
          Message msg = new Message();  
          msg.intention =  "Result";  
          msg.content = Integer.toString(Constant.JOB_EXEC_OK) + " " + result;  
          msg.communication = Integer.toString(clientID);  
          ch_ps.send(msg, Constant.FACILITATION_PORT);  
          System.out.println("Spawned Process : " + result + " routed to 
facilitator at " + agate_hostname);  
          msg.intention = "stop";  
          ch_ps.send(msg, Constant.PS_PORT);  

        } catch (IOException e)  
          { System.out.println("io : " + e); }  
    }  
}  

Listing 8.
  
   
 try  
    {  
     Process p = Runtime.getRuntime().exec(prog_name);  
     System.out.println("SpawnProcess : executing with" + 
prog_name+parameters);  
    
     if (parameters != null) {  
       PrintWriter pout = new PrintWriter(p.getOutputStream());  
       pout.println(parameters);  
       pout.flush();  
       pout.close();  
     }  

  DataInputStream din = new DataInputStream(new 
BufferedInputStream(p.getInputStream()));  
   

Listing 9.
  
    Channel ch_ps;  

     ch_ps = new Channel(Constant.PS_PORT);       
       
    
     Message msg = new Message();  
     msg.intention = "Result";  
     msg.communication = Integer.toString(clientID);  
     msg.content = result;  
     ch_ps.send(msg, Constant.FACILITATION_PORT);  



 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: info@sys-con.com

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.