id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
16,700
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.proxyHandler
public static ProxyHandler proxyHandler(ProxyClient proxyClient, HttpHandler next) { return ProxyHandler.builder().setProxyClient(proxyClient).setNext(next).build(); }
java
public static ProxyHandler proxyHandler(ProxyClient proxyClient, HttpHandler next) { return ProxyHandler.builder().setProxyClient(proxyClient).setNext(next).build(); }
[ "public", "static", "ProxyHandler", "proxyHandler", "(", "ProxyClient", "proxyClient", ",", "HttpHandler", "next", ")", "{", "return", "ProxyHandler", ".", "builder", "(", ")", ".", "setProxyClient", "(", "proxyClient", ")", ".", "setNext", "(", "next", ")", ".", "build", "(", ")", ";", "}" ]
Returns a handler that can act as a load balancing reverse proxy. @param proxyClient The proxy client to use to connect to the remote server @param next The next handler to invoke if the proxy client does not know how to proxy the request @return The proxy handler
[ "Returns", "a", "handler", "that", "can", "act", "as", "a", "load", "balancing", "reverse", "proxy", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L498-L500
16,701
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.learningPushHandler
public static LearningPushHandler learningPushHandler(int maxEntries, int maxAge, HttpHandler next) { return new LearningPushHandler(maxEntries, maxAge, next); }
java
public static LearningPushHandler learningPushHandler(int maxEntries, int maxAge, HttpHandler next) { return new LearningPushHandler(maxEntries, maxAge, next); }
[ "public", "static", "LearningPushHandler", "learningPushHandler", "(", "int", "maxEntries", ",", "int", "maxAge", ",", "HttpHandler", "next", ")", "{", "return", "new", "LearningPushHandler", "(", "maxEntries", ",", "maxAge", ",", "next", ")", ";", "}" ]
Creates a handler that automatically learns which resources to push based on the referer header @param maxEntries The maximum number of entries to store @param maxAge The maximum age of the entries @param next The next handler @return A caching push handler
[ "Creates", "a", "handler", "that", "automatically", "learns", "which", "resources", "to", "push", "based", "on", "the", "referer", "header" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L561-L563
16,702
undertow-io/undertow
core/src/main/java/io/undertow/client/http/HttpResponseParser.java
HttpResponseParser.handleStatusCode
@SuppressWarnings("unused") final void handleStatusCode(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) { StringBuilder stringBuilder = state.stringBuilder; while (buffer.hasRemaining()) { final char next = (char) buffer.get(); if (next == ' ' || next == '\t') { builder.setStatusCode(Integer.parseInt(stringBuilder.toString())); state.state = ResponseParseState.REASON_PHRASE; state.stringBuilder.setLength(0); state.parseState = 0; state.pos = 0; state.nextHeader = null; return; } else { stringBuilder.append(next); } } }
java
@SuppressWarnings("unused") final void handleStatusCode(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) { StringBuilder stringBuilder = state.stringBuilder; while (buffer.hasRemaining()) { final char next = (char) buffer.get(); if (next == ' ' || next == '\t') { builder.setStatusCode(Integer.parseInt(stringBuilder.toString())); state.state = ResponseParseState.REASON_PHRASE; state.stringBuilder.setLength(0); state.parseState = 0; state.pos = 0; state.nextHeader = null; return; } else { stringBuilder.append(next); } } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "final", "void", "handleStatusCode", "(", "ByteBuffer", "buffer", ",", "ResponseParseState", "state", ",", "HttpResponseBuilder", "builder", ")", "{", "StringBuilder", "stringBuilder", "=", "state", ".", "stringBuilder", ";", "while", "(", "buffer", ".", "hasRemaining", "(", ")", ")", "{", "final", "char", "next", "=", "(", "char", ")", "buffer", ".", "get", "(", ")", ";", "if", "(", "next", "==", "'", "'", "||", "next", "==", "'", "'", ")", "{", "builder", ".", "setStatusCode", "(", "Integer", ".", "parseInt", "(", "stringBuilder", ".", "toString", "(", ")", ")", ")", ";", "state", ".", "state", "=", "ResponseParseState", ".", "REASON_PHRASE", ";", "state", ".", "stringBuilder", ".", "setLength", "(", "0", ")", ";", "state", ".", "parseState", "=", "0", ";", "state", ".", "pos", "=", "0", ";", "state", ".", "nextHeader", "=", "null", ";", "return", ";", "}", "else", "{", "stringBuilder", ".", "append", "(", "next", ")", ";", "}", "}", "}" ]
Parses the status code. This is called from the generated bytecode. @param buffer The buffer @param state The current state @param builder The exchange builder @return The number of bytes remaining
[ "Parses", "the", "status", "code", ".", "This", "is", "called", "from", "the", "generated", "bytecode", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/client/http/HttpResponseParser.java#L175-L192
16,703
undertow-io/undertow
core/src/main/java/io/undertow/client/http/HttpResponseParser.java
HttpResponseParser.handleReasonPhrase
@SuppressWarnings("unused") final void handleReasonPhrase(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) { StringBuilder stringBuilder = state.stringBuilder; while (buffer.hasRemaining()) { final char next = (char) buffer.get(); if (next == '\n' || next == '\r') { builder.setReasonPhrase(stringBuilder.toString()); state.state = ResponseParseState.AFTER_REASON_PHRASE; state.stringBuilder.setLength(0); state.parseState = 0; state.leftOver = (byte) next; state.pos = 0; state.nextHeader = null; return; } else { stringBuilder.append(next); } } }
java
@SuppressWarnings("unused") final void handleReasonPhrase(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) { StringBuilder stringBuilder = state.stringBuilder; while (buffer.hasRemaining()) { final char next = (char) buffer.get(); if (next == '\n' || next == '\r') { builder.setReasonPhrase(stringBuilder.toString()); state.state = ResponseParseState.AFTER_REASON_PHRASE; state.stringBuilder.setLength(0); state.parseState = 0; state.leftOver = (byte) next; state.pos = 0; state.nextHeader = null; return; } else { stringBuilder.append(next); } } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "final", "void", "handleReasonPhrase", "(", "ByteBuffer", "buffer", ",", "ResponseParseState", "state", ",", "HttpResponseBuilder", "builder", ")", "{", "StringBuilder", "stringBuilder", "=", "state", ".", "stringBuilder", ";", "while", "(", "buffer", ".", "hasRemaining", "(", ")", ")", "{", "final", "char", "next", "=", "(", "char", ")", "buffer", ".", "get", "(", ")", ";", "if", "(", "next", "==", "'", "'", "||", "next", "==", "'", "'", ")", "{", "builder", ".", "setReasonPhrase", "(", "stringBuilder", ".", "toString", "(", ")", ")", ";", "state", ".", "state", "=", "ResponseParseState", ".", "AFTER_REASON_PHRASE", ";", "state", ".", "stringBuilder", ".", "setLength", "(", "0", ")", ";", "state", ".", "parseState", "=", "0", ";", "state", ".", "leftOver", "=", "(", "byte", ")", "next", ";", "state", ".", "pos", "=", "0", ";", "state", ".", "nextHeader", "=", "null", ";", "return", ";", "}", "else", "{", "stringBuilder", ".", "append", "(", "next", ")", ";", "}", "}", "}" ]
Parses the reason phrase. This is called from the generated bytecode. @param buffer The buffer @param state The current state @param builder The exchange builder @return The number of bytes remaining
[ "Parses", "the", "reason", "phrase", ".", "This", "is", "called", "from", "the", "generated", "bytecode", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/client/http/HttpResponseParser.java#L202-L220
16,704
undertow-io/undertow
core/src/main/java/io/undertow/client/http/HttpResponseParser.java
HttpResponseParser.httpStrings
protected static Map<String, HttpString> httpStrings() { final Map<String, HttpString> results = new HashMap<>(); final Class[] classs = {Headers.class, Methods.class, Protocols.class}; for (Class<?> c : classs) { for (Field field : c.getDeclaredFields()) { if (field.getType().equals(HttpString.class)) { field.setAccessible(true); HttpString result = null; try { result = (HttpString) field.get(null); results.put(result.toString(), result); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } } return results; }
java
protected static Map<String, HttpString> httpStrings() { final Map<String, HttpString> results = new HashMap<>(); final Class[] classs = {Headers.class, Methods.class, Protocols.class}; for (Class<?> c : classs) { for (Field field : c.getDeclaredFields()) { if (field.getType().equals(HttpString.class)) { field.setAccessible(true); HttpString result = null; try { result = (HttpString) field.get(null); results.put(result.toString(), result); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } } return results; }
[ "protected", "static", "Map", "<", "String", ",", "HttpString", ">", "httpStrings", "(", ")", "{", "final", "Map", "<", "String", ",", "HttpString", ">", "results", "=", "new", "HashMap", "<>", "(", ")", ";", "final", "Class", "[", "]", "classs", "=", "{", "Headers", ".", "class", ",", "Methods", ".", "class", ",", "Protocols", ".", "class", "}", ";", "for", "(", "Class", "<", "?", ">", "c", ":", "classs", ")", "{", "for", "(", "Field", "field", ":", "c", ".", "getDeclaredFields", "(", ")", ")", "{", "if", "(", "field", ".", "getType", "(", ")", ".", "equals", "(", "HttpString", ".", "class", ")", ")", "{", "field", ".", "setAccessible", "(", "true", ")", ";", "HttpString", "result", "=", "null", ";", "try", "{", "result", "=", "(", "HttpString", ")", "field", ".", "get", "(", "null", ")", ";", "results", ".", "put", "(", "result", ".", "toString", "(", ")", ",", "result", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "}", "}", "return", "results", ";", "}" ]
This is a bit of hack to enable the parser to get access to the HttpString's that are sorted in the static fields of the relevant classes. This means that in most cases a HttpString comparison will take the fast path == route, as they will be the same object @return
[ "This", "is", "a", "bit", "of", "hack", "to", "enable", "the", "parser", "to", "get", "access", "to", "the", "HttpString", "s", "that", "are", "sorted", "in", "the", "static", "fields", "of", "the", "relevant", "classes", ".", "This", "means", "that", "in", "most", "cases", "a", "HttpString", "comparison", "will", "take", "the", "fast", "path", "==", "route", "as", "they", "will", "be", "the", "same", "object" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/client/http/HttpResponseParser.java#L353-L373
16,705
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModCluster.java
ModCluster.createProxyHandler
public HttpHandler createProxyHandler() { return ProxyHandler.builder() .setProxyClient(container.getProxyClient()) .setMaxRequestTime(maxRequestTime) .setMaxConnectionRetries(maxRetries) .setReuseXForwarded(reuseXForwarded) .build(); }
java
public HttpHandler createProxyHandler() { return ProxyHandler.builder() .setProxyClient(container.getProxyClient()) .setMaxRequestTime(maxRequestTime) .setMaxConnectionRetries(maxRetries) .setReuseXForwarded(reuseXForwarded) .build(); }
[ "public", "HttpHandler", "createProxyHandler", "(", ")", "{", "return", "ProxyHandler", ".", "builder", "(", ")", ".", "setProxyClient", "(", "container", ".", "getProxyClient", "(", ")", ")", ".", "setMaxRequestTime", "(", "maxRequestTime", ")", ".", "setMaxConnectionRetries", "(", "maxRetries", ")", ".", "setReuseXForwarded", "(", "reuseXForwarded", ")", ".", "build", "(", ")", ";", "}" ]
Get the handler proxying the requests. @return the proxy handler
[ "Get", "the", "handler", "proxying", "the", "requests", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModCluster.java#L153-L160
16,706
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModCluster.java
ModCluster.advertise
public synchronized void advertise(MCMPConfig config) throws IOException { final MCMPConfig.AdvertiseConfig advertiseConfig = config.getAdvertiseConfig(); if (advertiseConfig == null) { throw new IllegalArgumentException("advertise not enabled"); } MCMPAdvertiseTask.advertise(container, advertiseConfig, xnioWorker); }
java
public synchronized void advertise(MCMPConfig config) throws IOException { final MCMPConfig.AdvertiseConfig advertiseConfig = config.getAdvertiseConfig(); if (advertiseConfig == null) { throw new IllegalArgumentException("advertise not enabled"); } MCMPAdvertiseTask.advertise(container, advertiseConfig, xnioWorker); }
[ "public", "synchronized", "void", "advertise", "(", "MCMPConfig", "config", ")", "throws", "IOException", "{", "final", "MCMPConfig", ".", "AdvertiseConfig", "advertiseConfig", "=", "config", ".", "getAdvertiseConfig", "(", ")", ";", "if", "(", "advertiseConfig", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"advertise not enabled\"", ")", ";", "}", "MCMPAdvertiseTask", ".", "advertise", "(", "container", ",", "advertiseConfig", ",", "xnioWorker", ")", ";", "}" ]
Start advertising a mcmp handler. @param config the mcmp handler config @throws IOException
[ "Start", "advertising", "a", "mcmp", "handler", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModCluster.java#L189-L195
16,707
undertow-io/undertow
core/src/main/java/io/undertow/util/LegacyCookieSupport.java
LegacyCookieSupport.isV0Separator
private static boolean isV0Separator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c)); } } return V0_SEPARATOR_FLAGS[c]; }
java
private static boolean isV0Separator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c)); } } return V0_SEPARATOR_FLAGS[c]; }
[ "private", "static", "boolean", "isV0Separator", "(", "final", "char", "c", ")", "{", "if", "(", "c", "<", "0x20", "||", "c", ">=", "0x7f", ")", "{", "if", "(", "c", "!=", "0x09", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "invalidControlCharacter", "(", "Integer", ".", "toString", "(", "c", ")", ")", ";", "}", "}", "return", "V0_SEPARATOR_FLAGS", "[", "c", "]", ";", "}" ]
Returns true if the byte is a separator as defined by V0 of the cookie spec.
[ "Returns", "true", "if", "the", "byte", "is", "a", "separator", "as", "defined", "by", "V0", "of", "the", "cookie", "spec", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/LegacyCookieSupport.java#L110-L118
16,708
undertow-io/undertow
core/src/main/java/io/undertow/util/LegacyCookieSupport.java
LegacyCookieSupport.isHttpSeparator
private static boolean isHttpSeparator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c)); } } return HTTP_SEPARATOR_FLAGS[c]; }
java
private static boolean isHttpSeparator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c)); } } return HTTP_SEPARATOR_FLAGS[c]; }
[ "private", "static", "boolean", "isHttpSeparator", "(", "final", "char", "c", ")", "{", "if", "(", "c", "<", "0x20", "||", "c", ">=", "0x7f", ")", "{", "if", "(", "c", "!=", "0x09", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "invalidControlCharacter", "(", "Integer", ".", "toString", "(", "c", ")", ")", ";", "}", "}", "return", "HTTP_SEPARATOR_FLAGS", "[", "c", "]", ";", "}" ]
Returns true if the byte is a separator as defined by V1 of the cookie spec, RFC2109. @throws IllegalArgumentException if a control character was supplied as input
[ "Returns", "true", "if", "the", "byte", "is", "a", "separator", "as", "defined", "by", "V1", "of", "the", "cookie", "spec", "RFC2109", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/LegacyCookieSupport.java#L146-L154
16,709
undertow-io/undertow
core/src/main/java/io/undertow/util/LegacyCookieSupport.java
LegacyCookieSupport.maybeQuote
public static void maybeQuote(StringBuilder buf, String value) { if (value==null || value.length()==0) { buf.append("\"\""); } else if (alreadyQuoted(value)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,1,value.length()-1)); buf.append('"'); } else if ((isHttpToken(value) && !ALLOW_HTTP_SEPARATORS_IN_V0) || (isV0Token(value) && ALLOW_HTTP_SEPARATORS_IN_V0)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); } else { buf.append(value); } }
java
public static void maybeQuote(StringBuilder buf, String value) { if (value==null || value.length()==0) { buf.append("\"\""); } else if (alreadyQuoted(value)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,1,value.length()-1)); buf.append('"'); } else if ((isHttpToken(value) && !ALLOW_HTTP_SEPARATORS_IN_V0) || (isV0Token(value) && ALLOW_HTTP_SEPARATORS_IN_V0)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); } else { buf.append(value); } }
[ "public", "static", "void", "maybeQuote", "(", "StringBuilder", "buf", ",", "String", "value", ")", "{", "if", "(", "value", "==", "null", "||", "value", ".", "length", "(", ")", "==", "0", ")", "{", "buf", ".", "append", "(", "\"\\\"\\\"\"", ")", ";", "}", "else", "if", "(", "alreadyQuoted", "(", "value", ")", ")", "{", "buf", ".", "append", "(", "'", "'", ")", ";", "buf", ".", "append", "(", "escapeDoubleQuotes", "(", "value", ",", "1", ",", "value", ".", "length", "(", ")", "-", "1", ")", ")", ";", "buf", ".", "append", "(", "'", "'", ")", ";", "}", "else", "if", "(", "(", "isHttpToken", "(", "value", ")", "&&", "!", "ALLOW_HTTP_SEPARATORS_IN_V0", ")", "||", "(", "isV0Token", "(", "value", ")", "&&", "ALLOW_HTTP_SEPARATORS_IN_V0", ")", ")", "{", "buf", ".", "append", "(", "'", "'", ")", ";", "buf", ".", "append", "(", "escapeDoubleQuotes", "(", "value", ",", "0", ",", "value", ".", "length", "(", ")", ")", ")", ";", "buf", ".", "append", "(", "'", "'", ")", ";", "}", "else", "{", "buf", ".", "append", "(", "value", ")", ";", "}", "}" ]
Quotes values if required. @param buf @param value
[ "Quotes", "values", "if", "required", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/LegacyCookieSupport.java#L186-L201
16,710
undertow-io/undertow
core/src/main/java/io/undertow/util/LegacyCookieSupport.java
LegacyCookieSupport.escapeDoubleQuotes
private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) { if (s == null || s.length() == 0 || s.indexOf('"') == -1) { return s; } StringBuilder b = new StringBuilder(); for (int i = beginIndex; i < endIndex; i++) { char c = s.charAt(i); if (c == '\\' ) { b.append(c); //ignore the character after an escape, just append it if (++i>=endIndex) throw UndertowMessages.MESSAGES.invalidEscapeCharacter(); b.append(s.charAt(i)); } else if (c == '"') b.append('\\').append('"'); else b.append(c); } return b.toString(); }
java
private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) { if (s == null || s.length() == 0 || s.indexOf('"') == -1) { return s; } StringBuilder b = new StringBuilder(); for (int i = beginIndex; i < endIndex; i++) { char c = s.charAt(i); if (c == '\\' ) { b.append(c); //ignore the character after an escape, just append it if (++i>=endIndex) throw UndertowMessages.MESSAGES.invalidEscapeCharacter(); b.append(s.charAt(i)); } else if (c == '"') b.append('\\').append('"'); else b.append(c); } return b.toString(); }
[ "private", "static", "String", "escapeDoubleQuotes", "(", "String", "s", ",", "int", "beginIndex", ",", "int", "endIndex", ")", "{", "if", "(", "s", "==", "null", "||", "s", ".", "length", "(", ")", "==", "0", "||", "s", ".", "indexOf", "(", "'", "'", ")", "==", "-", "1", ")", "{", "return", "s", ";", "}", "StringBuilder", "b", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "beginIndex", ";", "i", "<", "endIndex", ";", "i", "++", ")", "{", "char", "c", "=", "s", ".", "charAt", "(", "i", ")", ";", "if", "(", "c", "==", "'", "'", ")", "{", "b", ".", "append", "(", "c", ")", ";", "//ignore the character after an escape, just append it", "if", "(", "++", "i", ">=", "endIndex", ")", "throw", "UndertowMessages", ".", "MESSAGES", ".", "invalidEscapeCharacter", "(", ")", ";", "b", ".", "append", "(", "s", ".", "charAt", "(", "i", ")", ")", ";", "}", "else", "if", "(", "c", "==", "'", "'", ")", "b", ".", "append", "(", "'", "'", ")", ".", "append", "(", "'", "'", ")", ";", "else", "b", ".", "append", "(", "c", ")", ";", "}", "return", "b", ".", "toString", "(", ")", ";", "}" ]
Escapes any double quotes in the given string. @param s the input string @param beginIndex start index inclusive @param endIndex exclusive @return The (possibly) escaped string
[ "Escapes", "any", "double", "quotes", "in", "the", "given", "string", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/LegacyCookieSupport.java#L211-L232
16,711
undertow-io/undertow
core/src/main/java/io/undertow/protocols/ssl/ALPNHackServerHelloExplorer.java
ALPNHackServerHelloExplorer.removeAlpnExtensionsFromServerHello
static byte[] removeAlpnExtensionsFromServerHello(ByteBuffer source, final AtomicReference<String> selectedAlpnProtocol) throws SSLException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { exploreHandshake(source, source.remaining(), selectedAlpnProtocol, out); //we need to adjust the record length; int serverHelloLength = out.size() - 4; byte[] data = out.toByteArray(); //now we need to adjust the handshake frame length data[1] = (byte) ((serverHelloLength >> 16) & 0xFF); data[2] = (byte) ((serverHelloLength >> 8) & 0xFF); data[3] = (byte) (serverHelloLength & 0xFF); return data; } catch (AlpnProcessingException e) { return null; } }
java
static byte[] removeAlpnExtensionsFromServerHello(ByteBuffer source, final AtomicReference<String> selectedAlpnProtocol) throws SSLException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { exploreHandshake(source, source.remaining(), selectedAlpnProtocol, out); //we need to adjust the record length; int serverHelloLength = out.size() - 4; byte[] data = out.toByteArray(); //now we need to adjust the handshake frame length data[1] = (byte) ((serverHelloLength >> 16) & 0xFF); data[2] = (byte) ((serverHelloLength >> 8) & 0xFF); data[3] = (byte) (serverHelloLength & 0xFF); return data; } catch (AlpnProcessingException e) { return null; } }
[ "static", "byte", "[", "]", "removeAlpnExtensionsFromServerHello", "(", "ByteBuffer", "source", ",", "final", "AtomicReference", "<", "String", ">", "selectedAlpnProtocol", ")", "throws", "SSLException", "{", "ByteArrayOutputStream", "out", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "try", "{", "exploreHandshake", "(", "source", ",", "source", ".", "remaining", "(", ")", ",", "selectedAlpnProtocol", ",", "out", ")", ";", "//we need to adjust the record length;", "int", "serverHelloLength", "=", "out", ".", "size", "(", ")", "-", "4", ";", "byte", "[", "]", "data", "=", "out", ".", "toByteArray", "(", ")", ";", "//now we need to adjust the handshake frame length", "data", "[", "1", "]", "=", "(", "byte", ")", "(", "(", "serverHelloLength", ">>", "16", ")", "&", "0xFF", ")", ";", "data", "[", "2", "]", "=", "(", "byte", ")", "(", "(", "serverHelloLength", ">>", "8", ")", "&", "0xFF", ")", ";", "data", "[", "3", "]", "=", "(", "byte", ")", "(", "serverHelloLength", "&", "0xFF", ")", ";", "return", "data", ";", "}", "catch", "(", "AlpnProcessingException", "e", ")", "{", "return", "null", ";", "}", "}" ]
removes the ALPN extensions from the server hello @param source @return @throws SSLException
[ "removes", "the", "ALPN", "extensions", "from", "the", "server", "hello" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/ssl/ALPNHackServerHelloExplorer.java#L81-L100
16,712
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.findTarget
public ModClusterProxyTarget findTarget(final HttpServerExchange exchange) { // There is an option to disable the virtual host check, probably a default virtual host final PathMatcher.PathMatch<VirtualHost.HostEntry> entry = mapVirtualHost(exchange); if (entry == null) { return null; } for (final Balancer balancer : balancers.values()) { final Map<String, Cookie> cookies = exchange.getRequestCookies(); if (balancer.isStickySession()) { if (cookies.containsKey(balancer.getStickySessionCookie())) { String sessionId = cookies.get(balancer.getStickySessionCookie()).getValue(); Iterator<CharSequence> routes = parseRoutes(sessionId); if (routes.hasNext()) { return new ModClusterProxyTarget.ExistingSessionTarget(sessionId, routes, entry.getValue(), this, balancer.isStickySessionForce()); } } if (exchange.getPathParameters().containsKey(balancer.getStickySessionPath())) { String sessionId = exchange.getPathParameters().get(balancer.getStickySessionPath()).getFirst(); Iterator<CharSequence> jvmRoute = parseRoutes(sessionId); if (jvmRoute.hasNext()) { return new ModClusterProxyTarget.ExistingSessionTarget(sessionId, jvmRoute, entry.getValue(), this, balancer.isStickySessionForce()); } } } } return new ModClusterProxyTarget.BasicTarget(entry.getValue(), this); }
java
public ModClusterProxyTarget findTarget(final HttpServerExchange exchange) { // There is an option to disable the virtual host check, probably a default virtual host final PathMatcher.PathMatch<VirtualHost.HostEntry> entry = mapVirtualHost(exchange); if (entry == null) { return null; } for (final Balancer balancer : balancers.values()) { final Map<String, Cookie> cookies = exchange.getRequestCookies(); if (balancer.isStickySession()) { if (cookies.containsKey(balancer.getStickySessionCookie())) { String sessionId = cookies.get(balancer.getStickySessionCookie()).getValue(); Iterator<CharSequence> routes = parseRoutes(sessionId); if (routes.hasNext()) { return new ModClusterProxyTarget.ExistingSessionTarget(sessionId, routes, entry.getValue(), this, balancer.isStickySessionForce()); } } if (exchange.getPathParameters().containsKey(balancer.getStickySessionPath())) { String sessionId = exchange.getPathParameters().get(balancer.getStickySessionPath()).getFirst(); Iterator<CharSequence> jvmRoute = parseRoutes(sessionId); if (jvmRoute.hasNext()) { return new ModClusterProxyTarget.ExistingSessionTarget(sessionId, jvmRoute, entry.getValue(), this, balancer.isStickySessionForce()); } } } } return new ModClusterProxyTarget.BasicTarget(entry.getValue(), this); }
[ "public", "ModClusterProxyTarget", "findTarget", "(", "final", "HttpServerExchange", "exchange", ")", "{", "// There is an option to disable the virtual host check, probably a default virtual host", "final", "PathMatcher", ".", "PathMatch", "<", "VirtualHost", ".", "HostEntry", ">", "entry", "=", "mapVirtualHost", "(", "exchange", ")", ";", "if", "(", "entry", "==", "null", ")", "{", "return", "null", ";", "}", "for", "(", "final", "Balancer", "balancer", ":", "balancers", ".", "values", "(", ")", ")", "{", "final", "Map", "<", "String", ",", "Cookie", ">", "cookies", "=", "exchange", ".", "getRequestCookies", "(", ")", ";", "if", "(", "balancer", ".", "isStickySession", "(", ")", ")", "{", "if", "(", "cookies", ".", "containsKey", "(", "balancer", ".", "getStickySessionCookie", "(", ")", ")", ")", "{", "String", "sessionId", "=", "cookies", ".", "get", "(", "balancer", ".", "getStickySessionCookie", "(", ")", ")", ".", "getValue", "(", ")", ";", "Iterator", "<", "CharSequence", ">", "routes", "=", "parseRoutes", "(", "sessionId", ")", ";", "if", "(", "routes", ".", "hasNext", "(", ")", ")", "{", "return", "new", "ModClusterProxyTarget", ".", "ExistingSessionTarget", "(", "sessionId", ",", "routes", ",", "entry", ".", "getValue", "(", ")", ",", "this", ",", "balancer", ".", "isStickySessionForce", "(", ")", ")", ";", "}", "}", "if", "(", "exchange", ".", "getPathParameters", "(", ")", ".", "containsKey", "(", "balancer", ".", "getStickySessionPath", "(", ")", ")", ")", "{", "String", "sessionId", "=", "exchange", ".", "getPathParameters", "(", ")", ".", "get", "(", "balancer", ".", "getStickySessionPath", "(", ")", ")", ".", "getFirst", "(", ")", ";", "Iterator", "<", "CharSequence", ">", "jvmRoute", "=", "parseRoutes", "(", "sessionId", ")", ";", "if", "(", "jvmRoute", ".", "hasNext", "(", ")", ")", "{", "return", "new", "ModClusterProxyTarget", ".", "ExistingSessionTarget", "(", "sessionId", ",", "jvmRoute", ",", "entry", ".", "getValue", "(", ")", ",", "this", ",", "balancer", ".", "isStickySessionForce", "(", ")", ")", ";", "}", "}", "}", "}", "return", "new", "ModClusterProxyTarget", ".", "BasicTarget", "(", "entry", ".", "getValue", "(", ")", ",", "this", ")", ";", "}" ]
Get the mod_cluster proxy target. @param exchange the http exchange @return proxy target
[ "Get", "the", "mod_cluster", "proxy", "target", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L130-L156
16,713
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.addNode
public synchronized boolean addNode(final NodeConfig config, final Balancer.BalancerBuilder balancerConfig, final XnioIoThread ioThread, final ByteBufferPool bufferPool) { final String jvmRoute = config.getJvmRoute(); final Node existing = nodes.get(jvmRoute); if (existing != null) { if (config.getConnectionURI().equals(existing.getNodeConfig().getConnectionURI())) { // TODO better check if they are the same existing.resetState(); return true; } else { existing.markRemoved(); removeNode(existing); if (!existing.isInErrorState()) { return false; // replies with MNODERM error } } } final String balancerRef = config.getBalancer(); Balancer balancer = balancers.get(balancerRef); if (balancer != null) { UndertowLogger.ROOT_LOGGER.debugf("Balancer %s already exists, replacing", balancerRef); } balancer = balancerConfig.build(); balancers.put(balancerRef, balancer); final Node node = new Node(config, balancer, ioThread, bufferPool, this); nodes.put(jvmRoute, node); // Schedule the health check scheduleHealthCheck(node, ioThread); // Reset the load factor periodically if (updateLoadTask.cancelKey == null) { updateLoadTask.cancelKey = ioThread.executeAtInterval(updateLoadTask, modCluster.getHealthCheckInterval(), TimeUnit.MILLISECONDS); } // Remove from the failover groups failoverDomains.remove(node.getJvmRoute()); UndertowLogger.ROOT_LOGGER.registeringNode(jvmRoute, config.getConnectionURI()); return true; }
java
public synchronized boolean addNode(final NodeConfig config, final Balancer.BalancerBuilder balancerConfig, final XnioIoThread ioThread, final ByteBufferPool bufferPool) { final String jvmRoute = config.getJvmRoute(); final Node existing = nodes.get(jvmRoute); if (existing != null) { if (config.getConnectionURI().equals(existing.getNodeConfig().getConnectionURI())) { // TODO better check if they are the same existing.resetState(); return true; } else { existing.markRemoved(); removeNode(existing); if (!existing.isInErrorState()) { return false; // replies with MNODERM error } } } final String balancerRef = config.getBalancer(); Balancer balancer = balancers.get(balancerRef); if (balancer != null) { UndertowLogger.ROOT_LOGGER.debugf("Balancer %s already exists, replacing", balancerRef); } balancer = balancerConfig.build(); balancers.put(balancerRef, balancer); final Node node = new Node(config, balancer, ioThread, bufferPool, this); nodes.put(jvmRoute, node); // Schedule the health check scheduleHealthCheck(node, ioThread); // Reset the load factor periodically if (updateLoadTask.cancelKey == null) { updateLoadTask.cancelKey = ioThread.executeAtInterval(updateLoadTask, modCluster.getHealthCheckInterval(), TimeUnit.MILLISECONDS); } // Remove from the failover groups failoverDomains.remove(node.getJvmRoute()); UndertowLogger.ROOT_LOGGER.registeringNode(jvmRoute, config.getConnectionURI()); return true; }
[ "public", "synchronized", "boolean", "addNode", "(", "final", "NodeConfig", "config", ",", "final", "Balancer", ".", "BalancerBuilder", "balancerConfig", ",", "final", "XnioIoThread", "ioThread", ",", "final", "ByteBufferPool", "bufferPool", ")", "{", "final", "String", "jvmRoute", "=", "config", ".", "getJvmRoute", "(", ")", ";", "final", "Node", "existing", "=", "nodes", ".", "get", "(", "jvmRoute", ")", ";", "if", "(", "existing", "!=", "null", ")", "{", "if", "(", "config", ".", "getConnectionURI", "(", ")", ".", "equals", "(", "existing", ".", "getNodeConfig", "(", ")", ".", "getConnectionURI", "(", ")", ")", ")", "{", "// TODO better check if they are the same", "existing", ".", "resetState", "(", ")", ";", "return", "true", ";", "}", "else", "{", "existing", ".", "markRemoved", "(", ")", ";", "removeNode", "(", "existing", ")", ";", "if", "(", "!", "existing", ".", "isInErrorState", "(", ")", ")", "{", "return", "false", ";", "// replies with MNODERM error", "}", "}", "}", "final", "String", "balancerRef", "=", "config", ".", "getBalancer", "(", ")", ";", "Balancer", "balancer", "=", "balancers", ".", "get", "(", "balancerRef", ")", ";", "if", "(", "balancer", "!=", "null", ")", "{", "UndertowLogger", ".", "ROOT_LOGGER", ".", "debugf", "(", "\"Balancer %s already exists, replacing\"", ",", "balancerRef", ")", ";", "}", "balancer", "=", "balancerConfig", ".", "build", "(", ")", ";", "balancers", ".", "put", "(", "balancerRef", ",", "balancer", ")", ";", "final", "Node", "node", "=", "new", "Node", "(", "config", ",", "balancer", ",", "ioThread", ",", "bufferPool", ",", "this", ")", ";", "nodes", ".", "put", "(", "jvmRoute", ",", "node", ")", ";", "// Schedule the health check", "scheduleHealthCheck", "(", "node", ",", "ioThread", ")", ";", "// Reset the load factor periodically", "if", "(", "updateLoadTask", ".", "cancelKey", "==", "null", ")", "{", "updateLoadTask", ".", "cancelKey", "=", "ioThread", ".", "executeAtInterval", "(", "updateLoadTask", ",", "modCluster", ".", "getHealthCheckInterval", "(", ")", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "}", "// Remove from the failover groups", "failoverDomains", ".", "remove", "(", "node", ".", "getJvmRoute", "(", ")", ")", ";", "UndertowLogger", ".", "ROOT_LOGGER", ".", "registeringNode", "(", "jvmRoute", ",", "config", ".", "getConnectionURI", "(", ")", ")", ";", "return", "true", ";", "}" ]
Register a new node. @param config the node configuration @param balancerConfig the balancer configuration @param ioThread the associated I/O thread @param bufferPool the buffer pool @return whether the node could be created or not
[ "Register", "a", "new", "node", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L167-L205
16,714
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.enableNode
public synchronized boolean enableNode(final String jvmRoute) { final Node node = nodes.get(jvmRoute); if (node != null) { for (final Context context : node.getContexts()) { context.enable(); } return true; } return false; }
java
public synchronized boolean enableNode(final String jvmRoute) { final Node node = nodes.get(jvmRoute); if (node != null) { for (final Context context : node.getContexts()) { context.enable(); } return true; } return false; }
[ "public", "synchronized", "boolean", "enableNode", "(", "final", "String", "jvmRoute", ")", "{", "final", "Node", "node", "=", "nodes", ".", "get", "(", "jvmRoute", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "for", "(", "final", "Context", "context", ":", "node", ".", "getContexts", "(", ")", ")", "{", "context", ".", "enable", "(", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Management command enabling all contexts on the given node. @param jvmRoute the jvmRoute @return
[ "Management", "command", "enabling", "all", "contexts", "on", "the", "given", "node", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L213-L222
16,715
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.disableNode
public synchronized boolean disableNode(final String jvmRoute) { final Node node = nodes.get(jvmRoute); if (node != null) { for (final Context context : node.getContexts()) { context.disable(); } return true; } return false; }
java
public synchronized boolean disableNode(final String jvmRoute) { final Node node = nodes.get(jvmRoute); if (node != null) { for (final Context context : node.getContexts()) { context.disable(); } return true; } return false; }
[ "public", "synchronized", "boolean", "disableNode", "(", "final", "String", "jvmRoute", ")", "{", "final", "Node", "node", "=", "nodes", ".", "get", "(", "jvmRoute", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "for", "(", "final", "Context", "context", ":", "node", ".", "getContexts", "(", ")", ")", "{", "context", ".", "disable", "(", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Management command disabling all contexts on the given node. @param jvmRoute the jvmRoute @return
[ "Management", "command", "disabling", "all", "contexts", "on", "the", "given", "node", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L230-L239
16,716
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.stopNode
public synchronized boolean stopNode(final String jvmRoute) { final Node node = nodes.get(jvmRoute); if (node != null) { for (final Context context : node.getContexts()) { context.stop(); } return true; } return false; }
java
public synchronized boolean stopNode(final String jvmRoute) { final Node node = nodes.get(jvmRoute); if (node != null) { for (final Context context : node.getContexts()) { context.stop(); } return true; } return false; }
[ "public", "synchronized", "boolean", "stopNode", "(", "final", "String", "jvmRoute", ")", "{", "final", "Node", "node", "=", "nodes", ".", "get", "(", "jvmRoute", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "for", "(", "final", "Context", "context", ":", "node", ".", "getContexts", "(", ")", ")", "{", "context", ".", "stop", "(", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Management command stopping all contexts on the given node. @param jvmRoute the jvmRoute @return
[ "Management", "command", "stopping", "all", "contexts", "on", "the", "given", "node", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L247-L256
16,717
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.enableContext
public synchronized boolean enableContext(final String contextPath, final String jvmRoute, final List<String> aliases) { final Node node = nodes.get(jvmRoute); if (node != null) { Context context = node.getContext(contextPath, aliases); if (context == null) { context = node.registerContext(contextPath, aliases); UndertowLogger.ROOT_LOGGER.registeringContext(contextPath, jvmRoute); UndertowLogger.ROOT_LOGGER.registeringContext(contextPath, jvmRoute, aliases); for (final String alias : aliases) { VirtualHost virtualHost = hosts.get(alias); if (virtualHost == null) { virtualHost = new VirtualHost(); hosts.put(alias, virtualHost); } virtualHost.registerContext(contextPath, jvmRoute, context); } } context.enable(); return true; } return false; }
java
public synchronized boolean enableContext(final String contextPath, final String jvmRoute, final List<String> aliases) { final Node node = nodes.get(jvmRoute); if (node != null) { Context context = node.getContext(contextPath, aliases); if (context == null) { context = node.registerContext(contextPath, aliases); UndertowLogger.ROOT_LOGGER.registeringContext(contextPath, jvmRoute); UndertowLogger.ROOT_LOGGER.registeringContext(contextPath, jvmRoute, aliases); for (final String alias : aliases) { VirtualHost virtualHost = hosts.get(alias); if (virtualHost == null) { virtualHost = new VirtualHost(); hosts.put(alias, virtualHost); } virtualHost.registerContext(contextPath, jvmRoute, context); } } context.enable(); return true; } return false; }
[ "public", "synchronized", "boolean", "enableContext", "(", "final", "String", "contextPath", ",", "final", "String", "jvmRoute", ",", "final", "List", "<", "String", ">", "aliases", ")", "{", "final", "Node", "node", "=", "nodes", ".", "get", "(", "jvmRoute", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "Context", "context", "=", "node", ".", "getContext", "(", "contextPath", ",", "aliases", ")", ";", "if", "(", "context", "==", "null", ")", "{", "context", "=", "node", ".", "registerContext", "(", "contextPath", ",", "aliases", ")", ";", "UndertowLogger", ".", "ROOT_LOGGER", ".", "registeringContext", "(", "contextPath", ",", "jvmRoute", ")", ";", "UndertowLogger", ".", "ROOT_LOGGER", ".", "registeringContext", "(", "contextPath", ",", "jvmRoute", ",", "aliases", ")", ";", "for", "(", "final", "String", "alias", ":", "aliases", ")", "{", "VirtualHost", "virtualHost", "=", "hosts", ".", "get", "(", "alias", ")", ";", "if", "(", "virtualHost", "==", "null", ")", "{", "virtualHost", "=", "new", "VirtualHost", "(", ")", ";", "hosts", ".", "put", "(", "alias", ",", "virtualHost", ")", ";", "}", "virtualHost", ".", "registerContext", "(", "contextPath", ",", "jvmRoute", ",", "context", ")", ";", "}", "}", "context", ".", "enable", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Register a web context. If the web context already exists, just enable it. @param contextPath the context path @param jvmRoute the jvmRoute @param aliases the virtual host aliases
[ "Register", "a", "web", "context", ".", "If", "the", "web", "context", "already", "exists", "just", "enable", "it", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L317-L338
16,718
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.findNewNode
Context findNewNode(final VirtualHost.HostEntry entry) { return electNode(entry.getContexts(), false, null); }
java
Context findNewNode(final VirtualHost.HostEntry entry) { return electNode(entry.getContexts(), false, null); }
[ "Context", "findNewNode", "(", "final", "VirtualHost", ".", "HostEntry", "entry", ")", "{", "return", "electNode", "(", "entry", ".", "getContexts", "(", ")", ",", "false", ",", "null", ")", ";", "}" ]
Find a new node handling this request. @param entry the resolved virtual host entry @return the context, {@code null} if not found
[ "Find", "a", "new", "node", "handling", "this", "request", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L394-L396
16,719
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.findFailoverNode
Context findFailoverNode(final VirtualHost.HostEntry entry, final String domain, final String session, final String jvmRoute, final boolean forceStickySession) { // If configured, deterministically choose the failover target by calculating hash of the session ID modulo number of electable nodes if (modCluster.isDeterministicFailover()) { List<String> candidates = new ArrayList<>(entry.getNodes().size()); for (String route : entry.getNodes()) { Node node = nodes.get(route); if (node != null && !node.isInErrorState() && !node.isHotStandby()) { candidates.add(route); } } // If there are no available regular nodes, all hot standby nodes become candidates if (candidates.isEmpty()) { for (String route : entry.getNodes()) { Node node = nodes.get(route); if (node != null && !node.isInErrorState() && node.isHotStandby()) { candidates.add(route); } } } if (candidates.isEmpty()) { return null; } String sessionId = session.substring(0, session.indexOf('.')); int index = (int) (Math.abs((long) sessionId.hashCode()) % candidates.size()); Collections.sort(candidates); String electedRoute = candidates.get(index); UndertowLogger.ROOT_LOGGER.debugf("Using deterministic failover target: %s", electedRoute); return entry.getContextForNode(electedRoute); } String failOverDomain = null; if (domain == null) { final Node node = nodes.get(jvmRoute); if (node != null) { failOverDomain = node.getNodeConfig().getDomain(); } if (failOverDomain == null) { failOverDomain = failoverDomains.get(jvmRoute); } } else { failOverDomain = domain; } final Collection<Context> contexts = entry.getContexts(); if (failOverDomain != null) { final Context context = electNode(contexts, true, failOverDomain); if (context != null) { return context; } } if (forceStickySession) { return null; } else { return electNode(contexts, false, null); } }
java
Context findFailoverNode(final VirtualHost.HostEntry entry, final String domain, final String session, final String jvmRoute, final boolean forceStickySession) { // If configured, deterministically choose the failover target by calculating hash of the session ID modulo number of electable nodes if (modCluster.isDeterministicFailover()) { List<String> candidates = new ArrayList<>(entry.getNodes().size()); for (String route : entry.getNodes()) { Node node = nodes.get(route); if (node != null && !node.isInErrorState() && !node.isHotStandby()) { candidates.add(route); } } // If there are no available regular nodes, all hot standby nodes become candidates if (candidates.isEmpty()) { for (String route : entry.getNodes()) { Node node = nodes.get(route); if (node != null && !node.isInErrorState() && node.isHotStandby()) { candidates.add(route); } } } if (candidates.isEmpty()) { return null; } String sessionId = session.substring(0, session.indexOf('.')); int index = (int) (Math.abs((long) sessionId.hashCode()) % candidates.size()); Collections.sort(candidates); String electedRoute = candidates.get(index); UndertowLogger.ROOT_LOGGER.debugf("Using deterministic failover target: %s", electedRoute); return entry.getContextForNode(electedRoute); } String failOverDomain = null; if (domain == null) { final Node node = nodes.get(jvmRoute); if (node != null) { failOverDomain = node.getNodeConfig().getDomain(); } if (failOverDomain == null) { failOverDomain = failoverDomains.get(jvmRoute); } } else { failOverDomain = domain; } final Collection<Context> contexts = entry.getContexts(); if (failOverDomain != null) { final Context context = electNode(contexts, true, failOverDomain); if (context != null) { return context; } } if (forceStickySession) { return null; } else { return electNode(contexts, false, null); } }
[ "Context", "findFailoverNode", "(", "final", "VirtualHost", ".", "HostEntry", "entry", ",", "final", "String", "domain", ",", "final", "String", "session", ",", "final", "String", "jvmRoute", ",", "final", "boolean", "forceStickySession", ")", "{", "// If configured, deterministically choose the failover target by calculating hash of the session ID modulo number of electable nodes", "if", "(", "modCluster", ".", "isDeterministicFailover", "(", ")", ")", "{", "List", "<", "String", ">", "candidates", "=", "new", "ArrayList", "<>", "(", "entry", ".", "getNodes", "(", ")", ".", "size", "(", ")", ")", ";", "for", "(", "String", "route", ":", "entry", ".", "getNodes", "(", ")", ")", "{", "Node", "node", "=", "nodes", ".", "get", "(", "route", ")", ";", "if", "(", "node", "!=", "null", "&&", "!", "node", ".", "isInErrorState", "(", ")", "&&", "!", "node", ".", "isHotStandby", "(", ")", ")", "{", "candidates", ".", "add", "(", "route", ")", ";", "}", "}", "// If there are no available regular nodes, all hot standby nodes become candidates", "if", "(", "candidates", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "String", "route", ":", "entry", ".", "getNodes", "(", ")", ")", "{", "Node", "node", "=", "nodes", ".", "get", "(", "route", ")", ";", "if", "(", "node", "!=", "null", "&&", "!", "node", ".", "isInErrorState", "(", ")", "&&", "node", ".", "isHotStandby", "(", ")", ")", "{", "candidates", ".", "add", "(", "route", ")", ";", "}", "}", "}", "if", "(", "candidates", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "String", "sessionId", "=", "session", ".", "substring", "(", "0", ",", "session", ".", "indexOf", "(", "'", "'", ")", ")", ";", "int", "index", "=", "(", "int", ")", "(", "Math", ".", "abs", "(", "(", "long", ")", "sessionId", ".", "hashCode", "(", ")", ")", "%", "candidates", ".", "size", "(", ")", ")", ";", "Collections", ".", "sort", "(", "candidates", ")", ";", "String", "electedRoute", "=", "candidates", ".", "get", "(", "index", ")", ";", "UndertowLogger", ".", "ROOT_LOGGER", ".", "debugf", "(", "\"Using deterministic failover target: %s\"", ",", "electedRoute", ")", ";", "return", "entry", ".", "getContextForNode", "(", "electedRoute", ")", ";", "}", "String", "failOverDomain", "=", "null", ";", "if", "(", "domain", "==", "null", ")", "{", "final", "Node", "node", "=", "nodes", ".", "get", "(", "jvmRoute", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "failOverDomain", "=", "node", ".", "getNodeConfig", "(", ")", ".", "getDomain", "(", ")", ";", "}", "if", "(", "failOverDomain", "==", "null", ")", "{", "failOverDomain", "=", "failoverDomains", ".", "get", "(", "jvmRoute", ")", ";", "}", "}", "else", "{", "failOverDomain", "=", "domain", ";", "}", "final", "Collection", "<", "Context", ">", "contexts", "=", "entry", ".", "getContexts", "(", ")", ";", "if", "(", "failOverDomain", "!=", "null", ")", "{", "final", "Context", "context", "=", "electNode", "(", "contexts", ",", "true", ",", "failOverDomain", ")", ";", "if", "(", "context", "!=", "null", ")", "{", "return", "context", ";", "}", "}", "if", "(", "forceStickySession", ")", "{", "return", "null", ";", "}", "else", "{", "return", "electNode", "(", "contexts", ",", "false", ",", "null", ")", ";", "}", "}" ]
Try to find a failover node within the same load balancing group. @param entry the resolved virtual host entry @param domain the load balancing domain, if known @param session the actual value of JSESSIONID/jsessionid cookie/parameter @param jvmRoute the original jvmRoute; in case of multiple routes, the first one @param forceStickySession whether sticky sessions are forced @return the context, {@code null} if not found
[ "Try", "to", "find", "a", "failover", "node", "within", "the", "same", "load", "balancing", "group", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L408-L466
16,720
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java
ModClusterContainer.mapVirtualHost
private PathMatcher.PathMatch<VirtualHost.HostEntry> mapVirtualHost(final HttpServerExchange exchange) { final String context = exchange.getRelativePath(); if(modCluster.isUseAlias()) { final String hostName = exchange.getRequestHeaders().getFirst(Headers.HOST); if (hostName != null) { // Remove the port from the host int i = hostName.indexOf(":"); VirtualHost host; if (i > 0) { host = hosts.get(hostName.substring(0, i)); if (host == null) { host = hosts.get(hostName); } } else { host = hosts.get(hostName); } if (host == null) { return null; } PathMatcher.PathMatch<VirtualHost.HostEntry> result = host.match(context); if (result.getValue() == null) { return null; } return result; } } else { for(Map.Entry<String, VirtualHost> host : hosts.entrySet()) { PathMatcher.PathMatch<VirtualHost.HostEntry> result = host.getValue().match(context); if (result.getValue() != null) { return result; } } } return null; }
java
private PathMatcher.PathMatch<VirtualHost.HostEntry> mapVirtualHost(final HttpServerExchange exchange) { final String context = exchange.getRelativePath(); if(modCluster.isUseAlias()) { final String hostName = exchange.getRequestHeaders().getFirst(Headers.HOST); if (hostName != null) { // Remove the port from the host int i = hostName.indexOf(":"); VirtualHost host; if (i > 0) { host = hosts.get(hostName.substring(0, i)); if (host == null) { host = hosts.get(hostName); } } else { host = hosts.get(hostName); } if (host == null) { return null; } PathMatcher.PathMatch<VirtualHost.HostEntry> result = host.match(context); if (result.getValue() == null) { return null; } return result; } } else { for(Map.Entry<String, VirtualHost> host : hosts.entrySet()) { PathMatcher.PathMatch<VirtualHost.HostEntry> result = host.getValue().match(context); if (result.getValue() != null) { return result; } } } return null; }
[ "private", "PathMatcher", ".", "PathMatch", "<", "VirtualHost", ".", "HostEntry", ">", "mapVirtualHost", "(", "final", "HttpServerExchange", "exchange", ")", "{", "final", "String", "context", "=", "exchange", ".", "getRelativePath", "(", ")", ";", "if", "(", "modCluster", ".", "isUseAlias", "(", ")", ")", "{", "final", "String", "hostName", "=", "exchange", ".", "getRequestHeaders", "(", ")", ".", "getFirst", "(", "Headers", ".", "HOST", ")", ";", "if", "(", "hostName", "!=", "null", ")", "{", "// Remove the port from the host", "int", "i", "=", "hostName", ".", "indexOf", "(", "\":\"", ")", ";", "VirtualHost", "host", ";", "if", "(", "i", ">", "0", ")", "{", "host", "=", "hosts", ".", "get", "(", "hostName", ".", "substring", "(", "0", ",", "i", ")", ")", ";", "if", "(", "host", "==", "null", ")", "{", "host", "=", "hosts", ".", "get", "(", "hostName", ")", ";", "}", "}", "else", "{", "host", "=", "hosts", ".", "get", "(", "hostName", ")", ";", "}", "if", "(", "host", "==", "null", ")", "{", "return", "null", ";", "}", "PathMatcher", ".", "PathMatch", "<", "VirtualHost", ".", "HostEntry", ">", "result", "=", "host", ".", "match", "(", "context", ")", ";", "if", "(", "result", ".", "getValue", "(", ")", "==", "null", ")", "{", "return", "null", ";", "}", "return", "result", ";", "}", "}", "else", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "VirtualHost", ">", "host", ":", "hosts", ".", "entrySet", "(", ")", ")", "{", "PathMatcher", ".", "PathMatch", "<", "VirtualHost", ".", "HostEntry", ">", "result", "=", "host", ".", "getValue", "(", ")", ".", "match", "(", "context", ")", ";", "if", "(", "result", ".", "getValue", "(", ")", "!=", "null", ")", "{", "return", "result", ";", "}", "}", "}", "return", "null", ";", "}" ]
Map a request to virtual host. @param exchange the http exchange
[ "Map", "a", "request", "to", "virtual", "host", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/ModClusterContainer.java#L473-L507
16,721
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSocketUtils.java
WebSocketUtils.transfer
public static long transfer(final ReadableByteChannel source, final long count, final ByteBuffer throughBuffer, final WritableByteChannel sink) throws IOException { long total = 0L; while (total < count) { throughBuffer.clear(); if (count - total < throughBuffer.remaining()) { throughBuffer.limit((int) (count - total)); } try { long res = source.read(throughBuffer); if (res <= 0) { return total == 0L ? res : total; } } finally { throughBuffer.flip(); } while (throughBuffer.hasRemaining()) { long res = sink.write(throughBuffer); if (res <= 0) { return total; } total += res; } } return total; }
java
public static long transfer(final ReadableByteChannel source, final long count, final ByteBuffer throughBuffer, final WritableByteChannel sink) throws IOException { long total = 0L; while (total < count) { throughBuffer.clear(); if (count - total < throughBuffer.remaining()) { throughBuffer.limit((int) (count - total)); } try { long res = source.read(throughBuffer); if (res <= 0) { return total == 0L ? res : total; } } finally { throughBuffer.flip(); } while (throughBuffer.hasRemaining()) { long res = sink.write(throughBuffer); if (res <= 0) { return total; } total += res; } } return total; }
[ "public", "static", "long", "transfer", "(", "final", "ReadableByteChannel", "source", ",", "final", "long", "count", ",", "final", "ByteBuffer", "throughBuffer", ",", "final", "WritableByteChannel", "sink", ")", "throws", "IOException", "{", "long", "total", "=", "0L", ";", "while", "(", "total", "<", "count", ")", "{", "throughBuffer", ".", "clear", "(", ")", ";", "if", "(", "count", "-", "total", "<", "throughBuffer", ".", "remaining", "(", ")", ")", "{", "throughBuffer", ".", "limit", "(", "(", "int", ")", "(", "count", "-", "total", ")", ")", ";", "}", "try", "{", "long", "res", "=", "source", ".", "read", "(", "throughBuffer", ")", ";", "if", "(", "res", "<=", "0", ")", "{", "return", "total", "==", "0L", "?", "res", ":", "total", ";", "}", "}", "finally", "{", "throughBuffer", ".", "flip", "(", ")", ";", "}", "while", "(", "throughBuffer", ".", "hasRemaining", "(", ")", ")", "{", "long", "res", "=", "sink", ".", "write", "(", "throughBuffer", ")", ";", "if", "(", "res", "<=", "0", ")", "{", "return", "total", ";", "}", "total", "+=", "res", ";", "}", "}", "return", "total", ";", "}" ]
Transfer the data from the source to the sink using the given through buffer to pass data through.
[ "Transfer", "the", "data", "from", "the", "source", "to", "the", "sink", "using", "the", "given", "through", "buffer", "to", "pass", "data", "through", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSocketUtils.java#L103-L129
16,722
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSocketUtils.java
WebSocketUtils.echoFrame
public static void echoFrame(final WebSocketChannel channel, final StreamSourceFrameChannel ws) throws IOException { final WebSocketFrameType type; switch (ws.getType()) { case PONG: // pong frames must be discarded ws.close(); return; case PING: // if a ping is send the autobahn testsuite expects a PONG when echo back type = WebSocketFrameType.PONG; break; default: type = ws.getType(); break; } final StreamSinkFrameChannel sink = channel.send(type); sink.setRsv(ws.getRsv()); initiateTransfer(ws, sink, new ChannelListener<StreamSourceFrameChannel>() { @Override public void handleEvent(StreamSourceFrameChannel streamSourceFrameChannel) { IoUtils.safeClose(streamSourceFrameChannel); } }, new ChannelListener<StreamSinkFrameChannel>() { @Override public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) { try { streamSinkFrameChannel.shutdownWrites(); } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSinkFrameChannel, channel); return; } try { if (!streamSinkFrameChannel.flush()) { streamSinkFrameChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener( new ChannelListener<StreamSinkFrameChannel>() { @Override public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) { streamSinkFrameChannel.getWriteSetter().set(null); IoUtils.safeClose(streamSinkFrameChannel); if (type == WebSocketFrameType.CLOSE) { IoUtils.safeClose(channel); } } }, new ChannelExceptionHandler<StreamSinkFrameChannel>() { @Override public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSinkFrameChannel, channel); } } )); streamSinkFrameChannel.resumeWrites(); } else { if (type == WebSocketFrameType.CLOSE) { IoUtils.safeClose(channel); } streamSinkFrameChannel.getWriteSetter().set(null); IoUtils.safeClose(streamSinkFrameChannel); } } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSinkFrameChannel, channel); } } }, new ChannelExceptionHandler<StreamSourceFrameChannel>() { @Override public void handleException(StreamSourceFrameChannel streamSourceFrameChannel, IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSourceFrameChannel, channel); } }, new ChannelExceptionHandler<StreamSinkFrameChannel>() { @Override public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSinkFrameChannel, channel); } }, channel.getBufferPool() ); }
java
public static void echoFrame(final WebSocketChannel channel, final StreamSourceFrameChannel ws) throws IOException { final WebSocketFrameType type; switch (ws.getType()) { case PONG: // pong frames must be discarded ws.close(); return; case PING: // if a ping is send the autobahn testsuite expects a PONG when echo back type = WebSocketFrameType.PONG; break; default: type = ws.getType(); break; } final StreamSinkFrameChannel sink = channel.send(type); sink.setRsv(ws.getRsv()); initiateTransfer(ws, sink, new ChannelListener<StreamSourceFrameChannel>() { @Override public void handleEvent(StreamSourceFrameChannel streamSourceFrameChannel) { IoUtils.safeClose(streamSourceFrameChannel); } }, new ChannelListener<StreamSinkFrameChannel>() { @Override public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) { try { streamSinkFrameChannel.shutdownWrites(); } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSinkFrameChannel, channel); return; } try { if (!streamSinkFrameChannel.flush()) { streamSinkFrameChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener( new ChannelListener<StreamSinkFrameChannel>() { @Override public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) { streamSinkFrameChannel.getWriteSetter().set(null); IoUtils.safeClose(streamSinkFrameChannel); if (type == WebSocketFrameType.CLOSE) { IoUtils.safeClose(channel); } } }, new ChannelExceptionHandler<StreamSinkFrameChannel>() { @Override public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSinkFrameChannel, channel); } } )); streamSinkFrameChannel.resumeWrites(); } else { if (type == WebSocketFrameType.CLOSE) { IoUtils.safeClose(channel); } streamSinkFrameChannel.getWriteSetter().set(null); IoUtils.safeClose(streamSinkFrameChannel); } } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSinkFrameChannel, channel); } } }, new ChannelExceptionHandler<StreamSourceFrameChannel>() { @Override public void handleException(StreamSourceFrameChannel streamSourceFrameChannel, IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSourceFrameChannel, channel); } }, new ChannelExceptionHandler<StreamSinkFrameChannel>() { @Override public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(streamSinkFrameChannel, channel); } }, channel.getBufferPool() ); }
[ "public", "static", "void", "echoFrame", "(", "final", "WebSocketChannel", "channel", ",", "final", "StreamSourceFrameChannel", "ws", ")", "throws", "IOException", "{", "final", "WebSocketFrameType", "type", ";", "switch", "(", "ws", ".", "getType", "(", ")", ")", "{", "case", "PONG", ":", "// pong frames must be discarded", "ws", ".", "close", "(", ")", ";", "return", ";", "case", "PING", ":", "// if a ping is send the autobahn testsuite expects a PONG when echo back", "type", "=", "WebSocketFrameType", ".", "PONG", ";", "break", ";", "default", ":", "type", "=", "ws", ".", "getType", "(", ")", ";", "break", ";", "}", "final", "StreamSinkFrameChannel", "sink", "=", "channel", ".", "send", "(", "type", ")", ";", "sink", ".", "setRsv", "(", "ws", ".", "getRsv", "(", ")", ")", ";", "initiateTransfer", "(", "ws", ",", "sink", ",", "new", "ChannelListener", "<", "StreamSourceFrameChannel", ">", "(", ")", "{", "@", "Override", "public", "void", "handleEvent", "(", "StreamSourceFrameChannel", "streamSourceFrameChannel", ")", "{", "IoUtils", ".", "safeClose", "(", "streamSourceFrameChannel", ")", ";", "}", "}", ",", "new", "ChannelListener", "<", "StreamSinkFrameChannel", ">", "(", ")", "{", "@", "Override", "public", "void", "handleEvent", "(", "StreamSinkFrameChannel", "streamSinkFrameChannel", ")", "{", "try", "{", "streamSinkFrameChannel", ".", "shutdownWrites", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "ioException", "(", "e", ")", ";", "IoUtils", ".", "safeClose", "(", "streamSinkFrameChannel", ",", "channel", ")", ";", "return", ";", "}", "try", "{", "if", "(", "!", "streamSinkFrameChannel", ".", "flush", "(", ")", ")", "{", "streamSinkFrameChannel", ".", "getWriteSetter", "(", ")", ".", "set", "(", "ChannelListeners", ".", "flushingChannelListener", "(", "new", "ChannelListener", "<", "StreamSinkFrameChannel", ">", "(", ")", "{", "@", "Override", "public", "void", "handleEvent", "(", "StreamSinkFrameChannel", "streamSinkFrameChannel", ")", "{", "streamSinkFrameChannel", ".", "getWriteSetter", "(", ")", ".", "set", "(", "null", ")", ";", "IoUtils", ".", "safeClose", "(", "streamSinkFrameChannel", ")", ";", "if", "(", "type", "==", "WebSocketFrameType", ".", "CLOSE", ")", "{", "IoUtils", ".", "safeClose", "(", "channel", ")", ";", "}", "}", "}", ",", "new", "ChannelExceptionHandler", "<", "StreamSinkFrameChannel", ">", "(", ")", "{", "@", "Override", "public", "void", "handleException", "(", "StreamSinkFrameChannel", "streamSinkFrameChannel", ",", "IOException", "e", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "ioException", "(", "e", ")", ";", "IoUtils", ".", "safeClose", "(", "streamSinkFrameChannel", ",", "channel", ")", ";", "}", "}", ")", ")", ";", "streamSinkFrameChannel", ".", "resumeWrites", "(", ")", ";", "}", "else", "{", "if", "(", "type", "==", "WebSocketFrameType", ".", "CLOSE", ")", "{", "IoUtils", ".", "safeClose", "(", "channel", ")", ";", "}", "streamSinkFrameChannel", ".", "getWriteSetter", "(", ")", ".", "set", "(", "null", ")", ";", "IoUtils", ".", "safeClose", "(", "streamSinkFrameChannel", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "ioException", "(", "e", ")", ";", "IoUtils", ".", "safeClose", "(", "streamSinkFrameChannel", ",", "channel", ")", ";", "}", "}", "}", ",", "new", "ChannelExceptionHandler", "<", "StreamSourceFrameChannel", ">", "(", ")", "{", "@", "Override", "public", "void", "handleException", "(", "StreamSourceFrameChannel", "streamSourceFrameChannel", ",", "IOException", "e", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "ioException", "(", "e", ")", ";", "IoUtils", ".", "safeClose", "(", "streamSourceFrameChannel", ",", "channel", ")", ";", "}", "}", ",", "new", "ChannelExceptionHandler", "<", "StreamSinkFrameChannel", ">", "(", ")", "{", "@", "Override", "public", "void", "handleException", "(", "StreamSinkFrameChannel", "streamSinkFrameChannel", ",", "IOException", "e", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "ioException", "(", "e", ")", ";", "IoUtils", ".", "safeClose", "(", "streamSinkFrameChannel", ",", "channel", ")", ";", "}", "}", ",", "channel", ".", "getBufferPool", "(", ")", ")", ";", "}" ]
Echo back the frame to the sender
[ "Echo", "back", "the", "frame", "to", "the", "sender" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSocketUtils.java#L134-L218
16,723
undertow-io/undertow
core/src/main/java/io/undertow/util/HeaderMap.java
HeaderMap.fastIterate
public long fastIterate() { final Object[] table = this.table; final int len = table.length; int ri = 0; int ci; while (ri < len) { final Object item = table[ri]; if (item != null) { if (item instanceof HeaderValues) { return (long)ri << 32L; } else { final HeaderValues[] row = (HeaderValues[]) item; ci = 0; final int rowLen = row.length; while (ci < rowLen) { if (row[ci] != null) { return (long)ri << 32L | (ci & 0xffffffffL); } ci ++; } } } ri++; } return -1L; }
java
public long fastIterate() { final Object[] table = this.table; final int len = table.length; int ri = 0; int ci; while (ri < len) { final Object item = table[ri]; if (item != null) { if (item instanceof HeaderValues) { return (long)ri << 32L; } else { final HeaderValues[] row = (HeaderValues[]) item; ci = 0; final int rowLen = row.length; while (ci < rowLen) { if (row[ci] != null) { return (long)ri << 32L | (ci & 0xffffffffL); } ci ++; } } } ri++; } return -1L; }
[ "public", "long", "fastIterate", "(", ")", "{", "final", "Object", "[", "]", "table", "=", "this", ".", "table", ";", "final", "int", "len", "=", "table", ".", "length", ";", "int", "ri", "=", "0", ";", "int", "ci", ";", "while", "(", "ri", "<", "len", ")", "{", "final", "Object", "item", "=", "table", "[", "ri", "]", ";", "if", "(", "item", "!=", "null", ")", "{", "if", "(", "item", "instanceof", "HeaderValues", ")", "{", "return", "(", "long", ")", "ri", "<<", "32L", ";", "}", "else", "{", "final", "HeaderValues", "[", "]", "row", "=", "(", "HeaderValues", "[", "]", ")", "item", ";", "ci", "=", "0", ";", "final", "int", "rowLen", "=", "row", ".", "length", ";", "while", "(", "ci", "<", "rowLen", ")", "{", "if", "(", "row", "[", "ci", "]", "!=", "null", ")", "{", "return", "(", "long", ")", "ri", "<<", "32L", "|", "(", "ci", "&", "0xffffffff", "L", ")", ";", "}", "ci", "++", ";", "}", "}", "}", "ri", "++", ";", "}", "return", "-", "1L", ";", "}" ]
Do a fast iteration of this header map without creating any objects. @return an opaque iterating cookie, or -1 if no iteration is possible @see #fiNext(long) @see #fiCurrent(long)
[ "Do", "a", "fast", "iteration", "of", "this", "header", "map", "without", "creating", "any", "objects", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/HeaderMap.java#L380-L405
16,724
undertow-io/undertow
core/src/main/java/io/undertow/util/HeaderMap.java
HeaderMap.fiNextNonEmpty
public long fiNextNonEmpty(long cookie) { if (cookie == -1L) return -1L; final Object[] table = this.table; final int len = table.length; int ri = (int) (cookie >> 32); int ci = (int) cookie; Object item = table[ri]; if (item instanceof HeaderValues[]) { final HeaderValues[] row = (HeaderValues[]) item; final int rowLen = row.length; if (++ci >= rowLen) { ri ++; ci = 0; } else if (row[ci] != null && !row[ci].isEmpty()) { return (long)ri << 32L | (ci & 0xffffffffL); } } else { ri ++; ci = 0; } while (ri < len) { item = table[ri]; if (item instanceof HeaderValues && !((HeaderValues) item).isEmpty()) { return (long)ri << 32L; } else if (item instanceof HeaderValues[]) { final HeaderValues[] row = (HeaderValues[]) item; final int rowLen = row.length; while (ci < rowLen) { if (row[ci] != null && !row[ci].isEmpty()) { return (long)ri << 32L | (ci & 0xffffffffL); } ci ++; } } ci = 0; ri ++; } return -1L; }
java
public long fiNextNonEmpty(long cookie) { if (cookie == -1L) return -1L; final Object[] table = this.table; final int len = table.length; int ri = (int) (cookie >> 32); int ci = (int) cookie; Object item = table[ri]; if (item instanceof HeaderValues[]) { final HeaderValues[] row = (HeaderValues[]) item; final int rowLen = row.length; if (++ci >= rowLen) { ri ++; ci = 0; } else if (row[ci] != null && !row[ci].isEmpty()) { return (long)ri << 32L | (ci & 0xffffffffL); } } else { ri ++; ci = 0; } while (ri < len) { item = table[ri]; if (item instanceof HeaderValues && !((HeaderValues) item).isEmpty()) { return (long)ri << 32L; } else if (item instanceof HeaderValues[]) { final HeaderValues[] row = (HeaderValues[]) item; final int rowLen = row.length; while (ci < rowLen) { if (row[ci] != null && !row[ci].isEmpty()) { return (long)ri << 32L | (ci & 0xffffffffL); } ci ++; } } ci = 0; ri ++; } return -1L; }
[ "public", "long", "fiNextNonEmpty", "(", "long", "cookie", ")", "{", "if", "(", "cookie", "==", "-", "1L", ")", "return", "-", "1L", ";", "final", "Object", "[", "]", "table", "=", "this", ".", "table", ";", "final", "int", "len", "=", "table", ".", "length", ";", "int", "ri", "=", "(", "int", ")", "(", "cookie", ">>", "32", ")", ";", "int", "ci", "=", "(", "int", ")", "cookie", ";", "Object", "item", "=", "table", "[", "ri", "]", ";", "if", "(", "item", "instanceof", "HeaderValues", "[", "]", ")", "{", "final", "HeaderValues", "[", "]", "row", "=", "(", "HeaderValues", "[", "]", ")", "item", ";", "final", "int", "rowLen", "=", "row", ".", "length", ";", "if", "(", "++", "ci", ">=", "rowLen", ")", "{", "ri", "++", ";", "ci", "=", "0", ";", "}", "else", "if", "(", "row", "[", "ci", "]", "!=", "null", "&&", "!", "row", "[", "ci", "]", ".", "isEmpty", "(", ")", ")", "{", "return", "(", "long", ")", "ri", "<<", "32L", "|", "(", "ci", "&", "0xffffffff", "L", ")", ";", "}", "}", "else", "{", "ri", "++", ";", "ci", "=", "0", ";", "}", "while", "(", "ri", "<", "len", ")", "{", "item", "=", "table", "[", "ri", "]", ";", "if", "(", "item", "instanceof", "HeaderValues", "&&", "!", "(", "(", "HeaderValues", ")", "item", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "(", "long", ")", "ri", "<<", "32L", ";", "}", "else", "if", "(", "item", "instanceof", "HeaderValues", "[", "]", ")", "{", "final", "HeaderValues", "[", "]", "row", "=", "(", "HeaderValues", "[", "]", ")", "item", ";", "final", "int", "rowLen", "=", "row", ".", "length", ";", "while", "(", "ci", "<", "rowLen", ")", "{", "if", "(", "row", "[", "ci", "]", "!=", "null", "&&", "!", "row", "[", "ci", "]", ".", "isEmpty", "(", ")", ")", "{", "return", "(", "long", ")", "ri", "<<", "32L", "|", "(", "ci", "&", "0xffffffff", "L", ")", ";", "}", "ci", "++", ";", "}", "}", "ci", "=", "0", ";", "ri", "++", ";", "}", "return", "-", "1L", ";", "}" ]
Find the next non-empty index in a fast iteration. @param cookie the previous cookie value @return the next cookie value, or -1L if iteration is done
[ "Find", "the", "next", "non", "-", "empty", "index", "in", "a", "fast", "iteration", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/HeaderMap.java#L491-L527
16,725
undertow-io/undertow
core/src/main/java/io/undertow/util/HeaderMap.java
HeaderMap.fiCurrent
public HeaderValues fiCurrent(long cookie) { try { final Object[] table = this.table; int ri = (int) (cookie >> 32); int ci = (int) cookie; final Object item = table[ri]; if (item instanceof HeaderValues[]) { return ((HeaderValues[])item)[ci]; } else if (ci == 0) { return (HeaderValues) item; } else { throw new NoSuchElementException(); } } catch (RuntimeException e) { throw new NoSuchElementException(); } }
java
public HeaderValues fiCurrent(long cookie) { try { final Object[] table = this.table; int ri = (int) (cookie >> 32); int ci = (int) cookie; final Object item = table[ri]; if (item instanceof HeaderValues[]) { return ((HeaderValues[])item)[ci]; } else if (ci == 0) { return (HeaderValues) item; } else { throw new NoSuchElementException(); } } catch (RuntimeException e) { throw new NoSuchElementException(); } }
[ "public", "HeaderValues", "fiCurrent", "(", "long", "cookie", ")", "{", "try", "{", "final", "Object", "[", "]", "table", "=", "this", ".", "table", ";", "int", "ri", "=", "(", "int", ")", "(", "cookie", ">>", "32", ")", ";", "int", "ci", "=", "(", "int", ")", "cookie", ";", "final", "Object", "item", "=", "table", "[", "ri", "]", ";", "if", "(", "item", "instanceof", "HeaderValues", "[", "]", ")", "{", "return", "(", "(", "HeaderValues", "[", "]", ")", "item", ")", "[", "ci", "]", ";", "}", "else", "if", "(", "ci", "==", "0", ")", "{", "return", "(", "HeaderValues", ")", "item", ";", "}", "else", "{", "throw", "new", "NoSuchElementException", "(", ")", ";", "}", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "new", "NoSuchElementException", "(", ")", ";", "}", "}" ]
Return the value at the current index in a fast iteration. @param cookie the iteration cookie value @return the values object at this position @throws NoSuchElementException if the cookie value is invalid
[ "Return", "the", "value", "at", "the", "current", "index", "in", "a", "fast", "iteration", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/HeaderMap.java#L536-L552
16,726
undertow-io/undertow
core/src/main/java/io/undertow/protocols/ssl/UndertowXnioSsl.java
UndertowXnioSsl.getSslEngine
public static SSLEngine getSslEngine(SslConnection connection) { if (connection instanceof UndertowSslConnection) { return ((UndertowSslConnection) connection).getSSLEngine(); } else { return JsseXnioSsl.getSslEngine(connection); } }
java
public static SSLEngine getSslEngine(SslConnection connection) { if (connection instanceof UndertowSslConnection) { return ((UndertowSslConnection) connection).getSSLEngine(); } else { return JsseXnioSsl.getSslEngine(connection); } }
[ "public", "static", "SSLEngine", "getSslEngine", "(", "SslConnection", "connection", ")", "{", "if", "(", "connection", "instanceof", "UndertowSslConnection", ")", "{", "return", "(", "(", "UndertowSslConnection", ")", "connection", ")", ".", "getSSLEngine", "(", ")", ";", "}", "else", "{", "return", "JsseXnioSsl", ".", "getSslEngine", "(", "connection", ")", ";", "}", "}" ]
Get the SSL engine for a given connection. @return the SSL engine
[ "Get", "the", "SSL", "engine", "for", "a", "given", "connection", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/ssl/UndertowXnioSsl.java#L144-L150
16,727
undertow-io/undertow
core/src/main/java/io/undertow/protocols/ssl/UndertowXnioSsl.java
UndertowXnioSsl.createSSLEngine
private static SSLEngine createSSLEngine(SSLContext sslContext, OptionMap optionMap, InetSocketAddress peerAddress, boolean client) { final SSLEngine engine = sslContext.createSSLEngine( optionMap.get(Options.SSL_PEER_HOST_NAME, peerAddress.getHostString()), optionMap.get(Options.SSL_PEER_PORT, peerAddress.getPort()) ); engine.setUseClientMode(client); engine.setEnableSessionCreation(optionMap.get(Options.SSL_ENABLE_SESSION_CREATION, true)); final Sequence<String> cipherSuites = optionMap.get(Options.SSL_ENABLED_CIPHER_SUITES); if (cipherSuites != null) { final Set<String> supported = new HashSet<String>(Arrays.asList(engine.getSupportedCipherSuites())); final List<String> finalList = new ArrayList<String>(); for (String name : cipherSuites) { if (supported.contains(name)) { finalList.add(name); } } engine.setEnabledCipherSuites(finalList.toArray(new String[finalList.size()])); } final Sequence<String> protocols = optionMap.get(Options.SSL_ENABLED_PROTOCOLS); if (protocols != null) { final Set<String> supported = new HashSet<String>(Arrays.asList(engine.getSupportedProtocols())); final List<String> finalList = new ArrayList<String>(); for (String name : protocols) { if (supported.contains(name)) { finalList.add(name); } } engine.setEnabledProtocols(finalList.toArray(new String[finalList.size()])); } return engine; }
java
private static SSLEngine createSSLEngine(SSLContext sslContext, OptionMap optionMap, InetSocketAddress peerAddress, boolean client) { final SSLEngine engine = sslContext.createSSLEngine( optionMap.get(Options.SSL_PEER_HOST_NAME, peerAddress.getHostString()), optionMap.get(Options.SSL_PEER_PORT, peerAddress.getPort()) ); engine.setUseClientMode(client); engine.setEnableSessionCreation(optionMap.get(Options.SSL_ENABLE_SESSION_CREATION, true)); final Sequence<String> cipherSuites = optionMap.get(Options.SSL_ENABLED_CIPHER_SUITES); if (cipherSuites != null) { final Set<String> supported = new HashSet<String>(Arrays.asList(engine.getSupportedCipherSuites())); final List<String> finalList = new ArrayList<String>(); for (String name : cipherSuites) { if (supported.contains(name)) { finalList.add(name); } } engine.setEnabledCipherSuites(finalList.toArray(new String[finalList.size()])); } final Sequence<String> protocols = optionMap.get(Options.SSL_ENABLED_PROTOCOLS); if (protocols != null) { final Set<String> supported = new HashSet<String>(Arrays.asList(engine.getSupportedProtocols())); final List<String> finalList = new ArrayList<String>(); for (String name : protocols) { if (supported.contains(name)) { finalList.add(name); } } engine.setEnabledProtocols(finalList.toArray(new String[finalList.size()])); } return engine; }
[ "private", "static", "SSLEngine", "createSSLEngine", "(", "SSLContext", "sslContext", ",", "OptionMap", "optionMap", ",", "InetSocketAddress", "peerAddress", ",", "boolean", "client", ")", "{", "final", "SSLEngine", "engine", "=", "sslContext", ".", "createSSLEngine", "(", "optionMap", ".", "get", "(", "Options", ".", "SSL_PEER_HOST_NAME", ",", "peerAddress", ".", "getHostString", "(", ")", ")", ",", "optionMap", ".", "get", "(", "Options", ".", "SSL_PEER_PORT", ",", "peerAddress", ".", "getPort", "(", ")", ")", ")", ";", "engine", ".", "setUseClientMode", "(", "client", ")", ";", "engine", ".", "setEnableSessionCreation", "(", "optionMap", ".", "get", "(", "Options", ".", "SSL_ENABLE_SESSION_CREATION", ",", "true", ")", ")", ";", "final", "Sequence", "<", "String", ">", "cipherSuites", "=", "optionMap", ".", "get", "(", "Options", ".", "SSL_ENABLED_CIPHER_SUITES", ")", ";", "if", "(", "cipherSuites", "!=", "null", ")", "{", "final", "Set", "<", "String", ">", "supported", "=", "new", "HashSet", "<", "String", ">", "(", "Arrays", ".", "asList", "(", "engine", ".", "getSupportedCipherSuites", "(", ")", ")", ")", ";", "final", "List", "<", "String", ">", "finalList", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "String", "name", ":", "cipherSuites", ")", "{", "if", "(", "supported", ".", "contains", "(", "name", ")", ")", "{", "finalList", ".", "add", "(", "name", ")", ";", "}", "}", "engine", ".", "setEnabledCipherSuites", "(", "finalList", ".", "toArray", "(", "new", "String", "[", "finalList", ".", "size", "(", ")", "]", ")", ")", ";", "}", "final", "Sequence", "<", "String", ">", "protocols", "=", "optionMap", ".", "get", "(", "Options", ".", "SSL_ENABLED_PROTOCOLS", ")", ";", "if", "(", "protocols", "!=", "null", ")", "{", "final", "Set", "<", "String", ">", "supported", "=", "new", "HashSet", "<", "String", ">", "(", "Arrays", ".", "asList", "(", "engine", ".", "getSupportedProtocols", "(", ")", ")", ")", ";", "final", "List", "<", "String", ">", "finalList", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "String", "name", ":", "protocols", ")", "{", "if", "(", "supported", ".", "contains", "(", "name", ")", ")", "{", "finalList", ".", "add", "(", "name", ")", ";", "}", "}", "engine", ".", "setEnabledProtocols", "(", "finalList", ".", "toArray", "(", "new", "String", "[", "finalList", ".", "size", "(", ")", "]", ")", ")", ";", "}", "return", "engine", ";", "}" ]
Create a new SSL engine, configured from an option map. @param sslContext the SSL context @param optionMap the SSL options @param peerAddress the peer address of the connection @return the configured SSL engine
[ "Create", "a", "new", "SSL", "engine", "configured", "from", "an", "option", "map", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/ssl/UndertowXnioSsl.java#L214-L244
16,728
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/sse/ServerSentEventConnection.java
ServerSentEventConnection.sendRetry
public synchronized void sendRetry(long retry, EventCallback callback) { if (open == 0 || shutdown) { if (callback != null) { callback.failed(this, null, null, null, new ClosedChannelException()); } return; } queue.add(new SSEData(retry, callback)); sink.getIoThread().execute(new Runnable() { @Override public void run() { synchronized (ServerSentEventConnection.this) { if (pooled == null) { fillBuffer(); writeListener.handleEvent(sink); } } } }); }
java
public synchronized void sendRetry(long retry, EventCallback callback) { if (open == 0 || shutdown) { if (callback != null) { callback.failed(this, null, null, null, new ClosedChannelException()); } return; } queue.add(new SSEData(retry, callback)); sink.getIoThread().execute(new Runnable() { @Override public void run() { synchronized (ServerSentEventConnection.this) { if (pooled == null) { fillBuffer(); writeListener.handleEvent(sink); } } } }); }
[ "public", "synchronized", "void", "sendRetry", "(", "long", "retry", ",", "EventCallback", "callback", ")", "{", "if", "(", "open", "==", "0", "||", "shutdown", ")", "{", "if", "(", "callback", "!=", "null", ")", "{", "callback", ".", "failed", "(", "this", ",", "null", ",", "null", ",", "null", ",", "new", "ClosedChannelException", "(", ")", ")", ";", "}", "return", ";", "}", "queue", ".", "add", "(", "new", "SSEData", "(", "retry", ",", "callback", ")", ")", ";", "sink", ".", "getIoThread", "(", ")", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "synchronized", "(", "ServerSentEventConnection", ".", "this", ")", "{", "if", "(", "pooled", "==", "null", ")", "{", "fillBuffer", "(", ")", ";", "writeListener", ".", "handleEvent", "(", "sink", ")", ";", "}", "}", "}", "}", ")", ";", "}" ]
Sends the 'retry' message to the client, instructing it how long to wait before attempting a reconnect. @param retry The retry time in milliseconds @param callback The callback that is notified on success or failure
[ "Sends", "the", "retry", "message", "to", "the", "client", "instructing", "it", "how", "long", "to", "wait", "before", "attempting", "a", "reconnect", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/sse/ServerSentEventConnection.java#L213-L233
16,729
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/sse/ServerSentEventConnection.java
ServerSentEventConnection.shutdown
public void shutdown() { if (open == 0 || shutdown) { return; } shutdown = true; sink.getIoThread().execute(new Runnable() { @Override public void run() { synchronized (ServerSentEventConnection.this) { if (queue.isEmpty() && pooled == null) { exchange.endExchange(); } } } }); }
java
public void shutdown() { if (open == 0 || shutdown) { return; } shutdown = true; sink.getIoThread().execute(new Runnable() { @Override public void run() { synchronized (ServerSentEventConnection.this) { if (queue.isEmpty() && pooled == null) { exchange.endExchange(); } } } }); }
[ "public", "void", "shutdown", "(", ")", "{", "if", "(", "open", "==", "0", "||", "shutdown", ")", "{", "return", ";", "}", "shutdown", "=", "true", ";", "sink", ".", "getIoThread", "(", ")", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "synchronized", "(", "ServerSentEventConnection", ".", "this", ")", "{", "if", "(", "queue", ".", "isEmpty", "(", ")", "&&", "pooled", "==", "null", ")", "{", "exchange", ".", "endExchange", "(", ")", ";", "}", "}", "}", "}", ")", ";", "}" ]
execute a graceful shutdown once all data has been sent
[ "execute", "a", "graceful", "shutdown", "once", "all", "data", "has", "been", "sent" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/sse/ServerSentEventConnection.java#L406-L422
16,730
undertow-io/undertow
websockets-jsr/src/main/java/io/undertow/websockets/jsr/util/ClassUtils.java
ClassUtils.getHandlerTypes
public static Map<Class<?>, Boolean> getHandlerTypes(Class<? extends MessageHandler> clazz) { Map<Class<?>, Boolean> types = new IdentityHashMap<>(2); for (Class<?> c = clazz; c != Object.class; c = c.getSuperclass()) { exampleGenericInterfaces(types, c, clazz); } if (types.isEmpty()) { throw JsrWebSocketMessages.MESSAGES.unknownHandlerType(clazz); } return types; }
java
public static Map<Class<?>, Boolean> getHandlerTypes(Class<? extends MessageHandler> clazz) { Map<Class<?>, Boolean> types = new IdentityHashMap<>(2); for (Class<?> c = clazz; c != Object.class; c = c.getSuperclass()) { exampleGenericInterfaces(types, c, clazz); } if (types.isEmpty()) { throw JsrWebSocketMessages.MESSAGES.unknownHandlerType(clazz); } return types; }
[ "public", "static", "Map", "<", "Class", "<", "?", ">", ",", "Boolean", ">", "getHandlerTypes", "(", "Class", "<", "?", "extends", "MessageHandler", ">", "clazz", ")", "{", "Map", "<", "Class", "<", "?", ">", ",", "Boolean", ">", "types", "=", "new", "IdentityHashMap", "<>", "(", "2", ")", ";", "for", "(", "Class", "<", "?", ">", "c", "=", "clazz", ";", "c", "!=", "Object", ".", "class", ";", "c", "=", "c", ".", "getSuperclass", "(", ")", ")", "{", "exampleGenericInterfaces", "(", "types", ",", "c", ",", "clazz", ")", ";", "}", "if", "(", "types", ".", "isEmpty", "(", ")", ")", "{", "throw", "JsrWebSocketMessages", ".", "MESSAGES", ".", "unknownHandlerType", "(", "clazz", ")", ";", "}", "return", "types", ";", "}" ]
Returns a map of all supported message types by the given handler class. The key of the map is the supported message type; the value indicates whether it is a partial message handler or not. @return a map of all supported message types by the given handler class.
[ "Returns", "a", "map", "of", "all", "supported", "message", "types", "by", "the", "given", "handler", "class", ".", "The", "key", "of", "the", "map", "is", "the", "supported", "message", "type", ";", "the", "value", "indicates", "whether", "it", "is", "a", "partial", "message", "handler", "or", "not", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/websockets-jsr/src/main/java/io/undertow/websockets/jsr/util/ClassUtils.java#L50-L59
16,731
undertow-io/undertow
core/src/main/java/io/undertow/util/DateUtils.java
DateUtils.toDateString
public static String toDateString(final Date date) { SimpleDateFormat df = RFC1123_PATTERN_FORMAT.get(); //we always need to set the time zone //because date format is stupid, and calling parse() can mutate the timezone //see UNDERTOW-458 df.setTimeZone(GMT_ZONE); return df.format(date); }
java
public static String toDateString(final Date date) { SimpleDateFormat df = RFC1123_PATTERN_FORMAT.get(); //we always need to set the time zone //because date format is stupid, and calling parse() can mutate the timezone //see UNDERTOW-458 df.setTimeZone(GMT_ZONE); return df.format(date); }
[ "public", "static", "String", "toDateString", "(", "final", "Date", "date", ")", "{", "SimpleDateFormat", "df", "=", "RFC1123_PATTERN_FORMAT", ".", "get", "(", ")", ";", "//we always need to set the time zone", "//because date format is stupid, and calling parse() can mutate the timezone", "//see UNDERTOW-458", "df", ".", "setTimeZone", "(", "GMT_ZONE", ")", ";", "return", "df", ".", "format", "(", "date", ")", ";", "}" ]
Converts a date to a format suitable for use in a HTTP request @param date The date @return The RFC-1123 formatted date
[ "Converts", "a", "date", "to", "a", "format", "suitable", "for", "use", "in", "a", "HTTP", "request" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/DateUtils.java#L102-L109
16,732
undertow-io/undertow
core/src/main/java/io/undertow/util/DateUtils.java
DateUtils.parseDate
public static Date parseDate(final String date) { /* IE9 sends a superflous lenght parameter after date in the If-Modified-Since header, which needs to be stripped before parsing. */ final int semicolonIndex = date.indexOf(';'); final String trimmedDate = semicolonIndex >= 0 ? date.substring(0, semicolonIndex) : date; ParsePosition pp = new ParsePosition(0); SimpleDateFormat dateFormat = RFC1123_PATTERN_FORMAT.get(); dateFormat.setTimeZone(GMT_ZONE); Date val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(RFC1036_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(ASCITIME_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(OLD_COOKIE_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } return null; }
java
public static Date parseDate(final String date) { /* IE9 sends a superflous lenght parameter after date in the If-Modified-Since header, which needs to be stripped before parsing. */ final int semicolonIndex = date.indexOf(';'); final String trimmedDate = semicolonIndex >= 0 ? date.substring(0, semicolonIndex) : date; ParsePosition pp = new ParsePosition(0); SimpleDateFormat dateFormat = RFC1123_PATTERN_FORMAT.get(); dateFormat.setTimeZone(GMT_ZONE); Date val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(RFC1036_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(ASCITIME_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(OLD_COOKIE_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } return null; }
[ "public", "static", "Date", "parseDate", "(", "final", "String", "date", ")", "{", "/*\n IE9 sends a superflous lenght parameter after date in the\n If-Modified-Since header, which needs to be stripped before\n parsing.\n\n */", "final", "int", "semicolonIndex", "=", "date", ".", "indexOf", "(", "'", "'", ")", ";", "final", "String", "trimmedDate", "=", "semicolonIndex", ">=", "0", "?", "date", ".", "substring", "(", "0", ",", "semicolonIndex", ")", ":", "date", ";", "ParsePosition", "pp", "=", "new", "ParsePosition", "(", "0", ")", ";", "SimpleDateFormat", "dateFormat", "=", "RFC1123_PATTERN_FORMAT", ".", "get", "(", ")", ";", "dateFormat", ".", "setTimeZone", "(", "GMT_ZONE", ")", ";", "Date", "val", "=", "dateFormat", ".", "parse", "(", "trimmedDate", ",", "pp", ")", ";", "if", "(", "val", "!=", "null", "&&", "pp", ".", "getIndex", "(", ")", "==", "trimmedDate", ".", "length", "(", ")", ")", "{", "return", "val", ";", "}", "pp", "=", "new", "ParsePosition", "(", "0", ")", ";", "dateFormat", "=", "new", "SimpleDateFormat", "(", "RFC1036_PATTERN", ",", "LOCALE_US", ")", ";", "dateFormat", ".", "setTimeZone", "(", "GMT_ZONE", ")", ";", "val", "=", "dateFormat", ".", "parse", "(", "trimmedDate", ",", "pp", ")", ";", "if", "(", "val", "!=", "null", "&&", "pp", ".", "getIndex", "(", ")", "==", "trimmedDate", ".", "length", "(", ")", ")", "{", "return", "val", ";", "}", "pp", "=", "new", "ParsePosition", "(", "0", ")", ";", "dateFormat", "=", "new", "SimpleDateFormat", "(", "ASCITIME_PATTERN", ",", "LOCALE_US", ")", ";", "dateFormat", ".", "setTimeZone", "(", "GMT_ZONE", ")", ";", "val", "=", "dateFormat", ".", "parse", "(", "trimmedDate", ",", "pp", ")", ";", "if", "(", "val", "!=", "null", "&&", "pp", ".", "getIndex", "(", ")", "==", "trimmedDate", ".", "length", "(", ")", ")", "{", "return", "val", ";", "}", "pp", "=", "new", "ParsePosition", "(", "0", ")", ";", "dateFormat", "=", "new", "SimpleDateFormat", "(", "OLD_COOKIE_PATTERN", ",", "LOCALE_US", ")", ";", "dateFormat", ".", "setTimeZone", "(", "GMT_ZONE", ")", ";", "val", "=", "dateFormat", ".", "parse", "(", "trimmedDate", ",", "pp", ")", ";", "if", "(", "val", "!=", "null", "&&", "pp", ".", "getIndex", "(", ")", "==", "trimmedDate", ".", "length", "(", ")", ")", "{", "return", "val", ";", "}", "return", "null", ";", "}" ]
Attempts to pass a HTTP date. @param date The date to parse @return The parsed date, or null if parsing failed
[ "Attempts", "to", "pass", "a", "HTTP", "date", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/DateUtils.java#L126-L171
16,733
undertow-io/undertow
core/src/main/java/io/undertow/util/DateUtils.java
DateUtils.handleIfUnmodifiedSince
public static boolean handleIfUnmodifiedSince(final HttpServerExchange exchange, final Date lastModified) { return handleIfUnmodifiedSince(exchange.getRequestHeaders().getFirst(Headers.IF_UNMODIFIED_SINCE), lastModified); }
java
public static boolean handleIfUnmodifiedSince(final HttpServerExchange exchange, final Date lastModified) { return handleIfUnmodifiedSince(exchange.getRequestHeaders().getFirst(Headers.IF_UNMODIFIED_SINCE), lastModified); }
[ "public", "static", "boolean", "handleIfUnmodifiedSince", "(", "final", "HttpServerExchange", "exchange", ",", "final", "Date", "lastModified", ")", "{", "return", "handleIfUnmodifiedSince", "(", "exchange", ".", "getRequestHeaders", "(", ")", ".", "getFirst", "(", "Headers", ".", "IF_UNMODIFIED_SINCE", ")", ",", "lastModified", ")", ";", "}" ]
Handles the if-unmodified-since header. returns true if the request should proceed, false otherwise @param exchange the exchange @param lastModified The last modified date @return
[ "Handles", "the", "if", "-", "unmodified", "-", "since", "header", ".", "returns", "true", "if", "the", "request", "should", "proceed", "false", "otherwise" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/DateUtils.java#L212-L214
16,734
undertow-io/undertow
core/src/main/java/io/undertow/util/FlexBase64.java
FlexBase64.encodeString
public static String encodeString(ByteBuffer source, boolean wrap) { return Encoder.encodeString(source, wrap, false); }
java
public static String encodeString(ByteBuffer source, boolean wrap) { return Encoder.encodeString(source, wrap, false); }
[ "public", "static", "String", "encodeString", "(", "ByteBuffer", "source", ",", "boolean", "wrap", ")", "{", "return", "Encoder", ".", "encodeString", "(", "source", ",", "wrap", ",", "false", ")", ";", "}" ]
Encodes a fixed and complete byte buffer into a Base64 String. <p>This method is only useful for applications which require a String and have all data to be encoded up-front. Note that byte arrays or buffers are almost always a better storage choice. They consume half the memory and can be reused (modified). In other words, it is almost always better to use {@link #encodeBytes}, {@link #createEncoder}, or {@link #createEncoderOutputStream} instead.</p> <pre><code> // Encodes "hello" FlexBase64.encodeString(ByteBuffer.wrap("hello".getBytes("US-ASCII")), false); </code></pre> @param source the byte buffer to encode from @param wrap whether or not to wrap the output at 76 chars with CRLFs @return a new String representing the Base64 output
[ "Encodes", "a", "fixed", "and", "complete", "byte", "buffer", "into", "a", "Base64", "String", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/FlexBase64.java#L232-L234
16,735
undertow-io/undertow
core/src/main/java/io/undertow/util/FlexBase64.java
FlexBase64.encodeStringURL
public static String encodeStringURL(ByteBuffer source, boolean wrap) { return Encoder.encodeString(source, wrap, true); }
java
public static String encodeStringURL(ByteBuffer source, boolean wrap) { return Encoder.encodeString(source, wrap, true); }
[ "public", "static", "String", "encodeStringURL", "(", "ByteBuffer", "source", ",", "boolean", "wrap", ")", "{", "return", "Encoder", ".", "encodeString", "(", "source", ",", "wrap", ",", "true", ")", ";", "}" ]
Encodes a fixed and complete byte buffer into a Base64url String. <p>This method is only useful for applications which require a String and have all data to be encoded up-front. Note that byte arrays or buffers are almost always a better storage choice. They consume half the memory and can be reused (modified). In other words, it is almost always better to use {@link #encodeBytes}, {@link #createEncoder}, or {@link #createEncoderOutputStream} instead.</p> <pre><code> // Encodes "hello" FlexBase64.encodeStringURL(ByteBuffer.wrap("hello".getBytes("US-ASCII")), false); </code></pre> @param source the byte buffer to encode from @param wrap whether or not to wrap the output at 76 chars with CRLFs @return a new String representing the Base64url output
[ "Encodes", "a", "fixed", "and", "complete", "byte", "buffer", "into", "a", "Base64url", "String", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/FlexBase64.java#L253-L255
16,736
undertow-io/undertow
core/src/main/java/io/undertow/util/FlexBase64.java
FlexBase64.encodeBytes
public static byte[] encodeBytes(byte[] source, int pos, int limit, boolean wrap) { return Encoder.encodeBytes(source, pos, limit, wrap, false); }
java
public static byte[] encodeBytes(byte[] source, int pos, int limit, boolean wrap) { return Encoder.encodeBytes(source, pos, limit, wrap, false); }
[ "public", "static", "byte", "[", "]", "encodeBytes", "(", "byte", "[", "]", "source", ",", "int", "pos", ",", "int", "limit", ",", "boolean", "wrap", ")", "{", "return", "Encoder", ".", "encodeBytes", "(", "source", ",", "pos", ",", "limit", ",", "wrap", ",", "false", ")", ";", "}" ]
Encodes a fixed and complete byte buffer into a Base64 byte array. <pre><code> // Encodes "ell" FlexBase64.encodeString("hello".getBytes("US-ASCII"), 1, 4, false); </code></pre> @param source the byte array to encode from @param pos the position to start encoding at @param limit the position to halt encoding at (exclusive) @param wrap whether or not to wrap at 76 characters with CRLFs @return a new byte array containing the encoded ASCII values
[ "Encodes", "a", "fixed", "and", "complete", "byte", "buffer", "into", "a", "Base64", "byte", "array", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/FlexBase64.java#L271-L273
16,737
undertow-io/undertow
core/src/main/java/io/undertow/util/FlexBase64.java
FlexBase64.encodeBytesURL
public static byte[] encodeBytesURL(byte[] source, int pos, int limit, boolean wrap) { return Encoder.encodeBytes(source, pos, limit, wrap, true); }
java
public static byte[] encodeBytesURL(byte[] source, int pos, int limit, boolean wrap) { return Encoder.encodeBytes(source, pos, limit, wrap, true); }
[ "public", "static", "byte", "[", "]", "encodeBytesURL", "(", "byte", "[", "]", "source", ",", "int", "pos", ",", "int", "limit", ",", "boolean", "wrap", ")", "{", "return", "Encoder", ".", "encodeBytes", "(", "source", ",", "pos", ",", "limit", ",", "wrap", ",", "true", ")", ";", "}" ]
Encodes a fixed and complete byte buffer into a Base64url byte array. <pre><code> // Encodes "ell" FlexBase64.encodeStringURL("hello".getBytes("US-ASCII"), 1, 4, false); </code></pre> @param source the byte array to encode from @param pos the position to start encoding at @param limit the position to halt encoding at (exclusive) @param wrap whether or not to wrap at 76 characters with CRLFs @return a new byte array containing the encoded ASCII values
[ "Encodes", "a", "fixed", "and", "complete", "byte", "buffer", "into", "a", "Base64url", "byte", "array", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/FlexBase64.java#L289-L291
16,738
undertow-io/undertow
core/src/main/java/io/undertow/util/FlexBase64.java
FlexBase64.createEncoderInputStream
public static EncoderInputStream createEncoderInputStream(InputStream source, int bufferSize, boolean wrap) { return new EncoderInputStream(source, bufferSize, wrap, false); }
java
public static EncoderInputStream createEncoderInputStream(InputStream source, int bufferSize, boolean wrap) { return new EncoderInputStream(source, bufferSize, wrap, false); }
[ "public", "static", "EncoderInputStream", "createEncoderInputStream", "(", "InputStream", "source", ",", "int", "bufferSize", ",", "boolean", "wrap", ")", "{", "return", "new", "EncoderInputStream", "(", "source", ",", "bufferSize", ",", "wrap", ",", "false", ")", ";", "}" ]
Creates an InputStream wrapper which encodes a source into base64 as it is read, until the source hits EOF. Upon hitting EOF, a standard base64 termination sequence will be readable. Clients can simply treat this input stream as if they were reading from a base64 encoded file. This stream attempts to read and encode in buffer size chunks from the source, in order to improve overall performance. Thus, BufferInputStream is not necessary and will lead to double buffering. <p>This stream is not thread-safe, and should not be shared between threads, without establishing a happens-before relationship.</p> @param source an input source to read from @param bufferSize the chunk size to buffer from the source @param wrap whether or not the stream should wrap base64 output at 76 characters @return an encoded input stream instance.
[ "Creates", "an", "InputStream", "wrapper", "which", "encodes", "a", "source", "into", "base64", "as", "it", "is", "read", "until", "the", "source", "hits", "EOF", ".", "Upon", "hitting", "EOF", "a", "standard", "base64", "termination", "sequence", "will", "be", "readable", ".", "Clients", "can", "simply", "treat", "this", "input", "stream", "as", "if", "they", "were", "reading", "from", "a", "base64", "encoded", "file", ".", "This", "stream", "attempts", "to", "read", "and", "encode", "in", "buffer", "size", "chunks", "from", "the", "source", "in", "order", "to", "improve", "overall", "performance", ".", "Thus", "BufferInputStream", "is", "not", "necessary", "and", "will", "lead", "to", "double", "buffering", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/FlexBase64.java#L404-L406
16,739
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http/HttpContinue.java
HttpContinue.sendContinueResponse
public static void sendContinueResponse(final HttpServerExchange exchange, final IoCallback callback) { if (!exchange.isResponseChannelAvailable()) { callback.onException(exchange, null, UndertowMessages.MESSAGES.cannotSendContinueResponse()); return; } internalSendContinueResponse(exchange, callback); }
java
public static void sendContinueResponse(final HttpServerExchange exchange, final IoCallback callback) { if (!exchange.isResponseChannelAvailable()) { callback.onException(exchange, null, UndertowMessages.MESSAGES.cannotSendContinueResponse()); return; } internalSendContinueResponse(exchange, callback); }
[ "public", "static", "void", "sendContinueResponse", "(", "final", "HttpServerExchange", "exchange", ",", "final", "IoCallback", "callback", ")", "{", "if", "(", "!", "exchange", ".", "isResponseChannelAvailable", "(", ")", ")", "{", "callback", ".", "onException", "(", "exchange", ",", "null", ",", "UndertowMessages", ".", "MESSAGES", ".", "cannotSendContinueResponse", "(", ")", ")", ";", "return", ";", "}", "internalSendContinueResponse", "(", "exchange", ",", "callback", ")", ";", "}" ]
Sends a continuation using async IO, and calls back when it is complete. @param exchange The exchange @param callback The completion callback
[ "Sends", "a", "continuation", "using", "async", "IO", "and", "calls", "back", "when", "it", "is", "complete", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http/HttpContinue.java#L101-L107
16,740
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http/HttpContinue.java
HttpContinue.createResponseSender
public static ContinueResponseSender createResponseSender(final HttpServerExchange exchange) throws IOException { if (!exchange.isResponseChannelAvailable()) { throw UndertowMessages.MESSAGES.cannotSendContinueResponse(); } if(exchange.getAttachment(ALREADY_SENT) != null) { return new ContinueResponseSender() { @Override public boolean send() throws IOException { return true; } @Override public void awaitWritable() throws IOException { } @Override public void awaitWritable(long time, TimeUnit timeUnit) throws IOException { } }; } HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange); exchange.putAttachment(ALREADY_SENT, true); newExchange.setStatusCode(StatusCodes.CONTINUE); newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0); final StreamSinkChannel responseChannel = newExchange.getResponseChannel(); return new ContinueResponseSender() { boolean shutdown = false; @Override public boolean send() throws IOException { if (!shutdown) { shutdown = true; responseChannel.shutdownWrites(); } return responseChannel.flush(); } @Override public void awaitWritable() throws IOException { responseChannel.awaitWritable(); } @Override public void awaitWritable(final long time, final TimeUnit timeUnit) throws IOException { responseChannel.awaitWritable(time, timeUnit); } }; }
java
public static ContinueResponseSender createResponseSender(final HttpServerExchange exchange) throws IOException { if (!exchange.isResponseChannelAvailable()) { throw UndertowMessages.MESSAGES.cannotSendContinueResponse(); } if(exchange.getAttachment(ALREADY_SENT) != null) { return new ContinueResponseSender() { @Override public boolean send() throws IOException { return true; } @Override public void awaitWritable() throws IOException { } @Override public void awaitWritable(long time, TimeUnit timeUnit) throws IOException { } }; } HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange); exchange.putAttachment(ALREADY_SENT, true); newExchange.setStatusCode(StatusCodes.CONTINUE); newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0); final StreamSinkChannel responseChannel = newExchange.getResponseChannel(); return new ContinueResponseSender() { boolean shutdown = false; @Override public boolean send() throws IOException { if (!shutdown) { shutdown = true; responseChannel.shutdownWrites(); } return responseChannel.flush(); } @Override public void awaitWritable() throws IOException { responseChannel.awaitWritable(); } @Override public void awaitWritable(final long time, final TimeUnit timeUnit) throws IOException { responseChannel.awaitWritable(time, timeUnit); } }; }
[ "public", "static", "ContinueResponseSender", "createResponseSender", "(", "final", "HttpServerExchange", "exchange", ")", "throws", "IOException", "{", "if", "(", "!", "exchange", ".", "isResponseChannelAvailable", "(", ")", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "cannotSendContinueResponse", "(", ")", ";", "}", "if", "(", "exchange", ".", "getAttachment", "(", "ALREADY_SENT", ")", "!=", "null", ")", "{", "return", "new", "ContinueResponseSender", "(", ")", "{", "@", "Override", "public", "boolean", "send", "(", ")", "throws", "IOException", "{", "return", "true", ";", "}", "@", "Override", "public", "void", "awaitWritable", "(", ")", "throws", "IOException", "{", "}", "@", "Override", "public", "void", "awaitWritable", "(", "long", "time", ",", "TimeUnit", "timeUnit", ")", "throws", "IOException", "{", "}", "}", ";", "}", "HttpServerExchange", "newExchange", "=", "exchange", ".", "getConnection", "(", ")", ".", "sendOutOfBandResponse", "(", "exchange", ")", ";", "exchange", ".", "putAttachment", "(", "ALREADY_SENT", ",", "true", ")", ";", "newExchange", ".", "setStatusCode", "(", "StatusCodes", ".", "CONTINUE", ")", ";", "newExchange", ".", "getResponseHeaders", "(", ")", ".", "put", "(", "Headers", ".", "CONTENT_LENGTH", ",", "0", ")", ";", "final", "StreamSinkChannel", "responseChannel", "=", "newExchange", ".", "getResponseChannel", "(", ")", ";", "return", "new", "ContinueResponseSender", "(", ")", "{", "boolean", "shutdown", "=", "false", ";", "@", "Override", "public", "boolean", "send", "(", ")", "throws", "IOException", "{", "if", "(", "!", "shutdown", ")", "{", "shutdown", "=", "true", ";", "responseChannel", ".", "shutdownWrites", "(", ")", ";", "}", "return", "responseChannel", ".", "flush", "(", ")", ";", "}", "@", "Override", "public", "void", "awaitWritable", "(", ")", "throws", "IOException", "{", "responseChannel", ".", "awaitWritable", "(", ")", ";", "}", "@", "Override", "public", "void", "awaitWritable", "(", "final", "long", "time", ",", "final", "TimeUnit", "timeUnit", ")", "throws", "IOException", "{", "responseChannel", ".", "awaitWritable", "(", "time", ",", "timeUnit", ")", ";", "}", "}", ";", "}" ]
Creates a response sender that can be used to send a HTTP 100-continue response. @param exchange The exchange @return The response sender
[ "Creates", "a", "response", "sender", "that", "can", "be", "used", "to", "send", "a", "HTTP", "100", "-", "continue", "response", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http/HttpContinue.java#L115-L166
16,741
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http/HttpContinue.java
HttpContinue.sendContinueResponseBlocking
public static void sendContinueResponseBlocking(final HttpServerExchange exchange) throws IOException { if (!exchange.isResponseChannelAvailable()) { throw UndertowMessages.MESSAGES.cannotSendContinueResponse(); } if(exchange.getAttachment(ALREADY_SENT) != null) { return; } HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange); exchange.putAttachment(ALREADY_SENT, true); newExchange.setStatusCode(StatusCodes.CONTINUE); newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0); newExchange.startBlocking(); newExchange.getOutputStream().close(); newExchange.getInputStream().close(); }
java
public static void sendContinueResponseBlocking(final HttpServerExchange exchange) throws IOException { if (!exchange.isResponseChannelAvailable()) { throw UndertowMessages.MESSAGES.cannotSendContinueResponse(); } if(exchange.getAttachment(ALREADY_SENT) != null) { return; } HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange); exchange.putAttachment(ALREADY_SENT, true); newExchange.setStatusCode(StatusCodes.CONTINUE); newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0); newExchange.startBlocking(); newExchange.getOutputStream().close(); newExchange.getInputStream().close(); }
[ "public", "static", "void", "sendContinueResponseBlocking", "(", "final", "HttpServerExchange", "exchange", ")", "throws", "IOException", "{", "if", "(", "!", "exchange", ".", "isResponseChannelAvailable", "(", ")", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "cannotSendContinueResponse", "(", ")", ";", "}", "if", "(", "exchange", ".", "getAttachment", "(", "ALREADY_SENT", ")", "!=", "null", ")", "{", "return", ";", "}", "HttpServerExchange", "newExchange", "=", "exchange", ".", "getConnection", "(", ")", ".", "sendOutOfBandResponse", "(", "exchange", ")", ";", "exchange", ".", "putAttachment", "(", "ALREADY_SENT", ",", "true", ")", ";", "newExchange", ".", "setStatusCode", "(", "StatusCodes", ".", "CONTINUE", ")", ";", "newExchange", ".", "getResponseHeaders", "(", ")", ".", "put", "(", "Headers", ".", "CONTENT_LENGTH", ",", "0", ")", ";", "newExchange", ".", "startBlocking", "(", ")", ";", "newExchange", ".", "getOutputStream", "(", ")", ".", "close", "(", ")", ";", "newExchange", ".", "getInputStream", "(", ")", ".", "close", "(", ")", ";", "}" ]
Sends a continue response using blocking IO @param exchange The exchange
[ "Sends", "a", "continue", "response", "using", "blocking", "IO" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http/HttpContinue.java#L183-L197
16,742
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http/HttpContinue.java
HttpContinue.rejectExchange
public static void rejectExchange(final HttpServerExchange exchange) { exchange.setStatusCode(StatusCodes.EXPECTATION_FAILED); exchange.setPersistent(false); exchange.endExchange(); }
java
public static void rejectExchange(final HttpServerExchange exchange) { exchange.setStatusCode(StatusCodes.EXPECTATION_FAILED); exchange.setPersistent(false); exchange.endExchange(); }
[ "public", "static", "void", "rejectExchange", "(", "final", "HttpServerExchange", "exchange", ")", "{", "exchange", ".", "setStatusCode", "(", "StatusCodes", ".", "EXPECTATION_FAILED", ")", ";", "exchange", ".", "setPersistent", "(", "false", ")", ";", "exchange", ".", "endExchange", "(", ")", ";", "}" ]
Sets a 417 response code and ends the exchange. @param exchange The exchange to reject
[ "Sets", "a", "417", "response", "code", "and", "ends", "the", "exchange", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http/HttpContinue.java#L204-L208
16,743
undertow-io/undertow
core/src/main/java/io/undertow/predicate/Predicates.java
Predicates.paths
public static Predicate paths(final String... paths) { final PathMatchPredicate[] predicates = new PathMatchPredicate[paths.length]; for (int i = 0; i < paths.length; ++i) { predicates[i] = new PathMatchPredicate(paths[i]); } return or(predicates); }
java
public static Predicate paths(final String... paths) { final PathMatchPredicate[] predicates = new PathMatchPredicate[paths.length]; for (int i = 0; i < paths.length; ++i) { predicates[i] = new PathMatchPredicate(paths[i]); } return or(predicates); }
[ "public", "static", "Predicate", "paths", "(", "final", "String", "...", "paths", ")", "{", "final", "PathMatchPredicate", "[", "]", "predicates", "=", "new", "PathMatchPredicate", "[", "paths", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paths", ".", "length", ";", "++", "i", ")", "{", "predicates", "[", "i", "]", "=", "new", "PathMatchPredicate", "(", "paths", "[", "i", "]", ")", ";", "}", "return", "or", "(", "predicates", ")", ";", "}" ]
Creates a predicate that returns true if any of the given paths match exactly.
[ "Creates", "a", "predicate", "that", "returns", "true", "if", "any", "of", "the", "given", "paths", "match", "exactly", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/predicate/Predicates.java#L75-L81
16,744
undertow-io/undertow
core/src/main/java/io/undertow/predicate/Predicates.java
Predicates.suffixes
public static Predicate suffixes(final String... paths) { if(paths.length == 1) { return suffix(paths[0]); } final PathSuffixPredicate[] predicates = new PathSuffixPredicate[paths.length]; for (int i = 0; i < paths.length; ++i) { predicates[i] = new PathSuffixPredicate(paths[i]); } return or(predicates); }
java
public static Predicate suffixes(final String... paths) { if(paths.length == 1) { return suffix(paths[0]); } final PathSuffixPredicate[] predicates = new PathSuffixPredicate[paths.length]; for (int i = 0; i < paths.length; ++i) { predicates[i] = new PathSuffixPredicate(paths[i]); } return or(predicates); }
[ "public", "static", "Predicate", "suffixes", "(", "final", "String", "...", "paths", ")", "{", "if", "(", "paths", ".", "length", "==", "1", ")", "{", "return", "suffix", "(", "paths", "[", "0", "]", ")", ";", "}", "final", "PathSuffixPredicate", "[", "]", "predicates", "=", "new", "PathSuffixPredicate", "[", "paths", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paths", ".", "length", ";", "++", "i", ")", "{", "predicates", "[", "i", "]", "=", "new", "PathSuffixPredicate", "(", "paths", "[", "i", "]", ")", ";", "}", "return", "or", "(", "predicates", ")", ";", "}" ]
Creates a predicate that returns true if the request path ends with any of the provided suffixes.
[ "Creates", "a", "predicate", "that", "returns", "true", "if", "the", "request", "path", "ends", "with", "any", "of", "the", "provided", "suffixes", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/predicate/Predicates.java#L93-L102
16,745
undertow-io/undertow
core/src/main/java/io/undertow/predicate/Predicates.java
Predicates.parse
public static Predicate parse(final String predicate) { return PredicateParser.parse(predicate, Thread.currentThread().getContextClassLoader()); }
java
public static Predicate parse(final String predicate) { return PredicateParser.parse(predicate, Thread.currentThread().getContextClassLoader()); }
[ "public", "static", "Predicate", "parse", "(", "final", "String", "predicate", ")", "{", "return", "PredicateParser", ".", "parse", "(", "predicate", ",", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ")", ";", "}" ]
parses the predicate string, and returns the result, using the TCCL to load predicate definitions @param predicate The prediate string @return The predicate
[ "parses", "the", "predicate", "string", "and", "returns", "the", "result", "using", "the", "TCCL", "to", "load", "predicate", "definitions" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/predicate/Predicates.java#L211-L213
16,746
undertow-io/undertow
core/src/main/java/io/undertow/predicate/Predicates.java
Predicates.parse
public static Predicate parse(final String predicate, ClassLoader classLoader) { return PredicateParser.parse(predicate, classLoader); }
java
public static Predicate parse(final String predicate, ClassLoader classLoader) { return PredicateParser.parse(predicate, classLoader); }
[ "public", "static", "Predicate", "parse", "(", "final", "String", "predicate", ",", "ClassLoader", "classLoader", ")", "{", "return", "PredicateParser", ".", "parse", "(", "predicate", ",", "classLoader", ")", ";", "}" ]
parses the predicate string, and returns the result @param predicate The prediate string @param classLoader The class loader to load the predicates from @return The predicate
[ "parses", "the", "predicate", "string", "and", "returns", "the", "result" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/predicate/Predicates.java#L221-L223
16,747
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/HpackDecoder.java
HpackDecoder.handleIndex
private void handleIndex(int index) throws HpackException { if (index <= Hpack.STATIC_TABLE_LENGTH) { addStaticTableEntry(index); } else { int adjustedIndex = getRealIndex(index - Hpack.STATIC_TABLE_LENGTH); HeaderField headerField = headerTable[adjustedIndex]; headerEmitter.emitHeader(headerField.name, headerField.value, false); } }
java
private void handleIndex(int index) throws HpackException { if (index <= Hpack.STATIC_TABLE_LENGTH) { addStaticTableEntry(index); } else { int adjustedIndex = getRealIndex(index - Hpack.STATIC_TABLE_LENGTH); HeaderField headerField = headerTable[adjustedIndex]; headerEmitter.emitHeader(headerField.name, headerField.value, false); } }
[ "private", "void", "handleIndex", "(", "int", "index", ")", "throws", "HpackException", "{", "if", "(", "index", "<=", "Hpack", ".", "STATIC_TABLE_LENGTH", ")", "{", "addStaticTableEntry", "(", "index", ")", ";", "}", "else", "{", "int", "adjustedIndex", "=", "getRealIndex", "(", "index", "-", "Hpack", ".", "STATIC_TABLE_LENGTH", ")", ";", "HeaderField", "headerField", "=", "headerTable", "[", "adjustedIndex", "]", ";", "headerEmitter", ".", "emitHeader", "(", "headerField", ".", "name", ",", "headerField", ".", "value", ",", "false", ")", ";", "}", "}" ]
Handle an indexed header representation @param index The index @throws HpackException
[ "Handle", "an", "indexed", "header", "representation" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/HpackDecoder.java#L288-L296
16,748
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/resource/DirectoryUtils.java
DirectoryUtils.sendRequestedBlobs
public static boolean sendRequestedBlobs(HttpServerExchange exchange) { ByteBuffer buffer = null; String type = null; String etag = null; String quotedEtag = null; if ("css".equals(exchange.getQueryString())) { buffer = Blobs.FILE_CSS_BUFFER.duplicate(); type = "text/css"; etag = Blobs.FILE_CSS_ETAG; quotedEtag = Blobs.FILE_CSS_ETAG_QUOTED; } else if ("js".equals(exchange.getQueryString())) { buffer = Blobs.FILE_JS_BUFFER.duplicate(); type = "application/javascript"; etag = Blobs.FILE_JS_ETAG; quotedEtag = Blobs.FILE_JS_ETAG_QUOTED; } if (buffer != null) { if(!ETagUtils.handleIfNoneMatch(exchange, new ETag(false, etag), false)) { exchange.setStatusCode(StatusCodes.NOT_MODIFIED); return true; } exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(buffer.limit())); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, type); exchange.getResponseHeaders().put(Headers.ETAG, quotedEtag); if (Methods.HEAD.equals(exchange.getRequestMethod())) { exchange.endExchange(); return true; } exchange.getResponseSender().send(buffer); return true; } return false; }
java
public static boolean sendRequestedBlobs(HttpServerExchange exchange) { ByteBuffer buffer = null; String type = null; String etag = null; String quotedEtag = null; if ("css".equals(exchange.getQueryString())) { buffer = Blobs.FILE_CSS_BUFFER.duplicate(); type = "text/css"; etag = Blobs.FILE_CSS_ETAG; quotedEtag = Blobs.FILE_CSS_ETAG_QUOTED; } else if ("js".equals(exchange.getQueryString())) { buffer = Blobs.FILE_JS_BUFFER.duplicate(); type = "application/javascript"; etag = Blobs.FILE_JS_ETAG; quotedEtag = Blobs.FILE_JS_ETAG_QUOTED; } if (buffer != null) { if(!ETagUtils.handleIfNoneMatch(exchange, new ETag(false, etag), false)) { exchange.setStatusCode(StatusCodes.NOT_MODIFIED); return true; } exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(buffer.limit())); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, type); exchange.getResponseHeaders().put(Headers.ETAG, quotedEtag); if (Methods.HEAD.equals(exchange.getRequestMethod())) { exchange.endExchange(); return true; } exchange.getResponseSender().send(buffer); return true; } return false; }
[ "public", "static", "boolean", "sendRequestedBlobs", "(", "HttpServerExchange", "exchange", ")", "{", "ByteBuffer", "buffer", "=", "null", ";", "String", "type", "=", "null", ";", "String", "etag", "=", "null", ";", "String", "quotedEtag", "=", "null", ";", "if", "(", "\"css\"", ".", "equals", "(", "exchange", ".", "getQueryString", "(", ")", ")", ")", "{", "buffer", "=", "Blobs", ".", "FILE_CSS_BUFFER", ".", "duplicate", "(", ")", ";", "type", "=", "\"text/css\"", ";", "etag", "=", "Blobs", ".", "FILE_CSS_ETAG", ";", "quotedEtag", "=", "Blobs", ".", "FILE_CSS_ETAG_QUOTED", ";", "}", "else", "if", "(", "\"js\"", ".", "equals", "(", "exchange", ".", "getQueryString", "(", ")", ")", ")", "{", "buffer", "=", "Blobs", ".", "FILE_JS_BUFFER", ".", "duplicate", "(", ")", ";", "type", "=", "\"application/javascript\"", ";", "etag", "=", "Blobs", ".", "FILE_JS_ETAG", ";", "quotedEtag", "=", "Blobs", ".", "FILE_JS_ETAG_QUOTED", ";", "}", "if", "(", "buffer", "!=", "null", ")", "{", "if", "(", "!", "ETagUtils", ".", "handleIfNoneMatch", "(", "exchange", ",", "new", "ETag", "(", "false", ",", "etag", ")", ",", "false", ")", ")", "{", "exchange", ".", "setStatusCode", "(", "StatusCodes", ".", "NOT_MODIFIED", ")", ";", "return", "true", ";", "}", "exchange", ".", "getResponseHeaders", "(", ")", ".", "put", "(", "Headers", ".", "CONTENT_LENGTH", ",", "String", ".", "valueOf", "(", "buffer", ".", "limit", "(", ")", ")", ")", ";", "exchange", ".", "getResponseHeaders", "(", ")", ".", "put", "(", "Headers", ".", "CONTENT_TYPE", ",", "type", ")", ";", "exchange", ".", "getResponseHeaders", "(", ")", ".", "put", "(", "Headers", ".", "ETAG", ",", "quotedEtag", ")", ";", "if", "(", "Methods", ".", "HEAD", ".", "equals", "(", "exchange", ".", "getRequestMethod", "(", ")", ")", ")", "{", "exchange", ".", "endExchange", "(", ")", ";", "return", "true", ";", "}", "exchange", ".", "getResponseSender", "(", ")", ".", "send", "(", "buffer", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Serve static resource for the directory listing @param exchange The exchange @return true if resources were served
[ "Serve", "static", "resource", "for", "the", "directory", "listing" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/resource/DirectoryUtils.java#L54-L91
16,749
undertow-io/undertow
core/src/main/java/io/undertow/websockets/WebSocketProtocolHandshakeHandler.java
WebSocketProtocolHandshakeHandler.addExtension
public WebSocketProtocolHandshakeHandler addExtension(ExtensionHandshake extension) { if (extension != null) { for (Handshake handshake : handshakes) { handshake.addExtension(extension); } } return this; }
java
public WebSocketProtocolHandshakeHandler addExtension(ExtensionHandshake extension) { if (extension != null) { for (Handshake handshake : handshakes) { handshake.addExtension(extension); } } return this; }
[ "public", "WebSocketProtocolHandshakeHandler", "addExtension", "(", "ExtensionHandshake", "extension", ")", "{", "if", "(", "extension", "!=", "null", ")", "{", "for", "(", "Handshake", "handshake", ":", "handshakes", ")", "{", "handshake", ".", "addExtension", "(", "extension", ")", ";", "}", "}", "return", "this", ";", "}" ]
Add a new WebSocket Extension into the handshakes defined in this handler. @param extension a new {@code ExtensionHandshake} instance @return current handler
[ "Add", "a", "new", "WebSocket", "Extension", "into", "the", "handshakes", "defined", "in", "this", "handler", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/WebSocketProtocolHandshakeHandler.java#L218-L225
16,750
undertow-io/undertow
core/src/main/java/io/undertow/util/WorkerUtils.java
WorkerUtils.executeAfter
public static XnioExecutor.Key executeAfter(XnioIoThread thread, Runnable task, long timeout, TimeUnit timeUnit) { try { return thread.executeAfter(task, timeout, timeUnit); } catch (RejectedExecutionException e) { if(thread.getWorker().isShutdown()) { UndertowLogger.ROOT_LOGGER.debugf(e, "Failed to schedule task %s as worker is shutting down", task); //we just return a bogus key in this case return new XnioExecutor.Key() { @Override public boolean remove() { return false; } }; } else { throw e; } } }
java
public static XnioExecutor.Key executeAfter(XnioIoThread thread, Runnable task, long timeout, TimeUnit timeUnit) { try { return thread.executeAfter(task, timeout, timeUnit); } catch (RejectedExecutionException e) { if(thread.getWorker().isShutdown()) { UndertowLogger.ROOT_LOGGER.debugf(e, "Failed to schedule task %s as worker is shutting down", task); //we just return a bogus key in this case return new XnioExecutor.Key() { @Override public boolean remove() { return false; } }; } else { throw e; } } }
[ "public", "static", "XnioExecutor", ".", "Key", "executeAfter", "(", "XnioIoThread", "thread", ",", "Runnable", "task", ",", "long", "timeout", ",", "TimeUnit", "timeUnit", ")", "{", "try", "{", "return", "thread", ".", "executeAfter", "(", "task", ",", "timeout", ",", "timeUnit", ")", ";", "}", "catch", "(", "RejectedExecutionException", "e", ")", "{", "if", "(", "thread", ".", "getWorker", "(", ")", ".", "isShutdown", "(", ")", ")", "{", "UndertowLogger", ".", "ROOT_LOGGER", ".", "debugf", "(", "e", ",", "\"Failed to schedule task %s as worker is shutting down\"", ",", "task", ")", ";", "//we just return a bogus key in this case", "return", "new", "XnioExecutor", ".", "Key", "(", ")", "{", "@", "Override", "public", "boolean", "remove", "(", ")", "{", "return", "false", ";", "}", "}", ";", "}", "else", "{", "throw", "e", ";", "}", "}", "}" ]
Schedules a task for future execution. If the execution is rejected because the worker is shutting down then it is logged at debug level and the exception is not re-thrown @param thread The IO thread @param task The task to execute @param timeout The timeout @param timeUnit The time unit
[ "Schedules", "a", "task", "for", "future", "execution", ".", "If", "the", "execution", "is", "rejected", "because", "the", "worker", "is", "shutting", "down", "then", "it", "is", "logged", "at", "debug", "level", "and", "the", "exception", "is", "not", "re", "-", "thrown" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/WorkerUtils.java#L44-L61
16,751
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/handlers/security/ServletConfidentialityConstraintHandler.java
ServletConfidentialityConstraintHandler.isConfidential
protected boolean isConfidential(final HttpServerExchange exchange) { ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); if(src != null) { return src.getOriginalRequest().isSecure(); } return super.isConfidential(exchange); }
java
protected boolean isConfidential(final HttpServerExchange exchange) { ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); if(src != null) { return src.getOriginalRequest().isSecure(); } return super.isConfidential(exchange); }
[ "protected", "boolean", "isConfidential", "(", "final", "HttpServerExchange", "exchange", ")", "{", "ServletRequestContext", "src", "=", "exchange", ".", "getAttachment", "(", "ServletRequestContext", ".", "ATTACHMENT_KEY", ")", ";", "if", "(", "src", "!=", "null", ")", "{", "return", "src", ".", "getOriginalRequest", "(", ")", ".", "isSecure", "(", ")", ";", "}", "return", "super", ".", "isConfidential", "(", "exchange", ")", ";", "}" ]
Use the HttpServerExchange supplied to check if this request is already 'sufficiently' confidential. Here we say 'sufficiently' as sub-classes can override this and maybe even go so far as querying the actual SSLSession. @param exchange - The {@link HttpServerExchange} for the request being processed. @return true if the request is 'sufficiently' confidential, false otherwise.
[ "Use", "the", "HttpServerExchange", "supplied", "to", "check", "if", "this", "request", "is", "already", "sufficiently", "confidential", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/handlers/security/ServletConfidentialityConstraintHandler.java#L94-L100
16,752
undertow-io/undertow
core/src/main/java/io/undertow/util/HexConverter.java
HexConverter.convertToHexString
public static String convertToHexString(byte[] toBeConverted) { if (toBeConverted == null) { throw new NullPointerException("Parameter to be converted can not be null"); } char[] converted = new char[toBeConverted.length * 2]; for (int i = 0; i < toBeConverted.length; i++) { byte b = toBeConverted[i]; converted[i * 2] = HEX_CHARS[b >> 4 & 0x0F]; converted[i * 2 + 1] = HEX_CHARS[b & 0x0F]; } return String.valueOf(converted); }
java
public static String convertToHexString(byte[] toBeConverted) { if (toBeConverted == null) { throw new NullPointerException("Parameter to be converted can not be null"); } char[] converted = new char[toBeConverted.length * 2]; for (int i = 0; i < toBeConverted.length; i++) { byte b = toBeConverted[i]; converted[i * 2] = HEX_CHARS[b >> 4 & 0x0F]; converted[i * 2 + 1] = HEX_CHARS[b & 0x0F]; } return String.valueOf(converted); }
[ "public", "static", "String", "convertToHexString", "(", "byte", "[", "]", "toBeConverted", ")", "{", "if", "(", "toBeConverted", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Parameter to be converted can not be null\"", ")", ";", "}", "char", "[", "]", "converted", "=", "new", "char", "[", "toBeConverted", ".", "length", "*", "2", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "toBeConverted", ".", "length", ";", "i", "++", ")", "{", "byte", "b", "=", "toBeConverted", "[", "i", "]", ";", "converted", "[", "i", "*", "2", "]", "=", "HEX_CHARS", "[", "b", ">>", "4", "&", "0x0F", "]", ";", "converted", "[", "i", "*", "2", "+", "1", "]", "=", "HEX_CHARS", "[", "b", "&", "0x0F", "]", ";", "}", "return", "String", ".", "valueOf", "(", "converted", ")", ";", "}" ]
Take the supplied byte array and convert it to a hex encoded String. @param toBeConverted - the bytes to be converted. @return the hex encoded String.
[ "Take", "the", "supplied", "byte", "array", "and", "convert", "it", "to", "a", "hex", "encoded", "String", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/HexConverter.java#L40-L53
16,753
undertow-io/undertow
core/src/main/java/io/undertow/server/Connectors.java
Connectors.flattenCookies
public static void flattenCookies(final HttpServerExchange exchange) { Map<String, Cookie> cookies = exchange.getResponseCookiesInternal(); boolean enableRfc6265Validation = exchange.getConnection().getUndertowOptions().get(UndertowOptions.ENABLE_RFC6265_COOKIE_VALIDATION, UndertowOptions.DEFAULT_ENABLE_RFC6265_COOKIE_VALIDATION); if (cookies != null) { for (Map.Entry<String, Cookie> entry : cookies.entrySet()) { exchange.getResponseHeaders().add(Headers.SET_COOKIE, getCookieString(entry.getValue(), enableRfc6265Validation)); } } }
java
public static void flattenCookies(final HttpServerExchange exchange) { Map<String, Cookie> cookies = exchange.getResponseCookiesInternal(); boolean enableRfc6265Validation = exchange.getConnection().getUndertowOptions().get(UndertowOptions.ENABLE_RFC6265_COOKIE_VALIDATION, UndertowOptions.DEFAULT_ENABLE_RFC6265_COOKIE_VALIDATION); if (cookies != null) { for (Map.Entry<String, Cookie> entry : cookies.entrySet()) { exchange.getResponseHeaders().add(Headers.SET_COOKIE, getCookieString(entry.getValue(), enableRfc6265Validation)); } } }
[ "public", "static", "void", "flattenCookies", "(", "final", "HttpServerExchange", "exchange", ")", "{", "Map", "<", "String", ",", "Cookie", ">", "cookies", "=", "exchange", ".", "getResponseCookiesInternal", "(", ")", ";", "boolean", "enableRfc6265Validation", "=", "exchange", ".", "getConnection", "(", ")", ".", "getUndertowOptions", "(", ")", ".", "get", "(", "UndertowOptions", ".", "ENABLE_RFC6265_COOKIE_VALIDATION", ",", "UndertowOptions", ".", "DEFAULT_ENABLE_RFC6265_COOKIE_VALIDATION", ")", ";", "if", "(", "cookies", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Cookie", ">", "entry", ":", "cookies", ".", "entrySet", "(", ")", ")", "{", "exchange", ".", "getResponseHeaders", "(", ")", ".", "add", "(", "Headers", ".", "SET_COOKIE", ",", "getCookieString", "(", "entry", ".", "getValue", "(", ")", ",", "enableRfc6265Validation", ")", ")", ";", "}", "}", "}" ]
Flattens the exchange cookie map into the response header map. This should be called by a connector just before the response is started. @param exchange The server exchange
[ "Flattens", "the", "exchange", "cookie", "map", "into", "the", "response", "header", "map", ".", "This", "should", "be", "called", "by", "a", "connector", "just", "before", "the", "response", "is", "started", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/Connectors.java#L94-L102
16,754
undertow-io/undertow
core/src/main/java/io/undertow/server/Connectors.java
Connectors.ungetRequestBytes
public static void ungetRequestBytes(final HttpServerExchange exchange, PooledByteBuffer... buffers) { PooledByteBuffer[] existing = exchange.getAttachment(HttpServerExchange.BUFFERED_REQUEST_DATA); PooledByteBuffer[] newArray; if (existing == null) { newArray = new PooledByteBuffer[buffers.length]; System.arraycopy(buffers, 0, newArray, 0, buffers.length); } else { newArray = new PooledByteBuffer[existing.length + buffers.length]; System.arraycopy(existing, 0, newArray, 0, existing.length); System.arraycopy(buffers, 0, newArray, existing.length, buffers.length); } exchange.putAttachment(HttpServerExchange.BUFFERED_REQUEST_DATA, newArray); //todo: force some kind of wakeup? exchange.addExchangeCompleteListener(BufferedRequestDataCleanupListener.INSTANCE); }
java
public static void ungetRequestBytes(final HttpServerExchange exchange, PooledByteBuffer... buffers) { PooledByteBuffer[] existing = exchange.getAttachment(HttpServerExchange.BUFFERED_REQUEST_DATA); PooledByteBuffer[] newArray; if (existing == null) { newArray = new PooledByteBuffer[buffers.length]; System.arraycopy(buffers, 0, newArray, 0, buffers.length); } else { newArray = new PooledByteBuffer[existing.length + buffers.length]; System.arraycopy(existing, 0, newArray, 0, existing.length); System.arraycopy(buffers, 0, newArray, existing.length, buffers.length); } exchange.putAttachment(HttpServerExchange.BUFFERED_REQUEST_DATA, newArray); //todo: force some kind of wakeup? exchange.addExchangeCompleteListener(BufferedRequestDataCleanupListener.INSTANCE); }
[ "public", "static", "void", "ungetRequestBytes", "(", "final", "HttpServerExchange", "exchange", ",", "PooledByteBuffer", "...", "buffers", ")", "{", "PooledByteBuffer", "[", "]", "existing", "=", "exchange", ".", "getAttachment", "(", "HttpServerExchange", ".", "BUFFERED_REQUEST_DATA", ")", ";", "PooledByteBuffer", "[", "]", "newArray", ";", "if", "(", "existing", "==", "null", ")", "{", "newArray", "=", "new", "PooledByteBuffer", "[", "buffers", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "buffers", ",", "0", ",", "newArray", ",", "0", ",", "buffers", ".", "length", ")", ";", "}", "else", "{", "newArray", "=", "new", "PooledByteBuffer", "[", "existing", ".", "length", "+", "buffers", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "existing", ",", "0", ",", "newArray", ",", "0", ",", "existing", ".", "length", ")", ";", "System", ".", "arraycopy", "(", "buffers", ",", "0", ",", "newArray", ",", "existing", ".", "length", ",", "buffers", ".", "length", ")", ";", "}", "exchange", ".", "putAttachment", "(", "HttpServerExchange", ".", "BUFFERED_REQUEST_DATA", ",", "newArray", ")", ";", "//todo: force some kind of wakeup?", "exchange", ".", "addExchangeCompleteListener", "(", "BufferedRequestDataCleanupListener", ".", "INSTANCE", ")", ";", "}" ]
Attached buffered data to the exchange. The will generally be used to allow data to be re-read. @param exchange The HTTP server exchange @param buffers The buffers to attach
[ "Attached", "buffered", "data", "to", "the", "exchange", ".", "The", "will", "generally", "be", "used", "to", "allow", "data", "to", "be", "re", "-", "read", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/Connectors.java#L110-L123
16,755
undertow-io/undertow
core/src/main/java/io/undertow/server/Connectors.java
Connectors.verifyToken
public static void verifyToken(HttpString header) { int length = header.length(); for(int i = 0; i < length; ++i) { byte c = header.byteAt(i); if(!ALLOWED_TOKEN_CHARACTERS[c]) { throw UndertowMessages.MESSAGES.invalidToken(c); } } }
java
public static void verifyToken(HttpString header) { int length = header.length(); for(int i = 0; i < length; ++i) { byte c = header.byteAt(i); if(!ALLOWED_TOKEN_CHARACTERS[c]) { throw UndertowMessages.MESSAGES.invalidToken(c); } } }
[ "public", "static", "void", "verifyToken", "(", "HttpString", "header", ")", "{", "int", "length", "=", "header", ".", "length", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "++", "i", ")", "{", "byte", "c", "=", "header", ".", "byteAt", "(", "i", ")", ";", "if", "(", "!", "ALLOWED_TOKEN_CHARACTERS", "[", "c", "]", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "invalidToken", "(", "c", ")", ";", "}", "}", "}" ]
Verifies that the contents of the HttpString are a valid token according to rfc7230. @param header The header to verify
[ "Verifies", "that", "the", "contents", "of", "the", "HttpString", "are", "a", "valid", "token", "according", "to", "rfc7230", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/Connectors.java#L526-L534
16,756
undertow-io/undertow
core/src/main/java/io/undertow/io/UndertowOutputStream.java
UndertowOutputStream.resetBuffer
public void resetBuffer() { if(anyAreSet(state, FLAG_WRITE_STARTED)) { throw UndertowMessages.MESSAGES.cannotResetBuffer(); } buffer = null; IoUtils.safeClose(pooledBuffer); pooledBuffer = null; }
java
public void resetBuffer() { if(anyAreSet(state, FLAG_WRITE_STARTED)) { throw UndertowMessages.MESSAGES.cannotResetBuffer(); } buffer = null; IoUtils.safeClose(pooledBuffer); pooledBuffer = null; }
[ "public", "void", "resetBuffer", "(", ")", "{", "if", "(", "anyAreSet", "(", "state", ",", "FLAG_WRITE_STARTED", ")", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "cannotResetBuffer", "(", ")", ";", "}", "buffer", "=", "null", ";", "IoUtils", ".", "safeClose", "(", "pooledBuffer", ")", ";", "pooledBuffer", "=", "null", ";", "}" ]
If the response has not yet been written to the client this method will clear the streams buffer, invalidating any content that has already been written. If any content has already been sent to the client then this method will throw and IllegalStateException @throws java.lang.IllegalStateException If the response has been commited
[ "If", "the", "response", "has", "not", "yet", "been", "written", "to", "the", "client", "this", "method", "will", "clear", "the", "streams", "buffer", "invalidating", "any", "content", "that", "has", "already", "been", "written", ".", "If", "any", "content", "has", "already", "been", "sent", "to", "the", "client", "then", "this", "method", "will", "throw", "and", "IllegalStateException" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/io/UndertowOutputStream.java#L80-L87
16,757
undertow-io/undertow
core/src/main/java/io/undertow/conduits/DeflatingStreamSinkConduit.java
DeflatingStreamSinkConduit.performFlushIfRequired
private boolean performFlushIfRequired() throws IOException { if (anyAreSet(state, FLUSHING_BUFFER)) { final ByteBuffer[] bufs = new ByteBuffer[additionalBuffer == null ? 1 : 2]; long totalLength = 0; bufs[0] = currentBuffer.getBuffer(); totalLength += bufs[0].remaining(); if (additionalBuffer != null) { bufs[1] = additionalBuffer; totalLength += bufs[1].remaining(); } if (totalLength > 0) { long total = 0; long res = 0; do { res = next.write(bufs, 0, bufs.length); total += res; if (res == 0) { return false; } } while (total < totalLength); } additionalBuffer = null; currentBuffer.getBuffer().clear(); state = state & ~FLUSHING_BUFFER; } return true; }
java
private boolean performFlushIfRequired() throws IOException { if (anyAreSet(state, FLUSHING_BUFFER)) { final ByteBuffer[] bufs = new ByteBuffer[additionalBuffer == null ? 1 : 2]; long totalLength = 0; bufs[0] = currentBuffer.getBuffer(); totalLength += bufs[0].remaining(); if (additionalBuffer != null) { bufs[1] = additionalBuffer; totalLength += bufs[1].remaining(); } if (totalLength > 0) { long total = 0; long res = 0; do { res = next.write(bufs, 0, bufs.length); total += res; if (res == 0) { return false; } } while (total < totalLength); } additionalBuffer = null; currentBuffer.getBuffer().clear(); state = state & ~FLUSHING_BUFFER; } return true; }
[ "private", "boolean", "performFlushIfRequired", "(", ")", "throws", "IOException", "{", "if", "(", "anyAreSet", "(", "state", ",", "FLUSHING_BUFFER", ")", ")", "{", "final", "ByteBuffer", "[", "]", "bufs", "=", "new", "ByteBuffer", "[", "additionalBuffer", "==", "null", "?", "1", ":", "2", "]", ";", "long", "totalLength", "=", "0", ";", "bufs", "[", "0", "]", "=", "currentBuffer", ".", "getBuffer", "(", ")", ";", "totalLength", "+=", "bufs", "[", "0", "]", ".", "remaining", "(", ")", ";", "if", "(", "additionalBuffer", "!=", "null", ")", "{", "bufs", "[", "1", "]", "=", "additionalBuffer", ";", "totalLength", "+=", "bufs", "[", "1", "]", ".", "remaining", "(", ")", ";", "}", "if", "(", "totalLength", ">", "0", ")", "{", "long", "total", "=", "0", ";", "long", "res", "=", "0", ";", "do", "{", "res", "=", "next", ".", "write", "(", "bufs", ",", "0", ",", "bufs", ".", "length", ")", ";", "total", "+=", "res", ";", "if", "(", "res", "==", "0", ")", "{", "return", "false", ";", "}", "}", "while", "(", "total", "<", "totalLength", ")", ";", "}", "additionalBuffer", "=", "null", ";", "currentBuffer", ".", "getBuffer", "(", ")", ".", "clear", "(", ")", ";", "state", "=", "state", "&", "~", "FLUSHING_BUFFER", ";", "}", "return", "true", ";", "}" ]
The we are in the flushing state then we flush to the underlying stream, otherwise just return true @return false if there is still more to flush
[ "The", "we", "are", "in", "the", "flushing", "state", "then", "we", "flush", "to", "the", "underlying", "stream", "otherwise", "just", "return", "true" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/conduits/DeflatingStreamSinkConduit.java#L427-L453
16,758
undertow-io/undertow
core/src/main/java/io/undertow/conduits/DeflatingStreamSinkConduit.java
DeflatingStreamSinkConduit.deflateData
private void deflateData(boolean force) throws IOException { //we don't need to flush here, as this should have been called already by the time we get to //this point boolean nextCreated = false; try (PooledByteBuffer arrayPooled = this.exchange.getConnection().getByteBufferPool().getArrayBackedPool().allocate()) { PooledByteBuffer pooled = this.currentBuffer; final ByteBuffer outputBuffer = pooled.getBuffer(); final boolean shutdown = anyAreSet(state, SHUTDOWN); ByteBuffer buf = arrayPooled.getBuffer(); while (force || !deflater.needsInput() || (shutdown && !deflater.finished())) { int count = deflater.deflate(buf.array(), buf.arrayOffset(), buf.remaining(), force ? Deflater.SYNC_FLUSH: Deflater.NO_FLUSH); Connectors.updateResponseBytesSent(exchange, count); if (count != 0) { int remaining = outputBuffer.remaining(); if (remaining > count) { outputBuffer.put(buf.array(), buf.arrayOffset(), count); } else { if (remaining == count) { outputBuffer.put(buf.array(), buf.arrayOffset(), count); } else { outputBuffer.put(buf.array(), buf.arrayOffset(), remaining); additionalBuffer = ByteBuffer.allocate(count - remaining); additionalBuffer.put(buf.array(), buf.arrayOffset() + remaining, count - remaining); additionalBuffer.flip(); } outputBuffer.flip(); this.state |= FLUSHING_BUFFER; if (next == null) { nextCreated = true; this.next = createNextChannel(); } if (!performFlushIfRequired()) { return; } } } else { force = false; } } } finally { if (nextCreated) { if (anyAreSet(state, WRITES_RESUMED)) { next.resumeWrites(); } } } }
java
private void deflateData(boolean force) throws IOException { //we don't need to flush here, as this should have been called already by the time we get to //this point boolean nextCreated = false; try (PooledByteBuffer arrayPooled = this.exchange.getConnection().getByteBufferPool().getArrayBackedPool().allocate()) { PooledByteBuffer pooled = this.currentBuffer; final ByteBuffer outputBuffer = pooled.getBuffer(); final boolean shutdown = anyAreSet(state, SHUTDOWN); ByteBuffer buf = arrayPooled.getBuffer(); while (force || !deflater.needsInput() || (shutdown && !deflater.finished())) { int count = deflater.deflate(buf.array(), buf.arrayOffset(), buf.remaining(), force ? Deflater.SYNC_FLUSH: Deflater.NO_FLUSH); Connectors.updateResponseBytesSent(exchange, count); if (count != 0) { int remaining = outputBuffer.remaining(); if (remaining > count) { outputBuffer.put(buf.array(), buf.arrayOffset(), count); } else { if (remaining == count) { outputBuffer.put(buf.array(), buf.arrayOffset(), count); } else { outputBuffer.put(buf.array(), buf.arrayOffset(), remaining); additionalBuffer = ByteBuffer.allocate(count - remaining); additionalBuffer.put(buf.array(), buf.arrayOffset() + remaining, count - remaining); additionalBuffer.flip(); } outputBuffer.flip(); this.state |= FLUSHING_BUFFER; if (next == null) { nextCreated = true; this.next = createNextChannel(); } if (!performFlushIfRequired()) { return; } } } else { force = false; } } } finally { if (nextCreated) { if (anyAreSet(state, WRITES_RESUMED)) { next.resumeWrites(); } } } }
[ "private", "void", "deflateData", "(", "boolean", "force", ")", "throws", "IOException", "{", "//we don't need to flush here, as this should have been called already by the time we get to", "//this point", "boolean", "nextCreated", "=", "false", ";", "try", "(", "PooledByteBuffer", "arrayPooled", "=", "this", ".", "exchange", ".", "getConnection", "(", ")", ".", "getByteBufferPool", "(", ")", ".", "getArrayBackedPool", "(", ")", ".", "allocate", "(", ")", ")", "{", "PooledByteBuffer", "pooled", "=", "this", ".", "currentBuffer", ";", "final", "ByteBuffer", "outputBuffer", "=", "pooled", ".", "getBuffer", "(", ")", ";", "final", "boolean", "shutdown", "=", "anyAreSet", "(", "state", ",", "SHUTDOWN", ")", ";", "ByteBuffer", "buf", "=", "arrayPooled", ".", "getBuffer", "(", ")", ";", "while", "(", "force", "||", "!", "deflater", ".", "needsInput", "(", ")", "||", "(", "shutdown", "&&", "!", "deflater", ".", "finished", "(", ")", ")", ")", "{", "int", "count", "=", "deflater", ".", "deflate", "(", "buf", ".", "array", "(", ")", ",", "buf", ".", "arrayOffset", "(", ")", ",", "buf", ".", "remaining", "(", ")", ",", "force", "?", "Deflater", ".", "SYNC_FLUSH", ":", "Deflater", ".", "NO_FLUSH", ")", ";", "Connectors", ".", "updateResponseBytesSent", "(", "exchange", ",", "count", ")", ";", "if", "(", "count", "!=", "0", ")", "{", "int", "remaining", "=", "outputBuffer", ".", "remaining", "(", ")", ";", "if", "(", "remaining", ">", "count", ")", "{", "outputBuffer", ".", "put", "(", "buf", ".", "array", "(", ")", ",", "buf", ".", "arrayOffset", "(", ")", ",", "count", ")", ";", "}", "else", "{", "if", "(", "remaining", "==", "count", ")", "{", "outputBuffer", ".", "put", "(", "buf", ".", "array", "(", ")", ",", "buf", ".", "arrayOffset", "(", ")", ",", "count", ")", ";", "}", "else", "{", "outputBuffer", ".", "put", "(", "buf", ".", "array", "(", ")", ",", "buf", ".", "arrayOffset", "(", ")", ",", "remaining", ")", ";", "additionalBuffer", "=", "ByteBuffer", ".", "allocate", "(", "count", "-", "remaining", ")", ";", "additionalBuffer", ".", "put", "(", "buf", ".", "array", "(", ")", ",", "buf", ".", "arrayOffset", "(", ")", "+", "remaining", ",", "count", "-", "remaining", ")", ";", "additionalBuffer", ".", "flip", "(", ")", ";", "}", "outputBuffer", ".", "flip", "(", ")", ";", "this", ".", "state", "|=", "FLUSHING_BUFFER", ";", "if", "(", "next", "==", "null", ")", "{", "nextCreated", "=", "true", ";", "this", ".", "next", "=", "createNextChannel", "(", ")", ";", "}", "if", "(", "!", "performFlushIfRequired", "(", ")", ")", "{", "return", ";", "}", "}", "}", "else", "{", "force", "=", "false", ";", "}", "}", "}", "finally", "{", "if", "(", "nextCreated", ")", "{", "if", "(", "anyAreSet", "(", "state", ",", "WRITES_RESUMED", ")", ")", "{", "next", ".", "resumeWrites", "(", ")", ";", "}", "}", "}", "}" ]
Runs the current data through the deflater. As much as possible this will be buffered in the current output stream. @throws IOException
[ "Runs", "the", "current", "data", "through", "the", "deflater", ".", "As", "much", "as", "possible", "this", "will", "be", "buffered", "in", "the", "current", "output", "stream", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/conduits/DeflatingStreamSinkConduit.java#L479-L526
16,759
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSocketChannel.java
WebSocketChannel.sendClose
public void sendClose() throws IOException { closeReason = ""; closeCode = CloseMessage.NORMAL_CLOSURE; StreamSinkFrameChannel closeChannel = send(WebSocketFrameType.CLOSE); closeChannel.shutdownWrites(); if (!closeChannel.flush()) { closeChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener( null, new ChannelExceptionHandler<StreamSinkChannel>() { @Override public void handleException(final StreamSinkChannel channel, final IOException exception) { IoUtils.safeClose(WebSocketChannel.this); } } )); closeChannel.resumeWrites(); } }
java
public void sendClose() throws IOException { closeReason = ""; closeCode = CloseMessage.NORMAL_CLOSURE; StreamSinkFrameChannel closeChannel = send(WebSocketFrameType.CLOSE); closeChannel.shutdownWrites(); if (!closeChannel.flush()) { closeChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener( null, new ChannelExceptionHandler<StreamSinkChannel>() { @Override public void handleException(final StreamSinkChannel channel, final IOException exception) { IoUtils.safeClose(WebSocketChannel.this); } } )); closeChannel.resumeWrites(); } }
[ "public", "void", "sendClose", "(", ")", "throws", "IOException", "{", "closeReason", "=", "\"\"", ";", "closeCode", "=", "CloseMessage", ".", "NORMAL_CLOSURE", ";", "StreamSinkFrameChannel", "closeChannel", "=", "send", "(", "WebSocketFrameType", ".", "CLOSE", ")", ";", "closeChannel", ".", "shutdownWrites", "(", ")", ";", "if", "(", "!", "closeChannel", ".", "flush", "(", ")", ")", "{", "closeChannel", ".", "getWriteSetter", "(", ")", ".", "set", "(", "ChannelListeners", ".", "flushingChannelListener", "(", "null", ",", "new", "ChannelExceptionHandler", "<", "StreamSinkChannel", ">", "(", ")", "{", "@", "Override", "public", "void", "handleException", "(", "final", "StreamSinkChannel", "channel", ",", "final", "IOException", "exception", ")", "{", "IoUtils", ".", "safeClose", "(", "WebSocketChannel", ".", "this", ")", ";", "}", "}", ")", ")", ";", "closeChannel", ".", "resumeWrites", "(", ")", ";", "}", "}" ]
Send a Close frame without a payload
[ "Send", "a", "Close", "frame", "without", "a", "payload" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSocketChannel.java#L361-L377
16,760
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendPingBlocking
public static void sendPingBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(data, WebSocketFrameType.PING, wsChannel); }
java
public static void sendPingBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(data, WebSocketFrameType.PING, wsChannel); }
[ "public", "static", "void", "sendPingBlocking", "(", "final", "ByteBuffer", "data", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "sendBlockingInternal", "(", "data", ",", "WebSocketFrameType", ".", "PING", ",", "wsChannel", ")", ";", "}" ]
Sends a complete ping message using blocking IO @param data The data to send @param wsChannel The web socket channel
[ "Sends", "a", "complete", "ping", "message", "using", "blocking", "IO" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L378-L380
16,761
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendPingBlocking
public static void sendPingBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(pooledData, WebSocketFrameType.PING, wsChannel); }
java
public static void sendPingBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(pooledData, WebSocketFrameType.PING, wsChannel); }
[ "public", "static", "void", "sendPingBlocking", "(", "final", "PooledByteBuffer", "pooledData", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "sendBlockingInternal", "(", "pooledData", ",", "WebSocketFrameType", ".", "PING", ",", "wsChannel", ")", ";", "}" ]
Sends a complete ping message using blocking IO Automatically frees the pooled byte buffer when done. @param pooledData The data to send, it will be freed when done @param wsChannel The web socket channel
[ "Sends", "a", "complete", "ping", "message", "using", "blocking", "IO", "Automatically", "frees", "the", "pooled", "byte", "buffer", "when", "done", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L399-L401
16,762
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendPongBlocking
public static void sendPongBlocking(final ByteBuffer[] data, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(mergeBuffers(data), WebSocketFrameType.PONG, wsChannel); }
java
public static void sendPongBlocking(final ByteBuffer[] data, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(mergeBuffers(data), WebSocketFrameType.PONG, wsChannel); }
[ "public", "static", "void", "sendPongBlocking", "(", "final", "ByteBuffer", "[", "]", "data", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "sendBlockingInternal", "(", "mergeBuffers", "(", "data", ")", ",", "WebSocketFrameType", ".", "PONG", ",", "wsChannel", ")", ";", "}" ]
Sends a complete pong message using blocking IO @param data The data to send @param wsChannel The web socket channel
[ "Sends", "a", "complete", "pong", "message", "using", "blocking", "IO" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L567-L569
16,763
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendPongBlocking
public static void sendPongBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(pooledData, WebSocketFrameType.PONG, wsChannel); }
java
public static void sendPongBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(pooledData, WebSocketFrameType.PONG, wsChannel); }
[ "public", "static", "void", "sendPongBlocking", "(", "final", "PooledByteBuffer", "pooledData", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "sendBlockingInternal", "(", "pooledData", ",", "WebSocketFrameType", ".", "PONG", ",", "wsChannel", ")", ";", "}" ]
Sends a complete pong message using blocking IO Automatically frees the pooled byte buffer when done. @param pooledData The data to send, it will be freed when done @param wsChannel The web socket channel
[ "Sends", "a", "complete", "pong", "message", "using", "blocking", "IO", "Automatically", "frees", "the", "pooled", "byte", "buffer", "when", "done", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L578-L580
16,764
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendBinaryBlocking
public static void sendBinaryBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(data, WebSocketFrameType.BINARY, wsChannel); }
java
public static void sendBinaryBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(data, WebSocketFrameType.BINARY, wsChannel); }
[ "public", "static", "void", "sendBinaryBlocking", "(", "final", "ByteBuffer", "data", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "sendBlockingInternal", "(", "data", ",", "WebSocketFrameType", ".", "BINARY", ",", "wsChannel", ")", ";", "}" ]
Sends a complete binary message using blocking IO @param data The data to send @param wsChannel The web socket channel
[ "Sends", "a", "complete", "binary", "message", "using", "blocking", "IO" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L736-L738
16,765
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendBinaryBlocking
public static void sendBinaryBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(pooledData, WebSocketFrameType.BINARY, wsChannel); }
java
public static void sendBinaryBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException { sendBlockingInternal(pooledData, WebSocketFrameType.BINARY, wsChannel); }
[ "public", "static", "void", "sendBinaryBlocking", "(", "final", "PooledByteBuffer", "pooledData", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "sendBlockingInternal", "(", "pooledData", ",", "WebSocketFrameType", ".", "BINARY", ",", "wsChannel", ")", ";", "}" ]
Sends a complete binary message using blocking IO Automatically frees the pooled byte buffer when done. @param pooledData The data to send, it will be freed when done @param wsChannel The web socket channel
[ "Sends", "a", "complete", "binary", "message", "using", "blocking", "IO", "Automatically", "frees", "the", "pooled", "byte", "buffer", "when", "done", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L757-L759
16,766
undertow-io/undertow
core/src/main/java9/io/undertow/util/FastConcurrentDirectDeque.java
FastConcurrentDirectDeque.newNode
static <E> Node<E> newNode(E item) { Node<E> node = new Node<E>(); ITEM.set(node, item); return node; }
java
static <E> Node<E> newNode(E item) { Node<E> node = new Node<E>(); ITEM.set(node, item); return node; }
[ "static", "<", "E", ">", "Node", "<", "E", ">", "newNode", "(", "E", "item", ")", "{", "Node", "<", "E", ">", "node", "=", "new", "Node", "<", "E", ">", "(", ")", ";", "ITEM", ".", "set", "(", "node", ",", "item", ")", ";", "return", "node", ";", "}" ]
Returns a new node holding item. Uses relaxed write because item can only be seen after piggy-backing publication via CAS.
[ "Returns", "a", "new", "node", "holding", "item", ".", "Uses", "relaxed", "write", "because", "item", "can", "only", "be", "seen", "after", "piggy", "-", "backing", "publication", "via", "CAS", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java9/io/undertow/util/FastConcurrentDirectDeque.java#L300-L304
16,767
undertow-io/undertow
core/src/main/java9/io/undertow/util/FastConcurrentDirectDeque.java
FastConcurrentDirectDeque.bulkRemove
private boolean bulkRemove(Predicate<? super E> filter) { boolean removed = false; for (Node<E> p = first(), succ; p != null; p = succ) { succ = succ(p); final E item; if ((item = p.item) != null && filter.test(item) && ITEM.compareAndSet(p, item, null)) { unlink(p); removed = true; } } return removed; }
java
private boolean bulkRemove(Predicate<? super E> filter) { boolean removed = false; for (Node<E> p = first(), succ; p != null; p = succ) { succ = succ(p); final E item; if ((item = p.item) != null && filter.test(item) && ITEM.compareAndSet(p, item, null)) { unlink(p); removed = true; } } return removed; }
[ "private", "boolean", "bulkRemove", "(", "Predicate", "<", "?", "super", "E", ">", "filter", ")", "{", "boolean", "removed", "=", "false", ";", "for", "(", "Node", "<", "E", ">", "p", "=", "first", "(", ")", ",", "succ", ";", "p", "!=", "null", ";", "p", "=", "succ", ")", "{", "succ", "=", "succ", "(", "p", ")", ";", "final", "E", "item", ";", "if", "(", "(", "item", "=", "p", ".", "item", ")", "!=", "null", "&&", "filter", ".", "test", "(", "item", ")", "&&", "ITEM", ".", "compareAndSet", "(", "p", ",", "item", ",", "null", ")", ")", "{", "unlink", "(", "p", ")", ";", "removed", "=", "true", ";", "}", "}", "return", "removed", ";", "}" ]
Implementation of bulk remove methods.
[ "Implementation", "of", "bulk", "remove", "methods", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java9/io/undertow/util/FastConcurrentDirectDeque.java#L1670-L1683
16,768
undertow-io/undertow
core/src/main/java/io/undertow/server/ServerConnection.java
ServerConnection.pushResource
public boolean pushResource(final String path, final HttpString method, final HeaderMap requestHeaders, HttpHandler handler) { return false; }
java
public boolean pushResource(final String path, final HttpString method, final HeaderMap requestHeaders, HttpHandler handler) { return false; }
[ "public", "boolean", "pushResource", "(", "final", "String", "path", ",", "final", "HttpString", "method", ",", "final", "HeaderMap", "requestHeaders", ",", "HttpHandler", "handler", ")", "{", "return", "false", ";", "}" ]
Attempts to push a resource if this connection supports server push. Otherwise the request is ignored. Note that push is always done on a best effort basis, even if this method returns true it is possible that the remote endpoint will reset the stream. The {@link io.undertow.server.HttpHandler} passed in will be used to generate the pushed response @param path The path of the resource @param method The request method @param requestHeaders The request headers @return <code>true</code> if the server attempted the push, false otherwise
[ "Attempts", "to", "push", "a", "resource", "if", "this", "connection", "supports", "server", "push", ".", "Otherwise", "the", "request", "is", "ignored", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/ServerConnection.java#L276-L278
16,769
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java
NodePingUtil.pingHost
static void pingHost(InetSocketAddress address, HttpServerExchange exchange, PingCallback callback, OptionMap options) { final XnioIoThread thread = exchange.getIoThread(); final XnioWorker worker = thread.getWorker(); final HostPingTask r = new HostPingTask(address, worker, callback, options); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), r, 5, TimeUnit.SECONDS); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : thread, r); }
java
static void pingHost(InetSocketAddress address, HttpServerExchange exchange, PingCallback callback, OptionMap options) { final XnioIoThread thread = exchange.getIoThread(); final XnioWorker worker = thread.getWorker(); final HostPingTask r = new HostPingTask(address, worker, callback, options); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), r, 5, TimeUnit.SECONDS); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : thread, r); }
[ "static", "void", "pingHost", "(", "InetSocketAddress", "address", ",", "HttpServerExchange", "exchange", ",", "PingCallback", "callback", ",", "OptionMap", "options", ")", "{", "final", "XnioIoThread", "thread", "=", "exchange", ".", "getIoThread", "(", ")", ";", "final", "XnioWorker", "worker", "=", "thread", ".", "getWorker", "(", ")", ";", "final", "HostPingTask", "r", "=", "new", "HostPingTask", "(", "address", ",", "worker", ",", "callback", ",", "options", ")", ";", "// Schedule timeout task", "scheduleCancelTask", "(", "exchange", ".", "getIoThread", "(", ")", ",", "r", ",", "5", ",", "TimeUnit", ".", "SECONDS", ")", ";", "exchange", ".", "dispatch", "(", "exchange", ".", "isInIoThread", "(", ")", "?", "SameThreadExecutor", ".", "INSTANCE", ":", "thread", ",", "r", ")", ";", "}" ]
Try to open a socket connection to given address. @param address the socket address @param exchange the http servers exchange @param callback the ping callback @param options the options
[ "Try", "to", "open", "a", "socket", "connection", "to", "given", "address", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java#L83-L91
16,770
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java
NodePingUtil.pingHttpClient
static void pingHttpClient(URI connection, PingCallback callback, HttpServerExchange exchange, UndertowClient client, XnioSsl xnioSsl, OptionMap options) { final XnioIoThread thread = exchange.getIoThread(); final RequestExchangeListener exchangeListener = new RequestExchangeListener(callback, NodeHealthChecker.NO_CHECK, true); final Runnable r = new HttpClientPingTask(connection, exchangeListener, thread, client, xnioSsl, exchange.getConnection().getByteBufferPool(), options); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : thread, r); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), exchangeListener, 5, TimeUnit.SECONDS); }
java
static void pingHttpClient(URI connection, PingCallback callback, HttpServerExchange exchange, UndertowClient client, XnioSsl xnioSsl, OptionMap options) { final XnioIoThread thread = exchange.getIoThread(); final RequestExchangeListener exchangeListener = new RequestExchangeListener(callback, NodeHealthChecker.NO_CHECK, true); final Runnable r = new HttpClientPingTask(connection, exchangeListener, thread, client, xnioSsl, exchange.getConnection().getByteBufferPool(), options); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : thread, r); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), exchangeListener, 5, TimeUnit.SECONDS); }
[ "static", "void", "pingHttpClient", "(", "URI", "connection", ",", "PingCallback", "callback", ",", "HttpServerExchange", "exchange", ",", "UndertowClient", "client", ",", "XnioSsl", "xnioSsl", ",", "OptionMap", "options", ")", "{", "final", "XnioIoThread", "thread", "=", "exchange", ".", "getIoThread", "(", ")", ";", "final", "RequestExchangeListener", "exchangeListener", "=", "new", "RequestExchangeListener", "(", "callback", ",", "NodeHealthChecker", ".", "NO_CHECK", ",", "true", ")", ";", "final", "Runnable", "r", "=", "new", "HttpClientPingTask", "(", "connection", ",", "exchangeListener", ",", "thread", ",", "client", ",", "xnioSsl", ",", "exchange", ".", "getConnection", "(", ")", ".", "getByteBufferPool", "(", ")", ",", "options", ")", ";", "exchange", ".", "dispatch", "(", "exchange", ".", "isInIoThread", "(", ")", "?", "SameThreadExecutor", ".", "INSTANCE", ":", "thread", ",", "r", ")", ";", "// Schedule timeout task", "scheduleCancelTask", "(", "exchange", ".", "getIoThread", "(", ")", ",", "exchangeListener", ",", "5", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}" ]
Try to ping a server using the undertow client. @param connection the connection URI @param callback the ping callback @param exchange the http servers exchange @param client the undertow client @param xnioSsl the ssl setup @param options the options
[ "Try", "to", "ping", "a", "server", "using", "the", "undertow", "client", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java#L103-L111
16,771
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java
NodePingUtil.pingNode
static void pingNode(final Node node, final HttpServerExchange exchange, final PingCallback callback) { if (node == null) { callback.failed(); return; } final int timeout = node.getNodeConfig().getPing(); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : exchange.getIoThread(), new Runnable() { @Override public void run() { node.getConnectionPool().connect(null, exchange, new ProxyCallback<ProxyConnection>() { @Override public void completed(final HttpServerExchange exchange, ProxyConnection result) { final RequestExchangeListener exchangeListener = new RequestExchangeListener(callback, NodeHealthChecker.NO_CHECK, false); exchange.dispatch(SameThreadExecutor.INSTANCE, new ConnectionPoolPingTask(result, exchangeListener, node.getNodeConfig().getConnectionURI())); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), exchangeListener, timeout, TimeUnit.SECONDS); } @Override public void failed(HttpServerExchange exchange) { callback.failed(); } @Override public void queuedRequestFailed(HttpServerExchange exchange) { callback.failed(); } @Override public void couldNotResolveBackend(HttpServerExchange exchange) { callback.failed(); } }, timeout, TimeUnit.SECONDS, false); } }); }
java
static void pingNode(final Node node, final HttpServerExchange exchange, final PingCallback callback) { if (node == null) { callback.failed(); return; } final int timeout = node.getNodeConfig().getPing(); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : exchange.getIoThread(), new Runnable() { @Override public void run() { node.getConnectionPool().connect(null, exchange, new ProxyCallback<ProxyConnection>() { @Override public void completed(final HttpServerExchange exchange, ProxyConnection result) { final RequestExchangeListener exchangeListener = new RequestExchangeListener(callback, NodeHealthChecker.NO_CHECK, false); exchange.dispatch(SameThreadExecutor.INSTANCE, new ConnectionPoolPingTask(result, exchangeListener, node.getNodeConfig().getConnectionURI())); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), exchangeListener, timeout, TimeUnit.SECONDS); } @Override public void failed(HttpServerExchange exchange) { callback.failed(); } @Override public void queuedRequestFailed(HttpServerExchange exchange) { callback.failed(); } @Override public void couldNotResolveBackend(HttpServerExchange exchange) { callback.failed(); } }, timeout, TimeUnit.SECONDS, false); } }); }
[ "static", "void", "pingNode", "(", "final", "Node", "node", ",", "final", "HttpServerExchange", "exchange", ",", "final", "PingCallback", "callback", ")", "{", "if", "(", "node", "==", "null", ")", "{", "callback", ".", "failed", "(", ")", ";", "return", ";", "}", "final", "int", "timeout", "=", "node", ".", "getNodeConfig", "(", ")", ".", "getPing", "(", ")", ";", "exchange", ".", "dispatch", "(", "exchange", ".", "isInIoThread", "(", ")", "?", "SameThreadExecutor", ".", "INSTANCE", ":", "exchange", ".", "getIoThread", "(", ")", ",", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "node", ".", "getConnectionPool", "(", ")", ".", "connect", "(", "null", ",", "exchange", ",", "new", "ProxyCallback", "<", "ProxyConnection", ">", "(", ")", "{", "@", "Override", "public", "void", "completed", "(", "final", "HttpServerExchange", "exchange", ",", "ProxyConnection", "result", ")", "{", "final", "RequestExchangeListener", "exchangeListener", "=", "new", "RequestExchangeListener", "(", "callback", ",", "NodeHealthChecker", ".", "NO_CHECK", ",", "false", ")", ";", "exchange", ".", "dispatch", "(", "SameThreadExecutor", ".", "INSTANCE", ",", "new", "ConnectionPoolPingTask", "(", "result", ",", "exchangeListener", ",", "node", ".", "getNodeConfig", "(", ")", ".", "getConnectionURI", "(", ")", ")", ")", ";", "// Schedule timeout task", "scheduleCancelTask", "(", "exchange", ".", "getIoThread", "(", ")", ",", "exchangeListener", ",", "timeout", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "@", "Override", "public", "void", "failed", "(", "HttpServerExchange", "exchange", ")", "{", "callback", ".", "failed", "(", ")", ";", "}", "@", "Override", "public", "void", "queuedRequestFailed", "(", "HttpServerExchange", "exchange", ")", "{", "callback", ".", "failed", "(", ")", ";", "}", "@", "Override", "public", "void", "couldNotResolveBackend", "(", "HttpServerExchange", "exchange", ")", "{", "callback", ".", "failed", "(", ")", ";", "}", "}", ",", "timeout", ",", "TimeUnit", ".", "SECONDS", ",", "false", ")", ";", "}", "}", ")", ";", "}" ]
Try to ping a node using it's connection pool. @param node the node @param exchange the http servers exchange @param callback the ping callback
[ "Try", "to", "ping", "a", "node", "using", "it", "s", "connection", "pool", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java#L120-L157
16,772
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java
NodePingUtil.internalPingNode
static void internalPingNode(Node node, PingCallback callback, NodeHealthChecker healthChecker, XnioIoThread ioThread, ByteBufferPool bufferPool, UndertowClient client, XnioSsl xnioSsl, OptionMap options) { final URI uri = node.getNodeConfig().getConnectionURI(); final long timeout = node.getNodeConfig().getPing(); final RequestExchangeListener exchangeListener = new RequestExchangeListener(callback, healthChecker, true); final HttpClientPingTask r = new HttpClientPingTask(uri, exchangeListener, ioThread, client, xnioSsl, bufferPool, options); // Schedule timeout task scheduleCancelTask(ioThread, exchangeListener, timeout, TimeUnit.SECONDS); ioThread.execute(r); }
java
static void internalPingNode(Node node, PingCallback callback, NodeHealthChecker healthChecker, XnioIoThread ioThread, ByteBufferPool bufferPool, UndertowClient client, XnioSsl xnioSsl, OptionMap options) { final URI uri = node.getNodeConfig().getConnectionURI(); final long timeout = node.getNodeConfig().getPing(); final RequestExchangeListener exchangeListener = new RequestExchangeListener(callback, healthChecker, true); final HttpClientPingTask r = new HttpClientPingTask(uri, exchangeListener, ioThread, client, xnioSsl, bufferPool, options); // Schedule timeout task scheduleCancelTask(ioThread, exchangeListener, timeout, TimeUnit.SECONDS); ioThread.execute(r); }
[ "static", "void", "internalPingNode", "(", "Node", "node", ",", "PingCallback", "callback", ",", "NodeHealthChecker", "healthChecker", ",", "XnioIoThread", "ioThread", ",", "ByteBufferPool", "bufferPool", ",", "UndertowClient", "client", ",", "XnioSsl", "xnioSsl", ",", "OptionMap", "options", ")", "{", "final", "URI", "uri", "=", "node", ".", "getNodeConfig", "(", ")", ".", "getConnectionURI", "(", ")", ";", "final", "long", "timeout", "=", "node", ".", "getNodeConfig", "(", ")", ".", "getPing", "(", ")", ";", "final", "RequestExchangeListener", "exchangeListener", "=", "new", "RequestExchangeListener", "(", "callback", ",", "healthChecker", ",", "true", ")", ";", "final", "HttpClientPingTask", "r", "=", "new", "HttpClientPingTask", "(", "uri", ",", "exchangeListener", ",", "ioThread", ",", "client", ",", "xnioSsl", ",", "bufferPool", ",", "options", ")", ";", "// Schedule timeout task", "scheduleCancelTask", "(", "ioThread", ",", "exchangeListener", ",", "timeout", ",", "TimeUnit", ".", "SECONDS", ")", ";", "ioThread", ".", "execute", "(", "r", ")", ";", "}" ]
Internally ping a node. This should probably use the connections from the nodes pool, if there are any available. @param node the node @param callback the ping callback @param ioThread the xnio i/o thread @param bufferPool the xnio buffer pool @param client the undertow client @param xnioSsl the ssl setup @param options the options
[ "Internally", "ping", "a", "node", ".", "This", "should", "probably", "use", "the", "connections", "from", "the", "nodes", "pool", "if", "there", "are", "any", "available", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java#L170-L179
16,773
undertow-io/undertow
core/src/main/java/io/undertow/util/URLUtils.java
URLUtils.isAbsoluteUrl
public static boolean isAbsoluteUrl(String location) { if (location != null && location.length() > 0 && location.contains(":")) { try { URI uri = new URI(location); return uri.getScheme() != null; } catch (URISyntaxException e) { // ignore invalid locations and consider not absolute } } return false; }
java
public static boolean isAbsoluteUrl(String location) { if (location != null && location.length() > 0 && location.contains(":")) { try { URI uri = new URI(location); return uri.getScheme() != null; } catch (URISyntaxException e) { // ignore invalid locations and consider not absolute } } return false; }
[ "public", "static", "boolean", "isAbsoluteUrl", "(", "String", "location", ")", "{", "if", "(", "location", "!=", "null", "&&", "location", ".", "length", "(", ")", ">", "0", "&&", "location", ".", "contains", "(", "\":\"", ")", ")", "{", "try", "{", "URI", "uri", "=", "new", "URI", "(", "location", ")", ";", "return", "uri", ".", "getScheme", "(", ")", "!=", "null", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "// ignore invalid locations and consider not absolute", "}", "}", "return", "false", ";", "}" ]
Test if provided location is an absolute URI or not. @param location location to check, null = relative, having scheme = absolute @return true if location is considered absolute
[ "Test", "if", "provided", "location", "is", "an", "absolute", "URI", "or", "not", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/URLUtils.java#L324-L334
16,774
undertow-io/undertow
parser-generator/src/main/java/io/undertow/annotationprocessor/AbstractParserGenerator.java
AbstractParserGenerator.stateNotFound
private static void stateNotFound(final CodeAttribute c, final TableSwitchBuilder builder) { c.branchEnd(builder.getDefaultBranchEnd().get()); c.newInstruction(RuntimeException.class); c.dup(); c.ldc("Invalid character"); c.invokespecial(RuntimeException.class.getName(), "<init>", "(Ljava/lang/String;)V"); c.athrow(); }
java
private static void stateNotFound(final CodeAttribute c, final TableSwitchBuilder builder) { c.branchEnd(builder.getDefaultBranchEnd().get()); c.newInstruction(RuntimeException.class); c.dup(); c.ldc("Invalid character"); c.invokespecial(RuntimeException.class.getName(), "<init>", "(Ljava/lang/String;)V"); c.athrow(); }
[ "private", "static", "void", "stateNotFound", "(", "final", "CodeAttribute", "c", ",", "final", "TableSwitchBuilder", "builder", ")", "{", "c", ".", "branchEnd", "(", "builder", ".", "getDefaultBranchEnd", "(", ")", ".", "get", "(", ")", ")", ";", "c", ".", "newInstruction", "(", "RuntimeException", ".", "class", ")", ";", "c", ".", "dup", "(", ")", ";", "c", ".", "ldc", "(", "\"Invalid character\"", ")", ";", "c", ".", "invokespecial", "(", "RuntimeException", ".", "class", ".", "getName", "(", ")", ",", "\"<init>\"", ",", "\"(Ljava/lang/String;)V\"", ")", ";", "c", ".", "athrow", "(", ")", ";", "}" ]
Throws an exception when an invalid state is hit in a tableswitch
[ "Throws", "an", "exception", "when", "an", "invalid", "state", "is", "hit", "in", "a", "tableswitch" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/parser-generator/src/main/java/io/undertow/annotationprocessor/AbstractParserGenerator.java#L709-L716
16,775
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/HPackHuffman.java
HPackHuffman.decode
public static void decode(ByteBuffer data, int length, StringBuilder target) throws HpackException { assert data.remaining() >= length; int treePos = 0; boolean eosBits = true; int eosCount = 0; for (int i = 0; i < length; ++i) { byte b = data.get(); int bitPos = 7; while (bitPos >= 0) { int val = DECODING_TABLE[treePos]; if (((1 << bitPos) & b) == 0) { //bit not set, we want the lower part of the tree if ((val & LOW_TERMINAL_BIT) == 0) { treePos = val & LOW_MASK; eosBits = false; eosCount = 0; } else { target.append((char) (val & LOW_MASK)); treePos = 0; eosBits = true; eosCount = 0; } } else { //bit not set, we want the lower part of the tree if ((val & HIGH_TERMINAL_BIT) == 0) { treePos = (val >> 16) & LOW_MASK; if(eosBits) { eosCount++; } } else { target.append((char) ((val >> 16) & LOW_MASK)); treePos = 0; eosCount = 0; eosBits = true; } } bitPos--; } } if (!eosBits || eosCount > 7) { throw UndertowMessages.MESSAGES.huffmanEncodedHpackValueDidNotEndWithEOS(); } }
java
public static void decode(ByteBuffer data, int length, StringBuilder target) throws HpackException { assert data.remaining() >= length; int treePos = 0; boolean eosBits = true; int eosCount = 0; for (int i = 0; i < length; ++i) { byte b = data.get(); int bitPos = 7; while (bitPos >= 0) { int val = DECODING_TABLE[treePos]; if (((1 << bitPos) & b) == 0) { //bit not set, we want the lower part of the tree if ((val & LOW_TERMINAL_BIT) == 0) { treePos = val & LOW_MASK; eosBits = false; eosCount = 0; } else { target.append((char) (val & LOW_MASK)); treePos = 0; eosBits = true; eosCount = 0; } } else { //bit not set, we want the lower part of the tree if ((val & HIGH_TERMINAL_BIT) == 0) { treePos = (val >> 16) & LOW_MASK; if(eosBits) { eosCount++; } } else { target.append((char) ((val >> 16) & LOW_MASK)); treePos = 0; eosCount = 0; eosBits = true; } } bitPos--; } } if (!eosBits || eosCount > 7) { throw UndertowMessages.MESSAGES.huffmanEncodedHpackValueDidNotEndWithEOS(); } }
[ "public", "static", "void", "decode", "(", "ByteBuffer", "data", ",", "int", "length", ",", "StringBuilder", "target", ")", "throws", "HpackException", "{", "assert", "data", ".", "remaining", "(", ")", ">=", "length", ";", "int", "treePos", "=", "0", ";", "boolean", "eosBits", "=", "true", ";", "int", "eosCount", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "++", "i", ")", "{", "byte", "b", "=", "data", ".", "get", "(", ")", ";", "int", "bitPos", "=", "7", ";", "while", "(", "bitPos", ">=", "0", ")", "{", "int", "val", "=", "DECODING_TABLE", "[", "treePos", "]", ";", "if", "(", "(", "(", "1", "<<", "bitPos", ")", "&", "b", ")", "==", "0", ")", "{", "//bit not set, we want the lower part of the tree", "if", "(", "(", "val", "&", "LOW_TERMINAL_BIT", ")", "==", "0", ")", "{", "treePos", "=", "val", "&", "LOW_MASK", ";", "eosBits", "=", "false", ";", "eosCount", "=", "0", ";", "}", "else", "{", "target", ".", "append", "(", "(", "char", ")", "(", "val", "&", "LOW_MASK", ")", ")", ";", "treePos", "=", "0", ";", "eosBits", "=", "true", ";", "eosCount", "=", "0", ";", "}", "}", "else", "{", "//bit not set, we want the lower part of the tree", "if", "(", "(", "val", "&", "HIGH_TERMINAL_BIT", ")", "==", "0", ")", "{", "treePos", "=", "(", "val", ">>", "16", ")", "&", "LOW_MASK", ";", "if", "(", "eosBits", ")", "{", "eosCount", "++", ";", "}", "}", "else", "{", "target", ".", "append", "(", "(", "char", ")", "(", "(", "val", ">>", "16", ")", "&", "LOW_MASK", ")", ")", ";", "treePos", "=", "0", ";", "eosCount", "=", "0", ";", "eosBits", "=", "true", ";", "}", "}", "bitPos", "--", ";", "}", "}", "if", "(", "!", "eosBits", "||", "eosCount", ">", "7", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "huffmanEncodedHpackValueDidNotEndWithEOS", "(", ")", ";", "}", "}" ]
Decodes a huffman encoded string into the target StringBuilder. There must be enough space left in the buffer for this method to succeed. @param data The byte buffer @param length The data length @param target The target for the decompressed data
[ "Decodes", "a", "huffman", "encoded", "string", "into", "the", "target", "StringBuilder", ".", "There", "must", "be", "enough", "space", "left", "in", "the", "buffer", "for", "this", "method", "to", "succeed", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/HPackHuffman.java#L377-L419
16,776
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/HPackHuffman.java
HPackHuffman.encode
public static boolean encode(ByteBuffer buffer, String toEncode, boolean forceLowercase) { if (buffer.remaining() <= toEncode.length()) { return false; } int start = buffer.position(); //this sucks, but we need to put the length first //and we don't really have any option but to calculate it in advance to make sure we have left enough room //so we end up iterating twice int length = 0; for (int i = 0; i < toEncode.length(); ++i) { byte c = (byte) toEncode.charAt(i); if(forceLowercase) { c = Hpack.toLower(c); } HuffmanCode code = HUFFMAN_CODES[c]; length += code.length; } int byteLength = length / 8 + (length % 8 == 0 ? 0 : 1); buffer.put((byte) (1 << 7)); Hpack.encodeInteger(buffer, byteLength, 7); int bytePos = 0; byte currentBufferByte = 0; for (int i = 0; i < toEncode.length(); ++i) { byte c = (byte) toEncode.charAt(i); if(forceLowercase) { c = Hpack.toLower(c); } HuffmanCode code = HUFFMAN_CODES[c]; if (code.length + bytePos <= 8) { //it fits in the current byte currentBufferByte |= ((code.value & 0xFF) << 8 - (code.length + bytePos)); bytePos += code.length; } else { //it does not fit, it may need up to 4 bytes int val = code.value; int rem = code.length; while (rem > 0) { if (!buffer.hasRemaining()) { buffer.position(start); return false; } int remainingInByte = 8 - bytePos; if (rem > remainingInByte) { currentBufferByte |= (val >> (rem - remainingInByte)); } else { currentBufferByte |= (val << (remainingInByte - rem)); } if (rem > remainingInByte) { buffer.put(currentBufferByte); currentBufferByte = 0; bytePos = 0; } else { bytePos = rem; } rem -= remainingInByte; } } if (bytePos == 8) { if (!buffer.hasRemaining()) { buffer.position(start); return false; } buffer.put(currentBufferByte); currentBufferByte = 0; bytePos = 0; } if (buffer.position() - start > toEncode.length()) { //the encoded version is longer than the original //just return false buffer.position(start); return false; } } if (bytePos > 0) { //add the EOS bytes if we have not finished on a single byte if (!buffer.hasRemaining()) { buffer.position(start); return false; } buffer.put((byte) (currentBufferByte | ((0xFF) >> bytePos))); } return true; }
java
public static boolean encode(ByteBuffer buffer, String toEncode, boolean forceLowercase) { if (buffer.remaining() <= toEncode.length()) { return false; } int start = buffer.position(); //this sucks, but we need to put the length first //and we don't really have any option but to calculate it in advance to make sure we have left enough room //so we end up iterating twice int length = 0; for (int i = 0; i < toEncode.length(); ++i) { byte c = (byte) toEncode.charAt(i); if(forceLowercase) { c = Hpack.toLower(c); } HuffmanCode code = HUFFMAN_CODES[c]; length += code.length; } int byteLength = length / 8 + (length % 8 == 0 ? 0 : 1); buffer.put((byte) (1 << 7)); Hpack.encodeInteger(buffer, byteLength, 7); int bytePos = 0; byte currentBufferByte = 0; for (int i = 0; i < toEncode.length(); ++i) { byte c = (byte) toEncode.charAt(i); if(forceLowercase) { c = Hpack.toLower(c); } HuffmanCode code = HUFFMAN_CODES[c]; if (code.length + bytePos <= 8) { //it fits in the current byte currentBufferByte |= ((code.value & 0xFF) << 8 - (code.length + bytePos)); bytePos += code.length; } else { //it does not fit, it may need up to 4 bytes int val = code.value; int rem = code.length; while (rem > 0) { if (!buffer.hasRemaining()) { buffer.position(start); return false; } int remainingInByte = 8 - bytePos; if (rem > remainingInByte) { currentBufferByte |= (val >> (rem - remainingInByte)); } else { currentBufferByte |= (val << (remainingInByte - rem)); } if (rem > remainingInByte) { buffer.put(currentBufferByte); currentBufferByte = 0; bytePos = 0; } else { bytePos = rem; } rem -= remainingInByte; } } if (bytePos == 8) { if (!buffer.hasRemaining()) { buffer.position(start); return false; } buffer.put(currentBufferByte); currentBufferByte = 0; bytePos = 0; } if (buffer.position() - start > toEncode.length()) { //the encoded version is longer than the original //just return false buffer.position(start); return false; } } if (bytePos > 0) { //add the EOS bytes if we have not finished on a single byte if (!buffer.hasRemaining()) { buffer.position(start); return false; } buffer.put((byte) (currentBufferByte | ((0xFF) >> bytePos))); } return true; }
[ "public", "static", "boolean", "encode", "(", "ByteBuffer", "buffer", ",", "String", "toEncode", ",", "boolean", "forceLowercase", ")", "{", "if", "(", "buffer", ".", "remaining", "(", ")", "<=", "toEncode", ".", "length", "(", ")", ")", "{", "return", "false", ";", "}", "int", "start", "=", "buffer", ".", "position", "(", ")", ";", "//this sucks, but we need to put the length first", "//and we don't really have any option but to calculate it in advance to make sure we have left enough room", "//so we end up iterating twice", "int", "length", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "toEncode", ".", "length", "(", ")", ";", "++", "i", ")", "{", "byte", "c", "=", "(", "byte", ")", "toEncode", ".", "charAt", "(", "i", ")", ";", "if", "(", "forceLowercase", ")", "{", "c", "=", "Hpack", ".", "toLower", "(", "c", ")", ";", "}", "HuffmanCode", "code", "=", "HUFFMAN_CODES", "[", "c", "]", ";", "length", "+=", "code", ".", "length", ";", "}", "int", "byteLength", "=", "length", "/", "8", "+", "(", "length", "%", "8", "==", "0", "?", "0", ":", "1", ")", ";", "buffer", ".", "put", "(", "(", "byte", ")", "(", "1", "<<", "7", ")", ")", ";", "Hpack", ".", "encodeInteger", "(", "buffer", ",", "byteLength", ",", "7", ")", ";", "int", "bytePos", "=", "0", ";", "byte", "currentBufferByte", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "toEncode", ".", "length", "(", ")", ";", "++", "i", ")", "{", "byte", "c", "=", "(", "byte", ")", "toEncode", ".", "charAt", "(", "i", ")", ";", "if", "(", "forceLowercase", ")", "{", "c", "=", "Hpack", ".", "toLower", "(", "c", ")", ";", "}", "HuffmanCode", "code", "=", "HUFFMAN_CODES", "[", "c", "]", ";", "if", "(", "code", ".", "length", "+", "bytePos", "<=", "8", ")", "{", "//it fits in the current byte", "currentBufferByte", "|=", "(", "(", "code", ".", "value", "&", "0xFF", ")", "<<", "8", "-", "(", "code", ".", "length", "+", "bytePos", ")", ")", ";", "bytePos", "+=", "code", ".", "length", ";", "}", "else", "{", "//it does not fit, it may need up to 4 bytes", "int", "val", "=", "code", ".", "value", ";", "int", "rem", "=", "code", ".", "length", ";", "while", "(", "rem", ">", "0", ")", "{", "if", "(", "!", "buffer", ".", "hasRemaining", "(", ")", ")", "{", "buffer", ".", "position", "(", "start", ")", ";", "return", "false", ";", "}", "int", "remainingInByte", "=", "8", "-", "bytePos", ";", "if", "(", "rem", ">", "remainingInByte", ")", "{", "currentBufferByte", "|=", "(", "val", ">>", "(", "rem", "-", "remainingInByte", ")", ")", ";", "}", "else", "{", "currentBufferByte", "|=", "(", "val", "<<", "(", "remainingInByte", "-", "rem", ")", ")", ";", "}", "if", "(", "rem", ">", "remainingInByte", ")", "{", "buffer", ".", "put", "(", "currentBufferByte", ")", ";", "currentBufferByte", "=", "0", ";", "bytePos", "=", "0", ";", "}", "else", "{", "bytePos", "=", "rem", ";", "}", "rem", "-=", "remainingInByte", ";", "}", "}", "if", "(", "bytePos", "==", "8", ")", "{", "if", "(", "!", "buffer", ".", "hasRemaining", "(", ")", ")", "{", "buffer", ".", "position", "(", "start", ")", ";", "return", "false", ";", "}", "buffer", ".", "put", "(", "currentBufferByte", ")", ";", "currentBufferByte", "=", "0", ";", "bytePos", "=", "0", ";", "}", "if", "(", "buffer", ".", "position", "(", ")", "-", "start", ">", "toEncode", ".", "length", "(", ")", ")", "{", "//the encoded version is longer than the original", "//just return false", "buffer", ".", "position", "(", "start", ")", ";", "return", "false", ";", "}", "}", "if", "(", "bytePos", ">", "0", ")", "{", "//add the EOS bytes if we have not finished on a single byte", "if", "(", "!", "buffer", ".", "hasRemaining", "(", ")", ")", "{", "buffer", ".", "position", "(", "start", ")", ";", "return", "false", ";", "}", "buffer", ".", "put", "(", "(", "byte", ")", "(", "currentBufferByte", "|", "(", "(", "0xFF", ")", ">>", "bytePos", ")", ")", ")", ";", "}", "return", "true", ";", "}" ]
Encodes the given string into the buffer. If there is not enough space in the buffer, or the encoded version is bigger than the original it will return false and not modify the buffers position @param buffer The buffer to encode into @param toEncode The string to encode @param forceLowercase If the string should be encoded in lower case @return true if encoding succeeded
[ "Encodes", "the", "given", "string", "into", "the", "buffer", ".", "If", "there", "is", "not", "enough", "space", "in", "the", "buffer", "or", "the", "encoded", "version", "is", "bigger", "than", "the", "original", "it", "will", "return", "false", "and", "not", "modify", "the", "buffers", "position" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/HPackHuffman.java#L431-L516
16,777
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/resource/PathResourceManager.java
PathResourceManager.getSymlinkBase
private SymlinkResult getSymlinkBase(final String base, final Path file) throws IOException { int nameCount = file.getNameCount(); Path root = fileSystem.getPath(base); int rootCount = root.getNameCount(); Path f = file; for (int i = nameCount - 1; i>=0; i--) { if (Files.isSymbolicLink(f)) { return new SymlinkResult(i+1 > rootCount, f); } f = f.getParent(); } return null; }
java
private SymlinkResult getSymlinkBase(final String base, final Path file) throws IOException { int nameCount = file.getNameCount(); Path root = fileSystem.getPath(base); int rootCount = root.getNameCount(); Path f = file; for (int i = nameCount - 1; i>=0; i--) { if (Files.isSymbolicLink(f)) { return new SymlinkResult(i+1 > rootCount, f); } f = f.getParent(); } return null; }
[ "private", "SymlinkResult", "getSymlinkBase", "(", "final", "String", "base", ",", "final", "Path", "file", ")", "throws", "IOException", "{", "int", "nameCount", "=", "file", ".", "getNameCount", "(", ")", ";", "Path", "root", "=", "fileSystem", ".", "getPath", "(", "base", ")", ";", "int", "rootCount", "=", "root", ".", "getNameCount", "(", ")", ";", "Path", "f", "=", "file", ";", "for", "(", "int", "i", "=", "nameCount", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "Files", ".", "isSymbolicLink", "(", "f", ")", ")", "{", "return", "new", "SymlinkResult", "(", "i", "+", "1", ">", "rootCount", ",", "f", ")", ";", "}", "f", "=", "f", ".", "getParent", "(", ")", ";", "}", "return", "null", ";", "}" ]
Returns true is some element of path inside base path is a symlink.
[ "Returns", "true", "is", "some", "element", "of", "path", "inside", "base", "path", "is", "a", "symlink", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/resource/PathResourceManager.java#L300-L313
16,778
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/resource/PathResourceManager.java
PathResourceManager.isSymlinkSafe
private boolean isSymlinkSafe(final Path file) throws IOException { String canonicalPath = file.toRealPath().toString(); for (String safePath : this.safePaths) { if (safePath.length() > 0) { if (safePath.startsWith(fileSystem.getSeparator())) { /* * Absolute path */ if (safePath.length() > 0 && canonicalPath.length() >= safePath.length() && canonicalPath.startsWith(safePath)) { return true; } } else { /* * In relative path we build the path appending to base */ String absSafePath = base + fileSystem.getSeparator() + safePath; Path absSafePathFile = fileSystem.getPath(absSafePath); String canonicalSafePath = absSafePathFile.toRealPath().toString(); if (canonicalSafePath.length() > 0 && canonicalPath.length() >= canonicalSafePath.length() && canonicalPath.startsWith(canonicalSafePath)) { return true; } } } } return false; }
java
private boolean isSymlinkSafe(final Path file) throws IOException { String canonicalPath = file.toRealPath().toString(); for (String safePath : this.safePaths) { if (safePath.length() > 0) { if (safePath.startsWith(fileSystem.getSeparator())) { /* * Absolute path */ if (safePath.length() > 0 && canonicalPath.length() >= safePath.length() && canonicalPath.startsWith(safePath)) { return true; } } else { /* * In relative path we build the path appending to base */ String absSafePath = base + fileSystem.getSeparator() + safePath; Path absSafePathFile = fileSystem.getPath(absSafePath); String canonicalSafePath = absSafePathFile.toRealPath().toString(); if (canonicalSafePath.length() > 0 && canonicalPath.length() >= canonicalSafePath.length() && canonicalPath.startsWith(canonicalSafePath)) { return true; } } } } return false; }
[ "private", "boolean", "isSymlinkSafe", "(", "final", "Path", "file", ")", "throws", "IOException", "{", "String", "canonicalPath", "=", "file", ".", "toRealPath", "(", ")", ".", "toString", "(", ")", ";", "for", "(", "String", "safePath", ":", "this", ".", "safePaths", ")", "{", "if", "(", "safePath", ".", "length", "(", ")", ">", "0", ")", "{", "if", "(", "safePath", ".", "startsWith", "(", "fileSystem", ".", "getSeparator", "(", ")", ")", ")", "{", "/*\n * Absolute path\n */", "if", "(", "safePath", ".", "length", "(", ")", ">", "0", "&&", "canonicalPath", ".", "length", "(", ")", ">=", "safePath", ".", "length", "(", ")", "&&", "canonicalPath", ".", "startsWith", "(", "safePath", ")", ")", "{", "return", "true", ";", "}", "}", "else", "{", "/*\n * In relative path we build the path appending to base\n */", "String", "absSafePath", "=", "base", "+", "fileSystem", ".", "getSeparator", "(", ")", "+", "safePath", ";", "Path", "absSafePathFile", "=", "fileSystem", ".", "getPath", "(", "absSafePath", ")", ";", "String", "canonicalSafePath", "=", "absSafePathFile", ".", "toRealPath", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "canonicalSafePath", ".", "length", "(", ")", ">", "0", "&&", "canonicalPath", ".", "length", "(", ")", ">=", "canonicalSafePath", ".", "length", "(", ")", "&&", "canonicalPath", ".", "startsWith", "(", "canonicalSafePath", ")", ")", "{", "return", "true", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Security check for followSymlinks feature. Only follows those symbolink links defined in safePaths.
[ "Security", "check", "for", "followSymlinks", "feature", ".", "Only", "follows", "those", "symbolink", "links", "defined", "in", "safePaths", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/resource/PathResourceManager.java#L334-L364
16,779
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/resource/PathResourceManager.java
PathResourceManager.getFileResource
protected PathResource getFileResource(final Path file, final String path, final Path symlinkBase, String normalizedFile) throws IOException { if (this.caseSensitive) { if (symlinkBase != null) { String relative = symlinkBase.relativize(file.normalize()).toString(); String fileResolved = file.toRealPath().toString(); String symlinkBaseResolved = symlinkBase.toRealPath().toString(); if (!fileResolved.startsWith(symlinkBaseResolved)) { log.tracef("Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s", path, base, normalizedFile); return null; } String compare = fileResolved.substring(symlinkBaseResolved.length()); if(compare.startsWith(fileSystem.getSeparator())) { compare = compare.substring(fileSystem.getSeparator().length()); } if(relative.startsWith(fileSystem.getSeparator())) { relative = relative.substring(fileSystem.getSeparator().length()); } if (relative.equals(compare)) { log.tracef("Found path resource %s from path resource manager with base %s", path, base); return new PathResource(file, this, path, eTagFunction.generate(file)); } log.tracef("Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s", path, base, normalizedFile); return null; } else if (isFileSameCase(file, normalizedFile)) { log.tracef("Found path resource %s from path resource manager with base %s", path, base); return new PathResource(file, this, path, eTagFunction.generate(file)); } else { log.tracef("Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s", path, base, normalizedFile); return null; } } else { log.tracef("Found path resource %s from path resource manager with base %s", path, base); return new PathResource(file, this, path, eTagFunction.generate(file)); } }
java
protected PathResource getFileResource(final Path file, final String path, final Path symlinkBase, String normalizedFile) throws IOException { if (this.caseSensitive) { if (symlinkBase != null) { String relative = symlinkBase.relativize(file.normalize()).toString(); String fileResolved = file.toRealPath().toString(); String symlinkBaseResolved = symlinkBase.toRealPath().toString(); if (!fileResolved.startsWith(symlinkBaseResolved)) { log.tracef("Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s", path, base, normalizedFile); return null; } String compare = fileResolved.substring(symlinkBaseResolved.length()); if(compare.startsWith(fileSystem.getSeparator())) { compare = compare.substring(fileSystem.getSeparator().length()); } if(relative.startsWith(fileSystem.getSeparator())) { relative = relative.substring(fileSystem.getSeparator().length()); } if (relative.equals(compare)) { log.tracef("Found path resource %s from path resource manager with base %s", path, base); return new PathResource(file, this, path, eTagFunction.generate(file)); } log.tracef("Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s", path, base, normalizedFile); return null; } else if (isFileSameCase(file, normalizedFile)) { log.tracef("Found path resource %s from path resource manager with base %s", path, base); return new PathResource(file, this, path, eTagFunction.generate(file)); } else { log.tracef("Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s", path, base, normalizedFile); return null; } } else { log.tracef("Found path resource %s from path resource manager with base %s", path, base); return new PathResource(file, this, path, eTagFunction.generate(file)); } }
[ "protected", "PathResource", "getFileResource", "(", "final", "Path", "file", ",", "final", "String", "path", ",", "final", "Path", "symlinkBase", ",", "String", "normalizedFile", ")", "throws", "IOException", "{", "if", "(", "this", ".", "caseSensitive", ")", "{", "if", "(", "symlinkBase", "!=", "null", ")", "{", "String", "relative", "=", "symlinkBase", ".", "relativize", "(", "file", ".", "normalize", "(", ")", ")", ".", "toString", "(", ")", ";", "String", "fileResolved", "=", "file", ".", "toRealPath", "(", ")", ".", "toString", "(", ")", ";", "String", "symlinkBaseResolved", "=", "symlinkBase", ".", "toRealPath", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "!", "fileResolved", ".", "startsWith", "(", "symlinkBaseResolved", ")", ")", "{", "log", ".", "tracef", "(", "\"Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s\"", ",", "path", ",", "base", ",", "normalizedFile", ")", ";", "return", "null", ";", "}", "String", "compare", "=", "fileResolved", ".", "substring", "(", "symlinkBaseResolved", ".", "length", "(", ")", ")", ";", "if", "(", "compare", ".", "startsWith", "(", "fileSystem", ".", "getSeparator", "(", ")", ")", ")", "{", "compare", "=", "compare", ".", "substring", "(", "fileSystem", ".", "getSeparator", "(", ")", ".", "length", "(", ")", ")", ";", "}", "if", "(", "relative", ".", "startsWith", "(", "fileSystem", ".", "getSeparator", "(", ")", ")", ")", "{", "relative", "=", "relative", ".", "substring", "(", "fileSystem", ".", "getSeparator", "(", ")", ".", "length", "(", ")", ")", ";", "}", "if", "(", "relative", ".", "equals", "(", "compare", ")", ")", "{", "log", ".", "tracef", "(", "\"Found path resource %s from path resource manager with base %s\"", ",", "path", ",", "base", ")", ";", "return", "new", "PathResource", "(", "file", ",", "this", ",", "path", ",", "eTagFunction", ".", "generate", "(", "file", ")", ")", ";", "}", "log", ".", "tracef", "(", "\"Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s\"", ",", "path", ",", "base", ",", "normalizedFile", ")", ";", "return", "null", ";", "}", "else", "if", "(", "isFileSameCase", "(", "file", ",", "normalizedFile", ")", ")", "{", "log", ".", "tracef", "(", "\"Found path resource %s from path resource manager with base %s\"", ",", "path", ",", "base", ")", ";", "return", "new", "PathResource", "(", "file", ",", "this", ",", "path", ",", "eTagFunction", ".", "generate", "(", "file", ")", ")", ";", "}", "else", "{", "log", ".", "tracef", "(", "\"Rejected path resource %s from path resource manager with base %s, as the case did not match actual case of %s\"", ",", "path", ",", "base", ",", "normalizedFile", ")", ";", "return", "null", ";", "}", "}", "else", "{", "log", ".", "tracef", "(", "\"Found path resource %s from path resource manager with base %s\"", ",", "path", ",", "base", ")", ";", "return", "new", "PathResource", "(", "file", ",", "this", ",", "path", ",", "eTagFunction", ".", "generate", "(", "file", ")", ")", ";", "}", "}" ]
Apply security check for case insensitive file systems.
[ "Apply", "security", "check", "for", "case", "insensitive", "file", "systems", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/resource/PathResourceManager.java#L369-L403
16,780
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel.java
AbstractFramedStreamSourceChannel.resumeReadsInternal
void resumeReadsInternal(boolean wakeup) { synchronized (lock) { boolean alreadyResumed = anyAreSet(state, STATE_READS_RESUMED); state |= STATE_READS_RESUMED; if (!alreadyResumed || wakeup) { if (!anyAreSet(state, STATE_IN_LISTENER_LOOP)) { state |= STATE_IN_LISTENER_LOOP; getFramedChannel().runInIoThread(new Runnable() { @Override public void run() { try { boolean moreData; do { ChannelListener<? super R> listener = getReadListener(); if (listener == null || !isReadResumed()) { return; } ChannelListeners.invokeChannelListener((R) AbstractFramedStreamSourceChannel.this, listener); //if writes are shutdown or we become active then we stop looping //we stop when writes are shutdown because we can't flush until we are active //although we may be flushed as part of a batch moreData = (frameDataRemaining > 0 && data != null) || !pendingFrameData.isEmpty() || anyAreSet(state, STATE_WAITNG_MINUS_ONE); } while (allAreSet(state, STATE_READS_RESUMED) && allAreClear(state, STATE_CLOSED | STATE_STREAM_BROKEN) && moreData); } finally { state &= ~STATE_IN_LISTENER_LOOP; } } }); } } } }
java
void resumeReadsInternal(boolean wakeup) { synchronized (lock) { boolean alreadyResumed = anyAreSet(state, STATE_READS_RESUMED); state |= STATE_READS_RESUMED; if (!alreadyResumed || wakeup) { if (!anyAreSet(state, STATE_IN_LISTENER_LOOP)) { state |= STATE_IN_LISTENER_LOOP; getFramedChannel().runInIoThread(new Runnable() { @Override public void run() { try { boolean moreData; do { ChannelListener<? super R> listener = getReadListener(); if (listener == null || !isReadResumed()) { return; } ChannelListeners.invokeChannelListener((R) AbstractFramedStreamSourceChannel.this, listener); //if writes are shutdown or we become active then we stop looping //we stop when writes are shutdown because we can't flush until we are active //although we may be flushed as part of a batch moreData = (frameDataRemaining > 0 && data != null) || !pendingFrameData.isEmpty() || anyAreSet(state, STATE_WAITNG_MINUS_ONE); } while (allAreSet(state, STATE_READS_RESUMED) && allAreClear(state, STATE_CLOSED | STATE_STREAM_BROKEN) && moreData); } finally { state &= ~STATE_IN_LISTENER_LOOP; } } }); } } } }
[ "void", "resumeReadsInternal", "(", "boolean", "wakeup", ")", "{", "synchronized", "(", "lock", ")", "{", "boolean", "alreadyResumed", "=", "anyAreSet", "(", "state", ",", "STATE_READS_RESUMED", ")", ";", "state", "|=", "STATE_READS_RESUMED", ";", "if", "(", "!", "alreadyResumed", "||", "wakeup", ")", "{", "if", "(", "!", "anyAreSet", "(", "state", ",", "STATE_IN_LISTENER_LOOP", ")", ")", "{", "state", "|=", "STATE_IN_LISTENER_LOOP", ";", "getFramedChannel", "(", ")", ".", "runInIoThread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "boolean", "moreData", ";", "do", "{", "ChannelListener", "<", "?", "super", "R", ">", "listener", "=", "getReadListener", "(", ")", ";", "if", "(", "listener", "==", "null", "||", "!", "isReadResumed", "(", ")", ")", "{", "return", ";", "}", "ChannelListeners", ".", "invokeChannelListener", "(", "(", "R", ")", "AbstractFramedStreamSourceChannel", ".", "this", ",", "listener", ")", ";", "//if writes are shutdown or we become active then we stop looping", "//we stop when writes are shutdown because we can't flush until we are active", "//although we may be flushed as part of a batch", "moreData", "=", "(", "frameDataRemaining", ">", "0", "&&", "data", "!=", "null", ")", "||", "!", "pendingFrameData", ".", "isEmpty", "(", ")", "||", "anyAreSet", "(", "state", ",", "STATE_WAITNG_MINUS_ONE", ")", ";", "}", "while", "(", "allAreSet", "(", "state", ",", "STATE_READS_RESUMED", ")", "&&", "allAreClear", "(", "state", ",", "STATE_CLOSED", "|", "STATE_STREAM_BROKEN", ")", "&&", "moreData", ")", ";", "}", "finally", "{", "state", "&=", "~", "STATE_IN_LISTENER_LOOP", ";", "}", "}", "}", ")", ";", "}", "}", "}", "}" ]
For this class there is no difference between a resume and a wakeup
[ "For", "this", "class", "there", "is", "no", "difference", "between", "a", "resume", "and", "a", "wakeup" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel.java#L264-L297
16,781
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel.java
AbstractFramedStreamSourceChannel.dataReady
protected void dataReady(FrameHeaderData headerData, PooledByteBuffer frameData) { if(anyAreSet(state, STATE_STREAM_BROKEN | STATE_CLOSED)) { frameData.close(); return; } synchronized (lock) { boolean newData = pendingFrameData.isEmpty(); this.pendingFrameData.add(new FrameData(headerData, frameData)); if (newData) { if (waiters > 0) { lock.notifyAll(); } } waitingForFrame = false; } if (anyAreSet(state, STATE_READS_RESUMED)) { resumeReadsInternal(true); } if(headerData != null) { currentStreamSize += headerData.getFrameLength(); if(maxStreamSize > 0 && currentStreamSize > maxStreamSize) { handleStreamTooLarge(); } } }
java
protected void dataReady(FrameHeaderData headerData, PooledByteBuffer frameData) { if(anyAreSet(state, STATE_STREAM_BROKEN | STATE_CLOSED)) { frameData.close(); return; } synchronized (lock) { boolean newData = pendingFrameData.isEmpty(); this.pendingFrameData.add(new FrameData(headerData, frameData)); if (newData) { if (waiters > 0) { lock.notifyAll(); } } waitingForFrame = false; } if (anyAreSet(state, STATE_READS_RESUMED)) { resumeReadsInternal(true); } if(headerData != null) { currentStreamSize += headerData.getFrameLength(); if(maxStreamSize > 0 && currentStreamSize > maxStreamSize) { handleStreamTooLarge(); } } }
[ "protected", "void", "dataReady", "(", "FrameHeaderData", "headerData", ",", "PooledByteBuffer", "frameData", ")", "{", "if", "(", "anyAreSet", "(", "state", ",", "STATE_STREAM_BROKEN", "|", "STATE_CLOSED", ")", ")", "{", "frameData", ".", "close", "(", ")", ";", "return", ";", "}", "synchronized", "(", "lock", ")", "{", "boolean", "newData", "=", "pendingFrameData", ".", "isEmpty", "(", ")", ";", "this", ".", "pendingFrameData", ".", "add", "(", "new", "FrameData", "(", "headerData", ",", "frameData", ")", ")", ";", "if", "(", "newData", ")", "{", "if", "(", "waiters", ">", "0", ")", "{", "lock", ".", "notifyAll", "(", ")", ";", "}", "}", "waitingForFrame", "=", "false", ";", "}", "if", "(", "anyAreSet", "(", "state", ",", "STATE_READS_RESUMED", ")", ")", "{", "resumeReadsInternal", "(", "true", ")", ";", "}", "if", "(", "headerData", "!=", "null", ")", "{", "currentStreamSize", "+=", "headerData", ".", "getFrameLength", "(", ")", ";", "if", "(", "maxStreamSize", ">", "0", "&&", "currentStreamSize", ">", "maxStreamSize", ")", "{", "handleStreamTooLarge", "(", ")", ";", "}", "}", "}" ]
Called when data has been read from the underlying channel. @param headerData The frame header data. This may be null if the data is part of a an existing frame @param frameData The frame data
[ "Called", "when", "data", "has", "been", "read", "from", "the", "underlying", "channel", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel.java#L374-L398
16,782
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel.java
AbstractFramedStreamSourceChannel.markStreamBroken
protected void markStreamBroken() { if(anyAreSet(state, STATE_STREAM_BROKEN)) { return; } synchronized (lock) { state |= STATE_STREAM_BROKEN; PooledByteBuffer data = this.data; if(data != null) { try { data.close(); //may have been closed by the read thread } catch (Throwable e) { //ignore } this.data = null; } for(FrameData frame : pendingFrameData) { frame.frameData.close(); } pendingFrameData.clear(); if(isReadResumed()) { resumeReadsInternal(true); } if (waiters > 0) { lock.notifyAll(); } } }
java
protected void markStreamBroken() { if(anyAreSet(state, STATE_STREAM_BROKEN)) { return; } synchronized (lock) { state |= STATE_STREAM_BROKEN; PooledByteBuffer data = this.data; if(data != null) { try { data.close(); //may have been closed by the read thread } catch (Throwable e) { //ignore } this.data = null; } for(FrameData frame : pendingFrameData) { frame.frameData.close(); } pendingFrameData.clear(); if(isReadResumed()) { resumeReadsInternal(true); } if (waiters > 0) { lock.notifyAll(); } } }
[ "protected", "void", "markStreamBroken", "(", ")", "{", "if", "(", "anyAreSet", "(", "state", ",", "STATE_STREAM_BROKEN", ")", ")", "{", "return", ";", "}", "synchronized", "(", "lock", ")", "{", "state", "|=", "STATE_STREAM_BROKEN", ";", "PooledByteBuffer", "data", "=", "this", ".", "data", ";", "if", "(", "data", "!=", "null", ")", "{", "try", "{", "data", ".", "close", "(", ")", ";", "//may have been closed by the read thread", "}", "catch", "(", "Throwable", "e", ")", "{", "//ignore", "}", "this", ".", "data", "=", "null", ";", "}", "for", "(", "FrameData", "frame", ":", "pendingFrameData", ")", "{", "frame", ".", "frameData", ".", "close", "(", ")", ";", "}", "pendingFrameData", ".", "clear", "(", ")", ";", "if", "(", "isReadResumed", "(", ")", ")", "{", "resumeReadsInternal", "(", "true", ")", ";", "}", "if", "(", "waiters", ">", "0", ")", "{", "lock", ".", "notifyAll", "(", ")", ";", "}", "}", "}" ]
Called when this stream is no longer valid. Reads from the stream will result in an exception.
[ "Called", "when", "this", "stream", "is", "no", "longer", "valid", ".", "Reads", "from", "the", "stream", "will", "result", "in", "an", "exception", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel.java#L650-L676
16,783
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/util/SavedRequest.java
SavedRequest.getMaxBufferSizeToSave
public static int getMaxBufferSizeToSave(final HttpServerExchange exchange) { int maxSize = exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_BUFFERED_REQUEST_SIZE, UndertowOptions.DEFAULT_MAX_BUFFERED_REQUEST_SIZE); return maxSize; }
java
public static int getMaxBufferSizeToSave(final HttpServerExchange exchange) { int maxSize = exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_BUFFERED_REQUEST_SIZE, UndertowOptions.DEFAULT_MAX_BUFFERED_REQUEST_SIZE); return maxSize; }
[ "public", "static", "int", "getMaxBufferSizeToSave", "(", "final", "HttpServerExchange", "exchange", ")", "{", "int", "maxSize", "=", "exchange", ".", "getConnection", "(", ")", ".", "getUndertowOptions", "(", ")", ".", "get", "(", "UndertowOptions", ".", "MAX_BUFFERED_REQUEST_SIZE", ",", "UndertowOptions", ".", "DEFAULT_MAX_BUFFERED_REQUEST_SIZE", ")", ";", "return", "maxSize", ";", "}" ]
With added possibility to save data from buffer instead f from request body, there has to be method which returns max allowed buffer size to save. @param exchange @return
[ "With", "added", "possibility", "to", "save", "data", "from", "buffer", "instead", "f", "from", "request", "body", "there", "has", "to", "be", "method", "which", "returns", "max", "allowed", "buffer", "size", "to", "save", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/util/SavedRequest.java#L77-L80
16,784
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java
ProxyConnectionPool.returnConnection
private void returnConnection(final ConnectionHolder connectionHolder) { ClientStatistics stats = connectionHolder.clientConnection.getStatistics(); this.requestCount.incrementAndGet(); if(stats != null) { //we update the stats when the connection is closed this.read.addAndGet(stats.getRead()); this.written.addAndGet(stats.getWritten()); stats.reset(); } HostThreadData hostData = getData(); if (closed) { //the host has been closed IoUtils.safeClose(connectionHolder.clientConnection); ConnectionHolder con = hostData.availableConnections.poll(); while (con != null) { IoUtils.safeClose(con.clientConnection); con = hostData.availableConnections.poll(); } redistributeQueued(hostData); return; } //only do something if the connection is open. If it is closed then //the close setter will handle creating a new connection and decrementing //the connection count final ClientConnection connection = connectionHolder.clientConnection; if (connection.isOpen() && !connection.isUpgraded()) { CallbackHolder callback = hostData.awaitingConnections.poll(); while (callback != null && callback.isCancelled()) { callback = hostData.awaitingConnections.poll(); } if (callback != null) { if (callback.getTimeoutKey() != null) { callback.getTimeoutKey().remove(); } // Anything waiting for a connection is not expecting exclusivity. connectionReady(connectionHolder, callback.getCallback(), callback.getExchange(), false); } else { final int cachedConnectionCount = hostData.availableConnections.size(); if (cachedConnectionCount >= maxCachedConnections) { // Close the longest idle connection instead of the current one final ConnectionHolder holder = hostData.availableConnections.poll(); if (holder != null) { IoUtils.safeClose(holder.clientConnection); } } hostData.availableConnections.add(connectionHolder); // If the soft max and ttl are configured if (timeToLive > 0) { //we only start the timeout process once we have hit the core pool size //otherwise connections could start timing out immediately once the core pool size is hit //and if we never hit the core pool size then it does not make sense to start timers which are never //used (as timers are expensive) final long currentTime = System.currentTimeMillis(); connectionHolder.timeout = currentTime + timeToLive; if(hostData.availableConnections.size() > coreCachedConnections) { if (hostData.nextTimeout <= 0) { hostData.timeoutKey = WorkerUtils.executeAfter(connection.getIoThread(), hostData.timeoutTask, timeToLive, TimeUnit.MILLISECONDS); hostData.nextTimeout = connectionHolder.timeout; } } } } } else if (connection.isOpen() && connection.isUpgraded()) { //we treat upgraded connections as closed //as we do not want the connection pool filled with upgraded connections //if the connection is actually closed the close setter will handle it connection.getCloseSetter().set(null); handleClosedConnection(hostData, connectionHolder); } }
java
private void returnConnection(final ConnectionHolder connectionHolder) { ClientStatistics stats = connectionHolder.clientConnection.getStatistics(); this.requestCount.incrementAndGet(); if(stats != null) { //we update the stats when the connection is closed this.read.addAndGet(stats.getRead()); this.written.addAndGet(stats.getWritten()); stats.reset(); } HostThreadData hostData = getData(); if (closed) { //the host has been closed IoUtils.safeClose(connectionHolder.clientConnection); ConnectionHolder con = hostData.availableConnections.poll(); while (con != null) { IoUtils.safeClose(con.clientConnection); con = hostData.availableConnections.poll(); } redistributeQueued(hostData); return; } //only do something if the connection is open. If it is closed then //the close setter will handle creating a new connection and decrementing //the connection count final ClientConnection connection = connectionHolder.clientConnection; if (connection.isOpen() && !connection.isUpgraded()) { CallbackHolder callback = hostData.awaitingConnections.poll(); while (callback != null && callback.isCancelled()) { callback = hostData.awaitingConnections.poll(); } if (callback != null) { if (callback.getTimeoutKey() != null) { callback.getTimeoutKey().remove(); } // Anything waiting for a connection is not expecting exclusivity. connectionReady(connectionHolder, callback.getCallback(), callback.getExchange(), false); } else { final int cachedConnectionCount = hostData.availableConnections.size(); if (cachedConnectionCount >= maxCachedConnections) { // Close the longest idle connection instead of the current one final ConnectionHolder holder = hostData.availableConnections.poll(); if (holder != null) { IoUtils.safeClose(holder.clientConnection); } } hostData.availableConnections.add(connectionHolder); // If the soft max and ttl are configured if (timeToLive > 0) { //we only start the timeout process once we have hit the core pool size //otherwise connections could start timing out immediately once the core pool size is hit //and if we never hit the core pool size then it does not make sense to start timers which are never //used (as timers are expensive) final long currentTime = System.currentTimeMillis(); connectionHolder.timeout = currentTime + timeToLive; if(hostData.availableConnections.size() > coreCachedConnections) { if (hostData.nextTimeout <= 0) { hostData.timeoutKey = WorkerUtils.executeAfter(connection.getIoThread(), hostData.timeoutTask, timeToLive, TimeUnit.MILLISECONDS); hostData.nextTimeout = connectionHolder.timeout; } } } } } else if (connection.isOpen() && connection.isUpgraded()) { //we treat upgraded connections as closed //as we do not want the connection pool filled with upgraded connections //if the connection is actually closed the close setter will handle it connection.getCloseSetter().set(null); handleClosedConnection(hostData, connectionHolder); } }
[ "private", "void", "returnConnection", "(", "final", "ConnectionHolder", "connectionHolder", ")", "{", "ClientStatistics", "stats", "=", "connectionHolder", ".", "clientConnection", ".", "getStatistics", "(", ")", ";", "this", ".", "requestCount", ".", "incrementAndGet", "(", ")", ";", "if", "(", "stats", "!=", "null", ")", "{", "//we update the stats when the connection is closed", "this", ".", "read", ".", "addAndGet", "(", "stats", ".", "getRead", "(", ")", ")", ";", "this", ".", "written", ".", "addAndGet", "(", "stats", ".", "getWritten", "(", ")", ")", ";", "stats", ".", "reset", "(", ")", ";", "}", "HostThreadData", "hostData", "=", "getData", "(", ")", ";", "if", "(", "closed", ")", "{", "//the host has been closed", "IoUtils", ".", "safeClose", "(", "connectionHolder", ".", "clientConnection", ")", ";", "ConnectionHolder", "con", "=", "hostData", ".", "availableConnections", ".", "poll", "(", ")", ";", "while", "(", "con", "!=", "null", ")", "{", "IoUtils", ".", "safeClose", "(", "con", ".", "clientConnection", ")", ";", "con", "=", "hostData", ".", "availableConnections", ".", "poll", "(", ")", ";", "}", "redistributeQueued", "(", "hostData", ")", ";", "return", ";", "}", "//only do something if the connection is open. If it is closed then", "//the close setter will handle creating a new connection and decrementing", "//the connection count", "final", "ClientConnection", "connection", "=", "connectionHolder", ".", "clientConnection", ";", "if", "(", "connection", ".", "isOpen", "(", ")", "&&", "!", "connection", ".", "isUpgraded", "(", ")", ")", "{", "CallbackHolder", "callback", "=", "hostData", ".", "awaitingConnections", ".", "poll", "(", ")", ";", "while", "(", "callback", "!=", "null", "&&", "callback", ".", "isCancelled", "(", ")", ")", "{", "callback", "=", "hostData", ".", "awaitingConnections", ".", "poll", "(", ")", ";", "}", "if", "(", "callback", "!=", "null", ")", "{", "if", "(", "callback", ".", "getTimeoutKey", "(", ")", "!=", "null", ")", "{", "callback", ".", "getTimeoutKey", "(", ")", ".", "remove", "(", ")", ";", "}", "// Anything waiting for a connection is not expecting exclusivity.", "connectionReady", "(", "connectionHolder", ",", "callback", ".", "getCallback", "(", ")", ",", "callback", ".", "getExchange", "(", ")", ",", "false", ")", ";", "}", "else", "{", "final", "int", "cachedConnectionCount", "=", "hostData", ".", "availableConnections", ".", "size", "(", ")", ";", "if", "(", "cachedConnectionCount", ">=", "maxCachedConnections", ")", "{", "// Close the longest idle connection instead of the current one", "final", "ConnectionHolder", "holder", "=", "hostData", ".", "availableConnections", ".", "poll", "(", ")", ";", "if", "(", "holder", "!=", "null", ")", "{", "IoUtils", ".", "safeClose", "(", "holder", ".", "clientConnection", ")", ";", "}", "}", "hostData", ".", "availableConnections", ".", "add", "(", "connectionHolder", ")", ";", "// If the soft max and ttl are configured", "if", "(", "timeToLive", ">", "0", ")", "{", "//we only start the timeout process once we have hit the core pool size", "//otherwise connections could start timing out immediately once the core pool size is hit", "//and if we never hit the core pool size then it does not make sense to start timers which are never", "//used (as timers are expensive)", "final", "long", "currentTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "connectionHolder", ".", "timeout", "=", "currentTime", "+", "timeToLive", ";", "if", "(", "hostData", ".", "availableConnections", ".", "size", "(", ")", ">", "coreCachedConnections", ")", "{", "if", "(", "hostData", ".", "nextTimeout", "<=", "0", ")", "{", "hostData", ".", "timeoutKey", "=", "WorkerUtils", ".", "executeAfter", "(", "connection", ".", "getIoThread", "(", ")", ",", "hostData", ".", "timeoutTask", ",", "timeToLive", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "hostData", ".", "nextTimeout", "=", "connectionHolder", ".", "timeout", ";", "}", "}", "}", "}", "}", "else", "if", "(", "connection", ".", "isOpen", "(", ")", "&&", "connection", ".", "isUpgraded", "(", ")", ")", "{", "//we treat upgraded connections as closed", "//as we do not want the connection pool filled with upgraded connections", "//if the connection is actually closed the close setter will handle it", "connection", ".", "getCloseSetter", "(", ")", ".", "set", "(", "null", ")", ";", "handleClosedConnection", "(", "hostData", ",", "connectionHolder", ")", ";", "}", "}" ]
Called when the IO thread has completed a successful request @param connectionHolder The client connection holder
[ "Called", "when", "the", "IO", "thread", "has", "completed", "a", "successful", "request" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java#L180-L252
16,785
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java
ProxyConnectionPool.scheduleFailedHostRetry
private void scheduleFailedHostRetry(final HttpServerExchange exchange) { final int retry = connectionPoolManager.getProblemServerRetry(); // only schedule a retry task if the node is not available if (retry > 0 && !connectionPoolManager.isAvailable()) { WorkerUtils.executeAfter(exchange.getIoThread(), new Runnable() { @Override public void run() { if (closed) { return; } UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Attempting to reconnect to failed host %s", getUri()); client.connect(new ClientCallback<ClientConnection>() { @Override public void completed(ClientConnection result) { UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Connected to previously failed host %s, returning to service", getUri()); if (connectionPoolManager.clearError()) { // In case the node is available now, return the connection final ConnectionHolder connectionHolder = new ConnectionHolder(result); final HostThreadData data = getData(); result.getCloseSetter().set(new ChannelListener<ClientConnection>() { @Override public void handleEvent(ClientConnection channel) { handleClosedConnection(data, connectionHolder); } }); data.connections++; returnConnection(connectionHolder); } else { // Otherwise reschedule the retry task scheduleFailedHostRetry(exchange); } } @Override public void failed(IOException e) { UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Failed to reconnect to failed host %s", getUri()); connectionPoolManager.handleError(); scheduleFailedHostRetry(exchange); } }, bindAddress, getUri(), exchange.getIoThread(), ssl, exchange.getConnection().getByteBufferPool(), options); } }, retry, TimeUnit.SECONDS); } }
java
private void scheduleFailedHostRetry(final HttpServerExchange exchange) { final int retry = connectionPoolManager.getProblemServerRetry(); // only schedule a retry task if the node is not available if (retry > 0 && !connectionPoolManager.isAvailable()) { WorkerUtils.executeAfter(exchange.getIoThread(), new Runnable() { @Override public void run() { if (closed) { return; } UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Attempting to reconnect to failed host %s", getUri()); client.connect(new ClientCallback<ClientConnection>() { @Override public void completed(ClientConnection result) { UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Connected to previously failed host %s, returning to service", getUri()); if (connectionPoolManager.clearError()) { // In case the node is available now, return the connection final ConnectionHolder connectionHolder = new ConnectionHolder(result); final HostThreadData data = getData(); result.getCloseSetter().set(new ChannelListener<ClientConnection>() { @Override public void handleEvent(ClientConnection channel) { handleClosedConnection(data, connectionHolder); } }); data.connections++; returnConnection(connectionHolder); } else { // Otherwise reschedule the retry task scheduleFailedHostRetry(exchange); } } @Override public void failed(IOException e) { UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Failed to reconnect to failed host %s", getUri()); connectionPoolManager.handleError(); scheduleFailedHostRetry(exchange); } }, bindAddress, getUri(), exchange.getIoThread(), ssl, exchange.getConnection().getByteBufferPool(), options); } }, retry, TimeUnit.SECONDS); } }
[ "private", "void", "scheduleFailedHostRetry", "(", "final", "HttpServerExchange", "exchange", ")", "{", "final", "int", "retry", "=", "connectionPoolManager", ".", "getProblemServerRetry", "(", ")", ";", "// only schedule a retry task if the node is not available", "if", "(", "retry", ">", "0", "&&", "!", "connectionPoolManager", ".", "isAvailable", "(", ")", ")", "{", "WorkerUtils", ".", "executeAfter", "(", "exchange", ".", "getIoThread", "(", ")", ",", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "closed", ")", "{", "return", ";", "}", "UndertowLogger", ".", "PROXY_REQUEST_LOGGER", ".", "debugf", "(", "\"Attempting to reconnect to failed host %s\"", ",", "getUri", "(", ")", ")", ";", "client", ".", "connect", "(", "new", "ClientCallback", "<", "ClientConnection", ">", "(", ")", "{", "@", "Override", "public", "void", "completed", "(", "ClientConnection", "result", ")", "{", "UndertowLogger", ".", "PROXY_REQUEST_LOGGER", ".", "debugf", "(", "\"Connected to previously failed host %s, returning to service\"", ",", "getUri", "(", ")", ")", ";", "if", "(", "connectionPoolManager", ".", "clearError", "(", ")", ")", "{", "// In case the node is available now, return the connection", "final", "ConnectionHolder", "connectionHolder", "=", "new", "ConnectionHolder", "(", "result", ")", ";", "final", "HostThreadData", "data", "=", "getData", "(", ")", ";", "result", ".", "getCloseSetter", "(", ")", ".", "set", "(", "new", "ChannelListener", "<", "ClientConnection", ">", "(", ")", "{", "@", "Override", "public", "void", "handleEvent", "(", "ClientConnection", "channel", ")", "{", "handleClosedConnection", "(", "data", ",", "connectionHolder", ")", ";", "}", "}", ")", ";", "data", ".", "connections", "++", ";", "returnConnection", "(", "connectionHolder", ")", ";", "}", "else", "{", "// Otherwise reschedule the retry task", "scheduleFailedHostRetry", "(", "exchange", ")", ";", "}", "}", "@", "Override", "public", "void", "failed", "(", "IOException", "e", ")", "{", "UndertowLogger", ".", "PROXY_REQUEST_LOGGER", ".", "debugf", "(", "\"Failed to reconnect to failed host %s\"", ",", "getUri", "(", ")", ")", ";", "connectionPoolManager", ".", "handleError", "(", ")", ";", "scheduleFailedHostRetry", "(", "exchange", ")", ";", "}", "}", ",", "bindAddress", ",", "getUri", "(", ")", ",", "exchange", ".", "getIoThread", "(", ")", ",", "ssl", ",", "exchange", ".", "getConnection", "(", ")", ".", "getByteBufferPool", "(", ")", ",", "options", ")", ";", "}", "}", ",", "retry", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "}" ]
If a host fails we periodically retry @param exchange The server exchange
[ "If", "a", "host", "fails", "we", "periodically", "retry" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java#L366-L410
16,786
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java
ProxyConnectionPool.timeoutConnections
private void timeoutConnections(final long currentTime, final HostThreadData data) { int idleConnections = data.availableConnections.size(); for (;;) { ConnectionHolder holder; if (idleConnections > 0 && idleConnections > coreCachedConnections && (holder = data.availableConnections.peek()) != null) { if (!holder.clientConnection.isOpen()) { // Already closed connections decrease the available connections idleConnections--; } else if (currentTime >= holder.timeout) { // If the timeout is reached already, just close holder = data.availableConnections.poll(); IoUtils.safeClose(holder.clientConnection); idleConnections--; } else { if (data.timeoutKey != null) { data.timeoutKey.remove(); data.timeoutKey = null; } // Schedule a timeout task final long remaining = holder.timeout - currentTime + 1; data.nextTimeout = holder.timeout; data.timeoutKey = WorkerUtils.executeAfter(holder.clientConnection.getIoThread(), data.timeoutTask, remaining, TimeUnit.MILLISECONDS); return; } } else { // If we are below the soft limit, just cancel the task if (data.timeoutKey != null) { data.timeoutKey.remove(); data.timeoutKey = null; } data.nextTimeout = -1; return; } } }
java
private void timeoutConnections(final long currentTime, final HostThreadData data) { int idleConnections = data.availableConnections.size(); for (;;) { ConnectionHolder holder; if (idleConnections > 0 && idleConnections > coreCachedConnections && (holder = data.availableConnections.peek()) != null) { if (!holder.clientConnection.isOpen()) { // Already closed connections decrease the available connections idleConnections--; } else if (currentTime >= holder.timeout) { // If the timeout is reached already, just close holder = data.availableConnections.poll(); IoUtils.safeClose(holder.clientConnection); idleConnections--; } else { if (data.timeoutKey != null) { data.timeoutKey.remove(); data.timeoutKey = null; } // Schedule a timeout task final long remaining = holder.timeout - currentTime + 1; data.nextTimeout = holder.timeout; data.timeoutKey = WorkerUtils.executeAfter(holder.clientConnection.getIoThread(), data.timeoutTask, remaining, TimeUnit.MILLISECONDS); return; } } else { // If we are below the soft limit, just cancel the task if (data.timeoutKey != null) { data.timeoutKey.remove(); data.timeoutKey = null; } data.nextTimeout = -1; return; } } }
[ "private", "void", "timeoutConnections", "(", "final", "long", "currentTime", ",", "final", "HostThreadData", "data", ")", "{", "int", "idleConnections", "=", "data", ".", "availableConnections", ".", "size", "(", ")", ";", "for", "(", ";", ";", ")", "{", "ConnectionHolder", "holder", ";", "if", "(", "idleConnections", ">", "0", "&&", "idleConnections", ">", "coreCachedConnections", "&&", "(", "holder", "=", "data", ".", "availableConnections", ".", "peek", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "!", "holder", ".", "clientConnection", ".", "isOpen", "(", ")", ")", "{", "// Already closed connections decrease the available connections", "idleConnections", "--", ";", "}", "else", "if", "(", "currentTime", ">=", "holder", ".", "timeout", ")", "{", "// If the timeout is reached already, just close", "holder", "=", "data", ".", "availableConnections", ".", "poll", "(", ")", ";", "IoUtils", ".", "safeClose", "(", "holder", ".", "clientConnection", ")", ";", "idleConnections", "--", ";", "}", "else", "{", "if", "(", "data", ".", "timeoutKey", "!=", "null", ")", "{", "data", ".", "timeoutKey", ".", "remove", "(", ")", ";", "data", ".", "timeoutKey", "=", "null", ";", "}", "// Schedule a timeout task", "final", "long", "remaining", "=", "holder", ".", "timeout", "-", "currentTime", "+", "1", ";", "data", ".", "nextTimeout", "=", "holder", ".", "timeout", ";", "data", ".", "timeoutKey", "=", "WorkerUtils", ".", "executeAfter", "(", "holder", ".", "clientConnection", ".", "getIoThread", "(", ")", ",", "data", ".", "timeoutTask", ",", "remaining", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "return", ";", "}", "}", "else", "{", "// If we are below the soft limit, just cancel the task", "if", "(", "data", ".", "timeoutKey", "!=", "null", ")", "{", "data", ".", "timeoutKey", ".", "remove", "(", ")", ";", "data", ".", "timeoutKey", "=", "null", ";", "}", "data", ".", "nextTimeout", "=", "-", "1", ";", "return", ";", "}", "}", "}" ]
Timeout idle connections which are above the soft max cached connections limit. @param currentTime the current time @param data the local host thread data
[ "Timeout", "idle", "connections", "which", "are", "above", "the", "soft", "max", "cached", "connections", "limit", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java#L418-L452
16,787
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java
ProxyConnectionPool.getData
private HostThreadData getData() { Thread thread = Thread.currentThread(); if (!(thread instanceof XnioIoThread)) { throw UndertowMessages.MESSAGES.canOnlyBeCalledByIoThread(); } XnioIoThread ioThread = (XnioIoThread) thread; HostThreadData data = hostThreadData.get(ioThread); if (data != null) { return data; } data = new HostThreadData(); HostThreadData existing = hostThreadData.putIfAbsent(ioThread, data); if (existing != null) { return existing; } return data; }
java
private HostThreadData getData() { Thread thread = Thread.currentThread(); if (!(thread instanceof XnioIoThread)) { throw UndertowMessages.MESSAGES.canOnlyBeCalledByIoThread(); } XnioIoThread ioThread = (XnioIoThread) thread; HostThreadData data = hostThreadData.get(ioThread); if (data != null) { return data; } data = new HostThreadData(); HostThreadData existing = hostThreadData.putIfAbsent(ioThread, data); if (existing != null) { return existing; } return data; }
[ "private", "HostThreadData", "getData", "(", ")", "{", "Thread", "thread", "=", "Thread", ".", "currentThread", "(", ")", ";", "if", "(", "!", "(", "thread", "instanceof", "XnioIoThread", ")", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "canOnlyBeCalledByIoThread", "(", ")", ";", "}", "XnioIoThread", "ioThread", "=", "(", "XnioIoThread", ")", "thread", ";", "HostThreadData", "data", "=", "hostThreadData", ".", "get", "(", "ioThread", ")", ";", "if", "(", "data", "!=", "null", ")", "{", "return", "data", ";", "}", "data", "=", "new", "HostThreadData", "(", ")", ";", "HostThreadData", "existing", "=", "hostThreadData", ".", "putIfAbsent", "(", "ioThread", ",", "data", ")", ";", "if", "(", "existing", "!=", "null", ")", "{", "return", "existing", ";", "}", "return", "data", ";", "}" ]
Gets the host data for this thread @return The data for this thread
[ "Gets", "the", "host", "data", "for", "this", "thread" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java#L459-L475
16,788
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java
ProxyConnectionPool.closeCurrentConnections
void closeCurrentConnections() { final CountDownLatch latch = new CountDownLatch(hostThreadData.size()); for(final Map.Entry<XnioIoThread, HostThreadData> data : hostThreadData.entrySet()) { data.getKey().execute(new Runnable() { @Override public void run() { ConnectionHolder d = data.getValue().availableConnections.poll(); while (d != null) { IoUtils.safeClose(d.clientConnection); d = data.getValue().availableConnections.poll(); } data.getValue().connections = 0; latch.countDown(); } }); } try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } }
java
void closeCurrentConnections() { final CountDownLatch latch = new CountDownLatch(hostThreadData.size()); for(final Map.Entry<XnioIoThread, HostThreadData> data : hostThreadData.entrySet()) { data.getKey().execute(new Runnable() { @Override public void run() { ConnectionHolder d = data.getValue().availableConnections.poll(); while (d != null) { IoUtils.safeClose(d.clientConnection); d = data.getValue().availableConnections.poll(); } data.getValue().connections = 0; latch.countDown(); } }); } try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } }
[ "void", "closeCurrentConnections", "(", ")", "{", "final", "CountDownLatch", "latch", "=", "new", "CountDownLatch", "(", "hostThreadData", ".", "size", "(", ")", ")", ";", "for", "(", "final", "Map", ".", "Entry", "<", "XnioIoThread", ",", "HostThreadData", ">", "data", ":", "hostThreadData", ".", "entrySet", "(", ")", ")", "{", "data", ".", "getKey", "(", ")", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "ConnectionHolder", "d", "=", "data", ".", "getValue", "(", ")", ".", "availableConnections", ".", "poll", "(", ")", ";", "while", "(", "d", "!=", "null", ")", "{", "IoUtils", ".", "safeClose", "(", "d", ".", "clientConnection", ")", ";", "d", "=", "data", ".", "getValue", "(", ")", ".", "availableConnections", ".", "poll", "(", ")", ";", "}", "data", ".", "getValue", "(", ")", ".", "connections", "=", "0", ";", "latch", ".", "countDown", "(", ")", ";", "}", "}", ")", ";", "}", "try", "{", "latch", ".", "await", "(", "10", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Should only be used for tests.
[ "Should", "only", "be", "used", "for", "tests", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/ProxyConnectionPool.java#L550-L571
16,789
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/form/FormParserFactory.java
FormParserFactory.createParser
public FormDataParser createParser(final HttpServerExchange exchange) { FormDataParser existing = exchange.getAttachment(ATTACHMENT_KEY); if(existing != null) { return existing; } for (int i = 0; i < parserDefinitions.length; ++i) { FormDataParser parser = parserDefinitions[i].create(exchange); if (parser != null) { exchange.putAttachment(ATTACHMENT_KEY, parser); return parser; } } return null; }
java
public FormDataParser createParser(final HttpServerExchange exchange) { FormDataParser existing = exchange.getAttachment(ATTACHMENT_KEY); if(existing != null) { return existing; } for (int i = 0; i < parserDefinitions.length; ++i) { FormDataParser parser = parserDefinitions[i].create(exchange); if (parser != null) { exchange.putAttachment(ATTACHMENT_KEY, parser); return parser; } } return null; }
[ "public", "FormDataParser", "createParser", "(", "final", "HttpServerExchange", "exchange", ")", "{", "FormDataParser", "existing", "=", "exchange", ".", "getAttachment", "(", "ATTACHMENT_KEY", ")", ";", "if", "(", "existing", "!=", "null", ")", "{", "return", "existing", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parserDefinitions", ".", "length", ";", "++", "i", ")", "{", "FormDataParser", "parser", "=", "parserDefinitions", "[", "i", "]", ".", "create", "(", "exchange", ")", ";", "if", "(", "parser", "!=", "null", ")", "{", "exchange", ".", "putAttachment", "(", "ATTACHMENT_KEY", ",", "parser", ")", ";", "return", "parser", ";", "}", "}", "return", "null", ";", "}" ]
Creates a form data parser for this request. If a parser has already been created for the request the existing parser will be returned rather than creating a new one. @param exchange The exchange @return A form data parser, or null if there is no parser registered for the request content type
[ "Creates", "a", "form", "data", "parser", "for", "this", "request", ".", "If", "a", "parser", "has", "already", "been", "created", "for", "the", "request", "the", "existing", "parser", "will", "be", "returned", "rather", "than", "creating", "a", "new", "one", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/form/FormParserFactory.java#L53-L66
16,790
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/handlers/security/ServletFormAuthenticationMechanism.java
ServletFormAuthenticationMechanism.storeInitialLocation
protected void storeInitialLocation(final HttpServerExchange exchange, byte[] bytes, int contentLength) { if(!saveOriginalRequest) { return; } final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, true); Session session; if (System.getSecurityManager() == null) { session = httpSession.getSession(); } else { session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession)); } SessionManager manager = session.getSessionManager(); if (seenSessionManagers.add(manager)) { manager.registerSessionListener(LISTENER); } session.setAttribute(SESSION_KEY, RedirectBuilder.redirect(exchange, exchange.getRelativePath())); if(bytes == null) { SavedRequest.trySaveRequest(exchange); } else { SavedRequest.trySaveRequest(exchange, bytes, contentLength); } }
java
protected void storeInitialLocation(final HttpServerExchange exchange, byte[] bytes, int contentLength) { if(!saveOriginalRequest) { return; } final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, true); Session session; if (System.getSecurityManager() == null) { session = httpSession.getSession(); } else { session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession)); } SessionManager manager = session.getSessionManager(); if (seenSessionManagers.add(manager)) { manager.registerSessionListener(LISTENER); } session.setAttribute(SESSION_KEY, RedirectBuilder.redirect(exchange, exchange.getRelativePath())); if(bytes == null) { SavedRequest.trySaveRequest(exchange); } else { SavedRequest.trySaveRequest(exchange, bytes, contentLength); } }
[ "protected", "void", "storeInitialLocation", "(", "final", "HttpServerExchange", "exchange", ",", "byte", "[", "]", "bytes", ",", "int", "contentLength", ")", "{", "if", "(", "!", "saveOriginalRequest", ")", "{", "return", ";", "}", "final", "ServletRequestContext", "servletRequestContext", "=", "exchange", ".", "getAttachment", "(", "ServletRequestContext", ".", "ATTACHMENT_KEY", ")", ";", "HttpSessionImpl", "httpSession", "=", "servletRequestContext", ".", "getCurrentServletContext", "(", ")", ".", "getSession", "(", "exchange", ",", "true", ")", ";", "Session", "session", ";", "if", "(", "System", ".", "getSecurityManager", "(", ")", "==", "null", ")", "{", "session", "=", "httpSession", ".", "getSession", "(", ")", ";", "}", "else", "{", "session", "=", "AccessController", ".", "doPrivileged", "(", "new", "HttpSessionImpl", ".", "UnwrapSessionAction", "(", "httpSession", ")", ")", ";", "}", "SessionManager", "manager", "=", "session", ".", "getSessionManager", "(", ")", ";", "if", "(", "seenSessionManagers", ".", "add", "(", "manager", ")", ")", "{", "manager", ".", "registerSessionListener", "(", "LISTENER", ")", ";", "}", "session", ".", "setAttribute", "(", "SESSION_KEY", ",", "RedirectBuilder", ".", "redirect", "(", "exchange", ",", "exchange", ".", "getRelativePath", "(", ")", ")", ")", ";", "if", "(", "bytes", "==", "null", ")", "{", "SavedRequest", ".", "trySaveRequest", "(", "exchange", ")", ";", "}", "else", "{", "SavedRequest", ".", "trySaveRequest", "(", "exchange", ",", "bytes", ",", "contentLength", ")", ";", "}", "}" ]
This method doesn't save content of request but instead uses data from parameter. This should be used in case that data from request was already read and therefore it is not possible to save them. @param exchange @param bytes @param contentLength
[ "This", "method", "doesn", "t", "save", "content", "of", "request", "but", "instead", "uses", "data", "from", "parameter", ".", "This", "should", "be", "used", "in", "case", "that", "data", "from", "request", "was", "already", "read", "and", "therefore", "it", "is", "not", "possible", "to", "save", "them", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/handlers/security/ServletFormAuthenticationMechanism.java#L170-L192
16,791
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.setRequestURI
public HttpServerExchange setRequestURI(final String requestURI, boolean containsHost) { this.requestURI = requestURI; if (containsHost) { this.state |= FLAG_URI_CONTAINS_HOST; } else { this.state &= ~FLAG_URI_CONTAINS_HOST; } return this; }
java
public HttpServerExchange setRequestURI(final String requestURI, boolean containsHost) { this.requestURI = requestURI; if (containsHost) { this.state |= FLAG_URI_CONTAINS_HOST; } else { this.state &= ~FLAG_URI_CONTAINS_HOST; } return this; }
[ "public", "HttpServerExchange", "setRequestURI", "(", "final", "String", "requestURI", ",", "boolean", "containsHost", ")", "{", "this", ".", "requestURI", "=", "requestURI", ";", "if", "(", "containsHost", ")", "{", "this", ".", "state", "|=", "FLAG_URI_CONTAINS_HOST", ";", "}", "else", "{", "this", ".", "state", "&=", "~", "FLAG_URI_CONTAINS_HOST", ";", "}", "return", "this", ";", "}" ]
Sets the request URI @param requestURI The new request URI @param containsHost If this is true the request URI contains the host part
[ "Sets", "the", "request", "URI" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L466-L474
16,792
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.getHostPort
public int getHostPort() { String host = requestHeaders.getFirst(Headers.HOST); if (host != null) { //for ipv6 addresses we make sure we take out the first part, which can have multiple occurrences of : final int colonIndex; if (host.startsWith("[")) { colonIndex = host.indexOf(':', host.indexOf(']')); } else { colonIndex = host.indexOf(':'); } if (colonIndex != -1) { try { return Integer.parseInt(host.substring(colonIndex + 1)); } catch (NumberFormatException ignore) {} } if (getRequestScheme().equals("https")) { return 443; } else if (getRequestScheme().equals("http")) { return 80; } } return getDestinationAddress().getPort(); }
java
public int getHostPort() { String host = requestHeaders.getFirst(Headers.HOST); if (host != null) { //for ipv6 addresses we make sure we take out the first part, which can have multiple occurrences of : final int colonIndex; if (host.startsWith("[")) { colonIndex = host.indexOf(':', host.indexOf(']')); } else { colonIndex = host.indexOf(':'); } if (colonIndex != -1) { try { return Integer.parseInt(host.substring(colonIndex + 1)); } catch (NumberFormatException ignore) {} } if (getRequestScheme().equals("https")) { return 443; } else if (getRequestScheme().equals("http")) { return 80; } } return getDestinationAddress().getPort(); }
[ "public", "int", "getHostPort", "(", ")", "{", "String", "host", "=", "requestHeaders", ".", "getFirst", "(", "Headers", ".", "HOST", ")", ";", "if", "(", "host", "!=", "null", ")", "{", "//for ipv6 addresses we make sure we take out the first part, which can have multiple occurrences of :", "final", "int", "colonIndex", ";", "if", "(", "host", ".", "startsWith", "(", "\"[\"", ")", ")", "{", "colonIndex", "=", "host", ".", "indexOf", "(", "'", "'", ",", "host", ".", "indexOf", "(", "'", "'", ")", ")", ";", "}", "else", "{", "colonIndex", "=", "host", ".", "indexOf", "(", "'", "'", ")", ";", "}", "if", "(", "colonIndex", "!=", "-", "1", ")", "{", "try", "{", "return", "Integer", ".", "parseInt", "(", "host", ".", "substring", "(", "colonIndex", "+", "1", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "ignore", ")", "{", "}", "}", "if", "(", "getRequestScheme", "(", ")", ".", "equals", "(", "\"https\"", ")", ")", "{", "return", "443", ";", "}", "else", "if", "(", "getRequestScheme", "(", ")", ".", "equals", "(", "\"http\"", ")", ")", "{", "return", "80", ";", "}", "}", "return", "getDestinationAddress", "(", ")", ".", "getPort", "(", ")", ";", "}" ]
Return the port that this request was sent to. In general this will be the value of the Host header, minus the host name. @return The port part of the destination address
[ "Return", "the", "port", "that", "this", "request", "was", "sent", "to", ".", "In", "general", "this", "will", "be", "the", "value", "of", "the", "Host", "header", "minus", "the", "host", "name", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L666-L689
16,793
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.updateBytesSent
void updateBytesSent(long bytes) { if(Connectors.isEntityBodyAllowed(this) && !getRequestMethod().equals(Methods.HEAD)) { responseBytesSent += bytes; } }
java
void updateBytesSent(long bytes) { if(Connectors.isEntityBodyAllowed(this) && !getRequestMethod().equals(Methods.HEAD)) { responseBytesSent += bytes; } }
[ "void", "updateBytesSent", "(", "long", "bytes", ")", "{", "if", "(", "Connectors", ".", "isEntityBodyAllowed", "(", "this", ")", "&&", "!", "getRequestMethod", "(", ")", ".", "equals", "(", "Methods", ".", "HEAD", ")", ")", "{", "responseBytesSent", "+=", "bytes", ";", "}", "}" ]
Updates the number of response bytes sent. Used when compression is in use @param bytes The number of bytes to increase the response size by. May be negative
[ "Updates", "the", "number", "of", "response", "bytes", "sent", ".", "Used", "when", "compression", "is", "in", "use" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L736-L740
16,794
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.setDispatchExecutor
public HttpServerExchange setDispatchExecutor(final Executor executor) { if (executor == null) { dispatchExecutor = null; } else { dispatchExecutor = executor; } return this; }
java
public HttpServerExchange setDispatchExecutor(final Executor executor) { if (executor == null) { dispatchExecutor = null; } else { dispatchExecutor = executor; } return this; }
[ "public", "HttpServerExchange", "setDispatchExecutor", "(", "final", "Executor", "executor", ")", "{", "if", "(", "executor", "==", "null", ")", "{", "dispatchExecutor", "=", "null", ";", "}", "else", "{", "dispatchExecutor", "=", "executor", ";", "}", "return", "this", ";", "}" ]
Sets the executor that is used for dispatch operations where no executor is specified. @param executor The executor to use
[ "Sets", "the", "executor", "that", "is", "used", "for", "dispatch", "operations", "where", "no", "executor", "is", "specified", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L842-L849
16,795
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.setResponseContentLength
public HttpServerExchange setResponseContentLength(long length) { if (length == -1) { responseHeaders.remove(Headers.CONTENT_LENGTH); } else { responseHeaders.put(Headers.CONTENT_LENGTH, Long.toString(length)); } return this; }
java
public HttpServerExchange setResponseContentLength(long length) { if (length == -1) { responseHeaders.remove(Headers.CONTENT_LENGTH); } else { responseHeaders.put(Headers.CONTENT_LENGTH, Long.toString(length)); } return this; }
[ "public", "HttpServerExchange", "setResponseContentLength", "(", "long", "length", ")", "{", "if", "(", "length", "==", "-", "1", ")", "{", "responseHeaders", ".", "remove", "(", "Headers", ".", "CONTENT_LENGTH", ")", ";", "}", "else", "{", "responseHeaders", ".", "put", "(", "Headers", ".", "CONTENT_LENGTH", ",", "Long", ".", "toString", "(", "length", ")", ")", ";", "}", "return", "this", ";", "}" ]
Sets the response content length @param length The content length
[ "Sets", "the", "response", "content", "length" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1065-L1072
16,796
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.getQueryParameters
public Map<String, Deque<String>> getQueryParameters() { if (queryParameters == null) { queryParameters = new TreeMap<>(); } return queryParameters; }
java
public Map<String, Deque<String>> getQueryParameters() { if (queryParameters == null) { queryParameters = new TreeMap<>(); } return queryParameters; }
[ "public", "Map", "<", "String", ",", "Deque", "<", "String", ">", ">", "getQueryParameters", "(", ")", "{", "if", "(", "queryParameters", "==", "null", ")", "{", "queryParameters", "=", "new", "TreeMap", "<>", "(", ")", ";", "}", "return", "queryParameters", ";", "}" ]
Returns a mutable map of query parameters. @return The query parameters
[ "Returns", "a", "mutable", "map", "of", "query", "parameters", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1079-L1084
16,797
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.getPathParameters
public Map<String, Deque<String>> getPathParameters() { if (pathParameters == null) { pathParameters = new TreeMap<>(); } return pathParameters; }
java
public Map<String, Deque<String>> getPathParameters() { if (pathParameters == null) { pathParameters = new TreeMap<>(); } return pathParameters; }
[ "public", "Map", "<", "String", ",", "Deque", "<", "String", ">", ">", "getPathParameters", "(", ")", "{", "if", "(", "pathParameters", "==", "null", ")", "{", "pathParameters", "=", "new", "TreeMap", "<>", "(", ")", ";", "}", "return", "pathParameters", ";", "}" ]
Returns a mutable map of path parameters @return The path parameters
[ "Returns", "a", "mutable", "map", "of", "path", "parameters" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1104-L1109
16,798
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.setResponseCookie
public HttpServerExchange setResponseCookie(final Cookie cookie) { if(getConnection().getUndertowOptions().get(UndertowOptions.ENABLE_RFC6265_COOKIE_VALIDATION, UndertowOptions.DEFAULT_ENABLE_RFC6265_COOKIE_VALIDATION)) { if (cookie.getValue() != null && !cookie.getValue().isEmpty()) { Rfc6265CookieSupport.validateCookieValue(cookie.getValue()); } if (cookie.getPath() != null && !cookie.getPath().isEmpty()) { Rfc6265CookieSupport.validatePath(cookie.getPath()); } if (cookie.getDomain() != null && !cookie.getDomain().isEmpty()) { Rfc6265CookieSupport.validateDomain(cookie.getDomain()); } } if (responseCookies == null) { responseCookies = new TreeMap<>(); //hashmap is slow to allocate in JDK7 } responseCookies.put(cookie.getName(), cookie); return this; }
java
public HttpServerExchange setResponseCookie(final Cookie cookie) { if(getConnection().getUndertowOptions().get(UndertowOptions.ENABLE_RFC6265_COOKIE_VALIDATION, UndertowOptions.DEFAULT_ENABLE_RFC6265_COOKIE_VALIDATION)) { if (cookie.getValue() != null && !cookie.getValue().isEmpty()) { Rfc6265CookieSupport.validateCookieValue(cookie.getValue()); } if (cookie.getPath() != null && !cookie.getPath().isEmpty()) { Rfc6265CookieSupport.validatePath(cookie.getPath()); } if (cookie.getDomain() != null && !cookie.getDomain().isEmpty()) { Rfc6265CookieSupport.validateDomain(cookie.getDomain()); } } if (responseCookies == null) { responseCookies = new TreeMap<>(); //hashmap is slow to allocate in JDK7 } responseCookies.put(cookie.getName(), cookie); return this; }
[ "public", "HttpServerExchange", "setResponseCookie", "(", "final", "Cookie", "cookie", ")", "{", "if", "(", "getConnection", "(", ")", ".", "getUndertowOptions", "(", ")", ".", "get", "(", "UndertowOptions", ".", "ENABLE_RFC6265_COOKIE_VALIDATION", ",", "UndertowOptions", ".", "DEFAULT_ENABLE_RFC6265_COOKIE_VALIDATION", ")", ")", "{", "if", "(", "cookie", ".", "getValue", "(", ")", "!=", "null", "&&", "!", "cookie", ".", "getValue", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "Rfc6265CookieSupport", ".", "validateCookieValue", "(", "cookie", ".", "getValue", "(", ")", ")", ";", "}", "if", "(", "cookie", ".", "getPath", "(", ")", "!=", "null", "&&", "!", "cookie", ".", "getPath", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "Rfc6265CookieSupport", ".", "validatePath", "(", "cookie", ".", "getPath", "(", ")", ")", ";", "}", "if", "(", "cookie", ".", "getDomain", "(", ")", "!=", "null", "&&", "!", "cookie", ".", "getDomain", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "Rfc6265CookieSupport", ".", "validateDomain", "(", "cookie", ".", "getDomain", "(", ")", ")", ";", "}", "}", "if", "(", "responseCookies", "==", "null", ")", "{", "responseCookies", "=", "new", "TreeMap", "<>", "(", ")", ";", "//hashmap is slow to allocate in JDK7", "}", "responseCookies", ".", "put", "(", "cookie", ".", "getName", "(", ")", ",", "cookie", ")", ";", "return", "this", ";", "}" ]
Sets a response cookie @param cookie The cookie
[ "Sets", "a", "response", "cookie" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1141-L1158
16,799
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.isRequestComplete
public boolean isRequestComplete() { PooledByteBuffer[] data = getAttachment(BUFFERED_REQUEST_DATA); if(data != null) { return false; } return allAreSet(state, FLAG_REQUEST_TERMINATED); }
java
public boolean isRequestComplete() { PooledByteBuffer[] data = getAttachment(BUFFERED_REQUEST_DATA); if(data != null) { return false; } return allAreSet(state, FLAG_REQUEST_TERMINATED); }
[ "public", "boolean", "isRequestComplete", "(", ")", "{", "PooledByteBuffer", "[", "]", "data", "=", "getAttachment", "(", "BUFFERED_REQUEST_DATA", ")", ";", "if", "(", "data", "!=", "null", ")", "{", "return", "false", ";", "}", "return", "allAreSet", "(", "state", ",", "FLAG_REQUEST_TERMINATED", ")", ";", "}" ]
Returns true if all data has been read from the request, or if there was not data. @return true if the request is complete
[ "Returns", "true", "if", "all", "data", "has", "been", "read", "from", "the", "request", "or", "if", "there", "was", "not", "data", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1237-L1243