Search in sources :

Example 16 with XmlConfiguration

use of org.eclipse.jetty.xml.XmlConfiguration in project AJSC by att.

the class Runner method main.

/**
 * @param args
 * @throws Exception
 */
/**
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    try {
        System.out.println("Initializing the AJSC . . . ");
        // cleaning AJSC_HOME. During a Soa Cloud Install to a node with an
        // InstallRoot of "/",
        // AJSC_HOME is prefixed with "//" and causes subsequent program
        // failure. This code
        // 'cleans' AJSC_HOME and replaces "//" with "/" for those
        // particular Installations
        String ajscHome = System.getProperty("AJSC_HOME").replace("//", "/");
        System.setProperty("AJSC_HOME", ajscHome);
        System.out.println("AJSC_HOME has been set to: " + System.getProperty("AJSC_HOME"));
        String ajscConfHome = System.getProperty("AJSC_CONF_HOME");
        if (ajscConfHome == null || ajscConfHome.trim().length() <= 0) {
            System.setProperty("AJSC_CONF_HOME", ajscHome);
        } else {
            System.setProperty("AJSC_CONF_HOME", ajscConfHome.replace("//", "/"));
        }
        System.out.println("AJSC_CONF_HOME has been set to: " + System.getProperty("AJSC_CONF_HOME"));
        // Scan the sysprops directory and set the properties to System
        Properties prop = new Properties();
        String dirName = System.getProperty("AJSC_CONF_HOME") + "/etc/sysprops";
        System.out.println("System properties scanning directory has been set to: " + dirName);
        scanSystemPropsDir(dirName, prop);
        for (String key : prop.stringPropertyNames()) {
            System.setProperty(key, (String) prop.get(key));
        }
        String ajscSharedConfigLoc = System.getProperty("AJSC_SHARED_CONFIG");
        if (ajscSharedConfigLoc == null || ajscSharedConfigLoc.trim().length() <= 0) {
            ajscSharedConfigLoc = System.getProperty("AJSC_CONF_HOME");
        }
        String AJSC_JETTY_CONFIG_XML_LOC = System.getProperty("AJSC_HOME") + "/etc/ajsc-jetty.xml";
        // Setting up Temporary Directory for jetty to deploy webapps from
        File dir = new File(System.getProperty("AJSC_HOME") + File.separator + "jetty" + File.separator + "webapps");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // Setting up log directory for Java Util (JUL) Framework to work as intended
        File logDir = new File(System.getProperty("AJSC_HOME") + File.separator + "log");
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        Path basedir = FileSystems.getDefault().getPath(System.getProperty("AJSC_HOME") + File.separator + "jetty" + File.separator + "webapps");
        // Path p = Files.createTempDirectory("ajsc-temp.dir");
        // creates the temp directory to store ajsc.war - incorrect.  this is setting up the temp dir to explode ajsc-war
        Path p = Files.createTempDirectory(basedir, "ajsc-temp.dir");
        // setting the ajsc-temp-dir system property to point to ajsc.war
        // still need to set the ajsc-temp-dir, i believe to account for multiple instances.  this also sets the dir
        // underneath jetty/webapps which is what we still want
        System.setProperty("AJSC_TEMP_DIR", p.toString());
        System.out.println("AJSC_TEMP_DIR has been set to: " + System.getProperty("AJSC_TEMP_DIR"));
        // adding a shutdownHook to delete the temp dir created by each ajsc instance
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                File dir = new File(System.getProperty("AJSC_TEMP_DIR"));
                try {
                    FileUtils.deleteDirectory(dir);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        File ajscWarDir = new File(System.getProperty("AJSC_HOME") + File.separator + "lib");
        if (!ajscWarDir.exists()) {
            ajscWarDir.mkdirs();
        }
        // Setting URL Pattern for CamelServlet to register properly with
        // dme2
        setURLPatterns();
        // Retrieving the ajsc Context Path from program args and setting
        // the AJSC_CONTEXT_PATH to be used by ajsc-jetty.xml
        String ajscWarPath = getAjscWarCtxPath(args);
        System.setProperty("AJSC_CONTEXT_PATH", ajscWarPath);
        System.out.println("AJSC_CONTEXT_PATH has been set to: " + System.getProperty("AJSC_CONTEXT_PATH"));
        // I am also setting APP_CONTEXT_PATH here as well as
        // AJSC_CONTEXT_PATH as I believe the program later uses
        // APP_CONTEXT_PATH for some other logic. I would like to convert
        // that to AJSC_CONTEXT_PATH when I get a chance
        System.setProperty("APP_CONTEXT_PATH", ajscWarPath);
        // Retrieving the location of the ajsc war and setting this path to
        // be used by ajsc-jetty.xml
        String runTheMethod = getAjscWarWarPath(args).toString();
        String ajscWarWarPath = System.getProperty("AJSC_HOME") + File.separator + "lib" + File.separator + "ajsc.war";
        // Changing above code to simply set the folder path to /ajscWar for the ajsc.war location
        // String ajscWarWarPath = System.getProperty("AJSC_HOME").toString() + "/ajscWar";
        System.setProperty("AJSC_WAR_PATH", ajscWarWarPath);
        System.out.println("AJSC_WAR_PATH has been set to: " + System.getProperty("AJSC_WAR_PATH"));
        // Searching for a port to listen to and register with dme2 as an
        // ephemeral port
        int listenerPort = getListenerPort(args);
        if (listenerPort == 0) {
            ServerSocket s = new ServerSocket(0);
            listenerPort = s.getLocalPort();
            s.close();
        }
        System.setProperty("AJSC_HTTP_PORT", Integer.toString(listenerPort));
        System.out.println("AJSC_HTTP_PORT has been set to: " + System.getProperty("AJSC_HTTP_PORT"));
        System.setProperty("server.port", Integer.toString(listenerPort));
        // Setting up https port for ssl. Port will be passed to
        // ajsc-jetty.xml where actual configuration will take place
        String enableSSL = System.getProperty("enableSSL");
        if (enableSSL != null && enableSSL.equals("true")) {
            int httpsListenerPort = getHttpsListenerPort(args);
            if (httpsListenerPort == 0) {
                ServerSocket s = new ServerSocket(0);
                httpsListenerPort = s.getLocalPort();
                s.close();
            }
            System.setProperty("AJSC_HTTPS_PORT", Integer.toString(httpsListenerPort));
            System.out.println("AJSC_HTTPS_PORT has been set to: " + System.getProperty("AJSC_HTTPS_PORT"));
        }
        // Setting up the jetty Server by reading the ajsc-jetty.xml
        // configuration file
        XmlConfiguration ajscJettyConfigXml = new XmlConfiguration(getAjscJettyConfigXml(AJSC_JETTY_CONFIG_XML_LOC));
        int blockingQueueSize = 10;
        int corePoolSize = 100;
        int maxPoolSize = 100;
        int keepAliveTime = 3000;
        if (System.getProperty("AJSC_JETTY_BLOCKING_QUEUE_SIZE") != null) {
            blockingQueueSize = Integer.parseInt(System.getProperty("AJSC_JETTY_BLOCKING_QUEUE_SIZE"));
        }
        if (System.getProperty("AJSC_JETTY_ThreadCount_MIN") != null) {
            corePoolSize = Integer.parseInt(System.getProperty("AJSC_JETTY_ThreadCount_MIN"));
        }
        if (System.getProperty("AJSC_JETTY_ThreadCount_MAX") != null) {
            maxPoolSize = Integer.parseInt(System.getProperty("AJSC_JETTY_ThreadCount_MAX"));
        }
        if (System.getProperty("AJSC_JETTY_IDLETIME_MAX") != null) {
            keepAliveTime = Integer.parseInt(System.getProperty("AJSC_JETTY_IDLETIME_MAX"));
        }
        ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(blockingQueueSize);
        QueuedThreadPool pool = new QueuedThreadPool(maxPoolSize, corePoolSize, keepAliveTime, queue);
        // ExecutorThreadPool pool = new ExecutorThreadPool(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue);
        Server server = new Server(pool);
        ajscJettyConfigXml.configure(server);
        try {
            server.start();
            server.join();
        } finally {
            if (server.isFailed()) {
                try {
                    server.stop();
                    System.exit(0);
                } catch (Exception stopJettyForException) {
                    server.destroy();
                }
            }
        }
    // server.start();
    // server.join();
    } catch (Exception ex) {
        System.out.println("ERROR:" + ex.getMessage());
    }
}
Also used : Path(java.nio.file.Path) Server(org.eclipse.jetty.server.Server) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) Properties(java.util.Properties) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) File(java.io.File)

Example 17 with XmlConfiguration

use of org.eclipse.jetty.xml.XmlConfiguration in project ninja by ninjaframework.

the class NinjaJetty method buildServerOrApplyConfiguration.

private Server buildServerOrApplyConfiguration(String jettyConfiguration, Server server) throws Exception {
    // try local file first
    Resource jettyConfigurationFile = Resource.newResource(jettyConfiguration);
    if (jettyConfigurationFile == null || !jettyConfigurationFile.exists()) {
        // fallback to classpath
        jettyConfigurationFile = Resource.newClassPathResource(jettyConfiguration);
        if (jettyConfigurationFile == null || !jettyConfigurationFile.exists()) {
            throw new FileNotFoundException("Unable to find jetty configuration file either locally or on classpath '" + jettyConfiguration + "'");
        }
    }
    logger.info("Applying jetty configuration '{}'", jettyConfigurationFile);
    try (InputStream is = jettyConfigurationFile.getInputStream()) {
        XmlConfiguration configuration = new XmlConfiguration(is);
        // create or apply to existing
        if (server == null) {
            return (Server) configuration.configure();
        } else {
            return (Server) configuration.configure(server);
        }
    }
}
Also used : Server(org.eclipse.jetty.server.Server) InputStream(java.io.InputStream) Resource(org.eclipse.jetty.util.resource.Resource) FileNotFoundException(java.io.FileNotFoundException) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration)

Example 18 with XmlConfiguration

use of org.eclipse.jetty.xml.XmlConfiguration in project elasticsearch-jetty by sonian.

the class JettyHttpServerTransport method doStart.

@Override
protected void doStart() throws ElasticsearchException {
    PortsRange portsRange = new PortsRange(port);
    final AtomicReference<Exception> lastException = new AtomicReference<Exception>();
    Log.setLog(loggerWrapper);
    portsRange.iterate(new PortsRange.PortCallback() {

        @Override
        public boolean onPortNumber(int portNumber) {
            try {
                Server server = null;
                XmlConfiguration lastXmlConfiguration = null;
                Object[] objs = new Object[jettyConfig.length];
                Map<String, String> esProperties = jettySettings(bindHost, portNumber);
                for (int i = 0; i < jettyConfig.length; i++) {
                    String configFile = jettyConfig[i];
                    URL config = environment.resolveConfig(configFile);
                    XmlConfiguration xmlConfiguration = new XmlConfiguration(config);
                    // in the later configurations
                    if (lastXmlConfiguration != null) {
                        xmlConfiguration.getIdMap().putAll(lastXmlConfiguration.getIdMap());
                    } else {
                        xmlConfiguration.getIdMap().put("ESServerTransport", JettyHttpServerTransport.this);
                        xmlConfiguration.getIdMap().put("ESClient", client);
                    }
                    // Inject elasticsearch properties
                    xmlConfiguration.getProperties().putAll(esProperties);
                    objs[i] = xmlConfiguration.configure();
                    lastXmlConfiguration = xmlConfiguration;
                }
                // Find jetty Server with id  jettyConfigServerId
                Object serverObject = lastXmlConfiguration.getIdMap().get(jettyConfigServerId);
                if (serverObject != null) {
                    if (serverObject instanceof Server) {
                        server = (Server) serverObject;
                    }
                } else {
                    // For compatibility - if it's not available, find first available jetty Server
                    for (Object obj : objs) {
                        if (obj instanceof Server) {
                            server = (Server) obj;
                            break;
                        }
                    }
                }
                if (server == null) {
                    logger.error("Cannot find server with id [{}] in configuration files [{}]", jettyConfigServerId, jettyConfig);
                    lastException.set(new ElasticsearchException("Cannot find server with id " + jettyConfigServerId));
                    return true;
                }
                // Keep it for now for backward compatibility with previous versions of jetty.xml
                server.setAttribute(TRANSPORT_ATTRIBUTE, JettyHttpServerTransport.this);
                // Start all lifecycle objects configured by xml configurations
                for (Object obj : objs) {
                    if (obj instanceof LifeCycle) {
                        LifeCycle lifeCycle = (LifeCycle) obj;
                        if (!lifeCycle.isRunning()) {
                            lifeCycle.start();
                        }
                    }
                }
                jettyServer = server;
                lastException.set(null);
            } catch (BindException e) {
                lastException.set(e);
                return false;
            } catch (Exception e) {
                logger.error("Jetty Startup Failed ", e);
                lastException.set(e);
                return true;
            }
            return true;
        }
    });
    if (lastException.get() != null) {
        throw new BindHttpException("Failed to bind to [" + port + "]", lastException.get());
    }
    InetSocketAddress jettyBoundAddress = findFirstInetConnector(jettyServer);
    if (jettyBoundAddress != null) {
        InetSocketAddress publishAddress;
        try {
            publishAddress = new InetSocketAddress(networkService.resolvePublishHostAddress(publishHost), jettyBoundAddress.getPort());
        } catch (Exception e) {
            throw new BindTransportException("Failed to resolve publish address", e);
        }
        this.boundAddress = new BoundTransportAddress(new InetSocketTransportAddress(jettyBoundAddress), new InetSocketTransportAddress(publishAddress));
    } else {
        throw new BindHttpException("Failed to find a jetty connector with Inet transport");
    }
}
Also used : LifeCycle(org.eclipse.jetty.util.component.LifeCycle) Server(org.eclipse.jetty.server.Server) AtomicReference(java.util.concurrent.atomic.AtomicReference) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) ElasticsearchException(org.elasticsearch.ElasticsearchException) PortsRange(org.elasticsearch.common.transport.PortsRange) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) ElasticsearchException(org.elasticsearch.ElasticsearchException) BindTransportException(org.elasticsearch.transport.BindTransportException) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) BindTransportException(org.elasticsearch.transport.BindTransportException) Map(java.util.Map)

Example 19 with XmlConfiguration

use of org.eclipse.jetty.xml.XmlConfiguration in project otter by alibaba.

the class JettyEmbedServer method start.

public void start() throws Exception {
    Resource configXml = Resource.newSystemResource(config);
    XmlConfiguration configuration = new XmlConfiguration(configXml.getInputStream());
    server = (Server) configuration.configure();
    // Integer port = getPort();
    // if (port != null && port > 0) {
    // Connector[] connectors = server.getConnectors();
    // for (Connector connector : connectors) {
    // connector.setPort(port);
    // }
    // }
    Handler handler = server.getHandler();
    if (handler != null && handler instanceof WebAppContext) {
        WebAppContext webAppContext = (WebAppContext) handler;
        webAppContext.setResourceBase(JettyEmbedServer.class.getResource("/webapp").toString());
    }
    server.start();
    if (logger.isInfoEnabled()) {
        logger.info("##Jetty Embed Server is startup!");
    }
}
Also used : WebAppContext(org.eclipse.jetty.webapp.WebAppContext) Resource(org.eclipse.jetty.util.resource.Resource) Handler(org.eclipse.jetty.server.Handler) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration)

Example 20 with XmlConfiguration

use of org.eclipse.jetty.xml.XmlConfiguration in project otter by alibaba.

the class JettyEmbedServer method afterPropertiesSet.

public void afterPropertiesSet() throws Exception {
    Resource configXml = Resource.newSystemResource(config);
    XmlConfiguration configuration = new XmlConfiguration(configXml.getInputStream());
    server = (Server) configuration.configure();
    Integer port = getPort();
    if (port != null && port > 0) {
        Connector[] connectors = server.getConnectors();
        for (Connector connector : connectors) {
            connector.setPort(port);
        }
    }
    Handler handler = server.getHandler();
    if (handler != null && handler instanceof ServletContextHandler) {
        ServletContextHandler servletHandler = (ServletContextHandler) handler;
        servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", htdocsDir);
    }
    server.start();
    if (logger.isInfoEnabled()) {
        logger.info("##Jetty Embed Server is startup!");
    }
}
Also used : Connector(org.eclipse.jetty.server.Connector) Resource(org.eclipse.jetty.util.resource.Resource) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Aggregations

XmlConfiguration (org.eclipse.jetty.xml.XmlConfiguration)43 Server (org.eclipse.jetty.server.Server)24 Resource (org.eclipse.jetty.util.resource.Resource)18 URL (java.net.URL)12 File (java.io.File)9 IOException (java.io.IOException)9 HashMap (java.util.HashMap)6 Test (org.junit.Test)6 InputStream (java.io.InputStream)5 ArrayList (java.util.ArrayList)5 Handler (org.eclipse.jetty.server.Handler)5 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)5 FileInputStream (java.io.FileInputStream)4 URLClassLoader (java.net.URLClassLoader)4 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)4 JettyWebXmlConfiguration (org.eclipse.jetty.webapp.JettyWebXmlConfiguration)4 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)4 FileNotFoundException (java.io.FileNotFoundException)3 HttpURLConnection (java.net.HttpURLConnection)3 MalformedURLException (java.net.MalformedURLException)3