当前位置: 首页>>代码示例>>Scala>>正文


Scala Server类代码示例

本文整理汇总了Scala中org.eclipse.jetty.server.Server的典型用法代码示例。如果您正苦于以下问题:Scala Server类的具体用法?Scala Server怎么用?Scala Server使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Server类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: RunWebApp

//设置package包名称以及导入依赖的类
import org.eclipse.jetty.server.handler.ContextHandler
import org.eclipse.jetty.server.nio.SelectChannelConnector
import org.eclipse.jetty.server.{Handler, Server}
import org.eclipse.jetty.webapp.WebAppContext

object RunWebApp extends App {
  val server = new Server
  val scc = new SelectChannelConnector
  scc.setPort(8080)
  server.setConnectors(Array(scc))

  val context = new WebAppContext()
  context.setServer(server)
  context.setWar("src/main/webapp")

  val context0: ContextHandler = new ContextHandler();
  context0.setHandler(context)
  server.setHandler(context0)

  try {
    println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP")
    server.start()
    while (System.in.available() == 0) {
      Thread.sleep(5000)
    }
    server.stop()
    server.join()
  } catch {
    case exc: Exception => {
      exc.printStackTrace()
      System.exit(100)
    }
  }
} 
开发者ID:EasterTheBunny,项目名称:ourdistrict,代码行数:35,代码来源:RunWebApp.scala

示例2: MyBankServer

//设置package包名称以及导入依赖的类
package teksol.mybank.infrastructure

import java.util.concurrent.TimeUnit

import org.eclipse.jetty.server.Server
import org.slf4j.LoggerFactory
import org.springframework.util.Assert
import teksol.Config

class MyBankServer(address: String, port: Int) {
    Assert.notNull(address, "address")
    Assert.isTrue(0 <= port && port <= 65535, "port must be (0..65535), found " + port)

    private[this] val log = LoggerFactory.getLogger(this.getClass)

    
    def join(config: Config): Unit = {
        val server = new Server(port)
        server.setHandler(new MyBankHandler(config))
        new Thread(() => {
            server.start()
            server.join()
        }, "MyBank-HTTP-Server").start()

        TimeUnit.SECONDS.sleep(2)
        log.info("Press any key to stop Jetty server")
        System.in.read()
        server.stop()
    }
} 
开发者ID:francois,项目名称:family,代码行数:31,代码来源:MyBankServer.scala

示例3: AppMock

//设置package包名称以及导入依赖的类
package mesosphere.marathon.integration.setup

import java.lang.management.ManagementFactory

import org.eclipse.jetty.server.{ Request, Server }
import org.eclipse.jetty.server.handler.AbstractHandler
import javax.servlet.http.{ HttpServletResponse, HttpServletRequest }
import akka.actor.ActorSystem
import spray.client.pipelining._
import scala.concurrent.Await._
import scala.concurrent.duration._

class AppMock(appId: String, version: String, url: String) extends AbstractHandler {
  import scala.concurrent.ExecutionContext.Implicits.global

  implicit val system = ActorSystem()
  val pipeline = sendReceive
  val waitTime = 30.seconds

  val processId = ManagementFactory.getRuntimeMXBean.getName

  def start(port: Int): Unit = {
    val server = new Server(port)
    server.setHandler(this)
    server.start()
    val taskId = System.getenv().getOrDefault("MESOS_TASK_ID", "<UNKNOWN>")
    println(s"AppMock[$appId $version]: $taskId has taken the stage at port $port. Will query $url for health status.")
    server.join()
    println(s"AppMock[$appId $version]: says goodbye")
  }

  override def handle(
    target: String,
    baseRequest: Request,
    request: HttpServletRequest,
    response: HttpServletResponse): Unit = {

    if (request.getMethod == "GET" && request.getPathInfo == "/ping") {
      response.setStatus(200)
      baseRequest.setHandled(true)
      val marathonId = sys.env.getOrElse("MARATHON_APP_ID", "NO_MARATHON_APP_ID_SET")
      response.getWriter.println(s"Pong $marathonId")
    } else {
      val res = result(pipeline(Get(url)), waitTime)
      println(s"AppMock[$appId $version]: current health is $res")
      response.setStatus(res.status.intValue)
      baseRequest.setHandled(true)
      response.getWriter.print(res.entity.asString)
    }
  }
}

object AppMock {
  def main(args: Array[String]): Unit = {
    val port = args(0).toInt
    val appId = args(1)
    val version = args(2)
    val url = args(3) + "/" + port
    new AppMock(appId, version, url).start(port)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:62,代码来源:AppMock.scala

示例4: probeForCycleClass

//设置package包名称以及导入依赖的类
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}

import javax.servlet.ServletContext

import nl.knaw.dans.lib.logging.DebugEnhancedLogging
import org.eclipse.jetty.ajp.Ajp13SocketConnector
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.ServletContextHandler
import org.scalatra._
import org.scalatra.servlet.ScalatraListener

import scala.util.Try

class ${javaName}Service(serverPort: Int, app: ${javaName}App) extends DebugEnhancedLogging {
  import logger._

  private val server = new Server(serverPort)
  private val context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS)
  context.addEventListener(new ScalatraListener() {
    override def probeForCycleClass(classLoader: ClassLoader): (String, LifeCycle) = {
      ("anonymous", new LifeCycle {
        override def init(context: ServletContext): Unit = {
          context.mount(new ${javaName}Servlet(app), "/")
        }
      })
    }
  })
  server.setHandler(context)
  info(s"HTTP port is ${symbol_dollar}{serverPort}")

  def start(): Try[Unit] = Try {
    info("Starting service...")
    server.start()
  }

  def stop(): Try[Unit] = Try {
    info("Stopping service...")
    server.stop()
  }

  def destroy(): Try[Unit] = Try {
    server.destroy()
    app.close()
  }
} 
开发者ID:DANS-KNAW,项目名称:easy-module-archetype,代码行数:49,代码来源:__javaName__Service.scala

示例5: Web

//设置package包名称以及导入依赖的类
import java.io.File
import java.util
import java.util.Locale
import javax.servlet.DispatcherType

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.FilterHolder
import org.eclipse.jetty.util.resource.{Resource, ResourceCollection}
import org.eclipse.jetty.webapp.WebAppContext
import refpay.RefPayPlan
import unfiltered.filter.Plan

import scala.util.Properties

object Web extends App{


  Locale.setDefault(new Locale("no_NO"))

  val port = Properties.envOrElse("PORT", "9998").toInt

  val resources = new ResourceCollection(
    Resource.newResource(new File("src/main/webapp"))
  )
  val server = new Server(port)
  val context = new WebAppContext()
//  context.setContextPath("/api")
  context.setBaseResource(resources)
  registerPlan(new RefPayPlan, "Dommerbetaling", context)

  server.setHandler(context)
  server.setSendDateHeader(true)
  server.setStopAtShutdown(true)
  server.start()


  def registerPlan(plan: Plan, name: String, context: WebAppContext) {
    val holder = new FilterHolder(plan)
    holder.setName(name)
    context.addFilter(holder, "/*",  util.EnumSet.of(DispatcherType.REQUEST,DispatcherType.ASYNC,DispatcherType.ERROR,DispatcherType.FORWARD,DispatcherType.INCLUDE))
  }
} 
开发者ID:magott,项目名称:refpay,代码行数:43,代码来源:Web.scala

示例6: Param

//设置package包名称以及导入依赖的类
package org.cddcore.website

import javax.servlet.http.{HttpServletRequest, HttpServletResponse}

import org.cddcore.engine.Engine
import org.cddcore.rendering.{RenderConfiguration, RenderContext, Renderer, WebsiteUrlManipulators}
import org.eclipse.jetty.server.handler.AbstractHandler
import org.eclipse.jetty.server.{Handler, Request, Server}

case class Param(name: String, valueAsString: String, value: Any)

object WebServer {
  def defaultPort = {
    val portString = System.getenv("PORT")
    println("PortString[" + portString + "]")
    val port = portString match {
      case null => 8080;
      case _ => portString.toInt
    }
    println("Port[" + port + "]")
    port
  }

  def resourceHandlers = List(new ResourcesHandler("/images"), new ResourcesHandler("/stylesheets"))

  def defaultPathHandlers = List(new FavIconHandler, new RootPathHandler, new EngineComponentPathHandler)

  def apply(engines: List[Engine[_, _]], title: String = "Engines and Documents", port: Int = defaultPort, handlers: List[PathHandler] = defaultPathHandlers)(implicit renderConfiguration: RenderConfiguration) =
    new WebServer(port, new AggregateHandler(title, engines, resourceHandlers, handlers)(renderConfiguration.copy(urlBase = "/", urlManipulations = new WebsiteUrlManipulators)))

  //  def withPreHandlers(port: Int, engines: List[Engine], preHandlers: CddPathHandler*)(implicit ldp: CddDisplayProcessor): WebServer =
  //    new WebServer(port, new CddHandler("Engines and Documents", engines, preHandlers.toList ::: defaultPathHandlers)(ldp))
  //
  //  def defaultCddHandler(engines: List[Engine])(implicit ldp: CddDisplayProcessor) = new CddHandler("Engines and Documents", engines, defaultPathHandlers)(ldp)

}

class WebServer(val port: Int, val handler: Handler) {

  val server = new Server(port);
  server.setHandler(handler)

  def launch {
    start;
    server.join
  }

  def start = server.start

  def stop = server.stop
} 
开发者ID:phil-rice,项目名称:CddCore2,代码行数:52,代码来源:WebServer.scala

示例7: doStart

//设置package包名称以及导入依赖的类
package com.ftchinese.jobs.common

import org.eclipse.jetty.server.handler.gzip.GzipHandler
import org.eclipse.jetty.server.handler.{ContextHandler, ContextHandlerCollection}
import org.eclipse.jetty.server.{Server, ServerConnector}

import scala.collection.mutable.ArrayBuffer


    private def doStart(): Unit ={

        // The server
        _server = new Server()

        val connector = new ServerConnector(_server)
        connector.setHost(conf.serverHost)
        connector.setPort(_port)

        _server.addConnector(connector)

        // Set handlers
        if(_handlers.size > 0) {
            val collection = new ContextHandlerCollection

            val gzipHandlers = _handlers.map(h => {
                val gzipHandler = new GzipHandler
                gzipHandler.setHandler(h)
                gzipHandler
            })

            collection.setHandlers(gzipHandlers.toArray)

            _server.setHandler(collection)
        }

        // Start the server
        _server.start()
        _server.join()
    }

    def attachHandler(handler: ContextHandler): Unit ={
        _handlers += handler
    }

    def stop(): Unit ={
        if(_server == null)
            throw new Exception("Server is already stopped.")
        else {
            _server.stop()
            _server = null
        }
    }
} 
开发者ID:FTChinese,项目名称:push,代码行数:54,代码来源:HttpServer.scala

示例8: AdminHttpServer

//设置package包名称以及导入依赖的类
package com.pagerduty.scheduler.admin.http.standalone

import com.pagerduty.scheduler.admin.AdminService
import com.pagerduty.scheduler.admin.http.Settings
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.DefaultServlet
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener


class AdminHttpServer(settings: Settings, adminService: AdminService) {

  import AdminHttpServer._

  val ScalatraBootstrapClass = "com.pagerduty.scheduler.admin.http.standalone.ScalatraBootstrap"

  private val server = new Server(settings.httpPort)

  def start(): Unit = {
    val context = new WebAppContext()
    context.setContextPath("/")
    context.setResourceBase("/dev/null") // don't have any static resources to serve
    context.setInitParameter(ScalatraListener.LifeCycleKey, ScalatraBootstrapClass)
    context.setAttribute(AdminServiceAttributeKey, adminService)
    context.setAttribute(SettingsAttributeKey, settings)
    context.addEventListener(new ScalatraListener)
    context.addServlet(classOf[DefaultServlet], "/")

    server.setHandler(context)

    server.start
  }

  def running: Boolean = server.isRunning

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

object AdminHttpServer {
  val AdminServiceAttributeKey = "adminService"
  val SettingsAttributeKey = "settings"
} 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:45,代码来源:AdminHttpServer.scala

示例9: EmbeddedSchemaRegistry

//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.example

import java.util.Properties

import io.confluent.kafka.schemaregistry.rest.{SchemaRegistryConfig, SchemaRegistryRestApplication}
import net.manub.embeddedkafka.EmbeddedKafkaConfig
import org.eclipse.jetty.server.Server

object EmbeddedSchemaRegistry {
  private var serverMaybe: Option[Server] = None
  def start()(implicit config: EmbeddedKafkaConfig): Unit = {
    val props = new Properties()

    props.setProperty("kafkastore.connection.url", s"localhost:${config.zooKeeperPort}")
    val schemaRegistryConfig = new SchemaRegistryConfig(props)
    val app                  = new SchemaRegistryRestApplication(schemaRegistryConfig)
    val server: Server       = app.createServer
    server.start()
    serverMaybe = Some(server)
  }

  def stop() = {
    serverMaybe.foreach(_.stop())
  }
} 
开发者ID:ovotech,项目名称:comms-example-trigger,代码行数:26,代码来源:EmbeddedSchemaRegistry.scala

示例10: StaticServer

//设置package包名称以及导入依赖的类
package com.appliedscala.generator

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.handler.{DefaultHandler, HandlerList, ResourceHandler}
import org.slf4j.LoggerFactory


case class StaticServer(path: String, port: Int, fakeServer: Boolean) {
  val logger = LoggerFactory.getLogger("S2HttpServer")
  val server = {
    if (fakeServer) {
      None
    } else {
      logger.info(s"Starting the HTTP server")
      val jettyServer = new Server(port)
      val resource_handler = new ResourceHandler()
      resource_handler.setWelcomeFiles(Array("index.html"))
      resource_handler.setResourceBase(path)
      resource_handler.setDirectoriesListed(true)
      val handlers = new HandlerList()
      handlers.setHandlers(Array(resource_handler, new DefaultHandler()))
      jettyServer.setHandler(handlers)
      Some(jettyServer)
    }

  }

  def start(): Unit = {
    try {
      server.foreach {
        s => s.start()
        logger.info(s"The HTTP server has been started on port $port")
      }
    } catch {
    case e: Exception =>
      logger.error("Error occurred while trying to start the HTTP server", e)
    }
  }

  def stop(): Unit = {
    try {
      server.foreach { s =>
        s.stop()
        logger.info("The HTTP server has been stopped")
      }
    } catch {
      case e: Exception =>
        logger.error("Error occurred while trying to stop the HTTP server", e)
    }
  }
} 
开发者ID:denisftw,项目名称:s2gen,代码行数:52,代码来源:StaticServer.scala

示例11: JettyLauncher

//设置package包名称以及导入依赖的类
package com.github.twinra.lendmanager

import com.github.twinra.lendmanager.rest.ScalatraBootstrap
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.LazyLogging
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.DefaultServlet
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener


object JettyLauncher extends LazyLogging {
  def main(args: Array[String]): Unit = {
    val cfg = ConfigFactory.load("application.conf")
    val server = new Server(cfg.getInt("cfg.http.port"))

    val handler = new WebAppContext("src/main/webapp", "/") {
      addEventListener(new ScalatraListener)
      setInitParameter(ScalatraListener.LifeCycleKey, classOf[ScalatraBootstrap].getCanonicalName)
      addServlet(classOf[DefaultServlet], "/")
    }

    server.setHandler(handler)
    server.start()
    server.join()
  }
} 
开发者ID:twinra,项目名称:lending-manager,代码行数:28,代码来源:JettyLauncher.scala

示例12: RackServer

//设置package包名称以及导入依赖的类
package coder36.rack

import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import com.typesafe.scalalogging.LazyLogging
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.{ServletContextHandler, ServletHolder}

import scala.collection.mutable.Map

class RackServer extends LazyLogging {

  val port : Int = 8080
  var path : String = ""

  val apps = scala.collection.mutable.Map[String,RackServlet]()

  def map(path: String) : RackServer = {
    this.path = path
    this
  }

  def onto(rack: Rack) = {
    apps(path) = new RackServlet(rack, path)
  }

  def start() : RackServer = {
    val context = new ServletContextHandler(ServletContextHandler.SESSIONS)
    context.setContextPath("/")
    val server = new Server(port)
    server.setHandler(context)
    apps.foreach( app => context.addServlet(new ServletHolder(app._2), (app._1 + "/*").replaceAll("//", "/")) )
    println(s"\u001B[34mRack started... listening for HTTP on /0.0.0.0:${port}")
    server.start
    this
  }

}

class RackServlet(val rack: Rack, val path: String)  extends HttpServlet {

  override def service(request: HttpServletRequest, response: HttpServletResponse) {
    val res = Middleware.BaseRack( rack, request, response ).call(Map('base_path -> path))
    val status = res._1
    val headers = res._2
    val body = res._3
    response.setStatus(status)
    headers.foreach( (h) => response.addHeader(h._1, h._2))
    if( body != null ) response.getWriter().write(body)
  }
} 
开发者ID:coder36,项目名称:scalarack,代码行数:52,代码来源:Rackup.scala

示例13: FileUploadServerMain

//设置package包名称以及导入依赖的类
package jp.seraphr.fileupload.main

import org.eclipse.jetty.server.{ Handler, Server }
import org.eclipse.jetty.server.handler.{ DefaultHandler, HandlerList, ResourceHandler }
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener


object FileUploadServerMain extends App {
  val tPort = 8080

  val tServer = new Server(tPort)
  val tContext = new WebAppContext()
  tContext.setContextPath("/")
  tContext.setResourceBase("src/main/webapp")
  tContext.addEventListener(new ScalatraListener)
  tContext.setInitParameter(ScalatraListener.LifeCycleKey, classOf[ScalatraBootstrap].getName)

  val tResourceHandler = new ResourceHandler()
  tResourceHandler.setDirectoriesListed(true)
  tResourceHandler.setWelcomeFiles(Array("index.html"))
  //  tResourceHandler.setResourceBase("..")
  tResourceHandler.setResourceBase("../webapp/assets/")

  val tHandlers = new HandlerList()
  tHandlers.setHandlers(Array[Handler](tResourceHandler, tContext, new DefaultHandler()))
  tServer.setHandler(tHandlers)

  tServer.start()
  tServer.join()
} 
开发者ID:seraphr,项目名称:scalatra-reactjs-fileupload,代码行数:32,代码来源:FileuploadServerMain.scala

示例14: EmbeddedKafkaSchemaRegistry

//设置package包名称以及导入依赖的类
package nl.bigdatarepublic.streaming.embedded.adapter.kafka.registry

import java.util.Properties

import com.typesafe.scalalogging.LazyLogging
import io.confluent.kafka.schemaregistry.rest.{SchemaRegistryConfig, SchemaRegistryRestApplication}
import nl.bigdatarepublic.streaming.embedded.entity.EmbeddedService
import org.eclipse.jetty.server.Server

import scala.collection.JavaConverters._
import scala.util.{Failure, Success, Try}

class EmbeddedKafkaSchemaRegistry(props: Map[String, String]) extends EmbeddedService with LazyLogging {


  val app = new SchemaRegistryRestApplication(new SchemaRegistryConfig(props.asJava))
  var server : Server = _

  def start(): Unit = {

    Try({
      logger.info("Starting embedded KafkaSchemaRegistry...")
      // Only create server here instead of constructor, because it is initializing stuff already.
      server = app.createServer()
      server.start()
    }) match {
      case Success(_) => logger.info("Successfully started KafkaSchemaRegistry")
      case Failure(e) => logger.error("Failed to start KafkaSchemaRegistry", e)
    }
  }

  def stop(): Unit = {
    Try({
      logger.info("Stopping embedded KafkaSchemaRegistry...")
      // Only create server here instead of constructor, because it is initializing stuff already.
      server.stop()
    }) match {
      case Success(_) => logger.info("Successfully stopped KafkaSchemaRegistry")
      case Failure(e) => logger.error("Failed to stop KafkaSchemaRegistry", e)
    }


  }

}

object EmbeddedKafkaSchemaRegistry {

  def apply(props: Map[String, String]): EmbeddedKafkaSchemaRegistry = new EmbeddedKafkaSchemaRegistry(props)

  // Java compatibility
  def apply(props: Properties): EmbeddedKafkaSchemaRegistry = new EmbeddedKafkaSchemaRegistry(props.asScala.toMap)
} 
开发者ID:BigDataRepublic,项目名称:bdr-engineering-stack,代码行数:54,代码来源:EmbeddedKafkaSchemaRegistry.scala

示例15: Jetty

//设置package包名称以及导入依赖的类
// http://scalatra.org//guides/2.5/deployment/standalone.
package com.eddsteel.feedfilter.net

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

object Jetty {
  def main(args: Array[String]): Unit = {
    val port = Option(System.getenv("PORT")).map(_.toInt).getOrElse(8080)
    val server = new Server(port)
    val context = {
      val ctx = new WebAppContext()
      ctx.setContextPath("/")
      ctx.setResourceBase("src/main/resources")
      ctx.setResourceBase(getClass.getClassLoader.getResource("WEB-INF").toExternalForm)
      ctx.setInitParameter(
        ScalatraListener.LifeCycleKey,
        "com.eddsteel.feedfilter.net.ScalatraBootstrap")
      ctx.addEventListener(new ScalatraListener)
      ctx.addServlet(classOf[DefaultServlet], "/")
      ctx
    }
    server.setHandler(context)

    server.start
    server.join
  }
} 
开发者ID:eddsteel,项目名称:feed-filter,代码行数:31,代码来源:Jetty.scala


注:本文中的org.eclipse.jetty.server.Server类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。