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. If you want to give something back, a link to my newest project Lyrix.at would be awesome!

Today I had a weird problem with one of my lxc-containers on a Ubuntu 14.04 Host.. for no reason, the container changed its IP address.. This lead to the other containers not finding the container in question under its IP anymore.

I then tried to manually set the IP of the container in /etc/network/interfaces like this

# auto eth0
# iface eth0 inet static
# address 192.168.0.42
# network 192.168.0.0
# netmask 255.255.255.0
# broadcast 192.168.0.255
# gateway 192.168.0.1

However, this was not a good idea.. the container failed to start and basically hung like this:

# lxc-start -n lyrix-prod
<4>init: plymouth-upstart-bridge main process (5) terminated with status 1
<4>init: plymouth-upstart-bridge main process ended, respawning
<4>init: hwclock main process (7) terminated with status 77
<4>init: plymouth-upstart-bridge main process (15) terminated with status 1
<4>init: plymouth-upstart-bridge main process ended, respawning
<4>init: ureadahead main process (8) terminated with status 5
<4>init: plymouth-upstart-bridge main process (19) terminated with status 1
<4>init: plymouth-upstart-bridge main process ended, respawning
* Starting Mount filesystems on boot ...done.
* Stopping Send an event to indicate plymouth is up ...done.
* Starting Signal sysvinit that the rootfs is mounted ...done.
* Stopping Read required files in advance (for other mountpoints) ...done.
* Starting Clean /tmp directory ...done.
* Stopping Clean /tmp directory ...done.
* Starting Populate and link to /run filesystem ...done.
* Stopping Populate and link to /run filesystem ...done.
* Starting Track if upstart is running in a container ...done.
* Starting load fallback graphics devices ...done.
* Starting workaround for missing events in container ...done.
<4>init: udev-fallback-graphics main process (101) terminated with status 1
* Starting load fallback graphics devices ...fail!
<4>init: console-font main process (119) terminated with status 1
* Stopping workaround for missing events in container ...done.
* Starting userspace bootsplash ...done.
* Starting Initialize or finalize resolvconf ...done.
<4>init: setvtrgb main process (133) terminated with status 1
* Starting Send an event to indicate plymouth is up ...done.
* Starting configure network device security ...done.
* Stopping userspace bootsplash ...done.
<4>init: console-setup main process (153) terminated with status 1
* Stopping Send an event to indicate plymouth is up ...done.
* Starting Signal sysvinit that virtual filesystems are mounted ...done.
* Starting Signal sysvinit that virtual filesystems are mounted ...done.
* Starting Bridge udev events into upstart ...done.
* Starting Mount network filesystems ...done.
* Starting Signal sysvinit that local filesystems are mounted ...done.
* Starting configure network device security ...done.
* Starting device node and kernel event manager ...done.
<30>systemd-udevd[202]: starting version 204
* Starting Signal sysvinit that remote filesystems are mounted ...done.
* Starting Failsafe Boot Delay ...done.
* Starting flush early job output to logs ...done.
* Starting load modules from /etc/modules ...done.
* Stopping Mount filesystems on boot ...done.
* Stopping load modules from /etc/modules ...done.
* Stopping flush early job output to logs ...done.
* Stopping Mount network filesystems ...done.
* Starting configure network device ...done.
* Starting configure virtual network devices ...done.
* Starting system logging daemon ...done.
* Starting Bridge socket events into upstart ...done.
* Starting Bridge file events into upstart ...done.
^C ---- container was stuck here....

I resolved it with this ServerFault answer .. now I always configure my containers IP in its container-config file and let the container use the IP it gets from “the BIOS”.

/var/lib/lxc/$containername/config
lxc.network.type=veth
lxc.network.link=lxcbr0
lxc.network.flags=up
lxc.network.ipv4 = 10.0.3.220/24
lxc.network.ipv4.gateway = auto

The containers /etc/network/interfaces now looks like this


auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

Tada! My containers now always get the IPs I want them to get 🙂

I’m using PlayFramework 2.3 [1] on a new project of mine. Because I want the project to be safe by default, I enabled CSRF (Cross Site Request Forgery) Protection globally [2] [3].
In this project, I’m doing a pass-through of some legacy pages using a custom proxy I’ve built. These pages don’t know the concept of CSRF-Tokens and therefor need to be excluded from CSRF checking.
Unfortunately the PlayFrameworks CSRF-Filter currently only allows to either disable CSRF Protection globally and only enable it on certain actions or enable it globally and disable it nowhere… that’s not really what I want..

To accomplish my goal, I had to create a little hack.. thanks to the decorator pattern [4] it is only a few lines of code. It consists of 3 easy steps.

1. Adjust your Global.scala file like this

2. Adjust your routes file. Actions that should be excluded from the CSRF Check need a comment #NOCSRF above them like this

3. This is it basically. If you need your page to have a CSRF Token available (because it e.g. contains a login form), annotate or wrap your actions accordingly

For Scala:

Ärger mit dem “Gebühren Info Service” (GIS) des Österreichischen Rundfunks?

Dafür bietet die GIS eine Hotline… leider ist dies eine 0810 Nummer, welche trotz etwaiger Freiminunten in gängigen (Mobil)telefontarifen kostenpflichtig ist (10ct/Minute).
Abhilfe schafft hier ein kleiner Trick… man sieht sich dazu die aktuellen Nummern der GIS an:

Service Hotline
0810 00 10 80
Fax
05 0200 300

man nehme nun die Fax-Nummer und ersetze die 300 durch 100 und gelangt so zur “Telefonzentrale” des Gebühren Info Services. Von dort kann man sich bequem in die verschiedenen Abteilungen oder auch zur Hotline verbinden lassen.. ganz ohne Mehrkosten.

GIS Gratis Hotline “Telefonzentrale”:
05 0200 100

Hat das geholfen? Folge mir auf Twitter !

top