I get a
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/codec/binary/Hex
when i execute my code.
I have looked through a number of examples on this exception on stack overflow but nothing seems to help. My pom.xml looks like this
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Code to reproduce it looks like this
package com.mypackage;
import java.util.*;
import java.io.*;
import java.security.*;
import org.apache.commons.codec.binary.Hex;
public class Test{
private byte[] m_key;
private static String resourceFolder = System.getenv("SEABED_HOME").toString() + "/testing" + "/resources";
public static void main(String[] args)
{
Test t = new Test();
t.readKey();
}
public byte[] generateKey()
{
SecureRandom scr = new SecureRandom();
byte[] key = new byte[32];
scr.nextBytes(key);
return key;
}
private void readKey()
{
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(resourceFolder + "/.seabedkey"));
m_key = Hex.decodeHex(br.readLine().toCharArray());
}
catch(Exception e)
{
if(e instanceof FileNotFoundException)
{
System.out.println("Key not found, generating now");
writeKey(generateKey());
readKey();
return;
}
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
private void writeKey(byte[] key)
{
try{
FileOutputStream fos = new FileOutputStream(resourceFolder + "/.seabedkey");
fos.write(key);
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I execute it like this
java -cp target/mypackage-1.0-SNAPSHOT.jar:~/.m2/repository/commons-codec/commons-codec/1.10/commons-codec-1.10.jar com.mypackage.Test
It compiles but then at runtime it looks like the class cannot be found. I tried changing the scope of the dependency to provided
but apparently that is not the right way to use it so I switched back to the default which is compile
. I can find the jar in my .m2 folder so I am sure it is there.