部署 Maven 项目抛出 java.util.zip.ZipException:无效 LOC header(签名错误)

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

当我 运行 我的 mvn install 时出现以下异常。我什至删除了本地存储库,运行 再次遇到同样的异常。

[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] 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.access00(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

jar 文件可能已损坏。尝试删除以下文件夹的内容:

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

然后右击你的项目,selectMaven,更新项目,勾选强制更新Snapshots/Releases。

主要问题是 jar 文件损坏。

要找到损坏的,您需要在 Eclipse 的断点视图中添加一个 Java 异常断点,或者您喜欢的 IDE,select java.util.zip.ZipException class,并重启 Tomcat 实例。

当 JVM 在 ZipException 断点挂起时,您必须转到 JarFile.getManifestFromReference() 在堆栈跟踪中,并检查属性 name 以查看文件名。

之后,您应该从文件系统中删除该文件,然后右键单击您的项目,select Maven,更新项目,选中 Snapshots/Releases 的强制更新。

看起来像是您的 pom 文件中的 maven 编译器配置问题。默认版本 java 源和目标是 1.5,即使使用 JDK 也有更高版本。

要修复,请添加具有更高 java 版本的 maven 编译器插件配置部分,示例:

<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>

有关更多信息,请查看这些链接:

maven compiler

bug report

gsitgithub/find-currupt-jars.txt 开始,以下命令列出存储库中所有损坏的 jar 文件:

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

您可以删除损坏的jar文件,重新编译工程。

示例输出:

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)

我想练习一下。

使用你喜欢的IDE,这里以eclipse为例:

  1. 在异常堆栈中找到合适的位置
  2. 设置条件断点
  3. 调试它
  4. 它会在异常发生前打印损坏的 jar

我的解决方案是 运行 mvn-X:

$ mvn package -X

然后向后查看输出,直到看到失败,然后继续,直到看到 mvn 尝试处理的最后一个 jar 文件:

...
... <<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)

查看失败前的最后一个 jar 并将其从本地存储库中删除,即

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

您需要检查哪个 jar 有问题。它必须被损坏。再次删除那个 jar 和 运行 mvn spring-boot:run 命令。可能不止一个 jar 已损坏,因此每次您需要 运行 该命令来删除该 jar。在我的例子中 mysql,jackson,aspect jars 已损坏 mvn spring-boot:run 命令 3 次,我弄清楚了这一点并从 .m2 文件夹中删除了 jars。现在问题已经解决了。

我在将耳朵部署到本地 weblogic 实例时遇到了这个问题。清除本地存储库并再次构建 ear 解决了我的问题。

除了删除 .m2/repository,从服务器中删除应用程序,运行 服务器(没有应用程序),停止它并再次添加应用程序。现在它应该工作了。出于某种原因,仅从界面中清理服务器文件夹不会产生相同的效果。

这个答案不是给 DevOps/系统管理员的,而是给那些使用 IDE 像 eclipse 并面临 invalid LOC header (bad signature) 问题的人。

可以强制更新maven依赖,如下:

这里是一个用Java写的小检测器,直接复制然后运行 :)

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)

我们可以使用至少两个选项在 Maven 中强制执行校验和验证:

1.Adding --strict-checksums 到我们的 maven 命令。

2.Adding 对我们的maven设置文件进行如下配置:

<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>

此 post 中的更多详细信息:https://dzone.com/articles/maven-artifact-checksums-what

可能与这个问题的最初原因无关,但对于那些会面临同样问题的人 gradle 和本地模块依赖性

dependencies {
    checkstyle project(":module")
}

如果模块不包含组和版本,可能会发生此错误,因此在 module/build.gradle 中只需指定

plugins {
    id 'java-library'
}

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

如果您使用的是 CentOS linux 系统,Maven 本地存储库将是:

/root/.m2/repository/

您可以删除 .m2 并在开发工具中构建您的 maven 项目将解决此问题。

gradle 清理和重建对我有用。