java.util.function.BiConsumer Scala Examples

The following examples show how to use java.util.function.BiConsumer. 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: ClientAdapter.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.grpc.adapter.client.akka

import java.util.function.BiConsumer

import akka.NotUsed
import akka.stream.scaladsl.Source
import com.daml.grpc.adapter.ExecutionSequencerFactory
import com.daml.grpc.adapter.client.rs.ClientPublisher
import io.grpc.stub.StreamObserver

object ClientAdapter {

  def serverStreaming[Req, Resp](req: Req, stub: (Req, StreamObserver[Resp]) => Unit)(
      implicit executionSequencerFactory: ExecutionSequencerFactory): Source[Resp, NotUsed] =
    Source.fromPublisher(
      new ClientPublisher[Req, Resp](req, adaptStub(stub), executionSequencerFactory))

  private def adaptStub[Req, Resp](
      stub: (Req, StreamObserver[Resp]) => Unit
  ): BiConsumer[Req, StreamObserver[Resp]] = { (req, resp) =>
    stub(req, resp)
  }

} 
Example 2
Source File: S2Vertex.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.core

import java.util.function.BiConsumer

import org.apache.s2graph.core.S2Vertex.Props
import org.apache.s2graph.core.schema._
import org.apache.s2graph.core.types._
import org.apache.tinkerpop.gremlin.structure.Vertex
import org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality

import scala.collection.JavaConverters._

case class S2Vertex(graph: S2GraphLike,
                    id: VertexId,
                    ts: Long = System.currentTimeMillis(),
                    props: Props = S2Vertex.EmptyProps,
                    op: Byte = 0,
                    belongLabelIds: Seq[Int] = Seq.empty) extends S2VertexLike {

  //  lazy val kvs = Graph.client.vertexSerializer(this).toKeyValues

  
  override def serviceName = service.serviceName

  override def isAsync = false

  override def queueKey = Seq(ts.toString, serviceName).mkString("|")

  override def queuePartitionKey = id.innerId.toString

  override def hashCode() = {
    val hash = id.hashCode()
    //    logger.debug(s"Vertex.hashCode: $this -> $hash")
    hash
  }

  override def equals(obj: Any) = {
    obj match {
      case otherVertex: Vertex =>
        val ret = id == otherVertex.id
        //        logger.debug(s"Vertex.equals: $this, $obj => $ret")
        ret
      case _ => false
    }
  }

  override def toString(): String = {
    // V + L_BRACKET + vertex.id() + R_BRACKET;
    // v[VertexId(1, 1481694411514)]
    s"v[${id}]"
  }
}

object S2Vertex {

  val VertexLabelDelimiter = "::"

  type Props = java.util.Map[String, S2VertexProperty[_]]
  type State = Map[ColumnMeta, InnerValLike]
  def EmptyProps = new java.util.HashMap[String, S2VertexProperty[_]]()
  def EmptyState = Map.empty[ColumnMeta, InnerValLike]

  def toPropKey(labelId: Int): Int = Byte.MaxValue + labelId

  def toLabelId(propKey: Int): Int = propKey - Byte.MaxValue

  def isLabelId(propKey: Int): Boolean = propKey > Byte.MaxValue

  def fillPropsWithTs(vertex: S2VertexLike, props: Props): Unit = {
    props.forEach(new BiConsumer[String, S2VertexProperty[_]] {
      override def accept(key: String, p: S2VertexProperty[_]): Unit = {
//        vertex.property(Cardinality.single, key, p.value)
        vertex.propertyInner(Cardinality.single, key, p.value)
      }
    })
  }

  def fillPropsWithTs(vertex: S2VertexLike, state: State): Unit = {
    state.foreach { case (k, v) => vertex.propertyInner(Cardinality.single, k.name, v.value) }
  }

  def propsToState(props: Props): State = {
    props.asScala.map { case (k, v) =>
      v.columnMeta -> v.innerVal
    }.toMap
  }

  def stateToProps(vertex: S2VertexLike, state: State): Props = {
    state.foreach { case (k, v) =>
      vertex.property(k.name, v.value)
    }
    vertex.props
  }

} 
Example 3
Source File: S2EdgePropertyHelper.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.core

import java.util.function.BiConsumer

import org.apache.s2graph.core.S2Edge.Props
import org.apache.s2graph.core.schema.LabelMeta
import org.apache.s2graph.core.types.{InnerVal, InnerValLikeWithTs}
import org.apache.tinkerpop.gremlin.structure.Property

object S2EdgePropertyHelper {
  def propertyInner[V](edge: S2EdgeLike, key: String, value: V, ts: Long): Property[V] = {
    val labelMeta = edge.innerLabel.metaPropsInvMap.getOrElse(key, throw new RuntimeException(s"$key is not configured on Edge."))
    val newProp = new S2Property[V](edge, labelMeta, key, value, ts)
    edge.getPropsWithTs().put(key, newProp)
    newProp
  }

  def updatePropsWithTs(edge: S2EdgeLike, others: Props = S2Edge.EmptyProps): Props = {
    val emptyProp = S2Edge.EmptyProps

    edge.getPropsWithTs().forEach(new BiConsumer[String, S2Property[_]] {
      override def accept(key: String, value: S2Property[_]): Unit = emptyProp.put(key, value)
    })

    others.forEach(new BiConsumer[String, S2Property[_]] {
      override def accept(key: String, value: S2Property[_]): Unit = emptyProp.put(key, value)
    })

    emptyProp
  }

  def propertyValue(e: S2EdgeLike, key: String): Option[InnerValLikeWithTs] = {
    key match {
      case "from" | "_from" => Option(InnerValLikeWithTs(e.srcVertex.innerId, e.ts))
      case "to" | "_to" => Option(InnerValLikeWithTs(e.tgtVertex.innerId, e.ts))
      case "label" => Option(InnerValLikeWithTs(InnerVal.withStr(e.innerLabel.label, e.innerLabel.schemaVersion), e.ts))
      case "direction" => Option(InnerValLikeWithTs(InnerVal.withStr(e.getDirection(), e.innerLabel.schemaVersion), e.ts))
      case _ =>
        e.innerLabel.metaPropsInvMap.get(key).map(labelMeta => propertyValueInner(e, labelMeta))
    }
  }

  def propertyValuesInner(edge: S2EdgeLike, labelMetas: Seq[LabelMeta] = Nil): Map[LabelMeta, InnerValLikeWithTs] = {
    if (labelMetas.isEmpty) {
      edge.innerLabel.metaPropsDefaultMapInner.map { case (labelMeta, defaultVal) =>
        labelMeta -> edge.propertyValueInner(labelMeta)
      }
    } else {
      // This is important since timestamp is required for all edges.
      (LabelMeta.timestamp +: labelMetas).map { labelMeta =>
        labelMeta -> propertyValueInner(edge, labelMeta)
      }.toMap
    }
  }

  def propertyValueInner(edge: S2EdgeLike, labelMeta: LabelMeta): InnerValLikeWithTs = {
    //    propsWithTs.get(labelMeta.name).map(_.innerValWithTs).getOrElse()
    if (edge.getPropsWithTs().containsKey(labelMeta.name)) {
      edge.getPropsWithTs().get(labelMeta.name).innerValWithTs
    } else {
      edge.innerLabel.metaPropsDefaultMapInner(labelMeta)
    }
  }


  def toLabelMetas(edge: S2EdgeLike, keys: Seq[String]): Seq[LabelMeta] = {
    for {
      key <- keys
      labelMeta <- edge.innerLabel.metaPropsInvMap.get(key)
    } yield labelMeta
  }

} 
Example 4
Source File: S2VertexBuilder.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.core

import java.util
import java.util.function.BiConsumer

import org.apache.s2graph.core.S2Vertex.Props
import org.apache.s2graph.core.schema.ColumnMeta
import org.apache.s2graph.core.types.VertexId

class S2VertexBuilder(vertex: S2VertexLike) {
  def defaultProps: util.HashMap[String, S2VertexProperty[_]] = {
    val default = S2Vertex.EmptyProps
    val newProps = new S2VertexProperty(vertex, ColumnMeta.lastModifiedAtColumn, ColumnMeta.lastModifiedAtColumn.name, vertex.ts)
    default.put(ColumnMeta.lastModifiedAtColumn.name, newProps)
    default
  }

  def copyVertex(graph: S2GraphLike = vertex.graph,
                 id: VertexId = vertex.id,
                 ts: Long = vertex.ts,
                 props: Props = vertex.props,
                 op: Byte = vertex.op,
                 belongLabelIds: Seq[Int] = vertex.belongLabelIds): S2VertexLike = {
    val newProps = S2Vertex.EmptyProps
    val v = new S2Vertex(graph, id, ts, newProps, op, belongLabelIds)

    props.forEach(new BiConsumer[String, S2VertexProperty[_]] {
      override def accept(t: String, u: S2VertexProperty[_]) = {
        v.property(t, u.value)
      }
    })

    v
  }
} 
Example 5
Source File: CacheAsyncConnection.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.api.libs.ws.ahc.cache

import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
import java.util.function.BiConsumer

import play.shaded.ahc.org.asynchttpclient.AsyncHandler
import play.shaded.ahc.org.asynchttpclient.ListenableFuture
import play.shaded.ahc.org.asynchttpclient.Request
import org.slf4j.LoggerFactory
import play.shaded.ahc.org.asynchttpclient.handler.ProgressAsyncHandler


class CacheFuture[T](handler: AsyncHandler[T]) extends ListenableFuture[T] {

  private var innerFuture: java.util.concurrent.CompletableFuture[T] = _

  def setInnerFuture(future: java.util.concurrent.CompletableFuture[T]) = {
    innerFuture = future
  }

  override def isDone: Boolean = innerFuture.isDone

  override def done(): Unit = {}

  override def touch(): Unit = {}

  override def abort(t: Throwable): Unit = {
    innerFuture.completeExceptionally(t)
  }

  override def isCancelled: Boolean = {
    innerFuture.isCancelled
  }

  override def get(): T = {
    get(1000L, java.util.concurrent.TimeUnit.MILLISECONDS)
  }

  override def get(timeout: Long, unit: TimeUnit): T = {
    innerFuture.get(timeout, unit)
  }

  override def cancel(mayInterruptIfRunning: Boolean): Boolean = {
    innerFuture.cancel(mayInterruptIfRunning)
  }

  override def toString: String = {
    s"CacheFuture"
  }

  override def toCompletableFuture: CompletableFuture[T] = innerFuture

  override def addListener(listener: Runnable, executor: Executor): ListenableFuture[T] = {
    innerFuture.whenCompleteAsync(
      new BiConsumer[T, Throwable]() {
        override def accept(t: T, u: Throwable): Unit = listener.run()
      },
      executor
    )
    this
  }
} 
Example 6
Source File: ExceptionCountAccumulator.scala    From spark-distcp   with Apache License 2.0 5 votes vote down vote up
package com.coxautodata.objects

import java.util
import java.util.Collections
import java.util.function.{BiConsumer, BiFunction}

import org.apache.spark.util.AccumulatorV2

class ExceptionCountAccumulator extends AccumulatorV2[String, java.util.Map[String, Long]] {

  private val _map: java.util.Map[String, Long] = Collections.synchronizedMap(new util.HashMap[String, Long]())

  override def isZero: Boolean = _map.isEmpty

  override def copyAndReset(): ExceptionCountAccumulator = new ExceptionCountAccumulator

  override def copy(): ExceptionCountAccumulator = {
    val newAcc = new ExceptionCountAccumulator
    _map.synchronized {
      newAcc._map.putAll(_map)
    }
    newAcc
  }

  override def reset(): Unit = _map.clear()

  def add(e: Throwable): Unit = add(e.getClass.getName.stripSuffix("$"))

  override def add(k: String): Unit = {
    add(k, 1)
  }

  private def add(k: String, v: Long): Unit = {
    _map.merge(k, v, CombineCounts)
  }

  override def merge(other: AccumulatorV2[String, util.Map[String, Long]]): Unit = {
    other match {
      case e: ExceptionCountAccumulator =>
        e._map.forEach {
          new BiConsumer[String, Long] {
            override def accept(k: String, v: Long): Unit = add(k, v)
          }
        }
      case _ => throw new UnsupportedOperationException(
        s"Cannot merge ${this.getClass.getName} with ${other.getClass.getName}")
    }
  }

  override def value: util.Map[String, Long] = _map
}

object CombineCounts extends BiFunction[Long, Long, Long] {
  override def apply(t: Long, u: Long): Long = t + u
} 
Example 7
Source File: PipeToSupport.scala    From perf_tester   with Apache License 2.0 5 votes vote down vote up
package akka.pattern

import language.implicitConversions
import scala.concurrent.{ Future, ExecutionContext }
import scala.util.{ Failure, Success }
import akka.actor.{ Status, ActorRef, Actor }
import akka.actor.ActorSelection
import java.util.concurrent.CompletionStage
import java.util.function.BiConsumer

trait PipeToSupport {

  final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) {
    def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
      future andThen {
        case Success(r) ⇒ recipient ! r
        case Failure(f) ⇒ recipient ! Status.Failure(f)
      }
    }
    def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
      future andThen {
        case Success(r) ⇒ recipient ! r
        case Failure(f) ⇒ recipient ! Status.Failure(f)
      }
    }
    def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender)
    def to(recipient: ActorRef, sender: ActorRef): PipeableFuture[T] = {
      pipeTo(recipient)(sender)
      this
    }
    def to(recipient: ActorSelection): PipeableFuture[T] = to(recipient, Actor.noSender)
    def to(recipient: ActorSelection, sender: ActorRef): PipeableFuture[T] = {
      pipeToSelection(recipient)(sender)
      this
    }
  }

  final class PipeableCompletionStage[T](val future: CompletionStage[T])(implicit executionContext: ExecutionContext) {
    def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): CompletionStage[T] = {
      future whenComplete new BiConsumer[T, Throwable] {
        override def accept(t: T, ex: Throwable) {
          if (t != null) recipient ! t
          if (ex != null) recipient ! Status.Failure(ex)
        }
      }
    }
    def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): CompletionStage[T] = {
      future whenComplete new BiConsumer[T, Throwable] {
        override def accept(t: T, ex: Throwable) {
          if (t != null) recipient ! t
          if (ex != null) recipient ! Status.Failure(ex)
        }
      }
    }
    def to(recipient: ActorRef): PipeableCompletionStage[T] = to(recipient, Actor.noSender)
    def to(recipient: ActorRef, sender: ActorRef): PipeableCompletionStage[T] = {
      pipeTo(recipient)(sender)
      this
    }
    def to(recipient: ActorSelection): PipeableCompletionStage[T] = to(recipient, Actor.noSender)
    def to(recipient: ActorSelection, sender: ActorRef): PipeableCompletionStage[T] = {
      pipeToSelection(recipient)(sender)
      this
    }
  }

  
  implicit def pipeCompletionStage[T](future: CompletionStage[T])(implicit executionContext: ExecutionContext): PipeableCompletionStage[T] = new PipeableCompletionStage(future)
} 
Example 8
Source File: FutureTimeoutSupport.scala    From perf_tester   with Apache License 2.0 5 votes vote down vote up
package akka.pattern

import scala.concurrent.{ ExecutionContext, Promise, Future }
import akka.actor._
import scala.util.control.NonFatal
import scala.concurrent.duration.FiniteDuration
import java.util.concurrent.CompletionStage
import java.util.concurrent.CompletableFuture
import akka.dispatch.Futures
import java.util.function.BiConsumer

trait FutureTimeoutSupport {
  
  def afterCompletionStage[T](duration: FiniteDuration, using: Scheduler)(value: ⇒ CompletionStage[T])(implicit ec: ExecutionContext): CompletionStage[T] =
    if (duration.isFinite() && duration.length < 1) {
      try value catch { case NonFatal(t) ⇒ Futures.failedCompletionStage(t) }
    } else {
      val p = new CompletableFuture[T]
      using.scheduleOnce(duration) {
        try {
          val future = value
          future.whenComplete(new BiConsumer[T, Throwable] {
            override def accept(t: T, ex: Throwable): Unit = {
              if (t != null) p.complete(t)
              if (ex != null) p.completeExceptionally(ex)
            }
          })
        } catch {
          case NonFatal(ex) ⇒ p.completeExceptionally(ex)
        }
      }
      p
    }
} 
Example 9
Source File: package.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence

import java.util.concurrent.CompletionStage
import java.util.function.BiConsumer

import akka.actor.ActorRef

package object testkit {
  implicit class pipe[T](val stage: CompletionStage[T]) extends AnyVal {
    def pipeTo(recipient: ActorRef): Unit = {
      stage.whenComplete(new BiConsumer[T, Throwable] {
        override def accept(value: T, e: Throwable): Unit = {
          if (value != null) recipient ! value
          if (e != null) recipient ! e
        }
      })
    }
  }
} 
Example 10
Source File: package.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence

import java.util.concurrent.CompletionStage
import java.util.function.BiConsumer

import akka.actor.ActorRef

package object testkit {

  implicit class pipe[T](val stage: CompletionStage[T]) extends AnyVal {
    def pipeTo(recipient: ActorRef): Unit = {
      stage.whenComplete(new BiConsumer[T, Throwable] {
        override def accept(value: T, e: Throwable): Unit = {
          if (value != null) recipient ! value
          if (e != null) recipient ! e
        }
      })
    }
  }
} 
Example 11
Source File: CatsAsyncHandler.scala    From pulsar4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.pulsar4s.cats

import java.util.concurrent.CompletableFuture
import java.util.function.BiConsumer

import cats.implicits._
import cats.effect._
import com.sksamuel.pulsar4s.{AsyncHandler, ConsumerMessage, DefaultProducer, MessageId, Producer}
import org.apache.pulsar.client.api
import org.apache.pulsar.client.api.{ProducerBuilder, Reader, TypedMessageBuilder}

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


object CatsAsyncHandler extends CatsAsyncHandlerLowPriority {
  implicit def handler: AsyncHandler[IO] = asyncHandlerForCatsEffectAsync[IO]
}

trait CatsAsyncHandlerLowPriority {
  object CompletableFutureConverters {
    implicit class CompletableOps[T](f: => CompletableFuture[T]) {
      def toF[F[_]: Async]: F[T] =
        Async[F].async[T] { k =>
          f.whenCompleteAsync(new BiConsumer[T, Throwable] {
            override def accept(t: T, e: Throwable): Unit = {
              if (e != null) k.apply(Left(e))
              else k.apply(Right(t))
            }
          })
        }

    }
  }

  implicit def asyncHandlerForCatsEffectAsync[F[_]: Async]: AsyncHandler[F] = new AsyncHandler[F] {
    import CompletableFutureConverters._

    override def failed(e: Throwable): F[Nothing] = Async[F].raiseError(e)

    override def createProducer[T](builder: ProducerBuilder[T]): F[Producer[T]] = builder.createAsync().toF[F].map(new DefaultProducer(_))

    override def send[T](t: T, producer: api.Producer[T]): F[MessageId] = producer.sendAsync(t).toF[F].map(MessageId.fromJava)
    override def receive[T](consumer: api.Consumer[T]): F[ConsumerMessage[T]] = consumer.receiveAsync().toF[F].map(ConsumerMessage.fromJava)

    override def unsubscribeAsync(consumer: api.Consumer[_]): F[Unit] = consumer.unsubscribeAsync().toF[F].void

    override def getLastMessageId[T](consumer: api.Consumer[T]): F[MessageId] = consumer.getLastMessageIdAsync().toF[F].map(MessageId.fromJava)

    override def close(producer: api.Producer[_]): F[Unit] = producer.closeAsync().toF[F].void
    override def close(consumer: api.Consumer[_]): F[Unit] = consumer.closeAsync().toF[F].void

    override def seekAsync(consumer: api.Consumer[_], messageId: MessageId): F[Unit] = consumer.seekAsync(messageId).toF[F].void
    override def seekAsync(reader: api.Reader[_], messageId: MessageId): F[Unit] = reader.seekAsync(messageId).toF[F].void
    override def seekAsync(reader: api.Reader[_], timestamp: Long): F[Unit] = reader.seekAsync(timestamp).toF[F].void

    override def transform[A, B](t: F[A])(fn: A => Try[B]): F[B] =
      t.flatMap { a =>
        fn(a) match {
          case Success(b) => Async[F].pure(b)
          case Failure(e) => Async[F].raiseError(e)
        }
      }

    override def acknowledgeAsync[T](consumer: api.Consumer[T], messageId: MessageId): F[Unit] =
      consumer.acknowledgeAsync(messageId).toF[F].void

    override def acknowledgeCumulativeAsync[T](consumer: api.Consumer[T], messageId: MessageId): F[Unit] =
      consumer.acknowledgeCumulativeAsync(messageId).toF[F].void

    override def negativeAcknowledgeAsync[T](consumer: api.Consumer[T], messageId: MessageId): F[Unit] =
      Async[F].delay { consumer.negativeAcknowledge(messageId) }

    override def close(reader: Reader[_]): F[Unit] = reader.closeAsync().toF[F].void
    override def flush(producer: api.Producer[_]): F[Unit] = producer.flushAsync().toF[F].void

    override def nextAsync[T](reader: Reader[T]): F[ConsumerMessage[T]] =
      reader.readNextAsync().toF[F].map(ConsumerMessage.fromJava)

    override def send[T](builder: TypedMessageBuilder[T]): F[MessageId] =
      builder.sendAsync().toF[F].map(MessageId.fromJava)
  }

} 
Example 12
Source File: ScalazAsyncHandler.scala    From pulsar4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.pulsar4s.scalaz

import java.util.concurrent.CompletableFuture
import java.util.function.BiConsumer

import com.sksamuel.pulsar4s.{AsyncHandler, ConsumerMessage, DefaultProducer, MessageId, Producer}
import org.apache.pulsar.client.api
import org.apache.pulsar.client.api.Consumer
import org.apache.pulsar.client.api.{ProducerBuilder, Reader, TypedMessageBuilder}
import scalaz.concurrent.Task

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

class ScalazAsyncHandler extends AsyncHandler[Task] {

  implicit def completableVoidToTask(f: => CompletableFuture[Void]): Task[Unit] =
    completableToTask(f).map(_ => ())

  implicit def completableToTask[T](f: => CompletableFuture[T]): Task[T] = {
    Task.async[T] { k =>
      f.whenCompleteAsync(new BiConsumer[T, Throwable] {
        override def accept(t: T, e: Throwable): Unit = {
          if (e != null)
            k.apply(scalaz.\/.left(e))
          else
            k.apply(scalaz.\/.right(t))
        }
      })
    }
  }

  override def failed(e: Throwable): Task[Nothing] = Task.fail(e)

  override def createProducer[T](builder: ProducerBuilder[T]): Task[Producer[T]] =
    completableToTask(builder.createAsync()).map(new DefaultProducer(_))

  override def send[T](t: T, producer: api.Producer[T]): Task[MessageId] =
    completableToTask(producer.sendAsync(t)).map(MessageId.fromJava)

  override def receive[T](consumer: api.Consumer[T]): Task[ConsumerMessage[T]] =
    completableToTask(consumer.receiveAsync).map(ConsumerMessage.fromJava)
  
  override def getLastMessageId[T](consumer: api.Consumer[T]): Task[MessageId] =
    completableToTask(consumer.getLastMessageIdAsync()).map(MessageId.fromJava)

  override def unsubscribeAsync(consumer: api.Consumer[_]): Task[Unit] =
    consumer.unsubscribeAsync()

  override def seekAsync(consumer: api.Consumer[_], messageId: MessageId): Task[Unit] =
    consumer.seekAsync(messageId)
  
  override def seekAsync(reader: api.Reader[_], messageId: MessageId): Task[Unit] =
    reader.seekAsync(messageId)
  
  override def seekAsync(reader: api.Reader[_], timestamp: Long): Task[Unit] =
    reader.seekAsync(timestamp)

  override def transform[A, B](f: Task[A])(fn: A => Try[B]): Task[B] = f.flatMap { a =>
    fn(a) match {
      case Success(b) => Task.now(b)
      case Failure(e) => Task.fail(e)
    }
  }

  override def acknowledgeAsync[T](consumer: api.Consumer[T], messageId: MessageId): Task[Unit] =
    consumer.acknowledgeAsync(messageId)

  override def acknowledgeCumulativeAsync[T](consumer: api.Consumer[T], messageId: MessageId): Task[Unit] =
    consumer.acknowledgeCumulativeAsync(messageId)

  override def negativeAcknowledgeAsync[T](consumer: Consumer[T], messageId: MessageId): Task[Unit] =
    Task { consumer.negativeAcknowledge(messageId) }

  override def close(reader: Reader[_]): Task[Unit] = reader.closeAsync()
  override def close(producer: api.Producer[_]): Task[Unit] = producer.closeAsync()
  override def close(consumer: api.Consumer[_]): Task[Unit] = consumer.closeAsync()

  override def flush(producer: api.Producer[_]): Task[Unit] = producer.flushAsync()

  override def nextAsync[T](reader: Reader[T]): Task[ConsumerMessage[T]] =
    reader.readNextAsync().map(ConsumerMessage.fromJava)

  override def send[T](builder: TypedMessageBuilder[T]): Task[MessageId] =
    builder.sendAsync().map(MessageId.fromJava)
}

object ScalazAsyncHandler {
  implicit def handler: AsyncHandler[Task] = new ScalazAsyncHandler
} 
Example 13
Source File: ModelConfigurationParser.scala    From modelmatrix   with Apache License 2.0 5 votes vote down vote up
package com.collective.modelmatrix

import java.nio.charset.CodingErrorAction
import java.security.MessageDigest
import java.util.function.BiConsumer

import com.typesafe.config.{Config, ConfigValue}

import scala.io.Codec
import scalaz.{Failure, Success, ValidationNel}

class ModelConfigurationParser(config: Config, path: String = "features") {

  type FeatureDefinition = (String, ValidationNel[String, ModelFeature])

  private lazy val configLines: Seq[(String, Int)] = {
    implicit val codec = Codec("UTF-8")
    codec.onMalformedInput(CodingErrorAction.REPLACE)
    codec.onUnmappableCharacter(CodingErrorAction.REPLACE)
    contentLines.zipWithIndex
  }

  // Try to find feature row index in original config if possible
  private def featureIndex(f: String): Int = {
    configLines.find(_._1.contains(f)).map(_._2).getOrElse(0)
  }

  private[this] val originUrl = config.origin().url()

  // configuration file as lines
  lazy val contentLines: Seq[String] = {
    if (originUrl != null) {
      scala.io.Source.fromURL(originUrl).getLines().toSeq
      // ideally this case below should never happen unless the Config passed in argument is not parsed from a file
    } else Seq.empty
  }

  // configuration file as a String
  lazy val content: String = contentLines.mkString(System.lineSeparator())

  // md5sum of the configuration content
  lazy val checksum: String = MessageDigest.getInstance("MD5").digest(content.getBytes).map("%02X".format(_)).mkString

  def features(): Seq[FeatureDefinition] = {
    val builder = collection.mutable.ListBuffer.empty[FeatureDefinition]

    config.getObject(path).forEach(new BiConsumer[String, ConfigValue] {
      def accept(t: String, u: ConfigValue): Unit = {
        val parsedFeature = ModelFeature.parse(t, u.atKey(t), t)
        builder += (t -> parsedFeature)
      }
    })

    builder.toSeq.sortBy {
      case (f, Success(feature)) => (true, featureIndex(feature.feature), feature.group, feature.feature)
      case (f, Failure(_)) => (false, featureIndex(f), "", f)
    }
  }
} 
Example 14
Source File: Impl.scala    From jsdependencies   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package org.scalajs.jsdependencies.core.json

import org.json.simple.JSONValue

import java.io.{Writer, Reader}
import java.util.function.{BiConsumer, Consumer}

private[json] object Impl {

  type Repr = Object

  def fromString(x: String): Repr = x
  def fromNumber(x: Number): Repr = x
  def fromBoolean(x: Boolean): Repr = java.lang.Boolean.valueOf(x)

  def fromList(x: List[Repr]): Repr = {
    val result = new java.util.LinkedList[Repr]
    x.foreach(result.add(_))
    result
  }

  def fromMap(x: Map[String, Repr]): Repr = {
    val result = new java.util.HashMap[String, Repr]
    for ((key, value) <- x)
      result.put(key, value)
    result
  }

  def toString(x: Repr): String = x.asInstanceOf[String]
  def toNumber(x: Repr): Number = x.asInstanceOf[Number]
  def toBoolean(x: Repr): Boolean =
    x.asInstanceOf[java.lang.Boolean].booleanValue()

  def toList(x: Repr): List[Repr] = {
    val builder = List.newBuilder[Repr]
    x.asInstanceOf[java.util.List[Repr]].forEach(new Consumer[Repr] {
      def accept(elem: Repr): Unit =
        builder += elem
    })
    builder.result()
  }

  def toMap(x: Repr): Map[String, Repr] = {
    val builder = Map.newBuilder[String, Repr]
    x.asInstanceOf[java.util.Map[String, Repr]].forEach(new BiConsumer[String, Repr] {
      def accept(key: String, value: Repr): Unit =
        builder += key -> value
    })
    builder.result()
  }

  def serialize(x: Repr): String =
    JSONValue.toJSONString(x)

  def serialize(x: Repr, writer: Writer): Unit =
    JSONValue.writeJSONString(x, writer)

  def deserialize(str: String): Repr = JSONValue.parseWithException(str)

  def deserialize(reader: Reader): Repr = JSONValue.parseWithException(reader)

}