How can I do some db operation on playframework global class method on start.
I would like to put some data to db from other source.
For now I have:
My code:
public class Global extends GlobalSettings {
#Override
#Transactional
public void onStart(Application application) {
Akka.system().scheduler().schedule(
Duration.create(1, TimeUnit.SECONDS), // start task delay
Duration.create(24, TimeUnit.HOURS), // between task instance delay
//Duration.create(24, TimeUnit.HOURS), // between task instance delay
new Runnable() {
#Override
#Transactional
public void run() {
System.out.println("Importing CRM data...");
ImportCrmData.start();
System.out.println("... imported");
}
},
Akka.system().dispatcher()
);
I am getting an error:
[info] play - Shutdown application default Akka system.
[info] play - datasource [jdbc:mysql://localhost/svp] bound to JNDI as DefaultDS
[info] play - datasource [jdbc:mysql://192.168.0.4/scrm_customer] bound to JNDI as CRM
[info] play - database [default] connected at jdbc:mysql://localhost/svp
[info] play - database [crm] connected at jdbc:mysql://192.168.0.4/scrm_customer
[info] play - Starting application default Akka system.
[info] play - Application started (Dev)
Importing CRM data...
[ERROR] [12/08/2014 15:57:04.773] [application-akka.actor.default-dispatcher-3] [TaskInvocation] No EntityManager bound to this thread. Try wrapping this call in JPA.withTransaction, or ensure that the HTTP context is setup on this thread.
java.lang.RuntimeException: No EntityManager bound to this thread. Try wrapping this call in JPA.withTransaction, or ensure that the HTTP context is setup on this thread.
at play.db.jpa.JPA.em(JPA.java:55)
at models.Customer.getByCrmId(Customer.java:185)
at models.CustomerCRM.importCrmData(CustomerCRM.java:84)
at actions.ImportCrmData.start(ImportCrmData.java:28)
at Global$1.run(Global.java:40)
at akka.actor.LightArrayRevolverScheduler$$anon$3$$anon$2.run(Scheduler.scala:241)
at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:42)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Please give me some help.
I use playframework 2.2.4 with java
-------------------------------------EDIT-----------------------------------------
Afted adding:
JPA.withTransaction(() -> {
ImportCrmData.start();
});
I am getting error.
[info] Compiling 1 Java source to app/modules/common/target/scala-2.10/classes...
[error] app/modules/common/app/Global.java:38: error: illegal start of expression
[error] JPA.withTransaction(() -> {
[error] ^
[error] app/modules/common/app/Global.java:38: error: illegal start of expression
[error] JPA.withTransaction(() -> {
[error] ^
[error] app/modules/common/app/Global.java:38: error: illegal start of expression
[error] JPA.withTransaction(() -> {
[error] ^
[error] app/modules/common/app/Global.java:38: error: ';' expected
[error] JPA.withTransaction(() -> {
[error] ^
[error] app/modules/common/app/Global.java:39: error: illegal start of expression
[error] ImportCrmData.start();
[error] ^
[error] app/modules/common/app/Global.java:39: error: ';' expected
[error] ImportCrmData.start();
[error] ^
[error] app/modules/common/app/Global.java:40: error: illegal start of type
[error] });
[error] ^
[error] app/modules/common/app/Global.java:41: error: ')' expected
[error] }
[error] ^
[error] app/modules/common/app/Global.java:42: error: illegal start of expression
[error] },
[error] ^
[error] app/modules/common/app/Global.java:43: error: ';' expected
[error] Akka.system().dispatcher()
[error] ^
[error] app/modules/common/app/Global.java:43: error: ';' expected
[error] Akka.system().dispatcher()
[error] ^
[error] 11 errors
[error] (common/compile:compile) javac returned nonzero exit code
Finally I've added:
public void run() {
JPA.withTransaction(
ImportCrmData.start()
);
}
Remove #Transactional annotations, they are useful only in controllers. Wrap CRM import with JPA.withTransaction method. Java 8 syntax:
JPA.withTransaction(() -> {
ImportCrmData.start();
});
And non Java 8 syntax:
JPA.withTransaction(new Callback0() {
#Override
public void invoke() throws Throwable {
ImportCrmData.start();
}
});
Related
This question already has answers here:
Why does a Try/Catch block create new variable scope?
(5 answers)
Closed 6 years ago.
I wasn't able to get apache commons cli to work.
apache commons-cli
I have the most simple start:
This is the only class.
Resources are added with maven(commandline).
import org.apache.commons.cli.*;
public class App {
public static void main(String[] args) {
// create Options object
Options options = new Options();
CommandLineParser parser = new DefaultParser();
// add t option
options.addOption("t", false, "display current time");
try{
CommandLine cmd = parser.parse( options, args);
}catch(ParseExeption ex){
}
if(cmd.hasOption("t")) {
// print the date and time
}else {
// print the date
}
}
}
No matter what I tried. I get the "cannot find symbol".
This is the last part of the error:
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/peter/Code/java/using_archetypes/using_cli_1/src/main
/java/com/mkyong/core/utils/App.java:[27,8] cannot find symbol
symbol: class ParseExeption
location: class com.mkyong.core.utils.App
[ERROR] /Users/peter/Code/java/using_archetypes/using_cli_1/src/main
/java/com/mkyong/core/utils/App.java:[31,4] cannot find symbol
symbol: variable cmd
location: class com.mkyong.core.utils.App
[INFO] 2 errors
[INFO] -------------------------------------------------------------
[INFO]
-------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO]
-------------------------------------------------------------------
[INFO] Total time: 0.842 s
[INFO] Finished at: 2016-10-31T12:17:29+01:00
[INFO] Final Memory: 15M/309M
[INFO]
---------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-
compiler-plugin:3.1:compile (default-compile) on project
dateUtils2: Compilation failure: Compilation failure:
[ERROR] /Users/peter/Code/java/using_archetypes/using_cli_1/src/main
/java/com/mkyong/core/utils/App.java:[27,8] cannot find symbol
[ERROR] symbol: class ParseExeption
[ERROR] location: class com.mkyong.core.utils.App
[ERROR] /Users/peter/Code/java/using_archetypes/using_cli_1/src/main
/java/com/mkyong/core/utils/App.java:[31,4] cannot find symbol
[ERROR] symbol: variable cmd
[ERROR] location: class com.mkyong.core.utils.App
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven
with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug
logging.
[ERROR]
[ERROR] For more information about the errors and possible
solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN
/MojoFailureException
Please help me to start with the commons-cli.
This is compiled with the maven compiler.
thank you.
Simply replace ParseExeption with ParseExceptionand move the if/else block in the same code block as where you defined your variable cmd otherwise it won't be visible, for example as next:
public static void main(String[] args) throws ParseException{
// create Options object
Options options = new Options();
CommandLineParser parser = new DefaultParser();
// add t option
options.addOption("t", false, "display current time");
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("t")) {
// print the date and time
}else {
// print the date
}
}
In my current project, i have this code:
for(Annotation annotation : field.getAnnotations()) {
String package = annotation.annotationType().getPackage().getName();
if(package.equals("com.loja.annotations.input_type"))
input.setAttribute("type", annotation.annotationType().getSimpleName());
}
when i try build the project, this code causes a compilation failure due to this error:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project store: Compilation failure: Compilation failure:
[ERROR] /c:/Users/Kleber Mota/Documents/GitHub/app/src/main/java/com/loja/thymeleaf/processor/form/InputProcessor.java:[37,11] not a statement
[ERROR] /c:/Users/Kleber Mota/Documents/GitHub/app/src/main/java/com/loja/thymeleaf/processor/form/InputProcessor.java:[37,17] ';' expected
[ERROR] /c:/Users/Kleber Mota/Documents/GitHub/app/src/main/java/com/loja/thymeleaf/processor/form/InputProcessor.java:[38,14] illegal start of expression
[ERROR] /c:/Users/Kleber Mota/Documents/GitHub/app/src/main/java/com/loja/thymeleaf/processor/form/InputProcessor.java:[38,21] illegal start of expression
[ERROR] /c:/Users/Kleber Mota/Documents/GitHub/app/src/main/java/com/loja/thymeleaf/processor/form/InputProcessor.java:[38,28] ';' expected
[ERROR] /c:/Users/Kleber Mota/Documents/GitHub/app/src/main/java/com/loja/thymeleaf/processor/form/InputProcessor.java:[38,22] variable declaration not allowed here
anyone can see what's wrong here?
line 37 is: String package = annotation.annotationType().getPackage().getName(); and line 38 is if(package.equals("com.loja.annotations.input_type"))
you can try this..
annotation.annotationType().getName();
You can print out your "package" variable after line 37 (before if).
I wrote and ran the similar code and it worked for me. I created a custom annotation in my api package and line 37 returned "api".
I tried to build maven package from this source https://github.com/mpercy/flume-load-gen.
But, when I build it using mvn clean package, I got errors like this :
[ERROR] /home/vincentius/Documents/flume-load-gen-master/src/main/java/org/apache/flume/tcphammer/Hammer.java:[67,12] error: no suitable method found for info(String,String,int)
[ERROR]
[ERROR] method Logger.info(Marker,String,Throwable) is not applicable
[ERROR] (actual argument String cannot be converted to Marker by method invocation conversion)
[ERROR] method Logger.info(Marker,String,Object[]) is not applicable
[ERROR] (actual argument String cannot be converted to Marker by method invocation conversion)
[ERROR] method Logger.info(Marker,String,Object,Object) is not applicable
[ERROR] (actual and formal argument lists differ in length)
[ERROR] method Logger.info(Marker,String,Object) is not applicable
[ERROR] (actual argument String cannot be converted to Marker by method invocation conversion)
[ERROR] method Logger.info(Marker,String) is not applicable
[ERROR] (actual and formal argument lists differ in length)
[ERROR] method Logger.info(String,Throwable) is not applicable
[ERROR] (actual and formal argument lists differ in length)
[ERROR] method Logger.info(String,Object[]) is not applicable
[ERROR] (actual and formal argument lists differ in length)
[ERROR] method Logger.info(String,Object,Object) is not applicable
[ERROR] (actual argument int cannot be converted to Object by method invocation conversion)
[ERROR] method Logger.info(String,Object) is not applicable
[ERROR] (actual and formal argument lists differ in length)
[ERROR] method Logger.info(String) is not applicable
[ERROR] (actual and formal argument lists differ in length)
[ERROR] /home/vincentius/Documents/flume-load-gen-master/src/main/java/org/apache/flume/tcphammer/Hammer.java:[137,25] error: incompatible types
[ERROR]
[ERROR] could not parse error message: required: Object
[ERROR] found: long
[ERROR] /home/vincentius/Documents/flume-load-gen-master/src/main/java/org/apache/flume/tcphammer/Hammer.java:138: error: incompatible types
[ERROR] curLogIntervalNanosSlept / 1000000,
[ERROR] ^
[ERROR]
[ERROR] could not parse error message: required: Object
[ERROR] found: long
[ERROR] /home/vincentius/Documents/flume-load-gen-master/src/main/java/org/apache/flume/tcphammer/Hammer.java:139: error: cannot find symbol
[ERROR] String.format("%.2f", (100 * (double) curLogIntervalNanosSlept / (double) logDelta)),
[ERROR] ^
[ERROR]
[ERROR] could not parse error message: symbol: method format(String,double)
[ERROR] location: class String
[ERROR] /home/vincentius/Documents/flume-load-gen-master/src/main/java/org/apache/flume/tcphammer/Hammer.java:140: error: incompatible types
[ERROR] curLogIntervalEventsSent,
[ERROR] ^
[ERROR]
[ERROR] could not parse error message: required: Object
[ERROR] found: long
[ERROR] /home/vincentius/Documents/flume-load-gen-master/src/main/java/org/apache/flume/tcphammer/Hammer.java:141: error: cannot find symbol
[ERROR] String.format("%.2f", (double) curLogIntervalEventsSent / ((double) logDelta / 1000000000D)),
[ERROR] ^
[ERROR]
[ERROR] could not parse error message: symbol: method format(String,double)
[ERROR] location: class String
[ERROR] /home/vincentius/Documents/flume-load-gen-master/src/main/java/org/apache/flume/tcphammer/Hammer.java:142: error: incompatible types
[ERROR] eventCount,
[ERROR] ^
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
I think maven use wrong slf4j logger in this case.
But, I really don't know how to fix this.
Anyone can help? thanks!
Consider opening an issue at https://github.com/mpercy/flume-load-gen/issues because it is free software.
I`ve got simple validation like:
#Column(length=6)
#Pattern(regexp = "[0-9]{2}( |-)?[0-9]{3}", message = Errors.kod_pocztowy)
private String kod_pocztowy;
But it return strange errors:
failed: java.lang.NoClassDefFoundError: javax/el/ELContext
[error] at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolateExpression(ResourceBundleMessageInterpolator.java:227)
[error] at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolateMessage(ResourceBundleMessageInterpolator.java:187)
[error] at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolate(ResourceBundleMessageInterpolator.java:115)
[error] at org.hibernate.validator.internal.engine.ValidationContext.interpolate(ValidationContext.java:370)
[error] at org.hibernate.validator.internal.engine.ValidationContext.createConstraintViolation(ValidationContext.java:284)
[error] at org.hibernate.validator.internal.engine.ValidationContext.createConstraintViolations(ValidationContext.java:246)
[error] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:289)
[error] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:133)
[error] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
[error] at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:85)
[error] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:478)
[error] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:424)
[error] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:388)
[error] at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:340)
[error] at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:158)
When i`m changing message property to text like:
#Column(length=6)
#Pattern(regexp = "[0-9]{2}( |-)?[0-9]{3}", message = "Now its ok")
private String kod_pocztowy;
Then everything seems to be ok. What`s the problem ? Anyone can explain it for me?
Ok, i`ve found it by myself. Using chars like {} causes Ebean to load message from class and this message is related to that class.
I have added the simple code write to a file into an open source project (Saiku) that before my changes builds and compiles cleanly.
The program compiles cleanly in Centos 5.3 Eclipse (no red X's).
However, when rerunning the maven build script, the compiler errors are generated (Exhibit 1):
Does Maven compile java projects differently from Eclipse?
Exhibit 1:
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[67,8] illegal start of type
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[67,11] ';' expected
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[70,14] <identifier> expected
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[70,15] illegal start of type
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[71,14] <identifier> expected
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[73,14] <identifier> expected
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[75,11] illegal start of type
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[79,2] invalid method declaration; return type required
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[130,15] class, interface, or enum expected
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[130,43] class, interface, or enum expected
[ERROR]
[ERROR] /usr/local/.m2/repository/saiku/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/HierarchicalCellSetFormatter.java:[131,8] class, interface, or enum expected
[ERROR]
Exhibit 2:
import java.io.*; to the import section
try {
FileWriter fstream = new FileWriter("/usr/local/dailycandy/biserver.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
out.flush();
//Close the output stream
out.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
The code that you have added is not within a method/constructor/block etc. This is not valid Java, and thus does not compile.
You need to surround this with something like follows:
public void doSomething
{
// Insert code here
}
Alternatively, you can place it in an existing method, or constructor, depending on when you need this code to execute.
Why Eclipse is not highlighting this error is beyond me. It would normally report this. Try refreshing your project or cleaning/rebuilding and you should see that it will fail to compile.