How can I run a *.scala script in interpreting mode?
For example I have simple.scala:
// simple.scala
println("a simple program")
If use scala simple.scala, I got
error: Compile server encountered fatal condition: javax/tools/DiagnosticListener
java.lang.ClassNotFoundException: javax.tools.DiagnosticListener
at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:433)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:586)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
at scala.tools.util.PathResolverBase$Calculated$.javaBootClasspath(PathResolver.scala:277)
at scala.tools.util.PathResolverBase$Calculated$.basis(PathResolver.scala:283)
at scala.tools.util.PathResolverBase$Calculated$.containers$lzycompute(PathResolver.scala:293)
at scala.tools.util.PathResolverBase$Calculated$.containers(PathResolver.scala:293)
at scala.tools.util.PathResolverBase.containers(PathResolver.scala:309)
at scala.tools.util.PathResolver.computeResult(PathResolver.scala:341)
at scala.tools.util.PathResolver.computeResult(PathResolver.scala:332)
at scala.tools.util.PathResolverBase.result(PathResolver.scala:314)
at scala.tools.nsc.backend.JavaPlatform$class.classPath(JavaPlatform.scala:28)
at scala.tools.nsc.Global$GlobalPlatform.classPath(Global.scala:115)
at scala.tools.nsc.Global.scala$tools$nsc$Global$$recursiveClassPath(Global.scala:131)
at scala.tools.nsc.Global$GlobalMirror.rootLoader(Global.scala:64)
at scala.reflect.internal.Mirrors$Roots$RootClass.<init>(Mirrors.scala:307)
at scala.reflect.internal.Mirrors$Roots.RootClass$lzycompute(Mirrors.scala:321)
at scala.reflect.internal.Mirrors$Roots.RootClass(Mirrors.scala:321)
at scala.reflect.internal.Mirrors$Roots$EmptyPackageClass.<init>(Mirrors.scala:330)
at scala.reflect.internal.Mirrors$Roots.EmptyPackageClass$lzycompute(Mirrors.scala:336)
at scala.reflect.internal.Mirrors$Roots.EmptyPackageClass(Mirrors.scala:336)
at scala.reflect.internal.Mirrors$Roots.EmptyPackageClass(Mirrors.scala:276)
at scala.reflect.internal.Mirrors$RootsBase.init(Mirrors.scala:250)
at scala.tools.nsc.Global.rootMirror$lzycompute(Global.scala:73)
at scala.tools.nsc.Global.rootMirror(Global.scala:71)
at scala.tools.nsc.Global.rootMirror(Global.scala:39)
at scala.reflect.internal.Definitions$DefinitionsClass.ObjectClass$lzycompute(Definitions.scala:257)
at scala.reflect.internal.Definitions$DefinitionsClass.ObjectClass(Definitions.scala:257)
at scala.reflect.internal.Definitions$DefinitionsClass.init(Definitions.scala:1390)
at scala.tools.nsc.Global$Run.<init>(Global.scala:1242)
at scala.tools.nsc.StandardCompileServer.session(CompileServer.scala:151)
at scala.tools.util.SocketServer$$anonfun$doSession$1$$anonfun$apply$1.apply(SocketServer.scala:74)
at scala.tools.util.SocketServer$$anonfun$doSession$1$$anonfun$apply$1.apply(SocketServer.scala:74)
at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
at scala.Console$.withOut(Console.scala:65)
at scala.tools.util.SocketServer$$anonfun$doSession$1.apply(SocketServer.scala:74)
at scala.tools.util.SocketServer$$anonfun$doSession$1.apply(SocketServer.scala:69)
at scala.tools.nsc.io.Socket.applyReaderAndWriter(Socket.scala:49)
at scala.tools.util.SocketServer.doSession(SocketServer.scala:69)
at scala.tools.util.SocketServer.loop$1(SocketServer.scala:85)
at scala.tools.util.SocketServer.run(SocketServer.scala:97)
at scala.tools.nsc.CompileServer$$anonfun$execute$2$$anonfun$apply$mcZ$sp$1.apply$mcZ$sp(CompileServer.scala:218)
at scala.tools.nsc.CompileServer$$anonfun$execute$2$$anonfun$apply$mcZ$sp$1.apply(CompileServer.scala:213)
at scala.tools.nsc.CompileServer$$anonfun$execute$2$$anonfun$apply$mcZ$sp$1.apply(CompileServer.scala:213)
at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
at scala.Console$.withOut(Console.scala:53)
at scala.tools.nsc.CompileServer$$anonfun$execute$2.apply$mcZ$sp(CompileServer.scala:213)
at scala.tools.nsc.CompileServer$$anonfun$execute$2.apply(CompileServer.scala:213)
at scala.tools.nsc.CompileServer$$anonfun$execute$2.apply(CompileServer.scala:213)
at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
at scala.Console$.withErr(Console.scala:80)
But I can open the interpreter by command scala and then
> println("a simple program")
It works correctly.
Also, if I compile a more complete .scala (with an object which contains a main function) by scalac then run it by scala, things goes well.
I wonder if I can run a .scala script in the interpreter. Is there any thing wrong?
Update:
After I update scala from 2.11 to 3.20, there is no javax.tools.DiagnosticListener exceptions. But when I run scala -explain simple.scala, the error is:
-- [E103] Syntax Error: ~/simple.scala:2:0
2 |println("a simple program")
|^^^^^^^
|Illegal start of toplevel definition
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| A statement is an import or export, a definition or an expression.
| Some statements are only allowed in certain contexts
-----------------------------------------------------------------------------
1 error found
Error: Errors encountered during compilation
JAVA version: openjdk 16.0.1 2021-04-20
As mentioned by Seth Tisue, the following works:
def main(args: Array[String]): Unit =
// simple.scala
println("a simple program")
if you invoke it like this:
scala3 ~/simple.scala
Related
I'm trying to start a rather trivial example
KieContainer kieContainer = KieServices.Factory.get().getKieClasspathContainer();
StatelessKieSession kieSession = kieContainer.newStatelessKieSession("MyStatelessValidationStep");
and at the 2nd line I get an error NullPointerException which seems to be caused by the exception Unable to load dialect 'mvel'.
It happens with the latest Drools version 7.57.0.Final but works OK with e.g. 7.39.0.Final. I've listed the docs trying to find out what changed between those versions, but couldn't find the answer. So, is this a bug or I'm missing something new in my source code?
p.s.
Here is a list of the libraries I'm using:
ext {
drools_version = '7.57.0.Final'
slf4j_version = '1.7.32'
mvel_version = '2.4.12.Final'
junit_version = '5.6.0'
}
#"Roddy of the Frozen Peas", here are the dependencies:
dependencies {
// https://mvnrepository.com/artifact/org.drools/drools-core
implementation group: 'org.drools', name: 'drools-core', version: "$drools_version"
// https://mvnrepository.com/artifact/org.drools/drools-compiler
implementation group: 'org.drools', name: 'drools-compiler', version: "$drools_version"
// https://mvnrepository.com/artifact/org.kie/kie-api
compileOnly group: 'org.kie', name: 'kie-api', version: "$drools_version"
// https://mvnrepository.com/artifact/org.kie/kie-internal
implementation group: 'org.kie', name: 'kie-internal', version: "$drools_version"
// https://mvnrepository.com/artifact/org.slf4j/slf4j-api
implementation group: 'org.slf4j', name: 'slf4j-api', version: "$slf4j_version"
// https://mvnrepository.com/artifact/org.slf4j/slf4j-nop
implementation group: 'org.slf4j', name: 'slf4j-nop', version: "$slf4j_version"
// https://mvnrepository.com/artifact/org.mvel/mvel2
implementation group: 'org.mvel', name: 'mvel2', version: "$mvel_version"
testImplementation "org.junit.jupiter:junit-jupiter-api:$junit_version"
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}
Note that if I replace compileOnly with implementation for the kie-api, nothing changes in the final result - I still get NPE.
Since 7.45.0.Final MVEL evaluation has been moved to a separated module called drools-mvel, see the release notes. Please add that module as well or use instead the aggregator module drools-engine-classic
sbt sourceDirectories
only displays source directories of current project, but doesn’t display source directories of projects that it depends using
dependsOn(ProjectRef)
Below is the simplified task.
lazy val showAllSourceDirs = taskKey[Unit]("show source directories of all projects")
showAllSourceDirs := {
val projectRefs = loadedBuild.value.allProjectRefs.map(_._1)
projectRefs foreach { projectRef =>
/*
Below line is giving IllegalArgumentException exception :-
[error] java.lang.IllegalArgumentException: Could not find proxy for projectRef: sbt.ProjectRef in
List(value projectRef, value $anonfun, method sbtdef$1, method $sbtdef, object $7fb70afe92bc9a6fedc3,
package <empty>, package <root>) (currentOwner= method $sbtdef )
*/
val sources = (projectRef / Compile / sourceDirectories).value
sources.foreach( println )
}
}
Link for simplified project to reproduce problem :-
https://github.com/moglideveloper/Example
Steps :
Go to ApiSpec directory from command line and run below command :-
sbt showAllSourceDirs
Expected output : print all source directories of Api and ApiSpec project
Actual output : throws java.lang.IllegalArgumentException
I believe you cannot do that, because sbt works with macros. What you can do here, is adding sourceDirectories of Api into sourceDirectories of ApiSpec. This means, that if you add the following into your sbt:
Compile / sourceDirectories ++= (apiModule / Compile / sourceDirectories).value
Then, when running:
sbt sourceDirectories
You get the output:
[info] * /workspace/games/Example/ApiSpec/src/main/scala-2.12
[info] * /workspace/games/Example/ApiSpec/src/main/scala
[info] * /workspace/games/Example/ApiSpec/src/main/java
[info] * /workspace/games/Example/ApiSpec/target/scala-2.12/src_managed/main
[info] * /workspace/games/Example/Api/src/main/scala-2.12
[info] * /workspace/games/Example/Api/src/main/scala
[info] * /workspace/games/Example/Api/src/main/java
[info] * /workspace/games/Example/Api/target/scala-2.12/src_managed/main
There is one thing you need to notice - you are overriding the current sourceDirectories, so be sure you are not using it anywhere else.
Another note, is that you need to add this line on every dependency you have. So I am not sure how big is your project, and how feasible that is.
If you'd like to have a different task, you can do that, bur use the modules themselves, and not thru reflection, again due to macros.
lazy val showAllSourceDirs = taskKey[Unit]("show source directories of all projects")
showAllSourceDirs := {
println((apiSpecProject / Compile / sourceDirectories).value)
println((apiModule / Compile / sourceDirectories).value)
}
This is my first time using Scalatra, and I'm using it outside of SBT (building and running using mill). I get the following error which seems to be about a missing dependency.
2018.05.23 18:26:30 [main] INFO org.scalatra.servlet.ScalatraListener - The cycle class name from the config: ScalatraBootstrap
2018.05.23 18:26:30 [main] INFO org.scalatra.servlet.ScalatraListener - Initializing life cycle class: ScalatraBootstrap
2018.05.23 18:26:30 [main] ERROR org.scalatra.servlet.ScalatraListener - Failed to initialize scalatra application at
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getFilterRegistration(Ljava/lang/String;)Ljavax/servlet/FilterRegistration;
at org.scalatra.servlet.RichServletContext.mountFilter(RichServletContext.scala:162)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:85)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:93)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:90)
at ScalatraBootstrap.init(ScalatraBootstrap.scala:8)
at org.scalatra.servlet.ScalatraListener.configureCycleClass(ScalatraListener.scala:66)
at org.scalatra.servlet.ScalatraListener.contextInitialized(ScalatraListener.scala:22)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:890)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:558)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:853)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:370)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1497)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1459)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:785)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:287)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:545)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
at org.eclipse.jetty.server.Server.start(Server.java:419)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:108)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
at org.eclipse.jetty.server.Server.doStart(Server.java:386)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at com.example.JettyLauncher$.main(JettyLauncher.scala:20)
at com.example.JettyLauncher.main(JettyLauncher.scala)
Here are the dependencies I'm using:
val jettyVersion = "9.4.10.v20180503"
def ivyDeps = Agg(
ivy"org.scalatra::scalatra:2.6.3",
ivy"javax.servlet:servlet-api:2.5",
ivy"org.eclipse.jetty:jetty-server:$jettyVersion",
ivy"org.eclipse.jetty:jetty-servlet:$jettyVersion",
ivy"org.eclipse.jetty:jetty-webapp:$jettyVersion",
)
My JettyLauncher is a striaght copy from the web site, so far, except I changed the resourceBase to be something that actually exists (but it didn't help):
object JettyLauncher { // this is my entry object as specified in sbt project definition
def main(args: Array[String]) {
val port = if(System.getenv("PORT") != null) System.getenv("PORT").toInt else 5001
val server = new Server(port)
val context = new WebAppContext()
context setContextPath "/"
context.setResourceBase("repeater")
context.addEventListener(new ScalatraListener)
context.addServlet(classOf[DefaultServlet], "/")
server.setHandler(context)
server.start
server.join
}
}
My LifeCycle class is also fairly minimal:
class ScalatraBootstrap extends LifeCycle {
override def init(context: ServletContext) {
context mount (new RepeatAll, "/*")
}
}
UPDATE
I changed to using ScalatraServlet instead of ScalatraServlet, but get a similar issue:
2018.05.23 18:39:24 [main] ERROR org.scalatra.servlet.ScalatraListener - Failed to initialize scalatra application at
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getServletRegistration(Ljava/lang/String;)Ljavax/servlet/ServletRegistration;
at org.scalatra.servlet.RichServletContext.mountServlet(RichServletContext.scala:127)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:84)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:93)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:90)
at ScalatraBootstrap.init(ScalatraBootstrap.scala:8)
Update 2
Another important part of the stacktrace I missed posting earlier:
2018.05.23 18:39:24 [main] WARN org.eclipse.jetty.webapp.WebAppContext - Failed startup of context o.e.j.w.WebAppContext#3d74bf60{/,file:///home/brandon/workspace/sbh/repeater,UNAVAILABLE}
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getServletRegistration(Ljava/lang/String;)Ljavax/servlet/ServletRegistration;
at org.scalatra.servlet.RichServletContext.mountServlet(RichServletContext.scala:127)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:84)
at org.scalatra.servlet.RichServletContext.mount(RichServletContext.scala:93)
I tried putting a WEB-INF/web.xml under repeater as specified above, but same result.
My original code had a lot more going on, which distracted me from the true cause of the problem.
This captures the essential problem.
import org.scalatest.AsyncFlatSpec
import scala.concurrent.Future
class AsyncFlatSpecSpec extends AsyncFlatSpec
{
it should "parse an XML file" in {
// ... Parsing ...
Future.successful(succeed)
}
it should "parse an XML file" in {
// ... Serializing ...
Future.successful(succeed)
}
}
This produced these errors:
[info] DeferredAbortedSuite:
[error] Uncaught exception when running AsyncFlatSpecSpec: java.lang.ArrayIndexOutOfBoundsException: 17
[trace] Stack trace suppressed: run last test:testOnly for the full output.
There is no array access happening anywhere in my code. What's going on?
Running "last test:testOnly" wasn't much help:
[info] DeferredAbortedSuite:
[error] Uncaught exception when running AsyncFlatSpecSpec: java.lang.ArrayIndexOutOfBoundsException: 17
sbt.ForkMain$ForkError: java.lang.ArrayIndexOutOfBoundsException: 17
at org.scalatest.exceptions.StackDepth$class.stackTraceElement(StackDepth.scala:63)
at org.scalatest.exceptions.StackDepth$class.failedCodeFileName(StackDepth.scala:77)
at org.scalatest.exceptions.StackDepthException.failedCodeFileName(StackDepthException.scala:36)
at org.scalatest.exceptions.StackDepth$class.failedCodeFileNameAndLineNumberString(StackDepth.scala:59)
at org.scalatest.exceptions.StackDepthException.failedCodeFileNameAndLineNumberString(StackDepthException.scala:36)
at org.scalatest.tools.StringReporter$.withPossibleLineNumber(StringReporter.scala:442)
at org.scalatest.tools.StringReporter$.stringsToPrintOnError(StringReporter.scala:916)
at org.scalatest.tools.StringReporter$.fragmentsForEvent(StringReporter.scala:747)
at org.scalatest.tools.Framework$SbtLogInfoReporter.apply(Framework.scala:622)
at org.scalatest.tools.FilterReporter.apply(FilterReporter.scala:41)
at org.scalatest.tools.SbtDispatchReporter$$anonfun$apply$1.apply(SbtDispatchReporter.scala:23)
at org.scalatest.tools.SbtDispatchReporter$$anonfun$apply$1.apply(SbtDispatchReporter.scala:23)
at scala.collection.Iterator$class.foreach(Iterator.scala:893)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
at org.scalatest.tools.SbtDispatchReporter.apply(SbtDispatchReporter.scala:23)
at org.scalatest.tools.Framework$SbtReporter.apply(Framework.scala:1119)
at org.scalatest.tools.Framework.org$scalatest$tools$Framework$$runSuite(Framework.scala:387)
at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:506)
at sbt.ForkMain$Run$2.call(ForkMain.java:296)
at sbt.ForkMain$Run$2.call(ForkMain.java:286)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Confused, I retreated to the non-Async version, to see if that fared any
better.
import org.scalatest.FlatSpec
class FlatSpecSpec extends FlatSpec {
it should "parse an XML file" in {
// ... Parsing ...
succeed
}
it should "parse an XML file" in {
// ... Serializing ...
succeed
}
}
It produced this different, but still cryptic error message:
[info] DeferredAbortedSuite:
[info] Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite *** ABORTED *** (20 milliseconds)
[info] Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite (AsyncFlatSpecSpec.scala:32)
[info] ScalaTest
For completeness, here are the related portions of my build.sbt:
scalaVersion := "2.11.8"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0-M15" % "test"
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.0-M15"
This was ultimately a trivial mistake on my part, but I wanted to post this for the sake of anyone else Googling these errors.
As many readers probably noticed while going through the examples, the problem was that I had copy/pasted the same test description.
This allows the code to compile, but will fail at runtime with errors that
don't identify the description as the culprit.
Stupid error on my part, but it would be nice if the compiler reported it in a more helpful way.
I am using Logback + SLF4J to do logging for those actors with trait of akka.actor.ActorLogging. However, when I do the code log.error("Error occur!", e), the stack trace of the exception e is not logged, but only print a line of Error occur! WARNING arguments left: 1. I wonder why and how to print the stack trace in the log file. Thank you. The following is my logback.groovy file configuration.
appender("FILE", RollingFileAppender) {
file = "./logs/logd.txt"
append = true
rollingPolicy(TimeBasedRollingPolicy) {
fileNamePattern = "./logs/logd.%d{yyyy-MM-dd}.log"
maxHistory = 30
}
encoder(PatternLayoutEncoder) {
pattern = "%date{ISO8601} [%thread] %-5level %logger{36} %X{sourceThread} - %msg%n"
}
}
root(DEBUG, ["FILE"])
Akka has separate logging, which is configured in Akka's application.conf. If you want bridge to SLF4J/Logback - use thеsе settings:
akka {
loggers = ["akka.event.slf4j.Slf4jLogger"]
loglevel = "DEBUG"
}
See: http://doc.akka.io/docs/akka/2.0/scala/logging.html
As far as I can see here, reason (Throwable) should be the first argument of log.error:
def error(cause: Throwable, message: String)
That's why you see "WARNING arguments left" - your Throwable argument was just ignored.
The 'cause' exception should be the first argument to error, not the second (as correctly mentioned by JasonG in a comment on another answer).
Using the Akka log system instead of 'bare' scala-logging has some advantages around automatically added metadata and easier testing/filtering.
See also:
http://doc.akka.io/docs/akka/2.4.16/scala/logging.html
http://doc.akka.io/api/akka/2.4/akka/event/LoggingAdapter.html#error(cause:Throwable,message:String):Unit