Last active
May 27, 2016 00:23
-
-
Save andreluisdias/44596137faaa6a8c63a82e58c03d5682 to your computer and use it in GitHub Desktop.
Simple way to create a CRC code to a File within any JAR file, using Spring Boot and Lambda!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.io.File; | |
import java.io.InputStream; | |
import java.util.Enumeration; | |
import java.util.jar.JarEntry; | |
import java.util.jar.JarFile; | |
import java.util.zip.CRC32; | |
import lombok.extern.slf4j.Slf4j; | |
import org.springframework.boot.ExitCodeGenerator; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.context.ConfigurableApplicationContext; | |
@SpringBootApplication | |
@Slf4j | |
public class DemoFileCRCApplication { | |
public static void main(String[] args) throws Exception { | |
final ConfigurableApplicationContext runContext = SpringApplication.run(DemoFileCRCApplication.class, args); | |
final String jarFilePath = "[JAR PATH GOES HERE]"; | |
JarFile jar = new JarFile(new File(jarFilePath)); | |
Enumeration<JarEntry> entries = jar.entries(); | |
while (entries.hasMoreElements()) { | |
JarEntry jarEntry = entries.nextElement(); | |
updateFileCRC(jarEntry, jar); | |
log.info("File Name " + jarEntry.getName() + " - CRC = " + jarEntry.getCrc()); | |
} | |
jar.close(); | |
SpringApplication.exit(runContext, OK); | |
} | |
private static void updateFileCRC(final JarEntry jarEntry, final JarFile jar) throws Exception { | |
if (!jarEntry.isDirectory() && jarEntry.getCrc() == 0L) { | |
// Generates a new CRC for File | |
CRC32 newCRC = new CRC32(); | |
InputStream jarEntryIS = jar.getInputStream(jarEntry); | |
int i; | |
while ( (i = jarEntryIS.read()) != -1) newCRC.update(i); | |
jarEntry.setCrc(newCRC.getValue()); | |
log.info(">>>>>>>>>>>> Created CRC for file " + jarEntry.getName() + "=" + jarEntry.getCrc()); | |
} | |
} | |
private static final ExitCodeGenerator OK = () -> 100; // LAMBDA! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment