playframework,playframework-2.2 , 'Cannot init the Global object' error after adding a final static constant to Global class

'Cannot init the Global object' error after adding a final static constant to Global class


Tag: playframework,playframework-2.2

I'm using Play Framework 2.2.3 with Java.

I just add a constant to my Global class:

public static final String VERSION = play.application().configuration().getString("application.version");

Then I get this error:

play.api.PlayException: Cannot init the Global object[null]
    at play.api.WithDefaultGlobal$$anonfun$play$api$WithDefaultGlobal$$globalInstance$1.apply(Application.scala:55) ~[play_2.10.jar:2.2.3]
    at play.api.WithDefaultGlobal$$anonfun$play$api$WithDefaultGlobal$$globalInstance$1.apply(Application.scala:49) ~[play_2.10.jar:2.2.3]
    at play.utils.Threads$.withContextClassLoader(Threads.scala:18) ~[play_2.10.jar:2.2.3]
    at play.api.WithDefaultGlobal$$api$WithDefaultGlobal$$globalInstance(Application.scala:48) ~[play_2.10.jar:2.2.3]
    at$api$WithDefaultGlobal$$globalInstance$lzycompute(Application.scala:399) ~[play_2.10.jar:2.2.3]
    at$api$WithDefaultGlobal$$globalInstance(Application.scala:399) ~[play_2.10.jar:2.2.3]
Caused by: java.lang.ExceptionInInitializerError: null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_65]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance( ~[na:1.7.0_65]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance( ~[na:1.7.0_65]
    at java.lang.reflect.Constructor.newInstance( ~[na:1.7.0_65]
    at java.lang.Class.newInstance( ~[na:1.7.0_65]
    at play.api.WithDefaultGlobal$$api$WithDefaultGlobal$$javaGlobal(Application.scala:28) ~[play_2.10.jar:2.2.3]
Caused by: java.lang.RuntimeException: There is no started application
    at scala.sys.package$.error(package.scala:27) ~[scala-library.jar:na]
    at play.api.Play$$anonfun$current$1.apply(Play.scala:68) ~[play_2.10.jar:2.2.3]
    at play.api.Play$$anonfun$current$1.apply(Play.scala:68) ~[play_2.10.jar:2.2.3]
    at scala.Option.getOrElse(Option.scala:120) ~[scala-library.jar:na]
    at play.api.Play$.current(Play.scala:68) ~[play_2.10.jar:2.2.3]
    at play.api.Play.current(Play.scala) ~[play_2.10.jar:2.2.3]

Before my app was working fine. If I put this constant in any other class, my app is working fine. Only if I put it in Global I get this error. Any help?


As in this issue pointed out, if you want to access the configuration during application startup, you should use the onStart method.


How to keep Akka running all the time in Play 2.3

I am using akka as a scheduler in a website written with Play framework 2.3. I kept the server running by using activator run in dev environment. And when I changed some files and tried to visit my website, the Play server will compile these changed files and reload the...

Play Framework routing error that I can't fix

I am building my first controller with the Play Framework. I'm receiving the error: Compilation error value getAll is not a member of controllers.api.protocol.Period My routes.conf file looks like: # Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # Home page GET / controllers.Application.index()...

Play template project requires subscription to typesafe, why?

I'm using Play Framework to create a quick web app. I took template play-java-intro-reactive-platform-15v01, created a new app and when I want to run $ activator test I get an error: [error] == Typesafe Reactive Platform: project/ must exist with typesafe.subscription=< YOUR SUBSCRIPTION ID >. Why? Is it possible to...

Ignore dependency jars on dist task

I have a Play 2.3.x app that consists of some subprojects, and I use dist to generate a zip package of the full application. The problem is that this package is too big, because it includes every dependency needed for the app to run (ex: scala, play libs, db driver(s),...

Configuration depending on launch mode

Play can be launched in dev mode (via run), in production mode (via start) or in test mode. Is there a way to provide a different config file (conf/application.conf) depending on which mode it is launched in?

ScalaJson: Traversing JSValue structure (JSONPath syntax) where key might be one of two different strings

I need to retrieve information from a JsValue that may be structured in a few different ways buy the specific values I'm looking for will always be under similar names. So for example I could have something like: { "name" : "Watership Down", "location" : { "lat" : 51.235685, "long"...

Format a string and replace %s with html element in scala play framework

I have a string like "User: %s" and want to format it and replace "%s" with something like <a href="#">John</a>. How should I do it in view files? P.S. I am using "User: %s".format("John") but browser render I am <a href="#">John</a> instead of "I am John"....

How do I implement a PatternAnalyzer in elastic4s and elasticsearch to exclude result with a certain field

I'm trying to perform a query on my index and get all reviews that do NOT have a reviewer with a gravatar image. To do this I have implemented a PatternAnalyzerDefinition with a host pattern: "^https?\\:\\/\\/([^\\/?#]+)(?:[\\/?#]|$)" that should match and extract host of urls like: becomes: The mapping:...

Advanced HTTP server configurations in Play 2.3

I am using Play 2.3 to develop an application. I need to set http.netty.log.wire to true which is by default false as specified in Play documents. In the below link (last section) it says this option is available but it also specifies "we cannot use application.conf" to specify this.

Accessing a javascript file in play framework

value at is not a member of controllers.ReverseAssets not able to access javascript file using '"assets/app.js") ' <script src='@routes.Assets.**at**("assets/angular.min.js")'></script> ...

How to do database initialization when using DI in Play 2.4?

Play 2.4 discourages using GlobalSettings.onStart and whole Global object. I'm using play-slick and it has great DI sample in GitHub, but it is missing a example how to do database initialization. How does one implement the database initialization when using DI and when GlobalSettings.onStart is not available? Common cases for...

Model.Finder Deperecated Play! 2.4

I am building an application using the latest version of Play!. When defining a Finder( as in Model.Finder) my IDE gives me a warning Finder is deprecated. I can't find any information in the documentation about Model.Finder being deprecated of any alternative to using it. Has anyone experienced a similar...

How to configure the connection pool in Play Framework 1.3 through application.conf and

I'm configured the Play 1.3 application to use four databases (on three different servers). There was a problem of leakage connections, this problem has been partially solved, I wrote about this - Do I need to annotate JPA actions with @Transactional in Play Framework-1.x to prevent the connection leak? Now...

Global Exception Handling in play framework java 2.3.7

I am trying to implement global exception handling in Play framework(RESTful) using Java. While searching I found out that extending GlobalSettings and overriding the onError method should handle all errors and give the appropriate response/view. But in the console where I execute "activator run", I still get the ugly stack...

How does @Inject in Scala work

I'm wondering how does @Inject annotation in Play-Scala works. It obviously injects a dependency, but I'm curious how is it working. When I was using it on class extending controller and set routes generator to injectroutesgenerator it seems to autmagically create objects from those classes, but how do I use...

PlayFramework 2.2.6. Default cache expiration

I would like to store Java object in cache for user session. I would like to know what is default cache storage timeout. I user log in on 8.00 am I will store his user object in cache. Will it keep f.e. 10 hours until user will logout? Will be...

How can I get the ID of an item in a radio-group in a helper.form?

I am building some sort of quiz where the user gets a question and several possible answers. The answers are listed within a radio-group and could be duplicates! Example: How tall is tall? - Very! - Depends on your definition! - Very! The questions and answers come from a list...

Faking Ajax Request Form for testing

In my Playframework 2.4 project I have methods like this: public static Result resetValue(int client) { String receivedName= form().bindFromRequest().get("username"); User user = User.findByName(receivedName); if( user == null ) { return badRequest("No user logged in"); } user.setValue(0); user.saveUsertoDB(); return ok("Value set to zero"); } I want to write JUnit Tests for...

PlayFramework: value as is not a member of Array[Byte]

I want to make file download from a database using Play framework. But when I use this code I get this message: value as is not a member of Array[Byte] And if I change Ok("image/jpg")) to Ok(bytOfImage) it works good but I get a file with a name: secondindex without...

How to reuse MappedColumnType in Table classes?

The use of MappedColumnType is demonstrated in this example: How can I reuse dateColumnType in another table class?...

How to write a custom form helper template for dynamically generated content?

I have some sort of quiz system, where to user gets shown a question and several answer-options with radio-buttons. But as I am using a helper for a inputRadioGroup that gets filled via a list, it does not look pretty anymore (like Twitter Bootstrap). The radiobuttons are inline, while they...

Play Framework: How to Add a Header to Every Response

In the following Controller, Authenticated extracts the token from the request headers and invokes a given action if and only if the token is valid (the code has been simplified for clarity): object MyController extends Controller { def Authenticated(action: Token => EssentialAction) = EssentialAction { requestHeader => val jwt =...

Unit Testing a Play framework Controller

I have written this controller which works perfectly from browser package controllers import play.api._ import play.api.mvc._ class Application extends Controller { val productMap = Map(1 -> "Keyboard", 2 -> "Mouse", 3 -> "Monitor") def listProductsXML() = Action { Ok(views.xml.products(productMap)) } } The route is defined as GET /listProducts.xml controllers.Application.listProductsXML Now...

Scala Play syntax confustion “&>”

I am reading a reactive web programming book about Scala and Play. Can someone explain to me what the following code snippet is about? More specifically, what exactly does &> mean? I understand what an iteratee and enumerator is. val jsonStream: Enumerator[JsValue] = enumerator &> Encoding.decode() &> Enumeratee.grouped(JsonIteratees.jsSimpleObject) ...

Retrieve HTTP status from Promise on Play 2.3.7

in our project we use JSON for data transmission between front and backend. Basically we creating requests by preparing WSRequestHolder, just like the play doc tells to ( and then posting a json string. The WSResponse is then mapped "asJson" returned as a Promise. But unlike WSResponse, the JsonNode does...

Providing implicit value for singletons in Play Json library

I have following configuration: sealed trait Status case object Edited extends Status case object NotEdited extends Status case class Tweet(content:String, status:Status) I want to use Play Json format, so I guess I have to have something like this(I don't want to do it in companion object): trait JsonImpl{ implicit val...

Slick 3.0: Idiomatic way to GET results from the database inside of Option (Scala Play Framework)

I have this code for an API that allows me to retrieve and object from the database and return a JSON object using Slick 3.0: // Model case class Thing(id: Option[Int], name: String) object Thing { implicit val teamWrites = Json.writes[Thing] } class Things(tag: Tag) extends Table[Thing](tag, "thing") { def...

Play Framework: How to get the current port number

How do I get the current port number in a Play application? I use scala.

Play Scala 2.4 linking asynchronous calls

I'm trying to figure out how to link multiple asynchronous calls and return a result. I am currently trying to asynchronously user data first, and update user data asynchronously and return result, but it seems like it is not working :( i used map { result => Ok(result)}, but play...

How to use `controllers.Default.redirect` in Play 2.4 and `InjectedRoutesGenerator`

If I try to use controllers.Default.redirect(to = "/foo/bar") in my routes file with routesGenerator := InjectedRoutesGenerator enabled in my build.sbt file, I get the compilation error type Default is not a member of package controllers With this new injected routes feature in Play 2.4 is there still a way to...

hot swap in sbt project without play-plugin

When I am using play framework, every time I've changed the code, it will take effect automatically by re-compile the code. However, when I'm using sbt to run a project without play-plugin, it won't take effect. I'm wondering if there were a way to make sbt project hot swap the...

Table creation in play 2.4 with play-slick 1.0

I got the play-slick module up and running and am also using evolution in order to create the required tables in the database during application start. For evolution to work it is required to write a 1.sql script which contains the table definitions that I want to create. At the...

JQuery Grab text from td when button clicked

Using the Scala Play Framework in case there is something that adds to the question here. I have a test function ... <script> $(document).ready(function(){ $('.editbtn').click(function(){ $(this).html($(this).html() == 'edit' ? 'modify' : 'edit'); }); }); </script> and a table <table> <tr><td><button class="editbtn">edit</button></td></tr> <tr><td><button class="editbtn">edit</button></td></tr> <tr><td><button...

Json implicit format with recursive class definition

I have a recursive class defined : case class SettingsRepository(id: Option[BSONObjectID], name: Option[String], children: Option[List[SettingsRepository]]) with a JSON implicit format as below : implicit val repositoryFormat = Json.format[SettingsRepository] How can I do to resolve this compilation error? : No implicit format for Option[List[models.practice.SettingsRepository]] available. In /path/to/the/file.scala:95 95 implicit val repositoryFormat...

How to know an object has changed compared to database

I need to know if some fields of a model object has been changed before save because I need to compare the new values with the old ones. I can't touch the model classes are they are generated. My problem is that whenever I change an object in a controller...

Convert existing SBT Scala application to Play

I've been working on building an application with Akka actors, and now that I've completed the actor-based business logic I'd like to give it a RESTful + websocket front-end. I'm trying to find instructions for how to setup Play within the context of an existing application. The only instructions I...

Retrieving number of rows with non-empty one-to-many relation

I am using Play Framework 2 (Java) together with Ebean. Among my model classes, I have classA with a one-to-many relation to classB. The associated table for classB therefore has a field which either contains nullor an id for a classA entity. I would like to retrieve the number of...

Play Scala Converting sync to async

I've been trying to run an Action combined with Action async. I want to know how to run a separate async thread to retrieve some data from the server, and do a redirect or badrequest based off of that result asynchronously. Right now I have to send out a status...

Play Scala activator compile command shows value userid is not a member of[models.Changepas sword]

I am new to play framework(Scala),In my project I need to update new Password for this I need to get user id which is Primary key for that user table. Based on this unique user id value i will update Password. What I need need to get user table's user...

Play Framework using View Tags

This is my day 1 with play framework and I am using view templates Application.scala package controllers import play.api._ import play.api.mvc._ class Application extends Controller { val productMap = Map(1 -> "Keyboard", 2 -> "Mouse", 3 -> "Monitor") def listProducts() = Action { Ok(views.html.products(productMap.values.toSeq)) } } routes GET /listProducts controllers.Application.listProducts...

Play Framework 2.4 don't accept “public static Result” for controllers

I am try to start an app using Play Framework 2.4 with JDK8 in Mac, when I download the base using ./activator new Project play-java the template code contains the next: Project/app/controlles/ package controllers; import play.*; import play.mvc.*; import views.html.*; public class Application extends Controller { public Result index() {...

Not able to access key-values pairs in a JSON using Play library in scala

I am using elasticsearch where as a response from the server I get a JSON. So, val builder = new TermVectorRequestBuilder(client, "new_index", "documents", "0056").setSelectedFields("text") builder.setTermStatistics(true).setFieldStatistics(true) val resp: TermVectorResponse = builder.execute().actionGet() val json_reader = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint() where json_reader is of type org.elasticsearch.common.xcontent.XContentBuilder. Following is what json_reader looks like: "_index""new_index", "_type"...

Play Framework Form Error Handling

This is my view file containing the form that has to filled in by the user: @helper.form(call) { @helper.input(resumeForm("surname"), '_label -> "Surname") { (id, name, value, args) => <input name="@name" type="text" value="@value" placeholder="Enter your surname"> } } This is my custom field constructor: @(elements: helper.FieldElements) @if(!elements.args.isDefinedAt('showLabel) || elements.args('showLabel) == true)...

Play Framework 2.4 IDE Eclipse directions don't work

The directions can be found here: If I try and do activator eclipse I get an error that eclipse isn't a command. Specifically: "[error] Not a valid command: eclipse" If I I add addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0") to plugins.sbt it gives an error....

Finding the implicit value for Json in play

When I use the following code: import JsonImpl.graphFormat val js = Json.toJson(g)(graphFormat) My code compiles and works fine but when I do this it doesn't work and says: "No Json serializer found for type SGraph. Try to implement an implicit Writes or Format for this type." import JsonImpl.graphFormat val js...

Play Framework 2.4 Compilation Error in IntelliJ IDEA 14.1.3

I'm trying to use WebJars with Play Framework 2.4.0, in Intellij IDEA 14.1.3. I have SBT 1.7.0 plugin and Scala 1.5.2 plugin (with project Scala version 2.11.6). My application works well when I run it from the terminal ($ activator run or $ sbt run) but I have compilation error...

Deploying a tar file from CI to heroku

I have a play application for my website. Currently, codeship builds it, and heroku deploys it once the build succeeds. The problem is that since the project has become too big, heroku is not able to build it within 15 minutes while codeship can still build it in less than...

Why does Play Framework 2.3.8 Deployment not work?

I have written a program with the play framework 2.3.8 named quizSystem. It is using a memory database, some controller, viewclasses etc. Now I want to run my program on another machine (windows 7 with JDK 8u45 installed and the PATH set to the JDK), therefore I ran activator dist...

Play! Framework support for Java 8 Optional

I've got a Play! 2 routes file and controller that looks something like this: GET /books BooksController.getBooks(author: play.libs.F.Option[String]) public class BooksController extends Controller { public static Result getBooks(play.libs.F.Option<String> author) { ... } } I would like to refactor it to use Java 8's Optional, but this causes a compilation error:...