I am trying to use an open source tool built on Batik and I am running into trouble with one of the dependencies when I try to build it. Pretty sure this is something to do with classpaths and library locations, but I can't figure out what is happening.
So the project I am working with ( SVG2EMF ) is using the FreeHep EMF Driver, which in turn uses the FreeHep GraphicsIO project. Because these three have not been playing nicely on my system ( Ubuntu 14.04 ) I've downloaded the source for all three to try and step through the problem.
Everything builds correctly and I can step through the code successfully, but the unit tests on SVG2EMF fail at the point where the EMF Driver makes a call to something from GraphicsIO- the relevant parts of the code in question is here:
import org.freehep.graphicsio.ImageGraphics2D;
import org.freehep.graphicsio.ImageConstants;
// ...snip...
public class AlphaBlend extends EMFTag implements EMFConstants
{
// ...snip...
public void write(int tagID, EMFOutputStream emf) throws IOException
{
emf.writeRECTL(bounds);
emf.writeLONG(x);
emf.writeLONG(y);
emf.writeLONG(width);
emf.writeLONG(height);
dwROP.write(emf);
emf.writeLONG(xSrc);
emf.writeLONG(ySrc);
emf.writeXFORM(transform);
emf.writeCOLORREF(bkg);
emf.writeDWORD(usage);
emf.writeDWORD(size); // bmi follows this record immediately
emf.writeDWORD(BitmapInfoHeader.size);
emf.writeDWORD(size + BitmapInfoHeader.size); // bitmap follows bmi
emf.pushBuffer();
int encode;
// plain
encode = BI_RGB;
ImageGraphics2D.writeImage(
(RenderedImage) image,
ImageConstants.RAW.toLowerCase(),
ImageGraphics2D.getRAWProperties(bkg, "*BGRA"),
new NoCloseOutputStream(emf));
// emf.writeImage(image, bkg, "*BGRA", 1);
// png
// encode = BI_PNG;
// ImageGraphics2D.writeImage(image, "png", new Properties(), new
// NoCloseOutputStream(emf));
// jpg
// encode = BI_JPEG;
// ImageGraphics2D.writeImage(image, "jpg", new Properties(), new
// NoCloseOutputStream(emf));
int length = emf.popBuffer();
emf.writeDWORD(length);
emf.writeLONG(image.getWidth());
emf.writeLONG(image.getHeight());
BitmapInfoHeader header = new BitmapInfoHeader(image.getWidth(), image
.getHeight(), 32, encode, length, 0, 0, 0, 0);
bmi = new BitmapInfo(header);
bmi.write(emf);
emf.append();
}
This throws a NoClassDefFoundError specifically relating to org.freehep.graphicsio.ImageGraphics2D on that writeImage call. When I step through in the debugger, a watch on ImageConstants.RAW has the value of Unknown type "org.freehep.graphicsio.ImageConstants" even though the application built quite happily with those references. Any references to ImageGraphics2D behave in exactly the same way.
The dependency in the SVG2EMF pom.xml looks like this:
<dependencies>
<!-- some other dependencies -->
<dependency>
<groupId>org.freehep</groupId>
<artifactId>freehep-graphicsio-emf</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
Dependency from the FreeHEP EMF Driver looks like this:
<dependencies>
<!-- necessary because transitive deps seem to go above inhertied deps -->
<dependency>
<groupId>org.freehep</groupId>
<artifactId>freehep-util</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.freehep</groupId>
<artifactId>freehep-graphicsio</artifactId>
<version>2.1.1</version>
</dependency>
<!-- Other dependencies -->
</dependencies>
Can anybody shed any light on what is actually going on here or what I need to be doing in order to enable this to work?
EDIT: I think I have found where the problem is coming from- way down the StackTrace I see a "Caused by: ExceptionInInitializerError" - which appears to mark the class as inaccessible from then on. So the dependency does exist, but an exception is being thrown by the initializer which causes the JRE to mark it as unusable.
Further Edit: To solve these problems it can be useful ( although it is not mentioned anywhere on the freehep.org website ) to know that the project is now hosted on Github so you can find newer versions from there. In my case going straight to the latest version solved the problem.
Related
Im using apache-jena-libs library version 4.3.2(tried various versions). I've imported it as maven pom dependecny
<dependency>
<groupId>org.apache.jena</groupId>
<artifactId>apache-jena-libs</artifactId>
<version>4.3.2</version>
<type>pom</type>
</dependency>
And it has successfuly loaded(no errors)
(https://i.stack.imgur.com/h29Gp.png)
imports are fine as well, no errors there
import org.apache.jena.riot.*;
import org.apache.jena.graph.*;
but when I actually use library in code as such:
#Override
public synchronized void add(Reader reader, String fullFilePath, RDFFormat dataFormat, Resource... contexts) throws IOException, RDFParseException, RepositoryException {
this.verifyIsOpen();
this.flushDelayAdd();
// final boolean useStatementContext = contexts != null && contexts.length == 0;
IRI graphIri = (IRI) Arrays.stream(contexts).findFirst().get();
try {
Graph gf = Factory.createDefaultGraph();
org.apache.jena.riot.RDFParser.create()
.source(fullFilePath)
.forceLang(org.apache.jena.riot.Lang.JSONLD11)
.base(graphIri.stringValue())
.parse(gf);
gf.close();
...
Everything looks fine but during maven clean-install I get error "cannot access org.apache.jena.graph.Graph".
This method is a part of the standart public class(no bean).
Im using Intelij Idea 2022.2.3 (Ultimate Edition) with JDK 1.8 and maven 3.8.1.
This problem I am encountering is only with this library, tried to search for answers but havent found anything exactly like this. Does anyone have any clue what could be wrong please?
I'm trying to upgrade dependencies for a java application that uses com.vividsolutions.jts. I have removed all the references to this library from pom.xml and replaced them by the ones from org.locationtech.jts.
I have updated all the imports to use org.locationtech version. However, in my function I'm still getting an error related to com.vividsolutions object not being imported.
import org.locationtech.spatial4j.context.jts.JtsSpatialContext;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.spatial4j.shape.jts.JtsGeometry;
// ... other stuff
public static myFunc() {
GeometryFactory gf = new GeometryFactory();
LinearRing linear = gf.createLinearRing(coordinates);
JtsGeometry poly = new JtsGeometry(fact.createPolygon(linear), JtsSpatialContext.GEO, true, true);
}
Here's the error that I get for the last line of the above code: [ERROR] cannot access com.vividsolutions.jts.geom.Geometry [ERROR] class file for com.vividsolutions.jts.geom.Geometry not found
I'm clearly importing JtsGeometry from the new library at org.locationtech, however, it's still thinking the old library should be used.
The old library isn't in the dependency tree or the code anymore, as the followings don't return anything:
mvn dependency:tree | grep vivid
rg vivid
Any idea what I'm missing here or how I should troubleshoot this?
I'm not too sure what was wrong with the vividsolutions library inclusion. However, I was able to resolve my issue by including both of these in pom.xml:
<dependency>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>1.18.2</version>
</dependency>
<dependency>
<groupId>org.locationtech.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.8</version>
</dependency>
Initially I didn't have the second dependency in the pom.xml file.
Is there any way to get OpenCV from repository? Which artifact should I add to pom.xml? Every tutorial I'd found is from '14 and it seems like something changed - they say it is'nt in official Maven repository yet, but I've found entry:
<!-- https://mvnrepository.com/artifact/nu.pattern/opencv -->
<dependency>
<groupId>nu.pattern</groupId>
<artifactId>opencv</artifactId>
<version>2.4.9-7</version>
</dependency>
Sadly, I get error
Caused by: java.lang.UnsatisfiedLinkError: no opencv_java249 in java.library.path
when I'm using System.loadLibrary(Core.NATIVE_LIBRARY_NAME). Can I add this library in a way that would make my project include it and 'forget' about manually adding it to classpath?
Add the following dependency in your POM file:
<dependency>
<groupId>org.openpnp</groupId>
<artifactId>opencv</artifactId>
<version>3.2.0-0</version>
</dependency>
and replace the following lines:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME)
with
nu.pattern.OpenCV.loadShared();
This should solve the problem in WINDOWS also. Happy Coding.
This worked for me.
nu.pattern.OpenCV.loadLibrary();
I'm using following maven dependency
<dependency>
<groupId>nu.pattern</groupId>
<artifactId>opencv</artifactId>
<version>2.4.9-4</version>
</dependency>
Try this, see if it works:
nu.pattern.OpenCV.loadShared();
System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
More info here in API section: https://github.com/patternconsulting/opencv
Also have 2.4.9-7 opencv dependency.
There is currently no official way to use the official Java bindings for OpenCV as a Maven dependency (as already mentioned in the comments, the Maven artifact was already requested in #4588, but is still unattended). Nevertheless, there are 3 possible approaches to your problem:
java.lang.UnsatisfiedLinkError was thrown because you need to install the binding's binaries (that is "opencv_java") separately. Most likely, that unofficial artifact does not include them (or not the ones compatible with your system). In order to build the bindings:
git clone the OpenCV repository.
git checkout the intended version (it appears that you are using version 2.4.9, although more recent versions are available)
Follow the instructions here to build OpenCV and its Java bindings, thus yielding a dynamically linked library ("opencv_java249.dll", "libopencv_java249.so", or something else depending on your OS).
Copy the shared library file to your java.library.path (again, this variable is system-dependent, but can be defined when running your application). At this point you should be ready to use that artifact.
An alternative is to use other bindings: the JavaCPP presets for OpenCV seem to work just as nicely as the official ones, and these are registered in maven (binaries for various platforms included!). Just remember that the API may not be exactly the same.
This solution may sound too far out, but it has legitimately worked for me in the past. Basically, you can avoid using the bindings: implement your solution in C++, then either link it with the JVM via JNI or make it a separate application, used by the main application via other mechanisms of your system (process spawning, I/O channels, you name it). For instance, I have once made a service component for feature extraction that other programs would connect to via ZeroMQ sockets.
Just use it
nu.pattern.OpenCV.loadShared();
write a class with this static void method
class Test {
public static void loadOpenCVNativeLibrary() {
nu.pattern.OpenCV.loadShared();
}
}
and after call it in your application class (with static main) for web application (spring boot for example) like this
static {
Test.loadOpenCVNativeLibrary();
}
...
public static void main(String[] args) throws UnknownHostException {
}
All you need:
install jar in local maven repository with:
mvn install:install-file -Dfile=C:\opencv411\build\java\opencv-411.jar -DgroupId=org -DartifactId=opencv -Dversion=4.1.1 -Dpackaging=jar
create a dependency in pom.xml:
<dependency>
<groupId>org</groupId>
<artifactId>opencv</artifactId>
<version>4.1.1</version>
</dependency>
Now that jar is on, we need to somehow add the OpenCV libraries. I did this by adding the lib folder in java.library.path to the maven-surefire plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<argLine>-Djava.library.path=${project.build.outputDirectory}/lib</argLine>
</configuration>
</plugin>
public static void main(String[] arges) throws MalformedURLException,
IOException, Exception {
loadLibraries();
// create and print on screen a 3x3 identity matrix
System.out.println("Create a 3x3 identity matrix...");
Mat mat = Mat.eye(3, 3, CvType.CV_8UC1);
System.out.println("mat = " + mat.dump());
// prepare to convert a RGB image in gray scale
String location = "resources/Poli.jpg";
System.out.print("Convert the image at " + location + " in gray scale... ");
// get the jpeg image from the internal resource folder
Mat image = Imgcodecs.imread(location);
// convert the image in gray scale
Imgproc.cvtColor(image, image, Imgproc.COLOR_RGB2GRAY);
// write the new image on disk
Imgcodecs.imwrite("resources/Poli-gray.jpg", image);
System.out.println("Done!");
}
private static void loadLibraries() {
try {
InputStream in = null;
File fileOut = null;
String osName = System.getProperty("os.name");
// String opencvpath = System.getProperty("user.dir");
String opencvpath = "C:\\opencv411\\build\\java\\";
if (osName.startsWith("Windows")) {
int bitness = Integer.parseInt(System.getProperty("sun.arch.data.model"));
if (bitness == 32) {
opencvpath = opencvpath + "\\x86\\";
} else if (bitness == 64) {
opencvpath = opencvpath + "\\x64\\";
} else {
opencvpath = opencvpath + "\\x86\\";
}
} else if (osName.equals("Mac OS X")) {
opencvpath = opencvpath + "Your path to .dylib";
}
System.out.println(opencvpath);
// System.out.println("Core.NATIVE_LIBRARY_NAME = " + Core.NATIVE_LIBRARY_NAME);
System.out.println("Core.NATIVE_LIBRARY_NAME = " + "opencv_java411.dll");
// System.load(opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll");
System.load(opencvpath + "opencv_java411.dll");
} catch (Exception e) {
throw new RuntimeException("Failed to load opencv native library", e);
}
}
For those who wants to use OpenCV 3.2 in MacOs environment, you can use following repository definition:
<repositories>
<repository>
<id>kodfarki</id>
<url>https://raw.githubusercontent.com/kodfarki/repository/master/</url>
</repository>
</repositories>
There is also an example project in https://github.com/kodfarki/opencv-example.
To use this example project, you still need to install OpenCV binaries
brew tap homebrew/science
brew install opencv3 --with-java --with-contrib
For windows there was a problem with #Sachin Aryal's answer. The answer by #Anirban Chakraborty is a very good hint. But, there was still issues at runtime as described in this thread.
Finally replacing OpenCV.loadShared(); with OpenCV.loadLocally(); worked for me.
I'm trying to use Byte Buddy library in Android but I get an error:
java.lang.IllegalStateException: This JVM's version string does not
seem to be valid: 0
I have coded nothing yet, just:
ByteBuddy test = new ByteBuddy();
in my App.java
I have imported:
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>0.7.7</version>
</dependency>
but it didn't work, to I tried with:
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-android</artifactId>
<version>0.7.7</version>
</dependency>
but I still get same error.
EDIT
I have put this line before initialize ByteBuddy:
System.setProperty("java.version", "1.7.0_51");
But now I get this another error:
Caused by: java.lang.UnsupportedOperationException: can't load this
type of class file.
for this code:
Class<?> dynamicType = new ByteBuddy(ClassFileVersion.JAVA_V6)
.subclass(Object.class)
.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("Hello World!"))
.make()
.load(getClass().getClassLoader(), AndroidClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
The error is because java.version returns 0 in Android (See section System Properties here - Comparison of Java and Android API)
Also, if you observe ByteBuddy ClassFileVersion
forCurrentJavaVersion() : This method checks for versionString which should return any valid Java/JDK version else it
throws IllegalStateException("This JVM's version string does not seem to be valid: " + versionString);
& since java.version is returning 0, it's throwing IllegalStateException.
Try to log this value:
String versionString = System.getProperty(JAVA_VERSION_PROPERTY);
Log.d(TAG, versionString);//retruns 0 here
hence workaround for this issue is to add
System.setProperty(JAVA_VERSION_PROPERTY, "1.7.0_79");//add your jdk version here
before calling
ByteBuddy test = new ByteBuddy();
where JAVA_VERSION_PROPERTY is declared as:
private static final String JAVA_VERSION_PROPERTY = "java.version";
Also dependency to use is:
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>0.7.7</version>
</dependency>
Else if you are using studio, you can add
compile 'net.bytebuddy:byte-buddy:0.7.7'
to your app build.gradle.
Hope this will help solve your issue.
After some problems with differences between JSE versions, I'm trying to log the Java compiler version used to compile (it's Groovy 2.1.9, Grails 2.3.8, Java 1.7.0_60 in fact).
After some rummaging around, I've constructed this piece of code to read the leading bytes of the class - see /http://en.wikipedia.org/wiki/Java_class_file#General_layout
(change the path to the class to match the package name):
class CompilerVersionSupport {
public static String getVersion() {
String classAsPath = 'com/my/organisation/CompilerVersionSupport.class';
InputStream stream = (new CompilerVersionSupport()).getClass().getClassLoader().getResourceAsStream(classAsPath);
DataInputStream ins = new DataInputStream (stream)
assert( ins.readUnsignedShort() == 0xcafe )
assert( ins.readUnsignedShort() == 0xbabe )
int minor = ins.readUnsignedShort();
int major = ins.readUnsignedShort();
ins.close();
int javaVersion = major - 44
return "1.$javaVersion"
}
}
Trouble is, it returns 1.5.
What could be going on?
Charles
The default Groovy behaviour is not to compile the code with the same bytecode version as the JDK being used. 1.5 is the default for compatibility reasons, IMHO. If you want the compiler to output newer bytecode you need to set that explicitly.
For example if you're using Maven to compile the code, you can use the GMavenPlus plugin. See the description of the targetBytecode parameter.
If you're not using Maven you can use -Dgroovy.target.bytecode=1.7 or research the possibilities for your particular build tool
If you're using Maven as the build tool, then chances are that it's using the gmavenplus-plugin to compile Groovy. To find out the target Java version of the bytecode generated I poked into the pom of the gmavenplus-plugin that my application uses: ~/.m2/repository/org/codehaus/gmavenplus/gmavenplus-plugin/1.5/gmavenplus-plugin-1.5.pom.
Inside that file I saw this, notice <javaVersion/>,
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<mavenVersion>2.2.1</mavenVersion>
<coberturaPluginVersion>2.7</coberturaPluginVersion>
<javadocPluginVersion>2.10.1</javadocPluginVersion>
<!-- these are properties so integration tests can use them -->
<javaVersion>1.5</javaVersion>
<dependencyPluginVersion>2.10</dependencyPluginVersion>
<compilerPluginVersion>3.2</compilerPluginVersion>
<junitVersion>4.12</junitVersion>
<surefirePluginVersion>2.18.1</surefirePluginVersion>
<pluginPluginVersion>3.4</pluginPluginVersion>
<!-- this is a property so that site generation can use it -->
<sourcePluginVersion>2.4</sourcePluginVersion>
<!-- this is a property so that site generation and integration tests can use it -->
<groovyVersion>2.4.1</groovyVersion>
</properties>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compilerPluginVersion}</version>
<configuration>
<source>${javaVersion}</source>
<target>${javaVersion}</target>
</configuration>
</plugin>
I use IntelliJ for an IDE. IntelliJ is automatically setting the language level to Java 1.5. Even if I change it, when I re-import projects it resets back to Java 1.5 (I've fuzzed out sensitive information),
I think the issue is with the program you are using to find the class version. If the assertion is not enabled the stream doesnt read the first two unsigned shorts and hence the subsequent minor and major read statements results in 0Xcafe and 0xbabe respectively. Try enabling assertion or try using an if check.
public static String getVersion() throws Exception {
String classAsPath = "com/my/organisation/CompilerVersionSupport.class";
InputStream stream = (new CompilerVersionSupport()).getClass().getClassLoader().getResourceAsStream(classAsPath);
DataInputStream ins = new DataInputStream(stream);
if(ins.readUnsignedShort() != 0xcafe) throw new AssertionError("Invalid Class");
if(ins.readUnsignedShort() != 0xbabe) throw new AssertionError("Invalid Class");
int minor = ins.readUnsignedShort();
int major = ins.readUnsignedShort();
ins.close();
int javaVersion = major - 44;
return "1." + javaVersion;
}