net.chris54721.infinitycubed.utils.Utils.java Source code

Java tutorial

Introduction

Here is the source code for net.chris54721.infinitycubed.utils.Utils.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.utils;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import net.chris54721.infinitycubed.Launcher;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Utils {

    public static File getAppdataPath() {
        if (SystemUtils.IS_OS_WINDOWS)
            return new File(System.getenv("APPDATA"));
        if (SystemUtils.IS_OS_MAC_OSX)
            return new File(System.getProperty("user.home") + "/Library/Application Support");
        if (SystemUtils.IS_OS_LINUX)
            return new File(System.getProperty("user.home"));
        return new File(System.getProperty("user.home"));
    }

    public static String getJavaPath() {
        String path = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        if (SystemUtils.IS_OS_WINDOWS)
            path += "w";
        return path;
    }

    public static boolean copy(File source, File target) {
        try {
            Files.copy(source, target);
            return target.length() == source.length();
        } catch (Exception e) {
            LogHelper.error("Failed copying file: " + e.getMessage(), e);
            return false;
        }
    }

    public static boolean copyToDirectory(File source, File targetDir) {
        return copy(source, new File(targetDir, source.getName()));
    }

    public static void unzip(File zipFile, File outputFolder) {
        InputStream in = null;
        OutputStream out = null;
        try {
            ZipFile zip = new ZipFile(zipFile);
            Enumeration<? extends ZipEntry> entries = zip.entries();
            if (!outputFolder.isDirectory())
                outputFolder.mkdirs();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File entryTarget = new File(outputFolder, entry.getName());
                entryTarget.getParentFile().mkdirs();
                if (entry.isDirectory())
                    entryTarget.mkdirs();
                else {
                    in = zip.getInputStream(entry);
                    out = new FileOutputStream(entryTarget);
                    IOUtils.copy(in, out);
                }
            }
        } catch (Exception e) {
            LogHelper.error("Failed extracting " + zipFile.getName(), e);
        } finally {
            if (in != null)
                IOUtils.closeQuietly(in);
            if (out != null)
                IOUtils.closeQuietly(out);
        }
    }

    public static void restart() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    File executable = new File(URLDecoder.decode(
                            (Launcher.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()),
                            "UTF-8"));
                    List<String> command = new ArrayList<String>();
                    command.add(getJavaPath());
                    command.add("-jar");
                    command.add(executable.getAbsolutePath());
                    ProcessBuilder builder = new ProcessBuilder(command);
                    builder.start();
                } catch (Exception e) {
                    LogHelper.error("Failed restarting launcher, shutting down", e);
                    System.exit(-1);
                }
            }
        });
        System.exit(0);
    }

    public static URL getResource(String resource, String ext) {
        return Utils.class.getResource("/net/chris54721/infinitycubed/assets/" + resource + "." + ext);
    }

    public static Image getImageResource(String imageName) {
        ImageIcon image = new ImageIcon(Toolkit.getDefaultToolkit().getImage(getResource(imageName, "png")));
        if (image.getImageLoadStatus() == MediaTracker.COMPLETE)
            return image.getImage();
        else {
            LogHelper.error("Failed loading image resource " + imageName);
            return null;
        }
    }

    public static BufferedImage toBufferedImage(Image img) {
        if (img instanceof BufferedImage)
            return (BufferedImage) img;
        BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(img, 0, 0, null);
        bGr.dispose();
        return bimage;
    }

    public static String toString(URL url) throws IOException {
        return Resources.toString(url, Charsets.UTF_8);
    }

}