java.nio.channels.ServerSocketChannel Scala Examples

The following examples show how to use java.nio.channels.ServerSocketChannel. 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: RandomPortUtil.scala    From akka-persistence-dynamodb   with Apache License 2.0 5 votes vote down vote up
package com.github.j5ik2o.akka.persistence.dynamodb.utils

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel

trait RandomPortUtil {

  def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
    val serverSocket = ServerSocketChannel.open()
    try {
      serverSocket.socket.bind(new InetSocketAddress(interface, 0))
      val port = serverSocket.socket.getLocalPort
      new InetSocketAddress(interface, port)
    } finally serverSocket.close()
  }

  def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (String, Int) = {
    val socketAddress = temporaryServerAddress(interface)
    socketAddress.getHostName -> socketAddress.getPort
  }

  def temporaryServerPort(interface: String = "127.0.0.1"): Int =
    temporaryServerHostnameAndPort(interface)._2
}

object RandomPortUtil extends RandomPortUtil 
Example 2
Source File: package.scala    From drunk   with Apache License 2.0 5 votes vote down vote up
package com.github.jarlakxen

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel

import scala.concurrent._
import scala.concurrent.duration._

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import akka.testkit._

import org.scalatest.BeforeAndAfterAll

package object drunk {

  trait TestHttpServer extends BeforeAndAfterAll {
    this: Spec =>

    implicit val system: ActorSystem = ActorSystem("drunk-test")
    implicit def executor = system.dispatcher
    implicit val materializer = ActorMaterializer()

    private def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
      val serverSocket = ServerSocketChannel.open()
      try {
        serverSocket.socket.bind(new InetSocketAddress(interface, 0))
        val port = serverSocket.socket.getLocalPort
        new InetSocketAddress(interface, port)
      } finally serverSocket.close()
    }

    private def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (String, Int) = {
      val socketAddress = temporaryServerAddress(interface)
      (socketAddress.getHostName, socketAddress.getPort)
    }

    val (host, port) = temporaryServerHostnameAndPort()

    override protected def beforeAll(): Unit =
      Http().bindAndHandle(serverRoutes, host, port).futureValue

    override protected def afterAll(): Unit =
      TestKit.shutdownActorSystem(system)

    def serverRoutes: Route
  }

} 
Example 3
Source File: ResourceManagerLinkIT.scala    From sparta   with Apache License 2.0 5 votes vote down vote up
package com.stratio.sparta.serving.core.helpers

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel

import com.stratio.sparta.serving.core.config.SpartaConfig
import com.typesafe.config.ConfigFactory
import org.junit.runner.RunWith
import org.scalatest._
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class ResourceManagerLinkIT extends FlatSpec with
  ShouldMatchers with Matchers with BeforeAndAfter {

  var serverSocket: ServerSocketChannel = _
  val sparkUIPort = 4040
  val mesosPort = 5050
  val localhost = "127.0.0.1"

  after {
    serverSocket.close()
  }

  it should "return local Spark UI link" in {
    serverSocket = ServerSocketChannel.open()
    val localhostName = java.net.InetAddress.getLocalHost().getHostName()
    serverSocket.socket.bind(new InetSocketAddress(localhostName, sparkUIPort))
    val config = ConfigFactory.parseString(
      """
        |sparta{
        |  config {
        |    executionMode = local
        |  }
        |}
      """.stripMargin)
    SpartaConfig.initMainConfig(Option(config))
    ResourceManagerLinkHelper.getLink("local") should be(Some(s"http://${localhostName}:${sparkUIPort}"))
  }

  it should "return Mesos UI link" in {
    serverSocket = ServerSocketChannel.open()
    serverSocket.socket.bind(new InetSocketAddress(localhost,mesosPort))
    val config = ConfigFactory.parseString(
      """
        |sparta{
        |  config {
        |    executionMode = mesos
        |  }
        |
        |  mesos {
        |    master = "mesos://127.0.0.1:7077"
        |  }
        |}
      """.stripMargin)
    SpartaConfig.initMainConfig(Option(config))
    ResourceManagerLinkHelper.getLink("mesos") should be(Some(s"http://$localhost:$mesosPort"))
  }

} 
Example 4
Source File: SystemBuilder.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.sourcing.projections

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel

import akka.actor.ActorSystem
import akka.persistence.cassandra.testkit.CassandraLauncher
import com.typesafe.config.ConfigFactory


  final def cluster(name: String): ActorSystem = {
    val cassandra = CassandraLauncher.randomPort
    val remote    = freePort()
    val config    = ConfigFactory
      .parseString(s"""
         |test.cassandra-port = $cassandra
         |test.remote-port = $remote
       """.stripMargin)
      .withFallback(ConfigFactory.parseResources("cluster.conf"))
      .withFallback(ConfigFactory.parseResources("cassandra.conf"))
      .withFallback(ConfigFactory.load())
      .resolve()
    ActorSystem(name, config)
  }
} 
Example 5
Source File: RandomPortSupport.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.repository.util

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel


trait RandomPortSupport {

  def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
    val serverSocket = ServerSocketChannel.open()
    try {
      serverSocket.socket.bind(new InetSocketAddress(interface, 0))
      val port = serverSocket.socket.getLocalPort
      new InetSocketAddress(interface, port)
    } finally serverSocket.close()
  }

  def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (String, Int) = {
    val socketAddress = temporaryServerAddress(interface)
    socketAddress.getHostName -> socketAddress.getPort
  }

  def temporaryServerPort(interface: String = "127.0.0.1"): Int =
    temporaryServerHostnameAndPort(interface)._2
} 
Example 6
Source File: Utils.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel

import sbt._

object Utils {

  implicit class SbtLoggerOps(val self: sbt.Logger) extends AnyVal {

    def toScalaProcessLogger: scala.sys.process.ProcessLogger = new scala.sys.process.ProcessLogger {
      private val _log                     = new FullLogger(self)
      override def out(s: => String): Unit = _log.info(s)

      override def err(s: => String): Unit = _log.err(s)

      override def buffer[T](f: => T): T = _log.buffer(f)
    }
  }

  object RandomPortSupport {

    def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
      val serverSocket = ServerSocketChannel.open()
      try {
        serverSocket.socket.bind(new InetSocketAddress(interface, 0))
        val port = serverSocket.socket.getLocalPort
        new InetSocketAddress(interface, port)
      } finally serverSocket.close()
    }

    def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (String, Int) = {
      val socketAddress = temporaryServerAddress(interface)
      socketAddress.getHostName -> socketAddress.getPort
    }

    def temporaryServerPort(interface: String = "127.0.0.1"): Int =
      temporaryServerHostnameAndPort(interface)._2
  }

} 
Example 7
Source File: RandomPortSupport.scala    From reactive-aws-clients   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.reactive.aws.kinesis.test

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel


trait RandomPortSupport {

  def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
    val serverSocket = ServerSocketChannel.open()
    try {
      serverSocket.socket.bind(new InetSocketAddress(interface, 0))
      val port = serverSocket.socket.getLocalPort
      new InetSocketAddress(interface, port)
    } finally serverSocket.close()
  }

  def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (String, Int) = {
    val socketAddress = temporaryServerAddress(interface)
    socketAddress.getHostName -> socketAddress.getPort
  }

  def temporaryServerPort(interface: String = "127.0.0.1"): Int =
    temporaryServerHostnameAndPort(interface)._2
}

object RandomPortSupport extends RandomPortSupport 
Example 8
Source File: RandomPortSupport.scala    From reactive-aws-clients   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.reactive.aws.test

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel


trait RandomPortSupport {

  def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
    val serverSocket = ServerSocketChannel.open()
    try {
      serverSocket.socket.bind(new InetSocketAddress(interface, 0))
      val port = serverSocket.socket.getLocalPort
      new InetSocketAddress(interface, port)
    } finally serverSocket.close()
  }

  def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (String, Int) = {
    val socketAddress = temporaryServerAddress(interface)
    socketAddress.getHostName -> socketAddress.getPort
  }

  def temporaryServerPort(interface: String = "127.0.0.1"): Int =
    temporaryServerHostnameAndPort(interface)._2
} 
Example 9
Source File: EmbeddedConfluentRegistry.scala    From affinity   with Apache License 2.0 5 votes vote down vote up
package io.amient.affinity.kafka

import java.nio.channels.ServerSocketChannel
import java.util.Properties

import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient
import io.confluent.kafka.schemaregistry.rest.{SchemaRegistryConfig, SchemaRegistryRestApplication}
import org.scalatest.{BeforeAndAfterAll, Suite}
import org.slf4j.LoggerFactory

trait EmbeddedConfluentRegistry extends EmbeddedKafka with BeforeAndAfterAll {

  self: Suite =>

  private val log = LoggerFactory.getLogger(classOf[EmbeddedConfluentRegistry])

  private val registryConfig: SchemaRegistryConfig = new SchemaRegistryConfig(new Properties() {
    put("listeners", s"http://127.0.0.1:0")
    put("kafkastore.connection.url", zkConnect)
    put("avro.compatibility.level", "full")
    put("kafkastore.init.timeout.ms", "5000")
    put("kafkastore.topic", "_schemas")
    put("debug", "true")
  })
  private val app = new SchemaRegistryRestApplication(registryConfig)
  private val registry = app.createServer
  registry.start()

  val registryUrl = s"http://127.0.0.1:" + registry.getConnectors.head.getTransport.asInstanceOf[ServerSocketChannel].socket.getLocalPort
  log.info("Confluent schema registry listening at: " + registryUrl)
  val registryClient = new CachedSchemaRegistryClient(registryUrl, 20)

  abstract override def afterAll() = try {
    registry.stop()
  } finally {
    super.afterAll()
  }

} 
Example 10
Source File: package.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.util.ByteString

import scala.concurrent.Future

package object unicomplex {

  // Remove this once Akka-Http exposes this test utility.
  def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
    val serverSocket = ServerSocketChannel.open()
    try {
      serverSocket.socket.bind(new InetSocketAddress(interface, 0))
      val port = serverSocket.socket.getLocalPort
      new InetSocketAddress(interface, port)
    } finally serverSocket.close()
  }

  def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (InetSocketAddress, String, Int) = {
    val socketAddress = temporaryServerAddress(interface)
    (socketAddress, socketAddress.getHostName, socketAddress.getPort)
  }

  def extractEntityAsString(response: HttpResponse)
                           (implicit am: ActorMaterializer, system: ActorSystem): Future[String] = {
    import system.dispatcher
    response.entity.dataBytes.runFold(ByteString(""))(_ ++ _) map(_.utf8String)
  }

  def entityAsString(uri: String)(implicit am: ActorMaterializer, system: ActorSystem): Future[String] = {
    import system.dispatcher
    get(uri) flatMap extractEntityAsString
  }

  def entityAsStringWithHeaders(uri: String)(implicit am: ActorMaterializer, system: ActorSystem): Future[(String, Seq[HttpHeader])] = {
    import system.dispatcher
    get(uri) flatMap( response => extractEntityAsString(response) map((_, response.headers)))
  }

  def entityAsInt(uri: String)(implicit am: ActorMaterializer, system: ActorSystem): Future[Int] = {
    import system.dispatcher
    entityAsString(uri) map (s => s.toInt)
  }

  def get(uri: String)(implicit am: ActorMaterializer, system: ActorSystem): Future[HttpResponse] = {
    Http().singleRequest(HttpRequest(uri = Uri(uri)))
  }

  def post(uri: String, e: RequestEntity)(implicit am: ActorMaterializer, system: ActorSystem): Future[HttpResponse] = {
    Http().singleRequest(HttpRequest(method = HttpMethods.POST, uri = Uri(uri), entity = e))
  }

  def put(uri: String)(implicit am: ActorMaterializer, system: ActorSystem): Future[HttpResponse] = {
    Http().singleRequest(HttpRequest(method = HttpMethods.PUT, uri = Uri(uri)))
  }
} 
Example 11
Source File: Utils.scala    From akka-ddd-cqrs-es-example   with MIT License 5 votes vote down vote up
object Utils {
  import java.net.InetSocketAddress
  import java.nio.channels.ServerSocketChannel

  
  trait RandomPortSupport {

    def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
      val serverSocket = ServerSocketChannel.open()
      try {
        serverSocket.socket.bind(new InetSocketAddress(interface, 0))
        val port = serverSocket.socket.getLocalPort
        new InetSocketAddress(interface, port)
      } finally serverSocket.close()
    }

    def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (String, Int) = {
      val socketAddress = temporaryServerAddress(interface)
      socketAddress.getHostName -> socketAddress.getPort
    }

    def temporaryServerPort(interface: String = "127.0.0.1"): Int =
      temporaryServerHostnameAndPort(interface)._2
  }

  object RandomPortSupport extends RandomPortSupport

} 
Example 12
Source File: RandomPortSupport.scala    From akka-ddd-cqrs-es-example   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.bank.adaptor.util

import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel


trait RandomPortSupport {

  def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
    val serverSocket = ServerSocketChannel.open()
    try {
      serverSocket.socket.bind(new InetSocketAddress(interface, 0))
      val port = serverSocket.socket.getLocalPort
      new InetSocketAddress(interface, port)
    } finally serverSocket.close()
  }

  def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (String, Int) = {
    val socketAddress = temporaryServerAddress(interface)
    socketAddress.getHostName -> socketAddress.getPort
  }

  def temporaryServerPort(interface: String = "127.0.0.1"): Int =
    temporaryServerHostnameAndPort(interface)._2
}

object RandomPortSupport extends RandomPortSupport 
Example 13
Source File: TestUtils.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container


import java.net.InetSocketAddress
import java.nio.channels.ServerSocketChannel

object TestUtils {
  def temporaryServerAddress(interface: String = "127.0.0.1"): InetSocketAddress = {
    val serverSocket = ServerSocketChannel.open()
    try {
      serverSocket.socket.bind(new InetSocketAddress(interface, 0))
      val port = serverSocket.socket.getLocalPort
      new InetSocketAddress(interface, port)
    } finally serverSocket.close()
  }

  def temporaryServerHostnameAndPort(interface: String = "127.0.0.1"): (InetSocketAddress, String, Int) = {
    val socketAddress = temporaryServerAddress(interface)
    (socketAddress, socketAddress.getHostName, socketAddress.getPort)
  }
} 
Example 14
Source File: Main.scala    From spark-vector   with Apache License 2.0 5 votes vote down vote up
package com.actian.spark_vector.provider

import java.nio.channels.ServerSocketChannel

import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession

import resource.managed
import java.net.InetAddress

import com.actian.spark_vector.util.Logging

object Main extends App with Logging {
  import ProviderAuth._

  private val conf = new SparkConf()
    .setAppName("Spark-Vector external tables provider")
    .set("spark.task.maxFailures", "1")
    .set("spark.sql.caseSensitive", "false")
  logInfo(s"Starting Spark-Vector provider with config options: ${conf.getAll.toMap}")

  private var builder = SparkSession.builder.config(conf)
  if (conf.getBoolean("spark.vector.provider.hive", true)) {
    builder = builder.enableHiveSupport()
  }
  private val session = builder.getOrCreate()
  private lazy val handler = new RequestHandler(session, ProviderAuth(generateUsername, generatePassword))

  sys.addShutdownHook {
    session.close()
    logInfo("Shutting down Spark-Vector provider...")
  }
  for { server <- managed(ServerSocketChannel.open.bind(null)) } {
    logInfo(s"Spark-Vector provider initialized and starting listening for requests on port ${server.socket.getLocalPort}")
    println(s"vector_provider_hostname=${InetAddress.getLocalHost.getHostName}")
    println(s"vector_provider_port=${server.socket.getLocalPort}")
    println(s"vector_provider_username=${handler.auth.username}")
    println(s"vector_provider_password=${handler.auth.password}")
    while (true) handler.handle(server.accept)
  }
}