package common
- Alphabetic
- Public
- Protected
Type Members
- sealed abstract class Box[+A] extends Product with Serializable
The
Box
class is a container which is able to declare if it isFull
(containing a single non-null value) orEmptyBox
.The
Box
class is a container which is able to declare if it isFull
(containing a single non-null value) orEmptyBox
. AnEmptyBox
, or empty, can be theEmpty
singleton,Failure
orParamFailure
.Failure
andParamFailure
contain information about why theBox
is empty including exception information, possibly chainedFailure
s and aString
message.This serves a similar purpose to the
Option
class from Scala standard library but adds several features:- You can transform it to a
Failure
object if it isEmpty
(with the?~
orfailMsg
method). - You can chain failure messages on
Failure
s (with the?~!
orcompoundFailMsg
method). - You can "run" a function on a
Box
, with a default to return if the box isEmpty
:
val littleTeddyBears: Box[Int] = Full(10) littleTeddyBears.run("and then there were none") { (default: String, teddyBears: Int) => s"$teddyBears little teddy bears" } // => 10 little teddy bears val updatedTeddyBears: Box[Int] = Empty littleTeddyBears.run("and then there were none") { (default: String, teddyBears: Int) => s"$teddyBears little teddy bears" } // => and then there were none
- You can "pass" a
Box
to a function for side effects:
val littleTeddyBears: Box[Int] = Full(10) doSomething( littleTeddyBears $ { teddyBears: Box[Int] => println("Are there any?") println(teddyBears openOr 0) } ) // doSomething gets a Box[Int] as well
Exceptions and Empty Box Handling
If you grew up on Java, you're used to
Exception
s as part of your program logic. The Scala philosophy and the Lift philosophy is that exceptions are for exceptional conditions such as failure of an external resource (e.g., your database goes offline) rather than simply indicating that a parameter wasn't supplied or couldn't be parsed.Lift's
Box
and Scala'sOption
provide mechanisms for being explicit about a value existing or not existing rather than relying on a reference being not-null. However, extracting a value from aBox
should be done correctly. Available options are:- Using a
for
comprehension, especially for multiple boxes:
val loggedInUser: Box[User] = for { username <- possibleUsername password <- possiblePassword user <- User.find("username" -> username) if User.checkPassword(password, user.password) } yield { user }
- Using
map
,flatMap
,filter
, andforeach
(for
comprehensions use these under the covers):
val fullName: Box[String] = loggedInUser.map { user => user.name + " (" + user.nickname + ")" } val bestFriend: Box[User] = loggedInUser.flatMap { user => UserFriends.find(user.bestFriend.id) } val allowedUser: Box[User] = loggedInUser.filter(_.canAccess_?(currentPage)) fullName.foreach { name => logger.info(s"User $name is in the building.") }
- Using pattern-matching (a good way to deal with
Failure
s):
val loginMessage: String = loggedInUser match { case Full(user) => "Login successful!" case Failure(message, _, _) => s"Login failed: $message" case Empty => s"Unknown failure logging in." }
- For comparisons (e.g., in tests), use
==
and===
:
loggedInUser must_== Full(mockUser) (loggedInUser === mockUser) must beTrue
- You can transform it to a
- class BoxJBridge extends AnyRef
A bridge to make using Lift
Box
from Java easier.A bridge to make using Lift
Box
from Java easier.In particular, provides access to the
Box
companion object so that functions likelegacyNullTest
can be used easily from Java, as well as access to theEmpty
singleton so that empty values can be created easily from Java. - trait BoxLogging extends AnyRef
Mix this trait in to get some low-cost implicits for logging boxes easily.
Mix this trait in to get some low-cost implicits for logging boxes easily. The consumer will need to implement a
logBoxError
method to log messages with an optionalThrowable
, as well as its related friends for trace, debug, info, and warn levels. This allows abstracting out where and what the actual logger is.With this mixed in, boxes will have
logFailure
andlogFailure
methods. The first logs allFailure
s as well asEmpty
. The second logs onlyFailure
s andParamFailure
s, treatingEmpty
as a valid value. These both log their respective items at ERROR level. You can also usetraceLog*
,debugLog*
,infoLog*
, andwarnLog*
if you want to log at other levels (e.g., you can useinfoLogFailure
to log anEmpty
orFailure
atINFO
level).All of these return the box unchanged, so you can continue to use it in
for
comprehensions, callopenOr
on it, etc.There is an implementation for anyone who wants to use Lift's
Loggable
trait calledLoggableBoxLogging
. Another implementaiton is available for use with a plain SLF4J logger,SLF4JBoxLogging
. You can also implement a version for any other logging adapter. Lastly, you can simply importBoxLogging._
to get the methods available at a top level; however, note that using them this way will lose information about where the log message came from.Here is an example of how you might use this in system that executes a third- party service and notifies another system of failures.
val systemResult: Box[ServiceReturn] = system .executeService(true, requester) .map(...) .logFailure("Failed to execute service") match { case Full(content) => content case failure: Failure => otherSystem.notifyFailure(failure) case Empty => otherSystem.notifyFailure(Failure("No idea what happened.")) }
- sealed trait BoxOrRaw[T] extends AnyRef
Sometimes it's convenient to access either a
Box[T]
or aT
.Sometimes it's convenient to access either a
Box[T]
or aT
. If you specifyBoxOrRaw[T]
, either aT
or aBox[T]
can be passed and the "right thing" will happen, includingnull
s being treated asEmpty
. - sealed trait BoxTrait extends OptionImplicits
Implementation for the
Box
singleton. - trait Boxable[T] extends AnyRef
A trait that a class can mix into itself to indicate that it can convert itself into a
Box
. - final case class BoxedBoxOrRaw[T](box: Box[T]) extends BoxOrRaw[T] with Product with Serializable
The
BoxOrRaw
that represents a boxed value. - trait CommonLoanWrapper extends AnyRef
A component that takes action around some other functionality.
A component that takes action around some other functionality. It may choose to execute or not execute that functionality, but should not interpret or change the returned value; instead, it should perform orthogonal actions that need to occur around the given functionality. A canonical example is wrapping an SQL transaction around some piece of code.
As an example, this trait defines the principal contract for function objects that wrap the processing of HTTP requests in Lift.
- final case class ConstStringFunc(str: String) extends StringFunc with Product with Serializable
See
StringFunc
. - final class DoNotCallThisMethod extends AnyRef
Used as a return type for certain methods that should not be called.
Used as a return type for certain methods that should not be called. One example is the
get
method on a LiftBox
. It exists to prevent client code from using.get
as an easy way to open aBox
, so it needs a return type that will match no valid client return types. - sealed abstract class EmptyBox extends Box[Nothing] with Serializable
An
EmptyBox
is aBox
containing no value.An
EmptyBox
is aBox
containing no value. It can sometimes carry additional failure information, as inFailure
andParamFailure
. - sealed trait ExcludeThisType[A, B] extends AnyRef
Encoding for "A is not a subtype of B".
- sealed case class Failure(msg: String, exception: Box[Throwable], chain: Box[Failure]) extends EmptyBox with Product with Serializable
A
Failure
is anEmptyBox
with an additional failure message explaining the reason for its being empty.A
Failure
is anEmptyBox
with an additional failure message explaining the reason for its being empty. It can also optionally provide an exception and/or a chain of previousFailure
s that may have caused this one. - trait ForwardableActor[From, To] extends AnyRef
Interface for an actor that can internally forward received messages to other actors.
- final case class Full[+A](value: A) extends Box[A] with Product with Serializable
Full
is aBox
that contains a value. - final class Func extends AnyRef
The bridge from various arity FuncX to Scala's function instances
- trait Func0[Z] extends AnyRef
A zero argument function that returns something of type Z
- trait Func1[A, Z] extends AnyRef
A one argument function that returns something of type Z
- trait Func2[A, B, Z] extends AnyRef
A two argument function that returns something of type Z
- trait Func3[A, B, C, Z] extends AnyRef
A three argument function that returns something of type Z
- trait Func4[A, B, C, D, Z] extends AnyRef
A four argument function that returns something of type Z
- class FuncJBridge extends AnyRef
Bridges from Java functions to Scala functions.
Bridges from Java functions to Scala functions.
The implicits defined here allow Scala code to interact seamlessly between the Java function-like interfaces and the Scala function interfaces for various function arities.
In particular, there is a pair of implicits for each arity of function from 0 to 4. There is one implicit (called
lift
) from the Java function type to the corresponding Scala function type and one (calleddrop
) from the Scala function type to the corresponding Java function type. - trait GenericActor[+R] extends TypedActor[Any, R]
Generic Actor interface.
Generic Actor interface. Can receive any type of message. Can return (via
!!
and!?
) messages of typeR
. - class LRUMap[K, V] extends LinkedListElem[K, V]
Implements an LRU Hashmap.
Implements an LRU Hashmap. Given a size, this map will evict the least recently used item(s) when new items are added.
Note that
LRUMap
is not thread-safe. - trait LazyLoggable extends AnyRef
If you mix this into your class, you will get a protected
logger
instancelazy val
that will be aLogger
instance.If you mix this into your class, you will get a protected
logger
instancelazy val
that will be aLogger
instance.Useful for mixing into objects that are created before Lift has booted (and thus Logging is not yet configured).
- trait Loggable extends AnyRef
If you mix this into your class, you will get a protected
logger
instanceval
that will be aLogger
instance. - trait LoggableBoxLogging extends BoxLogging with Loggable
A version of
BoxLogging
with a default implementation oflogBoxError
that logs to the logger provided by Lift'sLoggable
. - trait Logger extends AnyRef
Logger
is a thin wrapper on top of an SLF4J Logger.Logger
is a thin wrapper on top of an SLF4J Logger.The main purpose is to utilize Scala features for logging.
Note that the dynamic type of "this" is used when this trait is mixed in.
This may not always be what you want. If you need the static type, you have to declare your own
Logger
:class MyClass { val logger = Logger(classOf[MyClass]) }
- final class ParamFailure[T] extends Failure with Serializable
A
ParamFailure
is aFailure
with an additional type-safe parameter that can allow an application to store other information related to the failure.A
ParamFailure
is aFailure
with an additional type-safe parameter that can allow an application to store other information related to the failure.For example:
val loggedInUser = for { username ?~ "Missing username" ~> "error.missingUser" password ?~! "Missing password" ~> "error.missingPassword" user <- User.find("username" -> username) if User.checkPassword(password, user.password) } yield { user } loggedInUser match { case ParamFailure(message, _, _, i18nKey: String) => tellUser(i18n(i18nKey)) case Failure(message, _, _) => tellUser(failureMessage) case Empty => tellUser("Unknown login failure.") case _ => tellUser("You're in!") }
- final case class RawBoxOrRaw[T](raw: T) extends BoxOrRaw[T] with Product with Serializable
The
BoxOrRaw
that represents a raw value. - final case class RealStringFunc(func: () => String) extends StringFunc with Product with Serializable
See
StringFunc
. - trait SLF4JBoxLogging extends BoxLogging
- trait SimpleActor[-T] extends AnyRef
The simple definition of an actor.
The simple definition of an actor. Something that can be sent a message of type
T
. - final case class SimpleList[T](underlying: List[T]) extends List[T] with Product with Serializable
An immutable singly linked list that uses the Scala List class as backing store, but is Java-friendly as a
java.util.List
.An immutable singly linked list that uses the Scala List class as backing store, but is Java-friendly as a
java.util.List
. Note however that since it is immutable, you have to capture the results of addition/removal operations.The typical mutating methods like
add
,set
,clear
, andremove
are all unsupported, as are mutating methods on its iterators, since this collection is immutable. - final case class SimpleVector[T](underlying: Vector[T]) extends List[T] with Product with Serializable
An immutable vector that uses the Scala
Vector
class as backing store, but is Java-friendly as ajava.util.List
.An immutable vector that uses the Scala
Vector
class as backing store, but is Java-friendly as ajava.util.List
. Note however that since it is immutable, you have to capture the results of addition/removal operations.The typical mutating methods like
add
,set
,clear
, andremove
are all unsupported, as are mutating methods on its iterators, since this collection is immutable.- See also
"Scala's Collection Library overview" section on Vectors for more information.
- trait SimplestActor extends SimpleActor[Any]
An Actor that can receive a message of any type.
- trait SimplestGenericActor extends GenericActor[Any]
Generic Actor interface.
Generic Actor interface. Can receive any type of message. Can return (via
!!
and!?
) messages of any type. - sealed trait StringFunc extends AnyRef
This trait is used to unify
()=>String
andString
into one type.This trait is used to unify
()=>String
andString
into one type. It is used in conjunction with the implicit conversions defined in its companion object. - sealed trait StringOrNodeSeq extends AnyRef
This trait is used to unify
String
s andNodeSeq
s into one type.This trait is used to unify
String
s andNodeSeq
s into one type. It is used in conjuction with the implicit conversions defined in its companion object. - trait Tryo extends AnyRef
- trait TypedActor[-T, +R] extends SimpleActor[T]
An Actor that can receive messsages of type
T
and return responses of typeR
. - class WrappedLogger extends Logger
Represents a
Logger
backed by an SLF4JLogger
.
Deprecated Type Members
- final case class ConstNodeSeqFunc(ns: NodeSeq) extends NodeSeqFunc with Product with Serializable
The case class that holds the
NodeSeq
constant.The case class that holds the
NodeSeq
constant.- Annotations
- @deprecated
- Deprecated
(Since version 3.0) Lift now mostly uses
NodeSeq=>NodeSeq
transformations rather thanNodeSeq
constants; consider doing the same.
- sealed trait NodeSeqFunc extends AnyRef
This trait is used to unify
()=>NodeSeq
andNodeSeq
into one type.This trait is used to unify
()=>NodeSeq
andNodeSeq
into one type. It is used in conjunction with the implicit conversions defined in its companion object.- Annotations
- @deprecated
- Deprecated
(Since version 3.0) Lift now mostly uses
NodeSeq=>NodeSeq
transformations rather thanNodeSeq
constants; consider doing the same.
- final case class RealNodeSeqFunc(func: () => NodeSeq) extends NodeSeqFunc with Product with Serializable
The case class that holds a
NodeSeq
function.The case class that holds a
NodeSeq
function.- Annotations
- @deprecated
- Deprecated
(Since version 3.0) Lift now mostly uses
NodeSeq=>NodeSeq
transformations rather thanNodeSeq
constants; consider doing the same.
Value Members
- object Box extends BoxTrait with Tryo with Serializable
The Box companion object provides methods to create a Box from:
- object BoxLogging extends LoggableBoxLogging
A convenience singleton for
BoxLogging
that makeslogFailure
andlogFailure
available for all code after it's been imported asimport com.elemica.common.BoxLogging._
.A convenience singleton for
BoxLogging
that makeslogFailure
andlogFailure
available for all code after it's been imported asimport com.elemica.common.BoxLogging._
. Logging done this way will come fromBoxLogging
, not from the class where the box was logged. - object BoxOrRaw
Companion object with implicit conversions to allow
BoxOrRaw[T]
to masquerade as the appropriate types. - object CombinableBox
Via an
HList
containing a collection ofBox
, either generates anHList
of the things (unboxed) or aList[Failure]
. - object CommonLoanWrapper
- case object Empty extends EmptyBox with Product with Serializable
Singleton object representing a completely empty
Box
with no value or failure information. - object ExcludeThisType
The companion object to
ExcludeThisType
.The companion object to
ExcludeThisType
. This allows one of specify that a type is not a subtype of another type.Based on work by Miles Sabin.
- object Failure extends Serializable
Companion object used to simplify the creation of a simple
Failure
with just a message. - object FuncJBridge extends FuncJBridge
- object HLists
Basic support for heterogeneous lists, aka HLists.
Basic support for heterogeneous lists, aka HLists.
An
HList
can be constructed like so:import olon.common.HLists._ trait Base case class Type1(value: String) extends Base case class Type2(otherValue: String) extends Base val myHList = Type1("Value") :+: Type2("Other Value") :+: HNil myHList match { case firstThing :+: secondThing :+: HNil => println(firstThing.value) println(secondThing.otherValue) }
Above, we see that the
HList
preserved the value of the types of its members, otherwise we wouldn't have been able to fetchvalue
andotherValue
, respectively.Trying the same thing with a list won't work:
val myList = Type1("Value") :: Type2("Other Value") :: Nil myList match { case firstThing :: secondThing :: Nil => // error: value value is not a member of Product with Serializable with Base println(firstThing.value) }
This is because
value
is not defined inBase
. The inferred type of theList
has to be a common ancestor class or trait ofType1
andType2
, and no such type has avalue
method. - object Log4j
Configuration helpers for the log4j logging backend.
- object Logback
Configuration helpers for the Logback logging backend.
- object Logger
Provides some helpers to easily create
Logger
instances.Provides some helpers to easily create
Logger
instances.For example:
class MyClass { val logger = Logger(classOf[MyClass]) }
It can also be used to provide global setup for loggers created this way:
Logger.setup = Full(Logback.withFile(new URL("file:///path/to/config.xml"))) class MyClass { val logger = Logger(classOf[MyClass]) logger.debug("Hello") // uses the above configuration }
Last but not least, you can wrap chunks of code with particular Mapped Diagnostic Context values:
Logger.logWith("mykey" -> "value") { logger.debug("stuff") // has mykey set to value in the MDC } logger.debug("more stuff") // mykey is set to its previous value
- object MDC
The Mapped Diagnostics Context can hold values per thread and output them with each logged output.
The Mapped Diagnostics Context can hold values per thread and output them with each logged output.
The logging backend needs to be configured to log these values.
- object ParamFailure extends Serializable
Companion object used to simplify the creation of simple
ParamFailure
s, as well as allow pattern-matching on theParamFailure
. - object StringFunc
Provides implicit conversions to the
StringFunc
trait.Provides implicit conversions to the
StringFunc
trait. This allows using aString
as a natural part of APIs that want to allow the flexibility of a()=>String
without having to write overloads for all methods that should accept both.Lift's Menu API, for example, allows CSS classes to be defined either as a
String
or a()=>String
. The latter could use the current request and session state to do more interesting things than a hard-codedString
would, while the former is simpler to use. - object StringOrNodeSeq
Provides implicit conversions to the
StringOrNodeSeq
trait, which can in turn be implicitly converted toNodeSeq
.Provides implicit conversions to the
StringOrNodeSeq
trait, which can in turn be implicitly converted toNodeSeq
. This allows using aString
as a natural part ofNodeSeq
APIs without having to explicitly wrap it inscala.xml.Text
or having to write overloads for all methods that should accept both.This is used in certain Lift APIs, for example, to accept either a
String
or more complex content. For example, abutton
can have either a simple label or complex HTML content. HTML APIs that can do this can accept a parameter of typeStringOrNodeSeq
to allow the user to pass either in as their needs dictate.
Deprecated Value Members
- object NodeSeqFunc
Provides implicit conversions to the
NodeSeqFunc
trait.Provides implicit conversions to the
NodeSeqFunc
trait. This allows using aNodeSeq
as a natural part of APIs that want to allow the flexibility of a()=>NodeSeq
without having to write overloads for all methods that should accept both.- Annotations
- @deprecated
- Deprecated
(Since version 3.0) Lift now mostly uses
NodeSeq=>NodeSeq
transformations rather thanNodeSeq
constants; consider doing the same.