Yaml fixtures of java playframework doesn't work as expected - java

I tried to make the zenTasks tutorial for the play-java framework (I use the current playframework, which is 2.3.2). As it comes to testing and adding fixtures I'm kind of lost!
The docu states that
Edit the conf/test-data.yml file and start to describe a User:
- !!models.User
email: bob#gmail.com
name: Bob
password: secret
...
And I should download a sample (which is in fact a dead link!)
So I tried myself adding more Users like this:
- !!models.User
email: somemail1#example.com
loginName: test1
- !!models.User
email: somemail2#example.com
loginName: test2
If I then try to load it via
Object load = Yaml.load("test-data.yml");
if (load instanceof List){
List list = (List)load;
Ebean.save(list);
} else {
Ebean.save(load);
}
I get the following Exception:
[error] Test ModelsTest.createAndRetrieveUser failed:
java.lang.IllegalArgumentException: This bean is of type [class
java.util.ArrayList] is not enhanced?, took 6.505 sec [error] at
com.avaje.ebeaninternal.server.persist.DefaultPersister.saveRecurse(DefaultPersister.java:270)
[error] at
com.avaje.ebeaninternal.server.persist.DefaultPersister.save(DefaultPersister.java:244)
[error] at
com.avaje.ebeaninternal.server.core.DefaultServer.save(DefaultServer.java:1610)
[error] at
com.avaje.ebeaninternal.server.core.DefaultServer.save(DefaultServer.java:1600)
[error] at com.avaje.ebean.Ebean.save(Ebean.java:453) [error]
at ModelsTest.createAndRetrieveUser(ModelsTest.java:18) [error]
...
How Am I supposed to load more than one User (or whatever object I wish) and parse them without exception?

In Ebean class save method is overloaded.
save(Object) - expects parameter which is entity (extends Model, has #Entity annotation)
save(Collection) - expects collection of entities.
Yaml.load function returns objecs which can be:
Entity
List of entities
But if we simply do:
Object load = Yaml.load("test-data.yml");
Ebean.save(load);
then save(Object) method will be called. This is because at compile time compiler doesn't know what exactly will Yaml.load return. So above code will throw exception posted is question when there is more then one user in "test-data.yml" file.
But when we cast the result to List as in code provided by OP then everything works good. save(Collection) method is called and all entities are saved correctly. So the code from question is correct.

I have same problem with loading data from "test-data.yml". But I have found solution for this problem. Here is http://kewool.com/2013/07/bugs-in-play-framework-version-2-1-1-tutorial-fixtures/ solution code. But all Ebean.save methods must be replaced with Ebean.saveAll methods.

Related

How to allow catchError in Jenkins?

So I fixed one of my organisation's needs by adding a catchError statement in one of their groovy files but in turn this creates a build error with a generic Jenkins test library BasePipelineTest:
[main] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - PipelineTest.testCall_AllFieldsAvailable:71 ? MissingMethod No signature
[main] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - PipelineTest.testCall_FieldsNotAvailable:130 ? MissingMethod No signature
As part of the Jenkins standard BasePipelineTest class the solution for this is typically:
helper.registerAllowedMethod("cleanWs", []) {}
For a method like cleanWs(), or something similar depending on the method and its inputs. However this is for methods with input values, but catchError doesn't have input values, rather it's done like:
catchError {
...
}
So helper.registerAllowedMethod("catchError", []) {} does not work. Does anyone know how to make it work for something like catchError?
I have also attempted:
helper.registerAllowedMethod("catchError", [com.lesfurets.jenkins.unit.catchError]) {}
This creates a MissingProperty error
Turns out the curly brackets themselves register as a class in groovy. I fixed it with:
helper.registerAllowedMethod("catchError", [Closure.class]) {}

Alternative for AnyLogic deprecated method getJComponent()?

I recently updated to AnyLogic PLE 8.4.0 and Java SE 12 on my Windows 10 laptop. And now an AnyLogic model that used to work earlier stops with the error "The method getJComponent() is undefined for the type ShapeTextField." I looked it up in AnyLogic/Help and I notice that getJComponent is identified as "Deprecated" and no alternative is identified. It appears to me that some mismatch happened between AnyLogic and Java updates that resulted in this error. I would appreciate any workarounds to get the model working.
Tried replacing getJComponent() with the following:
by getX() - gave error "cannot cast from double to Jtextfield"
by getPresentable() - gave error "cannot cast from Presentable to Jtextfield"
by getClass() - gave error "Description: Cannot cast from Class to JTextField."
by getComponentGraphics() - gave error "Description: The method getComponentGraphics() is undefined for the type ShapeTextField."
by equals - gave error "Description: The method equals(Object) in the type Object is not applicable for the arguments ()."
The code is:
((JTextField)(editbox.getJComponent())).setHorizontalAlignment(JTextField.LEFT);
This is defined in Simulation - Simulation Experiment / Java Actions/ Initial Experiment Setup field
Expected result: No error message. And the model should proceed to run window.
Thanks to the inputs from #Benjamin and #Felipe the following worked:
I replaced the editbox and buttons with corresponding artifacts from
AL8.4 palette. I copied the code from the earlier artifacts to
corresponding fields in the new artifacts. I deleted the artifacts
that were from AL7.
I commented out the line that was meant to align the editbox since
that capability is not available anymore.
With the above two changes I didn't get the error message about undefined method. The editbox and buttons worked and allowed me to enter XML filename and reading it with an XML parser routine. I have now run into issue with JAXB integration with AL8.4 and haven't been able to get past that yet. I will be posting that as a separate question.

Custom views in SecureSocial in Java

I saw a few questions about this topic, but none answer the part I am stuck on. By the way, based on the issues people are running into, I might suggest giving a default java implementation of the TemplatesPlugin after all.
The problem I have, is that I copied the two needed views from SecureSocial to my views folder, and changed the RequestHeader as others have noted to: play.api.mvc.RequestHeader and now I am getting:
ambiguous implicit values: both method requestHeader in object PlayMagicForJava of type => play.api.mvc.RequestHeader and value request of type play.api.mvc.RequestHeader match expected type play.api.mvc.RequestHeader
Version: Play-2.1.1, Java 7, SecureSocial from Master.
EDIT:
Play Compile:
[error] C:\Java\AwsConsole\app\views\secure\login.scala.html:41: ambiguous impli
cit values:
[error] both method requestHeader in object PlayMagicForJava of type => play.ap
i.mvc.RequestHeader
[error] and value request of type play.api.mvc.RequestHeader
[error] match expected type play.api.mvc.RequestHeader
[error] #provider(p.id)
[error] ^
[error] C:\Java\AwsConsole\app\views\secure\provider.scala.html:20: ambiguous im
plicit values:
[error] both method requestHeader in object PlayMagicForJava of type => play.ap
i.mvc.RequestHeader
[error] and value request of type play.api.mvc.RequestHeader
[error] match expected type play.api.mvc.RequestHeader
[error] <form action = "#securesocial.core.providers.utils.Route
sHelper.authenticateByPost("userpass").absoluteURL(IdentityProvider.sslEnabled)"
[error]
^
[error] two errors found
[error] (compile:compile) Compilation failed
Browsing after Play Run instead:
Internal server error, for (GET) [/] ->
sbt.PlayExceptions$CompilationException: Compilation error[ambiguous implicit va
lues:
both method requestHeader in object PlayMagicForJava of type => play.api.mvc.Re
questHeader
and value request of type play.api.mvc.RequestHeader
match expected type play.api.mvc.RequestHeader]
at sbt.PlayReloader$$anon$2$$anonfun$reload$2$$anonfun$apply$15$$anonfun
$apply$16.apply(PlayReloader.scala:349) ~[na:na]
at sbt.PlayReloader$$anon$2$$anonfun$reload$2$$anonfun$apply$15$$anonfun
$apply$16.apply(PlayReloader.scala:349) ~[na:na]
at scala.Option.map(Option.scala:133) ~[scala-library.jar:na]
at sbt.PlayReloader$$anon$2$$anonfun$reload$2$$anonfun$apply$15.apply(Pl
ayReloader.scala:349) ~[na:na]
at sbt.PlayReloader$$anon$2$$anonfun$reload$2$$anonfun$apply$15.apply(Pl
ayReloader.scala:346) ~[na:na]
at scala.Option.map(Option.scala:133) ~[scala-library.jar:na]
The request must be passed explicitely to the login template, the login template must pass the request explicitely to the provider template and the provider template must specify the request when invoking RoutesHelper.authenticateByPost("userpass").absoluteURL. More detailed:
The java TemplatesPlugin should have this getLoginPage implementation:
#Override
public <A> Html getLoginPage(final play.api.mvc.Request<A> request, final Form<Tuple2<String, String>> form,
final Option<String> msg) {
return views.html.login.render(request, form, msg);
}
The parameters (first line) of login.scala.html should look like this:
#(request: play.api.mvc.RequestHeader, loginForm: play.api.data.Form[(String,String)], errorMsg: Option[String] = None)
Change calls from login.scala.html to the provider template to pass the request explicitely (we'll adjust its parameters in the next step).
login.scala.html line 41, change
#provider(p.id)
to
#provider(request, p.id)
login.scala.html line 55, change
#provider("userpass", Some(loginForm))
to
#provider(request, "userpass", Some(loginForm))
The parameters (first line) of provider.scala.html should take the request as first, explicit parameter:
#(request: play.api.mvc.RequestHeader, providerId: String, loginForm: Option[play.api.data.Form[(String, String)]] = None)
Line 20 of the provider template needs to pass the request (so that the correct method is invoked, otherwise you'll get a RuntimeException: There is no HTTP Context available from here):
<form action = "#securesocial.core.providers.utils.RoutesHelper.authenticateByPost("userpass").absoluteURL(IdentityProvider.sslEnabled)(request)"
This should be all needed changes, if you're using other templates they would have to be adjusted accordingly.
Just to mentiond it: I had changed our java TemplatesPlugin to a scala version (to have it more straight forward).

org.jbehave.core.io.storyresourcenotfound exception when running jbehave test in eclipse

I am getting this exception when I run the IT test written jbehave in eclipse.
org.jbehave.core.io.storyresourcenotfound
I have path_steps.java and path_story.java in test/java/package and path.story file in the same package in test/resources/package.
Not sure what needs to be changed.
I'm not sure if my context was the same as yours, but in my case the problem was a typo in my steps file. I had a Then condition with two parameters but my method signature in my Steps.java file was missing one of them. I corrected the mistake and my tests passed successfully.
Here's what the error was that I was getting:
[INFO] Using controls UnmodifiableEmbedderControls[EmbedderControls[batch=false,skip=false,generateViewAfterStories=true,ignoreFailureInStories=true,ignoreFailureInView=false,verboseFailures=false,verboseFiltering=false,storyTimeoutInSecs=300,failOnStoryTimeout=false,threads=1]]
(BeforeStories)
[INFO] Running story com/netbase/OpMetricsFilterBuilder/stories/ComputeDerivedValue.story
Compute Derived Value
(com/netbase/OpMetricsFilterBuilder/stories/ComputeDerivedValue.story)
Narrative:
In order to explore how my social media activity ties to my core business metrics
As a n analyst
I want to compute a derived time series value from a set of component time series
Scenario: Compute Net Intent to Shop
Given the following time series:
|Date|Shop|NotShop|
|11/5/2014|330|400|
|11/6/2014|370|410|
|11/7/2014|320|390|
|11/8/2014|200|280|
|11/9/2014|430|450|
And a derived value name of NetIntentToShop
And a formula for computing the derived value is (#{Shop} - #{NotShop}) / (#{Shop} + #{NotShop}) * 100
When the NetIntentToShop is derived
Then the NetIntentToShop should be
|Date|NetIntentToShop|
|11/5/2014|-9.58904109589041|
|11/6/2014|-5.128205128205128|
|11/7/2014|-9.859154929577464|
|11/8/2014|-16.666666666666664|
|11/9/2014|-2.272727272727273| (FAILED)
(org.jbehave.core.io.StoryResourceNotFound: Story path 'NetIntentToShop' not found by class loader EmbedderClassLoader[urls=[/Users/mosofsky/Developer/SocialMetrics/nbsocialmetrics-frontend/target/classes/, appengine-api-1.0-sdk-1.9.15.jar, servlet-api-2.5.jar, jstl-1.2.jar, objectify-5.1.1.jar, guava-17.0.jar, jeval-0.9.4.jar, gwt-user-2.7.0-rc1.jar, validation-api-1.0.0.GA.jar, validation-api-1.0.0.GA-sources.jar, gwt-dev-2.7.0-rc1.jar, asm-5.0.3.jar, asm-util-5.0.3.jar, asm-tree-5.0.3.jar, asm-commons-5.0.3.jar, jbehave-core-3.9.5.jar, hamcrest-integration-1.3.jar, commons-collections-3.2.1.jar, commons-io-2.4.jar, commons-lang-2.6.jar, plexus-utils-3.0.10.jar, freemarker-2.3.19.jar, paranamer-2.4.jar, xstream-1.4.5.jar, xmlpull-1.1.3.1.jar, xpp3_min-1.1.4c.jar, jbehave-junit-runner-1.1.2.jar, junit-4.11.jar, mockito-core-1.9.5.jar, hamcrest-core-1.3.jar, hamcrest-library-1.3.jar, objenesis-1.3.jar],parent=ClassRealm[plugin>org.jbehave:jbehave-maven-plugin:3.9.5, parent: sun.misc.Launcher$AppClassLoader#6da21389]])
[WARNING] Failed to run story com/netbase/OpMetricsFilterBuilder/stories/ComputeDerivedValue.story
org.jbehave.core.io.StoryResourceNotFound: Story path 'NetIntentToShop' not found by class loader EmbedderClassLoader[urls=[/Users/mosofsky/Developer/SocialMetrics/nbsocialmetrics-frontend/target/classes/, appengine-api-1.0-sdk-1.9.15.jar, servlet-api-2.5.jar, jstl-1.2.jar, objectify-5.1.1.jar, guava-17.0.jar, jeval-0.9.4.jar, gwt-user-2.7.0-rc1.jar, validation-api-1.0.0.GA.jar, validation-api-1.0.0.GA-sources.jar, gwt-dev-2.7.0-rc1.jar, asm-5.0.3.jar, asm-util-5.0.3.jar, asm-tree-5.0.3.jar, asm-commons-5.0.3.jar, jbehave-core-3.9.5.jar, hamcrest-integration-1.3.jar, commons-collections-3.2.1.jar, commons-io-2.4.jar, commons-lang-2.6.jar, plexus-utils-3.0.10.jar, freemarker-2.3.19.jar, paranamer-2.4.jar, xstream-1.4.5.jar, xmlpull-1.1.3.1.jar, xpp3_min-1.1.4c.jar, jbehave-junit-runner-1.1.2.jar, junit-4.11.jar, mockito-core-1.9.5.jar, hamcrest-core-1.3.jar, hamcrest-library-1.3.jar, objenesis-1.3.jar],parent=ClassRealm[plugin>org.jbehave:jbehave-maven-plugin:3.9.5, parent: sun.misc.Launcher$AppClassLoader#6da21389]]
at org.jbehave.core.io.LoadFromClasspath.resourceAsStream(LoadFromClasspath.java:44)
at org.jbehave.core.io.LoadFromClasspath.loadResourceAsText(LoadFromClasspath.java:29)
at org.jbehave.core.model.ExamplesTableFactory.createExamplesTable(ExamplesTableFactory.java:76)
at org.jbehave.core.steps.ParameterConverters$ExamplesTableConverter.convertValue(ParameterConverters.java:647)
at org.jbehave.core.steps.ParameterConverters.convert(ParameterConverters.java:151)
at org.jbehave.core.steps.StepCreator.convertParameterValues(StepCreator.java:304)
at org.jbehave.core.steps.StepCreator.access$1100(StepCreator.java:36)
at org.jbehave.core.steps.StepCreator$ParametrisedStep.parametriseStep(StepCreator.java:640)
at org.jbehave.core.steps.StepCreator$ParametrisedStep.perform(StepCreator.java:592)
at org.jbehave.core.embedder.StoryRunner$FineSoFar.run(StoryRunner.java:535)
at org.jbehave.core.embedder.StoryRunner.runStepsWhileKeepingState(StoryRunner.java:515)
at org.jbehave.core.embedder.StoryRunner.runScenarioSteps(StoryRunner.java:479)
at org.jbehave.core.embedder.StoryRunner.runStepsWithLifecycle(StoryRunner.java:445)
at org.jbehave.core.embedder.StoryRunner.runCancellable(StoryRunner.java:305)
at org.jbehave.core.embedder.StoryRunner.run(StoryRunner.java:220)
at org.jbehave.core.embedder.StoryRunner.run(StoryRunner.java:181)
at org.jbehave.core.embedder.StoryManager$EnqueuedStory.call(StoryManager.java:262)
at org.jbehave.core.embedder.StoryManager$EnqueuedStory.call(StoryManager.java:229)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Here's the erroneous method signature:
#Then("the $derivedValueName should be: $expectedOutputDataTable")
public void thenTheDerivedValueShouldBe(ExamplesTable expectedOutputDataTable) {
Here's the correction:
#Then("the $derivedValueName should be: $expectedOutputDataTable")
public void thenTheDerivedValueShouldBe(String derivedValueName, ExamplesTable expectedOutputDataTable) {
It seems like a funny error message for my situation. I guess if a parameter is missing from the Steps.java file then Jbehave might go search for it as a resource.

findAll fails after play morphia is reinitialised

I have the following class which is persisted into a mongodb using morphia in a play! application. The class resides in a module which is a dependency of another play! application.
Its configuration is read from a file and persisted into the db on initial load (if its not already in the db) and then subsequent requests use the db version.
#Entity
public class Page extends Model {
#Id
public Long navigationId;
// etc ...
}
The initial load and subsequent query access works ok and i can see the page in mongo:
> db.Page.find({_id:20000})
{ "_id" : NumberLong(20000), "className" : "models.Page" etc }
However if i restart play! or make a code change that results in Morphia being reinitialised
(MorphiaPlugin-1.2.4> initialized appears in the logs) i get the following stack trace:
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.google.code.morphia.mapping.MappingException: Error setting value from converter (LongConverter) for models.Page.navigationId to 20000
at com.google.code.morphia.mapping.Mapper.fromDb(Mapper.java:487)
at com.google.code.morphia.mapping.Mapper.fromDBObject(Mapper.java:267)
at com.google.code.morphia.query.MorphiaIterator.convertItem(MorphiaIterator.java:66)
at com.google.code.morphia.query.MorphiaIterator.processItem(MorphiaIterator.java:53)
at com.google.code.morphia.query.MorphiaIterator.next(MorphiaIterator.java:48)
at com.google.code.morphia.query.QueryImpl.asList(QueryImpl.java:255)
at play.modules.morphia.Model$MorphiaQuery.asList(Model.java:1067)
at models.Page.findAll(Page.java)
at plugins.PageConfigLoadPlugin.loadPersistedPages(PageConfigLoadPlugin.java:62)
at plugins.PageConfigLoadPlugin.onApplicationStart(PageConfigLoadPlugin.java:51)
at play.plugins.PluginCollection.onApplicationStart(PluginCollection.java:425)
at play.Play.start(Play.java:495)
... 3 more
Caused by: java.lang.RuntimeException: com.google.code.morphia.mapping.MappingException: Error setting value from converter (LongConverter) for models.Page.navigationId to 20000
at com.google.code.morphia.mapping.ValueMapper.fromDBObject(ValueMapper.java:27)
at com.google.code.morphia.mapping.Mapper.readMappedField(Mapper.java:501)
at com.google.code.morphia.mapping.Mapper.fromDb(Mapper.java:484)
... 14 more
Caused by: com.google.code.morphia.mapping.MappingException: Error setting value from converter (LongConverter) for models.Page.navigationId to 20000
at com.google.code.morphia.converters.DefaultConverters.fromDBObject(DefaultConverters.java:133)
at com.google.code.morphia.mapping.ValueMapper.fromDBObject(ValueMapper.java:25)
... 16 more
If i drop the Collection from mongodb using the command line i can again load and query the Page obejct successfully from my play! web application
> db.Page.drop()
true
As I mentioned, this class is in a module. This problem only happens in one application that the module is a dependency of. The other demo application works fine.
any suggestions?
Does the dependent module have another alternate declaration of the Page or
Model classes?
From the top of the stack trace, ("com.google.code.morphia.mapping.MappingException: Error setting value from converter (LongConverter) for models.Page.navigationId to 20000"), it looks like there's a type mismatch between
the way a numeric value is being stored and retrieved. For example, in Java,
it is not uncommon to store something as a Double and then mistakenly try
to retrieve it as an Integer or a Long. So, can you verify that the
declaration of navigationId in the dependent module is the same as the one
you've shown here? They should share the definition, but its possible there's
an alternate.
Another thing to check is that your code is putting a Long into your
DBObject and not a float. For example, if you're inserting it via the shell,
you'll need to use one of the wrappers, e.g.
db.Page.save({_id:NumberLong(20000)});
Otherwise, this will also cause a mismatch when you retrieve it; by default
numbers in JavaScript are doubles.

Categories

Resources