package cleaner; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import javax.swing.JFileChooser; public class Main { public static void main(String[] args) throws Exception { String rutaRepo = (args.length > 0)?args[0]:null; cleanInvalidJARs(rutaRepo); } private static void cleanInvalidJARs(String rutaRepo) { File mavenRepo = null; if(rutaRepo != null) { mavenRepo = new File(rutaRepo); } else { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int op = chooser.showOpenDialog(null); if(op == JFileChooser.APPROVE_OPTION) { mavenRepo = chooser.getSelectedFile(); } } if(mavenRepo != null) { List invalidJARs = detectInvalidJARs(mavenRepo); for(File jar:invalidJARs) { System.out.println("Invalid JAR found at: "+jar.getAbsolutePath()); } Scanner sc = new Scanner(System.in); if(invalidJARs.isEmpty()) { System.out.println("No invalid JARs found"); } else { System.out.print("Do you want to delete them ? "); String action = sc.nextLine(); if(action.equals("Y")) { System.out.print("Do you want to delete the entire folders (includes the POM and other files) ? "); action = sc.nextLine(); deleteJARs(invalidJARs, action.equals("Y")); } } sc.close(); } } private static void deleteJARs(List jarList) { deleteJARs(jarList, true); } private static void deleteJARs(List jarList, boolean deleteParent) { for(File f:jarList) { if(deleteParent) { System.out.println("Deleting "+f.getParentFile().getAbsolutePath()); deleteDir(f.getParentFile()); } else { System.out.println("Deleting "+f.getAbsolutePath()); f.delete(); } } } private static void deleteDir(File currentDir) { if(currentDir.listFiles().length == 0) { currentDir.delete(); } else { for(File f:currentDir.listFiles()) { if(f.isDirectory()) { deleteDir(f); } else { f.delete(); } } } } private static List detectInvalidJARs(File currentDir) { List invalidJARs = new ArrayList<>(); for(File file:currentDir.listFiles()) { if(file.isDirectory()) { invalidJARs.addAll(detectInvalidJARs(file)); } else { if(file.getName().endsWith(".jar")) { if(!validateJAR(file)) { invalidJARs.add(file); } } } } return invalidJARs; } private static boolean validateJAR(File jarFile) { boolean valid = false; byte[] buffer = new byte[4]; byte[] jarSignature = new byte[]{0x50, 0x4B, 0x03, 0x04}; try { FileInputStream fis = new FileInputStream(jarFile); if(fis.read(buffer) == 4) { valid = Arrays.equals(buffer, jarSignature); } fis.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return valid; } }