java.net.URISyntaxException Scala Examples

The following examples show how to use java.net.URISyntaxException. 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: ClientArguments.scala    From multi-tenancy-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy

import java.net.{URI, URISyntaxException}

import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

import org.apache.log4j.Level

import org.apache.spark.util.{IntParam, MemoryParam, Utils}


  private def printUsageAndExit(exitCode: Int) {
    // TODO: It wouldn't be too hard to allow users to submit their app and dependency jars
    //       separately similar to in the YARN client.
    val usage =
     s"""
      |Usage: DriverClient [options] launch <active-master> <jar-url> <main-class> [driver options]
      |Usage: DriverClient kill <active-master> <driver-id>
      |
      |Options:
      |   -c CORES, --cores CORES        Number of cores to request (default: $DEFAULT_CORES)
      |   -m MEMORY, --memory MEMORY     Megabytes of memory to request (default: $DEFAULT_MEMORY)
      |   -s, --supervise                Whether to restart the driver on failure
      |                                  (default: $DEFAULT_SUPERVISE)
      |   -v, --verbose                  Print more debugging output
     """.stripMargin
    // scalastyle:off println
    System.err.println(usage)
    // scalastyle:on println
    System.exit(exitCode)
  }
}

private[deploy] object ClientArguments {
  val DEFAULT_CORES = 1
  val DEFAULT_MEMORY = Utils.DEFAULT_DRIVER_MEM_MB // MB
  val DEFAULT_SUPERVISE = false

  def isValidJarUrl(s: String): Boolean = {
    try {
      val uri = new URI(s)
      uri.getScheme != null && uri.getPath != null && uri.getPath.endsWith(".jar")
    } catch {
      case _: URISyntaxException => false
    }
  }
} 
Example 2
Source File: Url.scala    From paradox   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.paradox.markdown

import java.net.{ URI, URISyntaxException }


  case class Error(reason: String) extends RuntimeException(reason)

  def apply(base: String): Url = {
    parse(base, s"template resulted in an invalid URL [$base]")
  }

  def parse(base: String, msg: String): Url = {
    try Url(new URI(base)) catch {
      case e: URISyntaxException =>
        throw Url.Error(msg)
    }
  }
}

case class PropertyUrl(property: String, variables: String => Option[String]) {
  def base = variables(property) match {
    case Some(baseUrl) => baseUrl
    case None          => throw Url.Error(s"property [$property] is not defined")
  }

  def resolve(): Url = {
    Url.parse(base, s"property [$property] contains an invalid URL [$base]")
  }

  def format(args: String*) = Url(base.format(args: _*))

  def collect(f: PartialFunction[String, String]): Url = {
    PropertyUrl(property, variables(_).collect(f)).resolve
  }
} 
Example 3
Source File: ClientArguments.scala    From BigDatalog   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy

import java.net.{URI, URISyntaxException}

import scala.collection.mutable.ListBuffer

import org.apache.log4j.Level
import org.apache.spark.util.{IntParam, MemoryParam, Utils}


  private def printUsageAndExit(exitCode: Int) {
    // TODO: It wouldn't be too hard to allow users to submit their app and dependency jars
    //       separately similar to in the YARN client.
    val usage =
     s"""
      |Usage: DriverClient [options] launch <active-master> <jar-url> <main-class> [driver options]
      |Usage: DriverClient kill <active-master> <driver-id>
      |
      |Options:
      |   -c CORES, --cores CORES        Number of cores to request (default: $DEFAULT_CORES)
      |   -m MEMORY, --memory MEMORY     Megabytes of memory to request (default: $DEFAULT_MEMORY)
      |   -s, --supervise                Whether to restart the driver on failure
      |                                  (default: $DEFAULT_SUPERVISE)
      |   -v, --verbose                  Print more debugging output
     """.stripMargin
    // scalastyle:off println
    System.err.println(usage)
    // scalastyle:on println
    System.exit(exitCode)
  }
}

private[deploy] object ClientArguments {
  val DEFAULT_CORES = 1
  val DEFAULT_MEMORY = Utils.DEFAULT_DRIVER_MEM_MB // MB
  val DEFAULT_SUPERVISE = false

  def isValidJarUrl(s: String): Boolean = {
    try {
      val uri = new URI(s)
      uri.getScheme != null && uri.getPath != null && uri.getPath.endsWith(".jar")
    } catch {
      case _: URISyntaxException => false
    }
  }
} 
Example 4
Source File: S3DataPathTests.scala    From sagemaker-spark   with Apache License 2.0 5 votes vote down vote up
package com.amazonaws.services.sagemaker.sparksdk

import java.net.URISyntaxException

import org.scalatest.FlatSpec

class S3DataPathTests extends FlatSpec {

  "S3DataPath" should "create correct S3 URI string" in {
    val generatedUriString = new S3DataPath("my-bucket", "my-object").toS3UriString
    assert(generatedUriString == "s3://my-bucket/my-object")
  }

  it should "fail on load from invalid uri string" in {
    intercept[IllegalArgumentException] {
      S3DataPath.fromS3URI("http://not-an-s3-uri")
    }
    intercept[URISyntaxException] {
      S3DataPath.fromS3URI("You know nothing about URIs, John Snow")
    }
  }
} 
Example 5
Source File: ClientArguments.scala    From Spark-2.3.1   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy

import java.net.{URI, URISyntaxException}

import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

import org.apache.log4j.Level

import org.apache.spark.util.{IntParam, MemoryParam, Utils}


  private def printUsageAndExit(exitCode: Int) {
    // TODO: It wouldn't be too hard to allow users to submit their app and dependency jars
    //       separately similar to in the YARN client.
    val usage =
     s"""
      |Usage: DriverClient [options] launch <active-master> <jar-url> <main-class> [driver options]
      |Usage: DriverClient kill <active-master> <driver-id>
      |
      |Options:
      |   -c CORES, --cores CORES        Number of cores to request (default: $DEFAULT_CORES)
      |   -m MEMORY, --memory MEMORY     Megabytes of memory to request (default: $DEFAULT_MEMORY)
      |   -s, --supervise                Whether to restart the driver on failure
      |                                  (default: $DEFAULT_SUPERVISE)
      |   -v, --verbose                  Print more debugging output
     """.stripMargin
    // scalastyle:off println
    System.err.println(usage)
    // scalastyle:on println
    System.exit(exitCode)
  }
}

private[deploy] object ClientArguments {
  val DEFAULT_CORES = 1
  val DEFAULT_MEMORY = Utils.DEFAULT_DRIVER_MEM_MB // MB
  val DEFAULT_SUPERVISE = false

  def isValidJarUrl(s: String): Boolean = {
    try {
      val uri = new URI(s)
      uri.getScheme != null && uri.getPath != null && uri.getPath.endsWith(".jar")
    } catch {
      case _: URISyntaxException => false
    }
  }
} 
Example 6
Source File: ClientArguments.scala    From spark1.52   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy

import java.net.{URI, URISyntaxException}

import scala.collection.mutable.ListBuffer

import org.apache.log4j.Level
import org.apache.spark.util.{IntParam, MemoryParam, Utils}


  private def printUsageAndExit(exitCode: Int) {
    // TODO: It wouldn't be too hard to allow users to submit their app and dependency jars
    //       separately similar to in the YARN client.
    val usage =
    s"""
       |Usage: DriverClient [options] launch <active-master> <jar-url> <main-class> [driver options]
       |Usage: DriverClient kill <active-master> <driver-id>
       |
      |Options:
       |   -c CORES, --cores CORES        Number of cores to request (default: $DEFAULT_CORES)
       |   -m MEMORY, --memory MEMORY     Megabytes of memory to request (default: $DEFAULT_MEMORY)
       |   -s, --supervise                Whether to restart the driver on failure
       |                                  (default: $DEFAULT_SUPERVISE)
       |   -v, --verbose                  Print more debugging output
     """.stripMargin
    // scalastyle:off println
    System.err.println(usage)
    // scalastyle:on println
    System.exit(exitCode)
  }
}

private[deploy] object ClientArguments {
  val DEFAULT_CORES = 1
  val DEFAULT_MEMORY = Utils.DEFAULT_DRIVER_MEM_MB // MB
  val DEFAULT_SUPERVISE = false

  def isValidJarUrl(s: String): Boolean = {
    try {
      val uri = new URI(s)
      uri.getScheme != null && uri.getPath != null && uri.getPath.endsWith(".jar")
    } catch {
      case _: URISyntaxException => false
    }
  }
} 
Example 7
Source File: GitUrlsParser.scala    From jgit-spark-connector   with Apache License 2.0 5 votes vote down vote up
package tech.sourced.engine.util

import java.net.{URI, URISyntaxException}

object GitUrlsParser {
  private val isGit = """(.+)\@(.+):(.+)\.git""".r

  
  def getIdFromUrls(urls: Array[String]): String = {
    urls.flatMap({
      case isGit(_, host, path, _*) =>
        Some(s"$host/$path")
      case s => try {
        val u: URI = new URI(s)
        Some(u.getHost + u.getPath)
      } catch {
        case _: URISyntaxException => None
      }
    }).distinct.min
  }

} 
Example 8
Source File: Utils.scala    From kyuubi   with Apache License 2.0 5 votes vote down vote up
package org.apache.kyuubi

import java.io.{File, InputStreamReader, IOException}
import java.net.{URI, URISyntaxException}
import java.nio.charset.StandardCharsets
import java.util.{Properties, UUID}

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

private[kyuubi] object Utils extends Logging {

  import org.apache.kyuubi.config.KyuubiConf._

  def strToSeq(s: String): Seq[String] = {
    require(s != null)
    s.split(",").map(_.trim).filter(_.nonEmpty)
  }

  def getSystemProperties: Map[String, String] = {
    sys.props.toMap
  }

  def getDefaultPropertiesFile(env: Map[String, String] = sys.env): Option[File] = {
    env.get(KYUUBI_CONF_DIR)
      .orElse(env.get(KYUUBI_HOME).map(_ + File.separator + "/conf"))
      .map( d => new File(d + File.separator + KYUUBI_CONF_FILE_NAME))
      .filter(f => f.exists() && f.isFile)
  }

  def getPropertiesFromFile(file: Option[File]): Map[String, String] = {
    file.map { f =>
      info(s"Loading Kyuubi properties from ${f.getAbsolutePath}")
      val reader = new InputStreamReader(f.toURI.toURL.openStream(), StandardCharsets.UTF_8)
      try {
        val properties = new Properties()
        properties.load(reader)
        properties.stringPropertyNames().asScala.map { k =>
          (k, properties.getProperty(k).trim)
        }.toMap
      } catch {
        case e: IOException =>
          throw new KyuubiException(
            s"Failed when loading Kyuubi properties from ${f.getAbsolutePath}", e)
      } finally {
        reader.close()
      }
    }.getOrElse(Map.empty)
  }


  
  def createTempDir(
      root: String = System.getProperty("java.io.tmpdir"),
      namePrefix: String = "kyuubi"): File = {
    val dir = createDirectory(root, namePrefix)
    dir.deleteOnExit()
    dir
  }

} 
Example 9
Source File: ClientArguments.scala    From iolap   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy

import java.net.{URI, URISyntaxException}

import scala.collection.mutable.ListBuffer

import org.apache.log4j.Level
import org.apache.spark.util.{IntParam, MemoryParam, Utils}


  private def printUsageAndExit(exitCode: Int) {
    // TODO: It wouldn't be too hard to allow users to submit their app and dependency jars
    //       separately similar to in the YARN client.
    val usage =
     s"""
      |Usage: DriverClient [options] launch <active-master> <jar-url> <main-class> [driver options]
      |Usage: DriverClient kill <active-master> <driver-id>
      |
      |Options:
      |   -c CORES, --cores CORES        Number of cores to request (default: $DEFAULT_CORES)
      |   -m MEMORY, --memory MEMORY     Megabytes of memory to request (default: $DEFAULT_MEMORY)
      |   -s, --supervise                Whether to restart the driver on failure
      |                                  (default: $DEFAULT_SUPERVISE)
      |   -v, --verbose                  Print more debugging output
     """.stripMargin
    System.err.println(usage)
    System.exit(exitCode)
  }
}

private[deploy] object ClientArguments {
  val DEFAULT_CORES = 1
  val DEFAULT_MEMORY = 512 // MB
  val DEFAULT_SUPERVISE = false

  def isValidJarUrl(s: String): Boolean = {
    try {
      val uri = new URI(s)
      uri.getScheme != null && uri.getPath != null && uri.getPath.endsWith(".jar")
    } catch {
      case _: URISyntaxException => false
    }
  }
} 
Example 10
Source File: ClientArguments.scala    From drizzle-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy

import java.net.{URI, URISyntaxException}

import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

import org.apache.log4j.Level

import org.apache.spark.util.{IntParam, MemoryParam, Utils}


  private def printUsageAndExit(exitCode: Int) {
    // TODO: It wouldn't be too hard to allow users to submit their app and dependency jars
    //       separately similar to in the YARN client.
    val usage =
     s"""
      |Usage: DriverClient [options] launch <active-master> <jar-url> <main-class> [driver options]
      |Usage: DriverClient kill <active-master> <driver-id>
      |
      |Options:
      |   -c CORES, --cores CORES        Number of cores to request (default: $DEFAULT_CORES)
      |   -m MEMORY, --memory MEMORY     Megabytes of memory to request (default: $DEFAULT_MEMORY)
      |   -s, --supervise                Whether to restart the driver on failure
      |                                  (default: $DEFAULT_SUPERVISE)
      |   -v, --verbose                  Print more debugging output
     """.stripMargin
    // scalastyle:off println
    System.err.println(usage)
    // scalastyle:on println
    System.exit(exitCode)
  }
}

private[deploy] object ClientArguments {
  val DEFAULT_CORES = 1
  val DEFAULT_MEMORY = Utils.DEFAULT_DRIVER_MEM_MB // MB
  val DEFAULT_SUPERVISE = false

  def isValidJarUrl(s: String): Boolean = {
    try {
      val uri = new URI(s)
      uri.getScheme != null && uri.getPath != null && uri.getPath.endsWith(".jar")
    } catch {
      case _: URISyntaxException => false
    }
  }
} 
Example 11
Source File: StringJvmTests.scala    From mouse   with MIT License 5 votes vote down vote up
package mouse

import java.net.{MalformedURLException, URI, URISyntaxException, URL}

import cats.Eq
import cats.syntax.all._
import mouse.string._

class StringJvmTests extends MouseSuite {

  test("parseFloat") {
    "123.1".parseFloat should ===(123.1f.asRight[NumberFormatException])
  }

  test("parseURL") {
    implicit val urlEq: Eq[URL] = Eq.fromUniversalEquals
    implicit val malformedURLExceptionEq: Eq[MalformedURLException] =
      new Eq[MalformedURLException] {
        override def eqv(x: MalformedURLException, y: MalformedURLException): Boolean =
          x.getMessage == y.getMessage
      }

    "http://example.com".parseURL should ===(new URL("http://example.com").asRight[MalformedURLException])

    "blah".parseURL should ===(new MalformedURLException("no protocol: blah").asLeft)
  }

  test("parseURI") {
    implicit val urlEq: Eq[URI] = Eq.fromUniversalEquals
    implicit val malformedURIExceptionEq: Eq[URISyntaxException] =
      new Eq[URISyntaxException] {
        override def eqv(x: URISyntaxException, y: URISyntaxException): Boolean =
          x.getMessage == y.getMessage
      }

    "http://example.com".parseURI should ===(new URI("http://example.com").asRight[URISyntaxException])

    "invalid uri".parseURI should ===(new URISyntaxException("invalid uri", "Illegal character in path at index 7").asLeft)
  }

} 
Example 12
Source File: TestQName.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.xml.test.unit

import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.Assert._
import org.apache.daffodil.xml.QNameRegex
import org.apache.daffodil.xml.QName
import org.apache.daffodil.xml.RefQName
import org.apache.daffodil.xml.NoNamespace
import scala.util.Success
import org.apache.daffodil.xml.UnspecifiedNamespace
import org.apache.daffodil.xml.ExtendedQNameSyntaxException
import scala.util.Failure
import java.net.URISyntaxException

class TestQName {

  @Test def testQNameLongPrefix(): Unit = {
    val bigPrefix = ("a" * 6000)
    val data = <xs:element name="one" type={ bigPrefix + ":b" }/>
    val qntext = (data \ "@type").text

    // println("length of type attribute = " + qntext.length)
    qntext match {
      case QNameRegex.QName(pre, local) => {
        // println(pre)
        // println(local)
        assertEquals(6001, pre.length + local.length)
      }
    }
  }

  @Test def testExtQName1(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("local")
    tryrqn match {
      case Success(RefQName(None, "local", UnspecifiedNamespace)) => // ok
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName2(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("{}local")
    tryrqn match {
      case Success(RefQName(None, "local", NoNamespace)) => // ok
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName3(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("{uri}local")
    tryrqn match {
      case Success(RefQName(None, "local", ns)) => assertEquals("uri", ns.uri.toString)
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName4(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("pre:local")
    tryrqn match {
      case Success(RefQName(Some("pre"), "local", UnspecifiedNamespace)) => //ok
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName5(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("pre:{}local")
    tryrqn match {
      case Failure(exc: ExtendedQNameSyntaxException) => // ok
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName6(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("{http://<<notValidURI>>}local")
    tryrqn match {
      case Failure(exc: ExtendedQNameSyntaxException) => {
        val c = exc.getCause()
        c match {
          case usex: URISyntaxException => // ok
          case _ => fail("Expected a URISyntaxException, but got " + c)
        }
      }
      case Failure(exc) => fail(exc.getMessage())
      case _ => fail(tryrqn.toString)
    }
  }

} 
Example 13
Source File: SerializedCpg.scala    From codepropertygraph   with Apache License 2.0 5 votes vote down vote up
package io.shiftleft

import java.io.{File, IOException}
import java.net.{URI, URISyntaxException}
import java.nio.file.{FileSystem, FileSystems, Files}
import java.util

import com.google.protobuf.GeneratedMessageV3

class SerializedCpg extends AutoCloseable {

  
  @throws[IOException]
  def addOverlay(overlay: GeneratedMessageV3, name: String): Unit = {
    if (!isEmpty) {
      val pathInZip = zipFileSystem.getPath(s"${counter}_${name}")
      counter += 1
      val outputStream = Files.newOutputStream(pathInZip)
      overlay.writeTo(outputStream)
      outputStream.close()
    }
  }

  @throws[IOException]
  def addOverlay(overlays: Iterator[GeneratedMessageV3], name: String): Unit = {
    overlays.zipWithIndex.foreach {
      case (overlay, i) => addOverlay(overlay, name + "_" + i)
    }
  }

  @throws[IOException]
  override def close(): Unit = {
    if (!isEmpty) {
      zipFileSystem.close()
    }
  }
} 
Example 14
Source File: ClientArguments.scala    From SparkCore   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy

import java.net.{URI, URISyntaxException}

import scala.collection.mutable.ListBuffer

import org.apache.log4j.Level

import org.apache.spark.util.{IntParam, MemoryParam}


  def printUsageAndExit(exitCode: Int) {
    // TODO: It wouldn't be too hard to allow users to submit their app and dependency jars
    //       separately similar to in the YARN client.
    val usage =
     s"""
      |Usage: DriverClient [options] launch <active-master> <jar-url> <main-class> [driver options]
      |Usage: DriverClient kill <active-master> <driver-id>
      |
      |Options:
      |   -c CORES, --cores CORES        Number of cores to request (default: $DEFAULT_CORES)
      |   -m MEMORY, --memory MEMORY     Megabytes of memory to request (default: $DEFAULT_MEMORY)
      |   -s, --supervise                Whether to restart the driver on failure
      |                                  (default: $DEFAULT_SUPERVISE)
      |   -v, --verbose                  Print more debugging output
     """.stripMargin
    System.err.println(usage)
    System.exit(exitCode)
  }
}

object ClientArguments {
  private[spark] val DEFAULT_CORES = 1
  private[spark] val DEFAULT_MEMORY = 512 // MB
  private[spark] val DEFAULT_SUPERVISE = false

  def isValidJarUrl(s: String): Boolean = {
    try {
      val uri = new URI(s)
      uri.getScheme != null && uri.getPath != null && uri.getPath.endsWith(".jar")
    } catch {
      case _: URISyntaxException => false
    }
  }
} 
Example 15
Source File: ClientArguments.scala    From sparkoscope   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy

import java.net.{URI, URISyntaxException}

import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

import org.apache.log4j.Level

import org.apache.spark.util.{IntParam, MemoryParam, Utils}


  private def printUsageAndExit(exitCode: Int) {
    // TODO: It wouldn't be too hard to allow users to submit their app and dependency jars
    //       separately similar to in the YARN client.
    val usage =
     s"""
      |Usage: DriverClient [options] launch <active-master> <jar-url> <main-class> [driver options]
      |Usage: DriverClient kill <active-master> <driver-id>
      |
      |Options:
      |   -c CORES, --cores CORES        Number of cores to request (default: $DEFAULT_CORES)
      |   -m MEMORY, --memory MEMORY     Megabytes of memory to request (default: $DEFAULT_MEMORY)
      |   -s, --supervise                Whether to restart the driver on failure
      |                                  (default: $DEFAULT_SUPERVISE)
      |   -v, --verbose                  Print more debugging output
     """.stripMargin
    // scalastyle:off println
    System.err.println(usage)
    // scalastyle:on println
    System.exit(exitCode)
  }
}

private[deploy] object ClientArguments {
  val DEFAULT_CORES = 1
  val DEFAULT_MEMORY = Utils.DEFAULT_DRIVER_MEM_MB // MB
  val DEFAULT_SUPERVISE = false

  def isValidJarUrl(s: String): Boolean = {
    try {
      val uri = new URI(s)
      uri.getScheme != null && uri.getPath != null && uri.getPath.endsWith(".jar")
    } catch {
      case _: URISyntaxException => false
    }
  }
} 
Example 16
Source File: AkkaDiscoveryHelper.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.client

import java.net.URI
import java.net.URISyntaxException
import java.util.concurrent.ThreadLocalRandom
import java.util.concurrent.TimeUnit

import akka.discovery.ServiceDiscovery
import akka.discovery.ServiceDiscovery.ResolvedTarget
import com.typesafe.config.Config
import org.slf4j.LoggerFactory

import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.concurrent.duration._


private[lagom] class AkkaDiscoveryHelper(config: Config, serviceDiscovery: ServiceDiscovery)(
    implicit
    ec: ExecutionContext
) {
  private val logger = LoggerFactory.getLogger(this.getClass)

  private val serviceNameMapper = new ServiceNameMapper(config)
  private val lookupTimeout     = config.getDuration("lookup-timeout", TimeUnit.MILLISECONDS).millis

  def locateAll(name: String): Future[Seq[URI]] = {
    val serviceLookup = serviceNameMapper.mapLookupQuery(name)
    serviceDiscovery
      .lookup(serviceLookup.lookup, lookupTimeout)
      .map { resolved =>
        logger.debug("Retrieved addresses: {}", resolved.addresses)
        resolved.addresses.map(target => toURI(target, serviceLookup))
      }
  }

  def locate(name: String): Future[Option[URI]] = locateAll(name).map(selectRandomURI)

  private def toURI(resolvedTarget: ResolvedTarget, lookup: ServiceLookup): URI = {
    val port = resolvedTarget.port.getOrElse(-1)

    val scheme = lookup.scheme.orNull

    try {
      new URI(
        scheme,              // scheme
        null,                // userInfo
        resolvedTarget.host, // host
        port,                // port
        null,                // path
        null,                // query
        null                 // fragment
      )
    } catch {
      case e: URISyntaxException => throw new RuntimeException(e)
    }
  }

  private def selectRandomURI(uris: Seq[URI]) = uris match {
    case Nil      => None
    case Seq(one) => Some(one)
    case many     => Some(many(ThreadLocalRandom.current().nextInt(many.size)))
  }
} 
Example 17
Source File: AkkaDiscoveryHelper.scala    From lagom-akka-discovery-service-locator   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.client

import java.net.URI
import java.net.URISyntaxException
import java.util.concurrent.ThreadLocalRandom
import java.util.concurrent.TimeUnit

import akka.discovery.ServiceDiscovery
import akka.discovery.ServiceDiscovery.ResolvedTarget
import com.typesafe.config.Config
import org.slf4j.LoggerFactory

import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.concurrent.duration._


private[lagom] class AkkaDiscoveryHelper(config: Config, serviceDiscovery: ServiceDiscovery)(
    implicit ec: ExecutionContext) {

  private val logger = LoggerFactory.getLogger(this.getClass)

  private val serviceNameMapper = new ServiceNameMapper(config)
  private val lookupTimeout = config.getDuration("lookup-timeout", TimeUnit.MILLISECONDS).millis

  def locateAll(name: String): Future[Seq[URI]] = {
    val serviceLookup = serviceNameMapper.mapLookupQuery(name)
    serviceDiscovery
      .lookup(serviceLookup.lookup, lookupTimeout)
      .map { resolved =>
        logger.debug("Retrieved addresses: {}", resolved.addresses)
        resolved.addresses.map(target => toURI(target, serviceLookup))
      }
  }

  def locate(name: String): Future[Option[URI]] = locateAll(name).map(selectRandomURI)

  private def toURI(resolvedTarget: ResolvedTarget, lookup: ServiceLookup): URI = {

    val port = resolvedTarget.port.getOrElse(-1)

    val scheme = lookup.scheme.orNull

    try {
      new URI(scheme, // scheme
              null, // userInfo
              resolvedTarget.host, // host
              port, // port
              null, // path
              null, // query
              null // fragment
      )
    } catch {
      case e: URISyntaxException => throw new RuntimeException(e)
    }
  }

  private def selectRandomURI(uris: Seq[URI]) = uris match {
    case Nil      => None
    case Seq(one) => Some(one)
    case many     => Some(many(ThreadLocalRandom.current().nextInt(many.size)))
  }

}