com.zergiu.tvman.TVManWebServer.java Source code

Java tutorial

Introduction

Here is the source code for com.zergiu.tvman.TVManWebServer.java

Source

/*
 * Copyright (c) Sergiu Giurgiu 2011.
 *
 * This file is part of TVMan.
 *
 * TVMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TVMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TVMan.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.zergiu.tvman;

import org.eclipse.jetty.plus.jndi.Resource;
import org.eclipse.jetty.server.AbstractConnector;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslConnector;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslSocketConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

public class TVManWebServer {
    private WebAppContext context;
    private Server server;
    private String serverUrl;
    private Resource resource;
    private boolean shutdown = true;

    private static Logger log = LoggerFactory.getLogger(TVManWebServer.class);

    public TVManWebServer() {

    }

    public void start() throws Exception {
        TVManOptions options = TVManOptions.getInstance();
        log.debug("starting the server:");
        server = new Server();

        //if we ever want to run with the non-nio connector, we can
        AbstractConnector connector = null;

        connector = getJettyConnector();

        setupSSLContext(connector);

        setJettyConnectorProperties(connector);

        server.setConnectors(new Connector[] { connector });

        createApplicationContext();
        ContextHandlerCollection handler = new ContextHandlerCollection();
        handler.setHandlers(new Handler[] { context });

        resource = new Resource("jdbc/TVManDataSource", TVManDatasource.getDatasource(options.getDbLocation()));

        server.setHandler(handler);
        server.start();
        boolean ssl = options.isSsl();
        String protocol = ssl ? "https" : "http";
        serverUrl = protocol + "://" + options.getHost() + ":" + options.getPort() + "/";

        if (options.isShowSystemTray()) {
            TVDBSystemTray tray = new TVDBSystemTray(this);
            tray.showSystemTray();
        }
        shutdown = false;
        log.info("Server started and is listening on " + serverUrl);
        server.join();
    }

    private void createApplicationContext() {
        context = new WebAppContext(getClass().getResource("/com/zergiu/tvman/web").toExternalForm(), "/");
        context.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.webapp.JettyWebXmlConfiguration",

                // This enables the <resource-ref> section of web.xml
                "org.eclipse.jetty.plus.webapp.EnvConfiguration" });
        context.setExtractWAR(false);

    }

    private void setJettyConnectorProperties(AbstractConnector connector) {
        TVManOptions options = TVManOptions.getInstance();
        connector.setHost(options.getHost());
        connector.setPort(options.getPort());
        QueuedThreadPool threadPool = new QueuedThreadPool(options.getMaxThreads());
        threadPool.setMinThreads(options.getMinThreads());
        threadPool.setDetailedDump(options.isDetailedDump());
        connector.setThreadPool(threadPool);
        connector.setMaxIdleTime(options.getMaxIdleTime());
        connector.setAcceptors(options.getAcceptors());
        connector.setLowResourcesMaxIdleTime(options.getLowResourcesMaxIdleTime());
        connector.setStatsOn(options.isStatsOn());

        if (connector instanceof SelectChannelConnector) {
            ((SelectChannelConnector) connector).setLowResourcesConnections(options.getLowResourcesConnections());
        }
    }

    private void setupSSLContext(AbstractConnector connector) {
        TVManOptions options = TVManOptions.getInstance();
        if (options.isSsl() && (connector instanceof SslConnector)) {
            SslContextFactory factory = ((SslConnector) connector).getSslContextFactory();
            factory.setKeyStorePath(options.getKeystorePath());
            factory.setKeyStorePassword(options.getKeystorePassword());
            factory.setKeyManagerPassword(options.getKeystoreManagerPassword());
            factory.setTrustStore(options.getTrustStorePath());
            factory.setTrustStorePassword(options.getTrustStorePassword());
        }
    }

    private AbstractConnector getJettyConnector() {
        AbstractConnector connector;
        TVManOptions options = TVManOptions.getInstance();
        if (options.isUseIO()) {
            if (options.isSsl()) {
                connector = new SslSocketConnector();
            } else {
                connector = new SocketConnector();
            }
        } else {
            if (options.isSsl()) {
                connector = new SslSelectChannelConnector();
            } else {
                connector = new SelectChannelConnector();
            }
        }
        return connector;
    }

    public void shutdown() {
        if (shutdown) {
            return;
        }
        shutdownSchedulerFactory();
        shutdownJettyServer();
        context = null;
        server = null;
        resource = null;
        ApplicationContextProvider.getInstance().setApplicationContext(null);
        shutdown = true;
    }

    private void shutdownJettyServer() {
        context.setShutdown(true);
        try {
            resource.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            server.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void shutdownSchedulerFactory() {
        SchedulerFactoryBean schedulerFactory = ApplicationContextProvider.getApplicationContext()
                .getBean(SchedulerFactoryBean.class);
        if (schedulerFactory != null) {
            try {
                schedulerFactory.destroy();
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    }

    public String getServerUrl() {
        return serverUrl;
    }

}