pekko/akka-actor/src/main/scala/akka/japi/JavaAPI.scala

273 lines
8.5 KiB
Scala
Raw Normal View History

/*
2018-01-04 17:26:29 +00:00
* Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com>
*/
package akka.japi
import java.util.Collections.{ emptyList, singletonList }
import akka.util.Collections.EmptyImmutableSeq
import scala.collection.immutable
import scala.language.implicitConversions
import scala.reflect.ClassTag
import scala.runtime.AbstractPartialFunction
import scala.util.control.NoStackTrace
2011-08-26 17:25:18 +02:00
/**
* A Function interface. Used to create first-class-functions is Java.
*
* This class is kept for compatibility, but for future API's please prefer [[akka.japi.function.Function]].
*/
trait Function[T, R] {
@throws(classOf[Exception])
def apply(param: T): R
}
/**
* A Function interface. Used to create 2-arg first-class-functions is Java.
*
* This class is kept for compatibility, but for future API's please prefer [[akka.japi.function.Function2]].
*/
trait Function2[T1, T2, R] {
@throws(classOf[Exception])
def apply(arg1: T1, arg2: T2): R
}
/**
* A Procedure is like a Function, but it doesn't produce a return value.
*
* This class is kept for compatibility, but for future API's please prefer [[akka.japi.function.Procedure]].
*/
trait Procedure[T] {
@throws(classOf[Exception])
2012-05-18 13:37:26 +02:00
def apply(param: T): Unit
}
2010-11-24 14:49:10 +01:00
/**
* An executable piece of code that takes no parameters and doesn't return any value.
*
* This class is kept for compatibility, but for future API's please prefer [[akka.japi.function.Effect]].
2010-11-24 14:49:10 +01:00
*/
trait Effect {
@throws(classOf[Exception])
2012-05-18 13:37:26 +02:00
def apply(): Unit
2010-11-24 14:49:10 +01:00
}
/**
* Java API: Defines a criteria and determines whether the parameter meets this criteria.
*
* This class is kept for compatibility, but for future API's please prefer [[java.util.function.Predicate]].
*/
trait Predicate[T] {
def test(param: T): Boolean
}
/**
* Java API
* Represents a pair (tuple) of two elements.
*
* Additional tuple types for 3 to 22 values are defined in the `akka.japi.tuple` package, e.g. [[akka.japi.tuple.Tuple3]].
*/
@SerialVersionUID(1L)
case class Pair[A, B](first: A, second: B) {
def toScala: (A, B) = (first, second)
}
object Pair {
def create[A, B](first: A, second: B): Pair[A, B] = new Pair(first, second)
}
/**
* A constructor/factory, takes no parameters but creates a new value of type T every call.
*
* This class is kept for compatibility, but for future API's please prefer [[akka.japi.function.Creator]].
*/
@SerialVersionUID(1L)
trait Creator[T] extends Serializable {
/**
* This method must return a different instance upon every call.
*/
@throws(classOf[Exception])
def create(): T
}
object JavaPartialFunction {
sealed abstract class NoMatchException extends RuntimeException with NoStackTrace
case object NoMatch extends NoMatchException
final def noMatch(): RuntimeException = NoMatch
}
/**
* Helper for implementing a *pure* partial function: it will possibly be
* invoked multiple times for a single application, because its only abstract
* method is used for both isDefinedAt() and apply(); the former is mapped to
* `isCheck == true` and the latter to `isCheck == false` for those cases where
* this is important to know.
*
* Failure to match is signaled by throwing `noMatch()`, i.e. not returning
* normally (the exception used in this case is pre-allocated, hence not
* <i>that</i> expensive).
*
* {{{
* new JavaPartialFunction<Object, String>() {
* public String apply(Object in, boolean isCheck) {
* if (in instanceof TheThing) {
* if (isCheck) return null; // to spare the expensive or side-effecting code
* return doSomethingWithTheThing((TheThing) in);
* } else {
* throw noMatch();
* }
* }
* }
* }}}
*
* The typical use of partial functions from Akka looks like the following:
*
* {{{
* if (pf.isDefinedAt(x)) {
* pf.apply(x);
* }
* }}}
*
2014-02-27 17:14:38 -05:00
* i.e. it will first call `JavaPartialFunction.apply(x, true)` and if that
* does not throw `noMatch()` it will continue with calling
2014-02-27 17:14:38 -05:00
* `JavaPartialFunction.apply(x, false)`.
*/
abstract class JavaPartialFunction[A, B] extends AbstractPartialFunction[A, B] {
import JavaPartialFunction._
@throws(classOf[Exception])
def apply(x: A, isCheck: Boolean): B
final def isDefinedAt(x: A): Boolean = try { apply(x, true); true } catch { case NoMatch false }
final override def apply(x: A): B = try apply(x, false) catch { case NoMatch throw new MatchError(x) }
final override def applyOrElse[A1 <: A, B1 >: B](x: A1, default: A1 B1): B1 = try apply(x, false) catch { case NoMatch default(x) }
}
/**
* This class represents optional values. Instances of <code>Option</code>
* are either instances of case class <code>Some</code> or it is case
* object <code>None</code>.
*/
sealed abstract class Option[A] extends java.lang.Iterable[A] {
def get: A
/**
* Returns <code>a</code> if this is <code>some(a)</code> or <code>defaultValue</code> if
* this is <code>none</code>.
*/
def getOrElse[B >: A](defaultValue: B): B
def isEmpty: Boolean
2012-05-18 13:37:26 +02:00
def isDefined: Boolean = !isEmpty
def asScala: scala.Option[A]
def iterator: java.util.Iterator[A] = if (isEmpty) emptyList[A].iterator else singletonList(get).iterator
}
object Option {
/**
* <code>Option</code> factory that creates <code>Some</code>
*/
def some[A](v: A): Option[A] = Some(v)
/**
* <code>Option</code> factory that creates <code>None</code>
*/
def none[A] = None.asInstanceOf[Option[A]]
/**
* <code>Option</code> factory that creates <code>None</code> if
* <code>v</code> is <code>null</code>, <code>Some(v)</code> otherwise.
*/
def option[A](v: A): Option[A] = if (v == null) none else some(v)
2011-08-26 17:25:18 +02:00
/**
* Converts a Scala Option to a Java Option
*/
def fromScalaOption[T](scalaOption: scala.Option[T]): Option[T] = scalaOption match {
case scala.Some(r) some(r)
case scala.None none
}
/**
* Class <code>Some[A]</code> represents existing values of type
* <code>A</code>.
*/
final case class Some[A](v: A) extends Option[A] {
2012-05-18 13:37:26 +02:00
def get: A = v
def getOrElse[B >: A](defaultValue: B): B = v
2012-05-18 13:37:26 +02:00
def isEmpty: Boolean = false
def asScala: scala.Some[A] = scala.Some(v)
}
/**
* This case object represents non-existent values.
*/
private case object None extends Option[Nothing] {
2012-05-18 13:37:26 +02:00
def get: Nothing = throw new NoSuchElementException("None.get")
def getOrElse[B](defaultValue: B): B = defaultValue
2012-05-18 13:37:26 +02:00
def isEmpty: Boolean = true
def asScala: scala.None.type = scala.None
}
implicit def java2ScalaOption[A](o: Option[A]): scala.Option[A] = o.asScala
2011-08-26 17:25:18 +02:00
implicit def scala2JavaOption[A](o: scala.Option[A]): Option[A] = if (o.isDefined) some(o.get) else none
2010-10-29 16:33:31 +02:00
}
2012-01-26 17:47:31 +01:00
/**
* This class hold common utilities for Java
*/
object Util {
/**
* Returns a ClassTag describing the provided Class.
*/
def classTag[T](clazz: Class[T]): ClassTag[T] = ClassTag(clazz)
/**
* Returns an immutable.Seq representing the provided array of Classes,
* an overloading of the generic immutableSeq in Util, to accommodate for erasure.
*/
def immutableSeq(arr: Array[Class[_]]): immutable.Seq[Class[_]] = immutableSeq[Class[_]](arr)
/**
* Turns an array into an immutable Scala sequence (by copying it).
*/
def immutableSeq[T](arr: Array[T]): immutable.Seq[T] = if ((arr ne null) && arr.length > 0) Vector(arr: _*) else Nil
/**
* Turns an [[java.lang.Iterable]] into an immutable Scala sequence (by copying it).
*/
def immutableSeq[T](iterable: java.lang.Iterable[T]): immutable.Seq[T] =
iterable match {
case imm: immutable.Seq[_] imm.asInstanceOf[immutable.Seq[T]]
case other
val i = other.iterator()
if (i.hasNext) {
val builder = new immutable.VectorBuilder[T]
do { builder += i.next() } while (i.hasNext)
builder.result()
} else EmptyImmutableSeq
}
def immutableSingletonSeq[T](value: T): immutable.Seq[T] = value :: Nil
!htp #18919 #19519 New JavaDSL for Akka HTTP (#20518) * !htt #18919 #19519 Align Java HTTP server DSL with Scala This commits replaces the Java HTTP server DSL with a Java-8 centric one which exposes all scala DSL concepts to be usable from Java, including custom directives, (un)marshallers, rejections, headers, and type safety for path and query parameters. * Add RequestContext and RouteResult to Java DSL fix websockets WIP bring java docs up to date. This applies some updates to the root-level documentation * [htp] Fix java documentation to correctly mention timeouts Timeouts are configured the same in Java and Scala. Hence, linking to the scala docs for timeouts from Java. * =htc fix optionalHeaderValueByType in Java * =htt #20200 fix java testkit always using NoLogging instead logger * +htt actually run new javadsl tests, allow overriding config * =htt improve javadsl test infra with more details when fails * =htt fix bug in wrong path matcher exposed * +htp add missing remaining path matcher * =htp Java DSL cookie tests fixed * =htt Java DSL ParameterDirectivesTest fixed Protect the tweets from scalariform Incorrect response expectations in cache condition directives spec fixed * =htt Path directives for Java DSL * +!htt PathMatchers rewritten, made uniform and tests passing * Bugfix in java reject and a little test-boyscouting * Revert "Incorrect response expectations in cache condition directives spec fixed" This reverts commit cd50e89d45db010309f8249b090ea654ebb11c7a. * +htc HttpAPIsTest is compile time only, not for running Also, moved from the client package since not strictly a client test. SecurityDirectives passing Two faulty tests and two actual bugs. Fix for cache condition spec not working * Not sending in Unit instad of the implicit magnet in the test * HeaderMagnet now works as expected * Java API added for - and + on DateTime PetStore example and test fixed * Annotations to make marshalling work without default constructor * Made model class immutable Incorrect tests fixed Some scaladoc boyscouting as bonus * =htt RequestValTest sprinkled out across multiple directive tests Client ip extraction test with incorrect header name fixed. * =htt Incorrect CodingDirectivesTest fixed. * =htt Bugfix for Java Unmarshaller.firstOf and fixes to JavaRouteTest * =htt MarshallerTest fixed * Missing seal signature added to JavaDSL * More consistent (with Scala) test kit setup for Java * missing Javadocs added * Thread.sleep in default exception handler removed * =htt copy directive docs, prepare for finishing it up * +htt SecurityDirectives.authorize variants and test coverage added * +htt Custom headers in Java DSL * =htt WIP on java docs * +htp add missing parameterOrDefault directive Fixed a lot of doc warnings * =htc intense progress on javadsl docs * =htc #20470 Link to issue about docs and fix compile error compile, migration guide don't mima check http-experimental * =htt Java DSL doc warnings fixed. Only `Could not lex literal_block` ones left now * =htc fix mima settings * =doc fix MethodDirectives doc test with custom method * =htc fix coding directives spec after bad merge * =htc fix concat being corresponding to route() in javadsl * =htt Disable consistency check for route/concat as it fails only on ci server * !htt Minor fixes to PathMatchers
2016-05-16 10:38:40 +02:00
def javaArrayList[T](seq: Seq[T]): java.util.List[T] = {
val size = seq.size
val l = new java.util.ArrayList[T](size)
seq.foreach(l.add) // TODO could be optimised based on type of Seq
l
}
/**
* Turns an [[java.lang.Iterable]] into an immutable Scala IndexedSeq (by copying it).
*/
def immutableIndexedSeq[T](iterable: java.lang.Iterable[T]): immutable.IndexedSeq[T] =
immutableSeq(iterable).toVector
// TODO in case we decide to pull in scala-java8-compat methods below could be removed - https://github.com/akka/akka/issues/16247
def option[T](jOption: java.util.Optional[T]): scala.Option[T] =
scala.Option(jOption.orElse(null.asInstanceOf[T]))
}