play 2.4 ebean update optimistic locking - locking

I am trying to implement crud sort of like computer-database example using play 2.4 with ebeans. Everything works except update. When I run the computer-database example against same MariaDB and older ebeans (3.2.2), it does update just fine so does not seem to be an issue with the database. I am using MySQL connector though as found bug with Maria JDBC driver while using ebeans.
This code:
/**
* Handle the 'edit form' submission
*
* #param id Id of the user to edit
*/
public Result update(Long id) {
Form<User> userForm = form(User.class).bindFromRequest();
if(userForm.hasErrors()) {
return badRequest(editForm.render(id, userForm));
}
User userFromForm = userForm.get();
System.out.println(userForm.data());
userFromForm.update();
flash("success", "User " + userForm.get().alias + " has been updated");
return GO_HOME;
}
gives this error:
[OptimisticLockException: Data has changed. updated [0] rows sql[update user set alias=?, email=?, password=?, active=?, last_update=?, user_type_id=? where id=?] bind[null]]
The entity is defined like
#Entity
public class User extends Model {
private static final long serialVersionUID = 1L;
#Id
public Long id;
#Constraints.Required
public String alias;
#Constraints.Required
public String email;
#Constraints.Required
public String password;
#Constraints.Required
public char active;
#ManyToOne
public UserType userType;
#Version
#Column(columnDefinition = "timestamp default '2014-10-06 21:17:06'")
public Timestamp lastUpdate;
First, the version is not being placed in the where clause as expected. Also, the optimistic locking error is thrown.
I am connecting to MySQL. All other actions, save, delete etc. work fine.
Is this broke again?
plugins look like
// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.4.4")
// Web plugins
addSbtPlugin("com.typesafe.sbt" % "sbt-web" % "1.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-webdriver" % "1.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-js-engine" % "1.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.0.6")
addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.7")
addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0")
// Play enhancer - this automatically generates getters/setters for public fields
// and rewrites accessors of these fields to use the getters/setters. Remove this
// plugin if you prefer not to have this feature, or disable on a per project
// basis using disablePlugins(PlayEnhancer) in your build.sbt
addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.1.0")
// Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using
// enablePlugins(SbtEbean). Note, uncommenting this line will automatically bring in
// Play enhancer, regardless of whether the line above is commented out or not.
addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "1.0.0")
//Eclipse
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0")
build.sbt is
name := """mecamu-play"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean, SbtWeb, PlayEnhancer)
scalaVersion := "2.11.6"
libraryDependencies ++= Seq(
javaJdbc,
cache,
javaWs
)
// Play provides two styles of routers, one expects its actions to be injected, the
// other, legacy style, accesses its actions statically.
routesGenerator := InjectedRoutesGenerator
k in run := true
fork in run := true
Any help would be appreciated. I would love to use bound form updates with ebean the way they worked before.
Thanks so much

What the OptimisticLockException is saying is that update statement updated 0 rows. What that means is that the where clause did not match an existing row. What that means is you need to look at the specific bind values for the id and version columns: where id=? and version=?
If you have Ebean logging on (refer http://ebean-orm.github.io/docs/setup/logging) then the logging will include the bind values.
Once you know the bind values used in the where clause of the update you need to determine why they are not correct (why it results in 0 rows updated) ... so what values are set onto the bean using the form.
To me those are the steps you need to follow.
PS: Just because you log an issue in Stackoverflow does not mean the right people look at your issue. Both Playframework and Ebean have forums you can seek help on.

Well it turns out that this is likely a bug with ebeans 4.6.2
https://github.com/playframework/play-ebean/issues/44
I will see if I can use a later version where the issue is fixed like 4.7.2 or later. Since Play is using a plugin model for ebeans now, I am not quite sure how to control which version is pulled in. I am fairly new to scala/sbt. This bug with 4.6.2 explains why earlier versions seem to update fine.

Try to see your file 1.sql and check if the column exist or try a query such as describe your_table, if it does not exist try to drop table and re import again the same table script SQL

Related

How to mimic Optaplanner 7's MoveIteratorFactoryToMoveSelectorBridge in Optaplanner 8

We have implemented a custom construction heuristic with Optaplanner 7. We didn't use a simple CustomPhaseCommand; Instead, we extend MoveSelectorConfig and override buildBaseMoveSelector to return our own MoveFactory wrapped in a MoveIteratorFactoryToMoveSelectorBridge. We decided to do so, because it gives us the following advantages:
global termination config is supported out of the box
type safe configuration from code (no raw Strings)
With Optaplanner 8 the method buildBaseMoveSelector is gone from the MoveSelectorConfig API and building a custom config class seems to be prevented in the new implementation of MoveSelectorFactory.
Is it still possible to inject a proper custom construction heuristic into the Optaplanner 8 configuration and if yes, how? Or should we be using a CustomPhaseCommand with a custom self-implemented termination?
EDIT:
For clarity, in Optaplanner 7 we had the following snippet in our Optaplanner-config (defined in kotlin code):
ConstructionHeuristicPhaseConfig().apply {
foragerConfig = ConstructionHeuristicForagerConfig().apply {
pickEarlyType = FIRST_FEASIBLE_SCORE
}
entityPlacerConfig = QueuedEntityPlacerConfig().apply {
moveSelectorConfigList = listOf(
CustomMoveSelectorConfig().apply {
someProperty = 1
otherProperty = 0
}
)
}
},
CustomMoveSelectorConfig extends MoveSelectorConfig and overrides buildBaseMoveSelector:
class CustomMoveSelectorConfig(
var someProperty: Int = 0,
var otherProperty: Int = 0,
) : MoveSelectorConfig<CustomMoveSelectorConfig>() {
override fun buildBaseMoveSelector(
configPolicy: HeuristicConfigPolicy?,
minimumCacheType: SelectionCacheType?,
randomSelection: Boolean,
): MoveSelector {
return MoveIteratorFactoryToMoveSelectorBridge(
CustomMoveFactory(someProperty, otherProperty),
randomSelection
)
}
To summarize: We really need to plug our own MoveSelector with the custom factory. I think this is not possible with Optaplanner 8 at the moment.
Interesting extension.
Motivation for the changes in 8:
the buildBaseMoveSelector was not public API (the config package was not in the api package, we only guaranteed XML backwards compatibility for package config in 7). Now, we also guarantee API backwards compatibility for package config, so including programmatic configuration, because we moved all build* methods out of it.
In 8.2 or later we want to internalize the configuration in the SolverFactory, so we can build thousands of Solver instances faster. For example, loading classes wouldn't to be done only at SolverFactory build, once, no longer at every Solver build.
Anyway, let's first see if you can use the default way to override the moves of the CH, by explicitly configuring the queuedEntityPlacer and it's MoveIteratorFactory? https://docs.optaplanner.org/latestFinal/optaplanner-docs/html_single/#allocateEntityFromQueueConfiguration
I guess not, because you'd need mimic support... for the selected entity you need to generate n moves, but always the same entity during 1 placement (hence the need for mimicing).
Clearly, the changes in 8 prevent users from plugging in their own MoveSelectors (= which is an internal API, but anyway). We might be able to add an internal API to allow that again.

Howto tell PowerBuilder to pass options to a JVM when starting?

What I want to do?
I want to create and consume java objects in PowerBuilder and call methods on it. This should happen with less overhead possible.
I do not want to consume java webservices!
So I've a working sample in which I can create a java object, call a method on this object and output the result from the called method.
Everything is working as expected. I'm using Java 1.8.0_31.
But now I want to attach my java IDE (IntelliJ) to the running JVM (started by PowerBuilder) to debug the java code which gets called by PowerBuilder.
And now my question.
How do I tell PowerBuilder to add special options when starting the JVM?
In special I want to add the following option(s) in some way:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
The JVM is created like following:
LONG ll_result
inv_java = CREATE JavaVM
ll_result = inv_java.CreateJavaVM("C:\Development\tms java\pbJavaTest", FALSE)
CHOOSE CASE ll_result
CASE 1
CASE 0
CASE -1
MessageBox ( "", "jvm.dll was not found in the classpath.")
CASE -2
MessageBox ( "", "pbejbclient90.jar file was not found." )
CASE ELSE
MessageBox ( "", "Unknown result (" + String (ll_result ) +")" )
END CHOOSE
In the PowerBuilder help I found something about overriding the static registry classpath. There is something written about custom properties which sounds like what I'm looking for.
But there's no example on how to add JVM options to override default behavior.
Does anyone have a clue on how to tell PowerBuilder to use my options?
Or does anyone have any advice which could guide me in the right direction?
Update 1
I found an old post which solved my initial issue.
If someone else want to know how it works take a look at this post:
http://nntp-archive.sybase.com/nntp-archive/action/article/%3C46262213.6742.1681692777#sybase.com%3E
Hi, you need to set some windows registry entries.
Under HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\Powerbuilder\9.0\Java, there
are two folders: PBIDEConfig and PBRTConfig. The first one is used when
you run your application from within the IDE, and the latter is used
when you run your compiled application. Those two folders can have
PBJVMconfig and PBJVMprops folders within them.
PBJVMconfig is for JVM configuration options such as -Xms. You have to
specify incremental key values starting from "0" by one, and one special
key "Count" to tell Powerbuilder how many options exists to enumerate.
PBJVMprops is for all -D options. You do not need to specify -D for
PBJVMProps, just the name of the property and its value, and as many
properties as you wish.
Let me give some examples:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\PowerBuilder\9.0\Java\PBIDEConfig\PBJVMprops]
"java.security.auth.login.config"="auth.conf"
"user.language"="en"
[HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\PowerBuilder\9.0\Java\PBRTConfig\PBJVMconfig]
"0"="-client"
"1"="-Xms128m"
"2"="-Xmx512m"
"Count"="3"
[HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\PowerBuilder\9.0\Java\PBRTConfig\PBJVMprops]
"java.security.auth.login.config"="auth.conf"
"user.language"="en"
Regards,
Gokhan Demir
But now there's another issue...
PB isn't able to create EJB Proxies for my sample class which is really simple with java 1.8.0_31. They were created with the default version, which is 1.6.0_24.
public class Simple
{
public Simple()
{
}
public static String getValue()
{
return "blubber";
}
public int getInt32Value()
{
return 123456;
}
public double getDoubleVaue()
{
return 123.123;
}
public static void main(String[] args)
{
System.out.println(Simple.getValue());
}
}
The error is the following. :D
---------- Deploy: Deploy of project p_genapp_ejbclientproxy (15:35:18)
Retrieving PowerBuilder Proxies from EJB...
Generation Errors: Error: class not found: (
Deployment Error: No files returned for package/component 'Simple'. Error code: Unknown. Proxy was not created.
Done.
---------- Finished Deploy of project p_genapp_ejbclientproxy (15:35:19)
So the whole way isn't a option because we do not want to change the JAVA settings in PB back and forth just to generate new EJB Proxies for changed JAVA objects in the future...
So one option to test will be creating COM wrappers for JAVA classes to use them in PB...

ObjectARX SDK for c#

For last two days I have looking for sample code with steps which may help me to understand the Autocad API. so I can use the code in C#.
[CommandMethod("LISTGEn")]
public static void ListEntities()
{
Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table record for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,OpenMode.ForRead) as BlockTable;
// Open the Block table record Model space for read
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],OpenMode.ForRead) as BlockTableRecord;
int nCnt = 0;
acDoc.Editor.WriteMessage("\nModel space objects: ");
// Step through each object in Model space and
// display the type of object found
foreach (ObjectId acObjId in acBlkTblRec)
{
acDoc.Editor.WriteMessage("\n" + acObjId.ObjectClass.DxfName);
nCnt = nCnt + 1;
}
acDoc.Editor.WriteMessage(nCnt.ToString());
// If no objects are found then display a message
if (nCnt == 0)
{
acDoc.Editor.WriteMessage("\n No objects found");
}
// Dispose of the transaction
}
}
I can run the above code, but it's not functioning properly. It's difficult for me to understand how to get it work with Autocad. I have OjectARX SDK referenced,
I am working with VS2010 and Autocad 2012. Thank You for your help.
Ok, I got it only thing that is being required
1.) is to create a class library
2.) Then need to enter the above code in the class.
3.) Build your project by pressing F5.
4.) A DLL will be created in the bin/debug/ folder of your project
5.) Open Autocad.
6.) Write netload command.
7.) Select the DLL created and then write command "LISTGEN" and than kaboom it will show all the objects in your project.
To avoid having to manually netload your dll, you can use a temporary fix for debugging and write a lisp file to do it for you
(Command "netload" "path/to/your/.dll")\n
Or you can use \\
Take a look at my github. The link is on my profile. Look over the reference library, it's highly simplified for object model manipulation.
If you have any questions feel free to email me.

Play 2.1 for Http Server

I am new to play framework. My requirement is very simple. I want to create rest api server in scala using play framework. I could use play2-mini, but it seems it is outdated.
I want play 2.1 to be used in my project. Instead of setting play framework as dependency, I want only core module. So I have few questions -
What is core module of Play ? what is module name ?
Is it sufficient to use core module for creating asynchronous http server ?
This link says I can use core module instead of play-mini. If it's true, where can I get more info about it.
You can just simply setup a route and then point it to a controller that parses the data you send. Here is an example of json parsing and serving back a response with play.
http://www.playframework.com/documentation/2.1.1/ScalaJsonRequests
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.json._
// you need this import to have combinators
import play.api.libs.functional.syntax._
object Application extends Controller {
implicit val rds = (
(__ \ 'name).read[String] and
(__ \ 'age).read[Long]
) tupled
def sayHello = Action { request =>
request.body.asJson.map { json =>
json.validate[(String, Long)].map{
case (name, age) => Ok("Hello " + name + ", you're "+age)
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}.getOrElse {
BadRequest("Expecting Json data")
}
}
}
or even simpler...
def sayHello = Action(parse.json) { request =>
request.body.validate[(String, Long)].map{
case (name, age) => Ok("Hello " + name + ", you're "+age)
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}
Play Framework is a highly modular project. Internally it consists of around 20 subprojects. Some of them you can include in your project as a library dependency if you need them, for example anorm or jdbc. Other projects (i.e. PlayExceptions, RoutesCompiler, TemplatesCompiler etc.) are essential for any Play application, so you don't need to declare dependency on them. These projects could be called a 'core' of Play Framework.
In other words, if you need a Play application with minimum dependencies, just don't declare dependencies you don't need.
Play sources: https://github.com/playframework/Play20
I don't think there is much problem here. For example, this is my build.sbt used for a very small project, that uses json, in which I wanted to use Play libraries, but not necessarily create a full Play app:
name := "my-small-project"
version := "0.0.1-SNAPSHOT"
resolvers ++= Seq(
"TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases",
"Sonatype Repo" at "http://oss.sonatype.org/content/repositories/releases"
)
libraryDependencies ++= Seq(
"org.specs2" %% "specs2" % "2.3.7" % "test",
"commons-codec" % "commons-codec" % "1.8",
"com.typesafe.play" % "play_2.10" % "2.2.1",
"com.typesafe.play" % "play-json_2.10" % "2.2.1"
)
And You could still remove some dependencies here, especially if You don't need Base64 encoding. Here I consider play_2.10 as "the core" you're interested in. You should get yourself familiar with sbt though, but it's not that hard.
Also remember, that the difference between "a Play application" and "an application that uses Play libraries" is quite fuzzy, especially if you use sbt. And this is the beauty of it, this shows how Play creators thoughtfully tried not to invent a wheel once again by creating custom system requirements for their project to build. You can enter a Play app dir and type "sbt compile" for example instead of firing a Play console and it should work just fine.

Using Forms after migrating from playframework 2.0 to 2.1 RC2 (java)

I have updated my controllers with to use play.data.Form.form() method instead of Controller.form(). When I try to run my application I get errors like:
error: method render in class create_user cannot be applied to given types;
return ok(create_user.render("", Form.form(CreateUserInfo.class), creator.get()));
required: String, play.api.data.Form, User
found: String, play.data.Form, User
It looks like the my templates expect to get play.api.data.Form instead of play.data.Form. Is there suppost to be any implicit conversion or should I update my templates to use play.data.Form?
If I'm using play.data.Form in my templates I am missing out on some of the features of play.api.data.Form, like the ability to request parameters through the apply method ( ex: createUserForm("username") )
The solution was provided by Guillaume Bort at the playframework google group.
I forgot to add javaCore as a dependency for my application after updating Build.scala. You have to explicitly add javaCore as a dependency in 2.1.
val appDependencies = Seq(
javaCore
)
And remember to start using play.Project instead of PlayProject:
val main = play.Project(appName, appVersion, appDependencies).settings(
// Add your own project settings here
)