com.uniteddev.Unity.Downloader.java Source code

Java tutorial

Introduction

Here is the source code for com.uniteddev.Unity.Downloader.java

Source

/*
The MIT License (MIT)
    
Copyright (c) 2013 UnitedDev
    
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
    
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package com.uniteddev.Unity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class Downloader {

    static int cores = Runtime.getRuntime().availableProcessors();
    static ArrayList<String> files, rename_files, folders;

    public static void update() throws IOException, InterruptedException {
        files = new ArrayList<String>();
        rename_files = new ArrayList<String>();
        folders = new ArrayList<String>();
        Login.progress.setValue(0);
        ArrayList<String> listing = getDirectoryListing("");
        recursiveFileListing(listing, "");
        // TODO: merge similar thread pooling code & cleanup
        removeOutdated();
        removeRedundancies();
        downloadFiles();
        renameFiles();
        System.out.println("File Check Complete.");
        Login.progress.setValue(100);
        Login.progressText.setText("Update complete.");
    }

    public static void recursiveFileListing(ArrayList<String> extracted_links, String folder) throws IOException {
        for (int i = 0; i < extracted_links.size(); i++) {
            String target = extracted_links.get(i).toString();
            String new_folder = folder + target;
            while (target.endsWith("/")) {
                folders.add(new_folder);
                String foldername[] = new_folder.split("/");
                folder((Minecraft.getWorkingDirectory() + File.separator + new_folder),
                        foldername[foldername.length - 1]);
                recursiveFileListing(getDirectoryListing(new_folder), new_folder);
                break;
            }
            if (!new_folder.endsWith("/")) {
                files.add(new_folder);
                rename_files.add(new_folder);
            }
        }
    }

    public static ArrayList<String> getDirectoryListing(String url) throws IOException {
        Document doc = Jsoup.connect(Unity.url + Unity.folder + "/" + url).get();
        Elements extracted_links = doc.select("a[href]");
        ArrayList<String> links = new ArrayList<String>();
        for (int i = 0; i < extracted_links.size(); i++) {
            String check = extracted_links.get(i).attr("href");
            if (!(check.contains("?C=N;O=D")) && !(check.contains("?C=M;O=A")) && !(check.contains("?C=D;O=A"))
                    && !(check.contains("?C=S;O=A")) && !(check.contains("content/minecraft/files"))) {
                links.add(extracted_links.get(i).attr("href"));
            }
        }
        return links;
    }

    public static void removeOutdated() throws IOException, InterruptedException {
        Login.progressText.setText("Removing outdated files...");
        System.out.println("Removing outdated files...");
        class removefile implements Runnable {
            private int i;

            removefile(int i) {
                this.i = i;
            }

            public void run() {
                if (!((folders.get(this.i).contains("bin/")) || (folders.get(this.i).contains("resources/")))) {
                    try {
                        //System.out.println("Currently attempting Pool Index: "+this.i);
                        ArrayList<String> online_list = getDirectoryListing(folders.get(this.i));
                        ArrayList<String> offline_list = new ArrayList<String>();
                        if (new File(Minecraft.getWorkingDirectory(), folders.get(this.i)).isDirectory()) {
                            File[] offline_files = new File(Minecraft.getWorkingDirectory(), folders.get(this.i))
                                    .listFiles();
                            for (int j = 0; j < offline_files.length; j++) {
                                if (!offline_files[j].isDirectory()) {
                                    offline_list.add(offline_files[j].getName());
                                }
                            }
                        }
                        for (int j = 0; j < online_list.size(); j++) {
                            online_list.set(j, namefix(online_list.get(j)));
                        }
                        for (int j = 0; j < offline_list.size(); j++) {
                            if (!online_list.contains(offline_list.get(j))) {
                                clean(Minecraft.getWorkingDirectory() + File.separator + folders.get(this.i),
                                        offline_list.get(j));
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        ExecutorService pool = Executors.newFixedThreadPool(cores + 2);
        for (int i = 0; i < folders.size(); i++) {
            pool.submit(new removefile(i));
        }
        pool.shutdown();
        pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    }

    public static void removeRedundancies() throws InterruptedException {
        class removeRedundancy implements Runnable {
            private int i;

            removeRedundancy(int i) {
                this.i = i;
            }

            public void run() {
                files.remove(this.i);
            }
        }

        int i = 0;
        ExecutorService pool = Executors.newFixedThreadPool(cores);
        while (i < files.size()) {
            String file = files.get(i);
            file = namefix(file);
            if (new File(Minecraft.getWorkingDirectory(), file).exists())
                pool.submit(new removeRedundancy(i)); // this was originally a while loop
            else
                i++;
        }
        pool.shutdown();
        pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    }

    public static void downloadFiles() throws MalformedURLException, IOException, InterruptedException {

        class downloadFile implements Runnable {
            private int i;

            downloadFile(int i) {
                this.i = i;
            }

            public void run() {
                String filename = files.get(this.i).substring(files.get(this.i).lastIndexOf('/') + 1,
                        files.get(this.i).length());
                File f = new File(Minecraft.getWorkingDirectory(), files.get(this.i));
                try {
                    Login.progressText.setText("Downloading: " + filename);
                    System.out.println("Downloading: " + filename);
                    //System.out.println("Currently attempting Pool Index: "+this.i);
                    HttpURLConnection connect_url = setupHTTP(Unity.url + Unity.folder + "/" + files.get(this.i));
                    FileUtils.copyInputStreamToFile(connect_url.getInputStream(), f);
                } catch (FileNotFoundException e) {
                    Login.progressText.setText("File not found!");
                } catch (MalformedURLException e) {
                    System.out.println("DEV: FIX URL");
                    e.printStackTrace();
                } catch (IOException e) {
                    System.out.println("FileSystem Error");
                    e.printStackTrace();
                }
            }
        }

        Login.progressText.setText("Downloading new files...");
        System.out.println("Downloading new files...");
        System.out.println("Number of files to download: " + files.size());
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < files.size(); i++) {
            pool.submit(new downloadFile(i));
            Login.progress.setValue((int) (((double) i / files.size()) * 100));
        }
        pool.shutdown();
        pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    }

    public static void renameFiles() throws IOException, InterruptedException {
        Login.progressText.setText("Renaming files...");
        System.out.println("Renaming files...");
        class renameFile implements Runnable {
            private int i;

            renameFile(int i) {
                this.i = i;
            }

            public void run() {
                //System.out.println("Currently attempting Pool Index: "+this.i);
                String file = rename_files.get(this.i);
                if (file.contains("%20") || file.contains("%5b") || file.contains("%5d")) {
                    file = namefix(file);
                    File oldfile = new File(Minecraft.getWorkingDirectory(), rename_files.get(this.i));
                    if (oldfile.exists()) {
                        File newfile = new File(Minecraft.getWorkingDirectory(), file);
                        oldfile.renameTo(newfile);
                        System.out.println("Renamed " + oldfile.getName() + " to " + newfile.getName());
                    }
                }

            }
        }
        ExecutorService pool = Executors.newFixedThreadPool(cores + 4);
        for (int i = 0; i < rename_files.size(); i++) {
            pool.submit(new renameFile(i));
        }
        pool.shutdown();
        pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    }

    public static void clean(String folder, String file) {
        if (!(file.equals("rei_minimap"))) { // rei_minimap quick fix
            File local_file = new File(folder, file);
            Login.progressText.setText("File no longer needed: " + local_file.getAbsolutePath());
            System.out.println("File no longer needed: " + local_file.getAbsolutePath());
            local_file.delete();
        }
    }

    public static void folder(String dir, String dirname) {
        File folder = new File(dir);
        if (!folder.exists()) {
            folder.mkdir();
            Login.progressText.setText("Created directory: " + dirname);
            System.out.println("Created directory: " + dirname);
        }
    }

    public static String namefix(String file) {
        String[][] fixes = { { "%20", " " }, { "%5b", "[" }, { "%5d", "]" } };
        for (int i = 0; i < fixes.length; i++) {
            file = file.replaceAll(fixes[i][0], fixes[i][1]);
        }
        return file;
    }

    public static HttpURLConnection setupHTTP(String fileurl) throws MalformedURLException, IOException {
        HttpURLConnection httpConnection = (HttpURLConnection) new URL(fileurl).openConnection();
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("Content-Type", "application/java-archive");
        httpConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31");
        return httpConnection;
    }

}