Exception running TrueZip - java

I run a simple TrueZip code:
TFile src = new TFile(path + file_to_add);
TFile dst = new TFile(path + outZipFile);
src.cp_rp(dst);
When i run the program the compiler throws (on the first line):
java.lang.NoClassDefFoundError: de/schlichtherle/truezip/fs/FsSyncOption
I have truezip-file-7.4.3.jar and truezip-file-7.4.3-sources.jar files.
Am i missing jars or the problem may be something else?

add truezip-driver-file.jar & truezip-kernel.jar according to Maven POM.

Related

Maven: Access POM at runtime - How to get 'pom.xml' available from anywhere?

I want to access some information from the pom.xml to display in a Info dialog. So I googled and found this post:
public class MavenModelExample {
public static void main(String[] args) throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(new FileReader("pom.xml"));
System.out.println(model.getId());
System.out.println(model.getGroupId());
System.out.println(model.getArtifactId());
System.out.println(model.getVersion());
}
}
I implemented it in my tool, added
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>3.3.9</version>
</dependency>
to my pom and was happy that everything ran as expected when I run the tool from the project root directory with java -jar target\mytool.jar.
When I move to any other directory, e.g. directly into target and execute my tool with java -jar mytool.jar, I get:
java.io.FileNotFoundException: pom.xml (The system cannot find the specified file)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
Which is kind of comprehensible. How should the code know, where the pom.xml is located, as it is not a resource. Is there any way to work around that?
In the mean time I use the approach from this thread to obtain the version and artifactID.
The problem is that
Model model = reader.read(new FileReader("pom.xml"));
tries to read the POM from the directory where your program is executed. Normally, pom.xml won't get copied to target, but it is embedded in the resulting artifact. You can override and force Maven to copy the POM to the target directory if you want to (for your own project), but it won't help you for other Maven artifacts.
Most of the time, a Maven artifact will have the POM coordinates included in the JAR/WAR/EAR output. If you unpack such a file, you'll notice that there are two files stored under META-INF/maven/<groupId>/<artifactId>: pom.xml and pom.properties where the latter is far easier to parse than pom.xml but it doesn't include the dependencies.
Parsing the embedded pom.xml from the classpath (and not from disk) should work better for you, especially if you always run your program with java -jar target\mytool.jar. In your program, try this:
try (InputStream is = MavenModelExample.class.getClassLoader().getResourceAsStream("META-INF/maven/<your groupId>/<your artifactId>/pom.xml")) {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(is);
System.out.println(model.getId());
System.out.println(model.getGroupId());
System.out.println(model.getArtifactId());
System.out.println(model.getVersion());
// If you want to get fancy:
model.getDependencies().stream().forEach(System.out::println);
}
catch (IOException e) {
// Do whatever you need to do if the operation fails.
}
<your groupId> and <your artifactId> should be fairly static, but if you do relocate your artifact's coordinates, then you need to change this in your code as well.
problem is that :
read(new FileReader("pom.xml"))
works fine when you start your application from STS or else, but when you build your application as JAR the path of the pom.xml file change to :
META- INF/maven/${groupId}/${artifactId}/pom.xml.
for that, try this code :
MavenXpp3Reader mavenXpp3Reader = new MavenXpp3Reader();
Model model;
if ((new File("pom.xml")).exists()) {
model = mavenXpp3Reader.read(new FileReader("pom.xml"));
}
else {
// Packaged artifacts contain a META- INF/maven/${groupId}/${artifactId}/pom.properties
model = mavenXpp3Reader.read(new
InputStreamReader(Application.class.getResourceAsStream(
"/META-INF/maven/groupId/artifactId/pom.xml")));
}

How can I create executable jars with embedded tomcat 9?

Has anyone tried the plugin to build an executable war/jar using Tomcat 9?
I attempted to do so however ran into:
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.catalina.startup.Catalina.setConfig(Ljava/lang/String;)V
at org.apache.tomcat.maven.runner.Tomcat7Runner.run(Tomcat7Runner.java:240)
at org.apache.tomcat.maven.runner.Tomcat7RunnerCli.main(Tomcat7RunnerCli.java:204)
I looked at the source and changed Catalina.setConfig() to Catalina.setConfigFile() based on docs here. After doing so the .extract dir is just empty:
use extractDirectory:.extract populateWebAppWarPerContext
warValue:ROOT.war|ROOT populateWebAppWarPerContext
contextValue/warFileName:ROOT/ROOT.war webappWarPerContext entry
key/value: ROOT/ROOT.war expand to file:.extract/webapps/ROOT.war
Exception in thread "main" java.lang.Exception: FATAL: impossible to
create directories:.extract/webapps at
org.apache.tomcat.maven.runner.Tomcat7Runner.extract(Tomcat7Runner.java:586)
at
org.apache.tomcat.maven.runner.Tomcat7Runner.run(Tomcat7Runner.java:204)
at
org.apache.tomcat.maven.runner.Tomcat7RunnerCli.main(Tomcat7RunnerCli.java:204)
.... although there is a ROOT.war, server.xml, web.xml in the *-exec-war.jar.
Is there a better way to be creating exec-jars with embedded tomcat 9?
For those looking for a solution it was fairly straight forward to checkout the code for the plugin and make a few changes to get this to work. Namely:
Update POM to change the depends to Tomcat 9
Fix compile errors which generally stem from deprecated methods. The lookup on these methods can be found here. For example:
- container.setConfig( serverXml.getAbsolutePath() );
+ container.setConfigFile( serverXml.getAbsolutePath() );
... and ...
- staticContext.addServletMapping( "/", "staticContent" );
+ staticContext.addServletMappingDecoded( "/", "staticContent" );
There are a few others but generally not difficult to resolve. After doing so I updated my app's pom to use the modified version and was able to generate a Tomcat 9 exec jar.
I would love to hear what others are doing here. I know some are programmatically initializing Tomcat via a new Tomcat() instance however curious what other solutions exist ready made. Thanks
For future searchs, one solution is to use the DirResourceSet or JarResourceSet.
String webAppMount = "/WEB-INF/classes";
WebResourceSet webResourceSet;
if (!isJar()) {
webResourceSet = new DirResourceSet(webResourceRoot, webAppMount, getResourceFromFs(), "/");
} else {
webResourceSet = new JarResourceSet(webResourceRoot, webAppMount, getResourceFromJarFile(), "/");
}
webResourceRoot.addJarResources(webResourceSet);
context.setResources(webResourceRoot);
public static boolean isJar() {
URL resource = Main.class.getResource("/");
return resource == null;
}
public static String getResourceFromJarFile() {
File jarFile = new File(System.getProperty("java.class.path"));
return jarFile.getAbsolutePath();
}
public static String getResourceFromFs() {
URL resource = Main.class.getResource("/");
return resource.getFile();
}
When add the webapp, use root path "/" for docBase:
tomcat.addWebapp("", "/")
Credits for:
https://nkonev.name/post/101

java.lang.NoClassDefFoundError: org/apache/commons/lang/text/StrLookup

The error is pointing to EventUnitTesting.readPropertyFile(EventUnitTesting.java:168) in which the body of readPropertyFile() is
private void readPropertyFile() throws IOException, ConfigurationException{
file = new File(fileLocation + unitTestingFileName);
propertiesConfiguration = new PropertiesConfiguration(file);
List<Object> propertyKeysList = propertiesConfiguration.getList("regular");
Iterator<Object> propertyKeysIterator = propertyKeysList.iterator();
regularEvents = new ArrayList<String>();
while(propertyKeysIterator.hasNext()){
regularEvents.add((String)propertyKeysIterator.next());
}
propertyKeysList = propertiesConfiguration.getList("consolidated");
propertyKeysIterator = propertyKeysList.iterator();
consolidatedEvents = new ArrayList<String>();
while(propertyKeysIterator.hasNext()){
consolidatedEvents.add((String)propertyKeysIterator.next());
}
propertyKeysList = propertiesConfiguration.getList("correlated");
propertyKeysIterator = propertyKeysList.iterator();
correlatedEvents = new ArrayList<String>();
while(propertyKeysIterator.hasNext()){
correlatedEvents.add((String)propertyKeysIterator.next());
}
}
whereby I am using the Apache Commons Configuration library version 1.10 to read a properties file that has non-unique keys. I don't receive this error using a JBoss 6.4.8 purpose-built WAR but this error is generating on a JBoss converted 5.2 WAR.
I am using the Apache Commons Lang 2.1 so I'm not sure how org/apache/commons/lang/text/StrLookup can be a problem. All relevant *.java and *.class files have been copied into the converted jar file and everything is fine except this issue.
Note that NoClassDefFoundError is different than ClassNotFoundException. The former can mean that the class was found, but during the a static initializer an exception was thrown.
Wrap this method code in a try catch and output the exception. Likely you will see why.
Looks like some dependent jar was present at compile time but missing at runtime. Can you compare classpaths for build time and runtime. It will give you the difference which jar is missing and causing this issue.

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.

SCons not picking up all class files when creating a jar

SCons neophyte here. I am using it(version 2.0) to create a jar as follows:
compiled_classes = env.Java \
(target = compiled_classes_dir,
source = source_tld,
JAVAVERSION='1.6',
JAVACLASSPATH=['source_tld/libs/' +
file.name
for file in
Glob('source_tld/' +
'libs/*.jar')])
new_jar = env.Jar(target = jar_name,
source = compiled_classes_dir)
I am seeing an issue wherein class files belonging to classes that have inner classes(which when compiled into class files have a $ in the name) are not being handled properly i.e. they do not get included in the generated JAR. Any suggestions to address this would be greatly appreciated. TIA.
PS: This suggestion to add JAVAVERSION didn't seem to help.
Since SCons is incorrectly calculating the output classes I would suggest this workaround.
compiled_classes = env.Java \
(target = compiled_classes_dir,
source = source_tld,
JAVAVERSION='1.6',
JAVACLASSPATH=['source_tld/libs/' +
file.name
for file in
Glob('source_tld/' +
'libs/*.jar')])
#workaround to make sure classes are cleaned
env.Clean(compiled_classes, env.Dir(compiled_classes_dir))
# its important to set the JARCHDIR or the Jar command will not be run
# from the correct location if you want an executable Jar add the manifest here
new_jar = env.Jar(target = jar_name,
source = [compiled_classes_dir], JARCHDIR='$SOURCE')

Categories