java.util.Optional Scala Examples

The following examples show how to use java.util.Optional. 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: SampleContainer.scala    From testcontainers-scala   with MIT License 5 votes vote down vote up
package com.dimafeng.testcontainers.munit

import java.util.Optional

import com.dimafeng.testcontainers.{ContainerDef, SingleContainer}
import com.dimafeng.testcontainers.munit.SampleContainer.SampleJavaContainer
import com.dimafeng.testcontainers.lifecycle.TestLifecycleAware
import org.testcontainers.containers.{GenericContainer => JavaGenericContainer}
import org.testcontainers.lifecycle.{TestDescription, TestLifecycleAware => JavaTestLifecycleAware}

case class SampleContainer(sampleJavaContainer: SampleJavaContainer)
  extends SingleContainer[SampleJavaContainer] with TestLifecycleAware {
  override implicit val container: SampleJavaContainer = sampleJavaContainer

  override def beforeTest(description: TestDescription): Unit = {
    container.beforeTest(description)
  }

  override def afterTest(description: TestDescription, throwable: Option[Throwable]): Unit = {
    container.afterTest(description, throwable.fold[Optional[Throwable]](Optional.empty())(Optional.of))
  }
}

object SampleContainer {
  class SampleJavaContainer extends JavaGenericContainer with JavaTestLifecycleAware {

    override def beforeTest(description: TestDescription): Unit = {}

    override def afterTest(description: TestDescription, throwable: Optional[Throwable]): Unit = {}

    override def start(): Unit = {}

    override def stop(): Unit = {}
  }

  case class Def(sampleJavaContainer: SampleJavaContainer) extends ContainerDef {
    override type Container = SampleContainer
    override protected def createContainer(): SampleContainer = {
      SampleContainer(sampleJavaContainer)
    }
  }
} 
Example 2
Source File: MavenRemoveDependenciesSubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.maven.report

import java.io.{File, OutputStream}
import java.net.URI
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._
import scala.util.Try


class MavenRemoveDependenciesSubscriber(projectRoot: File) extends IReportEventSubscriber[RemoveDependencyEvent] {

  private[this] var details = Map.empty[URI, List[String]]

  override def filter(event: scala.Any): Optional[RemoveDependencyEvent] = {
    val removeEvent = event match {
      case e: ILoggingEvent =>
        if (e.getLoggerName.endsWith("MavenRemoveDependenciesRule") && e.getMessage == "{} removed dependency {} from {}") {
          val args = e.getArgumentArray
          Try(RemoveDependencyEvent(args(1).toString, args(2).asInstanceOf[File])).toOption
        } else None
      case _ => None
    }

    removeEvent.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = if (details.nonEmpty) {
    val outputTemplate =
      """
        |### MavenRemoveDependenciesRule
        |The following artifacts were removed from the POM:
      """.stripMargin
    val content = details.foldLeft(outputTemplate) {(c, detail) =>
      val header = s"\n#### File [${detail._1}](${detail._1})\n|Artifacts|\n|---------|\n"
      c + detail._2.foldLeft(header) {(result, artifact) =>
        result + s"|$artifact|\n"
      }
    }
    outputStream.write(content.getBytes("utf8"))
  }

  override def doAccept(event: RemoveDependencyEvent): Unit = {
    val relativePomPath = projectRoot.toURI relativize event.pomFile.toURI
    details get relativePomPath match {
      case Some(list) => details += relativePomPath -> (event.dependency :: list)
      case None => details += relativePomPath -> List(event.dependency)
    }
  }
}

case class RemoveDependencyEvent(dependency: String, pomFile: File) 
Example 3
Source File: MavenDependenciesMappingSubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.maven.report

import java.io.{File, OutputStream}
import java.net.URI
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._
import scala.util.Try


class MavenDependenciesMappingSubscriber(projectRoot: File) extends IReportEventSubscriber[DependencyMappingEvent] {

  private[this] var details = Map.empty[URI, List[DependencyMappingEvent]]

  override def filter(event: scala.Any): Optional[DependencyMappingEvent] = {
    val artifact = event match {
      case e: ILoggingEvent =>
        if (e.getLoggerName.endsWith("MavenDependenciesMappingRule") && e.getMessage == "{} mapped {} to {} in {}") {
          val args = e.getArgumentArray
          Try(DependencyMappingEvent(
            args(1).asInstanceOf[Set[_]].map(_.toString),
            args(2).asInstanceOf[Set[_]].map(_.toString),
            args(3).asInstanceOf[File]
          )).toOption
        } else None
      case _ => None
    }

    artifact.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = if (details.nonEmpty) {
    val outputTemplate =
      """
        |### MavenDependenciesMappingRule
        |The following groups of artifacts were mapped to new ones.
      """.stripMargin
    val content = details.foldLeft(outputTemplate) {(c, detail) =>
      val header = s"\n#### File [${detail._1}](${detail._1})\n|from|to|\n|----|---|\n"
      val body = detail._2.foldLeft(header) {(b, event) =>
        val from = event.from.foldLeft("<ul>") {(f, x) =>
          f + s"<li>$x</li>"
        } + "</ul>"
        val to = event.to.foldLeft("<ul>") {(f, x) =>
          f + s"<li>$x</li>"
        } + "</ul>"
        b + s"| $from | $to |\n"
      }
      c + body
    }
    outputStream.write(content.getBytes("utf8"))
  }

  override def doAccept(event: DependencyMappingEvent): Unit = {
    val relativePomPath = projectRoot.toURI relativize event.pomFile.toURI
    details get relativePomPath match {
      case Some(list) => details += relativePomPath -> (event :: list)
      case None => details += relativePomPath -> List(event)
    }
  }
}

case class DependencyMappingEvent(from: Set[String], to: Set[String], pomFile: File) 
Example 4
Source File: ArtifactsSummarySubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.maven.report

import java.io.{File, OutputStream}
import java.net.URI
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._
import scala.util.Try


class ArtifactsSummarySubscriber(projectRoot: File) extends IReportEventSubscriber[(URI, String)] {

  private[this] var artifacts = Set.empty[(URI, String)]

  override def filter(event: scala.Any): Optional[(URI, String)] = {
    val artifact = event match {
      case e: ILoggingEvent =>
        e.getMessage match {
          case "Found maven pom {} for artifact {}" =>
            val args = e.getArgumentArray
            Try((projectRoot.toURI.relativize(args(0).asInstanceOf[File].toURI), args(1).toString)).toOption
          case _ => None
        }
      case _ => None
    }

    artifact.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = if (artifacts.nonEmpty) {
    val outputTemplate = s"\r### Artifacts\n" +
      s"This upgrade request processed only the ${artifacts.size} Maven project artifacts\n" +
      s"that were referenced directly or indirectly by the project's parent POM:\n\n" +
      s"| No. | POM file | Artifact ID |\n" +
      s"| --- | -------- | ----------- |\n"
    var pomCount = 0
    val content = artifacts.foldLeft(outputTemplate) {(c, artifact) =>
      pomCount += 1
      c + s"| $pomCount | [${artifact._1}](${artifact._1}) | ${artifact._2} |\n"
    }
    outputStream.write(content.getBytes("utf8"))
  }

  override def doAccept(event: (URI, String)): Unit = if (event._1.toString != "pom.xml") artifacts += event

  override val sequence = 1
} 
Example 5
Source File: DropwizardRoundTripTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.Dropwizard

import com.fasterxml.jackson.databind.ObjectMapper
import examples.client.dropwizard.user.{ UserClient, GetUserByNameResponse => GetUserByNameClientResponse }
import examples.server.dropwizard.definitions.User
import examples.server.dropwizard.user.UserHandler._
import examples.server.dropwizard.user._
import helpers.MockHelpers._
import java.util
import java.util.Optional
import java.util.concurrent.{ CompletableFuture, CompletionStage }
import org.asynchttpclient.{ Request, Response }
import org.mockito.{ ArgumentMatchersSugar, MockitoSugar }
import org.scalatest.concurrent.Waiters
import org.scalatest.{ FreeSpec, Matchers }
import scala.compat.java8.FunctionConverters._

class DropwizardRoundTripTest extends FreeSpec with Matchers with Waiters with MockitoSugar with ArgumentMatchersSugar {
  private implicit val mapper = new ObjectMapper

  "Test server" in {
    val USERNAME = "foobar"

    val serverFuture  = new CompletableFuture[GetUserByNameResponse]
    val asyncResponse = mockAsyncResponse(serverFuture)

    val resource = new UserResource(new UserHandler {
      override def createUser(body: User): CompletionStage[CreateUserResponse]                                          = ???
      override def createUsersWithArrayInput(body: util.List[User]): CompletionStage[CreateUsersWithArrayInputResponse] = ???
      override def createUsersWithListInput(body: util.List[User]): CompletionStage[CreateUsersWithListInputResponse]   = ???
      override def loginUser(username: String, password: String): CompletionStage[LoginUserResponse]                    = ???
      override def logoutUser(): CompletionStage[LogoutUserResponse]                                                    = ???
      override def updateUser(username: String, body: User): CompletionStage[UpdateUserResponse]                        = ???
      override def deleteUser(username: String): CompletionStage[DeleteUserResponse]                                    = ???

      override def getUserByName(username: String): CompletionStage[GetUserByNameResponse] = {
        username match {
          case USERNAME =>
            serverFuture.complete(
              GetUserByNameResponse.Ok(
                new User.Builder()
                  .withEmail("[email protected]")
                  .withFirstName("Foo")
                  .withLastName("Bar")
                  .withId(1)
                  .withUsername(USERNAME)
                  .build()
              )
            )
          case "" =>
            serverFuture.complete(GetUserByNameResponse.BadRequest)
          case _ =>
            serverFuture.complete(GetUserByNameResponse.NotFound)
        }
        serverFuture
      }
    })

    val httpClient: Request => CompletionStage[Response] = { request =>
      val userPath = "^/v2/user/([^/]*)$".r
      request.getUri.getPath match {
        case userPath(username) =>
          resource.getUserByName(username, asyncResponse)
          serverFuture.thenApply({ response =>
            val entityBody = response match {
              case r: GetUserByNameResponse.Ok => Some(r.getEntityBody)
              case _                           => None
            }
            mockAHCResponse(request.getUrl, response.getStatusCode, entityBody)
          })
        case _ =>
          CompletableFuture.completedFuture(mockAHCResponse(request.getUrl, 404))
      }
    }

    val client = new UserClient.Builder()
      .withHttpClient(httpClient.asJava)
      .withObjectMapper(mapper)
      .build()

    val w = new Waiter
    client
      .getUserByName(USERNAME)
      .call()
      .whenComplete({ (response, t) =>
        w { t shouldBe null }
        response match {
          case r: GetUserByNameClientResponse.Ok =>
            w {
              r.getValue.getUsername.get shouldBe USERNAME
              r.getValue.getPassword shouldBe Optional.empty
            }
          case _: GetUserByNameClientResponse.BadRequest => w { fail("Got BadRequest") }
          case _: GetUserByNameClientResponse.NotFound   => w { fail("Got NotFound") }
        }
        w.dismiss()
      })
    w.await(dismissals(1))
  }
} 
Example 6
Source File: JacksonBuilderParamTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.Jackson

import examples.client.dropwizard.definitions.{ Category, Pet }
import java.util.Optional
import org.scalatest.{ FreeSpec, Matchers }

class JacksonBuilderParamTest extends FreeSpec with Matchers {
  "POJO builders should not accept nulls for required params" in {
    assertThrows[NullPointerException] {
      new Pet.Builder(null: String)
        .build()
    }
  }

  "POJO builders should accept nulls for the value variant for optional params" in {
    val pet = new Pet.Builder("fluffy")
      .withCategory(null: Category)
      .build()
    pet.getCategory shouldBe Optional.empty
  }

  "POJO builders should not accept nulls for the Optional<> variant for optional params" in {
    assertThrows[NullPointerException] {
      new Pet.Builder("fluffy")
        .withCategory(null: Optional[Category])
        .build()
    }
  }
} 
Example 7
Source File: ServiceLocatorSpec.scala    From reactive-lib   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.rp.servicediscovery.javadsl

import akka.actor.ActorSystem
import akka.testkit.{ ImplicitSender, TestKit }
import com.lightbend.rp.servicediscovery.scaladsl.{ Service, Settings }
import com.typesafe.config.ConfigFactory
import java.net.URI
import java.util.Optional
import org.scalatest.{ AsyncFunSuiteLike, BeforeAndAfterAll, DiagrammedAssertions }
import scala.collection.JavaConverters._
import scala.collection.immutable.Seq

object ServiceLocatorSpec {
  def config = ConfigFactory
    .parseString(
      s"""|com.lightbend.platform-tooling.service-discovery {
          |  external-service-addresses {
          |    "has-one" = ["http://127.0.0.1:9000"]
          |    "has-two" = ["http://127.0.0.1:8000", "http://127.0.0.1:8001"]
          |  }
          |}
          |""".stripMargin)
    .withFallback(ConfigFactory.defaultApplication())
}

class ServiceLocatorSpec extends TestKit(ActorSystem("service-locator", ServiceLocatorSpec.config))
  with ImplicitSender
  with AsyncFunSuiteLike
  with DiagrammedAssertions
  with BeforeAndAfterAll {

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  implicit val settings = Settings(system)

  test("addressSelectionFirst should work for empty lists") {
    assert(ServiceLocator.addressSelectionFirst.select(Seq().asJava) ===
      Optional.empty[URI]())
  }

  test("addressSelectionFirst should work for non-empty lists") {
    assert(ServiceLocator.addressSelectionFirst.select(
      Seq(
        Service("myservice.com", new URI("http://127.0.0.1:9000")),
        Service("myotherservice.com", new URI("http://127.0.0.1:9001"))).asJava).get() ===
      Service("myservice.com", new URI("http://127.0.0.1:9000")))
  }

  test("addressSelectionRandom should work for empty lists") {
    assert(ServiceLocator.addressSelectionFirst.select(Seq().asJava) === Optional.empty[URI]())
  }

  test("addressSelectionRandom should work for non-empty lists") {
    assert(ServiceLocator.addressSelectionFirst.select(Seq(Service("hello", new URI("http://127.0.0.1:9000"))).asJava).isPresent)
  }
} 
Example 8
Source File: MultipleContainersSpec.scala    From testcontainers-scala   with MIT License 5 votes vote down vote up
package com.dimafeng.testcontainers

import java.util.Optional

import com.dimafeng.testcontainers.MultipleContainersSpec.{InitializableContainer, TestSpec}
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.{Args, FlatSpec, Reporter}
import org.scalatestplus.mockito.MockitoSugar

class MultipleContainersSpec extends BaseSpec[ForEachTestContainer] {
  it should "call all expected methods of the multiple containers" in {
    val container1 = mock[SampleJavaContainer]
    val container2 = mock[SampleJavaContainer]

    val containers = MultipleContainers(new SampleContainer(container1), new SampleContainer(container2))

    new TestSpec({
      assert(1 == 1)
    }, containers).run(None, Args(mock[Reporter]))

    verify(container1).beforeTest(any())
    verify(container1).start()
    verify(container1).afterTest(any(), ArgumentMatchers.eq(Optional.empty()))
    verify(container1).stop()

    verify(container2).beforeTest(any())
    verify(container2).start()
    verify(container2).afterTest(any(), ArgumentMatchers.eq(Optional.empty()))
    verify(container2).stop()
  }

  
  it should "initialize containers lazily in `MultipleContainers` to let second container be depended on start data of the first one" in {
    lazy val container1 = new InitializableContainer("after start value")
    lazy val container2 = new InitializableContainer(container1.value)

    val containers = MultipleContainers(container1, container2)

    new TestSpec({
      assert(1 == 1)
    }, containers).run(None, Args(mock[Reporter]))

    assert(container1.value == "after start value")
    assert(container2.value == "after start value")
  }
}

object MultipleContainersSpec {

  class InitializableContainer(valueToBeSetAfterStart: String) extends SingleContainer[SampleJavaContainer] with MockitoSugar {
    override implicit val container: SampleJavaContainer = mock[SampleJavaContainer]
    var value: String = _

    override def start(): Unit = {
      value = valueToBeSetAfterStart
    }
  }

  class ExampleContainerWithVariable(val variable: String) extends SingleContainer[SampleJavaContainer] with MockitoSugar {
    override implicit val container: SampleJavaContainer = mock[SampleJavaContainer]
  }

  protected class TestSpec(testBody: => Unit, _container: Container) extends FlatSpec with ForEachTestContainer {
    override val container = _container

    it should "test" in {
      testBody
    }
  }

} 
Example 9
Source File: SampleContainer.scala    From testcontainers-scala   with MIT License 5 votes vote down vote up
package com.dimafeng.testcontainers

import java.util.Optional

import com.dimafeng.testcontainers.lifecycle.TestLifecycleAware
import org.testcontainers.containers.{GenericContainer => JavaGenericContainer}
import org.testcontainers.lifecycle.{TestDescription, TestLifecycleAware => JavaTestLifecycleAware}

class SampleJavaContainer extends JavaGenericContainer with JavaTestLifecycleAware {

  override def beforeTest(description: TestDescription): Unit = {
    println("beforeTest")
  }

  override def afterTest(description: TestDescription, throwable: Optional[Throwable]): Unit = {
    println("afterTest")
  }

  override def start(): Unit = {
    println("start")
  }

  override def stop(): Unit = {
    println("stop")
  }
}

case class SampleContainer(sampleJavaContainer: SampleJavaContainer)
  extends SingleContainer[SampleJavaContainer] with TestLifecycleAware {
  override implicit val container: SampleJavaContainer = sampleJavaContainer

  override def beforeTest(description: TestDescription): Unit = {
    container.beforeTest(description)
  }

  override def afterTest(description: TestDescription, throwable: Option[Throwable]): Unit = {
    container.afterTest(description, throwable.fold[Optional[Throwable]](Optional.empty())(Optional.of))
  }
}
object SampleContainer {
  case class Def(sampleJavaContainer: SampleJavaContainer) extends ContainerDef {
    override type Container = SampleContainer
    override protected def createContainer(): SampleContainer = {
      SampleContainer(sampleJavaContainer)
    }
  }
} 
Example 10
Source File: MavenExcludeDependenciesSubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.maven.report

import java.io.{File, OutputStream}
import java.net.URI
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._
import scala.util.Try


class MavenExcludeDependenciesSubscriber(projectRoot: File) extends IReportEventSubscriber[ExcludeDependencyEvent] {

  private[this] var events = Map.empty[URI, Set[ExcludeDependencyEvent]]

  override def filter(event: scala.Any): Optional[ExcludeDependencyEvent] = {
    val excludeEvent = event match {
      case e: ILoggingEvent =>
        if (e.getLoggerName.endsWith("MavenExcludeDependenciesRule") && e.getMessage == "{} excluded {} from {} in {}") {
          val args = e.getArgumentArray
          Try(ExcludeDependencyEvent(
            args(1).asInstanceOf[Set[_]].map(_.toString),
            args(2).toString,
            args(3).asInstanceOf[File]
          )).toOption
        } else None
      case _ => None
    }

    excludeEvent.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = if (events.nonEmpty) {
    val outputTemplate =
      """
        |### MavenExcludeDependenciesRule
        |The following artifacts were excluded:
      """.stripMargin
    val content = events.foldLeft(outputTemplate) {(c, event) =>
      val header = s"\n#### File [${event._1}](${event._1})\n|Artifact|Exclusions|\n|-------|------|\n"
      c + header + event._2.map(e => e.dep -> e.exclusions).toMap.foldLeft("") {(result, entry) =>
        result + s"|${entry._1}|" + entry._2.foldLeft("<ul>")(_ + "<li>" + _ + "</li>") + "</ul>|\n"
      }
    }
    outputStream.write(content.getBytes("utf8"))
  }

  override def doAccept(event: ExcludeDependencyEvent): Unit = {
    val relativePomPath = projectRoot.toURI relativize event.pomFile.toURI
    events get relativePomPath match {
      case Some(set) => events += relativePomPath -> (set + event)
      case None => events += relativePomPath -> Set(event)
    }
  }
}

case class ExcludeDependencyEvent(exclusions: Set[String], dep: String, pomFile: File) 
Example 11
Source File: SeleniumTestContainerSuite.scala    From testcontainers-scala   with MIT License 5 votes vote down vote up
package com.dimafeng.testcontainers

import java.io.File
import java.net.URL
import java.util.Optional

import com.dimafeng.testcontainers.lifecycle.TestLifecycleAware
import org.openqa.selenium.WebDriver
import org.openqa.selenium.remote.{DesiredCapabilities, RemoteWebDriver}
import org.scalatest.Suite
import org.testcontainers.containers.BrowserWebDriverContainer
import org.testcontainers.lifecycle.TestDescription

trait SeleniumTestContainerSuite extends ForEachTestContainer {
  self: Suite =>

  def desiredCapabilities: DesiredCapabilities

  def recordingMode: (BrowserWebDriverContainer.VncRecordingMode, File) = null

  val container = SeleniumContainer(desiredCapabilities, recordingMode)

  implicit def webDriver: WebDriver = container.webDriver
}

class SeleniumContainer(desiredCapabilities: Option[DesiredCapabilities] = None,
                        recordingMode: Option[(BrowserWebDriverContainer.VncRecordingMode, File)] = None)
  extends SingleContainer[BrowserWebDriverContainer[_]] with TestLifecycleAware {
  require(desiredCapabilities.isDefined, "'desiredCapabilities' is required parameter")

  override val container: BrowserWebDriverContainer[_] = new BrowserWebDriverContainer()
  desiredCapabilities.foreach(container.withDesiredCapabilities)
  recordingMode.foreach(Function.tupled(container.withRecordingMode))

  def password: String = container.getPassword

  def port: Int = container.getPort

  def seleniumAddress: URL = container.getSeleniumAddress

  def vncAddress: String = container.getVncAddress

  def webDriver: RemoteWebDriver = container.getWebDriver

  override def afterTest(description: TestDescription, throwable: Option[Throwable]): Unit = {
    val javaThrowable: Optional[Throwable] = throwable match {
      case Some(error) => Optional.of(error)
      case None => Optional.empty()
    }
    container.afterTest(description, javaThrowable)
  }
}

object SeleniumContainer {
  def apply(desiredCapabilities: DesiredCapabilities = null, recordingMode: (BrowserWebDriverContainer.VncRecordingMode, File) = null): SeleniumContainer =
    new SeleniumContainer(Option(desiredCapabilities), Option(recordingMode))
} 
Example 12
Source File: Contexts.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.javasupport.impl

import java.util.Optional

import io.cloudstate.javasupport.{ClientActionContext, Context, EffectContext, ServiceCall}

import scala.util.control.NoStackTrace
import com.google.protobuf.{Any => JavaPbAny}
import com.google.protobuf.any.{Any => ScalaPbAny}
import io.cloudstate.protocol.entity.{ClientAction, Failure, Forward, Reply, SideEffect}

private[impl] trait ActivatableContext extends Context {
  private final var active = true
  final def deactivate(): Unit = active = false
  final def checkActive(): Unit = if (!active) throw new IllegalStateException("Context no longer active!")
}

private[impl] trait AbstractEffectContext extends EffectContext {
  self: ActivatableContext =>

  private final var effects = List.empty[SideEffect]

  override final def effect(effect: ServiceCall, synchronous: Boolean): Unit = {
    checkActive()
    SideEffect(
      serviceName = effect.ref().method().getService.getFullName,
      commandName = effect.ref().method().getName,
      payload = Some(ScalaPbAny.fromJavaProto(effect.message())),
      synchronous = synchronous
    ) :: effects
  }

  final def sideEffects: List[SideEffect] = effects.reverse
}

private[impl] trait AbstractClientActionContext extends ClientActionContext {
  self: ActivatableContext =>

  def commandId: Long

  private final var error: Option[String] = None
  private final var forward: Option[Forward] = None

  override final def fail(errorMessage: String): RuntimeException = {
    checkActive()
    if (error.isEmpty) {
      error = Some(errorMessage)
      throw FailInvoked
    } else throw new IllegalStateException("fail(…) already previously invoked!")
  }

  override final def forward(to: ServiceCall): Unit = {
    checkActive()
    if (forward.isDefined) {
      throw new IllegalStateException("This context has already forwarded.")
    }
    forward = Some(
      Forward(
        serviceName = to.ref().method().getService.getFullName,
        commandName = to.ref().method().getName,
        payload = Some(ScalaPbAny.fromJavaProto(to.message()))
      )
    )
  }

  final def hasError: Boolean = error.isDefined

  final def createClientAction(reply: Optional[JavaPbAny], allowNoReply: Boolean): Option[ClientAction] =
    error match {
      case Some(msg) => Some(ClientAction(ClientAction.Action.Failure(Failure(commandId, msg))))
      case None =>
        if (reply.isPresent) {
          if (forward.isDefined) {
            throw new IllegalStateException(
              "Both a reply was returned, and a forward message was sent, choose one or the other."
            )
          }
          Some(ClientAction(ClientAction.Action.Reply(Reply(Some(ScalaPbAny.fromJavaProto(reply.get()))))))
        } else if (forward.isDefined) {
          Some(ClientAction(ClientAction.Action.Forward(forward.get)))
        } else if (allowNoReply) {
          None
        } else {
          throw new RuntimeException("No reply or forward returned by command handler!")
        }
    }
}

object FailInvoked extends Throwable with NoStackTrace {
  override def toString: String = "CommandContext.fail(…) invoked"
} 
Example 13
Source File: Contexts.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.javasupport.impl

import java.util.Optional

import io.cloudstate.javasupport.{ClientActionContext, Context, EffectContext, ServiceCall}

import scala.util.control.NoStackTrace
import com.google.protobuf.{Any => JavaPbAny}
import com.google.protobuf.any.{Any => ScalaPbAny}
import io.cloudstate.protocol.entity.{ClientAction, Failure, Forward, Reply, SideEffect}

private[impl] trait ActivatableContext extends Context {
  private final var active = true
  final def deactivate(): Unit = active = false
  final def checkActive(): Unit = if (!active) throw new IllegalStateException("Context no longer active!")
}

private[impl] trait AbstractEffectContext extends EffectContext {
  self: ActivatableContext =>

  private final var effects = List.empty[SideEffect]

  override final def effect(effect: ServiceCall, synchronous: Boolean): Unit = {
    checkActive()
    SideEffect(
      serviceName = effect.ref().method().getService.getFullName,
      commandName = effect.ref().method().getName,
      payload = Some(ScalaPbAny.fromJavaProto(effect.message())),
      synchronous = synchronous
    ) :: effects
  }

  final def sideEffects: List[SideEffect] = effects.reverse
}

private[impl] trait AbstractClientActionContext extends ClientActionContext {
  self: ActivatableContext =>

  def commandId: Long

  private final var error: Option[String] = None
  private final var forward: Option[Forward] = None

  override final def fail(errorMessage: String): RuntimeException = {
    checkActive()
    if (error.isEmpty) {
      error = Some(errorMessage)
      throw FailInvoked
    } else throw new IllegalStateException("fail(…) already previously invoked!")
  }

  override final def forward(to: ServiceCall): Unit = {
    checkActive()
    if (forward.isDefined) {
      throw new IllegalStateException("This context has already forwarded.")
    }
    forward = Some(
      Forward(
        serviceName = to.ref().method().getService.getFullName,
        commandName = to.ref().method().getName,
        payload = Some(ScalaPbAny.fromJavaProto(to.message()))
      )
    )
  }

  final def hasError: Boolean = error.isDefined

  final def createClientAction(reply: Optional[JavaPbAny], allowNoReply: Boolean): Option[ClientAction] =
    error match {
      case Some(msg) => Some(ClientAction(ClientAction.Action.Failure(Failure(commandId, msg))))
      case None =>
        if (reply.isPresent) {
          if (forward.isDefined) {
            throw new IllegalStateException(
              "Both a reply was returned, and a forward message was sent, choose one or the other."
            )
          }
          Some(ClientAction(ClientAction.Action.Reply(Reply(Some(ScalaPbAny.fromJavaProto(reply.get()))))))
        } else if (forward.isDefined) {
          Some(ClientAction(ClientAction.Action.Forward(forward.get)))
        } else if (allowNoReply) {
          None
        } else {
          throw new RuntimeException("No reply or forward returned by command handler!")
        }
    }
}

object FailInvoked extends Throwable with NoStackTrace {
  override def toString: String = "CommandContext.fail(…) invoked"
} 
Example 14
Source File: CompilerReporter.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.sbtscastie

import com.olegych.scastie.api

import play.api.libs.json.Json

import sbt._
import Keys._
import KeyRanks.DTask

import System.{lineSeparator => nl}

import xsbti.{Reporter, Problem, Position, Severity}
import java.util.Optional

object CompilerReporter {
  // compilerReporter is marked private in sbt
  private lazy val compilerReporter = TaskKey[xsbti.Reporter](
    "compilerReporter",
    "Experimental hook to listen (or send) compilation failure messages.",
    DTask
  )

  val setting: sbt.Def.Setting[_] =
    compilerReporter in (Compile, compile) := new xsbti.Reporter {
      private val buffer       = collection.mutable.ArrayBuffer.empty[Problem]
      def reset(): Unit        = buffer.clear()
      def hasErrors: Boolean   = buffer.exists(_.severity == Severity.Error)
      def hasWarnings: Boolean = buffer.exists(_.severity == Severity.Warn)

      def printSummary(): Unit = {
        def toApi(p: Problem): api.Problem = {
          def toOption[T](m: Optional[T]): Option[T] = {
            if (!m.isPresent) None
            else Some(m.get)
          }
          val severity =
            p.severity match {
              case xsbti.Severity.Info  => api.Info
              case xsbti.Severity.Warn  => api.Warning
              case xsbti.Severity.Error => api.Error
            }
          api.Problem(severity, toOption(p.position.line).map(_.toInt), p.message)
        }
        if (problems.nonEmpty) {
          val apiProblems = problems.map(toApi)
          println(Json.stringify(Json.toJson(apiProblems)))
        }
      }
      def problems: Array[Problem] = buffer.toArray
//        def log(pos: Position, msg: String, sev: Severity): Unit = {
      def log(problem: Problem): Unit = {
        object MyProblem extends Problem {
          def category: String   = "foo"
          def severity: Severity = problem.severity()
          def message: String    = problem.message()
          def position: Position = problem.position()
          override def toString  = s"$position:$severity: $message"
        }
        buffer.append(MyProblem)
      }
      def comment(pos: xsbti.Position, msg: String): Unit = ()
    }
} 
Example 15
Source File: mmkvStorageProvider.scala    From vm   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.mmadt.storage.mmkv

import java.util
import java.util.Optional

import org.mmadt.language.obj.Inst.Func
import org.mmadt.language.obj._
import org.mmadt.language.obj.`type`.{Type, __}
import org.mmadt.language.obj.op.initial.StartOp
import org.mmadt.language.obj.op.trace.RewriteOp
import org.mmadt.language.obj.value._
import org.mmadt.storage.StorageFactory._
import org.mmadt.storage.mmkv.mmkvStorageProvider._
import org.mmadt.storage.obj.value.VInst
import org.mmadt.storage.{StorageException, StorageProvider}

import scala.collection.JavaConverters._

))
}

object mmkvStorageProvider {
  private val opcode = "=mmkv"
  private val K: StrValue = str("k")
  private val V: StrValue = str("v")
  private val mmkv: Rec[StrValue, Type[Obj]] = rec(g = (",", Map(K -> int, V -> __))).named("mmkv")

  object mmkvOp {
    object mmkvGetRecords extends Func[Obj, Rec[StrValue, Obj]] {
      def apply(fileStr: Str): Inst[Obj, Rec[StrValue, Obj]] = new VInst[Obj, Rec[StrValue, Obj]](g = (opcode, List(fileStr)), func = this)
      override def apply(start: Obj, inst: Inst[Obj, Rec[StrValue, Obj]]): Rec[StrValue, Obj] = {
        if (inst.arg0[Obj].isInstanceOf[Type[_]])
          return rec[StrValue, Obj].via(start, inst)
        val fileStr: String = inst.arg0[StrValue].g
        (start match {
          case _: Type[_] => mmkvStore.open(fileStr).schema.via(start, inst).hardQ(*)
          case _ => mmkvStore.open(fileStr).stream((start, inst))
        }).asInstanceOf[Rec[StrValue, Obj]]
      }
    }

    object mmkvGetRecordsByKey extends Func[Obj, Rec[StrValue, Obj]] {
      def apply(fileStr: Obj, key: Obj): Inst[Obj, Rec[StrValue, Obj]] = new VInst[Obj, Rec[StrValue, Obj]](g = (opcode, List(fileStr, str("getByKeyEq"), key)), func = this)
      override def apply(start: Obj, inst: Inst[Obj, Rec[StrValue, Obj]]): Rec[StrValue, Obj] = {
        if (inst.arg0[Obj].isInstanceOf[Type[_]])
          return rec[StrValue, Obj].via(start, inst)
        val fileStr: String = inst.arg0[StrValue].g
        val key: Obj = inst.arg2[Obj]
        (start match {
          case _: Type[_] => mmkvStore.open(fileStr).schema.via(start, inst).hardQ(*)
          case _ => rec(K -> key, V -> mmkvStore.open(fileStr).get(key)).via(start,inst)
        })
      }
    }

    private def connect(file: Str): mmkvStore[Value[Obj], Value[Obj]] = {
      file match {
        case avalue: StrValue => mmkvStore.open(avalue.g)
        case _ => throw new StorageException("A str value is required to connect to mmkv: " + file)
      }
    }
  }

} 
Example 16
Source File: mmlangLanguageProvider.scala    From vm   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.mmadt.language.mmlang

import java.util.Optional

import javax.script.{Bindings, ScriptEngineManager, SimpleBindings}
import org.mmadt.language.LanguageProvider
import org.mmadt.language.jsr223.mmADTScriptEngine


class mmlangLanguageProvider extends LanguageProvider {
  override val name: String = mmlangLanguageProvider._name
  override def getEngine: Optional[mmADTScriptEngine] = Optional.of(mmlangLanguageProvider.scriptEngine())
}

object mmlangLanguageProvider {
  private val _name: String = "mmlang"
  private lazy val scriptEngineManager: ScriptEngineManager = {
    val manager: ScriptEngineManager = new ScriptEngineManager() // want to constrain the manager to only accessing mmADTScriptEngines
    manager
  }
  private def scriptEngine(): mmADTScriptEngine = scriptEngineManager.getEngineByName(_name).asInstanceOf[mmlangScriptEngine]

  private def bindings(pairs: Tuple2[String, Any]*): Bindings = {
    val bindings: Bindings = new SimpleBindings()
    pairs.foreach(s => bindings.put(s._1, s._2))
    bindings
  }
} 
Example 17
Source File: GremlinLanguageProvider.scala    From vm   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.mmadt.language.gremlin
import java.util.Optional

import javax.script.{Bindings, ScriptEngineManager, SimpleBindings}
import org.mmadt.language.LanguageProvider
import org.mmadt.language.jsr223.mmADTScriptEngine

class GremlinLanguageProvider extends LanguageProvider {
  override val name: String = GremlinLanguageProvider._name
  override def getEngine: Optional[mmADTScriptEngine] = Optional.of(GremlinLanguageProvider.scriptEngine())
}

object GremlinLanguageProvider {
  private val _name: String = "gremlin"
  private lazy val scriptEngineManager: ScriptEngineManager = {
    val manager: ScriptEngineManager = new ScriptEngineManager() // want to constrain the manager to only accessing mmADTScriptEngines
    manager
  }
  private def scriptEngine(): mmADTScriptEngine = scriptEngineManager.getEngineByName(_name).asInstanceOf[GremlinScriptEngine]

  private def bindings(pairs: Tuple2[String, Any]*): Bindings = {
    val bindings: Bindings = new SimpleBindings()
    pairs.foreach(s => bindings.put(s._1, s._2))
    bindings
  }
} 
Example 18
Source File: DefaultSource.scala    From spark-dynamodb   with Apache License 2.0 5 votes vote down vote up
package com.audienceproject.spark.dynamodb.datasource

import java.util.Optional

import org.apache.spark.sql.sources.DataSourceRegister
import org.apache.spark.sql.sources.v2.reader.DataSourceReader
import org.apache.spark.sql.sources.v2.writer.DataSourceWriter
import org.apache.spark.sql.sources.v2.{DataSourceOptions, ReadSupport, WriteSupport}
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.{SaveMode, SparkSession}
import org.slf4j.LoggerFactory

import scala.collection.JavaConverters._

class DefaultSource extends ReadSupport with WriteSupport with DataSourceRegister {

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

    override def createReader(schema: StructType, options: DataSourceOptions): DataSourceReader = {
        val optionsMap = options.asMap().asScala
        val defaultParallelism = optionsMap.get("defaultparallelism").map(_.toInt).getOrElse(getDefaultParallelism)
        new DynamoDataSourceReader(defaultParallelism, Map(optionsMap.toSeq: _*), Some(schema))
    }

    override def createReader(options: DataSourceOptions): DataSourceReader = {
        val optionsMap = options.asMap().asScala
        val defaultParallelism = optionsMap.get("defaultparallelism").map(_.toInt).getOrElse(getDefaultParallelism)
        new DynamoDataSourceReader(defaultParallelism, Map(optionsMap.toSeq: _*))
    }

    override def createWriter(writeUUID: String, schema: StructType, mode: SaveMode, options: DataSourceOptions): Optional[DataSourceWriter] = {
        if (mode == SaveMode.Append || mode == SaveMode.Overwrite)
            throw new IllegalArgumentException(s"DynamoDB data source does not support save modes ($mode)." +
                " Please use option 'update' (true | false) to differentiate between append/overwrite and append/update behavior.")
        val optionsMap = options.asMap().asScala
        val defaultParallelism = optionsMap.get("defaultparallelism").map(_.toInt).getOrElse(getDefaultParallelism)
        val writer = new DynamoDataSourceWriter(defaultParallelism, Map(optionsMap.toSeq: _*), schema)
        Optional.of(writer)
    }

    override def shortName(): String = "dynamodb"

    private def getDefaultParallelism: Int =
        SparkSession.getActiveSession match {
            case Some(spark) => spark.sparkContext.defaultParallelism
            case None =>
                logger.warn("Unable to read defaultParallelism from SparkSession." +
                    " Parallelism will be 1 unless overwritten with option `defaultParallelism`")
                1
        }

} 
Example 19
Source File: MavenAddDependenciesSubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.maven.report

import java.io.{File, OutputStream}
import java.net.URI
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._
import scala.util.Try


class MavenAddDependenciesSubscriber(projectRoot: File) extends IReportEventSubscriber[AddDependencyEvent] {

  private[this] var details = Map.empty[URI, List[String]]

  override def filter(event: scala.Any): Optional[AddDependencyEvent] = {
    val artifact = event match {
      case e: ILoggingEvent =>
        if (e.getLoggerName.endsWith("MavenAddDependenciesRule") && e.getMessage == "{} added dependency {} to {}") {
          val args = e.getArgumentArray
          Try(AddDependencyEvent(args(1).toString, args(2).asInstanceOf[File])).toOption
        } else None
      case _ => None
    }

    artifact.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = if (details.nonEmpty) {
    val outputTemplate =
      """
        |### MavenAddDependenciesRule
        |The following artifacts were added to the POM:
      """.stripMargin
    val content = details.foldLeft(outputTemplate) {(c, detail) =>
     val header = s"\n#### File [${detail._1}](${detail._1})\n|Artifacts|\n|---------|\n"
     c + detail._2.foldLeft(header) {(result, artifact) =>
       result + s"|$artifact|\n"
     }
    }
    outputStream.write(content.getBytes("utf8"))
  }

  override def doAccept(event: AddDependencyEvent): Unit = {
    val relativePomPath = projectRoot.toURI relativize event.pomFile.toURI
    details get relativePomPath match {
      case Some(list) => details += relativePomPath -> (event.dependency :: list)
      case None => details += relativePomPath -> List(event.dependency)
    }
  }
}

case class AddDependencyEvent(dependency: String, pomFile: File) 
Example 20
Source File: MavenAddManagedDependenciesSubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.maven.report

import java.io.{File, OutputStream}
import java.net.URI
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._
import scala.util.Try


class MavenAddManagedDependenciesSubscriber(projectRoot: File)
  extends IReportEventSubscriber[AddManagedDependencyEvent] {

  private[this] var details = Map.empty[URI, List[String]]

  override def filter(event: scala.Any): Optional[AddManagedDependencyEvent] = {
    val artifact = event match {
      case e: ILoggingEvent =>
        if (e.getLoggerName.endsWith("MavenAddManagedDependenciesRule")
          && e.getMessage == "{} added managed dependency {} to {}") {
          val args = e.getArgumentArray
          Try(AddManagedDependencyEvent(args(1).toString, args(2).asInstanceOf[File])).toOption
        } else None
      case _ => None
    }

    artifact.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = if (details.nonEmpty) {
    val outputTemplate =
      """
        |### MavenAddManagedDependenciesRule
        |The following artifacts were added to dependencyManagement of the POM:
      """.stripMargin
    val content = details.foldLeft(outputTemplate) {(c, detail) =>
     val header = s"\n#### File [${detail._1}](${detail._1})\n|Artifacts|\n|---------|\n"
     c + detail._2.foldLeft(header) {(result, artifact) =>
       result + s"|$artifact|\n"
     }
    }
    outputStream.write(content.getBytes("utf8"))
  }

  override def doAccept(event: AddManagedDependencyEvent): Unit = {
    val relativePomPath = projectRoot.toURI relativize event.pomFile.toURI
    details get relativePomPath match {
      case Some(list) => details += relativePomPath -> (event.dependency :: list)
      case None => details += relativePomPath -> List(event.dependency)
    }
  }
}

case class AddManagedDependencyEvent(dependency: String, pomFile: File) 
Example 21
Source File: ProjectDetailsSubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.report.impl;

import java.io.OutputStream
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._



class ProjectDetailsSubscriber extends IReportEventSubscriber[ProjectDetails]{

  private[this] var projectDetails: Option[ProjectDetails] = None

  override def filter(event: scala.Any): Optional[ProjectDetails] = {
    val details = event match {
      case event1: ILoggingEvent =>
        // Starting upgrade {} project to {}, pom {}
        val NoTaskId = """Starting upgrade (.*) project to (.*), pom (.*) with taskId None""".r
        val HasTaskId = """Starting upgrade (.*) project to (.*), pom (.*) with taskId Some\((.*)\)""".r

        event1.getFormattedMessage match {
          case HasTaskId(stack, targetVersion, pomPath, id) => Some(ProjectDetails(pomPath, stack, targetVersion, Some(id)))
          case NoTaskId(stack, targetVersion, pomPath) => Some(ProjectDetails(pomPath, stack, targetVersion, None))
          case _ => None
        }
      case _ => None
    }
    details.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = projectDetails match {
    case Some(ProjectDetails(pathToPom, stack, targetVersion, taskId)) =>
      outputStream.write(outputTemplate(pathToPom, stack, targetVersion, taskId).getBytes("utf8"))
    case None =>
  }

  private def outputTemplate(pathToPom: String,stack: String, targetVersion: String,  taskId: Option[String]) = {
    s"""
       |# $stack project upgrade report
       |## Project details
       |Name | Description
       |---- | -----------
       |Path to project POM |	$pathToPom
       |Target Version |	$targetVersion
       |Upgrade job ID | $taskId
       |Full upgrade log | [link](raptor-upgrade-debug${taskId.map("-" + _) getOrElse ""}.log)
       |Upgrade warnings only log | [link](raptor-upgrade-warn${taskId.map("-" + _) getOrElse ""}.log)
       |
     """.stripMargin
  }

  override def doAccept(event: ProjectDetails): Unit = projectDetails = Some(event)

  override val sequence = 0
}

case class ProjectDetails(pathToPom: String, stack: String, targetVersion: String, taskId: Option[String]) 
Example 22
Source File: ManualChangesSummarySubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.report.impl

import java.io.OutputStream
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._


class ManualChangesSummarySubscriber extends IReportEventSubscriber[(String, Int)] {

  private[this] var manualChanges = Map.empty[String, Int]

  override def filter(event: scala.Any): Optional[(String, Int)] = {
    val Regex = """Rule (.*) requires (\d+) manual changes""".r
    val info = event match {
      case event1: ILoggingEvent =>
        event1.getFormattedMessage match {
          case Regex(rule, num) => Some((rule, num.toInt))
          case _ => None
        }
      case _ => None
    }

    info.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = if (manualChanges.nonEmpty) {
    val outputTemplate = "\r## Manual Changes Required\n\n| Rule | Details |\n| ---- | ----------- |\n"
    val content = manualChanges.foldLeft(outputTemplate) {(c, summary) =>
      c + s"|[${summary._1}](#${summary._1.split("\\.").lastOption getOrElse ""}) | ${summary._2} manual changes required |\n"
    }
    outputStream.write(content.getBytes("utf8"))
  }

  override def doAccept(event: (String, Int)): Unit = manualChanges get event._1 match {
    case Some(num) => manualChanges += event._1 -> (event._2 + num)
    case None => manualChanges += event._1 -> event._2
  }

  override val sequence = 4
} 
Example 23
Source File: UpgradeSummarySubscriber.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.report.impl

import java.io.OutputStream
import java.util.Optional

import ch.qos.logback.classic.spi.ILoggingEvent
import com.ebay.rtran.report.api.IReportEventSubscriber

import scala.compat.java8.OptionConverters._


class UpgradeSummarySubscriber extends IReportEventSubscriber[(String, Int)] {

  private[this] var ruleSummary = Map.empty[String, Int]

  override def filter(event: scala.Any): Optional[(String, Int)] = {
    val Regex = """Rule (.+) was applied to (\d+).*""".r
    val info = event match {
      case event1: ILoggingEvent =>
        event1.getFormattedMessage match {
          case Regex(rule, num) => Some((rule, num.toInt))
          case _ => None
        }

      case _ => None
    }

    info.asJava
  }

  override def dumpTo(outputStream: OutputStream): Unit = if (ruleSummary.nonEmpty) {
    val outputTemplate = "\r## Summary\n\n| Operation | Details |\n| ---- | ----------- |\n"
    val content = ruleSummary.foldLeft(outputTemplate) {(c, summary) =>
      c + s"|[${summary._1}](#${summary._1.split("\\.").lastOption getOrElse ""}) | impacted ${summary._2} file(s) |\n"
    }
    outputStream.write(content.getBytes("utf8"))
  }

  override def doAccept(event: (String, Int)): Unit = ruleSummary get event._1 match {
    case Some(num) => ruleSummary += event._1 -> (event._2 + num)
    case None => ruleSummary += event._1 -> event._2
  }

  override val sequence = 3
} 
Example 24
Source File: ReportTest.scala    From RTran   with Apache License 2.0 5 votes vote down vote up
package com.ebay.rtran.report

import java.io.{File, FileOutputStream, OutputStream}
import java.util.Optional
import com.typesafe.scalalogging.LazyLogging
import com.ebay.rtran.report.api.IReportEventSubscriber
import org.scalatest.{FlatSpecLike, Matchers}


class ReportTest extends FlatSpecLike with Matchers with LazyLogging {

  "Report" should "accept log event correctly" in {
    val subscriber = new TestSubscriber
    val outputStream = new FileOutputStream("test")
    Report.createReport(outputStream, subscribers = List(subscriber))(testFunc())
    subscriber.getCount should be (3)
    new File("test").delete
  }

  "Report" should "work in concurrent mode" in {
    val subscribers = (1 to 10) map (_ => new TestSubscriber)

    subscribers foreach {sub =>
      new Thread(new TestThread(sub)).start()
    }

    val waitPeriod = 1000

    Thread.sleep(waitPeriod)

    subscribers foreach (_.getCount should be (3))
  }

  class TestThread(subscriber: IReportEventSubscriber[_]) extends Runnable {
    override def run(): Unit = {
      val file = new File(s"test-${System.nanoTime}")
      val outputStream = new FileOutputStream(file)
      Report.createReport(outputStream, subscribers = List(subscriber))(testFunc())
      file.delete
    }
  }

  def testFunc(): Unit = {
    val str = "hello"
    val number = 2000
    logger.info("String {}", str)
    logger.info(s"number ${number + 2}")
    logger.info("String {} number {}", str, number.toString)
  }

  class TestSubscriber extends IReportEventSubscriber[Int] {
    import scala.compat.java8.OptionConverters._

    private var count = 0

    def getCount = count

    override def filter(event: scala.Any): Optional[Int] = Some(1).asJava

    override def dumpTo(outputStream: OutputStream): Unit = {}

    override def doAccept(event: Int): Unit = count += event
  }

} 
Example 25
Source File: KVStoreIndex.scala    From affinity   with Apache License 2.0 5 votes vote down vote up
package io.amient.affinity.core.state

import java.nio.ByteBuffer
import java.util.Optional

import io.amient.affinity.core.serde.AbstractSerde
import io.amient.affinity.core.storage.MemStore
import io.amient.affinity.core.util.{ByteUtils, EventTime, TimeRange}

import scala.collection.JavaConverters._

class KVStoreIndex[K, V](identifier: String,
                         memstore: MemStore,
                         keySerde: AbstractSerde[K],
                         valueSerde: AbstractSerde[V],
                         ttlMs: Long) {

  def option[T](opt: Optional[T]): Option[T] = if (opt.isPresent) Some(opt.get()) else None

  def apply[T](key: K, range: TimeRange = TimeRange.UNBOUNDED)(f: Iterator[V] => T): T = {
    val bytePrefix: ByteBuffer = ByteBuffer.wrap(ByteUtils.intValue(key.hashCode()))
    val underlying = memstore.iterator(bytePrefix)
    try {
      f(underlying.asScala.flatMap { entry =>
        option(memstore.unwrap(entry.getKey(), entry.getValue, ttlMs))
          .filter(byteRecord => range.contains(byteRecord.timestamp))
          .filter(byteRecord => keySerde.fromBytes(byteRecord.value) == key)
          .map { byteRecord =>
            val resultKey = new Array[Byte](byteRecord.key.length - 4)
            ByteUtils.copy(byteRecord.key, 4, resultKey, 0, resultKey.length)
            valueSerde.fromBytes(resultKey)
          }
      })
    } finally {
      underlying.close()
    }
  }

  def numKeys: Long = memstore.numKeys()

  def getStats: String = {
    s"$identifier\n===================================================================\n" +
      s"MemStore[${memstore.getClass.getSimpleName}]\n${memstore.getStats}\n\n"
  }

  def put(k: K, value: V, timestamp: Long, tombstone: Boolean = false): Unit = {

    val bytePrefix = valueSerde.toBytes(value)
    val indexKey = new Array[Byte](4 + bytePrefix.length)
    ByteUtils.putIntValue(k.hashCode(), indexKey, 0)
    ByteUtils.copy(bytePrefix, 0, indexKey, 4, bytePrefix.length)

    //      val timerContext = writesMeter.markStart()
    try {
      if (tombstone || (ttlMs > 0 && timestamp + ttlMs < EventTime.unix)) {
        memstore.remove(ByteBuffer.wrap(indexKey))
      } else {
        memstore.put(ByteBuffer.wrap(indexKey), memstore.wrap(keySerde.toBytes(k), timestamp))
      }
      //      writesMeter.markSuccess(timerContext)
    } catch {
      case e: Throwable =>
        //          writesMeter.markFailure(timerContext)
        throw e
    }
  }

  def close(): Unit = {
    memstore.close()
    //    metrics.remove(s"state.$identifier.keys")
  }

} 
Example 26
Source File: PlayRouter.scala    From play-grpc   with Apache License 2.0 5 votes vote down vote up
package play.grpc.internal

import java.util.Optional
import java.util.concurrent.CompletionStage

import akka.annotation.InternalApi
import akka.dispatch.Dispatchers
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.HttpResponse
import akka.stream.Materializer
import play.api.inject.Injector
import play.api.mvc.Handler
import play.api.mvc.akkahttp.AkkaHttpHandler
import play.api.routing.Router
import play.api.routing.Router.Routes
import play.mvc.Http

import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.compat.java8.FutureConverters._
import scala.compat.java8.OptionConverters._


  final override def withPrefix(prefix: String): Router =
    if (prefix == "/") this
    else
      throw new UnsupportedOperationException(
        "Prefixing gRPC services is not widely supported by clients, " +
          s"strongly discouraged by the specification and therefore not supported. " +
          s"Attempted to prefix with [$prefix], yet already default prefix known to be [${this.prefix}]. " +
          s"When binding gRPC routers the path in `routes` MUST BE `/`.",
      )

} 
Example 27
Source File: GrpcMarshalling.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.javadsl

import java.util.concurrent.{ CompletableFuture, CompletionStage }
import java.util.Optional

import akka.NotUsed
import akka.actor.ActorSystem
import akka.actor.ClassicActorSystemProvider
import akka.grpc._
import akka.grpc.internal.{ CancellationBarrierGraphStage, GrpcResponseHelpers, MissingParameterException }
import akka.grpc.GrpcProtocol.{ GrpcProtocolReader, GrpcProtocolWriter }
import akka.http.javadsl.model.{ HttpRequest, HttpResponse }
import akka.japi.Function
import akka.stream.Materializer
import akka.stream.javadsl.{ Sink, Source }
import akka.util.ByteString

import com.github.ghik.silencer.silent

object GrpcMarshalling {

  def negotiated[T](
      req: HttpRequest,
      f: (GrpcProtocolReader, GrpcProtocolWriter) => CompletionStage[T]): Optional[CompletionStage[T]] =
    GrpcProtocol
      .negotiate(req)
      .map {
        case (maybeReader, writer) =>
          maybeReader.map(reader => f(reader, writer)).fold[CompletionStage[T]](failure, identity)
      }
      .fold(Optional.empty[CompletionStage[T]])(Optional.of)

  def unmarshal[T](
      data: Source[ByteString, AnyRef],
      u: ProtobufSerializer[T],
      mat: Materializer,
      reader: GrpcProtocolReader): CompletionStage[T] =
    data.via(reader.dataFrameDecoder).map(u.deserialize).runWith(Sink.headOption[T], mat).thenCompose[T] { opt =>
      if (opt.isPresent) CompletableFuture.completedFuture(opt.get)
      else failure(new MissingParameterException())
    }

  def unmarshalStream[T](
      data: Source[ByteString, AnyRef],
      u: ProtobufSerializer[T],
      @silent("never used") mat: Materializer,
      reader: GrpcProtocolReader): CompletionStage[Source[T, NotUsed]] = {
    CompletableFuture.completedFuture[Source[T, NotUsed]](
      data
        .mapMaterializedValue(_ => NotUsed)
        .via(reader.dataFrameDecoder)
        .map(japiFunction(u.deserialize))
        // In gRPC we signal failure by returning an error code, so we
        // don't want the cancellation bubbled out
        .via(new CancellationBarrierGraphStage)
        .mapMaterializedValue(japiFunction(_ => NotUsed)))
  }

  def marshal[T](
      e: T,
      m: ProtobufSerializer[T],
      writer: GrpcProtocolWriter,
      system: ClassicActorSystemProvider,
      eHandler: Function[ActorSystem, Function[Throwable, Trailers]] = GrpcExceptionHandler.defaultMapper)
      : HttpResponse =
    marshalStream(Source.single(e), m, writer, system, eHandler)

  def marshalStream[T](
      e: Source[T, NotUsed],
      m: ProtobufSerializer[T],
      writer: GrpcProtocolWriter,
      system: ClassicActorSystemProvider,
      eHandler: Function[ActorSystem, Function[Throwable, Trailers]] = GrpcExceptionHandler.defaultMapper)
      : HttpResponse =
    GrpcResponseHelpers(e.asScala, scalaAnonymousPartialFunction(eHandler))(m, writer, system)

  private def failure[R](error: Throwable): CompletableFuture[R] = {
    val future: CompletableFuture[R] = new CompletableFuture()
    future.completeExceptionally(error)
    future
  }
} 
Example 28
Source File: AkkaHttpSessionStoreTest.scala    From akka-http-pac4j   with Mozilla Public License 2.0 5 votes vote down vote up
package com.stackstate.pac4j.http

import java.util.Optional

import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.stackstate.pac4j.AkkaHttpWebContext
import com.stackstate.pac4j.store.{ForgetfulSessionStorage, InMemorySessionStorage}
import org.scalatest.{Matchers, WordSpecLike}

import scala.concurrent.duration._

class AkkaHttpSessionStoreTest extends WordSpecLike with Matchers with ScalatestRouteTest {
  "AkkaHttpSessionStore.get" should {
    "return null when the data is not available" in {
      new AkkaHttpSessionStore().get(
        new AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME),
        "mykey"
      ) shouldBe Optional.empty()
    }

    "return the data when available" in {
      val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), AkkaHttpWebContext.DEFAULT_COOKIE_NAME)
      new AkkaHttpSessionStore().set(context, "mykey", "yooo")
      new AkkaHttpSessionStore().get(context, "mykey") shouldBe Optional.of("yooo")
    }
  }
} 
Example 29
Source File: JavaConverters.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package akka.http.org.squbs.util

import java.util.Optional

import akka.NotUsed
import akka.http.impl.util.JavaMapping
import akka.http.javadsl.{model => jm}
import akka.http.scaladsl.Http.HostConnectionPool
import akka.http.scaladsl.HttpsConnectionContext
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.settings.ConnectionPoolSettings
import akka.http.{javadsl => jd}
import akka.japi.Pair
import akka.stream.scaladsl.{BidiFlow, Flow}
import akka.stream.{javadsl => js}

import scala.util.Try


object JavaConverters {
  def fromJava(connectionContext: Optional[jd.HttpsConnectionContext],
                                 settings: Optional[jd.settings.ConnectionPoolSettings]):
  (Option[HttpsConnectionContext], Option[ConnectionPoolSettings]) = {
    import scala.compat.java8.OptionConverters._
    val cCtx = connectionContext.asScala.asInstanceOf[Option[HttpsConnectionContext]]
    val sSettings = settings.asScala.asInstanceOf[Option[ConnectionPoolSettings]]
    (cCtx, sSettings)
  }

  def toJava[In1, Out1, In2, Out2, Context](bidiFlow: BidiFlow[(In1, Context), (Out1, Context), (In2, Context), (Out2, Context), NotUsed]):
  js.BidiFlow[Pair[In1, Context], Pair[Out1, Context], Pair[In2, Context], Pair[Out2, Context], NotUsed] = {
    implicit val sIn1Mapping = JavaMapping.identity[In1]
    implicit val sOut1Mapping = JavaMapping.identity[Out1]
    implicit val sIn2Mapping = JavaMapping.identity[In2]
    implicit val sOut2Mapping = JavaMapping.identity[Out2]
    implicit val contextMapping = JavaMapping.identity[Context]
    val javaToScalaAdapter = JavaMapping.adapterBidiFlow[Pair[In1, Context], (In1, Context), (Out2, Context), Pair[Out2, Context]]
    val scalaToJavaAdapter = JavaMapping.adapterBidiFlow[Pair[In2, Context], (In2, Context), (Out1, Context), Pair[Out1, Context]].reversed
    javaToScalaAdapter.atop(bidiFlow).atop(scalaToJavaAdapter).asJava
  }

  private def adaptTupleFlow[T](scalaFlow: Flow[(HttpRequest, T), (Try[HttpResponse], T), HostConnectionPool]):
  js.Flow[Pair[jm.HttpRequest, T], Pair[Try[jm.HttpResponse], T], jd.HostConnectionPool] = {
    implicit val _ = JavaMapping.identity[T]
    implicit object HostConnectionPoolMapping extends JavaMapping[jd.HostConnectionPool, HostConnectionPool] {
      def toScala(javaObject: jd.HostConnectionPool): HostConnectionPool =
        throw new UnsupportedOperationException("jd.HostConnectionPool cannot be converted to Scala")
      def toJava(scalaObject: HostConnectionPool): jd.HostConnectionPool = scalaObject.toJava
    }
    JavaMapping.toJava(scalaFlow)(JavaMapping.flowMapping[Pair[jm.HttpRequest, T], (HttpRequest, T),
      Pair[Try[jm.HttpResponse], T], (Try[HttpResponse], T), jd.HostConnectionPool, HostConnectionPool])
  }

  def toJava[T](flow: Flow[(HttpRequest, T), (Try[HttpResponse], T), HostConnectionPool]):
  js.Flow[Pair[jm.HttpRequest, T], Pair[Try[jm.HttpResponse], T], jd.HostConnectionPool] = {
    adaptTupleFlow[T](flow)
  }

  def toScala(uri: akka.http.javadsl.model.Uri) = JavaMapping.toScala(uri)
} 
Example 30
Source File: FriendEntity.scala    From activator-lagom-scala-chirper   with Apache License 2.0 5 votes vote down vote up
package sample.chirper.friend.impl

import com.lightbend.lagom.javadsl.persistence.PersistentEntity
import scala.collection.JavaConverters._
import akka.Done
import sample.chirper.friend.api.User
import java.util.Optional
import scala.compat.java8.OptionConverters._

class FriendEntity extends PersistentEntity[FriendCommand, FriendEvent, FriendState] {

  override def initialBehavior(snapshotState: Optional[FriendState]): Behavior = {
    val b = newBehaviorBuilder(snapshotState.orElseGet(() => FriendState(Option.empty)))

    b.setCommandHandler(classOf[CreateUser], (cmd: CreateUser, ctx: CommandContext[Done]) => {
      state.user match {
        case Some(_) =>
          ctx.invalidCommand(s"User ${entityId} is already created")
          ctx.done()
        case None =>
          val user = cmd.user
          val events = UserCreated(user.userId, user.name) +: user.friends.map(friendId => FriendAdded(user.userId, friendId))
          ctx.thenPersistAll(events.asJava, () => ctx.reply(Done))
      }
    })

    b.setEventHandler(classOf[UserCreated], (evt: UserCreated) => FriendState(new User(evt.userId, evt.name)))

    b.setCommandHandler(classOf[AddFriend], (cmd: AddFriend, ctx: CommandContext[Done]) => {
      state.user match {
        case None =>
          ctx.invalidCommand(s"User ${entityId} is not  created")
          ctx.done()
        case Some(user) if user.friends.contains(cmd.friendUserId) =>
          ctx.reply(Done)
          ctx.done()
        case Some(user) =>
          ctx.thenPersist(FriendAdded(user.userId, cmd.friendUserId), (evt: FriendAdded) => ctx.reply(Done))
      }
    })

    b.setEventHandler(classOf[FriendAdded], (evt: FriendAdded) => state.addFriend(evt.friendId))

    b.setReadOnlyCommandHandler(classOf[GetUser], (cmd: GetUser, ctx: ReadOnlyCommandContext[GetUserReply]) =>
      ctx.reply(GetUserReply(state.user))
    )

    b.build()
  }

} 
Example 31
Source File: CourierExceptionCompat.scala    From courier   with Apache License 2.0 5 votes vote down vote up
package org.coursera.courier.sbt

import xsbti.{Severity, Problem, Position}
import java.util.Optional
import sbt._

import scala.language.implicitConversions

object CourierExceptionCompat {

  
  class CourierCompilationException(
      source: Option[File],
      message: String,
      atLine: Option[Int],
      column: Option[Int],
      severity: Severity)
      extends xsbti.CompileFailed
      with FeedbackProvidedException {

    def arguments(): Array[String] = Array()
    def problems(): Array[Problem] =
      Array(new CourierCompilationProblem(source, message, atLine, column, severity))
    def line = atLine.map(_.asInstanceOf[java.lang.Integer]).orNull
    def position = column.map(_.asInstanceOf[java.lang.Integer]).orNull
    def sourceName = source.map(_.getAbsolutePath).orNull
  }

  class CourierCompilationProblem(
      source: Option[File],
      msg: String,
      atLine: Option[Int],
      column: Option[Int],
      svrty: Severity)
      extends Problem {
    def category(): String = "Courier"
    def severity(): Severity = svrty
    def message(): String = msg
    def position(): Position = new CourierCompilationErrorPosition(source, atLine, column)
  }

  class CourierCompilationErrorPosition(
      source: Option[File],
      atLine: Option[Int],
      column: Option[Int])
      extends Position {

    def toMaybe[T](option: Option[T]) =
      option.map { optionValue =>
        optionValue
      }.asJava

    def line(): Optional[Integer] = toMaybe(atLine.map(_.asInstanceOf[java.lang.Integer]))
    def lineContent(): String = ""
    def offset(): Optional[Integer] = toMaybe(column.map(_.asInstanceOf[java.lang.Integer]))
    def pointer(): Optional[Integer] = Optional.empty[java.lang.Integer]
    def pointerSpace(): Optional[String] = Optional.empty[String]
    def sourcePath(): Optional[String] = toMaybe(source.map(_.getAbsolutePath))
    def sourceFile(): Optional[File] = toMaybe(source)
  }
} 
Example 32
Source File: apiAdapter.scala    From sbt-idea-plugin   with Apache License 2.0 5 votes vote down vote up
package sbt.jetbrains.ideaPlugin

import java.io.InputStream
import java.nio.file.{Files, Path}

import sbt.File
import sbt.inc._
import java.util.Optional

object apiAdapter {
  type CompileResult = sbt.inc.Analysis
  type BuildDependencies = sbt.BuildDependencies
  val Using = sbt.Using
  def projectJarName(project: sbt.Project): String = s"${project.id}.jar"
  def extractAffectedFiles(initialTimestamp: Long, result: Seq[CompileResult]): Seq[File] = {
    def processCompilation(compileResult: CompileResult): Seq[File] = {
      val lastCompilation = compileResult.compilations.allCompilations.find(_.startTime() >= initialTimestamp).getOrElse(return Seq.empty)
      val startTime       = lastCompilation.startTime()
      val res = compileResult.stamps.products.collect {
        case (f, s:LastModified) if s.value >= startTime => f
      }.toSeq
      res
    }
    val res = result.flatMap(processCompilation)
    res
  }

  object SbtCompilationBackCompat {
    type Analysis         = sbt.inc.Analysis
    type Relations        = sbt.inc.Relations
    type CompileResult    = sbt.Compiler.CompileResult
    type CompileAnalysis  = sbt.inc.Analysis
    type PreviousResult   = sbt.Compiler.PreviousAnalysis
    type ClassFileManager = sbt.inc.ClassfileManager
    type IncOptions       = sbt.inc.IncOptions

    val Analysis = sbt.inc.Analysis

    implicit class CompileResultExt(val result: PreviousResult) extends AnyVal {
      def getAnalysis: Optional[CompileAnalysis] = Optional.of(result.analysis)
    }

    implicit class IncOptionsExt(val options: IncOptions) extends AnyVal {
      def withClassfileManager(manager: ClassFileManager): IncOptions =
        options.withNewClassfileManager(() => manager)
    }

    object PreviousResult {
      def empty(): PreviousResult =
        sbt.Compiler.PreviousAnalysis(Analysis.Empty, None)
    }
  }

  final class PathExt(val path: Path) extends AnyVal {
    import scala.collection.JavaConverters.asScalaIteratorConverter

    def /(string: String): Path = path.resolve(string)
    def list: Seq[Path] = Files.list(path).iterator().asScala.toSeq
    def exists: Boolean = Files.exists(path)
    def isDir: Boolean = Files.isDirectory(path)
    def inputStream: InputStream = Files.newInputStream(path)
  }

} 
Example 33
Source File: apiAdapter.scala    From sbt-idea-plugin   with Apache License 2.0 5 votes vote down vote up
package sbt.jetbrains.ideaPlugin

import java.io.InputStream
import java.nio.file.{Files, Path}
import java.util.Optional

object apiAdapter {
  type CompileResult = Any
  val Using = sbt.io.Using
  type BuildDependencies = sbt.internal.BuildDependencies

  def projectJarName(project: sbt.Project): String = s"${project.id}.jar"
  def extractAffectedFiles(result: CompileResult): Seq[sbt.File] = Seq.empty

  object SbtCompilationBackCompat {
    type Analysis         = sbt.internal.inc.Analysis
    type Relations        = sbt.internal.inc.Relations
    type CompileResult    = xsbti.compile.CompileResult
    type CompileAnalysis  = xsbti.compile.CompileAnalysis
    type PreviousResult   = xsbti.compile.PreviousResult
    type ClassFileManager = xsbti.compile.ClassFileManager
    type IncOptions       = xsbti.compile.IncOptions

    val Analysis = sbt.internal.inc.Analysis

    implicit class CompileResultExt(val result: PreviousResult) extends AnyVal {
      def getAnalysis: Optional[CompileAnalysis] = result.analysis()
    }

    implicit class IncOptionsExt(val options: IncOptions) extends AnyVal {
      def withClassfileManager(manager: ClassFileManager): IncOptions =
        options.withExternalHooks(options.externalHooks().withExternalClassFileManager(manager))
    }

    object PreviousResult {
      def empty(): PreviousResult =
        xsbti.compile.PreviousResult.create(Optional.empty(), Optional.empty())
    }
  }

  // / method is missing because it's already implemented in sbt 1.3 PathOps
  final class PathExt(val path: Path) extends AnyVal {
    import scala.collection.JavaConverters.asScalaIteratorConverter

    def list: Seq[Path] = Files.list(path).iterator().asScala.toSeq
    def exists: Boolean = Files.exists(path)
    def isDir: Boolean = Files.isDirectory(path)
    def inputStream: InputStream = Files.newInputStream(path)
  }
} 
Example 34
Source File: S2GraphVariables.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.core.features

import java.util
import java.util.Optional
import scala.collection.JavaConversions._
import org.apache.tinkerpop.gremlin.structure.Graph

class S2GraphVariables extends Graph.Variables {
  import scala.collection.mutable
  private val variables = mutable.Map.empty[String, Any]

  override def set(key: String, value: scala.Any): Unit = {
    if (key == null) throw Graph.Variables.Exceptions.variableKeyCanNotBeNull()
    if (key.isEmpty) throw Graph.Variables.Exceptions.variableKeyCanNotBeEmpty()
    if (value == null) throw Graph.Variables.Exceptions.variableValueCanNotBeNull()

    variables.put(key, value)
  }

  override def keys(): util.Set[String] = variables.keySet

  override def remove(key: String): Unit = {
    if (key == null) throw Graph.Variables.Exceptions.variableKeyCanNotBeNull()
    if (key.isEmpty) throw Graph.Variables.Exceptions.variableKeyCanNotBeEmpty()

    variables.remove(key)
  }

  override def get[R](key: String): Optional[R] = {
    if (key == null) throw Graph.Variables.Exceptions.variableKeyCanNotBeNull()
    if (key.isEmpty) throw Graph.Variables.Exceptions.variableKeyCanNotBeEmpty()
    variables.get(key) match {
      case None => Optional.empty()
      case Some(value) => if (value == null) Optional.empty() else Optional.of(value.asInstanceOf[R])
    }
  }

  override def toString: String = {
    s"variables[size:${variables.keys.size()}]"
  }
} 
Example 35
Source File: JavaExtraFormatsSpec.scala    From sjson-new   with Apache License 2.0 5 votes vote down vote up
package sjsonnew
package support.spray

import spray.json.{ JsValue, JsNumber, JsString, JsNull, JsTrue, JsFalse, JsObject }
import org.specs2.mutable._
import java.util.{ UUID, Optional }
import java.net.{ URI, URL }
import java.io.File

class JavaExtraFormatsSpec extends Specification with BasicJsonProtocol {
  case class Person(name: Optional[String], value: Optional[Int])
  implicit object PersonFormat extends JsonFormat[Person] {
    def write[J](x: Person, builder: Builder[J]): Unit = {
      builder.beginObject()
      builder.addField("name", x.name)
      builder.addField("value", x.value)
      builder.endObject()
    }
    def read[J](jsOpt: Option[J], unbuilder: Unbuilder[J]): Person =
      jsOpt match {
        case Some(js) =>
          unbuilder.beginObject(js)
          val name = unbuilder.readField[Optional[String]]("name")
          val value = unbuilder.readField[Optional[Int]]("value")
          unbuilder.endObject()
          Person(name, value)
        case None =>
          deserializationError("Expected JsObject but found None")
      }
  }

  "The uuidStringIso" should {
    val uuid = UUID.fromString("abc220ea-2a01-11e6-b67b-9e71128cae77")
    "convert a UUID to JsString" in {
      Converter.toJsonUnsafe(uuid) mustEqual JsString("abc220ea-2a01-11e6-b67b-9e71128cae77")
    }
    "convert the JsString back to the UUID" in {
      Converter.fromJsonUnsafe[UUID](JsString("abc220ea-2a01-11e6-b67b-9e71128cae77")) mustEqual uuid
    }
  }

  "The uriStringIso" should {
    val uri = new URI("http://localhost")
    "convert a URI to JsString" in {
      Converter.toJsonUnsafe(uri) mustEqual JsString("http://localhost")
    }
    "convert the JsString back to the URI" in {
      Converter.fromJsonUnsafe[URI](JsString("http://localhost")) mustEqual uri
    }
  }

  "The urlStringIso" should {
    val url = new URL("http://localhost")
    "convert a URL to JsString" in {
      Converter.toJsonUnsafe(url) mustEqual JsString("http://localhost")
    }
    "convert the JsString back to the URI" in {
      Converter.fromJsonUnsafe[URL](JsString("http://localhost")) mustEqual url
    }
  }

  "The fileStringIso" should {
    val f = new File("/tmp")
    val f2 = new File(new File("src"), "main")
    "convert a File to JsString" in {
      Converter.toJsonUnsafe(f) mustEqual JsString("file:///tmp/")
    }
    "convert a relative path to JsString" in {
      // https://tools.ietf.org/html/rfc3986#section-4.2
      Converter.toJsonUnsafe(f2) mustEqual JsString("src/main")
    }
    "convert the JsString back to the File" in {
      Converter.fromJsonUnsafe[File](JsString("file:///tmp/")) mustEqual f
    }
    "convert the JsString back to the relative path" in {
      Converter.fromJsonUnsafe[File](JsString("src/main")) mustEqual f2
    }
  }

  "The optionalFormat" should {
    "convert Optional.empty to JsNull" in {
      Converter.toJsonUnsafe(Optional.empty[Int]) mustEqual JsNull
    }
    "convert JsNull to None" in {
      Converter.fromJsonUnsafe[Optional[Int]](JsNull) mustEqual Optional.empty[Int]
    }
    "convert Some(Hello) to JsString(Hello)" in {
      Converter.toJsonUnsafe(Optional.of("Hello")) mustEqual JsString("Hello")
    }
    "convert JsString(Hello) to Some(Hello)" in {
      Converter.fromJsonUnsafe[Optional[String]](JsString("Hello")) mustEqual Optional.of("Hello")
    }
    "omit None fields" in {
      Converter.toJsonUnsafe(Person(Optional.empty[String], Optional.empty[Int])) mustEqual JsObject()
    }
  }
} 
Example 36
Source File: JsonJacksonMarshallerTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.json

import java.time.LocalDateTime
import java.util.Optional

import com.fasterxml.jackson.databind.ObjectMapper
import com.wix.e2e.http.api.Marshaller
import com.wix.e2e.http.json.MarshallingTestObjects.SomeCaseClass
import com.wix.test.random._
import org.joda.time.DateTimeZone.UTC
import org.joda.time.{DateTime, DateTimeZone}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class JsonJacksonMarshallerTest extends Spec {

  trait ctx extends Scope {
    val someStr = randomStr
    val javaDateTime = LocalDateTime.now()
    val someCaseClass = SomeCaseClass(randomStr, randomInt)
    val dateTime = new DateTime
    val dateTimeUTC = new DateTime(UTC)

    val marshaller: Marshaller = new JsonJacksonMarshaller
  }


  "JsonJacksonMarshaller" should {

    "marshall scala option properly" in new ctx {
      marshaller.unmarshall[Option[String]](
        marshaller.marshall( Some(someStr) )
      ) must beSome(someStr)
    }

    "marshall scala case classes properly" in new ctx {
      marshaller.unmarshall[SomeCaseClass](
        marshaller.marshall( someCaseClass )
      ) must_=== someCaseClass
    }

    "marshall datetime without zone" in new ctx {
      marshaller.unmarshall[DateTime](
        marshaller.marshall( dateTime.withZone(DateTimeZone.getDefault) )
      ) must_=== dateTime.withZone(UTC)
    }

    "marshall date time to textual format in UTC" in new ctx {
      marshaller.marshall( dateTime ) must contain(dateTime.withZone(UTC).toString)
    }


    "marshall java.time objects" in new ctx {
      marshaller.unmarshall[LocalDateTime](
        marshaller.marshall( javaDateTime )
      ) must_=== javaDateTime

    }

    "marshall java 8 Optional" in new ctx {
      marshaller.unmarshall[Optional[DateTime]](
        marshaller.marshall( dateTimeUTC )
      ) must_=== Optional.of(dateTimeUTC)

      marshaller.unmarshall[Optional[SomeCaseClass]](
        marshaller.marshall( someCaseClass )
      ) must_=== Optional.of(someCaseClass)
    }

    "expose jackson object mapper to allow external configuration" in new ctx {
      marshaller.asInstanceOf[JsonJacksonMarshaller].configure must beAnInstanceOf[ObjectMapper]
    }
  }
}

object MarshallingTestObjects {
  case class SomeCaseClass(s: String, i: Int)
} 
Example 37
Source File: RateStreamProvider.scala    From XSQL   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.sql.execution.streaming.sources

import java.util.Optional

import org.apache.spark.network.util.JavaUtils
import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.execution.streaming.continuous.RateStreamContinuousReader
import org.apache.spark.sql.sources.DataSourceRegister
import org.apache.spark.sql.sources.v2._
import org.apache.spark.sql.sources.v2.reader.streaming.{ContinuousReader, MicroBatchReader}
import org.apache.spark.sql.types._


  def valueAtSecond(seconds: Long, rowsPerSecond: Long, rampUpTimeSeconds: Long): Long = {
    // E.g., rampUpTimeSeconds = 4, rowsPerSecond = 10
    // Then speedDeltaPerSecond = 2
    //
    // seconds   = 0 1 2  3  4  5  6
    // speed     = 0 2 4  6  8 10 10 (speedDeltaPerSecond * seconds)
    // end value = 0 2 6 12 20 30 40 (0 + speedDeltaPerSecond * seconds) * (seconds + 1) / 2
    val speedDeltaPerSecond = rowsPerSecond / (rampUpTimeSeconds + 1)
    if (seconds <= rampUpTimeSeconds) {
      // Calculate "(0 + speedDeltaPerSecond * seconds) * (seconds + 1) / 2" in a special way to
      // avoid overflow
      if (seconds % 2 == 1) {
        (seconds + 1) / 2 * speedDeltaPerSecond * seconds
      } else {
        seconds / 2 * speedDeltaPerSecond * (seconds + 1)
      }
    } else {
      // rampUpPart is just a special case of the above formula: rampUpTimeSeconds == seconds
      val rampUpPart = valueAtSecond(rampUpTimeSeconds, rowsPerSecond, rampUpTimeSeconds)
      rampUpPart + (seconds - rampUpTimeSeconds) * rowsPerSecond
    }
  }
} 
Example 38
Source File: SigProofTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen

import java.io.{BufferedReader, File, FileReader}
import java.util.Optional
import java.{lang, util}

import com.horizen.box.WithdrawalRequestBox
import com.horizen.box.data.WithdrawalRequestBoxData
import com.horizen.cryptolibprovider.{SchnorrFunctionsImplZendoo, ThresholdSignatureCircuitImplZendoo}
import com.horizen.proposition.MCPublicKeyHashProposition
import com.horizen.schnorrnative.SchnorrSecretKey
import com.horizen.utils.BytesUtils
import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.{Ignore, Test}

import scala.collection.JavaConverters._
import scala.util.Random

class SigProofTest {
  private val classLoader: ClassLoader = getClass.getClassLoader
  private val sigCircuit: ThresholdSignatureCircuitImplZendoo = new ThresholdSignatureCircuitImplZendoo()
  private val schnorrFunctions: SchnorrFunctionsImplZendoo = new SchnorrFunctionsImplZendoo()

  private def buildSchnorrPrivateKey(index: Int): SchnorrSecretKey = {
    var bytes: Array[Byte] = null
    try {
      val resourceName = "schnorr_sk0"+ index + "_hex"
      val file = new FileReader(classLoader.getResource(resourceName).getFile)
      bytes = BytesUtils.fromHexString(new BufferedReader(file).readLine())
    }
    catch {
      case e: Exception =>
        assertEquals(e.toString(), true, false)
    }

    SchnorrSecretKey.deserialize(bytes)
  }

  //Test will take around 2 minutes, enable for sanity checking of ThresholdSignatureCircuit
  @Ignore
  @Test
  def simpleCheck(): Unit = {
    val keyPairsLen = 7
    val threshold = 5 //hardcoded value

    val keyPairs = (0 until keyPairsLen).view.map(buildSchnorrPrivateKey).map(secret => (secret, secret.getPublicKey))
    val publicKeysBytes: util.List[Array[Byte]] = keyPairs.map(_._2.serializePublicKey()).toList.asJava
    val provingKeyPath = new File(classLoader.getResource("sample_proving_key_7_keys_with_threshold_5").getFile).getAbsolutePath;
    val verificationKeyPath = new File(classLoader.getResource("sample_vk_7_keys_with_threshold_5").getFile).getAbsolutePath;

    val sysConstant = sigCircuit.generateSysDataConstant(publicKeysBytes, threshold)

    val mcBlockHash = Array.fill(32)(Random.nextInt().toByte)
    val previousMcBlockHash = Array.fill(32)(Random.nextInt().toByte)

    val wb: util.List[WithdrawalRequestBox] = Seq(new WithdrawalRequestBox(new WithdrawalRequestBoxData(new MCPublicKeyHashProposition(Array.fill(20)(Random.nextInt().toByte)), 2345), 42)).asJava

    val messageToBeSigned = sigCircuit.generateMessageToBeSigned(wb, mcBlockHash, previousMcBlockHash)

    val emptySigs = List.fill[Optional[Array[Byte]]](keyPairsLen - threshold)(Optional.empty[Array[Byte]]())
    val signatures: util.List[Optional[Array[Byte]]] = (keyPairs
      .map{case (secret, public) => schnorrFunctions.sign(secret.serializeSecretKey(), public.serializePublicKey(), messageToBeSigned)}
      .map(b => Optional.of(b))
      .take(threshold)
      .toList ++ emptySigs)
      .asJava

    val proofAndQuality: utils.Pair[Array[Byte], lang.Long] = sigCircuit.createProof(wb, mcBlockHash, previousMcBlockHash, publicKeysBytes, signatures, threshold, provingKeyPath)

    val result = sigCircuit.verifyProof(wb, mcBlockHash, previousMcBlockHash, proofAndQuality.getValue, proofAndQuality.getKey, sysConstant, verificationKeyPath)

    assertTrue("Proof verification expected to be successfully", result)
  }

} 
Example 39
Source File: IODBStoreAdapter.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.storage

import java.util.{ArrayList => JArrayList, List => JList}
import java.util.Optional
import com.horizen.utils.Pair

import scala.collection.JavaConverters._

import io.iohk.iodb.Store
import com.horizen.utils.ByteArrayWrapper

import scala.collection.mutable.ArrayBuffer

class IODBStoreAdapter (store : Store)
  extends Storage {

  override def get(key: ByteArrayWrapper): Optional[ByteArrayWrapper] = {
    val value = store.get(key)
    if (value.isEmpty)
      Optional.empty()
    else
      Optional.of(new ByteArrayWrapper(value.get))
  }

  override def getOrElse(key: ByteArrayWrapper, defaultValue: ByteArrayWrapper): ByteArrayWrapper = {
    val value = store.get(key)
    if (value.isEmpty)
      defaultValue
    else
      new ByteArrayWrapper(value.get)
  }

  override def get(keys: JList[ByteArrayWrapper]): JList[Pair[ByteArrayWrapper, Optional[ByteArrayWrapper]]] = {
    val keysList = new ArrayBuffer[ByteArrayWrapper]()
    val valList = store.get(keys.asScala)
    val values = new JArrayList[Pair[ByteArrayWrapper,Optional[ByteArrayWrapper]]]()

    for (v <- valList)
      if (v._2.isDefined)
        values.add(new Pair[ByteArrayWrapper,Optional[ByteArrayWrapper]](new ByteArrayWrapper(v._1),
          Optional.of(new ByteArrayWrapper(v._2.get))))
      else
        values.add(new Pair[ByteArrayWrapper,Optional[ByteArrayWrapper]](new ByteArrayWrapper(v._1),
          Optional.empty()))

    values
  }

  override def getAll: JList[Pair[ByteArrayWrapper, ByteArrayWrapper]] = {
    val values = new JArrayList[Pair[ByteArrayWrapper,ByteArrayWrapper]]()

    for ( i <- store.getAll())
      values.add(new Pair[ByteArrayWrapper,ByteArrayWrapper](new ByteArrayWrapper(i._1),
        new ByteArrayWrapper(i._2)))

    values
  }

  override def lastVersionID(): Optional[ByteArrayWrapper] = {
    val value = store.lastVersionID
    if (value.isEmpty)
      Optional.empty()
    else
      Optional.of(new ByteArrayWrapper(value.get))
  }

  override def update(version: ByteArrayWrapper, toUpdate: JList[Pair[ByteArrayWrapper, ByteArrayWrapper]],
                      toRemove: JList[ByteArrayWrapper]): Unit = {

    val listToUpdate = new ArrayBuffer[Tuple2[ByteArrayWrapper,ByteArrayWrapper]]()

    for (r <- toUpdate.asScala) {
      listToUpdate.append(new Tuple2[ByteArrayWrapper, ByteArrayWrapper](r.getKey, r.getValue))
    }

    store.update(version, toRemove.asScala, listToUpdate)
  }

  override def rollback(version : ByteArrayWrapper): Unit = {
    store.rollback(version)
  }

  override def rollbackVersions(): JList[ByteArrayWrapper] = {
    val versions = store.rollbackVersions()
    val value = new JArrayList[ByteArrayWrapper]()
    for (v <- versions)
      value.add(new ByteArrayWrapper(v))

    value
  }

  override def isEmpty(): Boolean = !lastVersionID().isPresent

  override def close(): Unit = {
    store.close()
  }
} 
Example 40
Source File: SidechainWalletTransactionStorage.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.storage

import java.util.Optional
import java.util.{ArrayList => JArrayList, List => JList}

import com.horizen.utils.{Pair => JPair}

import scala.collection.JavaConverters._
import com.horizen.SidechainTypes
import com.horizen.companion.SidechainTransactionsCompanion
import com.horizen.utils.ByteArrayWrapper
import scorex.crypto.hash.Blake2b256
import scorex.util.{ModifierId, ScorexLogging, idToBytes}

import scala.util.{Failure, Success, Try}

class SidechainWalletTransactionStorage (storage : Storage, sidechainTransactionsCompanion: SidechainTransactionsCompanion)
extends SidechainTypes
with ScorexLogging
{
  // Version - block Id
  // Key - byte array transaction Id
  // No remove operation

  require(storage != null, "Storage must be NOT NULL.")
  require(sidechainTransactionsCompanion != null, "SidechainTransactionsCompanion must be NOT NULL.")

  def calculateKey(transactionId : Array[Byte]) : ByteArrayWrapper = {
    new ByteArrayWrapper(Blake2b256.hash(transactionId))
  }

  def get (transactionId : Array[Byte]) : Option[SidechainTypes#SCBT] = {
    storage.get(calculateKey(transactionId)) match {
      case v if v.isPresent => {
        sidechainTransactionsCompanion.parseBytesTry(v.get().data) match {
          case Success(transaction) => Option(transaction.asInstanceOf[SidechainTypes#SCBT])
          case Failure(exception) => {
            log.error("Error while Transaction parsing.", exception)
            Option.empty
          }
        }
      }
      case _ => Option.empty
    }
  }


  def update (version : ByteArrayWrapper, transactionUpdateList : Seq[SidechainTypes#SCBT]) : Try[SidechainWalletTransactionStorage] = Try {
    require(transactionUpdateList != null, "List of Transactions to add/update must be NOT NULL. Use empty List instead.")
    require(!transactionUpdateList.contains(null), "Transactions to add/update must be NOT NULL.")

    val updateList = new JArrayList[JPair[ByteArrayWrapper,ByteArrayWrapper]]()

    for (tx <- transactionUpdateList)
      updateList.add(new JPair[ByteArrayWrapper, ByteArrayWrapper](calculateKey(idToBytes(ModifierId @@ tx.id)),
        new ByteArrayWrapper(sidechainTransactionsCompanion.toBytes(tx))))

    storage.update(version,
      updateList,
      new JArrayList[ByteArrayWrapper]())

    this
  }

  def lastVersionId : Optional[ByteArrayWrapper] = {
    storage.lastVersionID()
  }

  def rollbackVersions : List[ByteArrayWrapper] = {
    storage.rollbackVersions().asScala.toList
  }

  def rollback (version : ByteArrayWrapper) : Try[SidechainWalletTransactionStorage] = Try {
    require(version != null, "Version to rollback to must be NOT NULL.")
    storage.rollback(version)
    this
  }

  def isEmpty: Boolean = storage.isEmpty

} 
Example 41
Source File: OptionalsSpec.scala    From sonar-scala   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.mwz.sonar.scala
package util
package syntax

import java.util.Optional

import Optionals._
import org.scalatest.OptionValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class OptionalsSpec extends AnyFlatSpec with Matchers with OptionValues {
  it should "convert Java Optional to Scala Option" in {
    Optional.of("test").toOption.value shouldBe "test"
    Optional.empty[String].toOption shouldBe empty
  }

  it should "convert Scala Option to Java Optional" in {
    Some("test").toOptional shouldBe Optional.of("test")
    None.toOptional shouldBe Optional.empty
  }
} 
Example 42
Source File: DefaultSource.scala    From spark-cdm   with MIT License 5 votes vote down vote up
package com.microsoft.cdm

import java.util.Optional

import com.microsoft.cdm.read.CDMDataSourceReader
import com.microsoft.cdm.utils.{AADProvider, ADLGen2Provider, Constants, DataConverter}
import com.microsoft.cdm.write.CDMDataSourceWriter
import org.apache.spark.sql.SaveMode
import org.apache.spark.sql.sources.v2._
import org.apache.spark.sql.sources.v2.writer.DataSourceWriter
import org.apache.spark.sql.types.StructType


  def createWriter(jobId: String,
                   schema: StructType,
                   mode: SaveMode,
                   options: DataSourceOptions): Optional[DataSourceWriter] = {
    val modelDirectory = options.get("cdmFolder").get()
    val modelName = options.get("cdmModelName").get()
    val entity = options.get("entity").get()

    Optional.of(new CDMDataSourceWriter(jobId,
      schema, mode, getDataStorage(options), modelDirectory, modelName, entity, new DataConverter()))
  }
} 
Example 43
Source File: JavaExtraFormats.scala    From sjson-new   with Apache License 2.0 5 votes vote down vote up
package sjsonnew

import java.util.{ UUID, Optional }
import java.net.{ URI, URL }
import java.io.File
import java.math.{ BigInteger, BigDecimal => JBigDecimal }

trait JavaExtraFormats {
  this: PrimitiveFormats with AdditionalFormats with IsoFormats =>

  private[this] type JF[A] = JsonFormat[A] // simple alias for reduced verbosity

  implicit val javaBigIntegerFormat: JF[BigInteger] =
    projectFormat[BigInteger, BigInt](BigInt.apply, _.bigInteger)

  implicit val javaBigDecimalFormat: JF[JBigDecimal] =
    projectFormat[JBigDecimal, BigDecimal](BigDecimal.apply, _.bigDecimal)

  implicit val uuidStringIso: IsoString[UUID] = IsoString.iso[UUID](
    _.toString, UUID.fromString)
  implicit val uriStringIso: IsoString[URI] = IsoString.iso[URI](
    _.toASCIIString, new URI(_))
  implicit val urlStringIso: IsoString[URL] = IsoString.iso[URL](
    _.toURI.toASCIIString, (s: String) => (new URI(s)).toURL)

  private[this] final val FileScheme = "file"

  implicit val fileStringIso: IsoString[File] = IsoString.iso[File](
    (f: File) => {
      if (f.isAbsolute) {
        f.toPath.toUri.toASCIIString
      } else {
        new URI(null, normalizeName(f.getPath), null).toASCIIString
      }
    },
    (s: String) => uriToFile(new URI(s)))

  private[this] def normalizeName(name: String) = {
    val sep = File.separatorChar
    if (sep == '/') name else name.replace(sep, '/')
  }

  private[this] def uriToFile(uri: URI): File = {
    val part = uri.getSchemeSpecificPart
    // scheme might be omitted for relative URI reference.
    assert(
      Option(uri.getScheme) match {
        case None | Some(FileScheme) => true
        case _                       => false
      },
      s"Expected protocol to be '$FileScheme' or empty in URI $uri"
    )
    Option(uri.getAuthority) match {
      case None if part startsWith "/" => new File(uri)
      case _                           =>
        if (!(part startsWith "/") && (part contains ":")) new File("//" + part)
        else new File(part)
    }
  }

  implicit def optionalFormat[A :JF]: JF[Optional[A]] = new OptionalFormat[A]
  final class OptionalFormat[A :JF] extends JF[Optional[A]] {
    lazy val elemFormat = implicitly[JF[A]]
    def write[J](o: Optional[A], builder: Builder[J]): Unit =
      if (o.isPresent) elemFormat.write(o.get, builder)
      else builder.writeNull
    override def addField[J](name: String, o: Optional[A], builder: Builder[J]): Unit =
      if (o.isPresent) {
        builder.addFieldName(name)
        write(o, builder)
      } else ()
    def read[J](jsOpt: Option[J], unbuilder: Unbuilder[J]): Optional[A] =
      jsOpt match {
        case Some(js) =>
          if (unbuilder.isJnull(js)) Optional.empty[A]
          else Optional.ofNullable(elemFormat.read(jsOpt, unbuilder))
        case None => Optional.empty[A]
      }
  }
} 
Example 44
Source File: HttpProxy.scala    From embulk-output-s3_parquet   with MIT License 5 votes vote down vote up
package org.embulk.output.s3_parquet.aws

import java.util.Optional

import com.amazonaws.{ClientConfiguration, Protocol}
import org.embulk.config.{Config, ConfigDefault, ConfigException}
import org.embulk.output.s3_parquet.aws.HttpProxy.Task

object HttpProxy {

  trait Task {

    @Config("host")
    @ConfigDefault("null")
    def getHost: Optional[String]

    @Config("port")
    @ConfigDefault("null")
    def getPort: Optional[Int]

    @Config("protocol")
    @ConfigDefault("\"https\"")
    def getProtocol: String

    @Config("user")
    @ConfigDefault("null")
    def getUser: Optional[String]

    @Config("password")
    @ConfigDefault("null")
    def getPassword: Optional[String]

  }

  def apply(task: Task): HttpProxy = {
    new HttpProxy(task)
  }

}

class HttpProxy(task: Task) {

  def configureClientConfiguration(cc: ClientConfiguration): Unit = {
    task.getHost.ifPresent(v => cc.setProxyHost(v))
    task.getPort.ifPresent(v => cc.setProxyPort(v))

    Protocol.values.find(p => p.name().equals(task.getProtocol)) match {
      case Some(v) =>
        cc.setProtocol(v)
      case None =>
        throw new ConfigException(
          s"'${task.getProtocol}' is unsupported: `protocol` must be one of [${Protocol.values
            .map(v => s"'$v'")
            .mkString(", ")}]."
        )
    }

    task.getUser.ifPresent(v => cc.setProxyUsername(v))
    task.getPassword.ifPresent(v => cc.setProxyPassword(v))
  }
} 
Example 45
Source File: AwsClientConfiguration.scala    From embulk-output-s3_parquet   with MIT License 5 votes vote down vote up
package org.embulk.output.s3_parquet.aws

import java.util.Optional

import com.amazonaws.ClientConfiguration
import com.amazonaws.client.builder.AwsClientBuilder
import org.embulk.config.{Config, ConfigDefault}
import org.embulk.output.s3_parquet.aws.AwsClientConfiguration.Task

object AwsClientConfiguration {

  trait Task {

    @Config("http_proxy")
    @ConfigDefault("null")
    def getHttpProxy: Optional[HttpProxy.Task]

  }

  def apply(task: Task): AwsClientConfiguration = {
    new AwsClientConfiguration(task)
  }
}

class AwsClientConfiguration(task: Task) {

  def configureAwsClientBuilder[S <: AwsClientBuilder[S, T], T](
      builder: AwsClientBuilder[S, T]
  ): Unit = {
    task.getHttpProxy.ifPresent { v =>
      val cc = new ClientConfiguration
      HttpProxy(v).configureClientConfiguration(cc)
      builder.setClientConfiguration(cc)
    }
  }

} 
Example 46
Source File: AwsS3Configuration.scala    From embulk-output-s3_parquet   with MIT License 5 votes vote down vote up
package org.embulk.output.s3_parquet.aws

import java.util.Optional

import com.amazonaws.services.s3.AmazonS3ClientBuilder
import org.embulk.config.{Config, ConfigDefault}
import org.embulk.output.s3_parquet.aws.AwsS3Configuration.Task


object AwsS3Configuration {

  trait Task {

    @Config("accelerate_mode_enabled")
    @ConfigDefault("null")
    def getAccelerateModeEnabled: Optional[Boolean]

    @Config("chunked_encoding_disabled")
    @ConfigDefault("null")
    def getChunkedEncodingDisabled: Optional[Boolean]

    @Config("dualstack_enabled")
    @ConfigDefault("null")
    def getDualstackEnabled: Optional[Boolean]

    @Config("force_global_bucket_access_enabled")
    @ConfigDefault("null")
    def getForceGlobalBucketAccessEnabled: Optional[Boolean]

    @Config("path_style_access_enabled")
    @ConfigDefault("null")
    def getPathStyleAccessEnabled: Optional[Boolean]

    @Config("payload_signing_enabled")
    @ConfigDefault("null")
    def getPayloadSigningEnabled: Optional[Boolean]

  }

  def apply(task: Task): AwsS3Configuration = {
    new AwsS3Configuration(task)
  }
}

class AwsS3Configuration(task: Task) {

  def configureAmazonS3ClientBuilder(builder: AmazonS3ClientBuilder): Unit = {
    task.getAccelerateModeEnabled.ifPresent(v =>
      builder.setAccelerateModeEnabled(v)
    )
    task.getChunkedEncodingDisabled.ifPresent(v =>
      builder.setChunkedEncodingDisabled(v)
    )
    task.getDualstackEnabled.ifPresent(v => builder.setDualstackEnabled(v))
    task.getForceGlobalBucketAccessEnabled.ifPresent(v =>
      builder.setForceGlobalBucketAccessEnabled(v)
    )
    task.getPathStyleAccessEnabled.ifPresent(v =>
      builder.setPathStyleAccessEnabled(v)
    )
    task.getPayloadSigningEnabled.ifPresent(v =>
      builder.setPayloadSigningEnabled(v)
    )
  }

} 
Example 47
Source File: AwsEndpointConfiguration.scala    From embulk-output-s3_parquet   with MIT License 5 votes vote down vote up
package org.embulk.output.s3_parquet.aws

import java.util.Optional

import com.amazonaws.client.builder.AwsClientBuilder
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
import com.amazonaws.regions.{DefaultAwsRegionProviderChain, Regions}
import org.embulk.config.{Config, ConfigDefault}
import org.embulk.output.s3_parquet.aws.AwsEndpointConfiguration.Task

import scala.util.Try

object AwsEndpointConfiguration {

  trait Task {

    @Config("endpoint")
    @ConfigDefault("null")
    def getEndpoint: Optional[String]

    @Config("region")
    @ConfigDefault("null")
    def getRegion: Optional[String]

  }

  def apply(task: Task): AwsEndpointConfiguration = {
    new AwsEndpointConfiguration(task)
  }
}

class AwsEndpointConfiguration(task: Task) {

  def configureAwsClientBuilder[S <: AwsClientBuilder[S, T], T](
      builder: AwsClientBuilder[S, T]
  ): Unit = {
    if (task.getRegion.isPresent && task.getEndpoint.isPresent) {
      val ec =
        new EndpointConfiguration(task.getEndpoint.get, task.getRegion.get)
      builder.setEndpointConfiguration(ec)
    }
    else if (task.getRegion.isPresent && !task.getEndpoint.isPresent) {
      builder.setRegion(task.getRegion.get)
    }
    else if (!task.getRegion.isPresent && task.getEndpoint.isPresent) {
      val r: String = Try(new DefaultAwsRegionProviderChain().getRegion)
        .getOrElse(Regions.DEFAULT_REGION.getName)
      val e: String = task.getEndpoint.get
      val ec = new EndpointConfiguration(e, r)
      builder.setEndpointConfiguration(ec)
    }
  }

} 
Example 48
Source File: ConsoleSize.scala    From spark-tools   with Apache License 2.0 5 votes vote down vote up
package io.univalence.parka

import java.util.Optional
import org.jline.terminal.{ Size, TerminalBuilder }

case class ConsoleSize(columns: Int, rows: Int)

object ConsoleSize {

  val default = ConsoleSize(80, 25)

  def get: ConsoleSize =
    if (isInsideTrueTerminal) fromJline(TerminalBuilder.terminal().getSize)
    else default

  private def fromJline(size: Size) = ConsoleSize(size.getColumns, size.getRows)

  private def isInsideTrueTerminal: Boolean =
    (for {
      inIntelliJ <- isInsideIntelliJ
    } yield isInsideEmacs || !inIntelliJ).getOrElse(false)

  private def isInsideEmacs: Boolean = System.getenv("INSIDE_EMACS") != null

  
  private def isInsideIntelliJ: Option[Boolean] =
    try {
      // java.lang.ProcessHandle is defined in Java 9+ and not in Java 8 or before. So reflexion is mandatory here.
      val phClass    = Class.forName("java.lang.ProcessHandle")
      val current    = phClass.getMethod("current").invoke(null)
      val parent     = phClass.getMethod("parent").invoke(current).asInstanceOf[Optional[AnyRef]].orElse(null)
      val infoMethod = phClass.getMethod("info")
      val info       = infoMethod.invoke(parent)
      val command =
        infoMethod.getReturnType.getMethod("command").invoke(info).asInstanceOf[Optional[String]].orElse(null)

      Some(command != null && command.contains("idea"))
    } catch {
      case _: Throwable => None
    }
} 
Example 49
Source File: TemplateClassSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.codegen.backend.java.inner

import java.util.Optional

import com.daml.ledger.javaapi
import com.squareup.javapoet.{ClassName, ParameterizedTypeName, TypeName}
import javax.lang.model.element.Modifier
import org.scalatest.{FlatSpec, Matchers, OptionValues, TryValues}

import scala.collection.JavaConverters.iterableAsScalaIterableConverter

final class TemplateClassSpec extends FlatSpec with Matchers with OptionValues with TryValues {

  behavior of "TemplateClass.generateFromIdAndRecord"

  it should "generate a public static method" in {
    fromIdAndRecord.modifiers.asScala should contain only (Modifier.STATIC, Modifier.PUBLIC)
  }

  it should "generate a method returning the class itself" in {
    fromIdAndRecord.returnType shouldEqual className
  }

  it should "generate a method taking the expected parameters (with contract key)" in {
    val parameters = fromIdAndRecord.parameters.asScala.map(p => p.name -> p.`type`).toList
    parameters should contain theSameElementsInOrderAs Seq(
      "contractId" -> string,
      "record$" -> record,
      "agreementText" -> optionalString,
      "key" -> optionalContractKey,
      "signatories" -> setOfStrings,
      "observers" -> setOfStrings
    )
  }

  it should "generate a method taking the expected parameters (without contract key)" in {
    val parameters =
      fromIdAndRecordWithoutKey.parameters.asScala.map(p => p.name -> p.`type`).toList
    parameters should contain theSameElementsInOrderAs Seq(
      "contractId" -> string,
      "record$" -> record,
      "agreementText" -> optionalString,
      "signatories" -> setOfStrings,
      "observers" -> setOfStrings)
  }

  private[this] val className = ClassName.bestGuess("Test")
  private[this] val templateClassName = ClassName.bestGuess("Template")
  private[this] val idClassName = ClassName.bestGuess("Id")
  private[this] val ckClassName = ClassName.bestGuess("Ck")
  private[this] val fromIdAndRecord =
    TemplateClass.generateFromIdAndRecord(
      className,
      templateClassName,
      idClassName,
      Some(ckClassName))
  private[this] val fromIdAndRecordWithoutKey =
    TemplateClass.generateFromIdAndRecord(className, templateClassName, idClassName, None)
  private[this] val string = TypeName.get(classOf[String])
  private[this] val record = TypeName.get(classOf[javaapi.data.Record])
  private[this] val optionalString =
    ParameterizedTypeName.get(classOf[Optional[_]], classOf[String])
  private[this] val optionalContractKey =
    ParameterizedTypeName.get(ClassName.get(classOf[Optional[_]]), ckClassName)
  private[this] val setOfStrings =
    ParameterizedTypeName.get(classOf[java.util.Set[_]], classOf[String])

} 
Example 50
Source File: DataLayerHelpers.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.rxjava.grpc.helpers

import java.util.Optional

import com.daml.ledger.javaapi.data._
import com.daml.ledger.api.v1.active_contracts_service.GetActiveContractsResponse
import com.daml.ledger.api.v1.command_completion_service.CompletionEndResponse
import com.daml.ledger.api.v1.event.CreatedEvent
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset.Value.Absolute
import com.daml.ledger.api.v1.testing.time_service.GetTimeResponse
import com.google.protobuf.timestamp.Timestamp

import scala.collection.JavaConverters._

trait DataLayerHelpers {

  def ledgerServices: LedgerServices

  def genGetActiveContractsResponse: GetActiveContractsResponse = {
    new GetActiveContractsResponse(
      "",
      "workflowId",
      Seq[CreatedEvent](),
      None
    )
  }

  def genGetTimeResponse: GetTimeResponse = {
    new GetTimeResponse(Some(Timestamp(1l, 2)))
  }

  def genCommands(commands: List[Command], party: Option[String] = None): SubmitCommandsRequest = {
    new SubmitCommandsRequest(
      "workflowId",
      "applicationId",
      "commandId",
      party.getOrElse("party"),
      Optional.empty(),
      Optional.empty(),
      Optional.empty(),
      commands.asJava)
  }
  def genLedgerOffset(absVal: String): LedgerOffset =
    new LedgerOffset(Absolute(absVal))

  def genCompletionEndResponse(absVal: String): CompletionEndResponse =
    new CompletionEndResponse(Some(genLedgerOffset(absVal)))

  val filterNothing: FiltersByParty = new FiltersByParty(Map[String, Filter]().asJava)

  def filterFor(party: String): FiltersByParty =
    new FiltersByParty(
      Map(party -> new InclusiveFilter(Set.empty[Identifier].asJava).asInstanceOf[Filter]).asJava)
} 
Example 51
Source File: RDBDataTypeConverter.scala    From ohara   with Apache License 2.0 5 votes vote down vote up
package oharastream.ohara.connector.jdbc.datatype

import java.sql.{Date, ResultSet, Time, Timestamp}
import java.util.Optional

import oharastream.ohara.client.configurator.InspectApi.RdbColumn
import oharastream.ohara.connector.jdbc.util.DateTimeUtils

trait RDBDataTypeConverter {
  
  def converterValue(resultSet: ResultSet, column: RdbColumn): Any = {
    val columnName             = column.name
    val typeName               = column.dataType.toUpperCase
    val dataType: DataTypeEnum = converterDataType(column)
    dataType match {
      case DataTypeEnum.INTEGER =>
        java.lang.Integer.valueOf(resultSet.getInt(columnName))
      case DataTypeEnum.LONG =>
        java.lang.Long.valueOf(resultSet.getLong(columnName))
      case DataTypeEnum.BOOLEAN =>
        java.lang.Boolean.valueOf(resultSet.getBoolean(columnName))
      case DataTypeEnum.FLOAT =>
        java.lang.Float.valueOf(resultSet.getFloat(columnName))
      case DataTypeEnum.DOUBLE =>
        java.lang.Double.valueOf(resultSet.getDouble(columnName))
      case DataTypeEnum.BIGDECIMAL =>
        Optional.ofNullable(resultSet.getBigDecimal(columnName)).orElseGet(() => new java.math.BigDecimal(0L))
      case DataTypeEnum.STRING =>
        Optional.ofNullable(resultSet.getString(columnName)).orElseGet(() => "null")
      case DataTypeEnum.DATE =>
        Optional.ofNullable(resultSet.getDate(columnName, DateTimeUtils.CALENDAR)).orElseGet(() => new Date(0))
      case DataTypeEnum.TIME =>
        Optional.ofNullable(resultSet.getTime(columnName, DateTimeUtils.CALENDAR)).orElseGet(() => new Time(0))
      case DataTypeEnum.TIMESTAMP =>
        Optional
          .ofNullable(resultSet.getTimestamp(columnName, DateTimeUtils.CALENDAR))
          .orElseGet(() => new Timestamp(0))
      case DataTypeEnum.BYTES =>
        Optional.ofNullable(resultSet.getBytes(columnName)).orElseGet(() => Array())
      case _ =>
        throw new UnsupportedOperationException(
          s"JDBC Source Connector not support ${typeName} data type in ${columnName} column for ${dataBaseProductName} implement."
        )
    }
  }
  protected[datatype] def dataBaseProductName: String

  protected[datatype] def converterDataType(column: RdbColumn): DataTypeEnum
} 
Example 52
Source File: JavaServiceRegistryClient.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.registry

import java.net.URI
import java.util.Optional

import javax.inject.Inject
import javax.inject.Singleton
import com.lightbend.lagom.devmode.internal.registry.AbstractLoggingServiceRegistryClient
import com.lightbend.lagom.javadsl.api.transport.NotFound

import scala.collection.immutable
import scala.compat.java8.FutureConverters._
import scala.compat.java8.OptionConverters
import scala.concurrent.ExecutionContext
import scala.concurrent.Future

@Singleton
private[lagom] class JavaServiceRegistryClient @Inject() (
    registry: ServiceRegistry,
    implicit val ec: ExecutionContext
) extends AbstractLoggingServiceRegistryClient {
  protected override def internalLocateAll(serviceName: String, portName: Option[String]): Future[immutable.Seq[URI]] =
    registry
      .lookup(serviceName, OptionConverters.toJava(portName))
      .invoke()
      .toScala
      .map(immutable.Seq[URI](_))
      .recover {
        case _: NotFound => Nil
      }
} 
Example 53
Source File: ServiceRegistryServiceLocator.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.registry

import java.net.URI
import java.util.concurrent.CompletionStage
import java.util.Optional
import java.util.{ List => JList }

import javax.inject.Inject
import javax.inject.Singleton
import com.lightbend.lagom.devmode.internal.registry.ServiceRegistryClient
import com.lightbend.lagom.javadsl.api.Descriptor.Call
import com.lightbend.lagom.javadsl.client.CircuitBreakersPanel
import com.lightbend.lagom.javadsl.client.CircuitBreakingServiceLocator

import scala.collection.JavaConverters._
import scala.compat.java8.FutureConverters._
import scala.compat.java8.OptionConverters._
import scala.concurrent.ExecutionContext

@Singleton
private[lagom] class ServiceRegistryServiceLocator @Inject() (
    circuitBreakers: CircuitBreakersPanel,
    client: ServiceRegistryClient,
    implicit val ec: ExecutionContext
) extends CircuitBreakingServiceLocator(circuitBreakers) {
  override def locateAll(name: String, serviceCall: Call[_, _]): CompletionStage[JList[URI]] =
    // a ServiceLocator doesn't know what a `portName` is so we default to `None` and the
    // implementation will return any registry without a port name. This means that in order
    // for this queries to work any service registered using `http` as portName will also have
    // to be registered without name.
    client.locateAll(name, None).map(_.asJava).toJava

  override def locate(name: String, serviceCall: Call[_, _]): CompletionStage[Optional[URI]] =
    // a ServiceLocator doesn't know what a `portName` is so we default to `None` and the
    // implementation will return any registry without a port name. This means that in order
    // for this queries to work any service registered using `http` as portName will also have
    // to be registered without name.
    client.locateAll(name, None).map(_.headOption.asJava).toJava
} 
Example 54
Source File: NoServiceLocator.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.registry.impl

import java.net.URI
import java.util.Optional
import java.util.concurrent.CompletionStage
import java.util.function.{ Function => JFunction }

import com.lightbend.lagom.javadsl.api.Descriptor.Call
import com.lightbend.lagom.javadsl.api.ServiceLocator


class NoServiceLocator extends ServiceLocator {
  import java.util.concurrent.CompletableFuture

  override def locate(name: String, serviceCall: Call[_, _]): CompletionStage[Optional[URI]] =
    CompletableFuture.completedFuture(Optional.empty())

  override def doWithService[T](
      name: String,
      serviceCall: Call[_, _],
      block: JFunction[URI, CompletionStage[T]]
  ): CompletionStage[Optional[T]] =
    CompletableFuture.completedFuture(Optional.empty())
} 
Example 55
Source File: ServiceRegistryInteropSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.registry.impl

import java.net.URI
import java.util.Collections
import java.util.Optional

import akka.actor.ActorSystem
import akka.testkit.TestKit
import akka.util.ByteString
import com.lightbend.lagom.devmode.internal.scaladsl.registry.RegisteredService
import com.lightbend.lagom.devmode.internal.scaladsl.registry.ServiceRegistryService
import com.lightbend.lagom.internal.javadsl.registry.{ RegisteredService => jRegisteredService }
import com.lightbend.lagom.internal.javadsl.registry.{ ServiceRegistryService => jServiceRegistryService }
import com.lightbend.lagom.devmode.internal.scaladsl.registry.{ RegisteredService => sRegisteredService }
import com.lightbend.lagom.devmode.internal.scaladsl.registry.{ ServiceRegistryService => sServiceRegistryService }
import com.lightbend.lagom.javadsl.api.ServiceAcl
import com.lightbend.lagom.javadsl.api.deser.MessageSerializer
import com.lightbend.lagom.javadsl.api.deser.StrictMessageSerializer
import com.lightbend.lagom.javadsl.api.transport.MessageProtocol
import com.lightbend.lagom.javadsl.api.transport.Method
import com.lightbend.lagom.javadsl.jackson.JacksonSerializerFactory
import org.scalatest.BeforeAndAfterAll
import org.scalatest.concurrent.Futures
import play.api.libs.json.Format
import play.api.libs.json.Json
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class ServiceRegistryInteropSpec extends AnyFlatSpec with Matchers with Futures with BeforeAndAfterAll {
  val system                   = ActorSystem()
  val jacksonSerializerFactory = new JacksonSerializerFactory(system)

  protected override def afterAll(): Unit = {
    TestKit.shutdownActorSystem(actorSystem = system, verifySystemShutdown = true)
  }

  behavior.of("ServiceRegistry serializers")

  it should "should interop between java and scala (RegisteredService)" in {
    val msg = jRegisteredService.of("inventory", URI.create("https://localhost:123/asdf"), Optional.of("https"))
    roundTrip(msg) should be(msg)
  }

  it should "should interop between java and scala when optional fields are empty (RegisteredService)" in {
    val msg = jRegisteredService.of("inventory", URI.create("https://localhost:123/asdf"), Optional.empty[String])
    roundTrip(msg) should be(msg)
  }

  it should "should interop between java and scala (ServiceRegistryService)" in {
    val msg = jServiceRegistryService.of(
      URI.create("https://localhost:123/asdf"),
      Collections.singletonList(ServiceAcl.methodAndPath(Method.GET, "/items"))
    )
    roundTrip(msg) should be(msg)
  }

  it should "should interop between java and scala when optional fields are empty (ServiceRegistryService)" in {
    val msg = jServiceRegistryService.of(URI.create("https://localhost:123/asdf"), Collections.emptyList[ServiceAcl])
    roundTrip(msg) should be(msg)
  }

  private def roundTrip(input: jServiceRegistryService): jServiceRegistryService = {
    roundTrip(
      input,
      jacksonSerializerFactory.messageSerializerFor[jServiceRegistryService](classOf[jServiceRegistryService]),
      com.lightbend.lagom.scaladsl.playjson.JsonSerializer[ServiceRegistryService].format
    )(sServiceRegistryService.format)
  }

  private def roundTrip(input: jRegisteredService): jRegisteredService = {
    roundTrip(
      input,
      jacksonSerializerFactory.messageSerializerFor[jRegisteredService](classOf[jRegisteredService]),
      com.lightbend.lagom.scaladsl.playjson.JsonSerializer[RegisteredService].format
    )(sRegisteredService.format)
  }

  private def roundTrip[J, S](
      input: J,
      jacksonSerializer: StrictMessageSerializer[J],
      playJsonFormatter: Format[S]
  )(implicit format: Format[S]): J = {
    val byteString: ByteString = jacksonSerializer.serializerForRequest().serialize(input)
    val scalaValue: S          = playJsonFormatter.reads(Json.parse(byteString.toArray)).get
    val str: String            = playJsonFormatter.writes(scalaValue).toString()
    val jacksonDeserializer: MessageSerializer.NegotiatedDeserializer[J, ByteString] =
      jacksonSerializer.deserializer(
        new MessageProtocol(Optional.of("application/json"), Optional.empty[String], Optional.empty[String])
      )
    jacksonDeserializer.deserialize(ByteString(str))
  }
} 
Example 56
Source File: LagomPlayModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.play

import java.util.{ List => JList }
import java.util.Optional
import javax.inject.Inject

import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistry
import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistryService
import com.lightbend.lagom.devmode.internal.registry.serviceDnsRecords
import com.lightbend.lagom.javadsl.api.ServiceAcl
import com.lightbend.lagom.javadsl.api.ServiceInfo
import com.lightbend.lagom.javadsl.api.transport.Method
import com.typesafe.config.Config
import play.api.inject.ApplicationLifecycle
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment
import play.api.Logger

import scala.collection.JavaConverters._
import scala.compat.java8.FutureConverters._
import scala.util.Success
import scala.util.Try

class LagomPlayModule extends Module {
  private val logger = Logger(this.getClass)

  override def bindings(environment: Environment, config: Configuration): Seq[Binding[_]] = {
    val maybeServiceInfoBinding: Option[Binding[ServiceInfo]] = prepareServiceInfoBinding(config.underlying)
    val playRegistry                                          = bind[PlayRegisterWithServiceRegistry].toSelf.eagerly()

    Seq(
      playRegistry
    ) ++ maybeServiceInfoBinding.toList
  }

  private def prepareServiceInfoBinding(config: Config) = {
    val triedServiceName                   = Try(config.getString("lagom.play.service-name"))
    val triedAcls: Try[JList[_ <: Config]] = Try(config.getConfigList("lagom.play.acls"))

    val warning = "Service setup via 'application.conf' is deprecated. Remove 'lagom.play.service-name' and/or " +
      "'lagom.play.acls' and use 'bindServiceInfo' on your Guice's Module class."

    val maybeServiceInfoBinding = (triedServiceName, triedAcls) match {
      case (Success(serviceName), Success(aclList)) => {
        logger.warn(warning)
        // create a ServiceInfo in case user doesn't see the warning
        val acls = parseAclList(aclList)
        Some(bind[ServiceInfo].toInstance(ServiceInfo.of(serviceName, acls: _*)))
      }
      case (Success(serviceName), _) => {
        logger.warn(warning)
        // create a ServiceInfo in case user doesn't see the warning
        Some(bind[ServiceInfo].toInstance(ServiceInfo.of(serviceName)))
      }
      case (_, Success(_)) => {
        logger.warn(warning)
        // can't create a ServiceInfo because service-name is missing
        None
      }
      case _ => None
    }
    maybeServiceInfoBinding
  }

  private def parseAclList(aclList: JList[_ <: Config]): Seq[ServiceAcl] = {
    aclList.asScala.map { aclConfig =>
      val method = if (aclConfig.hasPath("method")) {
        Optional.of(new Method(aclConfig.getString("method")))
      } else Optional.empty[Method]
      val pathRegex = if (aclConfig.hasPath("path-regex")) {
        Optional.of(aclConfig.getString("path-regex"))
      } else Optional.empty[String]
      new ServiceAcl(method, pathRegex)
    }.toSeq
  }
}

class PlayRegisterWithServiceRegistry @Inject() (
    config: Config,
    serviceInfo: ServiceInfo,
    serviceRegistry: ServiceRegistry,
    applicationLifecycle: ApplicationLifecycle
) {
  val uris = serviceDnsRecords(config)

  private val serviceAcls = serviceInfo.getAcls
  private val service     = ServiceRegistryService.of(uris.asJava, serviceAcls)
  // TODO: fix -> this register operation is registering all ACLs under the microservice name, not under each locatable service name. Will lead to unlocatable.
  serviceRegistry.register(serviceInfo.serviceName()).invoke(service)

  applicationLifecycle.addStopHook(() => serviceRegistry.unregister(serviceInfo.serviceName()).invoke().toScala)
} 
Example 57
Source File: PersistentEntityRegistry.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence

import java.util.Optional
import java.util.UUID

import akka.NotUsed
import akka.japi.Pair
import akka.stream.javadsl
import com.lightbend.lagom.javadsl.persistence.Offset.Sequence
import com.lightbend.lagom.javadsl.persistence.Offset.TimeBasedUUID


  @deprecated("Use eventStream(AggregateEventTag, Offset) instead", "1.2.0")
  def eventStream[Event <: AggregateEvent[Event]](
      aggregateTag: AggregateEventTag[Event],
      fromOffset: Optional[UUID]
  ): javadsl.Source[Pair[Event, UUID], NotUsed] = {
    val offset = if (fromOffset.isPresent) {
      Offset.timeBasedUUID(fromOffset.get())
    } else Offset.NONE
    eventStream(aggregateTag, offset).asScala.map { pair =>
      val uuid = pair.second match {
        case timeBased: TimeBasedUUID => timeBased.value()
        case sequence: Sequence       =>
          // While we *could* translate the sequence number to a time-based UUID, this would be very bad, since the UUID
          // would either be non unique (violating the fundamental aim of UUIDs), or it would change every time the
          // event was loaded. Also, a sequence number is not a timestamp.
          throw new IllegalStateException("Sequence based offset is not supported in a UUID event stream")
      }
      Pair(pair.first, uuid)
    }.asJava
  }
} 
Example 58
Source File: TransportExceptionSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.api.transport

import java.util
import java.util.Optional

import com.lightbend.lagom.javadsl.api.deser.DeserializationException
import com.lightbend.lagom.javadsl.api.deser.SerializationException

import scala.collection.immutable
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec


class TransportExceptionSpec extends AnyWordSpec with Matchers {
  val protocolTextPlain = new MessageProtocol(Optional.of("text/plain"), Optional.of("utf-8"), Optional.empty[String])
  val protocolJson      = new MessageProtocol(Optional.of("application/json"), Optional.of("utf-8"), Optional.empty[String])
  val protocolHtml      = new MessageProtocol(Optional.of("text/html"), Optional.of("utf-8"), Optional.empty[String])

  val supportedExceptions: immutable.Seq[TransportException] = List(
    new DeserializationException("some msg - DeserializationException"),
    new BadRequest("some msg - BadRequest"),
    new Forbidden("some msg - Forbidden"),
    new PolicyViolation("some msg - PolicyViolation"),
    new NotFound("some msg - NotFound"),
    new NotAcceptable(util.Arrays.asList(protocolJson, protocolTextPlain), protocolHtml),
    new PayloadTooLarge("some msg - PayloadTooLarge"),
    new UnsupportedMediaType(protocolTextPlain, protocolJson),
    new SerializationException("some msg - SerializationException")
  )

  "Lagom-provided TransportExceptions" should {
    supportedExceptions.foreach { ex =>
      s"be buildable from code and message (${ex.getClass.getName})" in {
        val reconstructed = TransportException.fromCodeAndMessage(ex.errorCode(), ex.exceptionMessage())
        reconstructed.getClass.getName should ===(ex.getClass.getName)
        reconstructed.exceptionMessage() should ===(ex.exceptionMessage())
      }
    }

    // TODO: implement roundtrip de/ser tests like in com.lightbend.lagom.scaladsl.api.ExceptionsSpec
  }
} 
Example 59
Source File: JdbcPersistentEntityRegistry.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.persistence.jdbc

import java.util.Optional

import javax.inject.Inject
import javax.inject.Singleton
import akka.actor.ActorSystem
import akka.persistence.jdbc.query.scaladsl.JdbcReadJournal
import com.lightbend.lagom.internal.javadsl.persistence.AbstractPersistentEntityRegistry
import com.lightbend.lagom.javadsl.persistence.PersistentEntity
import play.api.inject.Injector


@Singleton
private[lagom] final class JdbcPersistentEntityRegistry @Inject() (
    system: ActorSystem,
    injector: Injector,
    slickProvider: SlickProvider
) extends AbstractPersistentEntityRegistry(system, injector) {
  private lazy val ensureTablesCreated = slickProvider.ensureTablesCreated()

  override def register[C, E, S](entityClass: Class[_ <: PersistentEntity[C, E, S]]): Unit = {
    ensureTablesCreated
    super.register(entityClass)
  }

  protected override val queryPluginId = Optional.of(JdbcReadJournal.Identifier)
} 
Example 60
Source File: TestServiceLocator.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.testkit

import java.net.URI
import java.util.Optional
import java.util.concurrent.CompletionStage

import scala.compat.java8.FutureConverters._
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import com.lightbend.lagom.javadsl.api.Descriptor
import javax.inject.Inject
import javax.inject.Singleton

import com.lightbend.lagom.javadsl.client.CircuitBreakersPanel
import com.lightbend.lagom.javadsl.client.CircuitBreakingServiceLocator

@Singleton
private[lagom] class TestServiceLocator @Inject() (
    circuitBreakers: CircuitBreakersPanel,
    port: TestServiceLocatorPort,
    implicit val ec: ExecutionContext
) extends CircuitBreakingServiceLocator(circuitBreakers) {
  private val futureUri = port.port.map(p => URI.create("http://localhost:" + p))

  override def locate(name: String, call: Descriptor.Call[_, _]): CompletionStage[Optional[URI]] =
    futureUri.map(uri => Optional.of(uri)).toJava
}

private[lagom] final case class TestServiceLocatorPort(port: Future[Int]) 
Example 61
Source File: PersistentEntityTestDriverCompatSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.testkit

import scala.collection.JavaConverters._
import scala.concurrent.duration._
import com.lightbend.lagom.javadsl.persistence.TestEntity
import akka.testkit.TestProbe
import com.lightbend.lagom.internal.javadsl.persistence.PersistentEntityActor
import java.util.Optional

import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraPersistenceSpec

class PersistentEntityTestDriverCompatSpec extends CassandraPersistenceSpec {
  "PersistentEntityActor and PersistentEntityTestDriver" must {
    "produce same events and state" in {
      val probe1 = TestProbe()
      val p = system.actorOf(
        PersistentEntityActor.props(
          "test",
          Optional.of("1"),
          () => new TestEntity(system, probe1.ref),
          Optional.empty(),
          10.seconds,
          "",
          ""
        )
      )
      val probe2 = TestProbe()
      val driver = new PersistentEntityTestDriver(system, new TestEntity(system, probe2.ref), "1")

      val commands = List(
        TestEntity.Get.instance,
        TestEntity.Add.of("a"),
        TestEntity.Add.of("b"),
        TestEntity.Add.of(""),
        new TestEntity.ChangeMode(TestEntity.Mode.PREPEND),
        TestEntity.Add.of("C"),
        new TestEntity.Add("D", 2),
        TestEntity.Get.instance
      )

      val outcome = driver.run(commands: _*)

      commands.foreach(p ! _)

      val replySideEffects = outcome.sideEffects.asScala.collect {
        case PersistentEntityTestDriver.Reply(msg) => msg
      }
      val replies = receiveN(replySideEffects.size)
      replySideEffects should be(replies)
      // Add 2 generates 2 events, but only one reply so drop last event when comparing
      outcome.events.asScala.dropRight(1) should be(replies.collect { case evt: TestEntity.Evt => evt })

      outcome.state should be(replies.last)

      expectNoMessage(200.millis)
      probe1.expectMsgType[TestEntity.AfterRecovery]
      probe2.expectMsgType[TestEntity.AfterRecovery]

      outcome.issues.asScala.toList should be(Nil)
    }
  }
} 
Example 62
Source File: SessionDirectives.scala    From akka-http-session   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.session.javadsl

import java.util.Optional
import java.util.function.Supplier

import akka.http.javadsl.server.Route
import akka.http.javadsl.server.directives.RouteAdapter
import com.softwaremill.session._

import scala.compat.java8.OptionConverters._


trait SessionDirectives extends OneOffSessionDirectives with RefreshableSessionDirectives {

  def session[T](sc: SessionContinuity[T], st: GetSessionTransport, inner: java.util.function.Function[SessionResult[T], Route]): Route = RouteAdapter {
    com.softwaremill.session.SessionDirectives.session(sc, st) { sessionResult =>
      inner.apply(sessionResult).asInstanceOf[RouteAdapter].delegate
    }
  }

  def setSession[T](sc: SessionContinuity[T], st: SetSessionTransport, v: T, inner: Supplier[Route]): Route = RouteAdapter {
    com.softwaremill.session.SessionDirectives.setSession(sc, st, v) {
      inner.get.asInstanceOf[RouteAdapter].delegate
    }
  }

  def invalidateSession[T](sc: SessionContinuity[T], st: GetSessionTransport, inner: Supplier[Route]): Route = RouteAdapter {
    com.softwaremill.session.SessionDirectives.invalidateSession(sc, st) {
      inner.get.asInstanceOf[RouteAdapter].delegate
    }
  }

  def optionalSession[T](sc: SessionContinuity[T], st: GetSessionTransport, inner: java.util.function.Function[Optional[T], Route]): Route = RouteAdapter {
    com.softwaremill.session.SessionDirectives.optionalSession(sc, st) { session =>
      inner.apply(session.asJava).asInstanceOf[RouteAdapter].delegate
    }
  }

  def requiredSession[T](sc: SessionContinuity[T], st: GetSessionTransport, inner: java.util.function.Function[T, Route]): Route = RouteAdapter {
    com.softwaremill.session.SessionDirectives.requiredSession(sc, st) { session =>
      inner.apply(session).asInstanceOf[RouteAdapter].delegate
    }
  }

  def touchRequiredSession[T](sc: SessionContinuity[T], st: GetSessionTransport, inner: java.util.function.Function[T, Route]): Route = RouteAdapter {
    com.softwaremill.session.SessionDirectives.touchRequiredSession(sc, st) { session =>
      inner.apply(session).asInstanceOf[RouteAdapter].delegate
    }
  }

}

object SessionDirectives extends SessionDirectives 
Example 63
Source File: ManagementRouteProviderSettings.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management.javadsl

import java.util.Optional
import java.util.concurrent.CompletionStage
import java.util.function.{ Function => JFunction }

import akka.annotation.DoNotInherit
import akka.annotation.InternalApi
import akka.http.javadsl.HttpsConnectionContext
import akka.http.javadsl.model.Uri
import akka.http.javadsl.server.directives.SecurityDirectives.ProvidedCredentials
import akka.http.scaladsl.server.Directives.AsyncAuthenticator
import akka.management.scaladsl

object ManagementRouteProviderSettings {
  def create(selfBaseUri: Uri): ManagementRouteProviderSettings = {
    ManagementRouteProviderSettingsImpl(selfBaseUri, None, None, Optional.empty(), readOnly = true)
  }
}


@InternalApi private[akka] final case class ManagementRouteProviderSettingsImpl(
    override val selfBaseUri: Uri,
    javadslAuth: Option[JFunction[Optional[ProvidedCredentials], CompletionStage[Optional[String]]]],
    scaladslAuth: Option[AsyncAuthenticator[String]],
    override val httpsConnectionContext: Optional[HttpsConnectionContext],
    override val readOnly: Boolean
) extends ManagementRouteProviderSettings {

  // There is no public API for defining both so it should not be possible
  require(!(javadslAuth.isDefined && scaladslAuth.isDefined), "Defining both javadsl and scaladsl auth is not allowed")

  override def withAuth(newAuth: JFunction[Optional[ProvidedCredentials], CompletionStage[Optional[String]]])
      : ManagementRouteProviderSettings =
    copy(javadslAuth = Option(newAuth))

  override def withHttpsConnectionContext(
      newHttpsConnectionContext: HttpsConnectionContext): ManagementRouteProviderSettings =
    copy(
      selfBaseUri = selfBaseUri.scheme("https"),
      httpsConnectionContext = Optional.ofNullable(newHttpsConnectionContext))

  def scaladslHttpsConnectionContext: Option[akka.http.scaladsl.HttpsConnectionContext] = {
    if (httpsConnectionContext.isPresent) {
      httpsConnectionContext.get match {
        case ctx: akka.http.scaladsl.HttpsConnectionContext => Option(ctx)
        case other =>
          throw new IllegalStateException(
            "akka.http.javadsl.HttpsConnectionContext should be a " +
            s"akka.http.scaladsl.HttpsConnectionContext, but was [${other.getClass.getName}]")
      }
    } else {
      None
    }
  }

  override def withReadOnly(readOnly: Boolean): ManagementRouteProviderSettings = copy(readOnly = readOnly)

  def asScala: scaladsl.ManagementRouteProviderSettingsImpl =
    scaladsl.ManagementRouteProviderSettingsImpl(
      selfBaseUri = selfBaseUri.asScala,
      scaladslAuth,
      javadslAuth,
      scaladslHttpsConnectionContext,
      readOnly)
} 
Example 64
Source File: AkkaManagementSettings.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management

import java.net.InetAddress
import java.util.Optional

import scala.collection.JavaConverters._
import scala.collection.immutable
import scala.compat.java8.OptionConverters._

import akka.annotation.InternalApi
import com.typesafe.config.Config

final class AkkaManagementSettings(val config: Config) {
  private val managementConfig = config.getConfig("akka.management")

  object Http {
    private val cc = managementConfig.getConfig("http")

    val Hostname: String = {
      val hostname = cc.getString("hostname")
      if (hostname == "<hostname>") InetAddress.getLocalHost.getHostAddress
      else if (hostname.trim() == "") InetAddress.getLocalHost.getHostAddress
      else hostname
    }

    val Port: Int = {
      val p = cc.getInt("port")
      require(0 to 65535 contains p, s"akka.management.http.port must be 0 through 65535 (was ${p})")
      p
    }

    val EffectiveBindHostname: String = cc.getString("bind-hostname") match {
      case ""    => Hostname
      case value => value
    }

    val EffectiveBindPort: Int = cc.getString("bind-port") match {
      case "" => Port
      case value =>
        val p = value.toInt
        require(0 to 65535 contains p, s"akka.management.http.bind-port must be 0 through 65535 (was ${p})")
        p
    }

    val BasePath: Option[String] =
      Option(cc.getString("base-path")).flatMap(it => if (it.trim == "") None else Some(it))

    val RouteProviders: immutable.Seq[NamedRouteProvider] = {
      def validFQCN(value: Any) = {
        value != null &&
        value != "null" &&
        value.toString.trim.nonEmpty
      }

      cc.getConfig("routes")
        .root
        .unwrapped
        .asScala
        .collect {
          case (name, value) if validFQCN(value) => NamedRouteProvider(name, value.toString)
        }
        .toList
    }

    val RouteProvidersReadOnly: Boolean = cc.getBoolean("route-providers-read-only")
  }

  
@InternalApi private[akka] object AkkaManagementSettings {

  implicit class HasDefined(val config: Config) {
    def hasDefined(key: String): Boolean =
      config.hasPath(key) &&
      config.getString(key).trim.nonEmpty &&
      config.getString(key) != s"<$key>"

    def optDefinedValue(key: String): Option[String] =
      if (hasDefined(key)) Some(config.getString(key)) else None

    def optValue(key: String): Option[String] =
      config.getString(key) match {
        case ""    => None
        case other => Some(other)
      }
  }
}

final case class NamedRouteProvider(name: String, fullyQualifiedClassName: String) 
Example 65
Source File: ManagementRouteProviderSettings.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management.scaladsl

import java.util.Optional
import java.util.concurrent.CompletionStage
import java.util.function.{ Function => JFunction }

import akka.annotation.DoNotInherit
import akka.annotation.InternalApi
import akka.http.javadsl.server.directives.SecurityDirectives.ProvidedCredentials
import akka.http.scaladsl.HttpsConnectionContext
import akka.http.scaladsl.model.Uri
import akka.http.scaladsl.server.Directives.AsyncAuthenticator
import akka.management.javadsl

object ManagementRouteProviderSettings {
  def apply(selfBaseUri: Uri, readOnly: Boolean): ManagementRouteProviderSettings = {
    ManagementRouteProviderSettingsImpl(selfBaseUri, None, None, None, readOnly = readOnly)
  }
}


@InternalApi private[akka] final case class ManagementRouteProviderSettingsImpl(
    override val selfBaseUri: Uri,
    scaladslAuth: Option[AsyncAuthenticator[String]],
    javadslAuth: Option[JFunction[Optional[ProvidedCredentials], CompletionStage[Optional[String]]]],
    override val httpsConnectionContext: Option[HttpsConnectionContext],
    override val readOnly: Boolean
) extends ManagementRouteProviderSettings {

  // There is no public API for defining both so it should not be possible
  require(!(javadslAuth.isDefined && scaladslAuth.isDefined), "Defining both javadsl and scaladsl auth is not allowed")

  override def withAuth(newAuth: AsyncAuthenticator[String]): ManagementRouteProviderSettings =
    copy(scaladslAuth = Option(newAuth))

  override def withHttpsConnectionContext(
      newHttpsConnectionContext: HttpsConnectionContext): ManagementRouteProviderSettings =
    copy(selfBaseUri = selfBaseUri.withScheme("https"), httpsConnectionContext = Option(newHttpsConnectionContext))

  def javadslHttpsConnectionContext: Optional[akka.http.javadsl.HttpsConnectionContext] =
    httpsConnectionContext match {
      case None      => Optional.empty()
      case Some(ctx) => Optional.of(ctx) // a scaladsl.HttpsConnectionContext is a javadsl.HttpsConnectionContext
    }

  override def withReadOnly(readOnly: Boolean): ManagementRouteProviderSettings = copy(readOnly = readOnly)

  def asJava: javadsl.ManagementRouteProviderSettingsImpl =
    javadsl.ManagementRouteProviderSettingsImpl(
      selfBaseUri = akka.http.javadsl.model.Uri.create(selfBaseUri),
      javadslAuth,
      scaladslAuth,
      javadslHttpsConnectionContext,
      readOnly)

} 
Example 66
Source File: FileInputImpl.scala    From chatoverflow   with Eclipse Public License 2.0 5 votes vote down vote up
package org.codeoverflow.chatoverflow.requirement.service.file.impl

import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.util.Optional

import javax.imageio.ImageIO
import org.codeoverflow.chatoverflow.WithLogger
import org.codeoverflow.chatoverflow.api.io.input.FileInput
import org.codeoverflow.chatoverflow.registry.Impl
import org.codeoverflow.chatoverflow.requirement.impl.InputImpl
import org.codeoverflow.chatoverflow.requirement.service.file.FileConnector

@Impl(impl = classOf[FileInput], connector = classOf[FileConnector])
class FileInputImpl extends InputImpl[FileConnector] with FileInput with WithLogger {

  override def getFile(pathInResources: String): Optional[String] = Optional.ofNullable(sourceConnector.get.getFile(pathInResources).orNull)

  override def getBinaryFile(pathInResources: String): Optional[Array[Byte]] = Optional.ofNullable(sourceConnector.get.getBinaryFile(pathInResources).orNull)

  override def getImage(pathInResources: String): Optional[BufferedImage] = {
    val data = sourceConnector.get.getBinaryFile(pathInResources)
    if (data.isEmpty) {
      None
    }
    val bis = new ByteArrayInputStream(data.get)
    Optional.of(ImageIO.read(bis))
  }

  override def start(): Boolean = true

  
  override def stop(): Boolean = true
}