170

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
Matias Sebastiao
  • 1,691
  • 1
  • 13
  • 13
Karthick
  • 1,845
  • 3
  • 13
  • 15
  • 1
    Made a plugin for this problem -> https://github.com/goxr3plus/CorruptedJarsDetector – GOXR3PLUS Oct 11 '18 at 08: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 Oct 13 '18 at 15:48
  • Marco the code for the repository is the one in class lol :) – GOXR3PLUS Oct 13 '18 at 16:25

14 Answers14

227

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.

Azim
  • 1,157
  • 8
  • 29
Siva Anand
  • 2,712
  • 2
  • 15
  • 9
  • 4
    This should be marked as the solution. I believe it is also the solution to several other related questions which have no answers. Thanks Siva! – Hack-R Oct 20 '16 at 18:58
  • 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 Feb 06 '17 at 12:20
  • 1
    very nice.. after spending 7 hours I found out the solution... KUDOS for you man.... – Sufiyan Ansari Aug 07 '17 at 15:59
  • 4
    This works but deleting entire maven local repository is not the best option. Just delete the related jar files and that's enough. – Levent Divilioglu Oct 07 '17 at 18:36
  • 2
    Don't have to delete all the dependencies, on the top you can find which dependencies is has bad LOC Header. – umar faraz Apr 06 '18 at 14:41
  • Any idea how to fail the build in case of these error existence? Now mvn clean package succeeds even though there are these invalid LOC header errors – leokom Apr 20 '18 at 11:52
  • 3
    Just to note the obvious: When somebody encounters `invalid LOC header` in Gradle build, you just delete `~/.gradle/caches` folder (Linux). – Martin Vseticka Aug 24 '18 at 16:23
  • Is it not an overkill to delete all stuff? – Witold Kaczurba Jan 15 '19 at 13:29
111

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.

Richard Osseweyer
  • 1,581
  • 20
  • 21
Matias Sebastiao
  • 1,691
  • 1
  • 13
  • 13
83

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.

Amit Ray
  • 3,322
  • 2
  • 17
  • 34
alok
  • 2,380
  • 18
  • 15
41

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)
Javier
  • 10,845
  • 4
  • 41
  • 52
  • 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 Jul 05 '17 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 Jul 05 '17 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 Jul 06 '17 at 15:33
  • 2
    You are the best, MAN! – Igor Masternoy Jul 26 '17 at 23:04
  • 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 Apr 24 '18 at 10:17
  • Absolutely great answer, removing thousands of libraries inside .m2 is a lot to lose. Thanks – Qussay Najjar Apr 29 '18 at 19:28
11

I'd like to give my 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

samm
  • 525
  • 4
  • 20
  • 1
    This is a far better solution that clearing the entire m2 repository, which in my case would take ages to download again. – Martin Cassidy May 21 '18 at 11:51
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/
Chris Snow
  • 20,818
  • 29
  • 115
  • 263
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

harvyS
  • 510
  • 6
  • 7
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

Vishrant
  • 10,695
  • 8
  • 48
  • 87
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)
GOXR3PLUS
  • 5,939
  • 3
  • 30
  • 79
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

JuanMoreno
  • 1,693
  • 1
  • 15
  • 24
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.

Mofi
  • 38,783
  • 14
  • 62
  • 115
SMT_Dev
  • 9
  • 2
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.

Alex
  • 3,209
  • 10
  • 47
  • 75
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"
lanwen
  • 2,061
  • 15
  • 28
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.

Virudhai Paul
  • 61
  • 1
  • 8