Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Java library groovy

Tags:

java

groovy

i want to use a method defined in the apache.common.net library in my groovy-Script.

I first downloaded and included it in my config:

            this.class.classLoader.rootLoader.addURL(new URL("file:///${currentDir}/lib/commons-net-3.3.jar"))

Afterwards i try to use it in my groovy-script like this (to make it clear: the import pimpim.* imports also the classLoader above):

    import pimpim.*

import org.apache.commons.net.ftp.*

def pm = PM.getInstance("test")


public class FileUploadDemo {
  public static void main(String[] args) {
    FTPClient client = new FTPClient();

I also tried several annotations for the "import" like

import org.apache.commons.net.ftp.FTPClient

But i keep getting this error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Y:\pimconsole\scripts\ftp.gy: 11: unable to resolve class FTPClient
 @ line 11, column 15.
       FTPClient client = new FTPClient();

What did i miss? Sorry, i am still new to groovy :/

like image 398
Mattes Avatar asked Aug 24 '15 10:08

Mattes


People also ask

How do I import a Java class into Groovy?

The same code in Java needs an import statement to Date class like this: import java. util. Date. Groovy by default imports these classes for you.

Can you import libraries in Java?

It is simple to import any library that is referenced in the Project properties. Add library in the project using properties then import that. But net it built-in library provided in JDK and JRE. You can use import java.net.

How import Groovy library to IntelliJ?

In the Project tool window, right-click the project and from the context menu, select Add Framework Support. In the dialog that opens, select Groovy and click OK. IntelliJ IDEA adds the Groovy SDK to your project and you can add Groovy classes and Groovy scripts.


1 Answers

So, you can add it to the classpath when you start up your script;

groovy -cp .;lib/commons-net-3.3.jar ftp.gy

Or, you can add a @Grab annotation to your script, and Groovy will download the dependency and add it to the classpath before running (but this can not work if your scripts are executed on a box with no access to maven);

@Grab('commons-net:commons-net:3.3')
import org.apache.commons.net.ftp.*

...rest of your script...

Or the classpath hacking route you have above should work if you try:

this.getClass().classLoader.rootLoader.addURL(new File("lib/commons-net-3.3.jar").toURL())
like image 65
tim_yates Avatar answered Oct 24 '22 19:10

tim_yates