I have a Java web application that exposes several REST endpoints. They all work. They can be hit and return the expected data (plain text). I need them to return JSON instead. To do this, the application needs to:
Include the "jersey-media-moxy" jar
Include #XmlRootElement atop any POJO we want converted to JSON
I added the #XmlRootElement to the class. Our project builds with gradle. I added this line to the bottom of the dependencies section of our build.gradle file:
compile group: 'org.glassfish.jersey.media', name: 'jersey-media-moxy', version: '2.26'
It looks almost identical to the line above it:
compile group: 'org.glassfish.jersey.media', name: 'jersey-media-multipart', version: '2.22.2'
Except for the name and version, of course. It builds fine. I had to add the jar (jersey-media-moxy-2.26.jar) to our dependency hierarchy, but no big deal.
It runs fine, until the user logs in. A number of components on the main screen are missing, and it spews errors (the application always spews errors, but they are expected). The new errors are varied, but a repeated one is:
SEVERE: StandardWrapper.Throwable
java.lang.NoClassDefFoundError: jersey/repackaged/com/google/common/base/Predicate
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
...
The stack trace never includes any of our source code as the culprit. It's all org.glassfish.jersey and org.apache.catalina.core errors (we are using Tomcat as our server). Clearly, something is wrong.
I've tried more things to resolve it than I like to recall, but some include:
Adding the jersey-media-moxy in a different location of the 40 or so dependencies we have (no difference)
Explicitly adding all the jersey-media-moxy dependencies (even though it builds fine without them; no difference)
Removing the jersey-media-multipart dependency (build fails)
Scrapping the workspace and doing a fresh "get" from source control, and re-adding the jersey-media-moxy dependency (no difference)
Bringing the jersey-media-multipart up to the latest version (doesn't build)
Removed the jersey-media-moxy dependency to see if I really need it (who knows? Maybe jersey-media-multipart already contains it) and changed the object I'm returning to a very simple class (it just contains a string). (that fails, it really does need jersey-media-moxy)
I am the only Java developer here, and this is the first time I've used gradle or Jersey. There are other ways to produce JSON, I know (such as using gson), but we really want to have Jersey do it, since we're using the framework already.
We use Eclipse (Oxygen) as our IDE and Tomcat as our server.
One big question I have is why would a new jar break an existing one?
The second question is the big one, of course: what can I do to resolve this issue?
Your 2.26 and 2.22.2 discrepancy is probably the problem. Don't mix your Jersey module versions.
why would a new jar break an existing one?
Because it isn't just a single jar that you are adding. When using a dependency management system like with Maven or Gradle, you are dealing with dependencies not just jars, and the ones that you explicitly list can have their own dependencies that implicitly get pulled in. For instance if you were to just add jersey-media-moxy, it would pull in like 10+ extra jars.
The problem with this is that if you use incompatible version, both jersey-media-moxy and jersey-media-multipart pull in some of the same jars, put you can't have more than one version of a class. So only one of the classes from those two jars will be used. And as you know, software changes with version changes. So one class might be trying to use a class that exists in one version and not in another version. This is just one of the problems you can face if you don't manage your dependencies versions correctly.
Related
Hi I'm working on an Android app and I need to use a library called Semantics3. The issue I'm having is that the Semantics3 library depends on a few different libraries one of which is org.json but Android Studio automatically includes its own unique version of org.json which causes various issues. I've tried a few things to work around this and I'll describe them below.
First, I just imported the Semantics3 library. All the code compiles but when code from the library runs to make a service call the app crashes. This is due to a "NoSuchMethod" error because Semantics3 makes use of a constructor from a class in org.json which the AS version doesn't include.
To get around this I made my own jar file of the Semantics3 code and add in the dependencies it needs on my own in Gradle. The app still crashes, though not because it can't find the constructor. In this case the error is due to an exception from org.json, specifically "org.json.JSONException: Value com.android.okhttp.internal.huc.HttpURLConnectionImpl of type java.lang.String cannot be converted to JSONObject". I couldn't figure out why this error was popping up so I decided to try out the Semantics3 library outside of Android and just made a simple Maven project. In the Maven project I can make service calls just fine with no issue, but if I add the jar file and dependencies on my own, I get the same error as in AS.
So I figure there's something missing in the source code on Github that I used to make the jar or something but that's beyond me to figure out, so I'm back at trying to just import the library. My final and current attempt involves trying to explicitly import the version of org.json that Semantics3 needs along with the Semantics3 library in Gradle. But when I bring in the Sematnics3 library I try to exclude the transitive dependency Semantics3 introduces to org.json. I've included the Gradle file for this attempt below.
// https://mvnrepository.com/artifact/com.semantics3/Sem3Java
implementation('com.semantics3:Sem3Java:1.2.4'){
exclude group:'org.json:json'
}
implementation 'org.json:json'
constraints {
implementation(group: 'org.json', name: 'json', version: '20190722') {
because 'Semantics3 requires version 20190722 of org.json, not the default AS version'
}
}
The issue is when I try to run the code with the above setup in Gradle I get an error saying there are duplicate class definitions contained in the Semantics3 library and org.json library. And yes there are certainly conflicts but I thought the exclude bit to the Semantics3 implementation would be enough to prevent that from happening. Did I make a mistake somewhere or am I misunderstanding or misusing the exclude? If it makes a difference it appears the Semantics3 library does hardcode the org.json library into its Jar file. I appreciate any help with this. Thank you.
I am building a web application and I am using Dropwizard 1.3.0, which has a dependency on jetty-io 9.4.8. This dependency has conflicts with another package (dropwizard-websocket-jee7-bundle 2.0.0), because it seem to fetch the wrong version number.
I looked into tha package, and found the method that has been renamed in 9.4.x - AbstractWebSocketConnection.java from 9.3.x - AbstractWebSocketConnection.java. The issue is that even though in Gradle the dependency tree shows I fetched 9.4.8 (the new one which I need), I still get the older, 9.3.x java file which causes the conflicts. I tried to Invalidate Caches / Restart and rebuild the whole project, but I seem to get the outdated file all the time.
What are the possible solutions for this?
If your bad class are imported by a transitive dependency, try to exclude explicit the transitive dependency.
For example if your required library is 'my.group:requiredLibrary:2.0.0' and there are another version in 'my.group:someDependency:0.1.5' you can do like this:
dependencies{
compile 'my.group:requiredLibrary:2.0.0'
compile ('my.group:someDependency:0.1.5'){
exclude group: 'my.group' module:'requiredLibrary'
}
}
Try forcing a particular version in your build.gradle
Example here: https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html
Java 8 here.
Say there is an old version of the widget libray, with Maven coordinates widgetmakers:widget:1.0.4, that has a class defined in it like so:
public class Widget {
private String meow;
// constructor, getters, setters, etc.
}
Years pass. The maintainers of this widget library decide that a Widget should never meow, rather, that it should in fact bark. And so a new release is made, with Maven coordinates widgetmakers:widget:2.0.0 and with Widget looking like:
public class Widget {
private Bark bark;
// constructor, getters, setters, etc.
}
So now I go to build my app, myapp. And, wanting to use the latest stable versions of all my dependencies, I declare my dependencies like so (inside of build.gradle):
dependencies {
compile (
,'org.slf4j:slf4j-api:1.7.20'
,'org.slf4j:slf4j-simple:1.7.20'
,'bupo:fizzbuzz:3.7.14'
,'commons-cli:commons-cli:1.2'
,'widgetmakers:widget:2.0.0'
)
}
Now let's say that this (fictional) fizzbuzz library has always depended on a 1.x version of the widget library, where Widget would meow.
So now, I'm specifying 2 versions of widget on my compile classpath:
widgetmakers:widget:1.0.4 which is pulled in by the fizzbuzz library, as a dependency of it; and
widgetmakers:widget:2.0.0 which I am referencing directly
So obviously, depending on which version of Widget gets classloaded first, we will either have a Widget#meow or a Widget#bark.
Does Gradle provide any facilities for helping me out here? Is there any way to pull in multiple versions of the same class, and configure fizzbuzz classes to use the old version of Widget, and my classes to use the new version? If not, the only solutions I can think of are:
I might be able to accomplish some kind of shading- and/or fatjar-based soltuion, where perhaps I pull in all my dependencies as packages under myapp/bin and then give them different version-prefixes. Admittedly I don't see a clear solution here, but am sure something is feasible (yet totally hacky/nasty). Or...
Carefully inspect my entire dependency graph and just make sure that all of my transitive dependencies don't conflict with each other. In this case for me, this means either submitting a pull-request to the fizzbuzz maintainers to upgrade it to the latest widget version, or, sadly, downgrading myapp to use the older widget version.
But Gradle (so far) has been magic for me. So I ask: is there any Gradle magic that can avail me here?
Don't know the specifics of Gradle, as I'm a Maven person, but this is more generic anyway. You basically have two options (and both are hacky):
ClassLoader magic. Somehow, you need to convince your build system to load two versions of the library (good luck with that), then at runtime, load the classes that use the old version with a ClassLoader that has the old version. I have done this, but it's a pain. (Tools like OSGI may take away some of this pain)
Package shading. Repackage the library A that uses the old version of library B, so that B is actually inside A, but with a B-specific package prefix. This is common practice, e.g. Spring ships its own version of asm. On the Maven side, the maven-shade-plugin does this, there probably is a Gradle equivalent. Or you can use ProGuard, the 800 pound gorilla of Jar manipulation.
Gradle will only set up the classpath with your dependencies, it doesn't provide its own runtime to encapsulate dependencies and its transitive dependencies. The version active at runtime will be the one according to the classloading rules, which I believe is the first jar in the classpath order to contain the class. OSGI provides runtime that can deal with situations like this and so will the upcoming module system.
EDIT: Bjorn is right in that it will try to resolve conflicts in different versions; it'll compile the classpath based on its strategies, so the order you put your dependencies in the file doesn't matter. However you still only get one class per classname, it won't resolve OP's issue
If you have different versions of a library with otherwise equal coordinates, Gradles conflict resolution mechanism comes into play.
The default resolution strategy is to use the newest requested version of the library. You will not get multiple versions of the same library in your dependendcy graph.
If you really need different versions of the same library at runtime you would have to either do some ClassLoader magic which definitely is possible or do some shading for one of the libraries or both.
Regarding conflict resolution, Gradle has built-in the newest strategy that is default and a fail strategy that fails if different versions are in the dependency graph and you have to explicitly resolve version conflicts in your build files.
Worse case is when the same class appears in multiple jars. This is more insidious - look at the metrics jars from Codahale and Dropwizard with incompatible versions of the same class in the two jars.
The gradle classpath-hell plugin can detect this horror.
A project runs on Google App Engine. The project has dependency that uses a class that can't be invoked on App Engine due to security constraints (it's not on the whitelist). My (very hacky) solution was to just copy a modified version of that class into my project (matching the original Class's name and package) that doesn't need the restricted class. This works on both dev and live, I assume because my source appears in the classpath before my external dependencies.
To make it a bit cleaner, I decided to put my modified version of that class into it's own project that can be packaged up in a jar and published for anyone else to use should they face this problem.
Here's my build.gradle:
// my jar that has 'fixed' version of Class.
compile files('path/to/my-hack-0.0.1.jar')
// dependency that includes class that won't run on appengine
compile 'org.elasticsearch:elasticsearch:1.4.4'
On my local dev server, this works fine, the code finds my hacked version of the class first at runtime. On live, for some unknown reason, the version in the elasticsearch dependency is loaded first.
I know having two versions of the same class in the classpath isn't ideal but I was hoping I could reliably force my version to be at the start of the classpath. Any ideas? Alternatively, is there a better way to solve this problem?
Not really sure if this is what people visiting this question were looking for, but this was what my problem and a solution that I reached at.
Jar A: contains class XYZ
Jar B: also contains class XYZ
My Project needs Jar B on the classpath before Jar A to be able to get compiled.
Problem is Gradle sorts the dependencies based on alphabetical order post resolving them which meant Jar B will be coming after Jar A in the generated classpath leading to error while compiling.
Solution:
Declare a custom configuration and patch the compileClasspath. This is how the relevant portion of build.gradle might look like.
configurations {
priority
sourceSets.main.compileClasspath = configurations.priority + sourceSets.main.compileClasspath
}
dependencies {
priority 'org.blah:JarB:2.3'
compile 'org.blah:JarA:2.4'
...
}
It's the app engine classloader I should have been investigating, not gradle...
App Engine allows you to customise the class loader JAR ordering with a little bit of xml in your appengine-web.xml. In my case:
<class-loader-config>
<priority-specifier filename="my-hack-0.0.1.jar"/>
</class-loader-config>
This places my-hack-0.0.1.jar as the first JAR file to be searched for classes, barring those in the directory war/WEB-INF/classes/.
...Thanks to a nudge in the right direction from #Danilo Tommasina :)
UPDATE 2020:
I just hit the same problem again and came across my own question... This time, live appengine was loading a different version of org.json than was being loaded in dev. Very frustrating and no amount of fiddling the build script would fix it. For future searchers, if you're getting this:
java.lang.NoSuchMethodError: org.json.JSONObject.keySet()Ljava/util/Set;
It's because it's loading an old org.json dependency from god-knows-where. I fixed it by adding this to my appengine-web.xml:
<class-loader-config>
<priority-specifier filename="json-20180130.jar"/>
</class-loader-config>
You'll also need a matching dependency in build.gradle if you don't already have one:
compile 'org.json:json:20180130'
According to gradle dependencies documentation, the order of dependencies defines the order in the classpath. So, we can simply put the libraries in the correct order in "dependencies".
But beware! here are two rules with higher priorities:
For a dynamic version, a 'higher' static version is preferred over a 'lower' version.
Modules declared by a module descriptor file (Ivy or POM file) are preferred over modules that have an artifact file only.
I'm currently getting this error:
java.lang.NoSuchMethodError: org.json.JSONObject.keySet()Ljava/util/Set;
at ee.ut.cs.Parser.accessLint(Parser.java:39)
I have tried cleaning the project to no awail.
I suspect I have an error in the src/plugin/parse-htmlraw/build.xml while creating the jar file but I'm not certain. I understand that this error is because the function does not exist at runtime, but the object is created which means that the class is there, just not that function. I decompiled the .class file in created jar and it has the necessary functions.
Code is available at https://github.com/jaansusi/WCAGgrader
Q: What is wrong with the build that produces this error?
The problem is that even if I put the necessary class files in the jar I create, they are not linked correctly and the class that's called in the jar can't locate functions inside the other classes. The class object JSONObject is created but the functions inside the JSONObject class can't be found.
If you do not find the problematic version, there is a possibility you get it (especially if you are using Spring) from the following dependency -
<artifactId>android-json</artifactId>
<groupId>com.vaadin.external.google</groupId>
excluding it worked for me,
An easy way of analyzing dependencies is the maven-helper plugin in Intellij, see here
Check for the version you have used.
There might be a case where 2 different versions are being used which in turn causes this error.
To their own maven local repository com\Google\code\gson\gson, see if there are two or more version about json, will have to do is to delete the old, and remember to look at any other place in the project is introduced into the old version of the dependence, if any, change the old version of the dependence to the new version is perfectly solved this problem