SharkCORBAServer.java :  » Workflow-Engines » shark » org » enhydra » shark » corba » poa » Java Open Source

Java Open Source » Workflow Engines » shark 
shark » org » enhydra » shark » corba » poa » SharkCORBAServer.java
package org.enhydra.shark.corba.poa;

// Server will use the naming service.
// The package containing special exceptions thrown by the name service.

import java.util.Properties;

import org.enhydra.shark.api.admin.UserGroupManagerAdmin;
import org.enhydra.shark.api.client.wfservice.NameValue;
import org.enhydra.shark.api.client.wfservice.SharkInterface;
import org.enhydra.shark.api.common.SharkConstants;
import org.enhydra.shark.client.utilities.DeadlineChecker;
import org.enhydra.shark.client.utilities.SharkInterfaceWrapper;
import org.enhydra.shark.corba.WorkflowService.SharkConnection;
import org.enhydra.shark.corba.WorkflowService.SharkConnectionHelper;
import org.enhydra.shark.corba.WorkflowService.SharkInterfacePOA;
import org.enhydra.shark.utilities.MiscUtilities;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.InvalidName;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.Servant;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;
import org.omg.PortableServer.POAPackage.ObjectNotActive;
import org.omg.PortableServer.POAPackage.ServantAlreadyActive;
import org.omg.PortableServer.POAPackage.ServantNotActive;
import org.omg.PortableServer.POAPackage.WrongAdapter;
import org.omg.PortableServer.POAPackage.WrongPolicy;
import org.omg.WfBase.BaseException;
import org.omg.WfBase.NameValueInfo;
import org.omg.WorkflowModel.WfCreateProcessEventAudit;
import org.omg.WorkflowModel.WfDataEventAudit;
import org.omg.WorkflowModel.WfStateEventAudit;

/**
 * The server class for engine. It is registered in 'CORBA' name server. The client
 * applications has to get this object from the name server.
 * 
 * @author Sasa Bojanic
 * @author Vladimir Puskas
 * @author Rich Robinson
 * @author Andy Zeneski (jaz@ofbiz.org)
 * @author David Forslund
 */
public class SharkCORBAServer extends SharkInterfacePOA {

   private SharkInterface shark;

   private ORB orb;

   private String engineName;

   private String nsHost;

   private String nsPort;

   boolean trackObjects;

   private POA rootPOA;

   private SharkConnection connect = null;

   public SharkCORBAServer(String engineName,
                           String nsHost,
                           String nsPort,
                           SharkInterface shark) {
      // all parameters are required and cannot be null
      if (engineName == null)
         throw new IllegalArgumentException("Engine name cannot be null");
      if (nsHost == null)
         throw new IllegalArgumentException("Name server host cannot be null");
      if (nsPort == null)
         throw new IllegalArgumentException("Name server port cannot be null");
      if (shark == null)
         throw new IllegalArgumentException("Shark instance cannot be null");

      this.engineName = engineName;
      this.nsHost = nsHost;
      this.nsPort = nsPort;
      this.shark = shark;
      Properties shkProps = new Properties();
      try {
         shkProps = MiscUtilities.convertNameValueArrayToProperties(shark.getProperties());
      } catch (Exception ex) {
      }

      this.trackObjects = Boolean.valueOf(shkProps.getProperty("CORBAServer.TrackAndDisconnect",
                                                               "false"))
         .booleanValue();
      boolean ignoreProblematicRequester = new Boolean(shkProps.getProperty("CORBAServer.ignoreProblematicRequester",
                                                                            "true")).booleanValue();
      WfLinkingRequesterForCORBA.setIgnoreProblematicRequesterProcess(ignoreProblematicRequester);

      // Register a shutdown hook that cleanly shuts down Shark
      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
            shutdownORB();
            if (null != p) {
               p.destroy();
            }
         }
      });
   }

   public void startCORBAServer() throws Exception {
      // orb conf
      String[] a1 = {
            "-ORBInitialHost", nsHost, "-ORBInitialPort", nsPort
      };
      String[] a2 = {
            "-ORBInitRef",
            "NameService=corbaloc::" + nsHost + ":" + nsPort + "/NameService"
      };

      // create and initialize the ORB
      String vers = System.getProperty("java.version");
      System.out.println("java.version " + vers);
      if (vers.compareTo("1.4") < 0) {
         orb = ORB.init(a1, null);
      } else {
         orb = ORB.init(a2, null);
      }
      // org.omg.PortableServer.POA rootPOA = null;
      try {
         rootPOA = org.omg.PortableServer.POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
         /*
          * Policy[] tpolicy = new Policy[3]; tpolicy[0] =
          * rootPOA.create_id_assignment_policy(IdAssignmentPolicyValue.SYSTEM_ID);
          * tpolicy[1] =
          * rootPOA.create_servant_retention_policy(ServantRetentionPolicyValue.RETAIN);
          * tpolicy[2] =
          * rootPOA.create_implicit_activation_policy(ImplicitActivationPolicyValue.IMPLICIT_ACTIVATION);
          * childPOA = rootPOA.create_POA("childPOA",rootPOA.the_POAManager(), tpolicy);
          */
         // rootPOA.servant_to_reference(this);
      } catch (org.omg.CORBA.ORBPackage.InvalidName invalidName) {
         invalidName.printStackTrace(); // To change body of catch statement use File |
         // Settings | File Templates.
      } /*
          * catch (InvalidPolicy invalidPolicy) { invalidPolicy.printStackTrace(); //To
          * change body of catch statement use File | Settings | File Templates. } catch
          * (AdapterAlreadyExists adapterAlreadyExists) {
          * adapterAlreadyExists.printStackTrace(); //To change body of catch statement
          * use File | Settings | File Templates. } /*catch (ServantNotActive
          * servantNotActive) { servantNotActive.printStackTrace(); //To change body of
          * catch statement use File | Settings | File Templates. } catch (WrongPolicy
          * wrongPolicy) { wrongPolicy.printStackTrace(); //To change body of catch
          * statement use File | Settings | File Templates. }
          */
      // _this(orb);
      // orb.connect(this._this_object());
      // get the root naming context
      org.omg.CORBA.Object objRef = null;
      try {
         objRef = orb.resolve_initial_references("NameService");
      } catch (Exception ex) {
         System.err.println("startCORBAServer: " + ex);
         // The following code is included to enable Shark Server to be
         // started
         // from Shark project script that starts all project parts at
         // ones
         for (int i = 0; i < 2; i++) {

            try {
               Thread.sleep(2500);
               objRef = orb.resolve_initial_references("NameService");
            } catch (Exception ex2) {
               System.err.println("NameService failed " + ex2);
            }
            if (objRef != null) {
               break;
            }
         }
      }

      // check the root
      if (objRef == null) {
         throw new Exception("Unable to obtain initial reference from orb");
      }

      // get the naming context
      NamingContext ncRef = NamingContextHelper.narrow(objRef);
      if (ncRef == null) {
         throw new Exception("Null NamingContext");
      } 
      System.out.println("NameService contacted");
      // bind the object reference in naming
      NameComponent nc = new NameComponent(engineName, "");
      NameComponent path[] = {
         nc
      };
      try {
         rootPOA.the_POAManager().activate();
         rootPOA.activate_object(this);
         SharkCORBAUtilities.setPOA(rootPOA);
         SharkCORBAUtilities.setORB(orb);
         ncRef.rebind(path, this._this_object());

         System.out.println("CORBA Server registered and activated");
      } catch (NotFound e) {
         throw new Exception(e);
      } catch (CannotProceed e) {
         throw new Exception(e);
      } catch (InvalidName e) {
         throw new Exception(e);
      } catch (AdapterInactive adapterInactive) {
         adapterInactive.printStackTrace();
      } catch (ServantAlreadyActive es) {
         es.printStackTrace();
      } catch (WrongPolicy wp) {
         wp.printStackTrace();
      }
      // start the orb
      orb.run(); // WARNING this blocks; objects calling this method
      // should be threaded

   }

   public ORB getBoundORB() {
      return orb;
   }

   public void shutdownORB() {
      try {
         orb.disconnect(this._this_object());
         orb.shutdown(false);
      } catch (Exception e) {
         // maybe throw some log4j in here
      }
   }

   void shutdown() {
      shutdownORB();
      System.exit(0);
   }

   public SharkInterface getShark() {
      return shark;
   }

   public SharkConnection getSharkConnection() throws BaseException {

      // if (connect != null) return connect;
      try {
         SharkConnectionCORBA connectImpl = new SharkConnectionCORBA(this,
                                                                     shark.getSharkConnection());
         rootPOA.activate_object(connectImpl);
         connect = SharkConnectionHelper.narrow(rootPOA.servant_to_reference(connectImpl));

      } catch (ServantAlreadyActive servantAlreadyActive) {
         servantAlreadyActive.printStackTrace();
      } catch (WrongPolicy wrongPolicy) {
         wrongPolicy.printStackTrace();
      } catch (ServantNotActive servantNotActive) {
         servantNotActive.printStackTrace();
      } catch (Exception ex) {
         ex.printStackTrace();
      }

      return connect;
      // return new SharkConnectionCORBA(this, shark.getSharkConnection())._this();
   }

   public NameValueInfo[] getProperties() throws BaseException {
      NameValue[] props = null;
      try {
         props = shark.getProperties();
      } catch (Exception ex) {
         throw new BaseException();
      }
      return SharkCORBAUtilities.makeCORBANameValueInfoArray(props);
   }

   boolean validateUser(String username, String pwd) {
      try {
         Object plugin = shark.getPlugIn(SharkConstants.PLUGIN_USER_GROUP);
         if (plugin instanceof UserGroupManagerAdmin) {
            UserGroupManagerAdmin uga = (UserGroupManagerAdmin) plugin;
            return uga.validateUser(username, pwd);
         }
      } catch (Exception ex) {
      }
      return true;
   }

   private static Process p;

   private static long nameserverRestart_ms = 0;

   // private static Thread penelope;
   // If exists, first argument is the path to Shark configuration file
   public static void main(String args[]) {
      try {

         SharkInterfaceWrapper.setProperties(args[0], true);
         org.enhydra.shark.api.client.wfservice.SharkInterface shark = SharkInterfaceWrapper.getShark();

         Properties properties = MiscUtilities.convertNameValueArrayToProperties(shark.getProperties());
         String nameserverhost = properties.getProperty("nameserverhost", "localhost");
         final String nameserverport = properties.getProperty("nameserverport", "10123");
         String enginename = properties.getProperty("enginename", "Shark");
         final String nameServerExecutable = properties.getProperty("nameserver.executable",
                                                                    null);
         String nameserverRestart = properties.getProperty("nameserver.restarting_period_minutes",
                                                           "0");

         double nsrmin = 0;
         try {
            nsrmin = Double.parseDouble(nameserverRestart);
            nameserverRestart_ms = (long) (nsrmin * 60 * 1000);
         } catch (Exception ex) {
         }
         // initialize deadline timer
         String delay = null;
         if (args.length > 1) {
            delay = args[1];
         } else {
            delay = properties.getProperty("Deadlines.pollingTime", "300000");
         }
         if (properties.getProperty("Deadlines.SERVER_SIDE_CHECKING", "false")
            .equals("true")) {
            DeadlineChecker dc=new DeadlineChecker(SharkInterfaceWrapper.getDefaultUser(), null, Long.parseLong(delay), 100, 10, true);
         }

         // create/start the server
         final SharkCORBAServer ws = new SharkCORBAServer(enginename,
                                                          nameserverhost,
                                                          nameserverport,
                                                          shark);
         if (null != nameServerExecutable) {
            if (nameserverRestart_ms > 0) {
               System.out.println("Nameserver will be restarted every "
                                  + nameserverRestart + " minutes!");
            }

            new Thread() {
               public void run() {
                  while (true) {
                     try {
                        p = Runtime.getRuntime().exec(nameServerExecutable
                                                      + " -ORBInitialPort "
                                                      + nameserverport);

                        System.out.println("Nameserver is (re)started!");
                        // (re)register with name server in a separate
                        // thread
                        new Thread() {
                           public void run() {
                              try {
                                 ws.startCORBAServer();
                              } catch (Exception ex) {
                                 ex.printStackTrace(System.out);
                                 throw new Error();

                              }
                           }
                        }.start();
                        if (nameserverRestart_ms > 0) {
                           new Thread() {
                              public void run() {
                                 try {
                                    Thread.sleep(nameserverRestart_ms);
                                 } catch (Exception ex) {
                                 } finally {
                                    p.destroy();
                                 }
                              }
                           }.start();
                        }

                     } catch (Throwable t) {
                        t.printStackTrace();
                        System.out.println("Didn't start the nameserver");
                        // throw new RootError("Didn't start the
                        // nameserver",t);
                     }

                     while (true) {
                        try {
                           p.waitFor();
                        } catch (InterruptedException e) {
                           continue;
                        }

                        // Process is terminated
                        break;
                     }
                  }
               }
            }.start();
         } else {
            ws.startCORBAServer();
         }

      } catch (Throwable e) {
         e.printStackTrace(System.out);
         throw new Error();
      }
   }

   public void doneWith(org.omg.CORBA.Object toDisconnect) {
      // get the servant associated with this CORBA object
      Servant s = null;
      try {
         s = rootPOA.reference_to_servant(toDisconnect);
      } catch (ObjectNotActive objectNotActive) {
         objectNotActive.printStackTrace();
      } catch (WrongPolicy wrongPolicy) {
         wrongPolicy.printStackTrace();
      } catch (WrongAdapter wrongAdapter) {
         wrongAdapter.printStackTrace();
      }

      if (s instanceof Collective) {
         ((Collective) s).__disband(orb);
      } else {
         try {
            if (toDisconnect instanceof WfCreateProcessEventAudit) {
               WfLinkingRequesterForCORBA.emptyCollective(((WfCreateProcessEventAudit) toDisconnect).process_key(),
                                                          getBoundORB());
            }
            if (toDisconnect instanceof WfDataEventAudit) {
               WfLinkingRequesterForCORBA.emptyCollective(((WfDataEventAudit) toDisconnect).process_key(),
                                                          getBoundORB());
            }
            if (toDisconnect instanceof WfStateEventAudit) {
               WfLinkingRequesterForCORBA.emptyCollective(((WfStateEventAudit) toDisconnect).process_key(),
                                                          getBoundORB());
            }
            toDisconnect._release();
            ;
            // orb.disconnect(toDisconnect);
         } catch (Exception ex) {
            System.err.println("exception in doneWith" + ex);
         }
      }
   }

   public static boolean doesTransactionExist() {
      return false;
   }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.