Beispiel #1
0
  /**
   * Create an <code>ObjectName</code> for this <code>Loader</code> object.
   *
   * @param domain Domain in which this name is to be created
   * @param loader The Loader to be named
   * @exception MalformedObjectNameException if a name cannot be created
   */
  static ObjectName createObjectName(String domain, Loader loader)
      throws MalformedObjectNameException {

    ObjectName name = null;
    Container container = loader.getContainer();

    if (container instanceof Engine) {
      name = new ObjectName(domain + ":type=Loader");
    } else if (container instanceof Host) {
      name = new ObjectName(domain + ":type=Loader,host=" + container.getName());
    } else if (container instanceof Context) {
      String path = ((Context) container).getPath();
      if (path.length() < 1) {
        path = "/";
      }
      Host host = (Host) container.getParent();
      name = new ObjectName(domain + ":type=Loader,path=" + path + ",host=" + host.getName());
    } else if (container == null) {
      // What is that ???
      DefaultContext defaultContext = loader.getDefaultContext();
      if (defaultContext != null) {
        Container parent = defaultContext.getParent();
        if (parent instanceof Engine) {
          name = new ObjectName(domain + ":type=DefaultLoader");
        } else if (parent instanceof Host) {
          name = new ObjectName(domain + ":type=DefaultLoader,host=" + parent.getName());
        }
      }
    }

    return (name);
  }
  private static StandardContext startWebApp(Host host, WSEndpointDeploymentUnit unit)
      throws Exception {
    StandardContext context = new StandardContext();
    try {
      JBossWebMetaData jbwebMD = unit.getAttachment(WSAttachmentKeys.JBOSSWEB_METADATA_KEY);
      context.setPath(jbwebMD.getContextRoot());
      context.addLifecycleListener(new ContextConfig());
      ServerConfigService config =
          (ServerConfigService)
              unit.getServiceRegistry().getService(WSServices.CONFIG_SERVICE).getService();
      File docBase = new File(config.getValue().getServerTempDir(), jbwebMD.getContextRoot());
      if (!docBase.exists()) {
        docBase.mkdirs();
      }
      context.setDocBase(docBase.getPath());

      final Loader loader = new WebCtxLoader(unit.getAttachment(WSAttachmentKeys.CLASSLOADER_KEY));
      loader.setContainer(host);
      context.setLoader(loader);
      context.setInstanceManager(new LocalInstanceManager());

      addServlets(jbwebMD, context);

      host.addChild(context);
      context.create();
    } catch (Exception e) {
      throw MESSAGES.createContextPhaseFailed(e);
    }
    try {
      context.start();
    } catch (LifecycleException e) {
      throw MESSAGES.startContextPhaseFailed(e);
    }
    return context;
  }
  /**
   * Load and return the Session associated with the specified session identifier from this Store,
   * without removing it. If there is no such stored Session, return <code>null</code>.
   *
   * @param id Session identifier of the session to load
   * @exception ClassNotFoundException if a deserialization error occurs
   * @exception IOException if an input/output error occurs
   */
  @Override
  public Session load(String id) throws ClassNotFoundException, IOException {

    // Open an input stream to the specified pathname, if any
    File file = file(id);
    if (file == null) {
      return (null);
    }

    if (!file.exists()) {
      return (null);
    }
    if (manager.getContext().getLogger().isDebugEnabled()) {
      manager
          .getContext()
          .getLogger()
          .debug(sm.getString(getStoreName() + ".loading", id, file.getAbsolutePath()));
    }

    ObjectInputStream ois = null;
    Loader loader = null;
    ClassLoader classLoader = null;
    ClassLoader oldThreadContextCL = Thread.currentThread().getContextClassLoader();
    try (FileInputStream fis = new FileInputStream(file.getAbsolutePath());
        BufferedInputStream bis = new BufferedInputStream(fis)) {
      Context context = manager.getContext();
      if (context != null) loader = context.getLoader();
      if (loader != null) classLoader = loader.getClassLoader();
      if (classLoader != null) {
        Thread.currentThread().setContextClassLoader(classLoader);
        ois = new CustomObjectInputStream(bis, classLoader);
      } else {
        ois = new ObjectInputStream(bis);
      }

      StandardSession session = (StandardSession) manager.createEmptySession();
      session.readObjectData(ois);
      session.setManager(manager);
      return (session);
    } catch (FileNotFoundException e) {
      if (manager.getContext().getLogger().isDebugEnabled())
        manager.getContext().getLogger().debug("No persisted data file found");
      return (null);
    } finally {
      if (ois != null) {
        // Close the input stream
        try {
          ois.close();
        } catch (IOException f) {
          // Ignore
        }
      }
      Thread.currentThread().setContextClassLoader(oldThreadContextCL);
    }
  }
  @Override
  public void start(StartContext startContext) throws StartException {

    ServerEnvironment env = injectedServerEnvironment.getValue();
    Host virtualHost = injectedVirtualHost.getValue().getHost();
    BundleContext syscontext = injectedSystemContext.getValue();
    WebServer webServer = injectedWebServer.getValue();

    File storageDir =
        new File(
            env.getServerTempDir()
                + File.separator
                + CONTEXT_NAME
                + File.separator
                + "httpservice-root");
    context.setDocBase(storageDir.getPath());
    storageDir.mkdirs();

    context.setPath(CONTEXT_NAME);
    context.addLifecycleListener(new ContextConfig());
    Loader loader = new WebCtxLoader(getClass().getClassLoader());
    loader.setContainer(virtualHost);
    context.setLoader(loader);
    context.setInstanceManager(new LocalInstanceManager());

    context.addMimeMapping("html", "text/html");
    context.addMimeMapping("jpg", "image/jpeg");
    context.addMimeMapping("png", "image/png");
    context.addMimeMapping("gif", "image/gif");
    context.addMimeMapping("css", "text/css");
    context.addMimeMapping("js", "text/javascript");

    virtualHost.addChild(context);

    WEB_LOGGER.registerWebapp(context.getName());
    try {
      context.create();
    } catch (Exception ex) {
      throw new StartException(WebMessages.MESSAGES.createContextFailed(), ex);
    }
    try {
      context.start();
    } catch (LifecycleException ex) {
      throw new StartException(WebMessages.MESSAGES.startContextFailed(), ex);
    }

    Hashtable<String, Object> props = new Hashtable<String, Object>();
    props.put(Constants.SERVICE_RANKING, Integer.MIN_VALUE);
    props.put("provider", getClass().getPackage().getName());

    ServiceFactory serviceFactory = new HttpServiceFactory(webServer, virtualHost, context);
    registration = syscontext.registerService(HttpService.class.getName(), serviceFactory, props);
  }
  private void initializeSerializer()
      throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    log.info("Attempting to use serializer :" + serializationStrategyClass);
    serializer = (Serializer) Class.forName(serializationStrategyClass).newInstance();

    Loader loader = null;

    if (getContainer() != null) {
      loader = getContainer().getLoader();
    }

    ClassLoader classLoader = null;

    if (loader != null) {
      classLoader = loader.getClassLoader();
    }
    serializer.setClassLoader(classLoader);
  }
  @Override
  public synchronized void start() throws Exception {

    Host host = ServerUtil.getDefaultHost().getHost();
    _serverContext = (StandardContext) host.findChild("/" + _contextName);
    if (_serverContext == null) {
      _serverContext = new StandardContext();
      _serverContext.setPath("/" + _contextName);
      File docBase = new File(SERVER_TEMP_DIR, _contextName);
      if (!docBase.exists()) {
        if (!docBase.mkdirs()) {
          throw new RuntimeException("Unable to create temp directory " + docBase.getPath());
        }
      }
      _serverContext.setDocBase(docBase.getPath());
      _serverContext.addLifecycleListener(new ContextConfig());

      final Loader loader = new WebCtxLoader(Thread.currentThread().getContextClassLoader());
      loader.setContainer(host);
      _serverContext.setLoader(loader);
      _serverContext.setInstanceManager(new LocalInstanceManager());

      Wrapper wrapper = _serverContext.createWrapper();
      wrapper.setName(SERVLET_NAME);
      wrapper.setServletClass(SwitchYardRemotingServlet.class.getName());
      wrapper.setLoadOnStartup(1);
      _serverContext.addChild(wrapper);
      _serverContext.addServletMapping("/*", SERVLET_NAME);

      host.addChild(_serverContext);
      _serverContext.create();
      _serverContext.start();

      SwitchYardRemotingServlet remotingServlet = (SwitchYardRemotingServlet) wrapper.getServlet();
      remotingServlet.setEndpointPublisher(this);
      _log.info("Published Remote Service Endpoint " + _serverContext.getPath());
    } else {
      throw new RuntimeException("Context " + _contextName + " already exists!");
    }
  }
Beispiel #7
0
  public Servlet loadServlet() throws ServletException {
    if (instance != null) return instance;

    Servlet servlet = null;
    String actualClass = servletClass;
    if (actualClass == null) {
      throw new ServletException("servlet class has not been specified");
    }

    Loader loader = getLoader();
    // Acquire an instance of the class loader to be used
    if (loader == null) {
      throw new ServletException("No loader.");
    }
    ClassLoader classLoader = loader.getClassLoader();

    // Load the specified servlet class from the appropriate class loader
    Class classClass = null;
    try {
      if (classLoader != null) {
        classClass = classLoader.loadClass(actualClass);
      }
    } catch (ClassNotFoundException e) {
      throw new ServletException("Servlet class not found");
    }
    // Instantiate and initialize an instance of the servlet class itself
    try {
      servlet = (Servlet) classClass.newInstance();
    } catch (Throwable e) {
      throw new ServletException("Failed to instantiate servlet");
    }

    // Call the initialization method of this servlet
    try {
      servlet.init(null);
    } catch (Throwable f) {
      throw new ServletException("Failed initialize servlet.");
    }
    return servlet;
  }
 public ReplicationStream getReplicationStream(byte[] data, int offset, int length)
     throws IOException {
   ByteArrayInputStream fis = null;
   ReplicationStream ois = null;
   Loader loader = null;
   ClassLoader classLoader = null;
   // fix to be able to run the DeltaManager
   // stand alone without a container.
   // use the Threads context class loader
   if (container != null) loader = container.getLoader();
   if (loader != null) classLoader = loader.getClassLoader();
   else classLoader = Thread.currentThread().getContextClassLoader();
   // end fix
   fis = new ByteArrayInputStream(data, offset, length);
   if (classLoader == Thread.currentThread().getContextClassLoader()) {
     ois = new ReplicationStream(fis, new ClassLoader[] {classLoader});
   } else {
     ois =
         new ReplicationStream(
             fis, new ClassLoader[] {classLoader, Thread.currentThread().getContextClassLoader()});
   }
   return ois;
 }
 /**
  * Initialization.
  *
  * @throws ServletException
  */
 @SuppressWarnings("cast")
 @Override
 public void start() throws ServletException {
   log.info("Loading tomcat virtual host");
   if (webappFolder != null) {
     // check for match with base webapp root
     if (webappFolder.equals(webappRoot)) {
       log.error("Web application root cannot be the same as base");
       return;
     }
   }
   ClassLoader classloader = Thread.currentThread().getContextClassLoader();
   // ensure we have a host
   if (host == null) {
     host = createHost();
   }
   host.setParentClassLoader(classloader);
   String propertyPrefix = name;
   if (domain != null) {
     propertyPrefix += '_' + domain.replace('.', '_');
   }
   log.debug("Generating name (for props) {}", propertyPrefix);
   System.setProperty(propertyPrefix + ".webapp.root", webappRoot);
   log.info("Virtual host root: {}", webappRoot);
   log.info("Virtual host context id: {}", defaultApplicationContextId);
   // Root applications directory
   File appDirBase = new File(webappRoot);
   // Subdirs of root apps dir
   File[] dirs = appDirBase.listFiles(new TomcatLoader.DirectoryFilter());
   // Search for additional context files
   for (File dir : dirs) {
     String dirName = '/' + dir.getName();
     // check to see if the directory is already mapped
     if (null == host.findChild(dirName)) {
       String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName);
       Context ctx = null;
       if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
         log.debug("Adding ROOT context");
         ctx = addContext("/", webappContextDir);
       } else {
         log.debug("Adding context from directory scan: {}", dirName);
         ctx = addContext(dirName, webappContextDir);
       }
       log.debug("Context: {}", ctx);
       webappContextDir = null;
     }
   }
   appDirBase = null;
   dirs = null;
   // Dump context list
   if (log.isDebugEnabled()) {
     for (Container cont : host.findChildren()) {
       log.debug("Context child name: {}", cont.getName());
     }
   }
   engine.addChild(host);
   // Start server
   try {
     log.info("Starting Tomcat virtual host");
     // may not have to do this step for every host
     LoaderBase.setApplicationLoader(
         new TomcatApplicationLoader(embedded, host, applicationContext));
     for (Container cont : host.findChildren()) {
       if (cont instanceof StandardContext) {
         StandardContext ctx = (StandardContext) cont;
         ServletContext servletContext = ctx.getServletContext();
         log.debug("Context initialized: {}", servletContext.getContextPath());
         // set the hosts id
         servletContext.setAttribute("red5.host.id", getHostId());
         String prefix = servletContext.getRealPath("/");
         log.debug("Path: {}", prefix);
         try {
           Loader cldr = ctx.getLoader();
           log.debug("Loader type: {}", cldr.getClass().getName());
           ClassLoader webClassLoader = cldr.getClassLoader();
           log.debug("Webapp classloader: {}", webClassLoader);
           // create a spring web application context
           XmlWebApplicationContext appctx = new XmlWebApplicationContext();
           appctx.setClassLoader(webClassLoader);
           appctx.setConfigLocations(new String[] {"/WEB-INF/red5-*.xml"});
           // check for red5 context bean
           if (applicationContext.containsBean(defaultApplicationContextId)) {
             appctx.setParent(
                 (ApplicationContext) applicationContext.getBean(defaultApplicationContextId));
           } else {
             log.warn(
                 "{} bean was not found in context: {}",
                 defaultApplicationContextId,
                 applicationContext.getDisplayName());
             // lookup context loader and attempt to get what we need from it
             if (applicationContext.containsBean("context.loader")) {
               ContextLoader contextLoader =
                   (ContextLoader) applicationContext.getBean("context.loader");
               appctx.setParent(contextLoader.getContext(defaultApplicationContextId));
             } else {
               log.debug("Context loader was not found, trying JMX");
               MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
               // get the ContextLoader from jmx
               ContextLoaderMXBean proxy = null;
               ObjectName oName = null;
               try {
                 oName = new ObjectName("org.red5.server:name=contextLoader,type=ContextLoader");
                 if (mbs.isRegistered(oName)) {
                   proxy = JMX.newMXBeanProxy(mbs, oName, ContextLoaderMXBean.class, true);
                   log.debug("Context loader was found");
                   proxy.setParentContext(defaultApplicationContextId, appctx.getId());
                 } else {
                   log.warn("Context loader was not found");
                 }
               } catch (Exception e) {
                 log.warn("Exception looking up ContextLoader", e);
               }
             }
           }
           if (log.isDebugEnabled()) {
             if (appctx.getParent() != null) {
               log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
             }
           }
           //
           appctx.setServletContext(servletContext);
           // set the root webapp ctx attr on the each servlet context so spring can find it later
           servletContext.setAttribute(
               WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
           appctx.refresh();
         } catch (Throwable t) {
           log.error("Error setting up context: {}", servletContext.getContextPath(), t);
           if (log.isDebugEnabled()) {
             t.printStackTrace();
           }
         }
       }
     }
   } catch (Exception e) {
     log.error("Error loading Tomcat virtual host", e);
   }
 }
  /**
   * Starts a web application and its red5 (spring) component. This is basically a stripped down
   * version of init().
   *
   * @return true on success
   * @throws ServletException
   */
  @SuppressWarnings("cast")
  public boolean startWebApplication(String applicationName) throws ServletException {
    boolean result = false;
    log.info("Starting Tomcat virtual host - Web application");
    log.info("Virtual host root: {}", webappRoot);
    log.info("Virtual host context id: {}", defaultApplicationContextId);
    // application directory
    String contextName = '/' + applicationName;
    Container cont = null;
    // check if the context already exists for the host
    if ((cont = host.findChild(contextName)) == null) {
      log.debug("Context did not exist in host");
      String webappContextDir = FileUtil.formatPath(webappRoot, applicationName);
      // prepend slash
      Context ctx = addContext(contextName, webappContextDir);
      // set the newly created context as the current container
      cont = ctx;
    } else {
      log.debug("Context already exists in host");
    }
    try {
      ServletContext servletContext = ((Context) cont).getServletContext();
      log.debug("Context initialized: {}", servletContext.getContextPath());
      String prefix = servletContext.getRealPath("/");
      log.debug("Path: {}", prefix);
      Loader cldr = ((Context) cont).getLoader();
      log.debug("Loader type: {}", cldr.getClass().getName());
      ClassLoader webClassLoader = cldr.getClassLoader();
      log.debug("Webapp classloader: {}", webClassLoader);
      // create a spring web application context
      XmlWebApplicationContext appctx = new XmlWebApplicationContext();
      appctx.setClassLoader(webClassLoader);
      appctx.setConfigLocations(new String[] {"/WEB-INF/red5-*.xml"});
      // check for red5 context bean
      if (applicationContext.containsBean(defaultApplicationContextId)) {
        appctx.setParent(
            (ApplicationContext) applicationContext.getBean(defaultApplicationContextId));
      } else {
        log.warn(
            "{} bean was not found in context: {}",
            defaultApplicationContextId,
            applicationContext.getDisplayName());
        // lookup context loader and attempt to get what we need from it
        if (applicationContext.containsBean("context.loader")) {
          ContextLoader contextLoader =
              (ContextLoader) applicationContext.getBean("context.loader");
          appctx.setParent(contextLoader.getContext(defaultApplicationContextId));
        } else {
          log.debug("Context loader was not found, trying JMX");
          MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
          // get the ContextLoader from jmx
          ContextLoaderMXBean proxy = null;
          ObjectName oName = null;
          try {
            oName = new ObjectName("org.red5.server:name=contextLoader,type=ContextLoader");
            if (mbs.isRegistered(oName)) {
              proxy = JMX.newMXBeanProxy(mbs, oName, ContextLoaderMXBean.class, true);
              log.debug("Context loader was found");
              proxy.setParentContext(defaultApplicationContextId, appctx.getId());
            } else {
              log.warn("Context loader was not found");
            }
          } catch (Exception e) {
            log.warn("Exception looking up ContextLoader", e);
          }
        }
      }
      if (log.isDebugEnabled()) {
        if (appctx.getParent() != null) {
          log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
        }
      }
      //
      appctx.setServletContext(servletContext);
      // set the root webapp ctx attr on the each servlet context so spring can find it later
      servletContext.setAttribute(
          WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
      appctx.refresh();
      result = true;
    } catch (Throwable t) {
      log.error("Error setting up context: {}", applicationName, t);
      if (log.isDebugEnabled()) {
        t.printStackTrace();
      }
    }

    return result;
  }
  /**
   * Load any currently active sessions that were previously unloaded to the appropriate persistence
   * mechanism, if any. If persistence is not supported, this method returns without doing anything.
   *
   * @exception ClassNotFoundException if a serialized class cannot be found during the reload
   * @exception IOException if an input/output error occurs
   */
  public void load() throws ClassNotFoundException, IOException {

    if (debug >= 1) log("Start: Loading persisted sessions");

    // Initialize our internal data structures
    recycled.clear();
    sessions.clear();

    // Open an input stream to the specified pathname, if any
    File file = file();
    if (file == null) return;
    if (debug >= 1) log(sm.getString("standardManager.loading", pathname));
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    Loader loader = null;
    ClassLoader classLoader = null;
    try {
      fis = new FileInputStream(file.getAbsolutePath());
      BufferedInputStream bis = new BufferedInputStream(fis);
      if (container != null) loader = container.getLoader();
      if (loader != null) classLoader = loader.getClassLoader();
      if (classLoader != null) {
        if (debug >= 1) log("Creating custom object input stream for class loader " + classLoader);
        ois = new CustomObjectInputStream(bis, classLoader);
      } else {
        if (debug >= 1) log("Creating standard object input stream");
        ois = new ObjectInputStream(bis);
      }
    } catch (FileNotFoundException e) {
      if (debug >= 1) log("No persisted data file found");
      return;
    } catch (IOException e) {
      log(sm.getString("standardManager.loading.ioe", e), e);
      if (ois != null) {
        try {
          ois.close();
        } catch (IOException f) {;
        }
        ois = null;
      }
      throw e;
    }

    // Load the previously unloaded active sessions
    synchronized (sessions) {
      try {
        Integer count = (Integer) ois.readObject();
        int n = count.intValue();
        if (debug >= 1) log("Loading " + n + " persisted sessions");
        for (int i = 0; i < n; i++) {
          StandardSession session = new StandardSession(this);
          session.readObjectData(ois);
          session.setManager(this);
          sessions.put(session.getId(), session);
          session.activate();
        }
      } catch (ClassNotFoundException e) {
        log(sm.getString("standardManager.loading.cnfe", e), e);
        if (ois != null) {
          try {
            ois.close();
          } catch (IOException f) {;
          }
          ois = null;
        }
        throw e;
      } catch (IOException e) {
        log(sm.getString("standardManager.loading.ioe", e), e);
        if (ois != null) {
          try {
            ois.close();
          } catch (IOException f) {;
          }
          ois = null;
        }
        throw e;
      } finally {
        // Close the input stream
        try {
          if (ois != null) ois.close();
        } catch (IOException f) {
          // ignored
        }

        // Delete the persistent storage file
        if (file != null && file.exists()) file.delete();
      }
    }

    if (debug >= 1) log("Finish: Loading persisted sessions");
  }
Beispiel #12
0
  /**
   * Load the Session associated with the id <code>id</code>. If no such session is found <code>null
   * </code> is returned.
   *
   * @param id a value of type <code>String</code>
   * @return the stored <code>Session</code>
   * @exception ClassNotFoundException if an error occurs
   * @exception IOException if an input/output error occurred
   */
  public Session load(String id) throws ClassNotFoundException, IOException {
    ResultSet rst = null;
    StandardSession _session = null;
    Loader loader = null;
    ClassLoader classLoader = null;
    ObjectInputStream ois = null;
    BufferedInputStream bis = null;
    Container container = manager.getContainer();
    String loadSql =
        "SELECT "
            + sessionIdCol
            + ", "
            + sessionDataCol
            + " FROM "
            + sessionTable
            + " WHERE "
            + sessionIdCol
            + " = ? AND "
            + sessionAppCol
            + " = ?";

    synchronized (this) {
      Connection _conn = getConnection();
      if (_conn == null) {
        return (null);
      }

      try {
        if (preparedLoadSql == null) {
          preparedLoadSql = _conn.prepareStatement(loadSql);
        }

        preparedLoadSql.setString(1, id);
        preparedLoadSql.setString(2, getName());
        rst = preparedLoadSql.executeQuery();
        if (rst.next()) {
          bis = new BufferedInputStream(rst.getBinaryStream(2));

          if (container != null) {
            loader = container.getLoader();
          }
          if (loader != null) {
            classLoader = loader.getClassLoader();
          }
          if (classLoader != null) {
            ois = new CustomObjectInputStream(bis, classLoader);
          } else {
            ois = new ObjectInputStream(bis);
          }

          if (debug > 0) {
            log(sm.getString(getStoreName() + ".loading", id, sessionTable));
          }

          _session = (StandardSession) manager.createEmptySession();
          _session.readObjectData(ois);
          _session.setManager(manager);

        } else if (debug > 0) {
          log(getStoreName() + ": No persisted data object found");
        }
      } catch (SQLException e) {
        log(sm.getString(getStoreName() + ".SQLException", e));
      } finally {
        try {
          if (rst != null) {
            rst.close();
          }
        } catch (SQLException e) {;
        }
        if (ois != null) {
          try {
            ois.close();
          } catch (IOException e) {;
          }
        }
        release(_conn);
      }
    }

    return (_session);
  }