org.eclipse.jetty.server.Server Scala Examples

The following examples show how to use org.eclipse.jetty.server.Server. 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.
Example 1
Source File: ApplicationServer.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.todo.jetty

import io.udash.todo.services.InMemoryTodoStorage
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.handler.gzip.GzipHandler
import org.eclipse.jetty.server.session.SessionHandler
import org.eclipse.jetty.servlet.{DefaultServlet, ServletContextHandler, ServletHolder}

class ApplicationServer(val port: Int, resourceBase: String) {
  private val server = new Server(port)
  private val contextHandler = new ServletContextHandler
  private val appHolder = createAppHolder()
  private val atmosphereHolder = createAtmosphereHolder()

  contextHandler.setSessionHandler(new SessionHandler)
  contextHandler.setGzipHandler(new GzipHandler)
  contextHandler.getSessionHandler.addEventListener(new org.atmosphere.cpr.SessionSupport())
  contextHandler.addServlet(atmosphereHolder, "/atm/*")
  contextHandler.addServlet(appHolder, "/*")
  server.setHandler(contextHandler)

  def start(): Unit = server.start()
  def stop(): Unit = server.stop()

  private def createAppHolder() = {
    val appHolder = new ServletHolder(new DefaultServlet)
    appHolder.setAsyncSupported(true)
    appHolder.setInitParameter("resourceBase", resourceBase)
    appHolder
  }

  private def createAtmosphereHolder() = {
    import io.udash.rpc._
    import io.udash.todo.rpc._

    val config = new DefaultAtmosphereServiceConfig(_ =>
      new DefaultExposesServerRPC[MainServerRPC](new ExposedRpcInterfaces(InMemoryTodoStorage))
    )

    val framework = new DefaultAtmosphereFramework(config)

    val atmosphereHolder = new ServletHolder(new RpcServlet(framework))
    atmosphereHolder.setAsyncSupported(true)
    atmosphereHolder
  }

} 
Example 2
Source File: HttpServer.scala    From amaterasu   with Apache License 2.0 5 votes vote down vote up
package org.apache.amaterasu.leader.utilities

import org.apache.amaterasu.common.logging.Logging
import org.apache.log4j.{BasicConfigurator, Level, Logger}
import org.eclipse.jetty.server.handler.ErrorHandler
import org.eclipse.jetty.server.{Server, ServerConnector}
import org.eclipse.jetty.servlet.{DefaultServlet, ServletContextHandler, ServletHolder}
import org.eclipse.jetty.util.log.StdErrLog


    BasicConfigurator.configure()
    initLogging()
    server = new Server()
    val connector = new ServerConnector(server)
    connector.setPort(port.toInt)
    server.addConnector(connector)
    val context = new ServletContextHandler(ServletContextHandler.SESSIONS)
    context.setResourceBase(serverRoot)
    context.setContextPath("/")
    server.setHandler(context)
    context.setErrorHandler(new ErrorHandler())
    context.setInitParameter("dirAllowed", "true")
    context.setInitParameter("pathInfoOnly", "true")
    context.addServlet(new ServletHolder(new DefaultServlet()), "/")
    server.start()
  }

  def stop() {
    if (server == null) throw new IllegalStateException("Server not started")

    server.stop()
    server = null
  }

  def initLogging(): Unit = {
    System.setProperty("org.eclipse.jetty.util.log.class", classOf[StdErrLog].getName)
    Logger.getLogger("org.eclipse.jetty").setLevel(Level.OFF)
    Logger.getLogger("org.eclipse.jetty.websocket").setLevel(Level.OFF)
  }
} 
Example 3
Source File: SchemaRegistryService.scala    From ksql-streams   with Apache License 2.0 5 votes vote down vote up
package com.landoop.kstreams.sql.cluster

import java.util.Properties

import io.confluent.kafka.schemaregistry.avro.AvroCompatibilityLevel
import io.confluent.kafka.schemaregistry.client.rest.RestService
import io.confluent.kafka.schemaregistry.rest.{SchemaRegistryConfig, SchemaRegistryRestApplication}
import io.confluent.kafka.schemaregistry.storage.SchemaRegistry
import io.confluent.kafka.schemaregistry.zookeeper.SchemaRegistryIdentity
import org.eclipse.jetty.server.Server

class SchemaRegistryService(val port: Int,
                            val zookeeperConnection: String,
                            val kafkaTopic: String,
                            val avroCompatibilityLevel: AvroCompatibilityLevel,
                            val masterEligibility: Boolean) {

  private val app = new SchemaRegistryRestApplication({
    val prop = new Properties
    prop.setProperty("port", port.asInstanceOf[Integer].toString)
    prop.setProperty(SchemaRegistryConfig.KAFKASTORE_CONNECTION_URL_CONFIG, zookeeperConnection)
    prop.put(SchemaRegistryConfig.KAFKASTORE_TOPIC_CONFIG, kafkaTopic)
    prop.put(SchemaRegistryConfig.COMPATIBILITY_CONFIG, avroCompatibilityLevel.toString)
    prop.put(SchemaRegistryConfig.MASTER_ELIGIBILITY, masterEligibility.asInstanceOf[AnyRef])

    prop
  })

  val restServer: Server = app.createServer
  restServer.start()

  var Endpoint: String = {
    val uri = restServer.getURI.toString
    if (uri.endsWith("/")) uri.substring(0, uri.length - 1)
    else uri
  }

  val restClient = new RestService(Endpoint)

  def close() {
    if (restServer != null) {
      restServer.stop()
      restServer.join()
    }
  }

  def isMaster: Boolean = app.schemaRegistry.isMaster

  def setMaster(schemaRegistryIdentity: SchemaRegistryIdentity) {
    app.schemaRegistry.setMaster(schemaRegistryIdentity)
  }

  def myIdentity: SchemaRegistryIdentity = app.schemaRegistry.myIdentity

  def masterIdentity: SchemaRegistryIdentity = app.schemaRegistry.masterIdentity

  def schemaRegistry: SchemaRegistry = app.schemaRegistry
} 
Example 4
Source File: SchemaRegistryService.scala    From kafka-testing   with Apache License 2.0 5 votes vote down vote up
package com.landoop.kafka.testing

import java.net.{Socket, SocketException}
import java.util.Properties

import com.typesafe.scalalogging.StrictLogging
import io.confluent.kafka.schemaregistry.avro.AvroCompatibilityLevel
import io.confluent.kafka.schemaregistry.client.rest.RestService
import io.confluent.kafka.schemaregistry.rest.{SchemaRegistryConfig, SchemaRegistryRestApplication}
import io.confluent.kafka.schemaregistry.storage.{SchemaRegistry, SchemaRegistryIdentity}
import org.eclipse.jetty.server.Server

class SchemaRegistryService(val port: Int,
                            val zookeeperConnection: String,
                            val kafkaTopic: String,
                            val avroCompatibilityLevel: AvroCompatibilityLevel,
                            val masterEligibility: Boolean) extends StrictLogging {

  private val app = new SchemaRegistryRestApplication({
    val prop = new Properties
    prop.setProperty("port", port.asInstanceOf[Integer].toString)
    prop.setProperty(SchemaRegistryConfig.KAFKASTORE_CONNECTION_URL_CONFIG, zookeeperConnection)
    prop.put(SchemaRegistryConfig.KAFKASTORE_TOPIC_CONFIG, kafkaTopic)
    prop.put(SchemaRegistryConfig.COMPATIBILITY_CONFIG, avroCompatibilityLevel.toString)
    prop.put(SchemaRegistryConfig.MASTER_ELIGIBILITY, masterEligibility.asInstanceOf[AnyRef])
    prop
  })

  val restServer = startServer(port)

  var Endpoint: String = getEndpoint(restServer)

  val restClient = new RestService(Endpoint)

  def startServer(port: Int, retries: Int = 5): Option[Server] = {
    var retry = retries > 0
    var restServer: Option[Server] = None
    if (retry) {
      if (isPortInUse(port)) {
        logger.info(s"Schema Registry Port $port is already in use")
        Thread.sleep(2000)
        startServer(port, retries - 1)
      } else {
        restServer = Some(app.createServer)
        restServer.get.start()
      }
    }
    restServer
  }

  def getEndpoint(restServer: Option[Server]): String = {
    if (restServer.isDefined) {
      val uri = restServer.get.getURI.toString
      if (uri.endsWith("/")) {
        uri.substring(0, uri.length - 1)
      } else {
        uri
      }
    } else ""
  }

  private def isPortInUse(port: Integer): Boolean = try {
    new Socket("127.0.0.1", port).close()
    true
  }
  catch {
    case e: SocketException => false
  }

  def close() {
    if (restServer.isDefined) {
      restServer.get.stop()
      restServer.get.join()
    }
  }

  def isMaster: Boolean = app.schemaRegistry.isMaster

  def setMaster(schemaRegistryIdentity: SchemaRegistryIdentity): Unit =
    app.schemaRegistry.setMaster(schemaRegistryIdentity)

  def myIdentity: SchemaRegistryIdentity = app.schemaRegistry.myIdentity

  def masterIdentity: SchemaRegistryIdentity = app.schemaRegistry.masterIdentity

  def schemaRegistry: SchemaRegistry = app.schemaRegistry
} 
Example 5
Source File: CommonJettyMain.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.service.server

import org.eclipse.jetty.server.handler.gzip.GzipHandler
import org.eclipse.jetty.server.{HttpConfiguration, HttpConnectionFactory, NetworkTrafficServerConnector, Server}
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

import ai.deepsense.commons.utils.LoggerForCallerClass

object CommonJettyMain {

  val logger = LoggerForCallerClass()

  def startServer(
      contextPath: String,
      scalatraBootstrapClass: Class[_],
      webAppResourcePath: String,
      jettyConfig: JettyConfig
    ): Server = {
    val server: Server = new Server
    logger.info("Starting Jetty...")

    server setStopTimeout jettyConfig.stopTimeout.toMillis
    server setStopAtShutdown true

    val httpConfig = new HttpConfiguration()
    httpConfig setSendDateHeader true
    httpConfig setSendServerVersion false

    val connector = new NetworkTrafficServerConnector(server, new HttpConnectionFactory(httpConfig))
    connector setPort jettyConfig.port
    connector setSoLingerTime 0
    connector setIdleTimeout jettyConfig.connectorIdleTimeout.toMillis
    server addConnector connector

    val webApp = new WebAppContext
    webApp setInitParameter (
      ScalatraListener.LifeCycleKey,
      scalatraBootstrapClass.getCanonicalName
      )

    webApp setContextPath contextPath
    webApp setResourceBase getClass.getClassLoader.getResource(webAppResourcePath).toExternalForm
    webApp setEventListeners Array(new ScalatraListener)
    webApp setMaxFormContentSize jettyConfig.maxFormContentSize
    server insertHandler decorateWithGzipHandler(webApp)

    server.start()
    server
  }

  private def decorateWithGzipHandler(webApp: WebAppContext): GzipHandler = {
    val gzippedWebApp = new GzipHandler()
    gzippedWebApp.setIncludedMimeTypes(
      "text/css",
      "text/javascript",
      "text/html",
      "text/plain",
      "text/xml",
      "application/javascript",
      "application/json"
    )
    gzippedWebApp.setHandler(webApp)
    gzippedWebApp
  }

} 
Example 6
Source File: JettyMain.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.seahorse.scheduling.server

import com.typesafe.config.ConfigFactory
import org.eclipse.jetty.server.Server

import ai.deepsense.commons.service.server.{CommonJettyMain, JettyConfig}
import ai.deepsense.seahorse.scheduling.SchedulingManagerConfig
import ai.deepsense.seahorse.scheduling.db.{Database, FlywayMigration}

object JettyMain {

  def main(args: Array[String]): Unit = start(args, SchedulingManagerConfig.jetty)

  def start(args: Array[String], config: JettyConfig): Server = {
    Database.forceInitialization()
    FlywayMigration.run()

    CommonJettyMain.startServer(
      contextPath = "/schedulingmanager/v1/",
      scalatraBootstrapClass = classOf[ScalatraBootstrap],
      webAppResourcePath = "scalatra-webapp",
      config
    )
  }

} 
Example 7
Source File: JettyMain.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.seahorse.datasource.server

import org.eclipse.jetty.server.Server

import ai.deepsense.commons.service.server.CommonJettyMain
import ai.deepsense.seahorse.datasource.DatasourceManagerConfig
import ai.deepsense.seahorse.datasource.db.{Database, FlywayMigration}

object JettyMain {

  def main(args: Array[String]): Unit = start(args)

  def start(args: Array[String]): Server = {
    Database.forceInitialization()
    FlywayMigration.run()

    CommonJettyMain.startServer(
      contextPath = "/datasourcemanager/v1/",
      scalatraBootstrapClass = classOf[ScalatraBootstrap],
      webAppResourcePath = "scalatra-webapp",
      DatasourceManagerConfig.jetty
    )
  }

} 
Example 8
Source File: JettyMain.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.libraryservice

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

object JettyMain {

  def main(args: Array[String]): Unit = {
    val server: Server = new Server(Config.Server.port)
    val context = new WebAppContext()
    context setContextPath "/"
    context.setResourceBase("src/main/webapp")
    context.addEventListener(new ScalatraListener)

    server.setHandler(context)

    server.start()
    server.join()
  }
} 
Example 9
Source File: JettyLauncher.scala    From NGSI-LD_Experimental   with MIT License 5 votes vote down vote up
package main

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.{DefaultServlet, ServletContextHandler}
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener


object JettyLauncher extends Configuration  {
  def main(args:Array[String]) = {
    val port = System.getenv().getOrDefault(Port,DefaultPort).toInt

    val server = new Server(port)
    val context = new WebAppContext()

    context setContextPath "/"
    context.setResourceBase("src/main/webapp")
    context.addEventListener(new ScalatraListener)
    context.addServlet(classOf[DefaultServlet], "/")

    server.setHandler(context)

    server.start
    server.join
  }
} 
Example 10
Source File: ApplicationServer.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.demos.files.jetty

import javax.servlet.MultipartConfigElement

import io.udash.demos.files.ApplicationServerContexts
import io.udash.demos.files.rpc.{MainRpcEndpoint, MainServerRPC}
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.handler.gzip.GzipHandler
import org.eclipse.jetty.server.session.SessionHandler
import org.eclipse.jetty.servlet.{DefaultServlet, ServletContextHandler, ServletHolder}

class ApplicationServer(val port: Int, resourceBase: String) {

  private val server = new Server(port)
  private val contextHandler = new ServletContextHandler

  contextHandler.setSessionHandler(new SessionHandler)
  contextHandler.setGzipHandler(new GzipHandler)
  server.setHandler(contextHandler)

  def start(): Unit = server.start()
  def stop(): Unit = server.stop()

  private val appHolder = {
    val appHolder = new ServletHolder(new DefaultServlet)
    appHolder.setAsyncSupported(true)
    appHolder.setInitParameter("resourceBase", resourceBase)
    appHolder
  }
  contextHandler.addServlet(appHolder, "/*")

  private val uploadsHolder = {
    val holder = new ServletHolder(new DemoFileUploadServlet(resourceBase + "/uploads"))
    holder.getRegistration.setMultipartConfig(new MultipartConfigElement(""))
    holder
  }
  contextHandler.addServlet(uploadsHolder, ApplicationServerContexts.uploadContextPrefix + "/*")

  private val downloadsHolder = {
    val holder = new ServletHolder(new DemoFileDownloadServlet(resourceBase + "/uploads", ApplicationServerContexts.downloadContextPrefix))
    holder.getRegistration.setMultipartConfig(new MultipartConfigElement(""))
    holder
  }
  contextHandler.addServlet(downloadsHolder, ApplicationServerContexts.downloadContextPrefix + "/*")

  private val atmosphereHolder = {
    import io.udash.rpc._

    val config = new DefaultAtmosphereServiceConfig[MainServerRPC]((_) =>
      new DefaultExposesServerRPC[MainServerRPC](new MainRpcEndpoint)
    )
    val framework = new DefaultAtmosphereFramework(config)

    val atmosphereHolder = new ServletHolder(new RpcServlet(framework))
    atmosphereHolder.setAsyncSupported(true)
    atmosphereHolder
  }
  contextHandler.addServlet(atmosphereHolder, ApplicationServerContexts.atmosphereContextPrefix + "/*")
} 
Example 11
Source File: Main.scala    From scala-json-rpc   with MIT License 5 votes vote down vote up
package io.github.shogowada.scala.jsonrpc.example.e2e.websocket

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.DefaultServlet
import org.eclipse.jetty.util.resource.Resource
import org.eclipse.jetty.webapp.WebAppContext

object Main {
  def main(args: Array[String]): Unit = {
    val port = System.getProperty("port", "8080").toInt
    val server = new Server(port)

    val context = new WebAppContext()
    context.setContextPath("/")
    context.setResourceBase(
      Resource.newResource(ClassLoader.getSystemResource("public"))
          .getURI
          .toASCIIString
    )
    context.addServlet(classOf[DefaultServlet], "/")
    context.addServlet(classOf[JSONRPCWebSocketServlet], "/jsonrpc")

    server.setHandler(context)

    server.start()
    server.join()
  }
} 
Example 12
Source File: ExampleApp.scala    From spring-boot-scala-example   with Apache License 2.0 5 votes vote down vote up
package spring.boot.scala.example

import org.eclipse.jetty.server.{NetworkTrafficServerConnector, Server}
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory
import org.springframework.context.annotation.Bean

@SpringBootApplication
class ExampleApp {

  @Bean
  def webServerFactory(@Value("${server.http.port}") httpPort: Int): ConfigurableServletWebServerFactory = {
    val factory = new JettyServletWebServerFactory
    factory.addServerCustomizers((server: Server) => {
      val connector = new NetworkTrafficServerConnector(server)
      connector.setPort(httpPort)
      server.addConnector(connector)
    })
    factory
  }
}

object ExampleApp {
  def main(args: Array[String]): Unit = SpringApplication.run(classOf[ExampleApp], args: _*)

} 
Example 13
Source File: HttpStreamServer.scala    From spark-http-stream   with BSD 2-Clause "Simplified" License 5 votes vote down vote up
package org.apache.spark.sql.execution.streaming.http

import org.apache.spark.internal.Logging
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.ServletContextHandler

import javax.servlet.ServletConfig
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.eclipse.jetty.servlet.ServletHolder
import scala.collection.JavaConversions

class MissingRequiredRequestParameterException(paramName: String)
		extends RuntimeException(s"missing required request parameter: $paramName") {
}

class UnsupportedActionException(action: String)
		extends RuntimeException(s"unsupported action in HTTP request header: $action") {
}

object HttpStreamServer {
	def start(httpServletPath: String, httpPort: Int) = {
		val server = new HttpStreamServer(httpServletPath, httpPort);
		server.start;
		server;
	}
}


	def withActionsHandler[T <: ActionsHandler](actionsHandler: T): T = {
		this.actionsHandler = actionsHandler;
		actionsHandler;
	}

	def withBuffer(): MemoryBufferAsReceiver = {
		withActionsHandler(new MemoryBufferAsReceiver());
	}

	def withKafka(bootstrapServers: String): KafkaAsReceiver = {
		withActionsHandler(new KafkaAsReceiver(bootstrapServers));
	}

	def stop() = {
		httpStreamServlet.destroy();
		if (server != null)
			server.stop();
	}
} 
Example 14
Source File: ServletBasedRestApiTest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package rest

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.{ServletHandler, ServletHolder}

import scala.concurrent.duration._

abstract class ServletBasedRestApiTest extends RestApiTest with UsesHttpServer {
  override implicit def patienceConfig: PatienceConfig = PatienceConfig(10.seconds)

  def maxPayloadSize: Int = 1024 * 1024
  def serverTimeout: FiniteDuration = 10.seconds

  protected def setupServer(server: Server): Unit = {
    val servlet = new RestServlet(serverHandle, serverTimeout, maxPayloadSize)
    val holder = new ServletHolder(servlet)
    val handler = new ServletHandler
    handler.addServletWithMapping(holder, "/api/*")
    server.setHandler(handler)
  }
} 
Example 15
Source File: UsesHttpServer.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package rest

import org.eclipse.jetty.server.Server
import org.scalatest.{BeforeAndAfterAll, Suite}

trait UsesHttpServer extends BeforeAndAfterAll { this: Suite =>
  def port: Int
  val server: Server = new Server(port)
  def baseUrl = s"http://localhost:$port"

  protected def setupServer(server: Server): Unit

  override protected def beforeAll(): Unit = {
    super.beforeAll()
    setupServer(server)
    server.start()
  }

  override protected def afterAll(): Unit = {
    server.stop()
    super.afterAll()
  }
} 
Example 16
Source File: ServerMain.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package rest.examples

import io.udash.rest.RestServlet
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.{ServletContextHandler, ServletHolder}

import scala.concurrent.Future

class UserApiImpl extends UserApi {
  def createUser(name: String): Future[User] =
    Future.successful(User(UserId(0), name))
  def getUser(id: UserId): Future[User] =
    Future.successful(User(id, s"$id-name"))
}

object ServerMain {
  def main(args: Array[String]): Unit = {
    val server = new Server(9090)
    val handler = new ServletContextHandler
    handler.addServlet(new ServletHolder(RestServlet[UserApi](new UserApiImpl)), "/*")
    server.setHandler(handler)
    server.start()
    server.join()
  }
} 
Example 17
Source File: ApplicationServer.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.web.server

import io.udash.rest._
import io.udash.rpc._
import io.udash.rpc.utils.{CallLogging, DefaultAtmosphereFramework}
import io.udash.web.guide.demos.activity.{Call, CallLogger}
import io.udash.web.guide.demos.rest.MainServerREST
import io.udash.web.guide.rest.ExposedRestInterfaces
import io.udash.web.guide.rpc.ExposedRpcInterfaces
import io.udash.web.guide.{GuideExceptions, MainServerRPC}
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.handler.ContextHandlerCollection
import org.eclipse.jetty.server.handler.gzip.GzipHandler
import org.eclipse.jetty.server.session.SessionHandler
import org.eclipse.jetty.servlet.{DefaultServlet, ServletContextHandler, ServletHolder}

class ApplicationServer(val port: Int, homepageResourceBase: String, guideResourceBase: String) {
  private val server = new Server(port)

  def start(): Unit = {
    server.start()
  }

  def stop(): Unit = {
    server.stop()
  }

  private val homepage = {
    val ctx = createContextHandler(Array("udash.io", "www.udash.io", "127.0.0.1"))
    ctx.addServlet(createStaticHandler(homepageResourceBase), "?)*$")
    spaRewrite.setReplacement("/")
    rewrite.addRule(spaRewrite)
    rewrite.setHandler(contexts)
    rewrite
  }

  server.setHandler(rewriteHandler)

  private def createContextHandler(hosts: Array[String]): ServletContextHandler = {
    val context = new ServletContextHandler
    context.setSessionHandler(new SessionHandler)
    context.setGzipHandler(new GzipHandler)
    context.setVirtualHosts(hosts)
    context
  }

  private def createStaticHandler(resourceBase: String): ServletHolder = {
    val appHolder = new ServletHolder(new DefaultServlet)
    appHolder.setAsyncSupported(true)
    appHolder.setInitParameter("resourceBase", resourceBase)
    appHolder
  }
} 
Example 18
Source File: TestTargetServer.scala    From scalajs-reactjs   with MIT License 5 votes vote down vote up
package io.github.shogowada.scalajs.reactjs.example

import java.net.ServerSocket

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.handler.ResourceHandler

class TestTargetServer(project: String) {
  private var server: Server = _

  def start(): Unit = {
    val maybeTarget = sys.props.get(s"target.path.$project")
    assert(maybeTarget.isDefined)
    val target = maybeTarget.get
    println(s"Target path for $project: $target")

    val port = freePort
    println(s"Target port for $project: $port")

    server = new Server(port)
    val handler = new ResourceHandler()
    handler.setResourceBase(s"$target")
    server.setHandler(handler)
    server.start()

    println(s"Target host for $project: $host")
  }

  def freePort: Int = {
    var socket: ServerSocket = null
    var port: Int = 0
    try {
      socket = new ServerSocket(0)
      socket.setReuseAddress(true)
      port = socket.getLocalPort
    } finally {
      socket.close()
    }
    port
  }

  def host: String = s"http://localhost:${server.getURI.getPort}/classes"

  def stop(): Unit = {
    server.stop()
  }
}

object TestTargetServers {
  val customVirtualDOM = new TestTargetServer("custom-virtual-dom")
  val helloWorld = new TestTargetServer("helloworld")
  val helloWorldFunction = new TestTargetServer("helloworld-function")
  val interactiveHelloWorld = new TestTargetServer("interactive-helloworld")
  val lifecycle = new TestTargetServer("lifecycle")
  val reduxDevTools = new TestTargetServer("redux-devtools")
  val reduxMiddleware = new TestTargetServer("redux-middleware")
  val router = new TestTargetServer("router")
  val routerRedux = new TestTargetServer("router-redux")
  val style = new TestTargetServer("style")
  val todoApp = new TestTargetServer("todo-app")
  val todoAppRedux = new TestTargetServer("todo-app-redux")

  customVirtualDOM.start()
  helloWorld.start()
  helloWorldFunction.start()
  interactiveHelloWorld.start()
  lifecycle.start()
  reduxDevTools.start()
  reduxMiddleware.start()
  routerRedux.start()
  router.start()
  style.start()
  todoApp.start()
  todoAppRedux.start()

  sys.addShutdownHook(() => {
    customVirtualDOM.stop()
    helloWorld.stop()
    helloWorldFunction.stop()
    interactiveHelloWorld.stop()
    lifecycle.stop()
    reduxDevTools.stop()
    reduxMiddleware.stop()
    routerRedux.stop()
    router.stop()
    style.stop()
    todoApp.stop()
    todoAppRedux.stop()
  })
} 
Example 19
Source File: Main.scala    From scala-json-rpc   with MIT License 5 votes vote down vote up
package io.github.shogowada.scala.jsonrpc.example.e2e

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.DefaultServlet
import org.eclipse.jetty.util.resource.Resource
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

object Main {

  def main(args: Array[String]): Unit = {
    val port = System.getProperty("port", "8080").toInt
    println(s"Running server at port $port")

    val server = new Server(port)

    val context = new WebAppContext()
    context.setContextPath("/")
    context.setResourceBase(
      Resource.newResource(ClassLoader.getSystemResource("public"))
          .getURI
          .toASCIIString
    )
    context.setInitParameter(ScalatraListener.LifeCycleKey, classOf[ScalatraBootstrap].getCanonicalName)
    context.addEventListener(new ScalatraListener)
    context.addServlet(classOf[DefaultServlet], "/")

    server.setHandler(context)

    server.start()
    server.join()
  }
}