Skip to content

Commit e2a64e4

Browse files
authored
Merge pull request #182 from BobHanson/master
- adds UnknownHostException - "NetworkError" -- no wifi, method error 405, CORS error -- all throw UnknownHostExecption with responseCode set to 400 (but that is not retrievable, since getResponseCode() throws UHE!) - fixes incorrect HTTP response codes - fixes async return - implemented for Java (was just JavaScript) - adds SimpleHttpClient.createRequest(method,string)
2 parents 0625069 + 1d9f4b9 commit e2a64e4

File tree

11 files changed

+272
-96
lines changed

11 files changed

+272
-96
lines changed
1.22 KB
Binary file not shown.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
20201202180738
1+
20201203093348
1.22 KB
Binary file not shown.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
20201202180738
1+
20201203093348
1.22 KB
Binary file not shown.
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* This code is free software; you can redistribute it and/or modify it
6+
* under the terms of the GNU General Public License version 2 only, as
7+
* published by the Free Software Foundation. Oracle designates this
8+
* particular file as subject to the "Classpath" exception as provided
9+
* by Oracle in the LICENSE file that accompanied this code.
10+
*
11+
* This code is distributed in the hope that it will be useful, but WITHOUT
12+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14+
* version 2 for more details (a copy is included in the LICENSE file that
15+
* accompanied this code).
16+
*
17+
* You should have received a copy of the GNU General Public License version
18+
* 2 along with this work; if not, write to the Free Software Foundation,
19+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20+
*
21+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22+
* or visit www.oracle.com if you need additional information or have any
23+
* questions.
24+
*/
25+
26+
package java.net;
27+
28+
import java.io.IOException;
29+
30+
/**
31+
* Thrown to indicate that the IP address of a host could not be determined.
32+
*
33+
* @author Jonathan Payne
34+
* @since JDK1.0
35+
*/
36+
public
37+
class UnknownHostException extends IOException {
38+
private static final long serialVersionUID = -4639126076052875403L;
39+
40+
/**
41+
* Constructs a new {@code UnknownHostException} with the
42+
* specified detail message.
43+
*
44+
* @param host the detail message.
45+
*/
46+
public UnknownHostException(String host) {
47+
super(host);
48+
}
49+
50+
/**
51+
* Constructs a new {@code UnknownHostException} with no detail
52+
* message.
53+
*/
54+
public UnknownHostException() {
55+
}
56+
}

sources/net.sf.j2s.java.core/src/javajs/http/SimpleHttpClient.java

Lines changed: 89 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@
99
import java.net.HttpURLConnection;
1010
import java.net.MalformedURLException;
1111
import java.net.URI;
12+
import java.net.URISyntaxException;
1213
import java.net.URL;
1314
import java.net.URLEncoder;
15+
import java.net.UnknownHostException;
1416
import java.util.ArrayList;
1517
import java.util.HashMap;
1618
import java.util.LinkedHashMap;
@@ -43,7 +45,7 @@
4345
* @author Mateusz Warowny
4446
*
4547
*/
46-
class SimpleHttpClient implements HttpClient {
48+
public class SimpleHttpClient implements HttpClient {
4749

4850
SimpleHttpClient() {
4951
// for reflection
@@ -315,6 +317,7 @@ public void executeAsync(Consumer<HttpResponse> succeed,
315317
}
316318

317319
private HttpResponse executeImpl(Response r) {
320+
318321
Runnable runner = new Runnable() {
319322

320323
@Override
@@ -424,6 +427,8 @@ private HttpURLConnection getConnection(URL url) throws IOException {
424427

425428
class Response implements HttpResponse {
426429

430+
private final static int BAD_REQUEST = 400;
431+
427432
int state = 0;
428433

429434
/**
@@ -473,8 +478,8 @@ class Response implements HttpResponse {
473478
* getResponseCode() is called.)
474479
*
475480
* @param conn
476-
* @param request
477-
* @return Response
481+
* @param request
482+
* @return Response
478483
*
479484
* @throws IOException
480485
*/
@@ -491,34 +496,39 @@ Response getResponse(HttpURLConnection conn, Request request) throws IOException
491496
}
492497

493498
new Thread(() -> {
494-
// asynchronous methods cannot throw an exception.
495-
IOException exception = null;
499+
// asynchronous methods cannot throw an exception.
500+
IOException exception = null;
501+
try {
496502
if (method.equals(HttpRequest.METHOD_HEAD)) {
497-
try {
498-
state = conn.getResponseCode();
499-
} catch (IOException e) {
500-
exception = e;
501-
}
502-
doCallback(exception);
503+
state = conn.getResponseCode();
503504
} else {
504-
@SuppressWarnings("unused")
505-
Function<byte[], Void> f = new Function<byte[], Void>() {
506-
507-
@Override
508-
public Void apply(byte[] t) {
509-
state = 400; // Bad Request?
510-
try {
511-
state = SimpleHttpClient.Response.this.conn.getResponseCode();
512-
} catch (IOException e) {
513-
}
514-
doCallback(null);
515-
return null;
516-
}
517-
518-
};
519-
/** @j2sNative conn.getBytesAsync$java_util_function_Function(f) */
505+
@SuppressWarnings("unused")
506+
Function<byte[], Void> f = new Function<byte[], Void>() {
507+
508+
@Override
509+
public Void apply(byte[] t) {
510+
state = 400; // Bad Request?
511+
try {
512+
state = SimpleHttpClient.Response.this.conn.getResponseCode();
513+
doCallback(null);
514+
} catch (IOException e) {
515+
doCallback(e);
516+
}
517+
return null;
518+
}
519+
520+
};
521+
/** @j2sNative return conn.getBytesAsync$java_util_function_Function(f); */
522+
{
523+
f.apply(null);
524+
return;
525+
}
520526
}
521-
527+
} catch (IOException e) {
528+
exception = e;
529+
}
530+
doCallback(exception);
531+
522532
}).start();
523533
return this;
524534
}
@@ -550,6 +560,8 @@ protected boolean handleError(Throwable e) {
550560
if (!(e instanceof IOException)) {
551561
e = new IOException(e);
552562
}
563+
if (e instanceof UnknownHostException)
564+
state = BAD_REQUEST;
553565
IOException exception = (IOException) e;
554566
// setting e = null to indicated handled.
555567
if (isAsync) {
@@ -593,16 +605,33 @@ public Map<String, String> getHeaders() {
593605

594606
@Override
595607
public String getText() throws IOException {
596-
return new String( getBytes(getContent()));
608+
return new String(getBytes(getContent()));
597609
}
598610

599611
/**
600612
* In SwingJS, this is always a ByteArrayInputStream.
613+
* @throws IOException
601614
*/
602615
@Override
603616
public InputStream getContent() throws IOException {
604-
return (inputStream == null ? (inputStream = conn.getInputStream())
605-
: inputStream);
617+
if (conn == null)
618+
throw new IOException("Connection could not be opened");
619+
try {
620+
return (inputStream == null ? (inputStream = conn.getInputStream())
621+
: inputStream);
622+
} catch (IOException e) {
623+
if (state < 400)
624+
state = decodeServerException(e.toString());
625+
throw new IOException(e);
626+
}
627+
}
628+
629+
private int decodeServerException(String msg) {
630+
try {
631+
return Integer.parseInt(msg.substring(msg.indexOf("code:") + 5));
632+
} catch (Exception e) {
633+
}
634+
return 404;
606635
}
607636

608637
@Override
@@ -612,26 +641,49 @@ public void close() {
612641

613642
@Override
614643
public String toString() {
615-
return "JSHttpClient " + method + " state=" + state + " uri=" + uri;
644+
return "SimpleHttpClient " + method + " state=" + state + " uri=" + uri;
616645
}
617646

618647
}
619648

620-
public static String getBytes(InputStream is) throws IOException {
649+
public static byte[] getBytes(InputStream is) throws IOException {
621650

622651
// Java 9 version is better:
623-
// return new String(is.readAllBytes());
652+
// return is.readAllBytes();
624653

625654
ByteArrayOutputStream bos = new ByteArrayOutputStream(0x4000);
626655
byte[] buf = new byte[0x4000];
627-
int n = 0, ntotal = 0;
656+
int n = 0;
628657
while((n = is.read(buf)) >= 0) {
629-
ntotal += n;
630658
bos.write(buf, 0, n);
631659
}
632660
is.close();
633-
return new String(bos.toByteArray(), 0, ntotal);
661+
return bos.toByteArray();
634662

635663
}
636664

665+
public static HttpRequest createRequest(HttpClient client, String method, String url) throws IOException {
666+
667+
URI uri = null;
668+
try {
669+
uri = new URI(url);
670+
} catch (URISyntaxException e) {
671+
throw new IOException(e);
672+
}
673+
switch (method.toUpperCase()) {
674+
case "HEAD":
675+
return client.head(uri);
676+
case "GET":
677+
return client.get(uri);
678+
case "POST":
679+
return client.post(uri);
680+
case "PUT":
681+
return client.put(uri);
682+
case "DELETE":
683+
return client.delete(uri);
684+
default:
685+
throw new IOException("Unknown method:" + method);
686+
}
687+
}
688+
637689
}

sources/net.sf.j2s.java.core/src/javajs/util/AjaxURLConnection.java

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import java.net.HttpURLConnection;
1010
import java.net.URL;
1111
import java.net.URLConnection;
12+
import java.net.UnknownHostException;
1213
import java.util.ArrayList;
1314
import java.util.Arrays;
1415
import java.util.HashMap;
@@ -146,6 +147,8 @@ private Object doAjax(boolean isBinary, Function<Object, Void> whenDone) {
146147
* info = info || {}; if (!info.dataType) { info.isBinary =
147148
* !!isBinary; }
148149
*
150+
* info.type = this.method;
151+
*
149152
* whenDone && (info.fWhenDone =
150153
* function(data){whenDone.apply$O(data)});
151154
*
@@ -251,8 +254,15 @@ private void setJQueryResponseCodeFromJQuery(Object result) {
251254
* result[1] == 10); if (isEmpty) result = new Int8Array;
252255
*/
253256

254-
responseCode = isEmpty ? HTTP_NOT_FOUND : /** @j2sNative info.xhr.status || */
255-
0;
257+
responseCode = (!isEmpty ? /** @j2sNative info.xhr.status || */
258+
0 : getAJAXStatusError());
259+
}
260+
261+
private int getAJAXStatusError() {
262+
@SuppressWarnings("unused")
263+
Object info = this.info;
264+
// AJAX cannot distinguish among a network connection error, a method (PUT) error, or a file not found
265+
return /** @j2sNative !info.xhr.statusText || (info.xhr.statusText+"").indexOf("NetworkError:") == 0 ? 400 : */HTTP_NOT_FOUND;
256266
}
257267

258268
private String getFileDocumentDir() {
@@ -328,9 +338,10 @@ private byte[] getBytesOut() {
328338
//
329339

330340
if (formData != null) {
341+
String method = ("GET".equals(this.method) ? "POST" : this.method);
331342
Object map = ajax = (/**
332343
* @j2sNative 1 ? { data:new FormData(), processData:false, contentType:false,
333-
* type:"POST", j2sNoProxy:true } :
344+
* type:method, j2sNoProxy:true } :
334345
*/
335346
null);
336347
if (formData instanceof Map<?, ?>) {
@@ -389,12 +400,15 @@ public OutputStream getOutputStream() throws IOException {
389400

390401
@SuppressWarnings({ "null", "unused" })
391402
@Override
392-
public InputStream getInputStream() throws FileNotFoundException {
403+
public InputStream getInputStream() throws IOException {
393404
BufferedInputStream is = /** @j2sNative this.is || */null;
394405
if (is != null)
395406
return is;
396407
responseCode = -1;
397408
is = getInputStreamAndResponse(false);
409+
if (responseCode == HTTP_BAD_REQUEST) {
410+
throw new UnknownHostException(url.toString());
411+
}
398412
if (is == null)
399413
throw new FileNotFoundException("opening " + url);
400414
return is;
@@ -551,10 +565,14 @@ private String getCacheKey() {
551565

552566
@SuppressWarnings("unused")
553567
private boolean isNetworkError(BufferedInputStream is) {
554-
if (is != null) {
555-
if (responseCode > 0) {
556-
return (responseCode >= 400);
568+
if (responseCode > 0) {
569+
return (responseCode >= HTTP_BAD_REQUEST);
570+
}
571+
if (is == null) {
572+
if (ajax != null) {
573+
responseCode = getAJAXStatusError();
557574
}
575+
} else {
558576
responseCode = HTTP_OK;
559577
if (/** @j2sNative is._jsonData || */
560578
false)
@@ -635,7 +653,11 @@ public int getResponseCode() throws IOException {
635653
try {
636654
getInputStreamAndResponse(true);
637655
} catch (Exception e) {
656+
responseCode = HTTP_BAD_REQUEST;
638657
}
658+
}
659+
if (responseCode == HTTP_BAD_REQUEST) {
660+
throw new UnknownHostException(url.toString());
639661
}
640662
return responseCode;
641663
}

0 commit comments

Comments
 (0)