java.util.function.BiFunction Scala Examples
The following examples show how to use java.util.function.BiFunction.
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: SpringCloudGatewayHttpResponse.scala From Linkis with Apache License 2.0 | 5 votes |
package com.webank.wedatasphere.linkis.gateway.springcloud.http import java.util.function.BiFunction import com.webank.wedatasphere.linkis.common.conf.Configuration import com.webank.wedatasphere.linkis.gateway.http.GatewayHttpResponse import javax.servlet.http.Cookie import org.reactivestreams.Publisher import org.springframework.http.server.reactive.{AbstractServerHttpResponse, ServerHttpResponse} import org.springframework.http.{HttpStatus, ResponseCookie} import reactor.core.publisher.{Flux, Mono} import reactor.ipc.netty.http.server.HttpServerResponse import reactor.ipc.netty.http.websocket.{WebsocketInbound, WebsocketOutbound} class SpringCloudGatewayHttpResponse(response: ServerHttpResponse) extends GatewayHttpResponse { private val cachedHTTPResponseMsg = new StringBuilder private val cachedWebSocketResponseMsg = new StringBuilder private val cachedRedirectUrlMsg = new StringBuilder private var responseMono: Mono[Void] = _ override def addCookie(cookie: Cookie): Unit = { val responseCookie = ResponseCookie.from(cookie.getName, cookie.getValue) responseCookie.maxAge(cookie.getMaxAge) responseCookie.secure(cookie.getSecure) responseCookie.path(cookie.getPath) responseCookie.domain(cookie.getDomain) responseCookie.httpOnly(cookie.isHttpOnly) response.addCookie(responseCookie.build()) } override def setHeader(key: String, value: String): Unit = response.getHeaders.add(key, value) override def setStatus(status: Int): Unit = response.setStatusCode(HttpStatus.valueOf(status)) override def write(message: String): Unit = cachedHTTPResponseMsg.append(message) override def sendResponse(): Unit = if(responseMono == null) synchronized { if(responseMono != null) return if(cachedRedirectUrlMsg.nonEmpty) { if(response.getStatusCode == null || (response.getStatusCode != null && !response.getStatusCode.is3xxRedirection())) response.setStatusCode(HttpStatus.TEMPORARY_REDIRECT) response.getHeaders.set("Location", cachedRedirectUrlMsg.toString) responseMono = response.setComplete() return } setHeader("Content-Type", "application/json;charset=UTF-8") if(cachedHTTPResponseMsg.nonEmpty) { val dataBuffer = response.bufferFactory().wrap(cachedHTTPResponseMsg.toString.getBytes(Configuration.BDP_ENCODING.getValue)) val messageFlux = Flux.just(Array(dataBuffer): _*) responseMono = response.writeWith(messageFlux) } else if(cachedWebSocketResponseMsg.nonEmpty) { response match { case abstractResponse: AbstractServerHttpResponse => val nativeResponse = abstractResponse.getNativeResponse.asInstanceOf[HttpServerResponse] responseMono = nativeResponse.sendWebsocket(new BiFunction[WebsocketInbound, WebsocketOutbound, Publisher[Void]] { override def apply(in: WebsocketInbound, out: WebsocketOutbound): Publisher[Void] = { val dataBuffer = response.bufferFactory().wrap(cachedWebSocketResponseMsg.toString.getBytes(Configuration.BDP_ENCODING.getValue)) SpringCloudHttpUtils.sendWebSocket(out, dataBuffer) } }) case _ => } } } override def isCommitted: Boolean = responseMono != null def getResponseMono: Mono[Void] = responseMono override def writeWebSocket(message: String): Unit = cachedWebSocketResponseMsg.append(message) override def redirectTo(url: String): Unit = cachedRedirectUrlMsg.append(url) }
Example 2
Source File: ExceptionCountAccumulator.scala From spark-distcp with Apache License 2.0 | 5 votes |
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 3
Source File: CassandraReadSideImpl.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.internal.javadsl.persistence.cassandra import java.util import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage import java.util.function.BiFunction import java.util.function.Function import java.util.function.Supplier import javax.inject.Inject import javax.inject.Singleton import akka.Done import akka.actor.ActorSystem import com.datastax.driver.core.BoundStatement import com.lightbend.lagom.internal.javadsl.persistence.ReadSideImpl import com.lightbend.lagom.internal.persistence.cassandra.CassandraOffsetStore import com.lightbend.lagom.javadsl.persistence.ReadSideProcessor.ReadSideHandler import com.lightbend.lagom.javadsl.persistence._ import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraReadSide.ReadSideHandlerBuilder import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraReadSide import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraSession import play.api.inject.Injector @Singleton private[lagom] final class CassandraReadSideImpl @Inject() ( system: ActorSystem, session: CassandraSession, offsetStore: CassandraOffsetStore, readSide: ReadSideImpl, injector: Injector ) extends CassandraReadSide { private val dispatcher = system.settings.config.getString("lagom.persistence.read-side.use-dispatcher") implicit val ec = system.dispatchers.lookup(dispatcher) override def builder[Event <: AggregateEvent[Event]](eventProcessorId: String): ReadSideHandlerBuilder[Event] = { new ReadSideHandlerBuilder[Event] { import CassandraAutoReadSideHandler.Handler private var prepareCallback: AggregateEventTag[Event] => CompletionStage[Done] = tag => CompletableFuture.completedFuture(Done.getInstance()) private var globalPrepareCallback: () => CompletionStage[Done] = () => CompletableFuture.completedFuture(Done.getInstance()) private var handlers = Map.empty[Class[_ <: Event], Handler[Event]] override def setGlobalPrepare(callback: Supplier[CompletionStage[Done]]): ReadSideHandlerBuilder[Event] = { globalPrepareCallback = () => callback.get this } override def setPrepare( callback: Function[AggregateEventTag[Event], CompletionStage[Done]] ): ReadSideHandlerBuilder[Event] = { prepareCallback = callback.apply this } override def setEventHandler[E <: Event]( eventClass: Class[E], handler: Function[E, CompletionStage[util.List[BoundStatement]]] ): ReadSideHandlerBuilder[Event] = { handlers += (eventClass -> ((event: E, offset: Offset) => handler(event))) this } override def setEventHandler[E <: Event]( eventClass: Class[E], handler: BiFunction[E, Offset, CompletionStage[util.List[BoundStatement]]] ): ReadSideHandlerBuilder[Event] = { handlers += (eventClass -> handler.apply _) this } override def build(): ReadSideHandler[Event] = { new CassandraAutoReadSideHandler[Event]( session, offsetStore, handlers, globalPrepareCallback, prepareCallback, eventProcessorId, dispatcher ) } } } }
Example 4
Source File: CaffeineImplForAsyncCache.scala From graphcool-framework with Apache License 2.0 | 5 votes |
package cool.graph.cache import java.util.concurrent.{CompletableFuture, Executor} import java.util.function.BiFunction import com.github.benmanes.caffeine.cache.{AsyncCacheLoader, Caffeine, AsyncLoadingCache => AsyncCaffeineCache, Cache => CaffeineCache} import scala.compat.java8.FunctionConverters._ import scala.compat.java8.FutureConverters._ import scala.concurrent.{ExecutionContext, Future} object CaffeineImplForAsyncCache { def lfu[K, V >: Null](initialCapacity: Int, maxCapacity: Int)(implicit ec: ExecutionContext): AsyncCache[K, V] = { val caffeineCache = Caffeine .newBuilder() .initialCapacity(initialCapacity) .maximumSize(maxCapacity) .asInstanceOf[Caffeine[K, V]] .buildAsync[K, V](dummyLoader[K, V]) CaffeineImplForAsyncCache(caffeineCache) } //LfuCache requires a loader function on creation - this will not be used. private def dummyLoader[K, V] = new AsyncCacheLoader[K, V] { def asyncLoad(k: K, e: Executor) = Future.failed[V](new RuntimeException("Dummy loader should not be used by LfuCache")).toJava.toCompletableFuture } } case class CaffeineImplForAsyncCache[K, V >: Null](underlying: AsyncCaffeineCache[K, V])(implicit ec: ExecutionContext) extends AsyncCache[K, V] { override def get(key: K): Future[Option[V]] = { val cacheEntry = underlying.getIfPresent(key) if (cacheEntry != null) { cacheEntry.toScala.map(Some(_)) } else { Future.successful(None) } } override def put(key: K, value: Future[Option[V]]): Unit = { val asCompletableNullableFuture = value.map(_.orNull).toJava.toCompletableFuture underlying.put(key, asCompletableNullableFuture) } override def remove(key: K): Unit = underlying.synchronous().invalidate(key) override def getOrUpdate(key: K, fn: () => Future[V]): Future[V] = { val javaFn = toCaffeineMappingFunction[K, V](fn) underlying.get(key, javaFn).toScala } override def getOrUpdateOpt(key: K, fn: () => Future[Option[V]]): Future[Option[V]] = { val nullable: () => Future[V] = () => fn().map(_.orNull) val javaFn = toCaffeineMappingFunction[K, V](nullable) val cacheEntry = underlying.get(key, javaFn) if (cacheEntry != null) { cacheEntry.toScala.map(Option(_)) } else { Future.successful(None) } } private def toCaffeineMappingFunction[K, V](genValue: () ⇒ Future[V]): BiFunction[K, Executor, CompletableFuture[V]] = { asJavaBiFunction[K, Executor, CompletableFuture[V]]((_, _) ⇒ genValue().toJava.toCompletableFuture) } }
Example 5
package opencl.ir.interop import java.util.function.BiFunction import lift.arithmetic.ArithExpr import ir._ import ir.ast._ import opencl.ir.pattern._ object jGather { def create(idx: BiFunction[ArithExpr, Type, ArithExpr]) = { val idxLambda = (a: ArithExpr, t: Type) => idx(a,t) Gather(idxLambda) } } object jScatter { def create(idx: BiFunction[ArithExpr, Type, ArithExpr]) = { val idxLambda = (a: ArithExpr, t: Type) => idx(a,t) Scatter(idxLambda) } } object jMapGlb { def create(f: Lambda1) = MapGlb(f) def create(f: FunDecl) = MapGlb(Lambda1.FunDefToLambda(f)) } object jMapWrg { def create(f: Lambda1) = MapWrg(f) def create(f: FunDecl) = MapWrg(Lambda1.FunDefToLambda(f)) } object jMapLcl { def create(f: Lambda1) = MapLcl(f) def create(f: FunDecl) = MapLcl(Lambda1.FunDefToLambda(f)) } object jMapWarp { def create(f: Lambda1) = MapWarp(f) def create(f: FunDecl) = MapWarp(Lambda1.FunDefToLambda(f)) } object jMapLane { def create(f: Lambda1) = MapLane(f) def create(f: FunDecl) = MapLane(Lambda1.FunDefToLambda(f)) } object jMapSeq { def create(f: Lambda1) = MapSeq(f) def create(f: FunDecl) = MapSeq(Lambda1.FunDefToLambda(f)) } object jReduceSeq { def create(f: Lambda2, init: Value) = ReduceSeq(f, init) def create(f: FunDecl, init: Value) = ReduceSeq(Lambda2.FunDefToLambda(f), init) } object jReorderStride { def create (s: ArithExpr)= ReorderStride(s) } object jTranspose { def create = Transpose() def comp(f: Lambda) = create o f def comp(f: FunDecl) = create o Lambda.FunDefToLambda(f) } object jToGlobal { def create(f: Lambda1) = toGlobal(f) def create(f: FunDecl) = toGlobal(Lambda1.FunDefToLambda(f)) } object jToLocal { def create(f: Lambda1) = toLocal(f) def create(f: FunDecl) = toLocal(Lambda1.FunDefToLambda(f)) } object jSlide { def create(size: Int, step: Int, negOOB: (ArithExpr, ArithExpr) => ArithExpr, posOOB: (ArithExpr, ArithExpr) => ArithExpr) = Slide(size, step) } object jGroup2D { def create(size1: Int, step1: Int, size2: Int, step2: Int, negOOB: (ArithExpr, ArithExpr) => ArithExpr, posOOB: (ArithExpr, ArithExpr) => ArithExpr) = Slide2D(size1, step1, size2, step2) } object jGet { def create(e: Expr, n: Int) = Get(e, n) }
Example 6
Source File: CallSites.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.util import java.util.concurrent.ConcurrentHashMap import java.util.function.BiFunction private[scio] object CallSites { private val scioNs = "com.spotify.scio" private val beamNs = "org.apache.beam" private val methodMap = Map("$plus$plus" -> "++") private val nameCache = new ConcurrentHashMap[(String, String, Boolean), Int]() private def isExternalClass(c: String): Boolean = // Not in our code base or an interpreter (!c.startsWith(scioNs) && !c.startsWith("scala.") && !c.startsWith(beamNs)) || c.startsWith(s"$scioNs.examples.") || // unless if it's in examples c.startsWith(s"$scioNs.values.NamedTransformTest") || // or this test c.startsWith(s"$scioNs.values.SimpleJob") || // or this test c.startsWith(s"$scioNs.values.ClosureTest") || // or this test // or benchmarks/ITs (c.startsWith(scioNs) && (c.contains("Benchmark$") || c.contains("IT"))) private def isTransform(e: StackTraceElement): Boolean = e.getClassName == s"$scioNs.values.SCollectionImpl" && e.getMethodName == "transform" private def isPCollectionApply(e: StackTraceElement): Boolean = e.getClassName == s"$beamNs.sdk.values.PCollection" && e.getMethodName == "apply" def getAppName: String = Thread .currentThread() .getStackTrace .drop(1) .map(_.getClassName) .find(isExternalClass) .getOrElse("unknown") .split("\\.") .last .replaceAll("\\$$", "") def getCurrent: String = { val (method, location, nested) = getCurrentName val idx = nameCache.merge( (method, location, nested), 1, new BiFunction[Int, Int, Int] { override def apply(t: Int, u: Int): Int = t + u } ) if (nested) { s"$method:$idx" } else { s"$method@{$location}:$idx" } } def getCurrentName: (String, String, Boolean) = { val stack = Thread.currentThread().getStackTrace.drop(1) val firstExtIdx = stack.indexWhere(e => isExternalClass(e.getClassName)) val scioMethod = stack(firstExtIdx - 1).getMethodName val method = methodMap.getOrElse(scioMethod, scioMethod) // find first stack outside of Scio or SDK val externalCall = stack(firstExtIdx) val location = s"${externalCall.getFileName}:${externalCall.getLineNumber}" // check if transform is nested val transformIdx = stack.indexWhere(isTransform) val pApplyIdx = stack.indexWhere(isPCollectionApply) val isNested = transformIdx > 0 && pApplyIdx > 0 val collIdx = stack.lastIndexWhere(_.getClassName.contains("SCollectionImpl"), pApplyIdx) (stack.lift(collIdx).fold(method)(_.getMethodName), location, isNested) } }