/*
 * Copyright 2010-2011 Ning, Inc.
 *
 * Ning licenses this file to you 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.ning.metrics.collector.endpoint.servers;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.servlet.GuiceFilter;
import com.ning.metrics.collector.binder.config.CollectorConfig;
import com.ning.metrics.collector.binder.modules.JettyListener;
import com.ning.metrics.collector.endpoint.setup.SetupJULBridge;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

@Singleton
public class JettyServer
{
    private final static Logger log = Logger.getLogger(JettyServer.class);

    private boolean initialized = false;

    private final String ip;
    private final int port;
    private final int sslPort;
    private final boolean sslEnabled;
    private final String keystoreLocation;
    private final String keystorePassword;

    @Inject
    public JettyServer(
        CollectorConfig config
    )
    {
        this(config.getLocalIp(), config.getLocalPort(), config.isSSLEnabled(), config.getLocalSSLPort(), config.getSSLkeystoreLocation(), config.getSSLkeystorePassword());
    }

    public JettyServer(
        String ip,
        int port,
        boolean sslEnabled,
        int sslPort,
        String keystoreLocation,
        String keystorePassword
    )
    {
        this.ip = ip;
        this.port = port;
        this.sslEnabled = sslEnabled;
        this.sslPort = sslPort;
        this.keystoreLocation = keystoreLocation;
        this.keystorePassword = keystorePassword;

        ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory());
        executor.execute(new Runnable()
        {
            @Override
            public void run()
            {
                try {
                    start();
                    // Will be shut down automatically, see below
                }
                catch (Exception e) {
                    log.warn("Unable to start the Jetty server", e);
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

    private void start() throws Exception
    {
        final long startTime = System.currentTimeMillis();

        final Server server = new Server();

        Connector connector = new SelectChannelConnector();
        connector.setHost(ip);
        connector.setPort(port);
        server.addConnector(connector);

        if (sslEnabled) {
            SslSelectChannelConnector sslConnector = new SslSelectChannelConnector();
            sslConnector.setPort(sslPort);
            sslConnector.setKeystore(keystoreLocation);
            sslConnector.setKeyPassword(keystorePassword);
            sslConnector.setPassword(keystorePassword);
            server.addConnector(sslConnector);
        }

        server.setStopAtShutdown(true);

        ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
        context.addEventListener(new JettyListener());

        // Jersey insists on using java.util.logging (JUL)
        SetupJULBridge listener = new SetupJULBridge();
        context.addEventListener(listener);

        // Make sure Guice filter all requests
        FilterHolder filterHolder = new FilterHolder(GuiceFilter.class);
        context.addFilter(filterHolder, "/*", ServletContextHandler.NO_SESSIONS);

        ServletHolder sh = new ServletHolder(DefaultServlet.class);
        sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
        sh.setInitParameter("com.sun.jersey.config.property.packages", "com.ning.metrics.collector.endpoint");
        context.addServlet(sh, "/*");

        server.start();

        final long secondsToStart = (System.currentTimeMillis() - startTime) / 1000;
        log.info(String.format("Jetty server started in %d:%02d", secondsToStart / 60, secondsToStart % 60));

        initialized = true;
        server.join();
    }

    /**
     * Has Jetty finished its startup sequence?
     *
     * @return true iff Jetty has been setup
     */
    public boolean isInitialized()
    {
        return initialized;
    }
}

@@ -1700,124 +1700,36 @@
 ate 
-boolean initialized = false;%0A%0A    private final String ip;%0A    private final int port;%0A    private final int sslPort
+final CollectorConfig config
 ;%0A  
@@ -1742,22 +1742,16 @@
 ate 
-final 
 boolean 
 sslE
@@ -1750,104 +1750,27 @@
 ean 
-sslEnabled;%0A    private final String keystoreLocation;%0A    private final String keystorePassword
+initialized = false
 ;%0A%0A 
@@ -1803,25 +1803,16 @@
 yServer(
-%0A        
 Collecto
@@ -1825,21 +1825,16 @@
 g config
-%0A    
 )%0A    %7B%0A
@@ -1849,581 +1849,25 @@
 this
-(config.getLocalIp(), config.getLocalPort(), config.isSSLEnabled(), config.getLocalSSLPort(), config.getSSLkeystoreLocation(), config.getSSLkeystorePassword());%0A    %7D%0A%0A    public JettyServer(%0A        String ip,%0A        int port,%0A        boolean sslEnabled,%0A        int sslPort,%0A        String keystoreLocation,%0A        String keystorePassword%0A    )%0A    %7B%0A        this.ip = ip;%0A        this.port = port;%0A        this.sslEnabled = sslEnabled;%0A        this.sslPort = sslPort;%0A        this.keystoreLocation = keystoreLocation;%0A        this.keystorePassword = keystorePassword;%0A
+.config = config;
 %0A   
@@ -2681,18 +2681,35 @@
 setHost(
-ip
+config.getLocalIp()
 );%0A     
@@ -2729,20 +2729,37 @@
 setPort(
-p
+config.getLocalP
 ort
+()
 );%0A     
@@ -2810,18 +2810,29 @@
 if (
-ssl
+config.isSSL
 Enabled
+()
 ) %7B%0A
@@ -2954,15 +2954,32 @@
 ort(
-ssl
+config.getLocalSSL
 Port
+()
 );%0A 
@@ -3014,16 +3014,29 @@
 eystore(
+config.getSSL
 keystore
@@ -3043,16 +3043,18 @@
 Location
+()
 );%0A     
@@ -3080,32 +3080,45 @@
 .setKeyPassword(
+config.getSSL
 keystorePassword
@@ -3109,32 +3109,34 @@
 keystorePassword
+()
 );%0A            s
@@ -3159,16 +3159,29 @@
 assword(
+config.getSSL
 keystore
@@ -3188,16 +3188,18 @@
 Password
+()
 );%0A     

simplify JettyServer class