001package edu.pdx.cs410J.grader;
002
003import com.google.common.collect.Sets;
004
005import java.io.*;
006import java.util.Date;
007import java.util.HashMap;
008import java.util.Map;
009import java.util.Set;
010import java.util.jar.Attributes;
011import java.util.stream.Collectors;
012import java.util.zip.ZipEntry;
013
014class ZipFileOfFilesMaker extends ZipFileMaker {
015
016  private final Map<File, String> sourceFilesAndNames;
017
018  public ZipFileOfFilesMaker(Map<File, String> sourceFilesAndNames, File zipFile, Map<Attributes.Name, String> manifestEntries) throws FileNotFoundException {
019    super(new FileOutputStream(zipFile), manifestEntries);
020    this.sourceFilesAndNames = sourceFilesAndNames;
021  }
022
023  public void makeZipFile() throws IOException {
024    Map<ZipEntry, InputStream> zipFileEntries = new HashMap<>();
025
026    for (Map.Entry<File, String> fileEntry : sourceFilesAndNames.entrySet()) {
027      File file = fileEntry.getKey();
028      String fileName = fileEntry.getValue();
029      logger.debug("Adding " + fileName + " to zip");
030      ZipEntry entry = new ZipEntry(fileName);
031      entry.setTime(file.lastModified());
032      entry.setSize(file.length());
033
034      entry.setMethod(ZipEntry.DEFLATED);
035
036      zipFileEntries.put(entry, new FileInputStream(file));
037    }
038
039
040    makeZipFile(zipFileEntries);
041  }
042
043  public static void main(String[] args) throws IOException {
044    String zipFileName = null;
045    Set<File> files = Sets.newHashSet();
046
047    for (String arg : args) {
048      if (zipFileName == null) {
049        zipFileName = arg;
050
051      } else {
052        File file = new File(arg);
053        if (file.exists()) {
054          files.add(file);
055        }
056      }
057    }
058
059    if (zipFileName == null) {
060      usage("Missing zip file name");
061    }
062
063    if (files.isEmpty()) {
064      usage("Missing files");
065    }
066
067    Map<File, String> sourceFilesAndNames =
068      files.stream().collect(Collectors.toMap(file -> file, File::getPath));
069
070    assert zipFileName != null;
071    File zipFile = new File(zipFileName);
072
073    Map<Attributes.Name, String> manifestEntries = new HashMap<>();
074    manifestEntries.put(new Attributes.Name("Created-By"), System.getProperty("user.name"));
075    manifestEntries.put(Attributes.Name.MANIFEST_VERSION, new Date().toString());
076
077    new ZipFileOfFilesMaker(sourceFilesAndNames, zipFile, manifestEntries).makeZipFile();
078  }
079
080  private static void usage(String message) {
081    PrintStream err = System.err;
082    err.println("** " + message);
083    err.println("java ZipMaker zipFileName files+");
084    err.println("  ziprFileName    The name of the zip file to create");
085    err.println("  files+         One or more files to include in the zip");
086    err.println();
087
088    System.exit(1);
089  }
090}