-2

I have a groovy script which takes a 2 zip files, unzips them, then processes them.

The problem I have is when I go to unzip the zip files, each unzipped file produces a subfolder then the content of the unzip file not the content itself.

Example:

Currently this happens when I unzip

content-1232.zip -> /content-1232/content/<all content here>

What I want is

content-1232.zip -> /content-1232/<all_content>

or

Put into a new directory

content-1232.zip -> /new_directory/<all_content>

I tried this but to no avail:

Path basePath = Paths.get(output.getAbsolutePath())
Path srcPath = Paths.get(pdfContent.getAbsolutePath())
Path targetPath = basePath

Files.move(srcPath, targetPath.resolve(basePath.relativize(srcPath)))

Seems like a very simple thing to do but I'm not have any luck. How can I accomplish this in groovy? Any help will be appreciated

Edit:

static void main(String[] args) {
    logger.info("Beginning unpacking of content...")


    def output = new File("/Users/Haddad/Desktop/workspace/c")
    def pdfContent = new File("/Users/Haddad/Desktop/workspace/c/pdf-content")


    // Look for test1 and test2 production content zip file, ensure there's only 1 and unzip
    List appZip = FileUtil.discoverFiles(output, true, "test1-production-content-.*\\.zip")
    List compliZip = FileUtil.discoverFiles(output,true,"test2-production-content-.*\\.zip")

    assert appZip.size() == 1, "Did not find expected number of test1 content zip, actual size is: " + appZip.size()
    assert compliZip.size() == 1, "Did not find expected number of test2 content zip, actual size is " + appZip.size()

    def outputAppZip = new File(output.getAbsolutePath()+"/"+appZip.get(0).getName()+"-intermediate");
    def outputCompliZip = new File(output.getAbsolutePath()+"/"+compliZip.get(0).getName()+"-intermediate");

    ZipUtil.unzipToDisk(appZip.get(0), outputAppZip )
    ZipUtil.unzipToDisk(compliZip.get(0), outputCompliZip )


    // move it to pdf content
    List applicationContent = FileUtil.discoverDirectories(output, "one-production-content-.*-intermediate", true)
    assert applicationContent.size() == 1, "Did not find expected number of test1 contents " + applicationContent.size()

    def success = FileUtil.copy(applicationContent.get(0), pdfContent)
    assert success, "Could not copy tt content"

    // move pdf content
    List complianceContent = FileUtil.discoverDirectories(output, "two-production-content-.*-intermediate", true)
    assert complianceContent.size() == 1, "Did not find expected number of test2 contents " + complianceContent.size()
    success = FileUtil.copy(complianceContent.get(0), pdfContent)
    assert success, "Could not copy pdf content"

    // rename to not be unsupported
    List unsupportedDirs = FileUtil.discoverDirectories(pdfContent, "_unsupported_.*", true)
    for (File file : unsupportedDirs) {
        file.renameTo(new File(file.getParentFile(), file.getName().replace("_unsupported_", "")))
    }


    logger.info("Completed!")
}
Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219
mosawi
  • 1,283
  • 5
  • 25
  • 48
  • Show your unzip code. – Abhijit Sarkar Jul 08 '17 at 21:55
  • 2
    Nothing to do with Java or grails. Tags removed – tim_yates Jul 09 '17 at 00:32
  • @AbhijitSarkar just added the code. I hope this doesn't add any unnecessary complexity to my question – mosawi Jul 09 '17 at 00:32
  • @tim_yates I added the java tag again. Groovy and Java code are usually interchnagable so a solution in core java would work here as well – mosawi Jul 09 '17 at 00:34
  • 1
    `grails` tag is completely misleading - removed again. There's not a bit of grails specific code in this problem. – Abhijit Sarkar Jul 09 '17 at 00:39
  • What's the structure of each zip file? Is the directory `content` in them or are the files laid out flat (I'm guessing the former)? We shouldn't have to pull teeth to get information, your question is incomplete. Also specify what the `FileUtil` and `ZipUtil` classes are, because those are the ones doing the work. – Abhijit Sarkar Jul 09 '17 at 00:43
  • @AbhijitSarkar you are correct, it's not flat. When I unzip `content-1232.zip` it produces directory `content-1232` which contains – mosawi Jul 09 '17 at 00:51
  • Thanks @AbhijitSarkar however this is why I didn't want to post code. Generically speaking, based on the code you've seen and even without, how can I move the contents of a directory not including the Parents folder to another folder. This is a generic question which requires no context – mosawi Jul 09 '17 at 00:59
  • 1
    @mosawi That's not how it works. We are not consultants that get paid for answering a random question you throw at us. We are programmers that like to solve problems. And in order to do that we need to understand the context first. If you want to work with vague information, ask your superiors. – Abhijit Sarkar Jul 09 '17 at 01:08
  • Please read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) before attempting to ask more questions. –  Jul 09 '17 at 02:44
  • Please read [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) before attempting to ask more questions. –  Jul 09 '17 at 02:44

1 Answers1

0

How about this?

Input:

test.zip
--- test
------ test.txt

Output:

<someFolder>
--- test.txt

Code:

public class Main {

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        Path input = main.getInputPath(args);
        Path output = main.getOutputPath(args);

        main.extract(input, output);
        main.flatten(output);
    }

    private final Path getInputPath(String[] args) {
        if (args.length < 1) {
            throw new IllegalArgumentException("Usage: Main <inputFile> [<outputDirectory>]");
        }

        Path input = Paths.get(args[0]);

        if (!isRegularFile(input)) {
            throw new IllegalArgumentException(String.format("%s is not a file.", input.toFile().getAbsolutePath()));
        }

        return input;
    }

    private final Path getOutputPath(String[] args) throws IOException {
        return args.length < 2 ? Files.createTempDirectory(null) :
                Files.createDirectories(Paths.get(args[1]));
    }

    private final void extract(Path input, Path output) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input.toFile()))) {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                String fileName = ze.getName();

                if (fileName.contains("__MACOSX")) {
                    continue;
                }

                File file = new File(output.toFile(), fileName);

                if (ze.isDirectory()) {
                    Files.createDirectories(file.toPath());
                    continue;
                }

                System.out.println("Extracting: " + file.getAbsolutePath());

                try (FileOutputStream fos = new FileOutputStream(file, true)) {
                    byte[] buffer = new byte[4096];
                    for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                        fos.write(buffer, 0, len);
                    }
                }
            }
        }
    }

    private final void flatten(Path output) throws IOException {
        List<Path> children = Files.list(output)
                .collect(toList());

        if (children.size() == 1) {
            Path path = children.get(0);
            Files.list(path)
                    .forEach(f -> {
                        try {
                            System.out.printf("Moving %s to %s.\n", f.toFile().getAbsolutePath(),
                                    output.toFile().getAbsolutePath());
                            Files.move(f, Paths.get(output.toFile().getAbsolutePath(), f.toFile().getName()));
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });

            Files.delete(path);
        }
    }
}
Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219
  • Random downvote, care to explain? – Abhijit Sarkar Jul 09 '17 at 02:45
  • Thanks @AbhijitSarkar. Not sure who downvoted your answer or my question but this answer works great. I was wishing for a simple solution but this looks to work a lot better than what I had – mosawi Jul 09 '17 at 18:11
  • On the flatten method you have on the first line `List children = Files.list(output).collect(toList());` where is toList() ? – mosawi Jul 09 '17 at 18:35
  • I don't see `isRegularFile` method as well? Interested to see how it checks file type – mosawi Jul 09 '17 at 18:36
  • [toList](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toList--) [isRegularfile](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#isRegularFile-java.nio.file.Path-java.nio.file.LinkOption...-) This is why IDEs exist. Ask it to do static imports. – Abhijit Sarkar Jul 09 '17 at 18:38