public void stop() {
    /* Dump a message */
    System.err.println("ServiceDaemon: stopping");
    try {
      final File homeDir = existMain.detectHome();
      final String[] noArgs = {};
      final Classpath classpath = existMain.constructClasspath(homeDir, noArgs);
      final ClassLoader cl = classpath.getClassLoader(null);
      Thread.currentThread().setContextClassLoader(cl);
      final Class<?> brokerPoolClass = cl.loadClass("org.exist.storage.BrokerPool");
      // This only works in Java 1.5
      // Method stopAll = brokerPoolClass.getDeclaredMethod("stopAll",java.lang.Boolean.TYPE);
      // stopAll.invoke(null,Boolean.TRUE);

      // This is the ugly Java 1.4 version
      final Class<?>[] paramTypes = new Class[1];
      paramTypes[0] = java.lang.Boolean.TYPE;
      final Method stopAll = brokerPoolClass.getDeclaredMethod("stopAll", paramTypes);
      final Object[] arguments = new Object[1];
      arguments[0] = Boolean.TRUE;

      stopAll.invoke(null, arguments);
    } catch (final Exception ex) {
      ex.printStackTrace();
    }

    System.err.println("ServiceDaemon: stopped");
  }
Exemple #2
0
 public void initClasspath(Classpath classPath) throws IOException {
   // load tools.jar
   if (this.toolsJar != null) {
     classPath.addComponent(this.toolsJar);
   }
   // load comm.jar
   if (this.commJar != null) {
     classPath.addComponent(this.commJar);
   }
   // add OFBIZ_HOME to class path & load libs
   classPath.addClasspath(this.ofbizHome);
   loadLibs(classPath, this.ofbizHome, false);
   // load the lib directory
   if (this.baseLib != null) {
     loadLibs(classPath, this.baseLib, true);
   }
   // load the ofbiz-base.jar
   if (this.baseJar != null) {
     classPath.addComponent(this.baseJar);
   }
   // load the base schema directory
   if (this.baseDtd != null) {
     classPath.addComponent(this.baseDtd);
   }
   // load the config directory
   if (this.baseConfig != null) {
     classPath.addComponent(this.baseConfig);
   }
   classPath.instrument(this.instrumenterFile, this.instrumenterClassName);
 }
Exemple #3
0
 private Set<Class<?>> getClassesRecursive(String pkgName) {
   Set<Class<?>> result = new LinkedHashSet<>();
   for (Class<?> clazz : Classpath.findClasses(pkgName)) {
     if (isTestClass(clazz)) {
       result.add(clazz);
     }
   }
   return result;
 }
Exemple #4
0
  /** Establish a classloader with custom paths (if any) */
  protected void initClassLoader() {
    URL[] paths = _classpath.asArray();

    if (_classLoader == null && paths != null && paths.length > 0) {
      ClassLoader context = Thread.currentThread().getContextClassLoader();

      if (context == null) _classLoader = new URLClassLoader(paths);
      else _classLoader = new URLClassLoader(paths, context);

      Thread.currentThread().setContextClassLoader(_classLoader);
    }
  }
  private static ClassLoader resolveClassLoader(
      Map<String, ClassLoader> classLoaders,
      List<String> seen,
      Map<String, Classpath> classpaths,
      String id)
      throws MalformedURLException {
    if (classLoaders.containsKey(id)) {
      return classLoaders.get(id);
    }
    if (seen.contains(id)) {
      throw new ConfigurationException(MessageNames.CIRCULAR_CLASSPATH, id);
    }
    // Add the id to the list of classloaders we have attempted to build.
    seen.add(id);
    Classpath classpath = classpaths.get(id);
    if (classpath == null) {
      throw new ConfigurationException(MessageNames.CLASSPATH_UNDEFINED, id);
    }
    String parentClasspathId = classpath.getParent();
    ClassLoader parentClassLoader = null;
    if (parentClasspathId != null && !Strings.EMPTY.equals(parentClasspathId)) {
      parentClassLoader = resolveClassLoader(classLoaders, seen, classpaths, parentClasspathId);
    } else {
      /* Should be the 'extension' classloader. */
      parentClassLoader = Bootstrap.class.getClassLoader().getParent();
    }
    URL[] classpathUrls;
    classpathUrls = findClasspathURLS(classpath.getValue());

    SettableCodebaseClassLoader classLoader =
        new SettableCodebaseClassLoader(classpathUrls, parentClassLoader);
    classLoaders.put(id, classLoader);
    log.log(
        Level.FINE,
        MessageNames.CONFIGURED_CLASSPATH,
        new Object[] {id, Utils.format(classpathUrls)});
    seen.remove(id);
    return classLoader;
  }
  private static Map<String, ClassLoader> createClassLoaders(ContainerConfig config)
      throws MalformedURLException {

    Map<String, ClassLoader> classLoaders = new HashMap<String, ClassLoader>();
    classLoaders.put(Strings.BOOTSTRAP_CLASS_LOADER, Bootstrap.class.getClassLoader());
    /*
    Setup the classloaders according to the config file.
    */
    List<String> seen = new LinkedList<String>();
    Map<String, Classpath> classpaths = new HashMap<String, Classpath>();
    for (Classpath classpath : config.getClasspath()) {
      if (classpaths.containsKey(classpath.getId())) {
        throw new ConfigurationException(MessageNames.DUPLICATE_CLASSPATH, classpath.getId());
      }
      classpaths.put(classpath.getId(), classpath);
    }

    for (String id : classpaths.keySet()) {
      resolveClassLoader(classLoaders, seen, classpaths, id);
    }
    return classLoaders;
  }
Exemple #7
0
 private void loadLibs(Classpath classPath, String path, boolean recurse) throws IOException {
   File libDir = new File(path);
   if (libDir.exists()) {
     File files[] = libDir.listFiles();
     for (File file : files) {
       String fileName = file.getName();
       if (file.isHidden()) {
         continue;
       }
       // FIXME: filter out other files?
       if (file.isDirectory() && !"CVS".equals(fileName) && !".svn".equals(fileName) && recurse) {
         loadLibs(classPath, file.getCanonicalPath(), recurse);
       } else if (fileName.endsWith(".jar") || fileName.endsWith(".zip")) {
         classPath.addComponent(file);
       }
     }
   }
 }
Exemple #8
0
  /**
   * Configure a jetty instance and deploy the webapps presented as args
   *
   * @param args the command line arguments
   * @throws Exception if unable to configure
   */
  public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
      if ("--lib".equals(args[i])) {
        try (Resource lib = Resource.newResource(args[++i])) {
          if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib);
          _classpath.addJars(lib);
        }
      } else if ("--jar".equals(args[i])) {
        try (Resource jar = Resource.newResource(args[++i])) {
          if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar);
          _classpath.addPath(jar);
        }
      } else if ("--classes".equals(args[i])) {
        try (Resource classes = Resource.newResource(args[++i])) {
          if (!classes.exists() || !classes.isDirectory())
            usage("No such classes directory " + classes);
          _classpath.addPath(classes);
        }
      } else if (args[i].startsWith("--")) i++;
    }

    initClassLoader();

    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);

    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;

    boolean runnerServerInitialized = false;

    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--port":
          port = Integer.parseInt(args[++i]);
          break;
        case "--host":
          host = args[++i];
          break;
        case "--stop-port":
          stopPort = Integer.parseInt(args[++i]);
          break;
        case "--stop-key":
          stopKey = args[++i];
          break;
        case "--log":
          _logFile = args[++i];
          break;
        case "--out":
          String outFile = args[++i];
          PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
          LOG.info("Redirecting stderr/stdout to " + outFile);
          System.setErr(out);
          System.setOut(out);
          break;
        case "--path":
          contextPath = args[++i];
          contextPathSet = true;
          break;
        case "--config":
          if (_configFiles == null) _configFiles = new ArrayList<>();
          _configFiles.add(args[++i]);
          break;
        case "--lib":
          ++i; // skip

          break;
        case "--jar":
          ++i; // skip

          break;
        case "--classes":
          ++i; // skip

          break;
        case "--stats":
          _enableStats = true;
          _statsPropFile = args[++i];
          _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
          break;
        default:
          // process contexts

          if (!runnerServerInitialized) // log handlers not registered, server maybe not created,
                                        // etc
          {
            if (_server == null) // server not initialized yet
            {
              // build the server
              _server = new Server();
            }

            // apply jetty config files if there are any
            if (_configFiles != null) {
              for (String cfg : _configFiles) {
                try (Resource resource = Resource.newResource(cfg)) {
                  XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                  xmlConfiguration.configure(_server);
                }
              }
            }

            // check that everything got configured, and if not, make the handlers
            HandlerCollection handlers =
                (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
            if (handlers == null) {
              handlers = new HandlerCollection();
              _server.setHandler(handlers);
            }

            // check if contexts already configured
            _contexts =
                (ContextHandlerCollection)
                    handlers.getChildHandlerByClass(ContextHandlerCollection.class);
            if (_contexts == null) {
              _contexts = new ContextHandlerCollection();
              prependHandler(_contexts, handlers);
            }

            if (_enableStats) {
              // if no stats handler already configured
              if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                StatisticsHandler statsHandler = new StatisticsHandler();

                Handler oldHandler = _server.getHandler();
                statsHandler.setHandler(oldHandler);
                _server.setHandler(statsHandler);

                ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                statsContext.setSessionHandler(new SessionHandler());
                if (_statsPropFile != null) {
                  HashLoginService loginService =
                      new HashLoginService("StatsRealm", _statsPropFile);
                  Constraint constraint = new Constraint();
                  constraint.setName("Admin Only");
                  constraint.setRoles(new String[] {"admin"});
                  constraint.setAuthenticate(true);

                  ConstraintMapping cm = new ConstraintMapping();
                  cm.setConstraint(constraint);
                  cm.setPathSpec("/*");

                  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                  securityHandler.setLoginService(loginService);
                  securityHandler.setConstraintMappings(Collections.singletonList(cm));
                  securityHandler.setAuthenticator(new BasicAuthenticator());
                  statsContext.setSecurityHandler(securityHandler);
                }
              }
            }

            // ensure a DefaultHandler is present
            if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
              handlers.addHandler(new DefaultHandler());
            }

            // ensure a log handler is present
            _logHandler =
                (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
            if (_logHandler == null) {
              _logHandler = new RequestLogHandler();
              handlers.addHandler(_logHandler);
            }

            // check a connector is configured to listen on
            Connector[] connectors = _server.getConnectors();
            if (connectors == null || connectors.length == 0) {
              ServerConnector connector = new ServerConnector(_server);
              connector.setPort(port);
              if (host != null) connector.setHost(host);
              _server.addConnector(connector);
              if (_enableStats) connector.addBean(new ConnectorStatistics());
            } else {
              if (_enableStats) {
                for (Connector connector : connectors) {
                  ((AbstractConnector) connector).addBean(new ConnectorStatistics());
                }
              }
            }

            runnerServerInitialized = true;
          }

          // Create a context
          try (Resource ctx = Resource.newResource(args[i])) {
            if (!ctx.exists()) usage("Context '" + ctx + "' does not exist");

            if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath;

            // Configure the context
            if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) {
              // It is a context config file
              XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
              xmlConfiguration.getIdMap().put("Server", _server);
              ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
              if (contextPathSet) handler.setContextPath(contextPath);
              _contexts.addHandler(handler);
              handler.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            } else {
              // assume it is a WAR file
              WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
              webapp.setConfigurationClasses(__plusConfigurationClasses);
              webapp.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            }
          }
          // reset
          contextPathSet = false;
          contextPath = __defaultContextPath;
          break;
      }
    }

    if (_server == null) usage("No Contexts defined");
    _server.setStopAtShutdown(true);

    switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
      case 1:
        usage("Must specify --stop-key when --stop-port is specified");
        break;

      case 2:
        usage("Must specify --stop-port when --stop-key is specified");
        break;

      case 3:
        ShutdownMonitor monitor = ShutdownMonitor.getInstance();
        monitor.setPort(stopPort);
        monitor.setKey(stopKey);
        monitor.setExitVm(true);
        break;
    }

    if (_logFile != null) {
      NCSARequestLog requestLog = new NCSARequestLog(_logFile);
      requestLog.setExtended(false);
      _logHandler.setRequestLog(requestLog);
    }
  }
Exemple #9
0
 public void mergeXmlClasspath(Classpath xmlClasspath) {
   file.getBeforeMerged().execute(xmlClasspath);
   List<ClasspathEntry> entries = resolveDependencies();
   xmlClasspath.configure(entries);
   file.getWhenMerged().execute(xmlClasspath);
 }