net.chris54721.infinitycubed.Updater.java Source code

Java tutorial

Introduction

Here is the source code for net.chris54721.infinitycubed.Updater.java

Source

/*
 * This file is part of the InfinityCubed Launcher source code.
 * Copyright (C) 2014 InfinityCubed Team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.chris54721.infinitycubed;

import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import net.chris54721.infinitycubed.data.Downloadable;
import net.chris54721.infinitycubed.utils.LogHelper;
import net.chris54721.infinitycubed.utils.Reference;
import net.chris54721.infinitycubed.utils.Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;

public class Updater {

    public static void checkUpdates() {
        try {
            LogHelper.info("Checking for launcher updates");
            String version = Resources.toString(new URL(Reference.FILES_URL + "version.cfg"), Charsets.UTF_8);
            if (!version.equalsIgnoreCase(Launcher.getVersion()))
                downloadUpdate(version);
        } catch (Exception e) {
            LogHelper.error("Failed checking for launcher updates", e);
        }
    }

    private static void downloadUpdate(String version) {
        try {
            // TODO Trigger splashscreen progressbar (run downloadable w/custom ProgressListener)
            File executable = new File(URLDecoder.decode(
                    (Launcher.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()),
                    "UTF-8"));
            String extension = FilenameUtils.getExtension(executable.getName());
            File updateTemp = new File(Reference.DEFAULT_FOLDER, "update." + extension);
            Downloadable update = new Downloadable(
                    new URL(Reference.UPDATE_URL + extension + "/infinitycubed-" + version + "." + extension),
                    updateTemp);
            if (update.download()) {
                executable.delete();
                FileUtils.moveFile(updateTemp, executable);
                Utils.restart();
            } else
                LogHelper.warn("Failed downloading launcher update: file size not matching.");
        } catch (Exception e) {
            LogHelper.error("Failed downloading launcher update", e);
        }
    }

}