File “conf/routes”:
->      /api                        api.Routes // focus on the big R!
->      /                           website.Routes
File “conf/api.routes”:
GET    /healthCheck/status                              api.controllers.HealthCheck.status
GET    /healthCheck/version                             api.controllers.HealthCheck.version
file “conf/website.routes”:
GET    /                         controllers.Home.index
GET    /robots.txt               controllers.Assets.at(path=”/public”, file=”robots.txt”)
GET    /assets/*file             controllers.Assets.at(path=”/public”, file)
GET    /profile                  controllers.Users.profile

 

 

 

 

build.sbt:

javaOptions in Universal ++= Seq( // docker
....
  "-Djava.net.preferIPv4Stack=true"
)
javaOptions in run += "-Djava.net.preferIPv4Stack=true" // dev mode

additionally:

sbt -J-Djava.net.preferIPv4Stack=true

// pdf generation
val play2PDF = "it.innove" % "play2-pdf" % "1.5.1" excludeAll(
ExclusionRule(organization = "com.typesafe.play", name = "twirl-api_2.11"),
ExclusionRule(organization = "com.typesafe.play", name = "play-server_2.11"),
ExclusionRule(organization = "com.typesafe.play", name = "play-java_2.11"),
ExclusionRule(organization = "com.typesafe.play", name = "play-netty-server_2.11"),
ExclusionRule(organization = "com.typesafe.play", name = "play-logback_2.11")
)

Unfortunately, it’s required to hardcode the Scala Version into the Artifact name.. Bug https://github.com/sbt/sbt/issues/1518 is still open.
Additional note: ExclusionRule.artifact actually refers to the type of packaging.. like jar / pom / zip / etc.

To start SBT with the YourKit Agent on a Mac, do it like this (where YourKit-Java-Profiler-YYYY.MM.app is the default installation path):

sbt -J-agentpath:/Applications/YourKit-Java-Profiler-2016.02.app/Contents/Resources/bin/mac/libyjpagent.jnilib

This is the successor of my Post “PlayFramework 2.3: Global CSRF Protection – Disable CSRF selectively“, updated to PlayFramework 2.5!

Adjust your files like this:

1. Adjust your application.conf

2. Create your filter definitions

3. Create your wrapper

4. Annotate your route with the NOCSRF Tag

 
Enjoy!

Google Code shut down a year ago, and recently also their “Migrate to Github” feature was disabled.

Because I have/had also a old project hosted (and some people where asking about it recently), I had to find a way on how to migrate the project to Github anyway.

I did these steps

# download the svn dump'ed repo
wget https://storage.googleapis.com/google-code-archive-source/v2/code.google.com/spring-security-facelets-taglib/repo.svndump.gz
# unzip
gunzip repo.svndump.gz
# create the repo
svnadmin create /tmp/testgc
# restore it
svnadmin load /tmp/testgc/ < repo.svndump

# launch a local svn daemon
svnserve --foreground -d

# in another terminal, clone your repo now using git svn (optionally create a authors file for correctly mapping to git usernames)
git svn --stdlayout -A authors.txt clone svn://localhost/tmp/testgc/

# go into the cloned repo
cd testgc/
# add the upstream github repo
git remote add origin https://github.com/domdorn/spring-security-facelets-taglib.git

#push it
git push --set-upstream origin master

#till now, we only have the trunk / master branch
# get atlassians svn-migration-scripts.jar from https://bitbucket.org/atlassian/svn-migration-scripts/downloads
wget https://bitbucket.org/atlassian/svn-migration-scripts/downloads/svn-migration-scripts.jar

# run the scripts and expect the suggested actions
java -Dfile.encoding=utf-8 -jar svn-migration-scripts.jar clean-git

# if you like what you see (usually you do..), perform the actions
java -Dfile.encoding=utf-8 -jar svn-migration-scripts.jar clean-git --force 

# after this i had a branch structure like this:
git branch -a
# * master
#  remotes/origin/0.2_nate
#  remotes/origin/0.4_gblaszczyk
#  remotes/origin/jsf-1.2-spring-2
#  remotes/origin/jsf-1.2-spring-3
#  remotes/origin/jsf-2.0-spring-2
#  remotes/origin/jsf-2.0-spring-3
#  remotes/origin/master
#  remotes/origin/site
#  remotes/origin/site@17
#  remotes/origin/tags/0.1
#  remotes/origin/tags/0.3_jsf-1.2-spring-2
#  remotes/origin/tags/0.3_jsf-1.2-spring-3
#  remotes/origin/tags/0.3_jsf-2.0_spring-2
#  remotes/origin/tags/0.3_jsf-2.0_spring-3
#  remotes/origin/tags/0.5
#  remotes/origin/trunk

# checkout each branch (except tags and trunk) and push it
for i in `git branch -r | grep -v 'tags\|trunk' `; do git checkout ${i/origin\// }; git push;  done

# push the branches
git push --all origin
# checkout each tag and create a tag with the same name

for i in `git branch -r | grep 'tags'`; do git checkout $i; git tag ${i/origin\/tags\// }; done  

# push the tags git push --tags origin 

Thanks to @chrsmith for responding quickly to my google code email (4 minutes, wow!) and telling me about how to download the repo in the svn dump file format.

Thanks to Atlassian for their svn migration scripts

You can see the result of this work at my Spring Security JSF Taglib Github Project.

 

 

The PlayFramework documentation states on how to override a simple binding of a Class in your Guice Tests to another implementation, like this:

Application application = new GuiceApplicationBuilder()
    .overrides(bind(Component.class).to(MockComponent.class))
    .build();

If you’re using the CacheApi in your tests, you might stumble upon this kind of error:

Error in custom provider, net.sf.ehcache.ObjectExistsException: Cache cmsCache already exists
 at play.api.cache.EhCacheModule.play$api$cache$EhCacheModule$$bindCache$1(Cache.scala:178):
Binding(interface net.sf.ehcache.Ehcache qualified with QualifierInstance(@play.cache.NamedCache(value=cmsCache)) to ProviderTarget(play.api.cache.NamedEhCacheProvider@77f743af)) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)
 while locating net.sf.ehcache.Ehcache annotated with @play.cache.NamedCache(value=cmsCache)
 at play.api.cache.EhCacheModule.play$api$cache$EhCacheModule$$bindCache$1(Cache.scala:179):
Binding(interface play.api.cache.CacheApi qualified with QualifierInstance(@play.cache.NamedCache(value=cmsCache)) to ProviderTarget(play.api.cache.NamedCacheApiProvider@23f72489)) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)
 while locating play.api.cache.CacheApi annotated with @play.cache.NamedCache(value=cmsCache)
 at play.api.cache.EhCacheModule.play$api$cache$EhCacheModule$$bindCache$1(Cache.scala:180):
Binding(interface play.cache.CacheApi qualified with QualifierInstance(@play.cache.NamedCache(value=cmsCache)) to ProviderTarget(play.api.cache.NamedJavaCacheApiProvider@100cf07)) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)

to fix this error, create first a FakeCacheApi Class for your tests like this:

public class FakeCacheApi implements CacheApi {

    private HashMap<String, Object> data = new HashMap<>();


    @Override
    public <T> T get(String s) {
        return (T) data.get(s);
    }

    @Override
    public <T> T getOrElse(String s, Callable<T> callable, int i) {
        return getOrElse(s, callable);
    }

    @Override
    public <T> T getOrElse(String s, Callable<T> callable) {
        if (data.containsKey(s)) {
            return (T) data.get(s);
        } else {
            try {
                T value = callable.call();
                return value;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    @Override
    public void set(String s, Object o, int i) {
        data.put(s, o);
    }

    @Override
    public void set(String s, Object o) {
        data.put(s, o);
    }

    @Override
    public void remove(String s) {
        data.remove(s);
    }
}

and then override the bindings in your tests like this:

import play.cache.NamedCacheImpl;
....
Application application = new GuiceApplicationBuilder() .overrides(
bind(CacheApi.class).to(FakeCacheApi.class),
bind(CacheApi.class).qualifiedWith(new NamedCacheImpl("cmsCache")).to(FakeCacheApi.class) // repeat this line for every named cache you have
).build();

The Play-Framework 2.x provides helpers to work with forms. While the markup created by those helpers works ok for many simple projects, more advanced projects require a specific way on how to style form fields.

The Play-Framework documentation shows how to create a custom FieldConstructor to override the way a form-field is rendered.

This works by implicitly importing the newly created FieldConstructor in every form.

Making sure that this custom FieldConstructor is automatically used in every form, requires just a little code in build.sbt:

val templateSettings = Seq(
  TwirlKeys.templateImports += "views.helper.FoundationFieldConstructorHelper._"
)

 

lazy val mainProject = (project in file("."))
  .enablePlugins(PlayJava)
  ....
  .settings(templateSettings: _*)

Voila! Now this FieldConstructor is used in every form automatically.

An example for a custom FieldConstructor for the Foundation CSS Framework can be found at CoderWall

Packt Publishing, known for their Ebooks and Video courses on programming and programming related stuff, did a survey on whats nice and shiny in our industry at the moment.

To allow everyone access to the most important stuff at a reasonable price, they created a special offer:

  1. Every eBook and Video is now available for $10! Check out the Top 20 here.
  2. Grab some great course bundles  – 5 for $25 on every Video and eBook based on your most essential skills.
  3. PacktLib with over 3000 titles in our library at a reduced rate of $80 for a limited time.

To access the offer, just go here.

For my newest Project I’m using the Play!Framework in Version 2.3.
As I’m just starting out with Scala since a long abstinence, I choose to create a project where I could create controllers in either Java or Scala code.

To do this, I added the line

lazy val root = (project in file(".")).enablePlugins(PlayScala, PlayJava)

to my build.sbt file.

While developing Java Controllers and corresponding views works like a charm, I got an error like

[RuntimeException: There is no HTTP Context available from here.]

when I tried to use the same template also for a Scala Controller.

After some digging around, I found out that the reason for this is that for Java Controllers, a “Context-Object” is created which holds all the relevant stuff for rendering the view ( to be precise a play.mvc.Http.Context is created by the trait play.core.j.JavaAction which then provides everything the view could require as implicits through play.mvc.Http.Context.Implicit )

If you now create a normal Scala Action like this:


object EmailTesting extends Controller {

  def index = Action {
        Ok(views.html.testing.email.index.render())
  }
}

The magic that’s happening for the Java Controllers is missing.. your template tries to access the context/request/session but can’t find it because you would need to add it as implicit parameter which you can’t do if you want to use it from a Java Controller…

So, the trick to make your templates/views work both with Scala and with Java Controllers is to generate the play.mvc.Http.Context explicitly for rendering the view. I created a little helper class to make it easier to use:


object JavaContext {

  import play.mvc.Http
  import play.core.j.JavaHelpers

  def withContext[Status](block: => Status)(implicit header: RequestHeader): Status = {
    try {
      Http.Context.current.set(JavaHelpers.createJavaContext(header))
      block
    }
    finally {
      Http.Context.current.remove()
    }
  }
}

you can apply it then like this (note the requirement for the “implicit requestHeader : RequestHeader“):


object EmailTesting extends Controller {

  def index = Action {
    implicit requestHeader: RequestHeader =>

      JavaContext.withContext {
        Ok(views.html.testing.email.index.render())
      }
  }
}

Now you can use your templates from Java and Scala controllers! You can also use the JavaContext to store objects for usage in your Views without the need to add implicits all over the place.

Feel free to use this code under the Apache 2.0 License.

Update 2017:

For PlayFramework 2.6 you need to slightly adjust the code:

import play.api.mvc.RequestHeader

/**
  * Taken from http://dominikdorn.com/2014/08/play-framework-java-scala-in-one-project-no-http-context-available/
  */
object JavaContext {

  import play.mvc.Http
  import play.core.j.JavaHelpers

  def withContext[Status](block: => Status)(implicit header: RequestHeader): Status = {
    try {
      Http.Context.current.set(JavaHelpers.createJavaContext(header, JavaHelpers.createContextComponents()))
      block
    }
    finally {
      Http.Context.current.remove()
    }
  }
}


top