Java Code Examples for org.mortbay.jetty.Server#addConnector()

The following examples show how to use org.mortbay.jetty.Server#addConnector() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JettyLauncher.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(PORT);
    server.addConnector(connector);
    server.setStopAtShutdown(true);

    // the orders of handlers is very important!
    ContextHandler contextHandler = new ContextHandler();
    contextHandler.setContextPath("/reports");
    contextHandler.setResourceBase("./reports/");
    contextHandler.addHandler(new ResourceHandler());
    server.addHandler(contextHandler);

    server.addHandler(new WebAppContext("webapp", "/nextreports-server"));

    long t = System.currentTimeMillis();
    server.start();
    t = System.currentTimeMillis() - t;
    String version = server.getClass().getPackage().getImplementationVersion();
    System.out.println("Started Jetty Server " + version + " on port " + PORT + " in " + t / 1000 + "s");
    
    server.join();
}
 
Example 2
Source File: HttpServerImpl.java    From reef with Apache License 2.0 6 votes vote down vote up
private Server tryPort(final int portNumber) throws Exception {
  Server srv = new Server();
  final Connector connector = new SocketConnector();
  connector.setHost(this.hostAddress);
  connector.setPort(portNumber);
  srv.addConnector(connector);
  try {
    srv.start();
    LOG.log(Level.INFO, "Jetty Server started with port: {0}", portNumber);
  } catch (final BindException ex) {
    srv = null;
    LOG.log(Level.FINEST, "Cannot use host: {0},port: {1}. Will try another",
        new Object[] {this.hostAddress, portNumber});
  }
  return srv;
}
 
Example 3
Source File: CrawlDBTestUtil.java    From anthelion with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JettyServer with one static root context
 * 
 * @param port port to listen to
 * @param staticContent folder where static content lives
 * @throws UnknownHostException 
 */
public static Server getServer(int port, String staticContent) throws UnknownHostException{
  Server webServer = new org.mortbay.jetty.Server();
  SocketConnector listener = new SocketConnector();
  listener.setPort(port);
  listener.setHost("127.0.0.1");
  webServer.addConnector(listener);
  ContextHandler staticContext = new ContextHandler();
  staticContext.setContextPath("/");
  staticContext.setResourceBase(staticContent);
  staticContext.addHandler(new ResourceHandler());
  webServer.addHandler(staticContext);
  return webServer;
}
 
Example 4
Source File: CrawlDBTestUtil.java    From nutch-htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JettyServer with one static root context
 * 
 * @param port port to listen to
 * @param staticContent folder where static content lives
 * @throws UnknownHostException 
 */
public static Server getServer(int port, String staticContent) throws UnknownHostException{
  Server webServer = new org.mortbay.jetty.Server();
  SocketConnector listener = new SocketConnector();
  listener.setPort(port);
  listener.setHost("127.0.0.1");
  webServer.addConnector(listener);
  ContextHandler staticContext = new ContextHandler();
  staticContext.setContextPath("/");
  staticContext.setResourceBase(staticContent);
  staticContext.addHandler(new ResourceHandler());
  webServer.addHandler(staticContext);
  return webServer;
}
 
Example 5
Source File: HttpServer.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Create a status server on the given port.
 * The jsp scripts are taken from src/webapps/<name>.
 * @param name The name of the server
 * @param port The port to use on the server
 * @param findPort whether the server should start at the given port and 
 *        increment by 1 until it finds a free port.
 * @param conf Configuration 
 */
public HttpServer(String name, String bindAddress, int port,
    boolean findPort, Configuration conf) throws IOException {
  webServer = new Server();
  this.findPort = findPort;

  listener = createBaseListener(conf);
  listener.setHost(bindAddress);
  listener.setPort(port);
  webServer.addConnector(listener);

  int maxThreads = conf.getInt(HTTP_MAX_THREADS, -1);
  // If HTTP_MAX_THREADS is not configured, QueueThreadPool() will use the 
  // default value (currently 254).
  QueuedThreadPool threadPool = maxThreads == -1 ?
      new QueuedThreadPool() : new QueuedThreadPool(maxThreads);
  webServer.setThreadPool(threadPool);

  final String appDir = getWebAppsPath();
  ContextHandlerCollection contexts = new ContextHandlerCollection();
  webServer.setHandler(contexts);

  webAppContext = new WebAppContext();
  webAppContext.setContextPath("/");
  webAppContext.setWar(appDir + "/" + name);
  webAppContext.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, conf);
  webServer.addHandler(webAppContext);

  addDefaultApps(contexts, appDir);

  addGlobalFilter("safety", QuotingInputFilter.class.getName(), null);
  final FilterInitializer[] initializers = getFilterInitializers(conf); 
  if (initializers != null) {
    for(FilterInitializer c : initializers) {
      c.initFilter(this);
    }
  }
  addDefaultServlets();
}
 
Example 6
Source File: JettyServer.java    From fiware-cygnus with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Constructor.
 * @param mgmtIfPort
 * @param guiPort
 * @param handler
 * @param ipv6
 */
public JettyServer(int mgmtIfPort, int guiPort, AbstractHandler handler, boolean ipv6) {
    // create the server
    server = new Server();
    
    // add the Management Interface connector
    SelectChannelConnector conn1 = new SelectChannelConnector();
    
    if (ipv6) {
        conn1.setHost("::0");
    } else {
        conn1.setHost("0.0.0.0");
    } // if else
    
    conn1.setPort(mgmtIfPort);
    server.addConnector(conn1);
    
    if (guiPort != 0) {
        // add the GUI connector
        SelectChannelConnector conn2 = new SelectChannelConnector();
        
        if (ipv6) {
            conn2.setHost("::0");
        } else {
            conn2.setHost("0.0.0.0");
        } // if else
        
        conn2.setPort(guiPort);
        server.addConnector(conn2);
    } // if
    
    // set the handler
    server.setHandler(handler);
}
 
Example 7
Source File: HttpServer.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
/**
 * Create a status server on the given port.
 * The jsp scripts are taken from src/webapps/<name>.
 * @param name The name of the server
 * @param port The port to use on the server
 * @param findPort whether the server should start at the given port and 
 *        increment by 1 until it finds a free port.
 * @param conf Configuration 
 */
public HttpServer(String name, String bindAddress, int port,
    boolean findPort, Configuration conf) throws IOException {
  webServer = new Server();
  this.findPort = findPort;

  listener = createBaseListener(conf);
  listener.setHost(bindAddress);
  listener.setPort(port);
  webServer.addConnector(listener);

  webServer.setThreadPool(new QueuedThreadPool());

  final String appDir = getWebAppsPath();
  ContextHandlerCollection contexts = new ContextHandlerCollection();
  webServer.setHandler(contexts);

  webAppContext = new WebAppContext();
  webAppContext.setContextPath("/");
  webAppContext.setWar(appDir + "/" + name);
  webServer.addHandler(webAppContext);

  addDefaultApps(contexts, appDir);

  final FilterInitializer[] initializers = getFilterInitializers(conf); 
  if (initializers != null) {
    for(FilterInitializer c : initializers) {
      c.initFilter(this);
    }
  }
  addDefaultServlets();
}
 
Example 8
Source File: JettyContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void start() {
    String serverPort = ConfigUtils.getProperty(JETTY_PORT);
    int port;
    if (serverPort == null || serverPort.length() == 0) {
        port = DEFAULT_JETTY_PORT;
    } else {
        port = Integer.parseInt(serverPort);
    }
    connector = new SelectChannelConnector();
    connector.setPort(port);
    ServletHandler handler = new ServletHandler();
    
    String resources = ConfigUtils.getProperty(JETTY_DIRECTORY);
    if (resources != null && resources.length() > 0) {
        FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT);
        resourceHolder.setInitParameter("resources", resources);
    }
    
    ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*");
    pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES));
    pageHolder.setInitOrder(2);
    
    Server server = new Server();
    server.addConnector(connector);
    server.addHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + NetUtils.getLocalHost() + ":" + port + ", cause: " + e.getMessage(), e);
    }
}
 
Example 9
Source File: LocalServerWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Before
public void setupLocalServer() throws Exception {

    // Set up a local Jetty HTTP server
    Server server = new Server();
    server.addConnector(new SocketConnector());
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase("src/test/resources/server");
    server.addHandler(resourceHandler);
    server.start();

    // The server will have a random port assigned, so capture that
    localPort = server.getConnectors()[0].getLocalPort();
}
 
Example 10
Source File: JettyServer.java    From exhibitor with Apache License 2.0 5 votes vote down vote up
public JettyServer(int port, HttpsConfiguration httpsConf)
{
    server = new Server();

    SslSelectChannelConnector connector = new SslSelectChannelConnector();
    connector.setPort(port);
    connector.setKeystore(httpsConf.getServerKeystorePath());
    connector.setKeyPassword(httpsConf.getServerKeystorePassword());

    if ( httpsConf.isVerifyPeerCert() )
    {
        connector.setTruststore(httpsConf.getTruststorePath());
        connector.setTrustPassword(httpsConf.getTruststorePassword());
        connector.setNeedClientAuth(true);
    }

    connector.setWantClientAuth(httpsConf.isRequireClientCert());

    connector.setAcceptors(8);
    connector.setMaxIdleTime(5000);
    connector.setAcceptQueueSize(32);

    server.addConnector(connector);
    server.setStopAtShutdown(true);

    DefaultResourceConfig config = new DefaultResourceConfig(JettyServer.RestService.class);
    ServletContainer container = new ServletContainer(config);

    Context context = new Context(server, "/", Context.SESSIONS);
    context.addServlet(new ServletHolder(container), "/*");
}
 
Example 11
Source File: JettyContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void start() {
    String serverPort = ConfigUtils.getProperty(JETTY_PORT);
    int port;
    if (serverPort == null || serverPort.length() == 0) {
        port = DEFAULT_JETTY_PORT;
    } else {
        port = Integer.parseInt(serverPort);
    }
    connector = new SelectChannelConnector();
    connector.setPort(port);
    ServletHandler handler = new ServletHandler();
    
    String resources = ConfigUtils.getProperty(JETTY_DIRECTORY);
    if (resources != null && resources.length() > 0) {
        FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT);
        resourceHolder.setInitParameter("resources", resources);
    }
    
    ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*");
    pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES));
    pageHolder.setInitOrder(2);
    
    Server server = new Server();
    server.addConnector(connector);
    server.addHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + NetUtils.getLocalHost() + ":" + port + ", cause: " + e.getMessage(), e);
    }
}
 
Example 12
Source File: JettyContainer.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
public void start() {
    String serverPort = ConfigUtils.getProperty(JETTY_PORT);
    int port;
    if (serverPort == null || serverPort.length() == 0) {
        port = DEFAULT_JETTY_PORT;
    } else {
        port = Integer.parseInt(serverPort);
    }
    connector = new SelectChannelConnector();
    connector.setPort(port);
    ServletHandler handler = new ServletHandler();
    
    String resources = ConfigUtils.getProperty(JETTY_DIRECTORY);
    if (resources != null && resources.length() > 0) {
        FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT);
        resourceHolder.setInitParameter("resources", resources);
    }
    
    ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*");
    pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES));
    pageHolder.setInitOrder(2);
    
    Server server = new Server();
    server.addConnector(connector);
    server.addHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + NetUtils.getLocalHost() + ":" + port + ", cause: " + e.getMessage(), e);
    }
}
 
Example 13
Source File: JettyContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void start() {
    String serverPort = ConfigUtils.getProperty(JETTY_PORT);
    int port;
    if (serverPort == null || serverPort.length() == 0) {
        port = DEFAULT_JETTY_PORT;
    } else {
        port = Integer.parseInt(serverPort);
    }
    connector = new SelectChannelConnector();
    connector.setPort(port);
    ServletHandler handler = new ServletHandler();
    
    String resources = ConfigUtils.getProperty(JETTY_DIRECTORY);
    if (resources != null && resources.length() > 0) {
        FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT);
        resourceHolder.setInitParameter("resources", resources);
    }
    
    ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*");
    pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES));
    pageHolder.setInitOrder(2);
    
    Server server = new Server();
    server.addConnector(connector);
    server.addHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + NetUtils.getLocalHost() + ":" + port + ", cause: " + e.getMessage(), e);
    }
}
 
Example 14
Source File: JettyHttpServer.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
public JettyHttpServer(URL url, final HttpHandler handler) {
        super(url, handler);
        this.url = url;
        // TODO we should leave this setting to slf4j
        // we must disable the debug logging for production use
        Log.setLog(new StdErrLog());
        Log.getLog().setDebugEnabled(false);

        DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), handler);

        int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setDaemon(true);
        threadPool.setMaxThreads(threads);
        threadPool.setMinThreads(threads);

        SelectChannelConnector connector = new SelectChannelConnector();

        String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost());
        if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) {
            connector.setHost(bindIp);
        }
        connector.setPort(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()));

        server = new Server();
        server.setThreadPool(threadPool);
        server.addConnector(connector);

        ServletHandler servletHandler = new ServletHandler();
        ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*");
        servletHolder.setInitOrder(2);

        // dubbo's original impl can't support the use of ServletContext
//        server.addHandler(servletHandler);
        // TODO Context.SESSIONS is the best option here?
        Context context = new Context(server, "/", Context.SESSIONS);
        context.setServletHandler(servletHandler);
        ServletManager.getInstance().addServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), context.getServletContext());

        try {
            server.start();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to start jetty server on " + url.getParameter(Constants.BIND_IP_KEY) + ":" + url.getParameter(Constants.BIND_PORT_KEY) + ", cause: "
                    + e.getMessage(), e);
        }
    }
 
Example 15
Source File: HbaseRestLocalCluster.java    From hadoop-mini-clusters with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    VersionInfo.logVersion();
    Configuration conf = builder.getHbaseConfiguration();

    conf.set("hbase.rest.port", hbaseRestPort.toString());
    conf.set("hbase.rest.readonly", (hbaseRestReadOnly == null) ? "true" : hbaseRestReadOnly.toString());
    conf.set("hbase.rest.info.port", (hbaseRestInfoPort == null) ? "8085" : hbaseRestInfoPort.toString());
    String hbaseRestHost = (this.hbaseRestHost == null) ? "0.0.0.0" : this.hbaseRestHost;

    Integer hbaseRestThreadMax = (this.hbaseRestThreadMax == null) ? 100 : this.hbaseRestThreadMax;
    Integer hbaseRestThreadMin = (this.hbaseRestThreadMin == null) ? 2 : this.hbaseRestThreadMin;

    UserProvider userProvider = UserProvider.instantiate(conf);
    Pair<FilterHolder, Class<? extends ServletContainer>> pair = loginServerPrincipal(userProvider, conf);
    FilterHolder authFilter = pair.getFirst();
    Class<? extends ServletContainer> containerClass = pair.getSecond();
    RESTServlet.getInstance(conf, userProvider);

    // set up the Jersey servlet container for Jetty
    ServletHolder sh = new ServletHolder(containerClass);
    sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", ResourceConfig.class.getCanonicalName());
    sh.setInitParameter("com.sun.jersey.config.property.packages", "jetty");
    ServletHolder shPojoMap = new ServletHolder(containerClass);
    Map<String, String> shInitMap = sh.getInitParameters();
    for (Map.Entry<String, String> e : shInitMap.entrySet()) {
        shPojoMap.setInitParameter(e.getKey(), e.getValue());
    }
    shPojoMap.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true");

    // set up Jetty and run the embedded server

    server = new Server();

    Connector connector = new SelectChannelConnector();
    if (conf.getBoolean(RESTServer.REST_SSL_ENABLED, false)) {
        SslSelectChannelConnector sslConnector = new SslSelectChannelConnector();
        String keystore = conf.get(RESTServer.REST_SSL_KEYSTORE_STORE);
        String password = HBaseConfiguration.getPassword(conf, RESTServer.REST_SSL_KEYSTORE_PASSWORD, null);
        String keyPassword = HBaseConfiguration.getPassword(conf, RESTServer.REST_SSL_KEYSTORE_KEYPASSWORD, password);
        sslConnector.setKeystore(keystore);
        sslConnector.setPassword(password);
        sslConnector.setKeyPassword(keyPassword);
        connector = sslConnector;
    }
    connector.setPort(hbaseRestPort);
    connector.setHost(hbaseRestHost);
    connector.setHeaderBufferSize(8192);


    server.addConnector(connector);

    QueuedThreadPool threadPool = new QueuedThreadPool(hbaseRestThreadMax);
    threadPool.setMinThreads(hbaseRestThreadMin);
    server.setThreadPool(threadPool);

    server.setSendServerVersion(false);
    server.setSendDateHeader(false);
    server.setStopAtShutdown(true);
    // set up context
    Context context = new Context(server, "/", Context.SESSIONS);
    context.addServlet(shPojoMap, "/status/cluster");
    context.addServlet(sh, "/*");
    if (authFilter != null) {
        context.addFilter(authFilter, "/*", 1);
    }

    HttpServerUtil.constrainHttpMethods(context);

    // Put up info server.
    int port = (hbaseRestInfoPort == null) ? 8085 : hbaseRestInfoPort;
    if (port >= 0) {
        conf.setLong("startcode", System.currentTimeMillis());
        String a = hbaseRestHost;
        infoServer = new InfoServer("rest", a, port, false, conf);
        infoServer.setAttribute("hbase.conf", conf);
        infoServer.start();
    }
    // start server
    server.start();
}
 
Example 16
Source File: JettyHttpServer.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public JettyHttpServer(URL url, final HttpHandler handler){
        super(url, handler);

        // modified by lishen
        this.url = url;
        // TODO we should leave this setting to slf4j
        Log.setLog(new StdErrLog());
        Log.getLog().setDebugEnabled(false);

        DispatcherServlet.addHttpHandler(url.getPort(), handler);

        int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setDaemon(true);
        threadPool.setMaxThreads(threads);
        threadPool.setMinThreads(threads);

        SelectChannelConnector connector = new SelectChannelConnector();
        if (! url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) {
            connector.setHost(url.getHost());
        }
        connector.setPort(url.getPort());

        server = new Server();
        server.setThreadPool(threadPool);
        server.addConnector(connector);

        ServletHandler servletHandler = new ServletHandler();
        ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*");
        servletHolder.setInitOrder(2);

        // modified by lishen
        // dubbo's original impl can't support the use of ServletContext
//        server.addHandler(servletHandler);
        // TODO Context.SESSIONS is the best option here?
        Context context = new Context(server, "/", Context.SESSIONS);
        context.setServletHandler(servletHandler);
        ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext());

        try {
            server.start();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to start jetty server on " + url.getAddress() + ", cause: "
                                            + e.getMessage(), e);
        }
    }
 
Example 17
Source File: SubsonicDeployer.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
private void deployWebApp() {
    try {
        Server server = new Server();
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setMaxIdleTime(MAX_IDLE_TIME_MILLIS);
        connector.setHeaderBufferSize(HEADER_BUFFER_SIZE);
        connector.setHost(getHost());
        connector.setPort(getPort());
        if (isHttpsEnabled()) {
            connector.setConfidentialPort(getHttpsPort());
        }
        server.addConnector(connector);

        if (isHttpsEnabled()) {
            SslSocketConnector sslConnector = new SslSocketConnector();
            sslConnector.setMaxIdleTime(MAX_IDLE_TIME_MILLIS);
            sslConnector.setHeaderBufferSize(HEADER_BUFFER_SIZE);
            sslConnector.setHost(getHost());
            sslConnector.setPort(getHttpsPort());
            sslConnector.setKeystore(System.getProperty("subsonic.ssl.keystore", getClass().getResource("/subsonic.keystore").toExternalForm()));
            sslConnector.setPassword(System.getProperty("subsonic.ssl.password", "subsonic"));
            server.addConnector(sslConnector);
        }

        WebAppContext context = new WebAppContext();
        context.setTempDirectory(getJettyDirectory());
        context.setContextPath(getContextPath());
        context.setWar(getWar());
        context.setOverrideDescriptor("/web-jetty.xml");

        if (isHttpsEnabled()) {

            // Allow non-https for streaming and cover art (for Chromecast, UPnP, Sonos etc)
            context.getSecurityHandler().setConstraintMappings(new ConstraintMapping[]{
                    createConstraintMapping("/stream", Constraint.DC_NONE),
                    createConstraintMapping("/coverArt.view", Constraint.DC_NONE),
                    createConstraintMapping("/ws/*", Constraint.DC_NONE),
                    createConstraintMapping("/sonos/*", Constraint.DC_NONE),
                    createConstraintMapping("/", Constraint.DC_CONFIDENTIAL)
            });
        }

        server.addHandler(context);
        server.start();

        System.err.println("Subsonic running on: " + getUrl());
        if (isHttpsEnabled()) {
            System.err.println("                and: " + getHttpsUrl());
        }

    } catch (Throwable x) {
        x.printStackTrace();
        exception = x;
    }
}
 
Example 18
Source File: Main.java    From stanbol-freeling with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @param args
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    CommandLine line = parser.parse(options, args);
    args = line.getArgs();
    if(line.hasOption('h')){
        printHelp();
        System.exit(0);
    }
    //Parse the Freeling parameter and init the Freeling instance
    String sharedFolder = System.getenv(ENV_FREELING_SHARED_FOLDER);
    sharedFolder = System.getProperty(PROPERTY_FREELING_SHARED_FOLDER, sharedFolder);
    sharedFolder = line.getOptionValue('s', sharedFolder);
    if(sharedFolder == null){
        System.err.println("The Freeling shared Folder MUST BE set! \n");
        printHelp();
        System.exit(0);
    }
    File shared = new File(sharedFolder);
    if(!shared.isDirectory()){
        System.err.println("The configured Freeling shared folder '"
            + sharedFolder + "' is not a directory!\n");
        System.exit(1);
    }
    String configFolder = FilenameUtils.concat(sharedFolder, "config");
    configFolder = System.getProperty(PROPERTY_FREELING_CONFIG_FOLDER, configFolder);
    configFolder = line.getOptionValue('c', configFolder);
    File config = new File(configFolder);
    if(!config.isDirectory()){
        System.err.println("The configured Freeling config folder '"
            + configFolder + "' is not a directory!\n");
        System.exit(1);
    }
    String nativeLib = FilenameUtils.concat(sharedFolder, Freeling.DEFAULT_FREELING_LIB_PATH);
    if(new File(Freeling.DEFAULT_FREELING_LIB_PATH).isFile()){
        nativeLib = Freeling.DEFAULT_FREELING_LIB_PATH;
    }
    nativeLib = line.getOptionValue('l', nativeLib);
    if(!new File(nativeLib).isFile()){
        System.err.println("The configured Freeling native lib '"
                + nativeLib + "' is not a file!\n");
        System.exit(1);
    }
    Freeling freeling = new Freeling(
        config.getPath(), Freeling.DEFAULT_CONFIGURATION_FILENAME_SUFFIX, 
        shared.getPath(), nativeLib, Freeling.DEFAULT_FREELING_LOCALE, 
        getInt(line, 'i', DEFAULT_INIT_THREADS), 
        getInt(line, 'm', DEFAULT_MAX_POOL_SIZE), 
        getInt(line, 'q', DEFAULT_MIN_QUEUE_SIZE));
    
    
    //init the Jetty Server
    Server server = new Server();
    Connector con = new SelectChannelConnector();
    //we need the port
    con.setPort(getInt(line,'p',DEFAULT_PORT));
    server.addConnector(con);

    //init the Servlet and the ServletContext
    Context context = new Context(server, "/", Context.SESSIONS);
    ServletHolder holder = new ServletHolder(RestServlet.class);
    holder.setInitParameter("javax.ws.rs.Application", FreelingApplication.class.getName());
    context.addServlet(holder, "/*");
    
    //now initialise the servlet context
    context.setAttribute(Constants.SERVLET_ATTRIBUTE_CONTENT_ITEM_FACTORY, 
        lookupService(ContentItemFactory.class));
    context.setAttribute(Constants.SERVLET_ATTRIBUTE_FREELING, freeling);
    context.setAttribute(Constants.SERVLET_ATTRIBUTE_MAX_RESOURCE_WAIT_TIEM, 
        getLong(line,'w',Constants.DEFAULT_RESOURCE_WAIT_TIME));
    //Freeling
    
    server.start();
    try {
        server.join();
    }catch (InterruptedException e) {
    }
    System.err.println("Shutting down Freeling");
    freeling.close();
}
 
Example 19
Source File: JettyHttpServer.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
public JettyHttpServer(URL url, final HttpHandler handler){
        super(url, handler);

        // modified by lishen
        this.url = url;
        // TODO we should leave this setting to slf4j
        Log.setLog(new StdErrLog());
        Log.getLog().setDebugEnabled(false);

        DispatcherServlet.addHttpHandler(url.getPort(), handler);

        int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setDaemon(true);
        threadPool.setMaxThreads(threads);
        threadPool.setMinThreads(threads);

        SelectChannelConnector connector = new SelectChannelConnector();
        if (! url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) {
            connector.setHost(url.getHost());
        }
        connector.setPort(url.getPort());

        server = new Server();
        server.setThreadPool(threadPool);
        server.addConnector(connector);

        ServletHandler servletHandler = new ServletHandler();
        ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*");
        servletHolder.setInitOrder(2);

        // modified by lishen
        // dubbo's original impl can't support the use of ServletContext
//        server.addHandler(servletHandler);
        // TODO Context.SESSIONS is the best option here?
        Context context = new Context(server, "/", Context.SESSIONS);
        context.setServletHandler(servletHandler);
        ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext());

        try {
            server.start();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to start jetty server on " + url.getAddress() + ", cause: "
                                            + e.getMessage(), e);
        }
    }
 
Example 20
Source File: JettyHttpServer.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public JettyHttpServer(URL url, final HttpHandler handler){
        super(url, handler);

        // modified by lishen
        this.url = url;
        // TODO we should leave this setting to slf4j
        Log.setLog(new StdErrLog());
        Log.getLog().setDebugEnabled(false);

        DispatcherServlet.addHttpHandler(url.getPort(), handler);

        int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setDaemon(true);
        threadPool.setMaxThreads(threads);
        threadPool.setMinThreads(threads);

        SelectChannelConnector connector = new SelectChannelConnector();
        if (! url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) {
            connector.setHost(url.getHost());
        }
        connector.setPort(url.getPort());

        server = new Server();
        server.setThreadPool(threadPool);
        server.addConnector(connector);

        ServletHandler servletHandler = new ServletHandler();
        ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*");
        servletHolder.setInitOrder(2);

        // modified by lishen
        // dubbo's original impl can't support the use of ServletContext
//        server.addHandler(servletHandler);
        // TODO Context.SESSIONS is the best option here?
        Context context = new Context(server, "/", Context.SESSIONS);
        context.setServletHandler(servletHandler);
        ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext());

        try {
            server.start();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to start jetty server on " + url.getAddress() + ", cause: "
                                            + e.getMessage(), e);
        }
    }