181

I am getting the below exception when I run my mvn install. I have even deleted the local repository and ran again getting same exception.

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on project cores-batch: Error creating shaded jar: invalid LOC header (bad signature) -> [Help 1]

<?xml version="1.0" encoding="UTF-8"?>
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-shade-plugin</artifactId>
   <version>2.1</version>
   <configuration>
      <skipTests>true</skipTests>
   </configuration>
   <executions>
      <execution>
         <phase>package</phase>
         <goals>
            <goal>shade</goal>
         </goals>
         <configuration>
            <artifactSet>
               <excludes>
                  <exclude>commons-logging:commons-logging:jar:*</exclude>
               </excludes>
            </artifactSet>
            <filters>
               <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                     <!-- workaround for a spring issues -->
                     <exclude>META-INF/*.SF</exclude>
                     <exclude>META-INF/*.DSA</exclude>
                     <exclude>META-INF/*.RSA</exclude>
                     <!-- don't want to pick up any other log4j.xml -->
                     <exclude>log4j.xml</exclude>
                  </excludes>
               </filter>
            </filters>
            <!-- May be needed to work around another issue in Spring -->
            <transformers>
               <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.handlers</resource>
               </transformer>
               <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.schemas</resource>
               </transformer>
            </transformers>
         </configuration>
      </execution>
   </executions>
</plugin>

Error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on project cores-batch: Error creating shaded jar: invalid LOC header (bad signature) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.1:shade (default) on project cores-batch: Error creating shaded jar: invalid LOC header (bad signature)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error creating shaded jar: invalid LOC header (bad signature)
    at org.apache.maven.plugins.shade.mojo.ShadeMojo.execute(ShadeMojo.java:528)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(ZipFile.java:56)
    at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:679)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:415)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)
    at org.codehaus.plexus.util.IOUtil.copy(IOUtil.java:189)
    at org.codehaus.plexus.util.IOUtil.copy(IOUtil.java:175)
    at org.apache.maven.plugins.shade.DefaultShader.addResource(DefaultShader.java:427)
    at org.apache.maven.plugins.shade.DefaultShader.shade(DefaultShader.java:186)
    at org.apache.maven.plugins.shade.mojo.ShadeMojo.execute(ShadeMojo.java:458)
    ... 21 more
[ERROR] 
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
3
  • 1
    Made a plugin for this problem -> github.com/goxr3plus/CorruptedJarsDetector
    – GOXR3PLUS
    Commented Oct 11, 2018 at 8:27
  • 1
    @GOXR3PLUS There is not really code in that repo (except for the class in the README), even less that of a Maven plugin. I think that a maven plugin would be the best solution, actually - or just an extension of one of the existing plugins that allowed to do something like a mvn dependencies validate or so...
    – Marco13
    Commented Oct 13, 2018 at 15:48
  • Marco the code for the repository is the one in class lol :)
    – GOXR3PLUS
    Commented Oct 13, 2018 at 16:25

15 Answers 15

238

The jar file may be corrupt. Try removing the content of the following folder:

 C:\Users\[username]\.m2\repository

Then right click your project, select Maven, Update Project, check on Force Update of Snapshots/Releases.

6
  • The solution would be to fix maven so that it reloads the file from the repo at least once. Looking at the stacktrace, it's probaby too late at that time, but perhaps maven could optionally validate the archives when resolving the dependencies. As this happens quite often - maybe I'm on a bad net or something, it would help. This could also possibly fix the case when one jar is not downloaded at all, but the pom is, and maven does not notice...
    – KarlP
    Commented Feb 6, 2017 at 12:20
  • 1
    very nice.. after spending 7 hours I found out the solution... KUDOS for you man.... Commented Aug 7, 2017 at 15:59
  • 8
    This works but deleting entire maven local repository is not the best option. Just delete the related jar files and that's enough. Commented Oct 7, 2017 at 18:36
  • 3
    Don't have to delete all the dependencies, on the top you can find which dependencies is has bad LOC Header.
    – umar faraz
    Commented Apr 6, 2018 at 14:41
  • 3
    Just to note the obvious: When somebody encounters invalid LOC header in Gradle build, you just delete ~/.gradle/caches folder (Linux).
    – MartyIX
    Commented Aug 24, 2018 at 16:23
116

The mainly problem are corrupted jars.

To find the corrupted one, you need to add a Java Exception Breakpoint in the Breakpoints View of Eclipse, or your preferred IDE, select the java.util.zip.ZipException class, and restart Tomcat instance.

When the JVM suspends at ZipException breakpoint you must go to JarFile.getManifestFromReference() in the stack trace, and check attribute name to see the filename.

After that, you should delete the file from file system and then right click your project, select Maven, Update Project, check on Force Update of Snapshots/Releases.

12
  • 15
    I believe this should be the accepted answer. Simply removing hundreds of jar files and re-downloading them is not an efficient solution.
    – Mohsen
    Commented Feb 24, 2017 at 17:30
  • 11
    rm -rf .m2 = effective
    – Jeryl Cook
    Commented Mar 6, 2017 at 3:24
  • 2
    Awesome debugging technique there. Saved me from wasting bandwidth to download the whole dependencies or artifacts. Thank you. Commented Mar 9, 2017 at 7:55
  • 3
    Great technique !. I Couldn't find JarFile frame, but here found it as the expression ZipFile.this.name on ZipFile$ZipFileInputStream.read frame.
    – rlpatrao
    Commented Jul 27, 2017 at 2:49
  • 2
    A simple example of this corrupted jars: stackoverflow.com/a/46623719/3128926 Took 2 hours to understand what is the problem. Btw, removing only related jar files are enough instead of clearing the whole maven local cache. Commented Oct 7, 2017 at 18:36
85

You need to check which jar is giving problem. It must be corrupted. Delete that jar and run mvn spring-boot:run command again. May be more that one jar has corrupted so every time you need to run that command to delete that jar. In my case mysql, jackson, aspect jars was corrupted mvn spring-boot:run command 3 times and I figure out this and deleted the jars from .m2 folder. Now the issue has resolved.

44

From gsitgithub/find-currupt-jars.txt, the following command lists all the corrupted jar files in the repository:

find  /home/me/.m2/repository/ -name "*jar" | xargs -L 1 zip -T | grep error | grep invalid

You can delete the corrupted jar files, and recompile the project.

Example output:

warning [/cygdrive/J/repo/net/java/dev/jna/jna/4.1.0/jna-4.1.0.jar]:  98304 extra bytes at beginning or within zipfile
  (attempting to process anyway)
file #1:  bad zipfile offset (local header sig):  98304
  (attempting to re-compensate)
zip error: Zip file invalid, could not spawn unzip, or wrong unzip (original files unmodified)
5
  • 1
    sudo find ./repository/ -name "*jar" | sudo xargs -L 1 zip -T | grep error | grep invalid gives me xargs: zip: No such file or directory. this is using bash on ubuntu on windows, fyi
    – liltitus27
    Commented Jul 5, 2017 at 14:37
  • 1
    @liltitus27 This command line executes zip -T (test) on each jar under repository, then filtering which jars are invalid compressed files. Do you have zip command available?
    – Javier
    Commented Jul 5, 2017 at 14:44
  • it seems that in bash, i do not have zip installed. i did find that the exact command you posted works beautifully in cygwin, however. and also, it worked in finding bad jars, thanks!
    – liltitus27
    Commented Jul 6, 2017 at 15:33
  • The idea is to run zip -T on each jar stored under .m2/repository. In Windows, you can run it on Cygwin (/cygdrive/C/Users/torno/.m2/repository) as I did, and I think you can also run it with Bash on Windows 10 (/mnt/c/Users/torno/.m2/repository). I didn't investigate how to write an equivalent script with PowerShell, and I think it should no be possible with a cmd prompt.
    – Javier
    Commented Apr 24, 2018 at 10:17
  • 2
    Absolutely great answer, removing thousands of libraries inside .m2 is a lot to lose. Thanks Commented Apr 29, 2018 at 19:28
13

I'd like to give my practice.

Use your preferred IDE, take eclipse for for example here:

  1. Find an appropriate location within the exception stack
  2. Set conditional breakpoint
  3. Debug it
  4. It will print the corrupted jar before exception

enter image description here

2
  • 1
    This is a far better solution that clearing the entire m2 repository, which in my case would take ages to download again. Commented May 21, 2018 at 11:51
  • Simple and ease..
    – Ajay Takur
    Commented Mar 23, 2023 at 19:17
6

The solution for me was to run mvn with -X:

$ mvn package -X

Then look backwards through the output until you see the failure and then keep going until you see the last jar file that mvn tried to process:

...
... <<output ommitted>>
...
[DEBUG] Processing JAR /Users/snowch/.m2/repository/org/eclipse/jetty/jetty-server/9.2.15.v20160210/jetty-server-9.2.15.v20160210.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.607 s
[INFO] Finished at: 2017-10-04T14:30:13+01:00
[INFO] Final Memory: 23M/370M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.1.0:shade (default) on project kafka-connect-on-cloud-foundry: Error creating shaded jar: invalid LOC header (bad signature) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.1.0:shade (default) on project kafka-connect-on-cloud-foundry: Error creating shaded jar: invalid LOC header (bad signature)

Look at the last jar before it failed and remove that from the local repository, i.e.

$ rm -rf /Users/snowch/.m2/repository/org/eclipse/jetty/jetty-server/9.2.15.v20160210/
2

Looks like problem of configuration for maven compiler in your pom file. Default version java source and target is 1.5, even used JDK has higher version.

To fix, add maven compiler plugin configuration section with higher java version, example:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.6.1</version>
  <configuration>
    <source>1.6</source>
    <target>1.6</target>
  </configuration>
</plugin>

For more info check these links:

maven compiler

bug report

1

This answer is not for DevOps/ system admin guys, but for them who are using IDE like eclipse and facing invalid LOC header (bad signature) issue.

You can force update the maven dependencies, as follows:

enter image description here

enter image description here

1

Here is an small detector written in Java , just copy and run :)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

public class JarValidator {

    public static void main(String[] args) throws IOException {
        Path repositoryPath = Paths.get("C:\\Users\\goxr3plus\\.m2");

        // Check if the main Repository Exists
        if (Files.exists(repositoryPath)) {

            // Create a class instance
            JarValidator jv = new JarValidator();

            List<String> jarReport = new ArrayList<>();
            jarReport.add("Repository to process: " + repositoryPath.toString());

            // Get all the directory files
            List<Path> jarFiles = jv.getFiles(repositoryPath, ".jar");
            jarReport.add("Number of jars to process: " + jarFiles.size());
            jarReport.addAll(jv.openJars(jarFiles, true));

            // Print the report
            jarReport.stream().forEach(System.out::println);

        } else {
            System.out.println("Repository path " + repositoryPath + " does not exist.");
        }
    }

    /**
     * Get all the files from the given directory matching the specified extension
     * 
     * @param filePath      Absolute File Path
     * @param fileExtension File extension
     * @return A list of all the files contained in the directory
     * @throws IOException
     */
    private List<Path> getFiles(Path filePath, String fileExtension) throws IOException {
        return Files.walk(filePath).filter(p -> p.toString().endsWith(fileExtension)).collect(Collectors.toList());
    }

    /**
     * Try to open all the jar files
     * 
     * @param jarFiles
     * @return A List of Messages for Corrupted Jars
     */
    private List<String> openJars(List<Path> jarFiles, boolean showOkayJars) {
        int[] badJars = { 0 };
        List<String> messages = new ArrayList<>();

        // For Each Jar
        jarFiles.forEach(path -> {

            try (JarFile file = new JarFile(path.toFile())) {
                if (showOkayJars)
                    messages.add("OK : " + path.toString());
            } catch (IOException ex) {
                messages.add(path.toAbsolutePath() + " threw exception: " + ex.toString());
                badJars[0]++;
            }
        });

        messages.add("Total bad jars = " + badJars[0]);
        return messages;
    }

}

Output

Repository to process: C:\Users\goxr3plus\.m2
Number of jars to process: 4920
C:\Users\goxr3plus\.m2\repository\bouncycastle\isoparser-1.1.18.jar threw exception: java.util.zip.ZipException: zip END header not found
Total bad jars = 1
BUILD SUCCESSFUL (total time: 2 seconds)
1

We can force the checksum validation in maven with at least two options:

1.Adding the --strict-checksums to our maven command.

2.Adding the following configuration to our maven settings file:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">
    <!--...-->
    <profiles>
        <profile>
            <!--...-->
            <repositories>
                <repository>
                    <id>codehausSnapshots</id>
                    <name>Codehaus Snapshots</name>
                    <releases>
                        <enabled>false</enabled>
                        <updatePolicy>always</updatePolicy>
                        <checksumPolicy>fail</checksumPolicy>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                        <updatePolicy>never</updatePolicy>
                        <checksumPolicy>fail</checksumPolicy>
                    </snapshots>
                    <url>
                        <!--...-->
                    </url>
                </repository>
            </repositories>
            <pluginRepositories>
                <!--...-->
            </pluginRepositories>
            <!--...-->
        </profile>
    </profiles>
    <!--...-->
</settings>

More details in this post: https://dzone.com/articles/maven-artifact-checksums-what

0

Beyond removing .m2/repository, remove application from server, run server (without applications), stop it and add application again. Now it is supposed to work. For some reason just cleaning up server folders from interface doesn't have the same effect.

0

I was facing this issue while deploying my ear to my local weblogic instance. Clearing the local repository and building the ear again resolved the issue for me.

0

Maybe unrelated to the original reason in this question, but for those who would face same with gradle and local module dependency

dependencies {
    checkstyle project(":module")
}

this error could happen, if module doesn't contain group and version, so in the module/build.gradle just need to be specified

plugins {
    id 'java-library'
}

group = "com.example"
version = "master-SNAPSHOT"
0

If you are using CentOS linux system the Maven local repositary will be:

/root/.m2/repository/

You can remove .m2 and build your maven project in dev tool will fix the issue.

0

gradle clean and rebuild worked for me.

Not the answer you're looking for? Browse other questions tagged or ask your own question.