HttpUtil .java

net.minecraft.util.HttpUtil (class, 343 lines): members: downloadThreadsStarted, getSuitableLanPort, buildPostString, field_180193_a, postMap, get, logger.

net.minecraft.utilclass343 linescommon12.1 KB

API Surface (6)

String buildPostString(Map<String, Object> data)
String postMap(URL url, Map<String, Object> data, boolean skipLoggingErrors)
ListenableFuture<Object> downloadResourcePack(final File saveFile, final String packUrl, final Map<String, String> p_180192_2_, final int maxSize, final IProgressUpdate p_180192_4_, final Proxy p_180192_5_)
void run()
int getSuitableLanPort()
String get(URL url)

Fields & Constants (3)

field_180193_a
downloadThreadsStarted
logger

String literals (13)

"Content-Type"
"application/x-www-form-urlencoded"
"Content-Length"
"Content-Language"
"Could not post to "
"Downloading Resource Pack"
"Making Request..."
"Deleting "
" as it does not match what we currently have ("
" vs our "
", limit is "
", limit was "
"INTERRUPTED"

Code Graph: Dependencies (2)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

HttpUtil.java343 lines · MCP 1.8.9 · verbatimOriginal ↗
1
package net.minecraft.util;
2
3
import com.google.common.util.concurrent.ListenableFuture;
4
import com.google.common.util.concurrent.ListeningExecutorService;
5
import com.google.common.util.concurrent.MoreExecutors;
6
import com.google.common.util.concurrent.ThreadFactoryBuilder;
7
import java.io.BufferedReader;
8
import java.io.DataOutputStream;
9
import java.io.File;
10
import java.io.FileOutputStream;
11
import java.io.IOException;
12
import java.io.InputStream;
13
import java.io.InputStreamReader;
14
import java.io.OutputStream;
15
import java.io.UnsupportedEncodingException;
16
import java.net.HttpURLConnection;
17
import java.net.Proxy;
18
import java.net.ServerSocket;
19
import java.net.URL;
20
import java.net.URLEncoder;
21
import java.util.Map;
22
import java.util.Map.Entry;
23
import java.util.concurrent.Executors;
24
import java.util.concurrent.atomic.AtomicInteger;
25
import net.minecraft.server.MinecraftServer;
26
import org.apache.commons.io.FileUtils;
27
import org.apache.commons.io.IOUtils;
28
import org.apache.logging.log4j.LogManager;
29
import org.apache.logging.log4j.Logger;
30
31
public class HttpUtil
32
{
33
    public static final ListeningExecutorService field_180193_a = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool((new ThreadFactoryBuilder()).setDaemon(true).setNameFormat("Downloader %d").build()));
34
35
    /** The number of download threads that we have started so far. */
36
    private static final AtomicInteger downloadThreadsStarted = new AtomicInteger(0);
37
    private static final Logger logger = LogManager.getLogger();
38
39
    /**
40
     * Builds an encoded HTTP POST content string from a string map
41
     */
42
    public static String buildPostString(Map<String, Object> data)
43
    {
44
        StringBuilder stringbuilder = new StringBuilder();
45
46
        for (Entry<String, Object> entry : data.entrySet())
47
        {
48
            if (stringbuilder.length() > 0)
49
            {
50
                stringbuilder.append('&');
51
            }
52
53
            try
54
            {
55
                stringbuilder.append(URLEncoder.encode((String)entry.getKey(), "UTF-8"));
56
            }
57
            catch (UnsupportedEncodingException unsupportedencodingexception1)
58
            {
59
                unsupportedencodingexception1.printStackTrace();
60
            }
61
62
            if (entry.getValue() != null)
63
            {
64
                stringbuilder.append('=');
65
66
                try
67
                {
68
                    stringbuilder.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
69
                }
70
                catch (UnsupportedEncodingException unsupportedencodingexception)
71
                {
72
                    unsupportedencodingexception.printStackTrace();
73
                }
74
            }
75
        }
76
77
        return stringbuilder.toString();
78
    }
79
80
    /**
81
     * Sends a POST to the given URL using the map as the POST args
82
     */
83
    public static String postMap(URL url, Map<String, Object> data, boolean skipLoggingErrors)
84
    {
85
        return post(url, buildPostString(data), skipLoggingErrors);
86
    }
87
88
    /**
89
     * Sends a POST to the given URL
90
     */
91
    private static String post(URL url, String content, boolean skipLoggingErrors)
92
    {
93
        try
94
        {
95
            Proxy proxy = MinecraftServer.getServer() == null ? null : MinecraftServer.getServer().getServerProxy();
96
97
            if (proxy == null)
98
            {
99
                proxy = Proxy.NO_PROXY;
100
            }
101
102
            HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection(proxy);
103
            httpurlconnection.setRequestMethod("POST");
104
            httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
105
            httpurlconnection.setRequestProperty("Content-Length", "" + content.getBytes().length);
106
            httpurlconnection.setRequestProperty("Content-Language", "en-US");
107
            httpurlconnection.setUseCaches(false);
108
            httpurlconnection.setDoInput(true);
109
            httpurlconnection.setDoOutput(true);
110
            DataOutputStream dataoutputstream = new DataOutputStream(httpurlconnection.getOutputStream());
111
            dataoutputstream.writeBytes(content);
112
            dataoutputstream.flush();
113
            dataoutputstream.close();
114
            BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream()));
115
            StringBuffer stringbuffer = new StringBuffer();
116
            String s;
117
118
            while ((s = bufferedreader.readLine()) != null)
119
            {
120
                stringbuffer.append(s);
121
                stringbuffer.append('\r');
122
            }
123
124
            bufferedreader.close();
125
            return stringbuffer.toString();
126
        }
127
        catch (Exception exception)
128
        {
129
            if (!skipLoggingErrors)
130
            {
131
                logger.error((String)("Could not post to " + url), (Throwable)exception);
132
            }
133
134
            return "";
135
        }
136
    }
137
138
    public static ListenableFuture<Object> downloadResourcePack(final File saveFile, final String packUrl, final Map<String, String> p_180192_2_, final int maxSize, final IProgressUpdate p_180192_4_, final Proxy p_180192_5_)
139
    {
140
        ListenableFuture<?> listenablefuture = field_180193_a.submit(new Runnable()
141
        {
142
            public void run()
143
            {
144
                HttpURLConnection httpurlconnection = null;
145
                InputStream inputstream = null;
146
                OutputStream outputstream = null;
147
148
                if (p_180192_4_ != null)
149
                {
150
                    p_180192_4_.resetProgressAndMessage("Downloading Resource Pack");
151
                    p_180192_4_.displayLoadingString("Making Request...");
152
                }
153
154
                try
155
                {
156
                    try
157
                    {
158
                        byte[] abyte = new byte[4096];
159
                        URL url = new URL(packUrl);
160
                        httpurlconnection = (HttpURLConnection)url.openConnection(p_180192_5_);
161
                        float f = 0.0F;
162
                        float f1 = (float)p_180192_2_.entrySet().size();
163
164
                        for (Entry<String, String> entry : p_180192_2_.entrySet())
165
                        {
166
                            httpurlconnection.setRequestProperty((String)entry.getKey(), (String)entry.getValue());
167
168
                            if (p_180192_4_ != null)
169
                            {
170
                                p_180192_4_.setLoadingProgress((int)(++f / f1 * 100.0F));
171
                            }
172
                        }
173
174
                        inputstream = httpurlconnection.getInputStream();
175
                        f1 = (float)httpurlconnection.getContentLength();
176
                        int i = httpurlconnection.getContentLength();
177
178
                        if (p_180192_4_ != null)
179
                        {
180
                            p_180192_4_.displayLoadingString(String.format("Downloading file (%.2f MB)...", new Object[] {Float.valueOf(f1 / 1000.0F / 1000.0F)}));
181
                        }
182
183
                        if (saveFile.exists())
184
                        {
185
                            long j = saveFile.length();
186
187
                            if (j == (long)i)
188
                            {
189
                                if (p_180192_4_ != null)
190
                                {
191
                                    p_180192_4_.setDoneWorking();
192
                                }
193
194
                                return;
195
                            }
196
197
                            HttpUtil.logger.warn("Deleting " + saveFile + " as it does not match what we currently have (" + i + " vs our " + j + ").");
198
                            FileUtils.deleteQuietly(saveFile);
199
                        }
200
                        else if (saveFile.getParentFile() != null)
201
                        {
202
                            saveFile.getParentFile().mkdirs();
203
                        }
204
205
                        outputstream = new DataOutputStream(new FileOutputStream(saveFile));
206
207
                        if (maxSize > 0 && f1 > (float)maxSize)
208
                        {
209
                            if (p_180192_4_ != null)
210
                            {
211
                                p_180192_4_.setDoneWorking();
212
                            }
213
214
                            throw new IOException("Filesize is bigger than maximum allowed (file is " + f + ", limit is " + maxSize + ")");
215
                        }
216
217
                        int k = 0;
218
219
                        while ((k = inputstream.read(abyte)) >= 0)
220
                        {
221
                            f += (float)k;
222
223
                            if (p_180192_4_ != null)
224
                            {
225
                                p_180192_4_.setLoadingProgress((int)(f / f1 * 100.0F));
226
                            }
227
228
                            if (maxSize > 0 && f > (float)maxSize)
229
                            {
230
                                if (p_180192_4_ != null)
231
                                {
232
                                    p_180192_4_.setDoneWorking();
233
                                }
234
235
                                throw new IOException("Filesize was bigger than maximum allowed (got >= " + f + ", limit was " + maxSize + ")");
236
                            }
237
238
                            if (Thread.interrupted())
239
                            {
240
                                HttpUtil.logger.error("INTERRUPTED");
241
242
                                if (p_180192_4_ != null)
243
                                {
244
                                    p_180192_4_.setDoneWorking();
245
                                }
246
247
                                return;
248
                            }
249
250
                            outputstream.write(abyte, 0, k);
251
                        }
252
253
                        if (p_180192_4_ != null)
254
                        {
255
                            p_180192_4_.setDoneWorking();
256
                            return;
257
                        }
258
                    }
259
                    catch (Throwable throwable)
260
                    {
261
                        throwable.printStackTrace();
262
263
                        if (httpurlconnection != null)
264
                        {
265
                            InputStream inputstream1 = httpurlconnection.getErrorStream();
266
267
                            try
268
                            {
269
                                HttpUtil.logger.error(IOUtils.toString(inputstream1));
270
                            }
271
                            catch (IOException ioexception)
272
                            {
273
                                ioexception.printStackTrace();
274
                            }
275
                        }
276
277
                        if (p_180192_4_ != null)
278
                        {
279
                            p_180192_4_.setDoneWorking();
280
                            return;
281
                        }
282
                    }
283
                }
284
                finally
285
                {
286
                    IOUtils.closeQuietly(inputstream);
287
                    IOUtils.closeQuietly(outputstream);
288
                }
289
            }
290
        });
291
        return (ListenableFuture<Object>) listenablefuture;
292
    }
293
294
    public static int getSuitableLanPort() throws IOException
295
    {
296
        ServerSocket serversocket = null;
297
        int i = -1;
298
299
        try
300
        {
301
            serversocket = new ServerSocket(0);
302
            i = serversocket.getLocalPort();
303
        }
304
        finally
305
        {
306
            try
307
            {
308
                if (serversocket != null)
309
                {
310
                    serversocket.close();
311
                }
312
            }
313
            catch (IOException var8)
314
            {
315
                ;
316
            }
317
        }
318
319
        return i;
320
    }
321
322
    /**
323
     * Send a GET request to the given URL.
324
     */
325
    public static String get(URL url) throws IOException
326
    {
327
        HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection();
328
        httpurlconnection.setRequestMethod("GET");
329
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream()));
330
        StringBuilder stringbuilder = new StringBuilder();
331
        String s;
332
333
        while ((s = bufferedreader.readLine()) != null)
334
        {
335
            stringbuilder.append(s);
336
            stringbuilder.append('\r');
337
        }
338
339
        bufferedreader.close();
340
        return stringbuilder.toString();
341
    }
342
}
343

Deobfuscated MCP 1.8.9 source of HttpUtil from Marcelektro/MavenMCP-1.8.9 (net/minecraft/util/HttpUtil.java), stored verbatim.