I am trying a Maven Project with javacpp from Eclipse, and the project builds, but when I try to run it, it gives an exception and terminates itself. I am pretty new to Maven and managing pom.xml files, and I don't know what to do. The exception is:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no jniTest in java.library.path:
at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2447)
at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:809)
at java.base/java.lang.System.loadLibrary(System.java:1893)
at org.bytedeco.javacpp.Loader.loadLibrary(Loader.java:1683)
at org.bytedeco.javacpp.Loader.load(Loader.java:1300)
at org.bytedeco.javacpp.Loader.load(Loader.java:1123)
at com.berk.maventest.Test.<clinit>(Test.java:13)
Below is my pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.berk</groupId>
<artifactId>maventest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacpp-platform</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>ffmpeg-platform</artifactId>
<version>4.3.1-1.5.4</version>
</dependency>
</dependencies>
</project>
And my Test.java file:
package com.berk.maventest;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
#Platform(include = "Test.cpp")
#Namespace("TestLibrary")
public class Test extends Pointer{
static {
Loader.load();
}
public Test()
{
allocate();
}
private native void allocate();
public native int testMethod(int a);
public static void main(String [] args) {
//Calling the constructor
Test test = new Test();
//Calling the function
System.out.println("The answer is: " + test.testMethod(2));
//Calling the destructor
test.close();
}
}
I'm trying to learn JUnit Testing currently. I want to test first custom 'TestUnit' class but IDE tells me that Cannot resolve symbol 'TestUnit'. What I should do to fix this error?
TestUnit class:
package test.lessons.purejava;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestUnit {
#Test
public void testAdd(){
String string = "Test unit works";
assertEquals("Test unit works", string);
}
#Test
public void concatTest(){
Concatenation concatenation = new Concatenation();
String result = concatenation.concat("Hello", " World");
assertEquals("Hello World", result);
}
}
and pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test.lessons</groupId>
<artifactId>purejava</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!--<!–
https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
–>-->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!--<scope>test</scope>-->
</dependency>
</dependencies>
</project>
My porm.xml file looks like this...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>vget</artifactId>
<version>1.2.6</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
And My java code looks like this, But it is not adding the Vget from the maven to its import list...
package com.mycompany.mavenproject1;
import java.io.File;
import java.net.URL;
public class Downloader {
public static void main(String[] args) {
try {
// ex: http://www.youtube.com/watch?v=Nj6PFaDmp6c
String url = "https://www.youtube.com/watch?v=SCOKysMnH50";
// ex: "/Users/axet/Downloads"
String path = "";
VGet v = new VGet(new URL(url), new File(path));
v.download();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
The Line VGet v = new ... shows an error because the vget is not imported in the code and it is not imported because, the maven won't allow me to import it, I don't know what to do with it...
I have a project which has dependencies in its classpath (Java buildpath). Now I have converted it to maven project and compiling it using my customized Maven plugin. Following will be my POM file -
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>ear</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>com.my.maven.plugin</groupId>
<artifactId>my-maven-plugin</artifactId>
<version>0.0.1</version>
<extensions>true</extensions>
</plugin>
</plugins>
</build>
</project>
And in my-maven-plugin, I have overridden compile phase -
maven-plugin pom-
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>my-maven-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>maven-plugin</packaging>
<name>my-maven-plugin</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>3.3.9</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.3.9</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<version>3.3.9</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-embedder</artifactId>
<version>3.3.9</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-archiver</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>maven-surefire-common</artifactId>
<version>2.19.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-api</artifactId>
<version>2.19.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-component-annotations</artifactId>
<version>1.6</version>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.19.1</version>
</dependency>
</dependencies>
</project>
lifecycle.xml -
<?xml version="1.0" encoding="UTF-8"?>
<lifecycles>
<lifecycle>
<id>customLifeCycle</id>
<phases>
<phase>
<id>compile</id>
<executions>
<execution>
<goals>
<goal>mycompile</goal>
</goals>
</execution>
</executions>
</phase>
</phases>
</lifecycle>
</lifecycles>
components.xml
<?xml version="1.0" encoding="UTF-8"?>
<component-set>
<components>
<component>
<role>org.apache.maven.artifact.handler.ArtifactHandler</role>
<role-hint>ear</role-hint>
<implementation>org.apache.maven.artifact.handler.DefaultArtifactHandler</implementation>
<configuration>
<type>ear</type>
<extension>ear</extension>
<language>java</language>
<packaging>ear</packaging>
</configuration>
</component>
<component>
<role>org.apache.maven.lifecycle.mapping.LifecycleMapping</role>
<role-hint>ear</role-hint>
<implementation>org.apache.maven.lifecycle.mapping.DefaultLifecycleMapping</implementation>
<configuration>
<phases>
<process-resources>org.apache.maven.plugins:maven-resources-plugin:resources</process-resources>
<compile>com.test:my-maven-plugin:mycompile</compile>
<process-test-resources>org.apache.maven.plugins:maven-resources-plugin:testResources</process-test-resources>
<test-compile>org.apache.maven.plugins:maven-compiler-plugin:testCompile</test-compile>
<test>org.apache.maven.plugins:maven-surefire-plugin:test</test>
<install>org.apache.maven.plugins:maven-install-plugin:install</install>
<deploy>org.apache.maven.plugins:maven-deploy-plugin:deploy</deploy>
</phases>
</configuration>
</component>
</components>
</component-set>
And , overridden compile mojo -
#Mojo( name = "mycompile", defaultPhase = LifecyclePhase.COMPILE )
public class MyCompileMojo extends AbstractMojo{
#Parameter( defaultValue = "${project}", readonly = true, required = true )
private MavenProject project;
public void execute() throws MojoExecutionException, MojoFailureException {
}
}
Now, in compile phase, I want a list of JAR files which are present in classpath. How can I get it? I have tried following - but most of them returns target folder path and classes folder path
List<String> list1 = project.getCompileClasspathElements();
List<String> list2 = project.getRuntimeClasspathElements();
List<String> list3 = project.getSystemClasspathElements();
List<String> list4 = project.getTestClasspathElements();
List<Dependency> list5 = project.getCompileDependencies();
Properties list6 = project.getProperties();
List<Dependency> list7 = project.getSystemDependencies();
List<Dependency> list8 = project.getRuntimeDependencies();
My project structure to be compiled
The key ingredient you're missing is requiresDependencyResolution, which represent the set of dependencies that will be made available to the plugin. From the Mojo API reference:
Flags this Mojo as requiring the dependencies in the specified class path to be resolved before it can execute. [...] If the annotation is not present at all, the mojo must not make any assumptions about the artifacts associated with a Maven project.
To have access to the compile-time dependencies of the project, you can use ResolutionScope.COMPILE:
compile resolution scope = compile + system + provided dependencies
Among others, there is also COMPILE_PLUS_RUNTIME to have access to runtime scoped dependencies as well, or TEST to add the test scoped dependencies. When this parameter is not present for the Maven plugin, no classpath elements of the Maven project will be available to it, which is the behaviour you encountered.
Therefore, if you want the Maven plugin to get hold of the list of the compile-tile JAR files which are the dependencies of the current Maven project, you can have:
#Mojo(name = "mycompile", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE)
public class MyCompileMojo extends AbstractMojo {
#Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
public void execute() throws MojoExecutionException, MojoFailureException {
try {
List<String> list = project.getCompileClasspathElements();
getLog().info(list.toString());
} catch (DependencyResolutionRequiredException e) {
throw new MojoFailureException("Couldn't resolve compile dependencies", e);
}
}
}
The method getCompileClasspathElements() returns the list of path to the JAR files of each compile-time dependencies. It will also contain the path to the target/classes folder of the current Maven project, because it contains the compiled main Java sources of the project. The code above would simply print this list. Similarly, you would use getTestClasspathElements() together with ResolutionScope.TEST to have the list of test scoped dependencies, as well as compile-time dependencies.
If you only want the path to the JAR file of the dependencies, without the classes of the project itself, you can use the method getArtifacts() instead:
public void execute() throws MojoExecutionException, MojoFailureException {
Set<Artifact> artifacts = project.getArtifacts();
for (Artifact artifact : artifacts) {
System.out.println(artifact.getFile());
}
}
Note that for this to work, you need to make sure the compile phase (or test-compile) has run. The lists are lazily-populated. Running mvn clean test will make sure the plugin has access to the test scope dependencies if it declared a requiresDependencyResolution of TEST. Similarly, running mvn clean compile (along with changing the phase to <phase>compile</phase>) will make sure the plugin has access to the compile scope dependencies if it declared a requiresDependencyResolution of COMPILE.
Couple of side-notes:
The file lifecycle.xml has to be located inside src/main/resources/META-INF/maven. Note that this file is actually completely unused in your set-up, because you did not use the new customLifeCycle inside your components.xml, and override ear instead;
The file components.xml has to be located inside src/main/resources/META-INF/plexus. Note that the <compile>com.test:my-maven-plugin:mycompile</compile> has to match the group id and artifact id of the plugin;
The test project needs to use the plugin like so:
<packaging>ear</packaging> <!-- because your lifecycle mapping override ear -->
<dependencies>
<!-- some dependencies like maven-core -->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.test</groupId>
<artifactId>my-maven-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<extensions>true</extensions>
</plugin>
</plugins>
</build>
Then you can run mvn clean package and the plugin will correctly prints the path to JAR files of maven-core (for example) and its dependencies.
This worked for me.
I found it here https://www.mkyong.com/java/how-to-print-out-the-current-project-classpath/
package com.mkyong.io;
import java.net.URL;
import java.net.URLClassLoader;
public class App{
public static void main (String args[]) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}
}
}
In completion to the previous answer, you can read all Class-Path like that :
public static List<String> getClassPaths() {
List<String> list = new ArrayList<String>();
Enumeration res;
try {
res = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while (res.hasMoreElements()) {
try {
URL url = (URL)res.nextElement();
InputStream is = url.openStream();
if (is != null) {
Manifest manifest = new Manifest(is);
Attributes mainAttribs = manifest.getMainAttributes();
String classpath = mainAttribs.getValue("Class-Path");
if (classpath != null)
list.add(classpath);
}
}
catch (Exception e) {
// Silently ignore wrong manifests or stop the compilation
}
}
} catch (IOException e1) {
// Silently ignore wrong manifests or stop the compilation
}
return list;
}
If you need to go deeper into dependencies:
public static List<String> getClassPaths() {
List<String> list = new ArrayList<String>();
Enumeration res;
try {
res = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while (res.hasMoreElements()) {
try {
URL url = (URL)res.nextElement();
InputStream is = url.openStream();
if (is != null) {
Manifest manifest = new Manifest(is);
Attributes mainAttribs = manifest.getMainAttributes();
String classpath = mainAttribs.getValue("Class-Path");
if (classpath != null)
for (String lib : classpath.split(" ")) {
try {
list.addAll(getClassPathsFromJar(lib));
} catch (IOException ioe)
{
list.add(lib);
}
}
}
}
catch (Exception e) {
// Silently ignore wrong manifests or stop the compilation
}
}
} catch (IOException e1) {
// Silently ignore wrong manifests or stop the compilation
}
return list;
}
public static List<String> getClassPathsFromJar(String lib) throws IOException {
List<String> entries = new ArrayList<String>();
JarFile jar = new JarFile(lib);
Manifest manifest = jar.getManifest();
if (manifest == null) {
entries.add(lib);
return entries;
}
Attributes mainAttribs = manifest.getMainAttributes();
String classpath = mainAttribs.getValue("Class-Path");
if (classpath == null) {
entries.add(lib);
return entries;
}
for (String l : classpath.split(" ")) {
entries.addAll(getClassPathsFromJar(l));
}
return entries;
}
Very simple setup:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo-rest-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo-rest-client</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.5.Final</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-buffer</artifactId>
<version>4.1.5.Final</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-hystrix</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
And a test case to demonstrate different usages of AsyncRestTemplate:
SampleTests.java
package com.example;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandProperties;
import feign.RequestLine;
import feign.hystrix.HystrixFeign;
import feign.hystrix.SetterFactory;
import org.junit.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.Netty4ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;
public class SampleTests {
private static final String URL = "https://api.github.com/users/octocat";
private static final int DEFAULT_SLEEP_MILLIS = 20;
private static final int DEFAULT_TIMEOUT = 10000;
#Test(timeout = DEFAULT_TIMEOUT)
public void syncRestNetty() throws Exception {
RestTemplate restTemplate = new RestTemplate(new Netty4ClientHttpRequestFactory());
ResponseEntity<String> response = restTemplate.getForEntity(URL, String.class);
System.out.println("response = " + response);
}
#Test(timeout = DEFAULT_TIMEOUT)
public void asyncRestNetty() throws Exception {
AsyncRestTemplate restTemplate = new AsyncRestTemplate(new Netty4ClientHttpRequestFactory());
ListenableFuture<ResponseEntity<String>> listenableFuture = restTemplate.getForEntity(URL, String.class);
listenableFuture.addCallback(result -> System.out.println("result = " + result), Throwable::printStackTrace);
while (!listenableFuture.isDone()) {
Thread.sleep(DEFAULT_SLEEP_MILLIS);
}
System.out.println("the end");
}
#Test
public void asyncRestOkHttp() throws Exception {
AsyncRestTemplate restTemplate = new AsyncRestTemplate(new OkHttp3ClientHttpRequestFactory());
ListenableFuture<ResponseEntity<String>> listenableFuture = restTemplate.getForEntity(URL, String.class);
listenableFuture.addCallback(result -> System.out.println("result = " + result), Throwable::printStackTrace);
while (!listenableFuture.isDone()) {
Thread.sleep(DEFAULT_SLEEP_MILLIS);
}
System.out.println("the end");
}
#Test
public void asyncRestHystrixFeign() throws Exception {
GitHub gitHub = HystrixFeign.builder()
.setterFactory((target, method) -> new SetterFactory.Default().create(target, method).andCommandPropertiesDefaults(HystrixCommandProperties.defaultSetter().withExecutionTimeoutInMilliseconds(10000)))
.target(GitHub.class, "https://api.github.com");
HystrixCommand<String> command = gitHub.octocatAsync();
command.toObservable().subscribe(result -> System.out.println("result = " + result), Throwable::printStackTrace);
while (!command.isExecutionComplete()) {
Thread.sleep(DEFAULT_SLEEP_MILLIS);
}
System.out.println("command.getExecutionTimeInMilliseconds() = " + command.getExecutionTimeInMilliseconds());
System.out.println("the end");
}
interface GitHub {
#RequestLine("GET /users/octocat")
HystrixCommand<String> octocatAsync();
}
}
When trying to run the tests which use Netty they just hang forever. (To see this please remove the JUnit timeout constraint). But if I run the exact same code with other clients everything works as expected.
I have tried different versions of Spring Boot and Netty but did not succeed. And from the logs everything looks ok.
What am I missing here?
EDIT:
Opened a ticket https://jira.spring.io/browse/SPR-14744 as suggested on Spring Gitter
EDIT-2:
Answer from Brian Clozel helped me find the issue which is related to Netty not realizing the server sent an empty response (a particular case with Github API and plain http) so I am marking it as accepted.
Can you try to configure your request factory with a Netty Sslcontext?
Netty4ClientHttpRequestFactory nettyFactory = new Netty4ClientHttpRequestFactory();
nettyFactory.setSslContext(SslContextBuilder.forClient().build());
AsyncRestTemplate restTemplate = new AsyncRestTemplate(nettyFactory);
Without that context, the client is trying to send plaintext requests to the https endpoint; in that case, you're probably getting an HTTP 400 response.
In your example code, the throwable should be an instance of HttpClientErrorException, and you could get that information by logging the response status or its body with exception.getResponseBodyAsString().