aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/cc/polyfrost/oneconfig/utils/NetworkUtils.java
blob: b99d09641c0590dedc8127ff3f5ee93f3ed60ffa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package cc.polyfrost.oneconfig.utils;

import com.google.gson.JsonElement;
import cc.polyfrost.oneconfig.libs.universal.UDesktop;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * Utility class for accessing the internet.
 */
public final class NetworkUtils {

    /**
     * Gets the contents of a URL as a String.
     *
     * @param url       The URL to read.
     * @param userAgent The user agent to use.
     * @param timeout   The timeout in milliseconds.
     * @param useCaches Whether to use caches.
     * @return The contents of the URL.
     */
    public static String getString(String url, String userAgent, int timeout, boolean useCaches) {
        try (InputStreamReader input = new InputStreamReader(setupConnection(url, userAgent, timeout, useCaches), StandardCharsets.UTF_8)) {
            return IOUtils.toString(input);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Gets the contents of a URL as a String.
     *
     * @param url The URL to read.
     * @return The contents of the URL.
     * @see NetworkUtils#getString(String, String, int, boolean)
     */
    public static String getString(String url) {
        return getString(url, "OneConfig/1.0.0", 5000, false);
    }

    /**
     * Gets the contents of a URL as a JsonElement.
     *
     * @param url       The URL to read.
     * @param userAgent The user agent to use.
     * @param timeout   The timeout in milliseconds.
     * @param useCaches Whether to use caches.
     * @return The contents of the URL.
     * @see NetworkUtils#getString(String, String, int, boolean)
     * @see JsonUtils#parseString(String)
     */
    public static JsonElement getJsonElement(String url, String userAgent, int timeout, boolean useCaches) {
        return JsonUtils.parseString(getString(url, userAgent, timeout, useCaches));
    }

    /**
     * Gets the contents of a URL as a JsonElement.
     *
     * @param url The URL to read.
     * @return The contents of the URL.
     * @see NetworkUtils#getJsonElement(String, String, int, boolean)
     */
    public static JsonElement getJsonElement(String url) {
        return getJsonElement(url, "OneConfig/1.0.0", 5000, false);
    }

    /**
     * Downloads a file from a URL.
     *
     * @param url       The URL to download from.
     * @param file      The file to download to.
     * @param userAgent The user agent to use.
     * @param timeout   The timeout in milliseconds.
     * @param useCaches Whether to use caches.
     * @return Whether the download was successful.
     */
    public static boolean downloadFile(String url, File file, String userAgent, int timeout, boolean useCaches) {
        url = url.replace(" ", "%20");
        try (FileOutputStream fileOut = new FileOutputStream(file); BufferedInputStream in = new BufferedInputStream(setupConnection(url, userAgent, timeout, useCaches))) {
            IOUtils.copy(in, fileOut);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * Downloads a file from a URL.
     *
     * @param url  The URL to download from.
     * @param file The file to download to.
     * @return Whether the download was successful.
     * @see NetworkUtils#downloadFile(String, File, String, int, boolean)
     */
    public static boolean downloadFile(String url, File file) {
        return downloadFile(url, file, "OneConfig/1.0.0", 5000, false);
    }

    /**
     * Gets the SHA-256 hash of a file.
     *
     * @param file The file to hash.
     * @return The SHA-256 hash of the file.
     */
    public static String getFileChecksum(File file) {
        try (FileInputStream inputStream = new FileInputStream(file)) {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] bytesBuffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = inputStream.read(bytesBuffer)) != -1) {
                digest.update(bytesBuffer, 0, bytesRead);
            }

            return convertByteArrayToHexString(digest.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * Launches a URL in the default browser.
     *
     * @param uri The URI to launch.
     * @see UDesktop#browse(URI)
     * @see java.awt.Desktop#browse(URI)
     */
    public static void browseLink(String uri) {
        UDesktop.browse(URI.create(uri));
    }

    private static InputStream setupConnection(String url, String userAgent, int timeout, boolean useCaches) throws IOException {
        HttpURLConnection connection = ((HttpURLConnection) new URL(url).openConnection());
        connection.setRequestMethod("GET");
        connection.setUseCaches(useCaches);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.setReadTimeout(timeout);
        connection.setConnectTimeout(timeout);
        connection.setDoOutput(true);
        return connection.getInputStream();
    }

    private static String convertByteArrayToHexString(byte[] arrayBytes) {
        StringBuilder stringBuffer = new StringBuilder();
        for (byte arrayByte : arrayBytes) {
            stringBuffer.append(Integer.toString((arrayByte & 0xff) + 0x100, 16)
                    .substring(1));
        }
        return stringBuffer.toString();
    }
}