I am trying to execute a .groovy file in Java however being new to both Java and Groovy I am having some problems. I'm doing this to learn more and would appreciate if someone could tell me what i am doing wrong.
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyShell;
import javax.naming.Binding;
import java.io.File;
public class testClass extends GroovyShell{
public static void main(String[] args){
try{
ClassLoader parent = testClass.class.getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(new File("src/testg.groovy"));
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Object[] args1 = {};
groovyObject.invokeMethod("run",args1);
}catch(Exception e) {
System.out.println("error loading file");
}
}
}
I am getting the following errors :
Groovyc: Cannot compile Groovy files: no Groovy library is defined for module 'Prep'
Using javac 1.7.0_09 to compile java sources
Compilation completed with 1 error and 0 warnings in 9 sec
1 error
0 warnings
Groovyc: Internal groovyc error: code 1
Or perhaps someone could give me an example of how to execute e.g. hello world script written in groovy, in java.
That's not an error thrown by your code. It's an error thrown by IntelliJ, which tries to compile your .groovy file to a .class file.
Since what you want is to parse and run this groovy file at runtime, you shouldn't care about this error. Or rather, to avoid it, you should not put the .groovy file in a directory marked as a source directory in the IntelliJ project, so that IntelliJ doesn't try to compile it.
Related
I have been trying to compile my Java code using the format javac Main.java but for some reason the compiler says that my package does not exist and as a matter of fact it is in the project structure, here is a screenshot:
The exact error is: Main.java:1: error: package com.fasterxml.jackson.databind does not exist import com.fasterxml.jackson.databind.ObjectMapper;
And my code looks like this in my Main.java:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
public final class Main {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: Main [file path]");
return;
}
UdacisearchClient client =
new UdacisearchClient(
"CatFacts LLC",
17,
8000,
5,
Instant.now(),
Duration.ofDays(180),
ZoneId.of("America/Los_Angeles"),
"555 Meowmers Ln, Riverside, CA 92501");
Path outputPath = Path.of(args[0]);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.writeValue(Files.newBufferedWriter(outputPath), client);
System.out.println("Wrote to: "+ outputPath.toAbsolutePath());
UdacisearchClient deserialized = objectMapper.
readValue(Files.newBufferedReader(outputPath), UdacisearchClient.class);
System.out.println("Deserialized: " + deserialized);
}
}
The whole code is supposed to compile like this javac Main.java and then java Main client.json. When I try to compile it by going to Run, Edit Configurations and by adding client.json as the argument of my program it works like a charm, my object is serialized as a json object in the client.json file but when I compile using command line it says no package is found. The same error happens for any other dependency I try to use. It should be noted that when I instantiate objects from my dependency it looks fine as the import lines related to those objects aren't red. So I guess my issue resides in my command line compilation or my Intellij environment. I have tried many of the solution proposed online but the problem remains. I would like some help please.
It turns out the solution was simple.
First compiling the libraries inside the lib folder and Main.java doing :
javac -cp ".;lib/*" Main.java
Then running my class Main (containing my main function):
java -cp ".;lib/*" Main
I was missing on the dot "." and the semicolon ;!
My software used groovy.lang Java package to execute Groovy scripts from a shell, binding the variables in the script to Java objects.
A typical script looks like:
package packagename
// import Java classes
abstract class MyClass extends Script {
def myfunction() {
}
}
in this example, 'myfunction' will be called from the outside.
The scripts (located at the file system) are loaded by the following sequence from Java -
the code returns GroovyShell class instance:
GroovyClassLoader groovyClassLoader = new GroovyClassLoader(...)
File groovyFile = new File(groovyURL.toURI());
Class<?> groovyClass = groovyClassLoader.parseClass(groovyFile);
CompilerConfiguration groovyConfig = new CompilerConfiguration();
groovyConfig.setScriptBaseClass(groovyClass.getName());
return new GroovyShell(groovyClassLoader, new Binding(), groovyConfig);
My design goal is to add a Groovy library that can be shared between scripts
My preference is to implement a class (adding lines into the existing script seems to be a hack).
I made a simple class representing the library code. Right now, it looks like:
package shared
class MySharedLib
{
static def testFunction()
{
return "test";
}
}
To make sure the class it loaded, I added a call to
groovyClassLoader.parseClass(groovyLibraryFile)
before loading the actual script by:
groovyClassLoader.parseClass(groovyFile);
Now, from the script, I can call the library:
shared.MySharedLib.testFunction()
indeed return the string "test".
However, when trying to do the import via:
import shared.MySharedLib
in the script (before class definition) - I always got an error when loading the script:
Exception in thread "main" org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
script754084858.groovy: 14: unable to resolve class shared.MySharedLib
# line 14, column 1.
Tried to modify the classpath, it did not help. I realize something is wrong with my setup.
Will appreciate any tip how to load a Groovy library in the correct way.
Max
Thanks for comments.
I think I understand the cause.
It turns out that at some point, the "script" is being compiled using
GroovyClassLoader classLoader = new GroovyClassLoader(parentClassLoader);
GroovyCodeSource codeSource = new GroovyCodeSource(code, scriptClassName + ".groovy", "/groovy/script");
CompilationUnit cu = new CompilationUnit(classLoader);
cu.addSource(codeSource.getName(), codeSource.getScriptText());
cu.compile(CompilePhase.CLASS_GENERATION.getPhaseNumber());
The compilation fails when reaching the "import" statement, since the library class is not in the classpath, so it's unreachable.
Calling classLoader.addClasspath(path) with the appropriate path solves the issue.
So the problem was related to compilation - not to execution.
I am trying to compile a small program. During compilation, it tries to look at wrong path for java util libs. Below is the compilation output
javac -Xlint:unchecked adssim/util/XMLParser.java
adssim/util/XMLParser.java:3: error: cannot access util
import java.util.Vector;
^
bad source file: ./java/util.java
file does not contain class java.util
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
File loation
/apps/oasis/adarsh/adssim/util>ls -lrt XMLParser.java
-rwxrwxrwx 1 oasis oasis 1258 Apr 8 15:49 XMLParser.java
Classpath
/apps/oasis/adarsh/adssim/util>echo $CLASSPATH
:/apps/oasis/java/classes12.jar:/apps/oasis/java/ifxjdbc.jar:/apps/oasis/java/log4j-1.2.14.jar:/apps/oasis/java/commons-io-2.5.jar:/apps/oasis/adarsh/adssim:/apps/oasis/adarsh/adssim/util:/apps/oasis/adarsh/adssim/util/crypto:/apps/oasis/adarsh/adssim/channel:/apps/oasis/adarsh
File Source
package adssim.util;
import java.util.Vector;
public class XMLParser
{
public static Vector getXMLTagValue(String xml, String section) throws Exception
{
String xmlString = new String(xml);
Vector v = new Vector();
What am i doing wrong guys ?
Is there a file on your disk that is actually called util.java in a directory called java? Maybe you have created such a file by mistake?
This part of the error message makes it sound like that:
bad source file: ./java/util.java
I am trying to call an external Java function from Haxe using "extern".
Haxe Code :
extern class Ext
{
public static function test():String;
}
class Sample
{
public static function main()
{
trace(Ext.test());
}
}
Java Code :
public class Ext
{
public static String test()
{
return "Hello";
}
}
Both Sample.hx and Ext.java files are in the same folder.
When I try to execute haxe -main Sample -java Sample, I get the following error.
C:\Users\ila5\Desktop\CPP>haxe -main Sample -java Sample
haxelib run hxjava hxjava_build.txt --haxe-version 3201 --feature-level 1
javac.exe "-sourcepath" "src" "-d" "obj" "-g:none" "#cmd"
src\haxe\root\Sample.java:33: error: cannot find symbol
haxe.Log.trace.__hx_invoke2_o(0.0, haxe.root.Ext.test(), 0.0, new haxe.lang.DynamicObject(new java.lang.String[]{"className", "fileName", "methodName"}, new java.lang.Object[]{"Sample", "Sample.hx", "main"}, new java.lang.String[]{"lineNumber"}, new double[]{((double) (((double) (10) )) )}));
^
symbol: class Ext
location: package haxe.root
1 error
Compilation error
Native compilation failed
Error: Build failed
I would like to understand why the build failed. Any ideas?
I am not sure you might need to reference your Java code with -lib or something else?
But generally with Java target it's much simpler to just use a jar file. By typing haxe --help you will see the relevant command listed, I have never had a need to hand write externs for the Java target.
-java-lib <file> : add an external JAR or class directory library
The reason it fails is explained here
https://groups.google.com/forum/#!topic/haxelang/EHeoGN_Ppvg
I tried setting up with class paths and various options but did not get a solution, I think it's just a bit fiddly to do externs on the java target by hand. Really it's better to use Java compiler to create jars and let haxe auto generate the externs unless you get an issue then report it to hxJava repository.
Use -java-lib.
# build.sh
haxe Main.hx -main Main -java-lib javalib/ -java out
,
// ./Main.hx
import external.*;
class Main {
public static function main() {
trace(external.ExternalClass.myFunction());
}
}
,
// ./javalib/external/ExternalClass.java
package external;
public class ExternalClass {
public static String myFunction() {
return "External Java function";
}
}
,
./javalib/external/ExternalClass.class is the output of javac ExternalClass.java
Here is the thing: I am trying to run the example program in the joda-time project.
The start of the Examples.java file looks like this:
package org.joda.example.time;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Instant;
/**
* Example code demonstrating how to use Joda-Time.
*
* #author Stephen Colebourne
*/
public class Examples {
public static void main(String[] args) throws Exception {
try {
new Examples().run();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
And all the classes for compiling this Example.java is in a joda-time-2.3.jar.
I can successfully compile this program by using
javac -cp somewhere/joda-time-2.3.jar Example.java
And it generate an Example.class, but I jut cannot execute that.
So far I have tried:
java Examples
java -cp somewhere/joda-time-2.3.jar Examples
java -cp somewhere/joda-time-2.3.jar org.joda.example.time.Examples
But they all generate this kind of errors:
Error: Could not find or load main class org.joda.example.time.Example
Error: Could not find or load main class Examples
And I've tried both in the org/joda/example/time folder and the parent folder of org
Anyone can give an instruction on how to execute that? Really appreciate it!
Error: Could not find or load main class org.joda.example.time.Example
public class Examples {
Name of your class is Examples not Example
EDIT
Sorry for late reply...
To execute specific Java program you need to bring control to root directory so if your class is in abc/newdir/Examples.java you need to use cd command (in windows) to lead control to root directory and than compile or you can defeneitly go for the suggestion of kogut.
C:/abc/newdir>java -cp somewhere/joda-time-2.3.jar Examples
Modify your classpath parameter, so it should include directory where Example.class was generated.
In case of out/org/joda/example/time/Example.class you need to use
java -cp somewhere/jodata-time-2.3.jar:out org.joda.example.time.Example