modmanager.ArchiveExtractor.java Source code

Java tutorial

Introduction

Here is the source code for modmanager.ArchiveExtractor.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package modmanager;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;
import net.sf.sevenzipjbinding.SevenZipException;
import org.apache.commons.io.FilenameUtils;
import util.UnzipUtility;

/**
 *
 * @author ruman
 */
public class ArchiveExtractor extends SwingWorker<ArchiveExtractor.Response, String> {

    private static final UnzipUtility unzipper = new UnzipUtility();
    private static final Logger logger = Logger.getLogger(ArchiveExtractor.class.getName());
    private ModificationManager modmanager;
    private File[] zipfiles;

    public ArchiveExtractor(ModificationManager modmanager, File[] zipfiles) {
        this.modmanager = modmanager;
        this.zipfiles = zipfiles;
    }

    @Override
    protected Response doInBackground() {
        Response res = Response.SUCCESS;

        boolean somethingInstalled = false;

        for (File zipfile : zipfiles) {
            File destinationDirectory = new File(modmanager.getModificationDirectory(),
                    FilenameUtils.removeExtension(zipfile.getName()));

            if (destinationDirectory.exists()) {
                res = Response.SUCCESS_WITH_ERRORS;
                continue;
            } else {
                destinationDirectory.mkdirs();
            }

            try {

                unzipper.unzip(zipfile, destinationDirectory, new UnzipUtility.ProgressListener() {

                    @Override
                    public void progress(String file, int index, int max_count) {
                        publish(file);
                        setProgress((int) ((float) index / max_count * 100f));
                    }
                });

                somethingInstalled = true;
            } catch (IOException | SevenZipException ex) {
                logger.log(Level.SEVERE, ex.getMessage());

                destinationDirectory.delete();

                return Response.SUCCESS_WITH_ERRORS;
            }
        }

        return somethingInstalled ? res : Response.NO_CHANGE;
    }

    public static enum Response {

        SUCCESS, SUCCESS_WITH_ERRORS, NO_CHANGE
    }
}