|
| 1 | +package qz.ws; |
| 2 | + |
| 3 | +import org.eclipse.jetty.util.StaticException; |
| 4 | + |
| 5 | +import java.io.IOException; |
| 6 | +import java.nio.channels.ClosedChannelException; |
| 7 | +import java.util.Locale; |
| 8 | + |
| 9 | +/** |
| 10 | + * <code>ClosedChannelException</code> wrapper class for handling edge-cases where Jetty nests or hides |
| 11 | + * the underlying <code>Exception</code> cause. Inspired by #1300 and #1414 |
| 12 | + */ |
| 13 | +public class ClosedSocketException extends ClosedChannelException { |
| 14 | + public ClosedSocketException(String message) { |
| 15 | + super(); |
| 16 | + this.initCause(new IOException(message)); |
| 17 | + } |
| 18 | + |
| 19 | + public ClosedSocketException(Throwable t) { |
| 20 | + super(); |
| 21 | + this.initCause(t); |
| 22 | + } |
| 23 | + |
| 24 | + public static void filter(Throwable t) throws ClosedChannelException { |
| 25 | + Throwable throwable = t; |
| 26 | + while(true) { |
| 27 | + if(throwable instanceof ClosedChannelException) { |
| 28 | + throw (ClosedChannelException)throwable; |
| 29 | + } |
| 30 | + if(throwable != null) { |
| 31 | + throwable = throwable.getCause(); |
| 32 | + } else { |
| 33 | + break; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + if (messageMatchesClosed(t)) { |
| 38 | + throw new ClosedSocketException(t); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Check if a <code>Throwable</code> or its cause matches a <code>StaticException</code> |
| 44 | + * with "closed" in the message string. |
| 45 | + */ |
| 46 | + private static boolean messageMatchesClosed(Throwable t) { |
| 47 | + Throwable throwable = t; |
| 48 | + while(true) { |
| 49 | + if(throwable == null) { |
| 50 | + return false; |
| 51 | + } else if(!(throwable instanceof StaticException)) { |
| 52 | + // go deeper |
| 53 | + throwable = throwable.getCause(); |
| 54 | + } else { |
| 55 | + break; |
| 56 | + } |
| 57 | + } |
| 58 | + StaticException staticException = (StaticException)throwable; |
| 59 | + return staticException.getMessage() != null && staticException.getMessage().toLowerCase(Locale.ENGLISH).contains("closed"); |
| 60 | + } |
| 61 | +} |
0 commit comments