Intelij scala project does not support swing - java

I am unable to use swing library with my scala-sdk-2.12.4.
I am using Java 9 version.
When I try to run the program:
package rs.ac.bg.etf.zd173013m.gui
import swing._
object HelloWorld extends SimpleSwingApplication {
def top = new MainFrame {
title = "First Swing App"
contents = new Button {
text = "Click me"
}
}
}
I get the following error:
Exception in thread "main" java.lang.IncompatibleClassChangeError: Method scala.swing.Reactor.$init$()V must be InterfaceMethodref constant
at scala.swing.SwingApplication.<init>(SwingApplication.scala:4)
at scala.swing.SimpleSwingApplication.<init>(SimpleSwingApplication.scala:13)
at rs.ac.bg.etf.zd173013m.gui.HelloWorld$.<init>(Application.scala:5)
at rs.ac.bg.etf.zd173013m.gui.HelloWorld$.<clinit>(Application.scala)
at rs.ac.bg.etf.zd173013m.gui.HelloWorld.main(Application.scala)

You have incompatible JAR versions on your classpath. The code in the JAR containing "SwingApplication" was compiled against a different version of "Reactor" than the one on your classpath.
What are you using to manage your dependencies? I guess that you are downloading them manually.
Switch to a dependency management system like Gradle and this problem should go away, as it will ensure that all your dependencies are consistent.

Related

Java Library Commons Lang3 'ClassNotFoundException' error

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
public class MonsterGame {
public static void main(String[] args)
{
Monster.buildBattleBoard();
char[][] tempBattleBoard = new char[10][10];
// ObjectName[] ArrayName = new ObjectName[4];
Monster[] Monsters = new Monster[4];
// Monster(int health, int attack, int movement, String name)
Monsters[0] = new Monster(1000, 20, 1, "Frank");
Monsters[1] = new Monster(500, 40, 2, "Drac");
Monsters[2] = new Monster(1000, 20, 1, "Paul");
Monsters[3] = new Monster(1000, 20, 1, "George");
Monster.redrawBoard();
for (Monster m : Monsters) {
if(m.getAlive()) {
int arrayItemIndex = ArrayUtils.indexOf(Monsters, m);
m.moveMonster(Monsters, arrayItemIndex);
}
}
Monster.redrawBoard();
}
}
When trying to run this code, I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/ArrayUtils
at MonsterGame.main(MonsterGame.java:55)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang3.ArrayUtils
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 1 more
I have two files, in the same package. I've only shown this one because I do not believe the other file is the problem.
I followed a tutorial on how to use java libraries: download, import, build path etc.
The problem here is, the import seems to be fine but actually using the library is the problem.
I'm very new to Java so sorry if this is a very simple error to fix.
Thank you for any response/feedback in advance.
The referenced library you are using (apache common lang3) and any other library for that matter is used in three different ways.
First, you need the library during development, so your IDE can
validate your code, when you call classes, objects and methods from
the library.
During compilation you need the library, so the java
compiler can reference the right paths, and optimize your code,
where possible.
You need the library during runtime, when your program is run by the Java Virtual Machine, so it can find whatever you used from the library.
The first 2 are usually seen as one, because both is usually considered 'compile time', though strictly speaking only the second one actually is. This means that you need to have the library in place for the IDE (for points 1 and 2) and for the program (point 3). Your exception is thrown, because during runtime, your library is not found by the ClassLoader. The ClassLoader is the way the JVM loads classes for the programs it uses. If the JVM does not find a class, it cannot continue to execute the Thread you are running, and you are probably only running one Thread (a main thread).
Therefore your program breaks, and stops running. Please either recheck the tutorial you are using on how to correctly import libraries or export the library to the lib folder next to the jar you are exporting.
Edit: When using an up to date version of eclipse, and exporting a project as runnable jar, you are asked what way you want to handle libraries:
If you do not see this subsection of the export dialog, you are doing something wrong (probably you are not exporting as runnable jar).

Missing resolveStrategy breaks DSL when executed from runnable jar

I'm using the Groovy Spreadsheet Builder within one of my Grails projects to export some data as Excel file.
Everything works great until I create a runnable jar (using gradle assemble) and use this.
I'm using the builder within a service like this:
class ExcelService {
...
void export(OutputStream outputStream) {
...
PoiSpreadsheetBuilder.create(outputStream).build {
apply ExcelStylesheet
...
}
}
...
}
When I try to export my data from the app started using the generated jar I will get the following MissingMethodException:
groovy.lang.MissingMethodException: No signature of method: my.package.ExcelService.apply() is applicable for argument types: (java.lang.Class)
The (Java) interface of SpreadsheetBuilder looks like this:
public interface SpreadsheetBuilder {
void build(#DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = WorkbookDefinition.class) #ClosureParams(value = FromString.class, options = "builders.dsl.spreadsheet.builder.api.WorkbookDefinition") Configurer<WorkbookDefinition> workbookDefinition);
}
While debugging the execution of the code and the jar I found the difference while stepping through invokeMethod() of ClosureMetaClass.
When closure.getResolveStrategy(); in the working version is called Closure.DELEGATE_FIRST will be returned. Debugging the jar, the result will be 0 so that the MissingMethodException will be thrown later due to the wrong resolve strategy.
For now I have no idea how to solve this problem.
What is/could be the reason for this behavior?
What can I do to solve this issue?
I'm using Grails 3.3.8 with Java OpenJDK 1.8.0_192.
If you don't need to support JDK 7, you could upgrade to Groovy Spreadsheet Builder 2.0.0.RC1 which is only JDK 8 compatible but appears to solve the problem.
#ClosureParams and #DelegatesTo are applicable to parameters of type groovy.lang.Closure. In this case, you have applied it to Configurer<WorkbookDefinition>.

Running XSLT to RDF framework fails because of Saxon

I´m using Krextor to convert XML to RDF. It runs fine from the command line.
I try to run it from Java (Eclipse) using this code.
private static void XMLToRDF() throws KrextorException, ValidityException, ParsingException, IOException, XSLException{
Element root = new Element("person");
Attribute friend = new Attribute("friends", "http://van-houten.name/milhouse");
root.addAttribute(friend);
Element name = new Element("name");
name.appendChild("Bart Simpson");
root.appendChild(name);
nu.xom.Document inputDocument = new nu.xom.Document(root);
System.out.println(inputDocument.toXML());
Element root1 = inputDocument.getRootElement();
System.out.println(root1);
Krextor k = new Krextor();
nu.xom.Document outputDocument = k.extract("socialnetwork","turtle",inputDocument);
System.out.println(outputDocument.toString());
}
I have the following problem problem
Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/saxon/CollectionURIResolver
Caused by: java.lang.ClassNotFoundException: net.sf.saxon.CollectionURIResolver
I have included Saxon9he in the classpath, and I have also added manually as a library in the project but the error is the same.
I am the main developer of Krextor. And, #Michael Kay, actually a colleague of Grangel, so I will resolve the concrete problem with him locally.
So indeed the last Saxon version with which I did serious testing was 9.1; after that I haven't used Krextor integrated into Java but mainly used Krextor from the command line.
#Grangel, could you please file an issue for Krextor, and then we can work on fixing it together.
Indeed, #Michael Kay, for a while I had been including more recent Saxon versions with Krextor and updated the command line wrapper to use them (such as to add different JARs to the classpath), but I have not necessarily updated the Java wrapper code.

Building a ServiceLoader file with gradle: howto?

I am starting to switch from a well-known Java build system to Gradle to build all my projects, and after barely two hours into it I have already been able to publish a new version of one of my projects without a problem -- a breeze.
But now I encounter a difficulty. In short, I need to replicate the functionality of this Maven plugin which generates the necessary files for a ServiceLoader-enabled service.
In short: given a base class foo.bar.MyClass, it generates a file named META-INF/services/foo.bar.MyClass whose content is a set of classes in the current project which implement that interface/extend that base class. Such a file would look like:
com.mycompany.MyClassImpl
org.othercompany.MyClassImpl
In order to do this, it uses I don't know what as a classloader, loads the Class objects for com.myCompany.MyClassImpl or whatever and checks whether this class implements the wanted interface.
I am trying to do the same in Gradle. Hours of googling led me to this plugin, but after discussing with its author a little, it appears this plugin is able to merge such files, not create them. So, I have to do that myself...
And I am a real beginner both with Gradle and Groovy, which does not help! Here is my current code, link to the full build.gradle here; output (which I managed to get somehow; doesn't work from a clean dir) shown below (and please bear with me... I do Java, and I am final happy; Groovy is totally new to me):
/*
* TEST CODE
*/
final int CLASS_SUFFIX = ".class".length();
final URLClassLoader classLoader = this.class.classLoader;
// Where the classes are: OK
final File classesDir = sourceSets.main.output.classesDir;
final String basePath = classesDir.getCanonicalPath();
// Add them to the classloader: OK
classLoader.addURL(classesDir.toURI().toURL())
// Recurse over each file
classesDir.eachFileRecurse {
// You "return" from a closure, you do not "continue"...
if (!isPotentialClass(it))
return;
// Transform into a class name
final String path = it.getAbsolutePath();
final String name = path.substring(basePath.length() + 1);
final String className = name.substring(0, name.length() - CLASS_SUFFIX)
.replace('/', '.');
// Try and load it
try {
classLoader.loadClass(className);
println(className);
} catch (NoClassDefFoundError ignored) {
println("failed to load " + className + ": " + ignored);
}
}
boolean isPotentialClass(final File file)
{
return file.isFile() && file.name.endsWith(".class")
}
The output:
com.github.fge.msgsimple.InternalBundle
failed to load com.github.fge.msgsimple.bundle.MessageBundle: java.lang.NoClassDefFoundError: com/github/fge/Frozen
failed to load com.github.fge.msgsimple.bundle.MessageBundleBuilder: java.lang.NoClassDefFoundError: com/github/fge/Thawed
com.github.fge.msgsimple.bundle.PropertiesBundle$1
com.github.fge.msgsimple.bundle.PropertiesBundle
com.github.fge.msgsimple.provider.MessageSourceProvider
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider$1
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider$2
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider$3
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider$Builder
com.github.fge.msgsimple.provider.LoadingMessageSourceProvider
com.github.fge.msgsimple.provider.MessageSourceLoader
com.github.fge.msgsimple.provider.StaticMessageSourceProvider$Builder
com.github.fge.msgsimple.provider.StaticMessageSourceProvider$1
com.github.fge.msgsimple.provider.StaticMessageSourceProvider
com.github.fge.msgsimple.source.MessageSource
com.github.fge.msgsimple.source.MapMessageSource$Builder
com.github.fge.msgsimple.source.MapMessageSource$1
com.github.fge.msgsimple.source.MapMessageSource
com.github.fge.msgsimple.source.PropertiesMessageSource
com.github.fge.msgsimple.locale.LocaleUtils
com.github.fge.msgsimple.serviceloader.MessageBundleFactory
com.github.fge.msgsimple.serviceloader.MessageBundleProvider
:compileJava UP-TO-DATE
The problem is in the two first lines: Frozen and Thawed are in a different project, which is in the compile classpath but not in the classpath I managed to grab so far... As such, these classes cannot even load.
How do I modify that code so as to have the full compile classpath availabe? Is my first question. Second question: how do I plug that code, when it works, into the build process?
Here are some hints:
Create a new URLClassLoader, rather than reusing an existing one.
Initialize the class loader with sourceSets.main.compileClasspath (which is an Iterable<File>) rather than classesDir.
Turn the code into a Gradle task class. For more information, see "Writing a simple task class" in the Gradle User Guide.
Ideally, you'd use a library like ASM to analyze the code, rather than using a class loader. To avoid the case where you cannot load a class because it internally references a class that's not on the compile class path, you may want to initialize the class loader with sourceSets.main.runtimeClasspath instead.

Runtime error using the Eclipse Abstract Syntax Tree

I'm trying to use AST parser in a non-plugin environment. The code compiles, but I get the following runtime error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/resources/IResource
at org.eclipse.jdt.core.dom.ASTParser.(ASTParser.java:189)
at org.eclipse.jdt.core.dom.ASTParser.newParser(ASTParser.java: 118)
Here is the code I'm running:
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.dom.*;
public class TestAST
{
private void runTest()
{
String helloStr ="\n"+
"public class HelloWorld {\n"+
"\n"+
" private String name=\"\"\n\n"+
" /**\n"+
" * \n"+
" */\n"+
" public void sayHello() {\n"+
" System.out.println(\"Hello \"+name+\"!\");\n"+
" }\n"+
"\n"+
"}";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(helloStr.toCharArray());
parser.setResolveBindings(true);
ASTNode tree = parser.createAST(null);
tree.toString();
}
public static void main(String args[])
{
TestAST ast = new TestAST();
ast.runTest();
}
}
Does anyone know why this is happening?
Thanks in advance,
Shirley
I recently ran into a similar issue and I slowly stepped through fixing one dependency at a time and here is the list of required dependencies that I came up with. I hope this saves some time for people who try to do this same task:
List (which matches picture below):
ContentType (org.eclipse.core.contenttype)
Jobs (org.eclipse.core.jobs)
Resources (org.eclipse.core.resources)
Runtime (org.eclipse.core.runtime)
Equinox Common (org.eclipse.equinox.common)
Equinox Preferences (org.eclipse.equinox.preferences)
JDT (org.eclipse.jdt)
JDT Core (org.eclipse.jdt.core)
OSGI (org.eclipse.osgi)
OSGI Services (org.eclipse.osgi.services)
OSGI Util (org.eclipse.osgi.util)
All these JARs will likely already be contained in your Eclipse plugins directory and you can find and add them to the build path by adding them as external JARs.
The IResource class is not on your classpath when you start the application.
If you're not using Eclipse (or some other tool) to manage the dependencies, you're going to have to track down every jar file that the Abstract Syntax Tree classes require and manually include them on your classpath. I'm not sure exactly how many this might be, but Eclipse is made up of many dozens of plugins, and manually working out the build dependencies will be a chore.
Edit: To add IResorce to the classpath, the particular jar file you're looking for will be called something like org.eclipse.core.resources_3.5.0.v20090512.jar, depending on your version of Eclipse. But I don't think it will be the only one you'll need...
I had the same problem. I solved adding the jars into the required dependencies of the the plugin.xml. You can find it in the tab Dependencies of the plugin.xml file.

Categories