How to re-boot liftweb? - scala

I have my Boot.scala with boot method in it where i do my setup.
At the end, I make the call to LiftRules.statelessDispatchTable and append an new instance of my class that extends the RestHelper, which has the serve block.
At some point, I get a signal and need to change this class, so i need to make another call into the statelessDispatchTable to remove the original one and add a new one.
What's a good way to do this?
Thanks!
EDIT: I AM GOING TO UPDATE THE QUESTION WITH THE ANSWER I GOT FROM DAVID POLLAK:
You can't. Once your app is started, there's no way to change LiftRules.
However, the stuff you're adding to statelessDispatchTable is a PartialFunction[Req, Box[LiftResponse]] so you can write a PartialFunction that looks like:
object RestThing1 extends RestHelper { .... }
object RestThing2 extends RestHelper {....}
object MyDynamicRestThing extends PartialFunction[Req, Box[LiftResponse]] {
def isDefinedAt(in: Req): Boolean = if (testCondition) RestThing1.isDefinedAt(in) else RestThing2.isDefinedAt(in)
def apply(in: Req): Box[LiftRequest] = if (testCondition) RestThing1.apply(in) else RestThing2.apply(in)
}
LiftRules.statelessDispatchTable.append(MyDynamicRestThing)

You could create a second-level dispatch...e.g., an object that receives the requests, then according to some other logic proxies the requests on to the real handler. Then you don't have to mess with the top-level dispatch table at all.
Would really make sense to do this if what you are needing to do is toggle it based on a signal (e.g. it will revert back at some point), or if there is additional logic that would benefit from being in a proper abstraction.

Related

Pass data to a ScalaFX JFXApp

I wrote a GUI in ScalaFX whichs works quite well when testing it isolated. Things to mention:
The "real" application itself already has a main method, and only that one should be used to start the application, not the one I get when extending JFXApp. So the call to the main method of JFXApp is done manually, from the outside
It should be possible to pass a data structure to the JFXApp, so I added a setter
The whole startup procedure looks like this:
def main(args: Array[String]) {
...
...
JFXGui.setData(data)
JFXGui.main(Array())
}
The problem:
I cannot draw the contents of the data object as long as the main method of the JFX object is not called, so setData is really just a simple setter method. The idea is that JFXGui should draw the data as soon as possible after JFXGui.main was called. But: how can I realize this inside of JFXGui? Is there something like an "onready"-method?
In the above code, I tried to put the call to the setter after the call to the main method, so that the setter can trigger the drawing. What I hadn't in mind is that JFXGui.main is blocking forever, therefore the call to the setter is unreachable code.
How could I fix this? any help is appreciated, thanks.
edit:
JFXGui is the name of my ScalaFX UI:
object JFXGui extends JFXApp {
private var data: Data = _
def setData(data: Data) {
this.data = data;
}
// tons of ScalaFX related things which visualize the data object
// ...
}
Solution 1 (reusing JFXApp)
The Gui object no longer should be an object, but a class with constructor parameters.
class Gui(data: Data) extends JFXApp {
//your existing code without the field data and the method setData()
}
In the startup class:
new Gui(data).main(Array())
Solution 2 (Custom init)
You do not necessarily have to use JFXApp in order to run your application. I suggest you having a look at the source code of JFXApp.main() and the class AppHelper. They contain ~10 lines of code combined so you can just copy their source code and tailor it to your needs.

How can a private class method be tested in Scala?

I have a companion object with a private method, like so:
package com.example.people
class Person(val age: Int)
object Person {
private def transform(p: Person): Person = new Person(p.age + 1)
}
I would like to test this method, with something like:
class PersonSpec extends FlatSpec {
"A Person" should "transform correctly" in {
val p1 = new Person(1)
val p2 = Person.transform(p1) // doesn't compile, because transform is private!
assert( p2 === new Person(2) )
}
}
Any help on having test code access private methods?
Actually, as it is written, I might be able to create a subclass of Person, but what if Person is declared as final or sealed?
Thanks!
I am in the middle when it comes to testing everything. I don't usually test everything, but sometimes it's really useful to be able to unit test a private function without having to mangle my code to make it possible. If you're using ScalaTest, you can use the PrivateMethodTester to do it.
import org.scalatest.{ FlatSpec, PrivateMethodTester }
class PersonSpec extends FlatSpec with PrivateMethodTester {
"A Person" should "transform correctly" in {
val p1 = new Person(1)
val transform = PrivateMethod[Person]('transform)
// We need to prepend the object before invokePrivate to ensure
// the compiler can find the method with reflection
assert(p2 === p1 invokePrivate transform(p1))
}
}
That may not be exactly what you want to do, but you get the idea.
You could declare your method to be package private:
private[people] def transform(p: Person): Person = new Person(p.age + 1)
If you put PersonSpec in the same package it will be able to access it.
I leave it to you to decide if it's really wise to unit test a private method :)
The need to unit-test private methods is a design smell.
Either you test them through your public API which is ok if they are small and just helper methods - or, which is more likely, it contains different logic/responsibility and should be moved to another class that is used by delegation in the Person. Then you would test the public API of that class first.
See a related answer for more details.
Likely you can access it using Java/Scala reflection, but it is just a workaround for the design problem. Still, if you need to, see a related Java answer how to do that.
#jlegler's answer here helped me, but I still had some debugging to do before things worked, so I thought I'd write exactly what's needed for this here.
to test:
class A
object A {
private def foo(c: C): B = {...}
}
use:
val theFuncion = PrivateMethod[B]('foo)
val result = A invokePrivate theFunction(c)
Note the locations of A, B
Personally, I say make everything public and just prepend with _ or __ to indicate that other devs shouldn't use it.
I realize this is Scala and not Python, but regardless, "We're all consenting adults here."
"Private" methods aren't actually private (for example) and certainly aren't secure, so why make life harder for what is essentially a social contract? Prepend and be done -- if another dev wants to go poking around in dark places, they either have a good reason or deserve what they get.
Generally speaking: if you want to effectively test your code, you first have to write it testable.
Scala implements the functional paradigm and extensively uses immutable objects by design, "case classes" are examples (my opinion: the Person class should be a case class).
Implementing the private methods make sense if objects has mutable state, in this case you might want to protect the state of the objects. But if objects are immutable, why implement methods as private? In your example, the method produces a copy of Person, for what reason do you want to make it private? I do not see any reason.
I suggest you think about this. Again, if you want to effectively test your code you have to write it testable.
a possible work around would be testing private method indirectly: testing a public method which calls the private method
I don't think that unit testing is about testing contract of the class - it is about testing simple functionality(unit).
Also I don't think that it is a good idea to make some methods public only to make them easily testable. I believe that keeping API as narrow as possible is a good way to help other developers to use your code(IDE will not suggest private methods) and understand contract.
Also we should not put everything in a single method. So sometimes we can put some logic into a private method.... and of course we want to test it as well. Testing it through the public API will increase complexity of you test.(other option is to move logic of the private method to another helper class and test it there..this class will not be used directly by developers and will not clutter up api)
Guys from scalatest ,I think, added PrivateMethodTester for a purpose.

Akka and Actor behavior interface

I just start trying myself out with Scala. I grow confident enough to start refactoring an ongoing multi-threaded application that i have been working on for about a year and half.
However something that somehow bother and i can't somehow figure it out, is how to expose the interface/contract/protocole of an Actor? In the OO mode, i have my public interface with synchronized method if necessary, and i know what i can do with that object. Now that i'm going to use actor, it seems that all of that won't be available anymore.
More specifically, I a KbService in my app with a set of method to work with that Kb. I want to make it an actor on its own. For that i need to make all the method private or protected given that now they will be only called by my received method. Hence the to expose the set of available behavior.
Is there some best practice for that ?
To tackle this issue I generally expose the set of messages that an Actor can receive via a "protocol" object.
class TestActor extends Actor {
def receive = {
case Action1 => ???
case Action2 => ???
}
}
object TestActorProtocol {
case object Action1
case object Action2
}
So when you want to communicate with TestActor you must send it a message from its protocol object.
import example.TestActorProtocol._
testActorRef ! TestActorProtocol.Action1
It can become heavy sometimes, but at least there is some kind of contract exposed.
Hope it helps

Serialize Function1 to database

I know it's not directly possible to serialize a function/anonymous class to the database but what are the alternatives? Do you know any useful approach to this?
To present my situation: I want to award a user "badges" based on his scores. So I have different types of badges that can be easily defined by extending this class:
class BadgeType(id:Long, name:String, detector:Function1[List[UserScore],Boolean])
The detector member is a function that walks the list of scores and return true if the User qualifies for a badge of this type.
The problem is that each time I want to add/edit/modify a badge type I need to edit the source code, recompile the whole thing and re-deploy the server. It would be much more useful if I could persist all BadgeType instances to a database. But how to do that?
The only thing that comes to mind is to have the body of the function as a script (ex: Groovy) that is evaluated at runtime.
Another approach (that does not involve a database) might be to have each badge type into a jar that I can somehow hot-deploy at runtime, which I guess is how a plugin-system might work.
What do you think?
My very brief advice is that if you want this to be truly data-driven, you need to implement a rules DSL and an interpreter. The rules are what get saved to the database, and the interpreter takes a rule instance and evaluates it against some context.
But that's overkill most of the time. You're better off having a little snippet of actual Scala code that implements the rule for each badge, give them unique IDs, then store the IDs in the database.
e.g.:
trait BadgeEval extends Function1[User,Boolean] {
def badgeId: Int
}
object Badge1234 extends BadgeEval {
def badgeId = 1234
def apply(user: User) = {
user.isSufficientlyAwesome // && ...
}
}
You can either have a big whitelist of BadgeEval instances:
val weDontNeedNoStinkingBadges = Map(
1234 -> Badge1234,
5678 -> Badge5678,
// ...
}
def evaluator(id: Int): Option[BadgeEval] = weDontNeedNoStinkingBadges.get(id)
def doesUserGetBadge(user: User, id: Int) = evaluator(id).map(_(user)).getOrElse(false)
... or if you want to keep them decoupled, use reflection:
def badgeEvalClass(id: Int) = Class.forName("com.example.badge.Badge" + id + "$").asInstanceOf[Class[BadgeEval]]
... and if you're interested in runtime pluggability, try the service provider pattern.
You can try and use Scala Continuations - they can give you the ability to serialize the computation and run it at later time or even on another machine.
Some links:
Continuations
What are Scala continuations and why use them?
Swarm - Concurrency with Scala Continuations
Serialization relates to data rather than methods. You cannot serialize functionality because it is a class file which is designed to serialize that and object serialization serializes the fields of an object.
So like Alex says, you need a rule engine.
Try this one if you want something fairly simple, which is string based, so you can serialize the rules as strings in a database or file:
http://blog.maxant.co.uk/pebble/2011/11/12/1321129560000.html
Using a DSL has the same problems unless you interpret or compile the code at runtime.

ScalaTest: Issues with Singleton Object re-initialization

I am testing a parser I have written in Scala using ScalaTest. The parser handles one file at a time and it has a singleton object like following:
class Parser{...}
object Resolver {...}
The test case I have written is somewhat like this
describe("Syntax:") {
val dir = new File("tests\\syntax");
val files = dir.listFiles.filter(
f => """.*\.chalice$""".r.findFirstIn(f.getName).isDefined);
for(inputFile <- files) {
val parser = new Parser();
val c = Resolver.getClass.getConstructor();
c.setAccessible(true);
c.newInstance();
val iserror = errortest(inputFile)
val result = invokeparser(parser,inputFile.getAbsolutePath) //local method
it(inputFile.getName + (if (iserror)" ERR" else " NOERR") ){
if (!iserror) result should be (ResolverSuccess())
else if(result.isInstanceOf[ResolverError]) assert(true)
}
}
}
Now at each iteration the side effects of previous iterations inside the singleton object Resolver are not cleaned up.
Is there any way to specify to scalatest module to re-initialize the singleton objects?
Update: Using Daniel's suggestion, I have updated the code, also added more details.
Update: Apparently it is the Parser which is doing something fishy. At subsequent calls it doesn't discard the previous AST. strange. since this is off topic, I would dig more and probably use a separate thread for the discussion, thanks all for answering
Final Update: The issue was with a singleton object other than Resolver, it was in some other file so I had somehow missed it. I was able to solve this using Daniel Spiewak's reply. It is dirty way to do things but its also the only thing, given my circumstances and also given the fact I am writing a test code, which is not going into production use.
According to the language spec, no, there is no way to recreate singleton objects. However, it is possible to reflectively invoke the constructor of a singleton, which overwrites the internal MODULE$ field which contains the actual singleton value:
object Test
Test.hashCode // => e.g. 779942019
val c = Test.getClass.getConstructor()
c.setAccessible(true)
c.newInstance()
Test.hashCode // => e.g. 1806030550
Now that I've shared the evil secret with you, let me caution you never, ever to do this. I would try very very hard to adjust the code, rather than playing sneaky tricks like this one. However, if things are as you say, and you really do have no other option, this is at least something.
ScalaTest has several ways to let you reinitialize things between tests. However, this particular question is tough to answer without knowing more. The main question would be, what does it take to reinitialize the singleton object? If the singleton object can't be reinitialized without instantiating a new singleton object, then you'd need to make sure each test loaded the singleton object anew, which would require using custom class loaders. I find it hard to believe someone would design something that way, though. Can you update your question with more details like that? I'll take a look again later and see if the extra details makes the answer more obvious.
ScalaTest has a runpath that loads classes anew for each run, but not a testpath. So you'll have to roll your own. The real problem here is that someone has designed this in a way that it is not easily tested. I would look at loading Resolver and Parser with a URLClassLoader inside each test. That way you'd get a new Resolver each test.
You'll need to take Parser & Resolver off of the classpath and off of the runpath. Put them into a directory of their own. Then create a URLClassLoader for each test that points to that directory. Then call findClass("Parser") on that class loader to get it. I'm assuming Parser refers to Resolver, and in that case the JVM will go back to the class loader that loaded Parser to get Resolver, which is your URLClassLoader. Do a newInstance on the Parser to get the instance. That should solve your problem, because you'll get a new Resolver singleton object for each test.
No answer, but I do have a simple example of where you might want to reset the singleton object in order to test the singleton construction in multiple, potential situations. Consider something stupid like the following code. You may want to write tests that validates that an exception is thrown when the environment isn't setup correctly and also write a test validates that an exception does not occur when the environment is not setup correctly. I know, I know everyone says, "Provide a default when the environment isn't setup correctly." but I DO NOT want to do this; it would cause issues because there would be no notification that you're using the wrong system.
object RequiredProperties extends Enumeration {
type RequiredProperties = String
private def getRequiredEnvProp(propName: String) = {
sys.env.get(propName) match {
case None => throw new RuntimeException(s"$propName is required but not found in the environment.")
case Some(x) => x
}
}
val ENVIRONMENT: String = getRequiredEnvProp("ENVIRONMENT")
}
Usage:
Init(RequiredProperties.ENVIRONMENT)
If I provided a default then the user would never know that it wasn't set and defaulted to the dev environment. Or something along these lines.