Home » openejb-3.1.2-src » org.apache » openejb » server » [javadoc | source]

    1   /**
    2    * Licensed to the Apache Software Foundation (ASF) under one or more
    3    * contributor license agreements.  See the NOTICE file distributed with
    4    * this work for additional information regarding copyright ownership.
    5    * The ASF licenses this file to You under the Apache License, Version 2.0
    6    * (the "License"); you may not use this file except in compliance with
    7    * the License.  You may obtain a copy of the License at
    8    *
    9    *     http://www.apache.org/licenses/LICENSE-2.0
   10    *
   11    * Unless required by applicable law or agreed to in writing, software
   12    * distributed under the License is distributed on an "AS IS" BASIS,
   13    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   14    * See the License for the specific language governing permissions and
   15    * limitations under the License.
   16    */
   17   package org.apache.openejb.server;
   18   
   19   import org.apache.openejb.loader.FileUtils;
   20   import org.apache.openejb.loader.SystemInstance;
   21   import org.apache.openejb.util.LogCategory;
   22   import org.apache.openejb.util.Logger;
   23   import org.apache.openejb.util.Messages;
   24   import org.apache.openejb.spi.ContainerSystem;
   25   import org.apache.openejb.assembler.classic.ServiceInfo;
   26   import org.apache.openejb.assembler.classic.OpenEjbConfiguration;
   27   import org.apache.xbean.finder.ResourceFinder;
   28   import org.apache.xbean.recipe.ObjectRecipe;
   29   import org.apache.xbean.recipe.Option;
   30   
   31   import javax.naming.NamingException;
   32   import javax.naming.Binding;
   33   import javax.naming.NamingEnumeration;
   34   import javax.resource.spi.ResourceAdapter;
   35   import java.io.File;
   36   import java.io.FileInputStream;
   37   import java.io.FileOutputStream;
   38   import java.io.IOException;
   39   import java.net.InetAddress;
   40   import java.util.ArrayList;
   41   import java.util.Iterator;
   42   import java.util.List;
   43   import java.util.Map;
   44   import java.util.Properties;
   45   
   46   /**
   47    * @version $Rev: 791660 $ $Date: 2009-07-06 17:31:49 -0700 (Mon, 06 Jul 2009) $
   48    * @org.apache.xbean.XBean element="serviceManager"
   49    */
   50   public class ServiceManager {
   51   
   52       static Messages messages = new Messages("org.apache.openejb.server.util.resources");
   53       static Logger logger = Logger.getInstance(LogCategory.OPENEJB_SERVER_REMOTE, "org.apache.openejb.server.util.resources");
   54   
   55       private static ServiceManager manager;
   56   
   57       private static ServerService[] daemons;
   58   
   59       private boolean stop = false;
   60   
   61       public ServiceManager() {
   62       }
   63   
   64       public static ServiceManager getManager() {
   65           if (manager == null) {
   66               manager = new ServiceManager();
   67           }
   68   
   69           return manager;
   70       }
   71   
   72       public static ServiceManager get() {
   73           return manager;
   74       }
   75   
   76   
   77       // Have properties files (like xinet.d) that specifies what daemons to
   78       // Look into the xinet.d file structure again
   79       // conf/server.d/
   80       //    admin.properties
   81       //    ejbd.properties
   82       //    webadmin.properties
   83       //    telnet.properties
   84       //    corba.properties
   85       //    soap.properties
   86       //    xmlrpc.properties
   87       //    httpejb.properties
   88       //    webejb.properties
   89       //    xmlejb.properties
   90       // Each contains the class name of the daemon implamentation
   91       // The port to use
   92       // whether it's turned on
   93   
   94       // May be reusable elsewhere, move if another use occurs
   95       public static class ServiceFinder {
   96           private final ResourceFinder resourceFinder;
   97           private ClassLoader classLoader;
   98   
   99           public ServiceFinder(String basePath) {
  100               this(basePath, Thread.currentThread().getContextClassLoader());
  101           }
  102   
  103           public ServiceFinder(String basePath, ClassLoader classLoader) {
  104               this.resourceFinder = new ResourceFinder(basePath, classLoader);
  105               this.classLoader = classLoader;
  106           }
  107   
  108           public Map mapAvailableServices(Class interfase) throws IOException, ClassNotFoundException {
  109               Map services = resourceFinder.mapAvailableProperties(ServerService.class.getName());
  110   
  111               for (Iterator iterator = services.entrySet().iterator(); iterator.hasNext();) {
  112                   Map.Entry entry = (Map.Entry) iterator.next();
  113                   String name = (String) entry.getKey();
  114                   Properties properties = (Properties) entry.getValue();
  115   
  116                   String className = properties.getProperty("className");
  117                   if (className == null) {
  118                       className = properties.getProperty("classname");
  119                       if (className == null) {
  120                           className = properties.getProperty("server");
  121                       }
  122                   }
  123   
  124                   Class impl = classLoader.loadClass(className);
  125   
  126                   properties.put(interfase, impl);
  127                   String rawProperties = resourceFinder.findString(interfase.getName() + "/" + name);
  128                   properties.put(Properties.class, rawProperties);
  129   
  130               }
  131               return services;
  132           }
  133       }
  134   
  135       public void init() throws Exception {
  136           try {
  137               org.apache.log4j.MDC.put("SERVER", "main");
  138               InetAddress localhost = InetAddress.getLocalHost();
  139               org.apache.log4j.MDC.put("HOST", localhost.getHostName());
  140           } catch (Throwable e) {
  141           }
  142   
  143           DiscoveryRegistry registry = new DiscoveryRegistry();
  144           SystemInstance.get().setComponent(DiscoveryRegistry.class, registry);
  145   
  146           ServiceFinder serviceFinder = new ServiceFinder("META-INF/");
  147   
  148           Map<String, Properties> availableServices = serviceFinder.mapAvailableServices(ServerService.class);
  149   
  150           List enabledServers = new ArrayList();
  151   
  152           OpenEjbConfiguration conf = SystemInstance.get().getComponent(OpenEjbConfiguration.class);
  153           for (Iterator iterator = availableServices.entrySet().iterator(); iterator.hasNext();) {
  154               Map.Entry entry = (Map.Entry) iterator.next();
  155               String serviceName = (String) entry.getKey();
  156               Properties serviceProperties = (Properties) entry.getValue();
  157   
  158               logger.debug("Processing ServerService(id="+serviceName+")");
  159   
  160               overrideProperties(serviceName, serviceProperties);
  161               serviceProperties.setProperty("name", serviceName);
  162   
  163               if (conf != null && conf.facilities != null){
  164                   ServiceInfo info = new ServiceInfo();
  165                   info.className = ((Class) serviceProperties.get(ServerService.class)).getName();
  166                   info.service = "ServerService";
  167                   info.id = serviceName;
  168                   info.properties = serviceProperties;
  169                   conf.facilities.services.add(info);
  170               }
  171   
  172   
  173   
  174               boolean enabled = isEnabled(serviceProperties);
  175   
  176               logger.debug("Found ServerService(id=" + serviceName + ", disabled=" + (!enabled) + ")");
  177   
  178               if (enabled) {
  179   
  180                   Class serviceClass = (Class) serviceProperties.get(ServerService.class);
  181   
  182                   logger.debug("Creating ServerService(id=" + serviceName + ")");
  183   
  184                   try {
  185                       // Create Service
  186                       ServerService service = null;
  187   
  188   
  189                       ObjectRecipe recipe = new ObjectRecipe(serviceClass);
  190                       try {
  191                           // Do not import.  This class is not available in xbean-reflect-3.3
  192                           if (org.apache.xbean.recipe.ReflectionUtil.findStaticFactory(serviceClass, "createServerService", null, null) != null){
  193                               recipe = new ObjectRecipe(serviceClass, "createServerService");
  194                           }
  195                       } catch (Throwable e) {
  196                       }
  197   
  198                       recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
  199                       recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
  200   
  201                       service = (ServerService) recipe.create(serviceClass.getClassLoader());
  202   
  203                       if (service instanceof DiscoveryAgent){
  204                           DiscoveryAgent agent = (DiscoveryAgent) service;
  205                           registry.addDiscoveryAgent(agent);
  206                       }
  207   
  208                       if (!(service instanceof SelfManaging)) {
  209                           service = new ServicePool(service, serviceName, serviceProperties);
  210                           service = new ServiceLogger(service);
  211                           service = new ServiceAccessController(service);
  212                           service = new ServiceDaemon(service);
  213                       }
  214   
  215                       service.init(serviceProperties);
  216                       enabledServers.add(service);
  217                   } catch (Throwable t) {
  218                       logger.error("service.instantiation.err", t, serviceClass.getName(), t.getClass().getName(), t.getMessage());
  219                   }
  220               }
  221   
  222           }
  223   
  224           daemons = (ServerService[]) enabledServers.toArray(new ServerService[]{});
  225       }
  226   
  227       private void overrideProperties(String serviceName, Properties serviceProperties) throws IOException {
  228           FileUtils base = SystemInstance.get().getBase();
  229   
  230           // Override with file from conf dir
  231           File conf = base.getDirectory("conf");
  232           if (conf.exists()) {
  233               File serviceConfig = new File(conf, serviceName + ".properties");
  234               if (serviceConfig.exists()) {
  235                   FileInputStream in = new FileInputStream(serviceConfig);
  236                   try {
  237                       serviceProperties.load(in);
  238                   } finally {
  239                       in.close();
  240                   }
  241               } else {
  242                   FileOutputStream out = new FileOutputStream(serviceConfig);
  243                   try {
  244                       String rawPropsContent = (String) serviceProperties.get(Properties.class);
  245                       out.write(rawPropsContent.getBytes());
  246                   } finally {
  247                       out.close();
  248                   }
  249               }
  250           }
  251   
  252           // Override with system properties
  253           String prefix = serviceName + ".";
  254           Properties sysProps = new Properties(System.getProperties());
  255           sysProps.putAll(SystemInstance.get().getProperties());
  256           for (Iterator iterator1 = sysProps.entrySet().iterator(); iterator1.hasNext();) {
  257               Map.Entry entry1 = (Map.Entry) iterator1.next();
  258               String key = (String) entry1.getKey();
  259               Object value = entry1.getValue();
  260               if (value instanceof String && key.startsWith(prefix)) {
  261                   key = key.replaceFirst(prefix, "");
  262                   serviceProperties.setProperty(key, (String) value);
  263               }
  264           }
  265   
  266       }
  267   
  268       private boolean isEnabled(Properties props) {
  269           // if it should be started, continue
  270           String disabled = props.getProperty("disabled", "");
  271   
  272           if (disabled.equalsIgnoreCase("yes") || disabled.equalsIgnoreCase("true")) {
  273               return false;
  274           } else {
  275               return true;
  276           }
  277       }
  278   
  279       public synchronized void start() throws ServiceException {
  280           start(true);
  281       }
  282   
  283       public synchronized void start(boolean block) throws ServiceException {
  284           boolean display = System.getProperty("openejb.nobanner") == null;
  285   
  286           if (display) {
  287               System.out.println("  ** Starting Services **");
  288               printRow("NAME", "IP", "PORT");
  289           }
  290   
  291           for (int i = 0; i < daemons.length; i++) {
  292               ServerService d = daemons[i];
  293               try {
  294                   d.start();
  295                   if (display && d.getPort() != -1) {
  296                       printRow(d.getName(), d.getIP(), d.getPort() + "");
  297                   }
  298               } catch (Exception e) {
  299                   logger.fatal("Service Start Failed: "+d.getName() + " " + d.getIP() + " " + d.getPort() + ": " + e.getMessage());
  300                   if (display) {
  301                       printRow(d.getName(), "----", "FAILED");
  302                   }
  303               }
  304           }
  305           if (display) {
  306               System.out.println("-------");
  307               System.out.println("Ready!");
  308           }
  309           if (!block) return;
  310   
  311           /*
  312           * This will cause the user thread (the thread that keeps the
  313           *  vm alive) to go into a state of constant waiting.
  314           *  Each time the thread is woken up, it checks to see if
  315           *  it should continue waiting.
  316           *
  317           *  To stop the thread (and the VM), just call the stop method
  318           *  which will set 'stop' to true and notify the user thread.
  319           */
  320           try {
  321               while (!stop) {
  322   
  323                   this.wait(Long.MAX_VALUE);
  324               }
  325           } catch (Throwable t) {
  326               logger.fatal("Unable to keep the server thread alive. Received exception: " + t.getClass().getName() + " : " + t.getMessage());
  327           }
  328           logger.info("Stopping Remote Server");
  329       }
  330   
  331       public synchronized void stop() throws ServiceException {
  332           logger.info("Received stop signal");
  333           stop = true;
  334   
  335           try {
  336               ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
  337               NamingEnumeration<Binding> namingEnumeration = null;
  338               try {
  339                   namingEnumeration = containerSystem.getJNDIContext().listBindings("openejb/resourceAdapter");
  340               } catch (NamingException ignored) {
  341                   // no resource adapters were created
  342               }
  343               while (namingEnumeration != null && namingEnumeration.hasMoreElements()) {
  344                   Binding binding = namingEnumeration.nextElement();
  345                   Object object = binding.getObject();
  346                   ResourceAdapter resourceAdapter = (ResourceAdapter) object;
  347                   try {
  348                       resourceAdapter.stop();
  349                   } catch (Exception e) {
  350                       logger.fatal("ResourceAdapter Shutdown Failed: "+binding.getName(), e);
  351                   }
  352               }
  353           } catch (Throwable e) {
  354               logger.fatal("Unable to get ResourceAdapters from JNDI.  Stop must be called on them for proper vm shutdown.", e);
  355           }
  356   
  357           for (int i = 0; i < daemons.length; i++) {
  358               try {
  359                   daemons[i].stop();
  360               } catch (ServiceException e) {
  361                   logger.fatal("Service Shutdown Failed: "+daemons[i].getName()+".  Exception: "+e.getMessage(), e);
  362               }
  363           }
  364           notifyAll();
  365       }
  366   
  367       private void printRow(String col1, String col2, String col3) {
  368   
  369           col1 += "                    ";
  370           col1 = col1.substring(0, 20);
  371   
  372           col2 += "                    ";
  373           col2 = col2.substring(0, 15);
  374   
  375           col3 += "                    ";
  376           col3 = col3.substring(0, 6);
  377   
  378           StringBuffer sb = new StringBuffer(50);
  379           sb.append("  ").append(col1);
  380           sb.append(" ").append(col2);
  381           sb.append(" ").append(col3);
  382   
  383           System.out.println(sb.toString());
  384       }
  385   }

Home » openejb-3.1.2-src » org.apache » openejb » server » [javadoc | source]