Package com.adaptrex.server

Source Code of com.adaptrex.server.AdaptrexServer

/*
Copyright 2012 Adaptrex, LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.adaptrex.server;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.naming.NamingException;
import javax.servlet.DispatcherType;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;
import org.eclipse.jetty.plus.jndi.Resource;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlets.GzipFilter;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.bridge.SLF4JBridgeHandler;

public class AdaptrexServer {

    private static Server jetty;
    private static Map<String, Object> config;
    private static Logger log = Logger.getLogger(AdaptrexServer.class);

    /*
     * Bootstrap
     */
    @SuppressWarnings("unchecked")
    public static void main(String... args) throws Exception {
  log.info("Starting Adaptrex Server...");

  /*
   * Get configuration
   */
  InputStream in = AdaptrexServer.class.getClassLoader().getResourceAsStream("adaptrex.config");
  try {
      config = new ObjectMapper().readValue(in, Map.class);
  } catch (Exception e) {
      log.warn("Adaptrex Config Error: Could not find load adaptrex.config.");
      log.warn("Error", e);
  }
  if (config == null) {
      return;
  }

  for (String arg : args) {
      if (arg.equals("-stop") || arg.equals("-restart")) {
    stopServer();
    if (arg.equals("-stop")) {
        log.info("The Adaptrex Server has been stopped.");
        return;
    }
      }
  }

  /*
   * Inevitably some dependency is going to use java.util.Logging
   * Use jul-to-slf4j and the SLF4JBridgeHandler to send it over SLF4J
   */
  SLF4JBridgeHandler.removeHandlersForRootLogger();
  SLF4JBridgeHandler.install();

  /*
   * Get a Jetty server
   */
  Integer port = (Integer) config.get("port");
  if (port != null) {
      port = 8080;
  }
  jetty = new Server(port);


  /*
   * Create global data sources
   */
  if (config.get("dataSource") != null) {
      createDataSource(jetty, (Map<String, String>) config.get("dataSource"));
  }
  if (config.get("dataSources") != null) {
      for (Map<String, String> dataSourceConfig : (List<Map<String, String>>) config.get("dataSources")) {
    createDataSource(jetty, dataSourceConfig);
      }
  }

  /*
   * Create the collection of webapp contexts
   */
  ContextHandlerCollection contexts = new ContextHandlerCollection();

  /*
   * Loop through the webapps defined in the configuration
   */
  for (Map<String, Object> webappConfig : (List<Map<String, Object>>) config.get("webapps")) {
      try {
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setDisplayName((String) webappConfig.get("name"));

    String base = (String) config.get("webappBase");

    String contextPath = (String) webappConfig.get("contextPath");
    if (contextPath == null) {
        contextPath = "";
    }
    webAppContext.setContextPath("/" + contextPath);

    String filePath = ((base != null) ? base : "") + webappConfig.get("filePath");
    if (filePath.toLowerCase().endsWith(".war")) {
        webAppContext.setWar(filePath);
    } else {
        webAppContext.setResourceBase(filePath);
    }

    /*
     * Standard Jetty WebApp Configuration
     */
    webAppContext.setConfigurationClasses(new String[]{
          "org.eclipse.jetty.webapp.WebInfConfiguration",
          "org.eclipse.jetty.webapp.WebXmlConfiguration",
          "org.eclipse.jetty.webapp.MetaInfConfiguration",
          "org.eclipse.jetty.webapp.FragmentConfiguration",
          "org.eclipse.jetty.plus.webapp.EnvConfiguration",
          "org.eclipse.jetty.plus.webapp.PlusConfiguration",
          "org.eclipse.jetty.annotations.AnnotationConfiguration",
          "org.eclipse.jetty.webapp.JettyWebXmlConfiguration"
      });

    /*
     * Add the data sources
     */
    if (webappConfig.get("dataSource") != null) {
        createDataSource(webAppContext, (Map<String, String>) webappConfig.get("dataSource"));
    }
    if (webappConfig.get("dataSources") != null) {
        for (Map<String, String> dataSourceConfig : (List<Map<String, String>>) webappConfig.get("dataSources")) {
      createDataSource(webAppContext, dataSourceConfig);
        }
    }

    /*
     * Add the default jetty servlet to serve static content from the lib filder
     */
    ServletHolder defaultServlet = new ServletHolder(new DefaultServlet());
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("dirAllowed", "false");
    params.put("aliases", "true");
    params.put("acceptRanges", "true");
    params.put("welcomeServlets", "false");
    params.put("redirectWelcome", "false");
    params.put("maxCacheSize", "256000000");
    params.put("maxCachedFileSize", "20000000");
    params.put("maxCachedFiles", "2048");
    params.put("gzip", "true");
    params.put("useFileMappedBuffer", "true");
    params.put("resourceCache", "resourceCache");
    defaultServlet.setInitParameters(params);
    defaultServlet.setInitOrder(0);
    webAppContext.addServlet(defaultServlet, "/lib/*");

    /*
     * Set up global defaults
     */
    webAppContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    webAppContext.setInitParameter("org.eclipse.jetty.servlet.Default.gzip", "true");

    /*
     * Add jetty's gzip filter
     */
    EnumSet<DispatcherType> all = EnumSet.allOf(DispatcherType.class);
    FilterHolder gzipFilter = new FilterHolder(new GzipFilter());
    gzipFilter.setInitParameter("mimeTypes", "text/html,text/xhtml,text/plain,text/xml,text/javascript,"
      + "application/xhtml+xml,application/xml,application/javascript,application/json");
    gzipFilter.setInitParameter("minGzipSize", "860");
    webAppContext.addFilter(gzipFilter, "/*", all);


    contexts.addHandler(webAppContext);
      } catch (Exception e) {
    String msg = "Error Configuring Webapp:\n" + e.getClass().getSimpleName() + "\n" + Arrays.toString(e.getStackTrace()).replaceAll(",", "\n");
    System.out.println(msg);
    log.warn(msg);
      }
  }

  /*
   * Add the contexts to the server
   */
  jetty.setHandler(contexts);

  /*
   * Standard jetty configs
   */
  jetty.setStopAtShutdown(true);
  jetty.setSendServerVersion(false);
  jetty.setSendDateHeader(true);
  jetty.setGracefulShutdown(1000);


  /*
   * Start jetty
   */
  try {
      (new ShutdownMonitor()).start();
      jetty.start();
      log.info("Started Adaptrex Server");
      jetty.join();
  } catch (Exception e) {
      log.info("Error Starting Adaptrex Server:\n" + e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()).replaceAll(",", "\n"));
  }
    }

    protected static void createDataSource(Object scope, Map<String, String> config) {
  try {
      BasicDataSource ds = new BasicDataSource();
      ds.setDriverClassName(config.get("driver"));
      ds.setUrl(config.get("url"));
      ds.setUsername(config.get("username"));
      ds.setPassword(config.get("password"));

      Resource resource = new Resource(scope, "jdbc/" + config.get("name"), ds);
  } catch (NamingException e) {
      String msg = "Error Configuring DataSource:\n" + e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()).replaceAll(",", "\n");
      System.out.println(msg);
      log.warn(msg);
  }
    }

    /*
     * Previous instances of this server should have a listener running waiting
     * for a ping to trigger it's shutdown before we attempt to start a new instance
     */
    private static void stopServer() throws UnknownHostException, IOException {
  Integer shutdownPort = (Integer) config.get("shutdownPort");
  if (shutdownPort == null) {
      shutdownPort = 8079;
  }

  try {
      Socket s = new Socket(InetAddress.getByName("127.0.0.1"), shutdownPort);
      OutputStream out = s.getOutputStream();
      out.write(("\r\n").getBytes());
      out.flush();
      s.close();
  } catch (Exception e) {
      System.out.println("Adaptrex Server Not Running");
      return;
  }

  /*
   * The prior instance's monitor will continue to respond until jetty
   * is completely shut down.  Keep trying until we get a bad response
   * from the monitor.  Once we have a bad response, we know we can
   * continue in this instance of the application
   */
  while (true) {
      try {
    Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), shutdownPort);
      } catch (Exception ioe) {
    break;
      }
  }
    }

    ;
 
    /*
     * The shutdown monitor runs in a separate thread waiting for a request
     */
    private static class ShutdownMonitor extends Thread {

  private ServerSocket socket;

  public ShutdownMonitor() {
      setDaemon(true);
      setName("ShutdownMonitor");
      try {
    Integer shutdownPort = (Integer) config.get("shutdownPort");
    socket = new ServerSocket((shutdownPort == null) ? 8079 : shutdownPort, 1, InetAddress.getByName("127.0.0.1"));
      } catch (Exception e) {
    throw new RuntimeException(e);
      }
  }

  @Override
  public void run() {
      Socket accept;
      try {
    accept = socket.accept();
    BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
    reader.readLine();
    log.info("Stopping");
    try {
        jetty.stop();
    } catch (Exception e) {
        log.warn("Error", e);
    }

    accept.close();
    socket.close();
      } catch (Exception e) {
    throw new RuntimeException(e);
      }
  }
    }
}
TOP

Related Classes of com.adaptrex.server.AdaptrexServer

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.