package common
- Alphabetic
- Public
- All
Type Members
-
sealed abstract
class
Box[+A] extends Product with Serializable
The
Boxclass is a container which is able to declare if it isFull(containing a single non-null value) orEmptyBox.The
Boxclass is a container which is able to declare if it isFull(containing a single non-null value) orEmptyBox. AnEmptyBox, or empty, can be theEmptysingleton,FailureorParamFailure.FailureandParamFailurecontain information about why theBoxis empty including exception information, possibly chainedFailures and aStringmessage.This serves a similar purpose to the
Optionclass from Scala standard library but adds several features:- You can transform it to a
Failureobject if it isEmpty(with the?~orfailMsgmethod). - You can chain failure messages on
Failures (with the?~!orcompoundFailMsgmethod). - 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
Boxto 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
Exceptions 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
Boxand Scala'sOptionprovide 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 aBoxshould be done correctly. Available options are:- Using a
forcomprehension, 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(forcomprehensions 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
Failures):
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
Boxfrom Java easier.A bridge to make using Lift
Boxfrom Java easier.In particular, provides access to the
Boxcompanion object so that functions likelegacyNullTestcan be used easily from Java, as well as access to theEmptysingleton 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
logBoxErrormethod 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
logFailureandlogFailuremethods. The first logs allFailures as well asEmpty. The second logs onlyFailures andParamFailures, treatingEmptyas 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 useinfoLogFailureto log anEmptyorFailureatINFOlevel).All of these return the box unchanged, so you can continue to use it in
forcomprehensions, callopenOron it, etc.There is an implementation for anyone who wants to use Lift's
Loggabletrait 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 aTor aBox[T]can be passed and the "right thing" will happen, includingnulls being treated asEmpty. -
sealed
trait
BoxTrait extends OptionImplicits
Implementation for the
Boxsingleton. -
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
BoxOrRawthat 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
getmethod on a LiftBox. It exists to prevent client code from using.getas 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
EmptyBoxis aBoxcontaining no value.An
EmptyBoxis aBoxcontaining no value. It can sometimes carry additional failure information, as inFailureandParamFailure. -
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
Failureis anEmptyBoxwith an additional failure message explaining the reason for its being empty.A
Failureis anEmptyBoxwith an additional failure message explaining the reason for its being empty. It can also optionally provide an exception and/or a chain of previousFailures 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
Fullis aBoxthat 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
LRUMapis not thread-safe. -
trait
LazyLoggable extends AnyRef
If you mix this into your class, you will get a protected
loggerinstancelazy valthat will be aLoggerinstance.If you mix this into your class, you will get a protected
loggerinstancelazy valthat will be aLoggerinstance.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
loggerinstancevalthat will be aLoggerinstance. -
trait
LoggableBoxLogging extends BoxLogging with Loggable
A version of
BoxLoggingwith a default implementation oflogBoxErrorthat logs to the logger provided by Lift'sLoggable. -
trait
Logger extends AnyRef
Loggeris a thin wrapper on top of an SLF4J Logger.Loggeris 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
ParamFailureis aFailurewith an additional type-safe parameter that can allow an application to store other information related to the failure.A
ParamFailureis aFailurewith 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
BoxOrRawthat 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, andremoveare 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
Vectorclass as backing store, but is Java-friendly as ajava.util.List.An immutable vector that uses the Scala
Vectorclass 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, andremoveare 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
()=>StringandStringinto one type.This trait is used to unify
()=>StringandStringinto 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
Strings andNodeSeqs into one type.This trait is used to unify
Strings andNodeSeqs 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
Tand return responses of typeR. -
class
WrappedLogger extends Logger
Represents a
Loggerbacked by an SLF4JLogger. -
final
case class
ConstNodeSeqFunc(ns: NodeSeq) extends NodeSeqFunc with Product with Serializable
The case class that holds the
NodeSeqconstant.The case class that holds the
NodeSeqconstant.- Annotations
- @deprecated
- Deprecated
(Since version 3.0) Lift now mostly uses
NodeSeq=>NodeSeqtransformations rather thanNodeSeqconstants; consider doing the same.
-
sealed
trait
NodeSeqFunc extends AnyRef
This trait is used to unify
()=>NodeSeqandNodeSeqinto one type.This trait is used to unify
()=>NodeSeqandNodeSeqinto 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=>NodeSeqtransformations rather thanNodeSeqconstants; consider doing the same.
-
final
case class
RealNodeSeqFunc(func: () ⇒ NodeSeq) extends NodeSeqFunc with Product with Serializable
The case class that holds a
NodeSeqfunction.The case class that holds a
NodeSeqfunction.- Annotations
- @deprecated
- Deprecated
(Since version 3.0) Lift now mostly uses
NodeSeq=>NodeSeqtransformations rather thanNodeSeqconstants; 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
BoxLoggingthat makeslogFailureandlogFailureavailable for all code after it's been imported asimport com.elemica.common.BoxLogging._.A convenience singleton for
BoxLoggingthat makeslogFailureandlogFailureavailable 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
HListcontaining a collection ofBox, either generates anHListof the things (unboxed) or aList[Failure]. - object CommonLoanWrapper
-
object
Empty extends EmptyBox with Product with Serializable
Singleton object representing a completely empty
Boxwith 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
Failurewith just a message. - object FuncJBridge extends FuncJBridge
-
object
HLists
Basic support for heterogeneous lists, aka HLists.
Basic support for heterogeneous lists, aka HLists.
An
HListcan be constructed like so:import net.liftweb.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
HListpreserved the value of the types of its members, otherwise we wouldn't have been able to fetchvalueandotherValue, 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
valueis not defined inBase. The inferred type of theListhas to be a common ancestor class or trait ofType1andType2, and no such type has avaluemethod. -
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
Loggerinstances.Provides some helpers to easily create
Loggerinstances.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
ParamFailures, as well as allow pattern-matching on theParamFailure. -
object
StringFunc
Provides implicit conversions to the
StringFunctrait.Provides implicit conversions to the
StringFunctrait. This allows using aStringas a natural part of APIs that want to allow the flexibility of a()=>Stringwithout 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
Stringor a()=>String. The latter could use the current request and session state to do more interesting things than a hard-codedStringwould, while the former is simpler to use. -
object
StringOrNodeSeq
Provides implicit conversions to the
StringOrNodeSeqtrait, which can in turn be implicitly converted toNodeSeq.Provides implicit conversions to the
StringOrNodeSeqtrait, which can in turn be implicitly converted toNodeSeq. This allows using aStringas a natural part ofNodeSeqAPIs without having to explicitly wrap it inscala.xml.Textor having to write overloads for all methods that should accept both.This is used in certain Lift APIs, for example, to accept either a
Stringor more complex content. For example, abuttoncan have either a simple label or complex HTML content. HTML APIs that can do this can accept a parameter of typeStringOrNodeSeqto allow the user to pass either in as their needs dictate.
Deprecated Value Members
-
object
NodeSeqFunc
Provides implicit conversions to the
NodeSeqFunctrait.Provides implicit conversions to the
NodeSeqFunctrait. This allows using aNodeSeqas a natural part of APIs that want to allow the flexibility of a()=>NodeSeqwithout having to write overloads for all methods that should accept both.- Annotations
- @deprecated
- Deprecated
(Since version 3.0) Lift now mostly uses
NodeSeq=>NodeSeqtransformations rather thanNodeSeqconstants; consider doing the same.