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,600
find-sec-bugs/find-sec-bugs
findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintMethodConfig.java
TaintMethodConfig.setOuputTaint
public void setOuputTaint(Taint taint) { if (taint == null) { this.outputTaint = null; return; } Taint taintCopy = new Taint(taint); taintCopy.invalidateVariableIndex(); this.outputTaint = taintCopy; }
java
public void setOuputTaint(Taint taint) { if (taint == null) { this.outputTaint = null; return; } Taint taintCopy = new Taint(taint); taintCopy.invalidateVariableIndex(); this.outputTaint = taintCopy; }
[ "public", "void", "setOuputTaint", "(", "Taint", "taint", ")", "{", "if", "(", "taint", "==", "null", ")", "{", "this", ".", "outputTaint", "=", "null", ";", "return", ";", "}", "Taint", "taintCopy", "=", "new", "Taint", "(", "taint", ")", ";", "taintCopy", ".", "invalidateVariableIndex", "(", ")", ";", "this", ".", "outputTaint", "=", "taintCopy", ";", "}" ]
Sets the output taint of the method describing the taint transfer, copy of the parameter is made and variable index is invalidated @param taint output taint to set
[ "Sets", "the", "output", "taint", "of", "the", "method", "describing", "the", "taint", "transfer", "copy", "of", "the", "parameter", "is", "made", "and", "variable", "index", "is", "invalidated" ]
362da013cef4925e6a1506dd3511fe5bdcc5fba3
https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintMethodConfig.java#L150-L158
16,601
find-sec-bugs/find-sec-bugs
findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintMethodConfig.java
TaintMethodConfig.isInformative
public boolean isInformative() { if (this == SAFE_CONFIG) { // these are loaded automatically, do not need to store them return false; } if (outputTaint == null) { return false; } if (!outputTaint.isUnknown()) { return true; } if (outputTaint.hasParameters()) { return true; } if (outputTaint.getRealInstanceClass() != null) { return true; } if (outputTaint.hasTags() || outputTaint.isRemovingTags()) { return true; } return false; }
java
public boolean isInformative() { if (this == SAFE_CONFIG) { // these are loaded automatically, do not need to store them return false; } if (outputTaint == null) { return false; } if (!outputTaint.isUnknown()) { return true; } if (outputTaint.hasParameters()) { return true; } if (outputTaint.getRealInstanceClass() != null) { return true; } if (outputTaint.hasTags() || outputTaint.isRemovingTags()) { return true; } return false; }
[ "public", "boolean", "isInformative", "(", ")", "{", "if", "(", "this", "==", "SAFE_CONFIG", ")", "{", "// these are loaded automatically, do not need to store them", "return", "false", ";", "}", "if", "(", "outputTaint", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "!", "outputTaint", ".", "isUnknown", "(", ")", ")", "{", "return", "true", ";", "}", "if", "(", "outputTaint", ".", "hasParameters", "(", ")", ")", "{", "return", "true", ";", "}", "if", "(", "outputTaint", ".", "getRealInstanceClass", "(", ")", "!=", "null", ")", "{", "return", "true", ";", "}", "if", "(", "outputTaint", ".", "hasTags", "(", ")", "||", "outputTaint", ".", "isRemovingTags", "(", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if the summary needs to be saved or has no information value @return true if summary should be saved, false otherwise
[ "Checks", "if", "the", "summary", "needs", "to", "be", "saved", "or", "has", "no", "information", "value" ]
362da013cef4925e6a1506dd3511fe5bdcc5fba3
https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintMethodConfig.java#L184-L205
16,602
find-sec-bugs/find-sec-bugs
findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/AbstractInjectionDetector.java
AbstractInjectionDetector.report
@Override public void report() { // collect sinks and report each once Set<InjectionSink> injectionSinksToReport = new HashSet<InjectionSink>(); for (Set<InjectionSink> injectionSinkSet : injectionSinks.values()) { for (InjectionSink injectionSink : injectionSinkSet) { injectionSinksToReport.add(injectionSink); } } for (InjectionSink injectionSink : injectionSinksToReport) { bugReporter.reportBug(injectionSink.generateBugInstance(false)); } }
java
@Override public void report() { // collect sinks and report each once Set<InjectionSink> injectionSinksToReport = new HashSet<InjectionSink>(); for (Set<InjectionSink> injectionSinkSet : injectionSinks.values()) { for (InjectionSink injectionSink : injectionSinkSet) { injectionSinksToReport.add(injectionSink); } } for (InjectionSink injectionSink : injectionSinksToReport) { bugReporter.reportBug(injectionSink.generateBugInstance(false)); } }
[ "@", "Override", "public", "void", "report", "(", ")", "{", "// collect sinks and report each once", "Set", "<", "InjectionSink", ">", "injectionSinksToReport", "=", "new", "HashSet", "<", "InjectionSink", ">", "(", ")", ";", "for", "(", "Set", "<", "InjectionSink", ">", "injectionSinkSet", ":", "injectionSinks", ".", "values", "(", ")", ")", "{", "for", "(", "InjectionSink", "injectionSink", ":", "injectionSinkSet", ")", "{", "injectionSinksToReport", ".", "add", "(", "injectionSink", ")", ";", "}", "}", "for", "(", "InjectionSink", "injectionSink", ":", "injectionSinksToReport", ")", "{", "bugReporter", ".", "reportBug", "(", "injectionSink", ".", "generateBugInstance", "(", "false", ")", ")", ";", "}", "}" ]
Once the analysis is completed, all the collected sinks are reported as bugs.
[ "Once", "the", "analysis", "is", "completed", "all", "the", "collected", "sinks", "are", "reported", "as", "bugs", "." ]
362da013cef4925e6a1506dd3511fe5bdcc5fba3
https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/AbstractInjectionDetector.java#L58-L70
16,603
find-sec-bugs/find-sec-bugs
findsecbugs-samples-deps/src/main/java/org/apache/jasper/runtime/PageContextImpl.java
PageContextImpl.proprietaryEvaluate
public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap) throws ELException { return "" ; }
java
public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap) throws ELException { return "" ; }
[ "public", "static", "Object", "proprietaryEvaluate", "(", "final", "String", "expression", ",", "final", "Class", "<", "?", ">", "expectedType", ",", "final", "PageContext", "pageContext", ",", "final", "ProtectedFunctionMapper", "functionMap", ")", "throws", "ELException", "{", "return", "\"\"", ";", "}" ]
directly referenced by JSPC-generated code
[ "directly", "referenced", "by", "JSPC", "-", "generated", "code" ]
362da013cef4925e6a1506dd3511fe5bdcc5fba3
https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-samples-deps/src/main/java/org/apache/jasper/runtime/PageContextImpl.java#L25-L30
16,604
find-sec-bugs/find-sec-bugs
findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/BasicInjectionDetector.java
BasicInjectionDetector.loadConfiguredSinks
protected void loadConfiguredSinks(String filename, String bugType) { SINKS_LOADER.loadConfiguredSinks(filename, bugType, new SinksLoader.InjectionPointReceiver() { @Override public void receiveInjectionPoint(String fullMethodName, InjectionPoint injectionPoint) { addParsedInjectionPoint(fullMethodName, injectionPoint); } }); }
java
protected void loadConfiguredSinks(String filename, String bugType) { SINKS_LOADER.loadConfiguredSinks(filename, bugType, new SinksLoader.InjectionPointReceiver() { @Override public void receiveInjectionPoint(String fullMethodName, InjectionPoint injectionPoint) { addParsedInjectionPoint(fullMethodName, injectionPoint); } }); }
[ "protected", "void", "loadConfiguredSinks", "(", "String", "filename", ",", "String", "bugType", ")", "{", "SINKS_LOADER", ".", "loadConfiguredSinks", "(", "filename", ",", "bugType", ",", "new", "SinksLoader", ".", "InjectionPointReceiver", "(", ")", "{", "@", "Override", "public", "void", "receiveInjectionPoint", "(", "String", "fullMethodName", ",", "InjectionPoint", "injectionPoint", ")", "{", "addParsedInjectionPoint", "(", "fullMethodName", ",", "injectionPoint", ")", ";", "}", "}", ")", ";", "}" ]
Loads taint sinks from configuration @param filename name of the configuration file @param bugType type of an injection bug
[ "Loads", "taint", "sinks", "from", "configuration" ]
362da013cef4925e6a1506dd3511fe5bdcc5fba3
https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/BasicInjectionDetector.java#L108-L115
16,605
find-sec-bugs/find-sec-bugs
findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/BasicInjectionDetector.java
BasicInjectionDetector.loadCustomSinks
protected void loadCustomSinks(String fileName, String bugType) { InputStream stream = null; try { File file = new File(fileName); if (file.exists()) { stream = new FileInputStream(file); loadConfiguredSinks(stream, bugType); } else { stream = getClass().getClassLoader().getResourceAsStream(fileName); loadConfiguredSinks(stream, bugType); } } catch (Exception ex) { throw new RuntimeException("Cannot load custom injection sinks from " + fileName, ex); } finally { IO.close(stream); } }
java
protected void loadCustomSinks(String fileName, String bugType) { InputStream stream = null; try { File file = new File(fileName); if (file.exists()) { stream = new FileInputStream(file); loadConfiguredSinks(stream, bugType); } else { stream = getClass().getClassLoader().getResourceAsStream(fileName); loadConfiguredSinks(stream, bugType); } } catch (Exception ex) { throw new RuntimeException("Cannot load custom injection sinks from " + fileName, ex); } finally { IO.close(stream); } }
[ "protected", "void", "loadCustomSinks", "(", "String", "fileName", ",", "String", "bugType", ")", "{", "InputStream", "stream", "=", "null", ";", "try", "{", "File", "file", "=", "new", "File", "(", "fileName", ")", ";", "if", "(", "file", ".", "exists", "(", ")", ")", "{", "stream", "=", "new", "FileInputStream", "(", "file", ")", ";", "loadConfiguredSinks", "(", "stream", ",", "bugType", ")", ";", "}", "else", "{", "stream", "=", "getClass", "(", ")", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "fileName", ")", ";", "loadConfiguredSinks", "(", "stream", ",", "bugType", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"Cannot load custom injection sinks from \"", "+", "fileName", ",", "ex", ")", ";", "}", "finally", "{", "IO", ".", "close", "(", "stream", ")", ";", "}", "}" ]
Loads taint sinks configuration file from file system. If the file doesn't exist on file system, loads the file from classpath. @param fileName name of the configuration file @param bugType type of an injection bug
[ "Loads", "taint", "sinks", "configuration", "file", "from", "file", "system", ".", "If", "the", "file", "doesn", "t", "exist", "on", "file", "system", "loads", "the", "file", "from", "classpath", "." ]
362da013cef4925e6a1506dd3511fe5bdcc5fba3
https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/BasicInjectionDetector.java#L152-L168
16,606
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java
DeploymentInfo.addFirstAuthenticationMechanism
public DeploymentInfo addFirstAuthenticationMechanism(final String name, final AuthenticationMechanism mechanism) { authenticationMechanisms.put(name, new ImmediateAuthenticationMechanismFactory(mechanism)); if(loginConfig == null) { loginConfig = new LoginConfig(null); } loginConfig.addFirstAuthMethod(new AuthMethodConfig(name)); return this; }
java
public DeploymentInfo addFirstAuthenticationMechanism(final String name, final AuthenticationMechanism mechanism) { authenticationMechanisms.put(name, new ImmediateAuthenticationMechanismFactory(mechanism)); if(loginConfig == null) { loginConfig = new LoginConfig(null); } loginConfig.addFirstAuthMethod(new AuthMethodConfig(name)); return this; }
[ "public", "DeploymentInfo", "addFirstAuthenticationMechanism", "(", "final", "String", "name", ",", "final", "AuthenticationMechanism", "mechanism", ")", "{", "authenticationMechanisms", ".", "put", "(", "name", ",", "new", "ImmediateAuthenticationMechanismFactory", "(", "mechanism", ")", ")", ";", "if", "(", "loginConfig", "==", "null", ")", "{", "loginConfig", "=", "new", "LoginConfig", "(", "null", ")", ";", "}", "loginConfig", ".", "addFirstAuthMethod", "(", "new", "AuthMethodConfig", "(", "name", ")", ")", ";", "return", "this", ";", "}" ]
Adds an authentication mechanism directly to the deployment. This mechanism will be first in the list. In general you should just use {@link #addAuthenticationMechanism(String, io.undertow.security.api.AuthenticationMechanismFactory)} and allow the user to configure the methods they want by name. This method is essentially a convenience method, if is the same as registering a factory under the provided name that returns and authentication mechanism, and then adding it to the login config list. If you want your mechanism to be the only one in the deployment you should first invoke {@link #clearLoginMethods()}. @param name The authentication mechanism name @param mechanism The mechanism @return this deployment info
[ "Adds", "an", "authentication", "mechanism", "directly", "to", "the", "deployment", ".", "This", "mechanism", "will", "be", "first", "in", "the", "list", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java#L1007-L1014
16,607
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java
DeploymentInfo.addLastAuthenticationMechanism
public DeploymentInfo addLastAuthenticationMechanism(final String name, final AuthenticationMechanism mechanism) { authenticationMechanisms.put(name, new ImmediateAuthenticationMechanismFactory(mechanism)); if(loginConfig == null) { loginConfig = new LoginConfig(null); } loginConfig.addLastAuthMethod(new AuthMethodConfig(name)); return this; }
java
public DeploymentInfo addLastAuthenticationMechanism(final String name, final AuthenticationMechanism mechanism) { authenticationMechanisms.put(name, new ImmediateAuthenticationMechanismFactory(mechanism)); if(loginConfig == null) { loginConfig = new LoginConfig(null); } loginConfig.addLastAuthMethod(new AuthMethodConfig(name)); return this; }
[ "public", "DeploymentInfo", "addLastAuthenticationMechanism", "(", "final", "String", "name", ",", "final", "AuthenticationMechanism", "mechanism", ")", "{", "authenticationMechanisms", ".", "put", "(", "name", ",", "new", "ImmediateAuthenticationMechanismFactory", "(", "mechanism", ")", ")", ";", "if", "(", "loginConfig", "==", "null", ")", "{", "loginConfig", "=", "new", "LoginConfig", "(", "null", ")", ";", "}", "loginConfig", ".", "addLastAuthMethod", "(", "new", "AuthMethodConfig", "(", "name", ")", ")", ";", "return", "this", ";", "}" ]
Adds an authentication mechanism directly to the deployment. This mechanism will be last in the list. In general you should just use {@link #addAuthenticationMechanism(String, io.undertow.security.api.AuthenticationMechanismFactory)} and allow the user to configure the methods they want by name. This method is essentially a convenience method, if is the same as registering a factory under the provided name that returns and authentication mechanism, and then adding it to the login config list. If you want your mechanism to be the only one in the deployment you should first invoke {@link #clearLoginMethods()}. @param name The authentication mechanism name @param mechanism The mechanism @return
[ "Adds", "an", "authentication", "mechanism", "directly", "to", "the", "deployment", ".", "This", "mechanism", "will", "be", "last", "in", "the", "list", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java#L1031-L1038
16,608
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java
DeploymentInfo.addAuthenticationMechanism
public DeploymentInfo addAuthenticationMechanism(final String name, final AuthenticationMechanismFactory factory) { authenticationMechanisms.put(name.toUpperCase(Locale.US), factory); return this; }
java
public DeploymentInfo addAuthenticationMechanism(final String name, final AuthenticationMechanismFactory factory) { authenticationMechanisms.put(name.toUpperCase(Locale.US), factory); return this; }
[ "public", "DeploymentInfo", "addAuthenticationMechanism", "(", "final", "String", "name", ",", "final", "AuthenticationMechanismFactory", "factory", ")", "{", "authenticationMechanisms", ".", "put", "(", "name", ".", "toUpperCase", "(", "Locale", ".", "US", ")", ",", "factory", ")", ";", "return", "this", ";", "}" ]
Adds an authentication mechanism. The name is case insenstive, and will be converted to uppercase internally. @param name The name @param factory The factory @return
[ "Adds", "an", "authentication", "mechanism", ".", "The", "name", "is", "case", "insenstive", "and", "will", "be", "converted", "to", "uppercase", "internally", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java#L1047-L1050
16,609
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java
DeploymentInfo.isAuthenticationMechanismPresent
public boolean isAuthenticationMechanismPresent(final String mechanismName) { if(loginConfig != null) { for(AuthMethodConfig method : loginConfig.getAuthMethods()) { if(method.getName().equalsIgnoreCase(mechanismName)) { return true; } } } return false; }
java
public boolean isAuthenticationMechanismPresent(final String mechanismName) { if(loginConfig != null) { for(AuthMethodConfig method : loginConfig.getAuthMethods()) { if(method.getName().equalsIgnoreCase(mechanismName)) { return true; } } } return false; }
[ "public", "boolean", "isAuthenticationMechanismPresent", "(", "final", "String", "mechanismName", ")", "{", "if", "(", "loginConfig", "!=", "null", ")", "{", "for", "(", "AuthMethodConfig", "method", ":", "loginConfig", ".", "getAuthMethods", "(", ")", ")", "{", "if", "(", "method", ".", "getName", "(", ")", ".", "equalsIgnoreCase", "(", "mechanismName", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Returns true if the specified mechanism is present in the login config @param mechanismName The mechanism name @return true if the mechanism is enabled
[ "Returns", "true", "if", "the", "specified", "mechanism", "is", "present", "in", "the", "login", "config" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java#L1061-L1070
16,610
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java
DeploymentInfo.addPreCompressedResourceEncoding
public DeploymentInfo addPreCompressedResourceEncoding(String encoding, String extension) { preCompressedResources.put(encoding, extension); return this; }
java
public DeploymentInfo addPreCompressedResourceEncoding(String encoding, String extension) { preCompressedResources.put(encoding, extension); return this; }
[ "public", "DeploymentInfo", "addPreCompressedResourceEncoding", "(", "String", "encoding", ",", "String", "extension", ")", "{", "preCompressedResources", ".", "put", "(", "encoding", ",", "extension", ")", ";", "return", "this", ";", "}" ]
Adds a pre compressed resource encoding and maps it to a file extension @param encoding The content encoding @param extension The file extension @return this builder
[ "Adds", "a", "pre", "compressed", "resource", "encoding", "and", "maps", "it", "to", "a", "file", "extension" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/api/DeploymentInfo.java#L1342-L1345
16,611
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/Servlets.java
Servlets.defaultContainer
public static ServletContainer defaultContainer() { if (container != null) { return container; } synchronized (Servlets.class) { if (container != null) { return container; } return container = ServletContainer.Factory.newInstance(); } }
java
public static ServletContainer defaultContainer() { if (container != null) { return container; } synchronized (Servlets.class) { if (container != null) { return container; } return container = ServletContainer.Factory.newInstance(); } }
[ "public", "static", "ServletContainer", "defaultContainer", "(", ")", "{", "if", "(", "container", "!=", "null", ")", "{", "return", "container", ";", "}", "synchronized", "(", "Servlets", ".", "class", ")", "{", "if", "(", "container", "!=", "null", ")", "{", "return", "container", ";", "}", "return", "container", "=", "ServletContainer", ".", "Factory", ".", "newInstance", "(", ")", ";", "}", "}" ]
Returns the default servlet container. For most embedded use cases this will be sufficient. @return The default servlet container
[ "Returns", "the", "default", "servlet", "container", ".", "For", "most", "embedded", "use", "cases", "this", "will", "be", "sufficient", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/Servlets.java#L54-L64
16,612
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/Servlets.java
Servlets.servlet
public static ServletInfo servlet(final String name, final Class<? extends Servlet> servletClass, final InstanceFactory<? extends Servlet> servlet) { return new ServletInfo(name, servletClass, servlet); }
java
public static ServletInfo servlet(final String name, final Class<? extends Servlet> servletClass, final InstanceFactory<? extends Servlet> servlet) { return new ServletInfo(name, servletClass, servlet); }
[ "public", "static", "ServletInfo", "servlet", "(", "final", "String", "name", ",", "final", "Class", "<", "?", "extends", "Servlet", ">", "servletClass", ",", "final", "InstanceFactory", "<", "?", "extends", "Servlet", ">", "servlet", ")", "{", "return", "new", "ServletInfo", "(", "name", ",", "servletClass", ",", "servlet", ")", ";", "}" ]
Creates a new servlet description with the given name and class @param name The servlet name @param servletClass The servlet class @return A new servlet description
[ "Creates", "a", "new", "servlet", "description", "with", "the", "given", "name", "and", "class" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/Servlets.java#L112-L114
16,613
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/Servlets.java
Servlets.filter
public static FilterInfo filter(final String name, final Class<? extends Filter> filterClass) { return new FilterInfo(name, filterClass); }
java
public static FilterInfo filter(final String name, final Class<? extends Filter> filterClass) { return new FilterInfo(name, filterClass); }
[ "public", "static", "FilterInfo", "filter", "(", "final", "String", "name", ",", "final", "Class", "<", "?", "extends", "Filter", ">", "filterClass", ")", "{", "return", "new", "FilterInfo", "(", "name", ",", "filterClass", ")", ";", "}" ]
Creates a new filter description with the given name and class @param name The filter name @param filterClass The filter class @return A new filter description
[ "Creates", "a", "new", "filter", "description", "with", "the", "given", "name", "and", "class" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/Servlets.java#L134-L136
16,614
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/Servlets.java
Servlets.multipartConfig
public static MultipartConfigElement multipartConfig(String location, long maxFileSize, long maxRequestSize, int fileSizeThreshold) { return new MultipartConfigElement(location, maxFileSize, maxRequestSize, fileSizeThreshold); }
java
public static MultipartConfigElement multipartConfig(String location, long maxFileSize, long maxRequestSize, int fileSizeThreshold) { return new MultipartConfigElement(location, maxFileSize, maxRequestSize, fileSizeThreshold); }
[ "public", "static", "MultipartConfigElement", "multipartConfig", "(", "String", "location", ",", "long", "maxFileSize", ",", "long", "maxRequestSize", ",", "int", "fileSizeThreshold", ")", "{", "return", "new", "MultipartConfigElement", "(", "location", ",", "maxFileSize", ",", "maxRequestSize", ",", "fileSizeThreshold", ")", ";", "}" ]
Creates a new multipart config element @param location the directory location where files will be stored @param maxFileSize the maximum size allowed for uploaded files @param maxRequestSize the maximum size allowed for multipart/form-data requests @param fileSizeThreshold the size threshold after which files will be written to disk
[ "Creates", "a", "new", "multipart", "config", "element" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/Servlets.java#L159-L161
16,615
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/Servlets.java
Servlets.errorPage
public static ErrorPage errorPage(String location, Class<? extends Throwable> exceptionType) { return new ErrorPage(location, exceptionType); }
java
public static ErrorPage errorPage(String location, Class<? extends Throwable> exceptionType) { return new ErrorPage(location, exceptionType); }
[ "public", "static", "ErrorPage", "errorPage", "(", "String", "location", ",", "Class", "<", "?", "extends", "Throwable", ">", "exceptionType", ")", "{", "return", "new", "ErrorPage", "(", "location", ",", "exceptionType", ")", ";", "}" ]
Create an ErrorPage instance for a given exception type @param location The location to redirect to @param exceptionType The exception type @return The error page definition
[ "Create", "an", "ErrorPage", "instance", "for", "a", "given", "exception", "type" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/Servlets.java#L204-L206
16,616
undertow-io/undertow
core/src/main/java/io/undertow/protocols/ssl/SslConduit.java
SslConduit.doWrap
private long doWrap(ByteBuffer[] userBuffers, int off, int len) throws IOException { if(anyAreSet(state, FLAG_CLOSED)) { throw new ClosedChannelException(); } if(outstandingTasks > 0) { return 0; } if(anyAreSet(state, FLAG_WRITE_REQUIRES_READ)) { doUnwrap(null, 0, 0); if(allAreClear(state, FLAG_READ_REQUIRES_WRITE)) { //unless a wrap is immediatly required we just return return 0; } } if(wrappedData != null) { int res = sink.write(wrappedData.getBuffer()); if(res == 0 || wrappedData.getBuffer().hasRemaining()) { return 0; } wrappedData.getBuffer().clear(); } else { wrappedData = bufferPool.allocate(); } try { SSLEngineResult result = null; while (result == null || (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP && result.getStatus() != SSLEngineResult.Status.BUFFER_OVERFLOW)) { if (userBuffers == null) { result = engine.wrap(EMPTY_BUFFER, wrappedData.getBuffer()); } else { result = engine.wrap(userBuffers, off, len, wrappedData.getBuffer()); } } wrappedData.getBuffer().flip(); if (result.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) { throw new IOException("underflow"); //todo: can this happen? } else if (result.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW) { if (!wrappedData.getBuffer().hasRemaining()) { //if an earlier wrap suceeded we ignore this throw new IOException("overflow"); //todo: handle properly } } //attempt to write it out, if we fail we just return //we ignore the handshake status, as wrap will get called again if (wrappedData.getBuffer().hasRemaining()) { sink.write(wrappedData.getBuffer()); } //if it was not a complete write we just return if (wrappedData.getBuffer().hasRemaining()) { return result.bytesConsumed(); } if (!handleHandshakeResult(result)) { return 0; } if (result.getStatus() == SSLEngineResult.Status.CLOSED && userBuffers != null) { notifyWriteClosed(); throw new ClosedChannelException(); } return result.bytesConsumed(); } catch (RuntimeException|IOException|Error e) { try { close(); } catch (Throwable ex) { UndertowLogger.REQUEST_LOGGER.debug("Exception closing SSLConduit after exception in doWrap()", ex); } throw e; } finally { //this can be cleared if the channel is fully closed if(wrappedData != null) { if (!wrappedData.getBuffer().hasRemaining()) { wrappedData.close(); wrappedData = null; } } } }
java
private long doWrap(ByteBuffer[] userBuffers, int off, int len) throws IOException { if(anyAreSet(state, FLAG_CLOSED)) { throw new ClosedChannelException(); } if(outstandingTasks > 0) { return 0; } if(anyAreSet(state, FLAG_WRITE_REQUIRES_READ)) { doUnwrap(null, 0, 0); if(allAreClear(state, FLAG_READ_REQUIRES_WRITE)) { //unless a wrap is immediatly required we just return return 0; } } if(wrappedData != null) { int res = sink.write(wrappedData.getBuffer()); if(res == 0 || wrappedData.getBuffer().hasRemaining()) { return 0; } wrappedData.getBuffer().clear(); } else { wrappedData = bufferPool.allocate(); } try { SSLEngineResult result = null; while (result == null || (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP && result.getStatus() != SSLEngineResult.Status.BUFFER_OVERFLOW)) { if (userBuffers == null) { result = engine.wrap(EMPTY_BUFFER, wrappedData.getBuffer()); } else { result = engine.wrap(userBuffers, off, len, wrappedData.getBuffer()); } } wrappedData.getBuffer().flip(); if (result.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) { throw new IOException("underflow"); //todo: can this happen? } else if (result.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW) { if (!wrappedData.getBuffer().hasRemaining()) { //if an earlier wrap suceeded we ignore this throw new IOException("overflow"); //todo: handle properly } } //attempt to write it out, if we fail we just return //we ignore the handshake status, as wrap will get called again if (wrappedData.getBuffer().hasRemaining()) { sink.write(wrappedData.getBuffer()); } //if it was not a complete write we just return if (wrappedData.getBuffer().hasRemaining()) { return result.bytesConsumed(); } if (!handleHandshakeResult(result)) { return 0; } if (result.getStatus() == SSLEngineResult.Status.CLOSED && userBuffers != null) { notifyWriteClosed(); throw new ClosedChannelException(); } return result.bytesConsumed(); } catch (RuntimeException|IOException|Error e) { try { close(); } catch (Throwable ex) { UndertowLogger.REQUEST_LOGGER.debug("Exception closing SSLConduit after exception in doWrap()", ex); } throw e; } finally { //this can be cleared if the channel is fully closed if(wrappedData != null) { if (!wrappedData.getBuffer().hasRemaining()) { wrappedData.close(); wrappedData = null; } } } }
[ "private", "long", "doWrap", "(", "ByteBuffer", "[", "]", "userBuffers", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "anyAreSet", "(", "state", ",", "FLAG_CLOSED", ")", ")", "{", "throw", "new", "ClosedChannelException", "(", ")", ";", "}", "if", "(", "outstandingTasks", ">", "0", ")", "{", "return", "0", ";", "}", "if", "(", "anyAreSet", "(", "state", ",", "FLAG_WRITE_REQUIRES_READ", ")", ")", "{", "doUnwrap", "(", "null", ",", "0", ",", "0", ")", ";", "if", "(", "allAreClear", "(", "state", ",", "FLAG_READ_REQUIRES_WRITE", ")", ")", "{", "//unless a wrap is immediatly required we just return", "return", "0", ";", "}", "}", "if", "(", "wrappedData", "!=", "null", ")", "{", "int", "res", "=", "sink", ".", "write", "(", "wrappedData", ".", "getBuffer", "(", ")", ")", ";", "if", "(", "res", "==", "0", "||", "wrappedData", ".", "getBuffer", "(", ")", ".", "hasRemaining", "(", ")", ")", "{", "return", "0", ";", "}", "wrappedData", ".", "getBuffer", "(", ")", ".", "clear", "(", ")", ";", "}", "else", "{", "wrappedData", "=", "bufferPool", ".", "allocate", "(", ")", ";", "}", "try", "{", "SSLEngineResult", "result", "=", "null", ";", "while", "(", "result", "==", "null", "||", "(", "result", ".", "getHandshakeStatus", "(", ")", "==", "SSLEngineResult", ".", "HandshakeStatus", ".", "NEED_WRAP", "&&", "result", ".", "getStatus", "(", ")", "!=", "SSLEngineResult", ".", "Status", ".", "BUFFER_OVERFLOW", ")", ")", "{", "if", "(", "userBuffers", "==", "null", ")", "{", "result", "=", "engine", ".", "wrap", "(", "EMPTY_BUFFER", ",", "wrappedData", ".", "getBuffer", "(", ")", ")", ";", "}", "else", "{", "result", "=", "engine", ".", "wrap", "(", "userBuffers", ",", "off", ",", "len", ",", "wrappedData", ".", "getBuffer", "(", ")", ")", ";", "}", "}", "wrappedData", ".", "getBuffer", "(", ")", ".", "flip", "(", ")", ";", "if", "(", "result", ".", "getStatus", "(", ")", "==", "SSLEngineResult", ".", "Status", ".", "BUFFER_UNDERFLOW", ")", "{", "throw", "new", "IOException", "(", "\"underflow\"", ")", ";", "//todo: can this happen?", "}", "else", "if", "(", "result", ".", "getStatus", "(", ")", "==", "SSLEngineResult", ".", "Status", ".", "BUFFER_OVERFLOW", ")", "{", "if", "(", "!", "wrappedData", ".", "getBuffer", "(", ")", ".", "hasRemaining", "(", ")", ")", "{", "//if an earlier wrap suceeded we ignore this", "throw", "new", "IOException", "(", "\"overflow\"", ")", ";", "//todo: handle properly", "}", "}", "//attempt to write it out, if we fail we just return", "//we ignore the handshake status, as wrap will get called again", "if", "(", "wrappedData", ".", "getBuffer", "(", ")", ".", "hasRemaining", "(", ")", ")", "{", "sink", ".", "write", "(", "wrappedData", ".", "getBuffer", "(", ")", ")", ";", "}", "//if it was not a complete write we just return", "if", "(", "wrappedData", ".", "getBuffer", "(", ")", ".", "hasRemaining", "(", ")", ")", "{", "return", "result", ".", "bytesConsumed", "(", ")", ";", "}", "if", "(", "!", "handleHandshakeResult", "(", "result", ")", ")", "{", "return", "0", ";", "}", "if", "(", "result", ".", "getStatus", "(", ")", "==", "SSLEngineResult", ".", "Status", ".", "CLOSED", "&&", "userBuffers", "!=", "null", ")", "{", "notifyWriteClosed", "(", ")", ";", "throw", "new", "ClosedChannelException", "(", ")", ";", "}", "return", "result", ".", "bytesConsumed", "(", ")", ";", "}", "catch", "(", "RuntimeException", "|", "IOException", "|", "Error", "e", ")", "{", "try", "{", "close", "(", ")", ";", "}", "catch", "(", "Throwable", "ex", ")", "{", "UndertowLogger", ".", "REQUEST_LOGGER", ".", "debug", "(", "\"Exception closing SSLConduit after exception in doWrap()\"", ",", "ex", ")", ";", "}", "throw", "e", ";", "}", "finally", "{", "//this can be cleared if the channel is fully closed", "if", "(", "wrappedData", "!=", "null", ")", "{", "if", "(", "!", "wrappedData", ".", "getBuffer", "(", ")", ".", "hasRemaining", "(", ")", ")", "{", "wrappedData", ".", "close", "(", ")", ";", "wrappedData", "=", "null", ";", "}", "}", "}", "}" ]
Wraps the user data and attempts to send it to the remote client. If data has already been buffered then this is attempted to be sent first. If the supplied buffers are null then a wrap operation is still attempted, which will happen during the handshaking process. @param userBuffers The buffers @param off The offset @param len The length @return The amount of data consumed @throws IOException
[ "Wraps", "the", "user", "data", "and", "attempts", "to", "send", "it", "to", "the", "remote", "client", ".", "If", "data", "has", "already", "been", "buffered", "then", "this", "is", "attempted", "to", "be", "sent", "first", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/ssl/SslConduit.java#L874-L949
16,617
undertow-io/undertow
core/src/main/java/io/undertow/protocols/ssl/SslConduit.java
SslConduit.runTasks
private void runTasks() { //don't run anything in the IO thread till the tasks are done delegate.getSinkChannel().suspendWrites(); delegate.getSourceChannel().suspendReads(); List<Runnable> tasks = new ArrayList<>(); Runnable t = engine.getDelegatedTask(); while (t != null) { tasks.add(t); t = engine.getDelegatedTask(); } synchronized (this) { outstandingTasks += tasks.size(); for (final Runnable task : tasks) { getWorker().execute(new Runnable() { @Override public void run() { try { task.run(); } finally { synchronized (SslConduit.this) { if (outstandingTasks == 1) { getWriteThread().execute(new Runnable() { @Override public void run() { synchronized (SslConduit.this) { SslConduit.this.notifyAll(); --outstandingTasks; try { doHandshake(); } catch (IOException | RuntimeException | Error e) { IoUtils.safeClose(connection); } if (anyAreSet(state, FLAG_READS_RESUMED)) { wakeupReads(); //wakeup, because we need to run an unwrap even if there is no data to be read } if (anyAreSet(state, FLAG_WRITES_RESUMED)) { resumeWrites(); //we don't need to wakeup, as the channel should be writable } } } }); } else { outstandingTasks--; } } } } }); } } }
java
private void runTasks() { //don't run anything in the IO thread till the tasks are done delegate.getSinkChannel().suspendWrites(); delegate.getSourceChannel().suspendReads(); List<Runnable> tasks = new ArrayList<>(); Runnable t = engine.getDelegatedTask(); while (t != null) { tasks.add(t); t = engine.getDelegatedTask(); } synchronized (this) { outstandingTasks += tasks.size(); for (final Runnable task : tasks) { getWorker().execute(new Runnable() { @Override public void run() { try { task.run(); } finally { synchronized (SslConduit.this) { if (outstandingTasks == 1) { getWriteThread().execute(new Runnable() { @Override public void run() { synchronized (SslConduit.this) { SslConduit.this.notifyAll(); --outstandingTasks; try { doHandshake(); } catch (IOException | RuntimeException | Error e) { IoUtils.safeClose(connection); } if (anyAreSet(state, FLAG_READS_RESUMED)) { wakeupReads(); //wakeup, because we need to run an unwrap even if there is no data to be read } if (anyAreSet(state, FLAG_WRITES_RESUMED)) { resumeWrites(); //we don't need to wakeup, as the channel should be writable } } } }); } else { outstandingTasks--; } } } } }); } } }
[ "private", "void", "runTasks", "(", ")", "{", "//don't run anything in the IO thread till the tasks are done", "delegate", ".", "getSinkChannel", "(", ")", ".", "suspendWrites", "(", ")", ";", "delegate", ".", "getSourceChannel", "(", ")", ".", "suspendReads", "(", ")", ";", "List", "<", "Runnable", ">", "tasks", "=", "new", "ArrayList", "<>", "(", ")", ";", "Runnable", "t", "=", "engine", ".", "getDelegatedTask", "(", ")", ";", "while", "(", "t", "!=", "null", ")", "{", "tasks", ".", "add", "(", "t", ")", ";", "t", "=", "engine", ".", "getDelegatedTask", "(", ")", ";", "}", "synchronized", "(", "this", ")", "{", "outstandingTasks", "+=", "tasks", ".", "size", "(", ")", ";", "for", "(", "final", "Runnable", "task", ":", "tasks", ")", "{", "getWorker", "(", ")", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "task", ".", "run", "(", ")", ";", "}", "finally", "{", "synchronized", "(", "SslConduit", ".", "this", ")", "{", "if", "(", "outstandingTasks", "==", "1", ")", "{", "getWriteThread", "(", ")", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "synchronized", "(", "SslConduit", ".", "this", ")", "{", "SslConduit", ".", "this", ".", "notifyAll", "(", ")", ";", "--", "outstandingTasks", ";", "try", "{", "doHandshake", "(", ")", ";", "}", "catch", "(", "IOException", "|", "RuntimeException", "|", "Error", "e", ")", "{", "IoUtils", ".", "safeClose", "(", "connection", ")", ";", "}", "if", "(", "anyAreSet", "(", "state", ",", "FLAG_READS_RESUMED", ")", ")", "{", "wakeupReads", "(", ")", ";", "//wakeup, because we need to run an unwrap even if there is no data to be read", "}", "if", "(", "anyAreSet", "(", "state", ",", "FLAG_WRITES_RESUMED", ")", ")", "{", "resumeWrites", "(", ")", ";", "//we don't need to wakeup, as the channel should be writable", "}", "}", "}", "}", ")", ";", "}", "else", "{", "outstandingTasks", "--", ";", "}", "}", "}", "}", "}", ")", ";", "}", "}", "}" ]
Execute all the tasks in the worker Once they are complete we notify any waiting threads and wakeup reads/writes as appropriate
[ "Execute", "all", "the", "tasks", "in", "the", "worker" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/ssl/SslConduit.java#L1054-L1107
16,618
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/RequestLimit.java
RequestLimit.setMaximumConcurrentRequests
public int setMaximumConcurrentRequests(int newMax) { if (newMax < 1) { throw new IllegalArgumentException("Maximum concurrent requests must be at least 1"); } int oldMax = this.max; this.max = newMax; if(newMax > oldMax) { synchronized (this) { while (!queue.isEmpty()) { int oldVal, newVal; do { oldVal = requests; if (oldVal >= max) { return oldMax; } newVal = oldVal + 1; } while (!requestsUpdater.compareAndSet(this, oldVal, newVal)); SuspendedRequest res = queue.poll(); res.exchange.dispatch(res.next); } } } return oldMax; }
java
public int setMaximumConcurrentRequests(int newMax) { if (newMax < 1) { throw new IllegalArgumentException("Maximum concurrent requests must be at least 1"); } int oldMax = this.max; this.max = newMax; if(newMax > oldMax) { synchronized (this) { while (!queue.isEmpty()) { int oldVal, newVal; do { oldVal = requests; if (oldVal >= max) { return oldMax; } newVal = oldVal + 1; } while (!requestsUpdater.compareAndSet(this, oldVal, newVal)); SuspendedRequest res = queue.poll(); res.exchange.dispatch(res.next); } } } return oldMax; }
[ "public", "int", "setMaximumConcurrentRequests", "(", "int", "newMax", ")", "{", "if", "(", "newMax", "<", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Maximum concurrent requests must be at least 1\"", ")", ";", "}", "int", "oldMax", "=", "this", ".", "max", ";", "this", ".", "max", "=", "newMax", ";", "if", "(", "newMax", ">", "oldMax", ")", "{", "synchronized", "(", "this", ")", "{", "while", "(", "!", "queue", ".", "isEmpty", "(", ")", ")", "{", "int", "oldVal", ",", "newVal", ";", "do", "{", "oldVal", "=", "requests", ";", "if", "(", "oldVal", ">=", "max", ")", "{", "return", "oldMax", ";", "}", "newVal", "=", "oldVal", "+", "1", ";", "}", "while", "(", "!", "requestsUpdater", ".", "compareAndSet", "(", "this", ",", "oldVal", ",", "newVal", ")", ")", ";", "SuspendedRequest", "res", "=", "queue", ".", "poll", "(", ")", ";", "res", ".", "exchange", ".", "dispatch", "(", "res", ".", "next", ")", ";", "}", "}", "}", "return", "oldMax", ";", "}" ]
Set the maximum concurrent requests. The value must be greater than or equal to one. @param newMax the maximum concurrent requests
[ "Set", "the", "maximum", "concurrent", "requests", ".", "The", "value", "must", "be", "greater", "than", "or", "equal", "to", "one", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/RequestLimit.java#L156-L179
16,619
undertow-io/undertow
core/src/main/java/io/undertow/util/PortableConcurrentDirectDeque.java
PortableConcurrentDirectDeque.toArrayList
private ArrayList<E> toArrayList() { ArrayList<E> list = new ArrayList<>(); for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null) list.add(item); } return list; }
java
private ArrayList<E> toArrayList() { ArrayList<E> list = new ArrayList<>(); for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null) list.add(item); } return list; }
[ "private", "ArrayList", "<", "E", ">", "toArrayList", "(", ")", "{", "ArrayList", "<", "E", ">", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Node", "<", "E", ">", "p", "=", "first", "(", ")", ";", "p", "!=", "null", ";", "p", "=", "succ", "(", "p", ")", ")", "{", "E", "item", "=", "p", ".", "item", ";", "if", "(", "item", "!=", "null", ")", "list", ".", "add", "(", "item", ")", ";", "}", "return", "list", ";", "}" ]
Creates an array list and fills it with elements of this list. Used by toArray. @return the arrayList
[ "Creates", "an", "array", "list", "and", "fills", "it", "with", "elements", "of", "this", "list", ".", "Used", "by", "toArray", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/PortableConcurrentDirectDeque.java#L800-L808
16,620
undertow-io/undertow
core/src/main/java/io/undertow/websockets/WebSocketExtension.java
WebSocketExtension.toExtensionHeader
public static String toExtensionHeader(final List<WebSocketExtension> extensions) { StringBuilder extensionsHeader = new StringBuilder(); if (extensions != null && extensions.size() > 0) { Iterator<WebSocketExtension> it = extensions.iterator(); while (it.hasNext()) { WebSocketExtension extension = it.next(); extensionsHeader.append(extension.getName()); for (Parameter param : extension.getParameters()) { extensionsHeader.append("; ").append(param.getName()); if (param.getValue() != null && param.getValue().length() > 0) { extensionsHeader.append("=").append(param.getValue()); } } if (it.hasNext()) { extensionsHeader.append(", "); } } } return extensionsHeader.toString(); }
java
public static String toExtensionHeader(final List<WebSocketExtension> extensions) { StringBuilder extensionsHeader = new StringBuilder(); if (extensions != null && extensions.size() > 0) { Iterator<WebSocketExtension> it = extensions.iterator(); while (it.hasNext()) { WebSocketExtension extension = it.next(); extensionsHeader.append(extension.getName()); for (Parameter param : extension.getParameters()) { extensionsHeader.append("; ").append(param.getName()); if (param.getValue() != null && param.getValue().length() > 0) { extensionsHeader.append("=").append(param.getValue()); } } if (it.hasNext()) { extensionsHeader.append(", "); } } } return extensionsHeader.toString(); }
[ "public", "static", "String", "toExtensionHeader", "(", "final", "List", "<", "WebSocketExtension", ">", "extensions", ")", "{", "StringBuilder", "extensionsHeader", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "extensions", "!=", "null", "&&", "extensions", ".", "size", "(", ")", ">", "0", ")", "{", "Iterator", "<", "WebSocketExtension", ">", "it", "=", "extensions", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "WebSocketExtension", "extension", "=", "it", ".", "next", "(", ")", ";", "extensionsHeader", ".", "append", "(", "extension", ".", "getName", "(", ")", ")", ";", "for", "(", "Parameter", "param", ":", "extension", ".", "getParameters", "(", ")", ")", "{", "extensionsHeader", ".", "append", "(", "\"; \"", ")", ".", "append", "(", "param", ".", "getName", "(", ")", ")", ";", "if", "(", "param", ".", "getValue", "(", ")", "!=", "null", "&&", "param", ".", "getValue", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "extensionsHeader", ".", "append", "(", "\"=\"", ")", ".", "append", "(", "param", ".", "getValue", "(", ")", ")", ";", "}", "}", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "extensionsHeader", ".", "append", "(", "\", \"", ")", ";", "}", "}", "}", "return", "extensionsHeader", ".", "toString", "(", ")", ";", "}" ]
Compose a String from a list of extensions to be used in the response of a protocol negotiation. @see io.undertow.util.Headers @param extensions list of {@link WebSocketExtension} @return a string representation of the extensions
[ "Compose", "a", "String", "from", "a", "list", "of", "extensions", "to", "be", "used", "in", "the", "response", "of", "a", "protocol", "negotiation", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/WebSocketExtension.java#L124-L143
16,621
undertow-io/undertow
core/src/main/java/io/undertow/server/AbstractServerConnection.java
AbstractServerConnection.restoreChannel
public void restoreChannel(final ConduitState state) { channel.getSinkChannel().setConduit(state.sink); channel.getSourceChannel().setConduit(state.source); }
java
public void restoreChannel(final ConduitState state) { channel.getSinkChannel().setConduit(state.sink); channel.getSourceChannel().setConduit(state.source); }
[ "public", "void", "restoreChannel", "(", "final", "ConduitState", "state", ")", "{", "channel", ".", "getSinkChannel", "(", ")", ".", "setConduit", "(", "state", ".", "sink", ")", ";", "channel", ".", "getSourceChannel", "(", ")", ".", "setConduit", "(", "state", ".", "source", ")", ";", "}" ]
Restores the channel conduits to a previous state. @param state The original state @see #resetChannel()
[ "Restores", "the", "channel", "conduits", "to", "a", "previous", "state", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/AbstractServerConnection.java#L250-L253
16,622
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.handleRequest
protected void handleRequest(final HttpString method, HttpServerExchange exchange) throws Exception { final RequestData requestData = parseFormData(exchange); boolean persistent = exchange.isPersistent(); exchange.setPersistent(false); //UNDERTOW-947 MCMP should not use persistent connections if (CONFIG.equals(method)) { processConfig(exchange, requestData); } else if (ENABLE_APP.equals(method)) { processCommand(exchange, requestData, MCMPAction.ENABLE); } else if (DISABLE_APP.equals(method)) { processCommand(exchange, requestData, MCMPAction.DISABLE); } else if (STOP_APP.equals(method)) { processCommand(exchange, requestData, MCMPAction.STOP); } else if (REMOVE_APP.equals(method)) { processCommand(exchange, requestData, MCMPAction.REMOVE); } else if (STATUS.equals(method)) { processStatus(exchange, requestData); } else if (INFO.equals(method)) { processInfo(exchange); } else if (DUMP.equals(method)) { processDump(exchange); } else if (PING.equals(method)) { processPing(exchange, requestData); } else { exchange.setPersistent(persistent); next.handleRequest(exchange); } }
java
protected void handleRequest(final HttpString method, HttpServerExchange exchange) throws Exception { final RequestData requestData = parseFormData(exchange); boolean persistent = exchange.isPersistent(); exchange.setPersistent(false); //UNDERTOW-947 MCMP should not use persistent connections if (CONFIG.equals(method)) { processConfig(exchange, requestData); } else if (ENABLE_APP.equals(method)) { processCommand(exchange, requestData, MCMPAction.ENABLE); } else if (DISABLE_APP.equals(method)) { processCommand(exchange, requestData, MCMPAction.DISABLE); } else if (STOP_APP.equals(method)) { processCommand(exchange, requestData, MCMPAction.STOP); } else if (REMOVE_APP.equals(method)) { processCommand(exchange, requestData, MCMPAction.REMOVE); } else if (STATUS.equals(method)) { processStatus(exchange, requestData); } else if (INFO.equals(method)) { processInfo(exchange); } else if (DUMP.equals(method)) { processDump(exchange); } else if (PING.equals(method)) { processPing(exchange, requestData); } else { exchange.setPersistent(persistent); next.handleRequest(exchange); } }
[ "protected", "void", "handleRequest", "(", "final", "HttpString", "method", ",", "HttpServerExchange", "exchange", ")", "throws", "Exception", "{", "final", "RequestData", "requestData", "=", "parseFormData", "(", "exchange", ")", ";", "boolean", "persistent", "=", "exchange", ".", "isPersistent", "(", ")", ";", "exchange", ".", "setPersistent", "(", "false", ")", ";", "//UNDERTOW-947 MCMP should not use persistent connections", "if", "(", "CONFIG", ".", "equals", "(", "method", ")", ")", "{", "processConfig", "(", "exchange", ",", "requestData", ")", ";", "}", "else", "if", "(", "ENABLE_APP", ".", "equals", "(", "method", ")", ")", "{", "processCommand", "(", "exchange", ",", "requestData", ",", "MCMPAction", ".", "ENABLE", ")", ";", "}", "else", "if", "(", "DISABLE_APP", ".", "equals", "(", "method", ")", ")", "{", "processCommand", "(", "exchange", ",", "requestData", ",", "MCMPAction", ".", "DISABLE", ")", ";", "}", "else", "if", "(", "STOP_APP", ".", "equals", "(", "method", ")", ")", "{", "processCommand", "(", "exchange", ",", "requestData", ",", "MCMPAction", ".", "STOP", ")", ";", "}", "else", "if", "(", "REMOVE_APP", ".", "equals", "(", "method", ")", ")", "{", "processCommand", "(", "exchange", ",", "requestData", ",", "MCMPAction", ".", "REMOVE", ")", ";", "}", "else", "if", "(", "STATUS", ".", "equals", "(", "method", ")", ")", "{", "processStatus", "(", "exchange", ",", "requestData", ")", ";", "}", "else", "if", "(", "INFO", ".", "equals", "(", "method", ")", ")", "{", "processInfo", "(", "exchange", ")", ";", "}", "else", "if", "(", "DUMP", ".", "equals", "(", "method", ")", ")", "{", "processDump", "(", "exchange", ")", ";", "}", "else", "if", "(", "PING", ".", "equals", "(", "method", ")", ")", "{", "processPing", "(", "exchange", ",", "requestData", ")", ";", "}", "else", "{", "exchange", ".", "setPersistent", "(", "persistent", ")", ";", "next", ".", "handleRequest", "(", "exchange", ")", ";", "}", "}" ]
Handle a management+ request. @param method the http method @param exchange the http server exchange @throws Exception
[ "Handle", "a", "management", "+", "request", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L182-L208
16,623
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.processCommand
void processCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException { if (exchange.getRequestPath().equals("*") || exchange.getRequestPath().endsWith("/*")) { processNodeCommand(exchange, requestData, action); } else { processAppCommand(exchange, requestData, action); } }
java
void processCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException { if (exchange.getRequestPath().equals("*") || exchange.getRequestPath().endsWith("/*")) { processNodeCommand(exchange, requestData, action); } else { processAppCommand(exchange, requestData, action); } }
[ "void", "processCommand", "(", "final", "HttpServerExchange", "exchange", ",", "final", "RequestData", "requestData", ",", "final", "MCMPAction", "action", ")", "throws", "IOException", "{", "if", "(", "exchange", ".", "getRequestPath", "(", ")", ".", "equals", "(", "\"*\"", ")", "||", "exchange", ".", "getRequestPath", "(", ")", ".", "endsWith", "(", "\"/*\"", ")", ")", "{", "processNodeCommand", "(", "exchange", ",", "requestData", ",", "action", ")", ";", "}", "else", "{", "processAppCommand", "(", "exchange", ",", "requestData", ",", "action", ")", ";", "}", "}" ]
Process a mod_cluster mgmt command. @param exchange the http server exchange @param requestData the request data @param action the mgmt action @throws IOException
[ "Process", "a", "mod_cluster", "mgmt", "command", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L325-L331
16,624
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.processNodeCommand
void processNodeCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException { final String jvmRoute = requestData.getFirst(JVMROUTE); if (jvmRoute == null) { processError(TYPESYNTAX, SMISFLD, exchange); return; } if (processNodeCommand(jvmRoute, action)) { processOK(exchange); } else { processError(MCMPErrorCode.CANT_UPDATE_NODE, exchange); } }
java
void processNodeCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException { final String jvmRoute = requestData.getFirst(JVMROUTE); if (jvmRoute == null) { processError(TYPESYNTAX, SMISFLD, exchange); return; } if (processNodeCommand(jvmRoute, action)) { processOK(exchange); } else { processError(MCMPErrorCode.CANT_UPDATE_NODE, exchange); } }
[ "void", "processNodeCommand", "(", "final", "HttpServerExchange", "exchange", ",", "final", "RequestData", "requestData", ",", "final", "MCMPAction", "action", ")", "throws", "IOException", "{", "final", "String", "jvmRoute", "=", "requestData", ".", "getFirst", "(", "JVMROUTE", ")", ";", "if", "(", "jvmRoute", "==", "null", ")", "{", "processError", "(", "TYPESYNTAX", ",", "SMISFLD", ",", "exchange", ")", ";", "return", ";", "}", "if", "(", "processNodeCommand", "(", "jvmRoute", ",", "action", ")", ")", "{", "processOK", "(", "exchange", ")", ";", "}", "else", "{", "processError", "(", "MCMPErrorCode", ".", "CANT_UPDATE_NODE", ",", "exchange", ")", ";", "}", "}" ]
Process a mgmt command targeting a node. @param exchange the http server exchange @param requestData the request data @param action the mgmt action @throws IOException
[ "Process", "a", "mgmt", "command", "targeting", "a", "node", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L341-L352
16,625
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.processAppCommand
void processAppCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException { final String contextPath = requestData.getFirst(CONTEXT); final String jvmRoute = requestData.getFirst(JVMROUTE); final String aliases = requestData.getFirst(ALIAS); if (contextPath == null || jvmRoute == null || aliases == null) { processError(TYPESYNTAX, SMISFLD, exchange); return; } final List<String> virtualHosts = Arrays.asList(aliases.split(",")); if (virtualHosts == null || virtualHosts.isEmpty()) { processError(TYPESYNTAX, SCONBAD, exchange); return; } String response = null; switch (action) { case ENABLE: if (!container.enableContext(contextPath, jvmRoute, virtualHosts)) { processError(MCMPErrorCode.CANT_UPDATE_CONTEXT, exchange); return; } break; case DISABLE: if (!container.disableContext(contextPath, jvmRoute, virtualHosts)) { processError(MCMPErrorCode.CANT_UPDATE_CONTEXT, exchange); return; } break; case STOP: int i = container.stopContext(contextPath, jvmRoute, virtualHosts); final StringBuilder builder = new StringBuilder(); builder.append("Type=STOP-APP-RSP,JvmRoute=").append(jvmRoute); builder.append("Alias=").append(aliases); builder.append("Context=").append(contextPath); builder.append("Requests=").append(i); response = builder.toString(); break; case REMOVE: if (!container.removeContext(contextPath, jvmRoute, virtualHosts)) { processError(MCMPErrorCode.CANT_UPDATE_CONTEXT, exchange); return; } break; default: { processError(TYPESYNTAX, SMISFLD, exchange); return; } } if (response != null) { sendResponse(exchange, response); } else { processOK(exchange); } }
java
void processAppCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException { final String contextPath = requestData.getFirst(CONTEXT); final String jvmRoute = requestData.getFirst(JVMROUTE); final String aliases = requestData.getFirst(ALIAS); if (contextPath == null || jvmRoute == null || aliases == null) { processError(TYPESYNTAX, SMISFLD, exchange); return; } final List<String> virtualHosts = Arrays.asList(aliases.split(",")); if (virtualHosts == null || virtualHosts.isEmpty()) { processError(TYPESYNTAX, SCONBAD, exchange); return; } String response = null; switch (action) { case ENABLE: if (!container.enableContext(contextPath, jvmRoute, virtualHosts)) { processError(MCMPErrorCode.CANT_UPDATE_CONTEXT, exchange); return; } break; case DISABLE: if (!container.disableContext(contextPath, jvmRoute, virtualHosts)) { processError(MCMPErrorCode.CANT_UPDATE_CONTEXT, exchange); return; } break; case STOP: int i = container.stopContext(contextPath, jvmRoute, virtualHosts); final StringBuilder builder = new StringBuilder(); builder.append("Type=STOP-APP-RSP,JvmRoute=").append(jvmRoute); builder.append("Alias=").append(aliases); builder.append("Context=").append(contextPath); builder.append("Requests=").append(i); response = builder.toString(); break; case REMOVE: if (!container.removeContext(contextPath, jvmRoute, virtualHosts)) { processError(MCMPErrorCode.CANT_UPDATE_CONTEXT, exchange); return; } break; default: { processError(TYPESYNTAX, SMISFLD, exchange); return; } } if (response != null) { sendResponse(exchange, response); } else { processOK(exchange); } }
[ "void", "processAppCommand", "(", "final", "HttpServerExchange", "exchange", ",", "final", "RequestData", "requestData", ",", "final", "MCMPAction", "action", ")", "throws", "IOException", "{", "final", "String", "contextPath", "=", "requestData", ".", "getFirst", "(", "CONTEXT", ")", ";", "final", "String", "jvmRoute", "=", "requestData", ".", "getFirst", "(", "JVMROUTE", ")", ";", "final", "String", "aliases", "=", "requestData", ".", "getFirst", "(", "ALIAS", ")", ";", "if", "(", "contextPath", "==", "null", "||", "jvmRoute", "==", "null", "||", "aliases", "==", "null", ")", "{", "processError", "(", "TYPESYNTAX", ",", "SMISFLD", ",", "exchange", ")", ";", "return", ";", "}", "final", "List", "<", "String", ">", "virtualHosts", "=", "Arrays", ".", "asList", "(", "aliases", ".", "split", "(", "\",\"", ")", ")", ";", "if", "(", "virtualHosts", "==", "null", "||", "virtualHosts", ".", "isEmpty", "(", ")", ")", "{", "processError", "(", "TYPESYNTAX", ",", "SCONBAD", ",", "exchange", ")", ";", "return", ";", "}", "String", "response", "=", "null", ";", "switch", "(", "action", ")", "{", "case", "ENABLE", ":", "if", "(", "!", "container", ".", "enableContext", "(", "contextPath", ",", "jvmRoute", ",", "virtualHosts", ")", ")", "{", "processError", "(", "MCMPErrorCode", ".", "CANT_UPDATE_CONTEXT", ",", "exchange", ")", ";", "return", ";", "}", "break", ";", "case", "DISABLE", ":", "if", "(", "!", "container", ".", "disableContext", "(", "contextPath", ",", "jvmRoute", ",", "virtualHosts", ")", ")", "{", "processError", "(", "MCMPErrorCode", ".", "CANT_UPDATE_CONTEXT", ",", "exchange", ")", ";", "return", ";", "}", "break", ";", "case", "STOP", ":", "int", "i", "=", "container", ".", "stopContext", "(", "contextPath", ",", "jvmRoute", ",", "virtualHosts", ")", ";", "final", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "\"Type=STOP-APP-RSP,JvmRoute=\"", ")", ".", "append", "(", "jvmRoute", ")", ";", "builder", ".", "append", "(", "\"Alias=\"", ")", ".", "append", "(", "aliases", ")", ";", "builder", ".", "append", "(", "\"Context=\"", ")", ".", "append", "(", "contextPath", ")", ";", "builder", ".", "append", "(", "\"Requests=\"", ")", ".", "append", "(", "i", ")", ";", "response", "=", "builder", ".", "toString", "(", ")", ";", "break", ";", "case", "REMOVE", ":", "if", "(", "!", "container", ".", "removeContext", "(", "contextPath", ",", "jvmRoute", ",", "virtualHosts", ")", ")", "{", "processError", "(", "MCMPErrorCode", ".", "CANT_UPDATE_CONTEXT", ",", "exchange", ")", ";", "return", ";", "}", "break", ";", "default", ":", "{", "processError", "(", "TYPESYNTAX", ",", "SMISFLD", ",", "exchange", ")", ";", "return", ";", "}", "}", "if", "(", "response", "!=", "null", ")", "{", "sendResponse", "(", "exchange", ",", "response", ")", ";", "}", "else", "{", "processOK", "(", "exchange", ")", ";", "}", "}" ]
Process a command targeting an application. @param exchange the http server exchange @param requestData the request data @param action the mgmt action @return @throws IOException
[ "Process", "a", "command", "targeting", "an", "application", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L377-L432
16,626
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.processStatus
void processStatus(final HttpServerExchange exchange, final RequestData requestData) throws IOException { final String jvmRoute = requestData.getFirst(JVMROUTE); final String loadValue = requestData.getFirst(LOAD); if (loadValue == null || jvmRoute == null) { processError(TYPESYNTAX, SMISFLD, exchange); return; } UndertowLogger.ROOT_LOGGER.receivedNodeLoad(jvmRoute, loadValue); final int load = Integer.parseInt(loadValue); if (load > 0 || load == -2) { final Node node = container.getNode(jvmRoute); if (node == null) { processError(MCMPErrorCode.CANT_READ_NODE, exchange); return; } final NodePingUtil.PingCallback callback = new NodePingUtil.PingCallback() { @Override public void completed() { final String response = "Type=STATUS-RSP&State=OK&JVMRoute=" + jvmRoute + "&id=" + creationTime; try { if (load > 0) { node.updateLoad(load); } sendResponse(exchange, response); } catch (Exception e) { UndertowLogger.ROOT_LOGGER.failedToSendPingResponse(e); } } @Override public void failed() { final String response = "Type=STATUS-RSP&State=NOTOK&JVMRoute=" + jvmRoute + "&id=" + creationTime; try { node.markInError(); sendResponse(exchange, response); } catch (Exception e) { UndertowLogger.ROOT_LOGGER.failedToSendPingResponseDBG(e, node.getJvmRoute(), jvmRoute); } } }; // Ping the node node.ping(exchange, callback); } else if (load == 0) { final Node node = container.getNode(jvmRoute); if (node != null) { node.hotStandby(); sendResponse(exchange, "Type=STATUS-RSP&State=OK&JVMRoute=" + jvmRoute + "&id=" + creationTime); } else { processError(MCMPErrorCode.CANT_READ_NODE, exchange); } } else if (load == -1) { // Error, disable node final Node node = container.getNode(jvmRoute); if (node != null) { node.markInError(); sendResponse(exchange, "Type=STATUS-RSP&State=NOTOK&JVMRoute=" + jvmRoute + "&id=" + creationTime); } else { processError(MCMPErrorCode.CANT_READ_NODE, exchange); } } else { processError(TYPESYNTAX, SMISFLD, exchange); } }
java
void processStatus(final HttpServerExchange exchange, final RequestData requestData) throws IOException { final String jvmRoute = requestData.getFirst(JVMROUTE); final String loadValue = requestData.getFirst(LOAD); if (loadValue == null || jvmRoute == null) { processError(TYPESYNTAX, SMISFLD, exchange); return; } UndertowLogger.ROOT_LOGGER.receivedNodeLoad(jvmRoute, loadValue); final int load = Integer.parseInt(loadValue); if (load > 0 || load == -2) { final Node node = container.getNode(jvmRoute); if (node == null) { processError(MCMPErrorCode.CANT_READ_NODE, exchange); return; } final NodePingUtil.PingCallback callback = new NodePingUtil.PingCallback() { @Override public void completed() { final String response = "Type=STATUS-RSP&State=OK&JVMRoute=" + jvmRoute + "&id=" + creationTime; try { if (load > 0) { node.updateLoad(load); } sendResponse(exchange, response); } catch (Exception e) { UndertowLogger.ROOT_LOGGER.failedToSendPingResponse(e); } } @Override public void failed() { final String response = "Type=STATUS-RSP&State=NOTOK&JVMRoute=" + jvmRoute + "&id=" + creationTime; try { node.markInError(); sendResponse(exchange, response); } catch (Exception e) { UndertowLogger.ROOT_LOGGER.failedToSendPingResponseDBG(e, node.getJvmRoute(), jvmRoute); } } }; // Ping the node node.ping(exchange, callback); } else if (load == 0) { final Node node = container.getNode(jvmRoute); if (node != null) { node.hotStandby(); sendResponse(exchange, "Type=STATUS-RSP&State=OK&JVMRoute=" + jvmRoute + "&id=" + creationTime); } else { processError(MCMPErrorCode.CANT_READ_NODE, exchange); } } else if (load == -1) { // Error, disable node final Node node = container.getNode(jvmRoute); if (node != null) { node.markInError(); sendResponse(exchange, "Type=STATUS-RSP&State=NOTOK&JVMRoute=" + jvmRoute + "&id=" + creationTime); } else { processError(MCMPErrorCode.CANT_READ_NODE, exchange); } } else { processError(TYPESYNTAX, SMISFLD, exchange); } }
[ "void", "processStatus", "(", "final", "HttpServerExchange", "exchange", ",", "final", "RequestData", "requestData", ")", "throws", "IOException", "{", "final", "String", "jvmRoute", "=", "requestData", ".", "getFirst", "(", "JVMROUTE", ")", ";", "final", "String", "loadValue", "=", "requestData", ".", "getFirst", "(", "LOAD", ")", ";", "if", "(", "loadValue", "==", "null", "||", "jvmRoute", "==", "null", ")", "{", "processError", "(", "TYPESYNTAX", ",", "SMISFLD", ",", "exchange", ")", ";", "return", ";", "}", "UndertowLogger", ".", "ROOT_LOGGER", ".", "receivedNodeLoad", "(", "jvmRoute", ",", "loadValue", ")", ";", "final", "int", "load", "=", "Integer", ".", "parseInt", "(", "loadValue", ")", ";", "if", "(", "load", ">", "0", "||", "load", "==", "-", "2", ")", "{", "final", "Node", "node", "=", "container", ".", "getNode", "(", "jvmRoute", ")", ";", "if", "(", "node", "==", "null", ")", "{", "processError", "(", "MCMPErrorCode", ".", "CANT_READ_NODE", ",", "exchange", ")", ";", "return", ";", "}", "final", "NodePingUtil", ".", "PingCallback", "callback", "=", "new", "NodePingUtil", ".", "PingCallback", "(", ")", "{", "@", "Override", "public", "void", "completed", "(", ")", "{", "final", "String", "response", "=", "\"Type=STATUS-RSP&State=OK&JVMRoute=\"", "+", "jvmRoute", "+", "\"&id=\"", "+", "creationTime", ";", "try", "{", "if", "(", "load", ">", "0", ")", "{", "node", ".", "updateLoad", "(", "load", ")", ";", "}", "sendResponse", "(", "exchange", ",", "response", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "UndertowLogger", ".", "ROOT_LOGGER", ".", "failedToSendPingResponse", "(", "e", ")", ";", "}", "}", "@", "Override", "public", "void", "failed", "(", ")", "{", "final", "String", "response", "=", "\"Type=STATUS-RSP&State=NOTOK&JVMRoute=\"", "+", "jvmRoute", "+", "\"&id=\"", "+", "creationTime", ";", "try", "{", "node", ".", "markInError", "(", ")", ";", "sendResponse", "(", "exchange", ",", "response", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "UndertowLogger", ".", "ROOT_LOGGER", ".", "failedToSendPingResponseDBG", "(", "e", ",", "node", ".", "getJvmRoute", "(", ")", ",", "jvmRoute", ")", ";", "}", "}", "}", ";", "// Ping the node", "node", ".", "ping", "(", "exchange", ",", "callback", ")", ";", "}", "else", "if", "(", "load", "==", "0", ")", "{", "final", "Node", "node", "=", "container", ".", "getNode", "(", "jvmRoute", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "node", ".", "hotStandby", "(", ")", ";", "sendResponse", "(", "exchange", ",", "\"Type=STATUS-RSP&State=OK&JVMRoute=\"", "+", "jvmRoute", "+", "\"&id=\"", "+", "creationTime", ")", ";", "}", "else", "{", "processError", "(", "MCMPErrorCode", ".", "CANT_READ_NODE", ",", "exchange", ")", ";", "}", "}", "else", "if", "(", "load", "==", "-", "1", ")", "{", "// Error, disable node", "final", "Node", "node", "=", "container", ".", "getNode", "(", "jvmRoute", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "node", ".", "markInError", "(", ")", ";", "sendResponse", "(", "exchange", ",", "\"Type=STATUS-RSP&State=NOTOK&JVMRoute=\"", "+", "jvmRoute", "+", "\"&id=\"", "+", "creationTime", ")", ";", "}", "else", "{", "processError", "(", "MCMPErrorCode", ".", "CANT_READ_NODE", ",", "exchange", ")", ";", "}", "}", "else", "{", "processError", "(", "TYPESYNTAX", ",", "SMISFLD", ",", "exchange", ")", ";", "}", "}" ]
Process the status request. @param exchange the http server exchange @param requestData the request data @throws IOException
[ "Process", "the", "status", "request", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L441-L510
16,627
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.processPing
void processPing(final HttpServerExchange exchange, final RequestData requestData) throws IOException { final String jvmRoute = requestData.getFirst(JVMROUTE); final String scheme = requestData.getFirst(SCHEME); final String host = requestData.getFirst(HOST); final String port = requestData.getFirst(PORT); final String OK = "Type=PING-RSP&State=OK&id=" + creationTime; final String NOTOK = "Type=PING-RSP&State=NOTOK&id=" + creationTime; if (jvmRoute != null) { // ping the corresponding node. final Node nodeConfig = container.getNode(jvmRoute); if (nodeConfig == null) { sendResponse(exchange, NOTOK); return; } final NodePingUtil.PingCallback callback = new NodePingUtil.PingCallback() { @Override public void completed() { try { sendResponse(exchange, OK); } catch (Exception e) { e.printStackTrace(); } } @Override public void failed() { try { nodeConfig.markInError(); sendResponse(exchange, NOTOK); } catch (Exception e) { e.printStackTrace(); } } }; nodeConfig.ping(exchange, callback); } else { if (scheme == null && host == null && port == null) { sendResponse(exchange, OK); return; } else { if (host == null || port == null) { processError(TYPESYNTAX, SMISFLD, exchange); return; } // Check whether we can reach the host checkHostUp(scheme, host, Integer.parseInt(port), exchange, new NodePingUtil.PingCallback() { @Override public void completed() { sendResponse(exchange, OK); } @Override public void failed() { sendResponse(exchange, NOTOK); } }); return; } } }
java
void processPing(final HttpServerExchange exchange, final RequestData requestData) throws IOException { final String jvmRoute = requestData.getFirst(JVMROUTE); final String scheme = requestData.getFirst(SCHEME); final String host = requestData.getFirst(HOST); final String port = requestData.getFirst(PORT); final String OK = "Type=PING-RSP&State=OK&id=" + creationTime; final String NOTOK = "Type=PING-RSP&State=NOTOK&id=" + creationTime; if (jvmRoute != null) { // ping the corresponding node. final Node nodeConfig = container.getNode(jvmRoute); if (nodeConfig == null) { sendResponse(exchange, NOTOK); return; } final NodePingUtil.PingCallback callback = new NodePingUtil.PingCallback() { @Override public void completed() { try { sendResponse(exchange, OK); } catch (Exception e) { e.printStackTrace(); } } @Override public void failed() { try { nodeConfig.markInError(); sendResponse(exchange, NOTOK); } catch (Exception e) { e.printStackTrace(); } } }; nodeConfig.ping(exchange, callback); } else { if (scheme == null && host == null && port == null) { sendResponse(exchange, OK); return; } else { if (host == null || port == null) { processError(TYPESYNTAX, SMISFLD, exchange); return; } // Check whether we can reach the host checkHostUp(scheme, host, Integer.parseInt(port), exchange, new NodePingUtil.PingCallback() { @Override public void completed() { sendResponse(exchange, OK); } @Override public void failed() { sendResponse(exchange, NOTOK); } }); return; } } }
[ "void", "processPing", "(", "final", "HttpServerExchange", "exchange", ",", "final", "RequestData", "requestData", ")", "throws", "IOException", "{", "final", "String", "jvmRoute", "=", "requestData", ".", "getFirst", "(", "JVMROUTE", ")", ";", "final", "String", "scheme", "=", "requestData", ".", "getFirst", "(", "SCHEME", ")", ";", "final", "String", "host", "=", "requestData", ".", "getFirst", "(", "HOST", ")", ";", "final", "String", "port", "=", "requestData", ".", "getFirst", "(", "PORT", ")", ";", "final", "String", "OK", "=", "\"Type=PING-RSP&State=OK&id=\"", "+", "creationTime", ";", "final", "String", "NOTOK", "=", "\"Type=PING-RSP&State=NOTOK&id=\"", "+", "creationTime", ";", "if", "(", "jvmRoute", "!=", "null", ")", "{", "// ping the corresponding node.", "final", "Node", "nodeConfig", "=", "container", ".", "getNode", "(", "jvmRoute", ")", ";", "if", "(", "nodeConfig", "==", "null", ")", "{", "sendResponse", "(", "exchange", ",", "NOTOK", ")", ";", "return", ";", "}", "final", "NodePingUtil", ".", "PingCallback", "callback", "=", "new", "NodePingUtil", ".", "PingCallback", "(", ")", "{", "@", "Override", "public", "void", "completed", "(", ")", "{", "try", "{", "sendResponse", "(", "exchange", ",", "OK", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "@", "Override", "public", "void", "failed", "(", ")", "{", "try", "{", "nodeConfig", ".", "markInError", "(", ")", ";", "sendResponse", "(", "exchange", ",", "NOTOK", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", ";", "nodeConfig", ".", "ping", "(", "exchange", ",", "callback", ")", ";", "}", "else", "{", "if", "(", "scheme", "==", "null", "&&", "host", "==", "null", "&&", "port", "==", "null", ")", "{", "sendResponse", "(", "exchange", ",", "OK", ")", ";", "return", ";", "}", "else", "{", "if", "(", "host", "==", "null", "||", "port", "==", "null", ")", "{", "processError", "(", "TYPESYNTAX", ",", "SMISFLD", ",", "exchange", ")", ";", "return", ";", "}", "// Check whether we can reach the host", "checkHostUp", "(", "scheme", ",", "host", ",", "Integer", ".", "parseInt", "(", "port", ")", ",", "exchange", ",", "new", "NodePingUtil", ".", "PingCallback", "(", ")", "{", "@", "Override", "public", "void", "completed", "(", ")", "{", "sendResponse", "(", "exchange", ",", "OK", ")", ";", "}", "@", "Override", "public", "void", "failed", "(", ")", "{", "sendResponse", "(", "exchange", ",", "NOTOK", ")", ";", "}", "}", ")", ";", "return", ";", "}", "}", "}" ]
Process the ping request. @param exchange the http server exchange @param requestData the request data @throws IOException
[ "Process", "the", "ping", "request", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L519-L581
16,628
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.checkHostUp
protected void checkHostUp(final String scheme, final String host, final int port, final HttpServerExchange exchange, final NodePingUtil.PingCallback callback) { final XnioSsl xnioSsl = null; // TODO final OptionMap options = OptionMap.builder() .set(Options.TCP_NODELAY, true) .getMap(); try { // http, ajp and maybe more in future if ("ajp".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)) { final URI uri = new URI(scheme, null, host, port, "/", null, null); NodePingUtil.pingHttpClient(uri, callback, exchange, container.getClient(), xnioSsl, options); } else { final InetSocketAddress address = new InetSocketAddress(host, port); NodePingUtil.pingHost(address, exchange, callback, options); } } catch (URISyntaxException e) { callback.failed(); } }
java
protected void checkHostUp(final String scheme, final String host, final int port, final HttpServerExchange exchange, final NodePingUtil.PingCallback callback) { final XnioSsl xnioSsl = null; // TODO final OptionMap options = OptionMap.builder() .set(Options.TCP_NODELAY, true) .getMap(); try { // http, ajp and maybe more in future if ("ajp".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)) { final URI uri = new URI(scheme, null, host, port, "/", null, null); NodePingUtil.pingHttpClient(uri, callback, exchange, container.getClient(), xnioSsl, options); } else { final InetSocketAddress address = new InetSocketAddress(host, port); NodePingUtil.pingHost(address, exchange, callback, options); } } catch (URISyntaxException e) { callback.failed(); } }
[ "protected", "void", "checkHostUp", "(", "final", "String", "scheme", ",", "final", "String", "host", ",", "final", "int", "port", ",", "final", "HttpServerExchange", "exchange", ",", "final", "NodePingUtil", ".", "PingCallback", "callback", ")", "{", "final", "XnioSsl", "xnioSsl", "=", "null", ";", "// TODO", "final", "OptionMap", "options", "=", "OptionMap", ".", "builder", "(", ")", ".", "set", "(", "Options", ".", "TCP_NODELAY", ",", "true", ")", ".", "getMap", "(", ")", ";", "try", "{", "// http, ajp and maybe more in future", "if", "(", "\"ajp\"", ".", "equalsIgnoreCase", "(", "scheme", ")", "||", "\"http\"", ".", "equalsIgnoreCase", "(", "scheme", ")", ")", "{", "final", "URI", "uri", "=", "new", "URI", "(", "scheme", ",", "null", ",", "host", ",", "port", ",", "\"/\"", ",", "null", ",", "null", ")", ";", "NodePingUtil", ".", "pingHttpClient", "(", "uri", ",", "callback", ",", "exchange", ",", "container", ".", "getClient", "(", ")", ",", "xnioSsl", ",", "options", ")", ";", "}", "else", "{", "final", "InetSocketAddress", "address", "=", "new", "InetSocketAddress", "(", "host", ",", "port", ")", ";", "NodePingUtil", ".", "pingHost", "(", "address", ",", "exchange", ",", "callback", ",", "options", ")", ";", "}", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "callback", ".", "failed", "(", ")", ";", "}", "}" ]
Check whether a host is up. @param scheme the scheme @param host the host @param port the port @param exchange the http server exchange @param callback the ping callback
[ "Check", "whether", "a", "host", "is", "up", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L682-L701
16,629
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.sendResponse
static void sendResponse(final HttpServerExchange exchange, final String response) { exchange.setStatusCode(StatusCodes.OK); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); final Sender sender = exchange.getResponseSender(); UndertowLogger.ROOT_LOGGER.mcmpSendingResponse(exchange.getSourceAddress(), exchange.getStatusCode(), exchange.getResponseHeaders(), response); sender.send(response); }
java
static void sendResponse(final HttpServerExchange exchange, final String response) { exchange.setStatusCode(StatusCodes.OK); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); final Sender sender = exchange.getResponseSender(); UndertowLogger.ROOT_LOGGER.mcmpSendingResponse(exchange.getSourceAddress(), exchange.getStatusCode(), exchange.getResponseHeaders(), response); sender.send(response); }
[ "static", "void", "sendResponse", "(", "final", "HttpServerExchange", "exchange", ",", "final", "String", "response", ")", "{", "exchange", ".", "setStatusCode", "(", "StatusCodes", ".", "OK", ")", ";", "exchange", ".", "getResponseHeaders", "(", ")", ".", "add", "(", "Headers", ".", "CONTENT_TYPE", ",", "CONTENT_TYPE", ")", ";", "final", "Sender", "sender", "=", "exchange", ".", "getResponseSender", "(", ")", ";", "UndertowLogger", ".", "ROOT_LOGGER", ".", "mcmpSendingResponse", "(", "exchange", ".", "getSourceAddress", "(", ")", ",", "exchange", ".", "getStatusCode", "(", ")", ",", "exchange", ".", "getResponseHeaders", "(", ")", ",", "response", ")", ";", "sender", ".", "send", "(", "response", ")", ";", "}" ]
Send a simple response string. @param exchange the http server exchange @param response the response string
[ "Send", "a", "simple", "response", "string", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L709-L715
16,630
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.processOK
static void processOK(HttpServerExchange exchange) throws IOException { exchange.setStatusCode(StatusCodes.OK); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); exchange.endExchange(); }
java
static void processOK(HttpServerExchange exchange) throws IOException { exchange.setStatusCode(StatusCodes.OK); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); exchange.endExchange(); }
[ "static", "void", "processOK", "(", "HttpServerExchange", "exchange", ")", "throws", "IOException", "{", "exchange", ".", "setStatusCode", "(", "StatusCodes", ".", "OK", ")", ";", "exchange", ".", "getResponseHeaders", "(", ")", ".", "add", "(", "Headers", ".", "CONTENT_TYPE", ",", "CONTENT_TYPE", ")", ";", "exchange", ".", "endExchange", "(", ")", ";", "}" ]
If the process is OK, then add 200 HTTP status and its "OK" phrase @throws IOException
[ "If", "the", "process", "is", "OK", "then", "add", "200", "HTTP", "status", "and", "its", "OK", "phrase" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L722-L726
16,631
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.processError
static void processError(String type, String errString, HttpServerExchange exchange) { exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); exchange.getResponseHeaders().add(new HttpString("Version"), VERSION_PROTOCOL); exchange.getResponseHeaders().add(new HttpString("Type"), type); exchange.getResponseHeaders().add(new HttpString("Mess"), errString); exchange.endExchange(); UndertowLogger.ROOT_LOGGER.mcmpProcessingError(type, errString); }
java
static void processError(String type, String errString, HttpServerExchange exchange) { exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); exchange.getResponseHeaders().add(new HttpString("Version"), VERSION_PROTOCOL); exchange.getResponseHeaders().add(new HttpString("Type"), type); exchange.getResponseHeaders().add(new HttpString("Mess"), errString); exchange.endExchange(); UndertowLogger.ROOT_LOGGER.mcmpProcessingError(type, errString); }
[ "static", "void", "processError", "(", "String", "type", ",", "String", "errString", ",", "HttpServerExchange", "exchange", ")", "{", "exchange", ".", "setStatusCode", "(", "StatusCodes", ".", "INTERNAL_SERVER_ERROR", ")", ";", "exchange", ".", "getResponseHeaders", "(", ")", ".", "add", "(", "Headers", ".", "CONTENT_TYPE", ",", "CONTENT_TYPE", ")", ";", "exchange", ".", "getResponseHeaders", "(", ")", ".", "add", "(", "new", "HttpString", "(", "\"Version\"", ")", ",", "VERSION_PROTOCOL", ")", ";", "exchange", ".", "getResponseHeaders", "(", ")", ".", "add", "(", "new", "HttpString", "(", "\"Type\"", ")", ",", "type", ")", ";", "exchange", ".", "getResponseHeaders", "(", ")", ".", "add", "(", "new", "HttpString", "(", "\"Mess\"", ")", ",", "errString", ")", ";", "exchange", ".", "endExchange", "(", ")", ";", "UndertowLogger", ".", "ROOT_LOGGER", ".", "mcmpProcessingError", "(", "type", ",", "errString", ")", ";", "}" ]
Send an error message. @param type the error type @param errString the error string @param exchange the http server exchange
[ "Send", "an", "error", "message", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L739-L747
16,632
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
MCMPHandler.parseFormData
RequestData parseFormData(final HttpServerExchange exchange) throws IOException { // Read post parameters final FormDataParser parser = parserFactory.createParser(exchange); final FormData formData = parser.parseBlocking(); final RequestData data = new RequestData(); for (String name : formData) { final HttpString key = new HttpString(name); data.add(key, formData.get(name)); } return data; }
java
RequestData parseFormData(final HttpServerExchange exchange) throws IOException { // Read post parameters final FormDataParser parser = parserFactory.createParser(exchange); final FormData formData = parser.parseBlocking(); final RequestData data = new RequestData(); for (String name : formData) { final HttpString key = new HttpString(name); data.add(key, formData.get(name)); } return data; }
[ "RequestData", "parseFormData", "(", "final", "HttpServerExchange", "exchange", ")", "throws", "IOException", "{", "// Read post parameters", "final", "FormDataParser", "parser", "=", "parserFactory", ".", "createParser", "(", "exchange", ")", ";", "final", "FormData", "formData", "=", "parser", ".", "parseBlocking", "(", ")", ";", "final", "RequestData", "data", "=", "new", "RequestData", "(", ")", ";", "for", "(", "String", "name", ":", "formData", ")", "{", "final", "HttpString", "key", "=", "new", "HttpString", "(", "name", ")", ";", "data", ".", "add", "(", "key", ",", "formData", ".", "get", "(", "name", ")", ")", ";", "}", "return", "data", ";", "}" ]
Transform the form data into an intermediate request data which can me used by the web manager @param exchange the http server exchange @return @throws IOException
[ "Transform", "the", "form", "data", "into", "an", "intermediate", "request", "data", "which", "can", "me", "used", "by", "the", "web", "manager" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L757-L767
16,633
undertow-io/undertow
core/src/main/java/io/undertow/websockets/client/WebSocketClient.java
WebSocketClient.connectionBuilder
public static ConnectionBuilder connectionBuilder(XnioWorker worker, ByteBufferPool bufferPool, URI uri) { return new ConnectionBuilder(worker, bufferPool, uri); }
java
public static ConnectionBuilder connectionBuilder(XnioWorker worker, ByteBufferPool bufferPool, URI uri) { return new ConnectionBuilder(worker, bufferPool, uri); }
[ "public", "static", "ConnectionBuilder", "connectionBuilder", "(", "XnioWorker", "worker", ",", "ByteBufferPool", "bufferPool", ",", "URI", "uri", ")", "{", "return", "new", "ConnectionBuilder", "(", "worker", ",", "bufferPool", ",", "uri", ")", ";", "}" ]
Creates a new connection builder that can be used to create a web socket connection. @param worker The XnioWorker to use for the connection @param bufferPool The buffer pool @param uri The connection URI @return The connection builder
[ "Creates", "a", "new", "connection", "builder", "that", "can", "be", "used", "to", "create", "a", "web", "socket", "connection", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/client/WebSocketClient.java#L386-L388
16,634
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/compat/rewrite/RewriteRule.java
RewriteRule.evaluate
public CharSequence evaluate(CharSequence url, Resolver resolver) { Pattern pattern = this.pattern.get(); if (pattern == null) { // Parse the pattern int flags = 0; if (isNocase()) { flags |= Pattern.CASE_INSENSITIVE; } pattern = Pattern.compile(patternString, flags); this.pattern.set(pattern); } Matcher matcher = pattern.matcher(url); if (!matcher.matches()) { // Evaluation done return null; } // Evaluate conditions boolean done = false; boolean rewrite = true; Matcher lastMatcher = null; int pos = 0; while (!done) { if (pos < conditions.length) { rewrite = conditions[pos].evaluate(matcher, lastMatcher, resolver); if (rewrite) { Matcher lastMatcher2 = conditions[pos].getMatcher(); if (lastMatcher2 != null) { lastMatcher = lastMatcher2; } while (pos < conditions.length && conditions[pos].isOrnext()) { pos++; } } else if (!conditions[pos].isOrnext()) { done = true; } pos++; } else { done = true; } } // Use the substitution to rewrite the url if (rewrite) { if (isEnv()) { for (int i = 0; i < envSubstitution.size(); i++) { envResult.get(i).set(envSubstitution.get(i).evaluate(matcher, lastMatcher, resolver)); } } if (isCookie()) { cookieResult.set(cookieSubstitution.evaluate(matcher, lastMatcher, resolver)); } if (substitution != null) { return substitution.evaluate(matcher, lastMatcher, resolver); } else { return url; } } else { return null; } }
java
public CharSequence evaluate(CharSequence url, Resolver resolver) { Pattern pattern = this.pattern.get(); if (pattern == null) { // Parse the pattern int flags = 0; if (isNocase()) { flags |= Pattern.CASE_INSENSITIVE; } pattern = Pattern.compile(patternString, flags); this.pattern.set(pattern); } Matcher matcher = pattern.matcher(url); if (!matcher.matches()) { // Evaluation done return null; } // Evaluate conditions boolean done = false; boolean rewrite = true; Matcher lastMatcher = null; int pos = 0; while (!done) { if (pos < conditions.length) { rewrite = conditions[pos].evaluate(matcher, lastMatcher, resolver); if (rewrite) { Matcher lastMatcher2 = conditions[pos].getMatcher(); if (lastMatcher2 != null) { lastMatcher = lastMatcher2; } while (pos < conditions.length && conditions[pos].isOrnext()) { pos++; } } else if (!conditions[pos].isOrnext()) { done = true; } pos++; } else { done = true; } } // Use the substitution to rewrite the url if (rewrite) { if (isEnv()) { for (int i = 0; i < envSubstitution.size(); i++) { envResult.get(i).set(envSubstitution.get(i).evaluate(matcher, lastMatcher, resolver)); } } if (isCookie()) { cookieResult.set(cookieSubstitution.evaluate(matcher, lastMatcher, resolver)); } if (substitution != null) { return substitution.evaluate(matcher, lastMatcher, resolver); } else { return url; } } else { return null; } }
[ "public", "CharSequence", "evaluate", "(", "CharSequence", "url", ",", "Resolver", "resolver", ")", "{", "Pattern", "pattern", "=", "this", ".", "pattern", ".", "get", "(", ")", ";", "if", "(", "pattern", "==", "null", ")", "{", "// Parse the pattern", "int", "flags", "=", "0", ";", "if", "(", "isNocase", "(", ")", ")", "{", "flags", "|=", "Pattern", ".", "CASE_INSENSITIVE", ";", "}", "pattern", "=", "Pattern", ".", "compile", "(", "patternString", ",", "flags", ")", ";", "this", ".", "pattern", ".", "set", "(", "pattern", ")", ";", "}", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "url", ")", ";", "if", "(", "!", "matcher", ".", "matches", "(", ")", ")", "{", "// Evaluation done", "return", "null", ";", "}", "// Evaluate conditions", "boolean", "done", "=", "false", ";", "boolean", "rewrite", "=", "true", ";", "Matcher", "lastMatcher", "=", "null", ";", "int", "pos", "=", "0", ";", "while", "(", "!", "done", ")", "{", "if", "(", "pos", "<", "conditions", ".", "length", ")", "{", "rewrite", "=", "conditions", "[", "pos", "]", ".", "evaluate", "(", "matcher", ",", "lastMatcher", ",", "resolver", ")", ";", "if", "(", "rewrite", ")", "{", "Matcher", "lastMatcher2", "=", "conditions", "[", "pos", "]", ".", "getMatcher", "(", ")", ";", "if", "(", "lastMatcher2", "!=", "null", ")", "{", "lastMatcher", "=", "lastMatcher2", ";", "}", "while", "(", "pos", "<", "conditions", ".", "length", "&&", "conditions", "[", "pos", "]", ".", "isOrnext", "(", ")", ")", "{", "pos", "++", ";", "}", "}", "else", "if", "(", "!", "conditions", "[", "pos", "]", ".", "isOrnext", "(", ")", ")", "{", "done", "=", "true", ";", "}", "pos", "++", ";", "}", "else", "{", "done", "=", "true", ";", "}", "}", "// Use the substitution to rewrite the url", "if", "(", "rewrite", ")", "{", "if", "(", "isEnv", "(", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "envSubstitution", ".", "size", "(", ")", ";", "i", "++", ")", "{", "envResult", ".", "get", "(", "i", ")", ".", "set", "(", "envSubstitution", ".", "get", "(", "i", ")", ".", "evaluate", "(", "matcher", ",", "lastMatcher", ",", "resolver", ")", ")", ";", "}", "}", "if", "(", "isCookie", "(", ")", ")", "{", "cookieResult", ".", "set", "(", "cookieSubstitution", ".", "evaluate", "(", "matcher", ",", "lastMatcher", ",", "resolver", ")", ")", ";", "}", "if", "(", "substitution", "!=", "null", ")", "{", "return", "substitution", ".", "evaluate", "(", "matcher", ",", "lastMatcher", ",", "resolver", ")", ";", "}", "else", "{", "return", "url", ";", "}", "}", "else", "{", "return", "null", ";", "}", "}" ]
Evaluate the rule based on the context @return null if no rewrite took place
[ "Evaluate", "the", "rule", "based", "on", "the", "context" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/compat/rewrite/RewriteRule.java#L87-L145
16,635
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2StreamSinkChannel.java
Http2StreamSinkChannel.rstStream
void rstStream() { if (reset) { return; } reset = true; if(!isReadyForFlush()) { IoUtils.safeClose(this); } getChannel().removeStreamSink(getStreamId()); }
java
void rstStream() { if (reset) { return; } reset = true; if(!isReadyForFlush()) { IoUtils.safeClose(this); } getChannel().removeStreamSink(getStreamId()); }
[ "void", "rstStream", "(", ")", "{", "if", "(", "reset", ")", "{", "return", ";", "}", "reset", "=", "true", ";", "if", "(", "!", "isReadyForFlush", "(", ")", ")", "{", "IoUtils", ".", "safeClose", "(", "this", ")", ";", "}", "getChannel", "(", ")", ".", "removeStreamSink", "(", "getStreamId", "(", ")", ")", ";", "}" ]
Method that is invoked when the stream is reset.
[ "Method", "that", "is", "invoked", "when", "the", "stream", "is", "reset", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2StreamSinkChannel.java#L177-L186
16,636
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/spec/ServletContextImpl.java
ServletContextImpl.getSession
public HttpSessionImpl getSession(final String sessionId) { final SessionManager sessionManager = deployment.getSessionManager(); Session session = sessionManager.getSession(sessionId); if (session != null) { return SecurityActions.forSession(session, this, false); } return null; }
java
public HttpSessionImpl getSession(final String sessionId) { final SessionManager sessionManager = deployment.getSessionManager(); Session session = sessionManager.getSession(sessionId); if (session != null) { return SecurityActions.forSession(session, this, false); } return null; }
[ "public", "HttpSessionImpl", "getSession", "(", "final", "String", "sessionId", ")", "{", "final", "SessionManager", "sessionManager", "=", "deployment", ".", "getSessionManager", "(", ")", ";", "Session", "session", "=", "sessionManager", ".", "getSession", "(", "sessionId", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "return", "SecurityActions", ".", "forSession", "(", "session", ",", "this", ",", "false", ")", ";", "}", "return", "null", ";", "}" ]
Gets the session with the specified ID if it exists @param sessionId The session ID @return The session
[ "Gets", "the", "session", "with", "the", "specified", "ID", "if", "it", "exists" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/spec/ServletContextImpl.java#L840-L847
16,637
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/cache/LimitedBufferSlicePool.java
LimitedBufferSlicePool.allocate
public PooledByteBuffer allocate() { final Queue<Slice> sliceQueue = this.sliceQueue; final Slice slice = sliceQueue.poll(); if (slice == null && (maxRegions <= 0 || regionUpdater.getAndIncrement(this) < maxRegions)) { final int bufferSize = this.bufferSize; final int buffersPerRegion = this.buffersPerRegion; final ByteBuffer region = allocator.allocate(buffersPerRegion * bufferSize); int idx = bufferSize; for (int i = 1; i < buffersPerRegion; i ++) { sliceQueue.add(new Slice(region, idx, bufferSize)); idx += bufferSize; } final Slice newSlice = new Slice(region, 0, bufferSize); return new PooledByteBuffer(newSlice, newSlice.slice(), sliceQueue); } if (slice == null) { return null; } return new PooledByteBuffer(slice, slice.slice(), sliceQueue); }
java
public PooledByteBuffer allocate() { final Queue<Slice> sliceQueue = this.sliceQueue; final Slice slice = sliceQueue.poll(); if (slice == null && (maxRegions <= 0 || regionUpdater.getAndIncrement(this) < maxRegions)) { final int bufferSize = this.bufferSize; final int buffersPerRegion = this.buffersPerRegion; final ByteBuffer region = allocator.allocate(buffersPerRegion * bufferSize); int idx = bufferSize; for (int i = 1; i < buffersPerRegion; i ++) { sliceQueue.add(new Slice(region, idx, bufferSize)); idx += bufferSize; } final Slice newSlice = new Slice(region, 0, bufferSize); return new PooledByteBuffer(newSlice, newSlice.slice(), sliceQueue); } if (slice == null) { return null; } return new PooledByteBuffer(slice, slice.slice(), sliceQueue); }
[ "public", "PooledByteBuffer", "allocate", "(", ")", "{", "final", "Queue", "<", "Slice", ">", "sliceQueue", "=", "this", ".", "sliceQueue", ";", "final", "Slice", "slice", "=", "sliceQueue", ".", "poll", "(", ")", ";", "if", "(", "slice", "==", "null", "&&", "(", "maxRegions", "<=", "0", "||", "regionUpdater", ".", "getAndIncrement", "(", "this", ")", "<", "maxRegions", ")", ")", "{", "final", "int", "bufferSize", "=", "this", ".", "bufferSize", ";", "final", "int", "buffersPerRegion", "=", "this", ".", "buffersPerRegion", ";", "final", "ByteBuffer", "region", "=", "allocator", ".", "allocate", "(", "buffersPerRegion", "*", "bufferSize", ")", ";", "int", "idx", "=", "bufferSize", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "buffersPerRegion", ";", "i", "++", ")", "{", "sliceQueue", ".", "add", "(", "new", "Slice", "(", "region", ",", "idx", ",", "bufferSize", ")", ")", ";", "idx", "+=", "bufferSize", ";", "}", "final", "Slice", "newSlice", "=", "new", "Slice", "(", "region", ",", "0", ",", "bufferSize", ")", ";", "return", "new", "PooledByteBuffer", "(", "newSlice", ",", "newSlice", ".", "slice", "(", ")", ",", "sliceQueue", ")", ";", "}", "if", "(", "slice", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "PooledByteBuffer", "(", "slice", ",", "slice", ".", "slice", "(", ")", ",", "sliceQueue", ")", ";", "}" ]
Allocates a new byte buffer if possible @return new buffer or null if none available
[ "Allocates", "a", "new", "byte", "buffer", "if", "possible" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/cache/LimitedBufferSlicePool.java#L98-L117
16,638
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/protocol/Handshake.java
Handshake.handshake
public final void handshake(final WebSocketHttpExchange exchange) { exchange.putAttachment(WebSocketVersion.ATTACHMENT_KEY, version); handshakeInternal(exchange); }
java
public final void handshake(final WebSocketHttpExchange exchange) { exchange.putAttachment(WebSocketVersion.ATTACHMENT_KEY, version); handshakeInternal(exchange); }
[ "public", "final", "void", "handshake", "(", "final", "WebSocketHttpExchange", "exchange", ")", "{", "exchange", ".", "putAttachment", "(", "WebSocketVersion", ".", "ATTACHMENT_KEY", ",", "version", ")", ";", "handshakeInternal", "(", "exchange", ")", ";", "}" ]
Issue the WebSocket upgrade @param exchange The {@link WebSocketHttpExchange} for which the handshake and upgrade should occur.
[ "Issue", "the", "WebSocket", "upgrade" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/protocol/Handshake.java#L100-L103
16,639
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/protocol/Handshake.java
Handshake.performUpgrade
protected final void performUpgrade(final WebSocketHttpExchange exchange, final byte[] data) { exchange.setResponseHeader(Headers.CONTENT_LENGTH_STRING, String.valueOf(data.length)); exchange.setResponseHeader(Headers.UPGRADE_STRING, "WebSocket"); exchange.setResponseHeader(Headers.CONNECTION_STRING, "Upgrade"); upgradeChannel(exchange, data); }
java
protected final void performUpgrade(final WebSocketHttpExchange exchange, final byte[] data) { exchange.setResponseHeader(Headers.CONTENT_LENGTH_STRING, String.valueOf(data.length)); exchange.setResponseHeader(Headers.UPGRADE_STRING, "WebSocket"); exchange.setResponseHeader(Headers.CONNECTION_STRING, "Upgrade"); upgradeChannel(exchange, data); }
[ "protected", "final", "void", "performUpgrade", "(", "final", "WebSocketHttpExchange", "exchange", ",", "final", "byte", "[", "]", "data", ")", "{", "exchange", ".", "setResponseHeader", "(", "Headers", ".", "CONTENT_LENGTH_STRING", ",", "String", ".", "valueOf", "(", "data", ".", "length", ")", ")", ";", "exchange", ".", "setResponseHeader", "(", "Headers", ".", "UPGRADE_STRING", ",", "\"WebSocket\"", ")", ";", "exchange", ".", "setResponseHeader", "(", "Headers", ".", "CONNECTION_STRING", ",", "\"Upgrade\"", ")", ";", "upgradeChannel", "(", "exchange", ",", "data", ")", ";", "}" ]
convenience method to perform the upgrade
[ "convenience", "method", "to", "perform", "the", "upgrade" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/protocol/Handshake.java#L120-L125
16,640
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/protocol/Handshake.java
Handshake.selectSubprotocol
protected final void selectSubprotocol(final WebSocketHttpExchange exchange) { String requestedSubprotocols = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING); if (requestedSubprotocols == null) { return; } String[] requestedSubprotocolArray = PATTERN.split(requestedSubprotocols); String subProtocol = supportedSubprotols(requestedSubprotocolArray); if (subProtocol != null && !subProtocol.isEmpty()) { exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING, subProtocol); } }
java
protected final void selectSubprotocol(final WebSocketHttpExchange exchange) { String requestedSubprotocols = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING); if (requestedSubprotocols == null) { return; } String[] requestedSubprotocolArray = PATTERN.split(requestedSubprotocols); String subProtocol = supportedSubprotols(requestedSubprotocolArray); if (subProtocol != null && !subProtocol.isEmpty()) { exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING, subProtocol); } }
[ "protected", "final", "void", "selectSubprotocol", "(", "final", "WebSocketHttpExchange", "exchange", ")", "{", "String", "requestedSubprotocols", "=", "exchange", ".", "getRequestHeader", "(", "Headers", ".", "SEC_WEB_SOCKET_PROTOCOL_STRING", ")", ";", "if", "(", "requestedSubprotocols", "==", "null", ")", "{", "return", ";", "}", "String", "[", "]", "requestedSubprotocolArray", "=", "PATTERN", ".", "split", "(", "requestedSubprotocols", ")", ";", "String", "subProtocol", "=", "supportedSubprotols", "(", "requestedSubprotocolArray", ")", ";", "if", "(", "subProtocol", "!=", "null", "&&", "!", "subProtocol", ".", "isEmpty", "(", ")", ")", "{", "exchange", ".", "setResponseHeader", "(", "Headers", ".", "SEC_WEB_SOCKET_PROTOCOL_STRING", ",", "subProtocol", ")", ";", "}", "}" ]
Selects the first matching supported sub protocol and add it the the headers of the exchange.
[ "Selects", "the", "first", "matching", "supported", "sub", "protocol", "and", "add", "it", "the", "the", "headers", "of", "the", "exchange", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/protocol/Handshake.java#L159-L171
16,641
undertow-io/undertow
core/src/main/java/io/undertow/util/QValueParser.java
QValueParser.parse
public static List<List<QValueResult>> parse(List<String> headers) { final List<QValueResult> found = new ArrayList<>(); QValueResult current = null; for (final String header : headers) { final int l = header.length(); //we do not use a string builder //we just keep track of where the current string starts and call substring() int stringStart = 0; for (int i = 0; i < l; ++i) { char c = header.charAt(i); switch (c) { case ',': { if (current != null && (i - stringStart > 2 && header.charAt(stringStart) == 'q' && header.charAt(stringStart + 1) == '=')) { //if this is a valid qvalue current.qvalue = header.substring(stringStart + 2, i); current = null; } else if (stringStart != i) { current = handleNewEncoding(found, header, stringStart, i); } stringStart = i + 1; break; } case ';': { if (stringStart != i) { current = handleNewEncoding(found, header, stringStart, i); stringStart = i + 1; } break; } case ' ': { if (stringStart != i) { if (current != null && (i - stringStart > 2 && header.charAt(stringStart) == 'q' && header.charAt(stringStart + 1) == '=')) { //if this is a valid qvalue current.qvalue = header.substring(stringStart + 2, i); } else { current = handleNewEncoding(found, header, stringStart, i); } } stringStart = i + 1; } } } if (stringStart != l) { if (current != null && (l - stringStart > 2 && header.charAt(stringStart) == 'q' && header.charAt(stringStart + 1) == '=')) { //if this is a valid qvalue current.qvalue = header.substring(stringStart + 2, l); } else { current = handleNewEncoding(found, header, stringStart, l); } } } Collections.sort(found, Collections.reverseOrder()); String currentQValue = null; List<List<QValueResult>> values = new ArrayList<>(); List<QValueResult> currentSet = null; for(QValueResult val : found) { if(!val.qvalue.equals(currentQValue)) { currentQValue = val.qvalue; currentSet = new ArrayList<>(); values.add(currentSet); } currentSet.add(val); } return values; }
java
public static List<List<QValueResult>> parse(List<String> headers) { final List<QValueResult> found = new ArrayList<>(); QValueResult current = null; for (final String header : headers) { final int l = header.length(); //we do not use a string builder //we just keep track of where the current string starts and call substring() int stringStart = 0; for (int i = 0; i < l; ++i) { char c = header.charAt(i); switch (c) { case ',': { if (current != null && (i - stringStart > 2 && header.charAt(stringStart) == 'q' && header.charAt(stringStart + 1) == '=')) { //if this is a valid qvalue current.qvalue = header.substring(stringStart + 2, i); current = null; } else if (stringStart != i) { current = handleNewEncoding(found, header, stringStart, i); } stringStart = i + 1; break; } case ';': { if (stringStart != i) { current = handleNewEncoding(found, header, stringStart, i); stringStart = i + 1; } break; } case ' ': { if (stringStart != i) { if (current != null && (i - stringStart > 2 && header.charAt(stringStart) == 'q' && header.charAt(stringStart + 1) == '=')) { //if this is a valid qvalue current.qvalue = header.substring(stringStart + 2, i); } else { current = handleNewEncoding(found, header, stringStart, i); } } stringStart = i + 1; } } } if (stringStart != l) { if (current != null && (l - stringStart > 2 && header.charAt(stringStart) == 'q' && header.charAt(stringStart + 1) == '=')) { //if this is a valid qvalue current.qvalue = header.substring(stringStart + 2, l); } else { current = handleNewEncoding(found, header, stringStart, l); } } } Collections.sort(found, Collections.reverseOrder()); String currentQValue = null; List<List<QValueResult>> values = new ArrayList<>(); List<QValueResult> currentSet = null; for(QValueResult val : found) { if(!val.qvalue.equals(currentQValue)) { currentQValue = val.qvalue; currentSet = new ArrayList<>(); values.add(currentSet); } currentSet.add(val); } return values; }
[ "public", "static", "List", "<", "List", "<", "QValueResult", ">", ">", "parse", "(", "List", "<", "String", ">", "headers", ")", "{", "final", "List", "<", "QValueResult", ">", "found", "=", "new", "ArrayList", "<>", "(", ")", ";", "QValueResult", "current", "=", "null", ";", "for", "(", "final", "String", "header", ":", "headers", ")", "{", "final", "int", "l", "=", "header", ".", "length", "(", ")", ";", "//we do not use a string builder", "//we just keep track of where the current string starts and call substring()", "int", "stringStart", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "l", ";", "++", "i", ")", "{", "char", "c", "=", "header", ".", "charAt", "(", "i", ")", ";", "switch", "(", "c", ")", "{", "case", "'", "'", ":", "{", "if", "(", "current", "!=", "null", "&&", "(", "i", "-", "stringStart", ">", "2", "&&", "header", ".", "charAt", "(", "stringStart", ")", "==", "'", "'", "&&", "header", ".", "charAt", "(", "stringStart", "+", "1", ")", "==", "'", "'", ")", ")", "{", "//if this is a valid qvalue", "current", ".", "qvalue", "=", "header", ".", "substring", "(", "stringStart", "+", "2", ",", "i", ")", ";", "current", "=", "null", ";", "}", "else", "if", "(", "stringStart", "!=", "i", ")", "{", "current", "=", "handleNewEncoding", "(", "found", ",", "header", ",", "stringStart", ",", "i", ")", ";", "}", "stringStart", "=", "i", "+", "1", ";", "break", ";", "}", "case", "'", "'", ":", "{", "if", "(", "stringStart", "!=", "i", ")", "{", "current", "=", "handleNewEncoding", "(", "found", ",", "header", ",", "stringStart", ",", "i", ")", ";", "stringStart", "=", "i", "+", "1", ";", "}", "break", ";", "}", "case", "'", "'", ":", "{", "if", "(", "stringStart", "!=", "i", ")", "{", "if", "(", "current", "!=", "null", "&&", "(", "i", "-", "stringStart", ">", "2", "&&", "header", ".", "charAt", "(", "stringStart", ")", "==", "'", "'", "&&", "header", ".", "charAt", "(", "stringStart", "+", "1", ")", "==", "'", "'", ")", ")", "{", "//if this is a valid qvalue", "current", ".", "qvalue", "=", "header", ".", "substring", "(", "stringStart", "+", "2", ",", "i", ")", ";", "}", "else", "{", "current", "=", "handleNewEncoding", "(", "found", ",", "header", ",", "stringStart", ",", "i", ")", ";", "}", "}", "stringStart", "=", "i", "+", "1", ";", "}", "}", "}", "if", "(", "stringStart", "!=", "l", ")", "{", "if", "(", "current", "!=", "null", "&&", "(", "l", "-", "stringStart", ">", "2", "&&", "header", ".", "charAt", "(", "stringStart", ")", "==", "'", "'", "&&", "header", ".", "charAt", "(", "stringStart", "+", "1", ")", "==", "'", "'", ")", ")", "{", "//if this is a valid qvalue", "current", ".", "qvalue", "=", "header", ".", "substring", "(", "stringStart", "+", "2", ",", "l", ")", ";", "}", "else", "{", "current", "=", "handleNewEncoding", "(", "found", ",", "header", ",", "stringStart", ",", "l", ")", ";", "}", "}", "}", "Collections", ".", "sort", "(", "found", ",", "Collections", ".", "reverseOrder", "(", ")", ")", ";", "String", "currentQValue", "=", "null", ";", "List", "<", "List", "<", "QValueResult", ">", ">", "values", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "QValueResult", ">", "currentSet", "=", "null", ";", "for", "(", "QValueResult", "val", ":", "found", ")", "{", "if", "(", "!", "val", ".", "qvalue", ".", "equals", "(", "currentQValue", ")", ")", "{", "currentQValue", "=", "val", ".", "qvalue", ";", "currentSet", "=", "new", "ArrayList", "<>", "(", ")", ";", "values", ".", "add", "(", "currentSet", ")", ";", "}", "currentSet", ".", "add", "(", "val", ")", ";", "}", "return", "values", ";", "}" ]
Parses a set of headers that take q values to determine the most preferred one. It returns the result in the form of a sorted list of list, with every element in the list having the same q value. This means the highest priority items are at the front of the list. The container should use its own internal preferred ordering to determinately pick the correct item to use @param headers The headers @return The q value results
[ "Parses", "a", "set", "of", "headers", "that", "take", "q", "values", "to", "determine", "the", "most", "preferred", "one", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/QValueParser.java#L47-L119
16,642
undertow-io/undertow
core/src/main/java/io/undertow/conduits/AbstractFramedStreamSinkConduit.java
AbstractFramedStreamSinkConduit.queueFrame
protected void queueFrame(FrameCallBack callback, ByteBuffer... data) { queuedData += Buffers.remaining(data); bufferCount += data.length; frameQueue.add(new Frame(callback, data, 0, data.length)); }
java
protected void queueFrame(FrameCallBack callback, ByteBuffer... data) { queuedData += Buffers.remaining(data); bufferCount += data.length; frameQueue.add(new Frame(callback, data, 0, data.length)); }
[ "protected", "void", "queueFrame", "(", "FrameCallBack", "callback", ",", "ByteBuffer", "...", "data", ")", "{", "queuedData", "+=", "Buffers", ".", "remaining", "(", "data", ")", ";", "bufferCount", "+=", "data", ".", "length", ";", "frameQueue", ".", "add", "(", "new", "Frame", "(", "callback", ",", "data", ",", "0", ",", "data", ".", "length", ")", ")", ";", "}" ]
Queues a frame for sending. @param callback @param data
[ "Queues", "a", "frame", "for", "sending", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/conduits/AbstractFramedStreamSinkConduit.java#L81-L85
16,643
undertow-io/undertow
core/src/main/java/io/undertow/util/HttpString.java
HttpString.compareTo
public int compareTo(final HttpString other) { if(orderInt != 0 && other.orderInt != 0) { return signum(orderInt - other.orderInt); } final int len = Math.min(bytes.length, other.bytes.length); int res; for (int i = 0; i < len; i++) { res = signum(higher(bytes[i]) - higher(other.bytes[i])); if (res != 0) return res; } // shorter strings sort higher return signum(bytes.length - other.bytes.length); }
java
public int compareTo(final HttpString other) { if(orderInt != 0 && other.orderInt != 0) { return signum(orderInt - other.orderInt); } final int len = Math.min(bytes.length, other.bytes.length); int res; for (int i = 0; i < len; i++) { res = signum(higher(bytes[i]) - higher(other.bytes[i])); if (res != 0) return res; } // shorter strings sort higher return signum(bytes.length - other.bytes.length); }
[ "public", "int", "compareTo", "(", "final", "HttpString", "other", ")", "{", "if", "(", "orderInt", "!=", "0", "&&", "other", ".", "orderInt", "!=", "0", ")", "{", "return", "signum", "(", "orderInt", "-", "other", ".", "orderInt", ")", ";", "}", "final", "int", "len", "=", "Math", ".", "min", "(", "bytes", ".", "length", ",", "other", ".", "bytes", ".", "length", ")", ";", "int", "res", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "res", "=", "signum", "(", "higher", "(", "bytes", "[", "i", "]", ")", "-", "higher", "(", "other", ".", "bytes", "[", "i", "]", ")", ")", ";", "if", "(", "res", "!=", "0", ")", "return", "res", ";", "}", "// shorter strings sort higher", "return", "signum", "(", "bytes", ".", "length", "-", "other", ".", "bytes", ".", "length", ")", ";", "}" ]
Compare this string to another in a case-insensitive manner. @param other the other string @return -1, 0, or 1
[ "Compare", "this", "string", "to", "another", "in", "a", "case", "-", "insensitive", "manner", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/HttpString.java#L257-L269
16,644
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/compat/rewrite/Substitution.java
Substitution.evaluate
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < elements.length; i++) { buf.append(elements[i].evaluate(rule, cond, resolver)); } return buf.toString(); }
java
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < elements.length; i++) { buf.append(elements[i].evaluate(rule, cond, resolver)); } return buf.toString(); }
[ "public", "String", "evaluate", "(", "Matcher", "rule", ",", "Matcher", "cond", ",", "Resolver", "resolver", ")", "{", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "buf", ".", "append", "(", "elements", "[", "i", "]", ".", "evaluate", "(", "rule", ",", "cond", ",", "resolver", ")", ")", ";", "}", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Evaluate the substitution based on the context @param rule corresponding matched rule @param cond last matched condition @return
[ "Evaluate", "the", "substitution", "based", "on", "the", "context" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/compat/rewrite/Substitution.java#L243-L249
16,645
undertow-io/undertow
websockets-jsr/src/main/java/io/undertow/websockets/jsr/ServerWebSocketContainer.java
ServerWebSocketContainer.invokeEndpointMethod
public void invokeEndpointMethod(final Runnable invocation) { try { invokeEndpointTask.call(null, invocation); } catch (Exception e) { throw new RuntimeException(e); } }
java
public void invokeEndpointMethod(final Runnable invocation) { try { invokeEndpointTask.call(null, invocation); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "void", "invokeEndpointMethod", "(", "final", "Runnable", "invocation", ")", "{", "try", "{", "invokeEndpointTask", ".", "call", "(", "null", ",", "invocation", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Directly invokes an endpoint method, without dispatching to an executor @param invocation The invocation
[ "Directly", "invokes", "an", "endpoint", "method", "without", "dispatching", "to", "an", "executor" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/websockets-jsr/src/main/java/io/undertow/websockets/jsr/ServerWebSocketContainer.java#L602-L608
16,646
undertow-io/undertow
websockets-jsr/src/main/java/io/undertow/websockets/jsr/ServerWebSocketContainer.java
ServerWebSocketContainer.pause
public synchronized void pause(PauseListener listener) { closed = true; if(configuredServerEndpoints.isEmpty()) { listener.paused(); return; } if(listener != null) { pauseListeners.add(listener); } for (ConfiguredServerEndpoint endpoint : configuredServerEndpoints) { for (final Session session : endpoint.getOpenSessions()) { ((UndertowSession)session).getExecutor().execute(new Runnable() { @Override public void run() { try { session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "")); } catch (Exception e) { JsrWebSocketLogger.ROOT_LOGGER.couldNotCloseOnUndeploy(e); } } }); } } Runnable done = new Runnable() { int count = configuredServerEndpoints.size(); @Override public synchronized void run() { List<PauseListener> copy = null; synchronized (ServerWebSocketContainer.this) { count--; if (count == 0) { copy = new ArrayList<>(pauseListeners); pauseListeners.clear(); } } if(copy != null) { for (PauseListener p : copy) { p.paused(); } } } }; for (ConfiguredServerEndpoint endpoint : configuredServerEndpoints) { endpoint.notifyClosed(done); } }
java
public synchronized void pause(PauseListener listener) { closed = true; if(configuredServerEndpoints.isEmpty()) { listener.paused(); return; } if(listener != null) { pauseListeners.add(listener); } for (ConfiguredServerEndpoint endpoint : configuredServerEndpoints) { for (final Session session : endpoint.getOpenSessions()) { ((UndertowSession)session).getExecutor().execute(new Runnable() { @Override public void run() { try { session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "")); } catch (Exception e) { JsrWebSocketLogger.ROOT_LOGGER.couldNotCloseOnUndeploy(e); } } }); } } Runnable done = new Runnable() { int count = configuredServerEndpoints.size(); @Override public synchronized void run() { List<PauseListener> copy = null; synchronized (ServerWebSocketContainer.this) { count--; if (count == 0) { copy = new ArrayList<>(pauseListeners); pauseListeners.clear(); } } if(copy != null) { for (PauseListener p : copy) { p.paused(); } } } }; for (ConfiguredServerEndpoint endpoint : configuredServerEndpoints) { endpoint.notifyClosed(done); } }
[ "public", "synchronized", "void", "pause", "(", "PauseListener", "listener", ")", "{", "closed", "=", "true", ";", "if", "(", "configuredServerEndpoints", ".", "isEmpty", "(", ")", ")", "{", "listener", ".", "paused", "(", ")", ";", "return", ";", "}", "if", "(", "listener", "!=", "null", ")", "{", "pauseListeners", ".", "add", "(", "listener", ")", ";", "}", "for", "(", "ConfiguredServerEndpoint", "endpoint", ":", "configuredServerEndpoints", ")", "{", "for", "(", "final", "Session", "session", ":", "endpoint", ".", "getOpenSessions", "(", ")", ")", "{", "(", "(", "UndertowSession", ")", "session", ")", ".", "getExecutor", "(", ")", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "session", ".", "close", "(", "new", "CloseReason", "(", "CloseReason", ".", "CloseCodes", ".", "GOING_AWAY", ",", "\"\"", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "JsrWebSocketLogger", ".", "ROOT_LOGGER", ".", "couldNotCloseOnUndeploy", "(", "e", ")", ";", "}", "}", "}", ")", ";", "}", "}", "Runnable", "done", "=", "new", "Runnable", "(", ")", "{", "int", "count", "=", "configuredServerEndpoints", ".", "size", "(", ")", ";", "@", "Override", "public", "synchronized", "void", "run", "(", ")", "{", "List", "<", "PauseListener", ">", "copy", "=", "null", ";", "synchronized", "(", "ServerWebSocketContainer", ".", "this", ")", "{", "count", "--", ";", "if", "(", "count", "==", "0", ")", "{", "copy", "=", "new", "ArrayList", "<>", "(", "pauseListeners", ")", ";", "pauseListeners", ".", "clear", "(", ")", ";", "}", "}", "if", "(", "copy", "!=", "null", ")", "{", "for", "(", "PauseListener", "p", ":", "copy", ")", "{", "p", ".", "paused", "(", ")", ";", "}", "}", "}", "}", ";", "for", "(", "ConfiguredServerEndpoint", "endpoint", ":", "configuredServerEndpoints", ")", "{", "endpoint", ".", "notifyClosed", "(", "done", ")", ";", "}", "}" ]
Pauses the container @param listener
[ "Pauses", "the", "container" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/websockets-jsr/src/main/java/io/undertow/websockets/jsr/ServerWebSocketContainer.java#L919-L968
16,647
undertow-io/undertow
websockets-jsr/src/main/java/io/undertow/websockets/jsr/ServerWebSocketContainer.java
ServerWebSocketContainer.resume
public synchronized void resume() { closed = false; for(PauseListener p : pauseListeners) { p.resumed(); } pauseListeners.clear(); }
java
public synchronized void resume() { closed = false; for(PauseListener p : pauseListeners) { p.resumed(); } pauseListeners.clear(); }
[ "public", "synchronized", "void", "resume", "(", ")", "{", "closed", "=", "false", ";", "for", "(", "PauseListener", "p", ":", "pauseListeners", ")", "{", "p", ".", "resumed", "(", ")", ";", "}", "pauseListeners", ".", "clear", "(", ")", ";", "}" ]
resumes a paused container
[ "resumes", "a", "paused", "container" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/websockets-jsr/src/main/java/io/undertow/websockets/jsr/ServerWebSocketContainer.java#L1019-L1025
16,648
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/spec/HttpServletResponseImpl.java
HttpServletResponseImpl.encodeRedirectURL
public String encodeRedirectURL(String url) { if (isEncodeable(toAbsolute(url))) { return originalServletContext.getSessionConfig().rewriteUrl(url, servletContext.getSession(originalServletContext, exchange, true).getId()); } else { return url; } }
java
public String encodeRedirectURL(String url) { if (isEncodeable(toAbsolute(url))) { return originalServletContext.getSessionConfig().rewriteUrl(url, servletContext.getSession(originalServletContext, exchange, true).getId()); } else { return url; } }
[ "public", "String", "encodeRedirectURL", "(", "String", "url", ")", "{", "if", "(", "isEncodeable", "(", "toAbsolute", "(", "url", ")", ")", ")", "{", "return", "originalServletContext", ".", "getSessionConfig", "(", ")", ".", "rewriteUrl", "(", "url", ",", "servletContext", ".", "getSession", "(", "originalServletContext", ",", "exchange", ",", "true", ")", ".", "getId", "(", ")", ")", ";", "}", "else", "{", "return", "url", ";", "}", "}" ]
Encode the session identifier associated with this response into the specified redirect URL, if necessary. @param url URL to be encoded
[ "Encode", "the", "session", "identifier", "associated", "with", "this", "response", "into", "the", "specified", "redirect", "URL", "if", "necessary", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/spec/HttpServletResponseImpl.java#L619-L625
16,649
undertow-io/undertow
websockets-jsr/src/main/java/io/undertow/websockets/jsr/handshake/HandshakeUtil.java
HandshakeUtil.checkOrigin
public static boolean checkOrigin(ServerEndpointConfig config, WebSocketHttpExchange exchange) { ServerEndpointConfig.Configurator c = config.getConfigurator(); return c.checkOrigin(exchange.getRequestHeader(Headers.ORIGIN_STRING)); }
java
public static boolean checkOrigin(ServerEndpointConfig config, WebSocketHttpExchange exchange) { ServerEndpointConfig.Configurator c = config.getConfigurator(); return c.checkOrigin(exchange.getRequestHeader(Headers.ORIGIN_STRING)); }
[ "public", "static", "boolean", "checkOrigin", "(", "ServerEndpointConfig", "config", ",", "WebSocketHttpExchange", "exchange", ")", "{", "ServerEndpointConfig", ".", "Configurator", "c", "=", "config", ".", "getConfigurator", "(", ")", ";", "return", "c", ".", "checkOrigin", "(", "exchange", ".", "getRequestHeader", "(", "Headers", ".", "ORIGIN_STRING", ")", ")", ";", "}" ]
Checks the orgin against the
[ "Checks", "the", "orgin", "against", "the" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/websockets-jsr/src/main/java/io/undertow/websockets/jsr/handshake/HandshakeUtil.java#L53-L56
16,650
undertow-io/undertow
websockets-jsr/src/main/java/io/undertow/websockets/jsr/handshake/HandshakeUtil.java
HandshakeUtil.prepareUpgrade
public static void prepareUpgrade(final ServerEndpointConfig config, final WebSocketHttpExchange exchange) { ExchangeHandshakeRequest request = new ExchangeHandshakeRequest(exchange); ExchangeHandshakeResponse response = new ExchangeHandshakeResponse(exchange); ServerEndpointConfig.Configurator c = config.getConfigurator(); c.modifyHandshake(config, request, response); response.update(); }
java
public static void prepareUpgrade(final ServerEndpointConfig config, final WebSocketHttpExchange exchange) { ExchangeHandshakeRequest request = new ExchangeHandshakeRequest(exchange); ExchangeHandshakeResponse response = new ExchangeHandshakeResponse(exchange); ServerEndpointConfig.Configurator c = config.getConfigurator(); c.modifyHandshake(config, request, response); response.update(); }
[ "public", "static", "void", "prepareUpgrade", "(", "final", "ServerEndpointConfig", "config", ",", "final", "WebSocketHttpExchange", "exchange", ")", "{", "ExchangeHandshakeRequest", "request", "=", "new", "ExchangeHandshakeRequest", "(", "exchange", ")", ";", "ExchangeHandshakeResponse", "response", "=", "new", "ExchangeHandshakeResponse", "(", "exchange", ")", ";", "ServerEndpointConfig", ".", "Configurator", "c", "=", "config", ".", "getConfigurator", "(", ")", ";", "c", ".", "modifyHandshake", "(", "config", ",", "request", ",", "response", ")", ";", "response", ".", "update", "(", ")", ";", "}" ]
Prepare for upgrade
[ "Prepare", "for", "upgrade" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/websockets-jsr/src/main/java/io/undertow/websockets/jsr/handshake/HandshakeUtil.java#L61-L67
16,651
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodeLbStatus.java
NodeLbStatus.update
synchronized boolean update() { int elected = this.elected; int oldelected = this.oldelected; int lbfactor = this.lbfactor; if (lbfactor > 0) { this.lbstatus = ((elected - oldelected) * 1000) / lbfactor; } this.oldelected = elected; return elected != oldelected; // ping if they are equal }
java
synchronized boolean update() { int elected = this.elected; int oldelected = this.oldelected; int lbfactor = this.lbfactor; if (lbfactor > 0) { this.lbstatus = ((elected - oldelected) * 1000) / lbfactor; } this.oldelected = elected; return elected != oldelected; // ping if they are equal }
[ "synchronized", "boolean", "update", "(", ")", "{", "int", "elected", "=", "this", ".", "elected", ";", "int", "oldelected", "=", "this", ".", "oldelected", ";", "int", "lbfactor", "=", "this", ".", "lbfactor", ";", "if", "(", "lbfactor", ">", "0", ")", "{", "this", ".", "lbstatus", "=", "(", "(", "elected", "-", "oldelected", ")", "*", "1000", ")", "/", "lbfactor", ";", "}", "this", ".", "oldelected", "=", "elected", ";", "return", "elected", "!=", "oldelected", ";", "// ping if they are equal", "}" ]
Update the load balancing status. @return
[ "Update", "the", "load", "balancing", "status", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodeLbStatus.java#L51-L60
16,652
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Context.java
Context.handleRequest
void handleRequest(final ModClusterProxyTarget target, final HttpServerExchange exchange, final ProxyCallback<ProxyConnection> callback, long timeout, TimeUnit timeUnit, boolean exclusive) { if (addRequest()) { exchange.addExchangeCompleteListener(new ExchangeCompletionListener() { @Override public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) { requestDone(); nextListener.proceed(); } }); node.getConnectionPool().connect(target, exchange, callback, timeout, timeUnit, exclusive); } else { callback.failed(exchange); } }
java
void handleRequest(final ModClusterProxyTarget target, final HttpServerExchange exchange, final ProxyCallback<ProxyConnection> callback, long timeout, TimeUnit timeUnit, boolean exclusive) { if (addRequest()) { exchange.addExchangeCompleteListener(new ExchangeCompletionListener() { @Override public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) { requestDone(); nextListener.proceed(); } }); node.getConnectionPool().connect(target, exchange, callback, timeout, timeUnit, exclusive); } else { callback.failed(exchange); } }
[ "void", "handleRequest", "(", "final", "ModClusterProxyTarget", "target", ",", "final", "HttpServerExchange", "exchange", ",", "final", "ProxyCallback", "<", "ProxyConnection", ">", "callback", ",", "long", "timeout", ",", "TimeUnit", "timeUnit", ",", "boolean", "exclusive", ")", "{", "if", "(", "addRequest", "(", ")", ")", "{", "exchange", ".", "addExchangeCompleteListener", "(", "new", "ExchangeCompletionListener", "(", ")", "{", "@", "Override", "public", "void", "exchangeEvent", "(", "HttpServerExchange", "exchange", ",", "NextListener", "nextListener", ")", "{", "requestDone", "(", ")", ";", "nextListener", ".", "proceed", "(", ")", ";", "}", "}", ")", ";", "node", ".", "getConnectionPool", "(", ")", ".", "connect", "(", "target", ",", "exchange", ",", "callback", ",", "timeout", ",", "timeUnit", ",", "exclusive", ")", ";", "}", "else", "{", "callback", ".", "failed", "(", "exchange", ")", ";", "}", "}" ]
Handle a proxy request for this context. @param target the proxy target @param exchange the http server exchange @param callback the proxy callback @param timeout the timeout @param timeUnit the time unit @param exclusive whether this connection is exclusive
[ "Handle", "a", "proxy", "request", "for", "this", "context", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Context.java#L170-L183
16,653
undertow-io/undertow
core/src/main/java/io/undertow/util/ByteRange.java
ByteRange.parse
public static ByteRange parse(String rangeHeader) { if(rangeHeader == null || rangeHeader.length() < 7) { return null; } if(!rangeHeader.startsWith("bytes=")) { return null; } List<Range> ranges = new ArrayList<>(); String[] parts = rangeHeader.substring(6).split(","); for(String part : parts) { try { int index = part.indexOf('-'); if (index == 0) { //suffix range spec //represents the last N bytes //internally we represent this using a -1 as the start position long val = Long.parseLong(part.substring(1)); if(val < 0) { UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader); return null; } ranges.add(new Range(-1, val)); } else { if(index == -1) { UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader); return null; } long start = Long.parseLong(part.substring(0, index)); if(start < 0) { UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader); return null; } long end; if (index + 1 < part.length()) { end = Long.parseLong(part.substring(index + 1)); } else { end = -1; } ranges.add(new Range(start, end)); } } catch (NumberFormatException e) { UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader); return null; } } if(ranges.isEmpty()) { return null; } return new ByteRange(ranges); }
java
public static ByteRange parse(String rangeHeader) { if(rangeHeader == null || rangeHeader.length() < 7) { return null; } if(!rangeHeader.startsWith("bytes=")) { return null; } List<Range> ranges = new ArrayList<>(); String[] parts = rangeHeader.substring(6).split(","); for(String part : parts) { try { int index = part.indexOf('-'); if (index == 0) { //suffix range spec //represents the last N bytes //internally we represent this using a -1 as the start position long val = Long.parseLong(part.substring(1)); if(val < 0) { UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader); return null; } ranges.add(new Range(-1, val)); } else { if(index == -1) { UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader); return null; } long start = Long.parseLong(part.substring(0, index)); if(start < 0) { UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader); return null; } long end; if (index + 1 < part.length()) { end = Long.parseLong(part.substring(index + 1)); } else { end = -1; } ranges.add(new Range(start, end)); } } catch (NumberFormatException e) { UndertowLogger.REQUEST_LOGGER.debugf("Invalid range spec %s", rangeHeader); return null; } } if(ranges.isEmpty()) { return null; } return new ByteRange(ranges); }
[ "public", "static", "ByteRange", "parse", "(", "String", "rangeHeader", ")", "{", "if", "(", "rangeHeader", "==", "null", "||", "rangeHeader", ".", "length", "(", ")", "<", "7", ")", "{", "return", "null", ";", "}", "if", "(", "!", "rangeHeader", ".", "startsWith", "(", "\"bytes=\"", ")", ")", "{", "return", "null", ";", "}", "List", "<", "Range", ">", "ranges", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "[", "]", "parts", "=", "rangeHeader", ".", "substring", "(", "6", ")", ".", "split", "(", "\",\"", ")", ";", "for", "(", "String", "part", ":", "parts", ")", "{", "try", "{", "int", "index", "=", "part", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "index", "==", "0", ")", "{", "//suffix range spec", "//represents the last N bytes", "//internally we represent this using a -1 as the start position", "long", "val", "=", "Long", ".", "parseLong", "(", "part", ".", "substring", "(", "1", ")", ")", ";", "if", "(", "val", "<", "0", ")", "{", "UndertowLogger", ".", "REQUEST_LOGGER", ".", "debugf", "(", "\"Invalid range spec %s\"", ",", "rangeHeader", ")", ";", "return", "null", ";", "}", "ranges", ".", "add", "(", "new", "Range", "(", "-", "1", ",", "val", ")", ")", ";", "}", "else", "{", "if", "(", "index", "==", "-", "1", ")", "{", "UndertowLogger", ".", "REQUEST_LOGGER", ".", "debugf", "(", "\"Invalid range spec %s\"", ",", "rangeHeader", ")", ";", "return", "null", ";", "}", "long", "start", "=", "Long", ".", "parseLong", "(", "part", ".", "substring", "(", "0", ",", "index", ")", ")", ";", "if", "(", "start", "<", "0", ")", "{", "UndertowLogger", ".", "REQUEST_LOGGER", ".", "debugf", "(", "\"Invalid range spec %s\"", ",", "rangeHeader", ")", ";", "return", "null", ";", "}", "long", "end", ";", "if", "(", "index", "+", "1", "<", "part", ".", "length", "(", ")", ")", "{", "end", "=", "Long", ".", "parseLong", "(", "part", ".", "substring", "(", "index", "+", "1", ")", ")", ";", "}", "else", "{", "end", "=", "-", "1", ";", "}", "ranges", ".", "add", "(", "new", "Range", "(", "start", ",", "end", ")", ")", ";", "}", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "UndertowLogger", ".", "REQUEST_LOGGER", ".", "debugf", "(", "\"Invalid range spec %s\"", ",", "rangeHeader", ")", ";", "return", "null", ";", "}", "}", "if", "(", "ranges", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "new", "ByteRange", "(", "ranges", ")", ";", "}" ]
Attempts to parse a range request. If the range request is invalid it will just return null so that it may be ignored. @param rangeHeader The range spec @return A range spec, or null if the range header could not be parsed
[ "Attempts", "to", "parse", "a", "range", "request", ".", "If", "the", "range", "request", "is", "invalid", "it", "will", "just", "return", "null", "so", "that", "it", "may", "be", "ignored", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/ByteRange.java#L71-L120
16,654
undertow-io/undertow
core/src/main/java/io/undertow/util/ByteRange.java
ByteRange.getResponseResult
public RangeResponseResult getResponseResult(final long resourceContentLength, String ifRange, Date lastModified, String eTag) { if(ranges.isEmpty()) { return null; } long start = getStart(0); long end = getEnd(0); long rangeLength; if(ifRange != null && !ifRange.isEmpty()) { if(ifRange.charAt(0) == '"') { //entity tag if(eTag != null && !eTag.equals(ifRange)) { return null; } } else { Date ifDate = DateUtils.parseDate(ifRange); if(ifDate != null && lastModified != null && ifDate.getTime() < lastModified.getTime()) { return null; } } } if(start == -1 ) { //suffix range if(end < 0){ //ignore the range request return new RangeResponseResult(0, 0, 0, "bytes */" + resourceContentLength, StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE); } start = Math.max(resourceContentLength - end, 0); end = resourceContentLength - 1; rangeLength = resourceContentLength - start; } else if(end == -1) { //prefix range long toWrite = resourceContentLength - start; if(toWrite >= 0) { rangeLength = toWrite; } else { //ignore the range request return new RangeResponseResult(0, 0, 0, "bytes */" + resourceContentLength, StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE); } end = resourceContentLength - 1; } else { end = Math.min(end, resourceContentLength - 1); if(start >= resourceContentLength || start > end) { return new RangeResponseResult(0, 0, 0, "bytes */" + resourceContentLength, StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE); } rangeLength = end - start + 1; } return new RangeResponseResult(start, end, rangeLength, "bytes " + start + "-" + end + "/" + resourceContentLength, StatusCodes.PARTIAL_CONTENT); }
java
public RangeResponseResult getResponseResult(final long resourceContentLength, String ifRange, Date lastModified, String eTag) { if(ranges.isEmpty()) { return null; } long start = getStart(0); long end = getEnd(0); long rangeLength; if(ifRange != null && !ifRange.isEmpty()) { if(ifRange.charAt(0) == '"') { //entity tag if(eTag != null && !eTag.equals(ifRange)) { return null; } } else { Date ifDate = DateUtils.parseDate(ifRange); if(ifDate != null && lastModified != null && ifDate.getTime() < lastModified.getTime()) { return null; } } } if(start == -1 ) { //suffix range if(end < 0){ //ignore the range request return new RangeResponseResult(0, 0, 0, "bytes */" + resourceContentLength, StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE); } start = Math.max(resourceContentLength - end, 0); end = resourceContentLength - 1; rangeLength = resourceContentLength - start; } else if(end == -1) { //prefix range long toWrite = resourceContentLength - start; if(toWrite >= 0) { rangeLength = toWrite; } else { //ignore the range request return new RangeResponseResult(0, 0, 0, "bytes */" + resourceContentLength, StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE); } end = resourceContentLength - 1; } else { end = Math.min(end, resourceContentLength - 1); if(start >= resourceContentLength || start > end) { return new RangeResponseResult(0, 0, 0, "bytes */" + resourceContentLength, StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE); } rangeLength = end - start + 1; } return new RangeResponseResult(start, end, rangeLength, "bytes " + start + "-" + end + "/" + resourceContentLength, StatusCodes.PARTIAL_CONTENT); }
[ "public", "RangeResponseResult", "getResponseResult", "(", "final", "long", "resourceContentLength", ",", "String", "ifRange", ",", "Date", "lastModified", ",", "String", "eTag", ")", "{", "if", "(", "ranges", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "long", "start", "=", "getStart", "(", "0", ")", ";", "long", "end", "=", "getEnd", "(", "0", ")", ";", "long", "rangeLength", ";", "if", "(", "ifRange", "!=", "null", "&&", "!", "ifRange", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "ifRange", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "//entity tag", "if", "(", "eTag", "!=", "null", "&&", "!", "eTag", ".", "equals", "(", "ifRange", ")", ")", "{", "return", "null", ";", "}", "}", "else", "{", "Date", "ifDate", "=", "DateUtils", ".", "parseDate", "(", "ifRange", ")", ";", "if", "(", "ifDate", "!=", "null", "&&", "lastModified", "!=", "null", "&&", "ifDate", ".", "getTime", "(", ")", "<", "lastModified", ".", "getTime", "(", ")", ")", "{", "return", "null", ";", "}", "}", "}", "if", "(", "start", "==", "-", "1", ")", "{", "//suffix range", "if", "(", "end", "<", "0", ")", "{", "//ignore the range request", "return", "new", "RangeResponseResult", "(", "0", ",", "0", ",", "0", ",", "\"bytes */\"", "+", "resourceContentLength", ",", "StatusCodes", ".", "REQUEST_RANGE_NOT_SATISFIABLE", ")", ";", "}", "start", "=", "Math", ".", "max", "(", "resourceContentLength", "-", "end", ",", "0", ")", ";", "end", "=", "resourceContentLength", "-", "1", ";", "rangeLength", "=", "resourceContentLength", "-", "start", ";", "}", "else", "if", "(", "end", "==", "-", "1", ")", "{", "//prefix range", "long", "toWrite", "=", "resourceContentLength", "-", "start", ";", "if", "(", "toWrite", ">=", "0", ")", "{", "rangeLength", "=", "toWrite", ";", "}", "else", "{", "//ignore the range request", "return", "new", "RangeResponseResult", "(", "0", ",", "0", ",", "0", ",", "\"bytes */\"", "+", "resourceContentLength", ",", "StatusCodes", ".", "REQUEST_RANGE_NOT_SATISFIABLE", ")", ";", "}", "end", "=", "resourceContentLength", "-", "1", ";", "}", "else", "{", "end", "=", "Math", ".", "min", "(", "end", ",", "resourceContentLength", "-", "1", ")", ";", "if", "(", "start", ">=", "resourceContentLength", "||", "start", ">", "end", ")", "{", "return", "new", "RangeResponseResult", "(", "0", ",", "0", ",", "0", ",", "\"bytes */\"", "+", "resourceContentLength", ",", "StatusCodes", ".", "REQUEST_RANGE_NOT_SATISFIABLE", ")", ";", "}", "rangeLength", "=", "end", "-", "start", "+", "1", ";", "}", "return", "new", "RangeResponseResult", "(", "start", ",", "end", ",", "rangeLength", ",", "\"bytes \"", "+", "start", "+", "\"-\"", "+", "end", "+", "\"/\"", "+", "resourceContentLength", ",", "StatusCodes", ".", "PARTIAL_CONTENT", ")", ";", "}" ]
Returns a representation of the range result. If this returns null then a 200 response should be sent instead @param resourceContentLength @return
[ "Returns", "a", "representation", "of", "the", "range", "result", ".", "If", "this", "returns", "null", "then", "a", "200", "response", "should", "be", "sent", "instead" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/ByteRange.java#L127-L175
16,655
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java
Node.getLoad
public int getLoad() { final int status = this.state; if (anyAreSet(status, ERROR)) { return -1; } else if (anyAreSet(status, HOT_STANDBY)) { return 0; } else { return lbStatus.getLbFactor(); } }
java
public int getLoad() { final int status = this.state; if (anyAreSet(status, ERROR)) { return -1; } else if (anyAreSet(status, HOT_STANDBY)) { return 0; } else { return lbStatus.getLbFactor(); } }
[ "public", "int", "getLoad", "(", ")", "{", "final", "int", "status", "=", "this", ".", "state", ";", "if", "(", "anyAreSet", "(", "status", ",", "ERROR", ")", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "anyAreSet", "(", "status", ",", "HOT_STANDBY", ")", ")", "{", "return", "0", ";", "}", "else", "{", "return", "lbStatus", ".", "getLbFactor", "(", ")", ";", "}", "}" ]
Get the load information. Add the error information for clients. @return the node load
[ "Get", "the", "load", "information", ".", "Add", "the", "error", "information", "for", "clients", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java#L140-L149
16,656
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java
Node.checkHealth
protected void checkHealth(long threshold, NodeHealthChecker healthChecker) { final int state = this.state; if (anyAreSet(state, REMOVED | ACTIVE_PING)) { return; } healthCheckPing(threshold, healthChecker); }
java
protected void checkHealth(long threshold, NodeHealthChecker healthChecker) { final int state = this.state; if (anyAreSet(state, REMOVED | ACTIVE_PING)) { return; } healthCheckPing(threshold, healthChecker); }
[ "protected", "void", "checkHealth", "(", "long", "threshold", ",", "NodeHealthChecker", "healthChecker", ")", "{", "final", "int", "state", "=", "this", ".", "state", ";", "if", "(", "anyAreSet", "(", "state", ",", "REMOVED", "|", "ACTIVE_PING", ")", ")", "{", "return", ";", "}", "healthCheckPing", "(", "threshold", ",", "healthChecker", ")", ";", "}" ]
Check the health of the node and try to ping it if necessary. @param threshold the threshold after which the node should be removed @param healthChecker the node health checker
[ "Check", "the", "health", "of", "the", "node", "and", "try", "to", "ping", "it", "if", "necessary", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java#L189-L195
16,657
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java
Node.ping
void ping(final HttpServerExchange exchange, final NodePingUtil.PingCallback callback) { NodePingUtil.pingNode(this, exchange, callback); }
java
void ping(final HttpServerExchange exchange, final NodePingUtil.PingCallback callback) { NodePingUtil.pingNode(this, exchange, callback); }
[ "void", "ping", "(", "final", "HttpServerExchange", "exchange", ",", "final", "NodePingUtil", ".", "PingCallback", "callback", ")", "{", "NodePingUtil", ".", "pingNode", "(", "this", ",", "exchange", ",", "callback", ")", ";", "}" ]
Async ping from the user @param exchange the http server exchange @param callback the ping callback
[ "Async", "ping", "from", "the", "user" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java#L241-L243
16,658
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java
Node.registerContext
Context registerContext(final String path, final List<String> virtualHosts) { VHostMapping host = null; for (final VHostMapping vhost : vHosts) { if (virtualHosts.equals(vhost.getAliases())) { host = vhost; break; } } if (host == null) { host = new VHostMapping(this, virtualHosts); vHosts.add(host); } final Context context = new Context(path, host, this); contexts.add(context); return context; }
java
Context registerContext(final String path, final List<String> virtualHosts) { VHostMapping host = null; for (final VHostMapping vhost : vHosts) { if (virtualHosts.equals(vhost.getAliases())) { host = vhost; break; } } if (host == null) { host = new VHostMapping(this, virtualHosts); vHosts.add(host); } final Context context = new Context(path, host, this); contexts.add(context); return context; }
[ "Context", "registerContext", "(", "final", "String", "path", ",", "final", "List", "<", "String", ">", "virtualHosts", ")", "{", "VHostMapping", "host", "=", "null", ";", "for", "(", "final", "VHostMapping", "vhost", ":", "vHosts", ")", "{", "if", "(", "virtualHosts", ".", "equals", "(", "vhost", ".", "getAliases", "(", ")", ")", ")", "{", "host", "=", "vhost", ";", "break", ";", "}", "}", "if", "(", "host", "==", "null", ")", "{", "host", "=", "new", "VHostMapping", "(", "this", ",", "virtualHosts", ")", ";", "vHosts", ".", "add", "(", "host", ")", ";", "}", "final", "Context", "context", "=", "new", "Context", "(", "path", ",", "host", ",", "this", ")", ";", "contexts", ".", "add", "(", "context", ")", ";", "return", "context", ";", "}" ]
Register a context. @param path the context path @return the created context
[ "Register", "a", "context", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java#L251-L266
16,659
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java
Node.getContext
Context getContext(final String path, List<String> aliases) { VHostMapping host = null; for (final VHostMapping vhost : vHosts) { if (aliases.equals(vhost.getAliases())) { host = vhost; break; } } if (host == null) { return null; } for (final Context context : contexts) { if (context.getPath().equals(path) && context.getVhost() == host) { return context; } } return null; }
java
Context getContext(final String path, List<String> aliases) { VHostMapping host = null; for (final VHostMapping vhost : vHosts) { if (aliases.equals(vhost.getAliases())) { host = vhost; break; } } if (host == null) { return null; } for (final Context context : contexts) { if (context.getPath().equals(path) && context.getVhost() == host) { return context; } } return null; }
[ "Context", "getContext", "(", "final", "String", "path", ",", "List", "<", "String", ">", "aliases", ")", "{", "VHostMapping", "host", "=", "null", ";", "for", "(", "final", "VHostMapping", "vhost", ":", "vHosts", ")", "{", "if", "(", "aliases", ".", "equals", "(", "vhost", ".", "getAliases", "(", ")", ")", ")", "{", "host", "=", "vhost", ";", "break", ";", "}", "}", "if", "(", "host", "==", "null", ")", "{", "return", "null", ";", "}", "for", "(", "final", "Context", "context", ":", "contexts", ")", "{", "if", "(", "context", ".", "getPath", "(", ")", ".", "equals", "(", "path", ")", "&&", "context", ".", "getVhost", "(", ")", "==", "host", ")", "{", "return", "context", ";", "}", "}", "return", "null", ";", "}" ]
Get a context. @param path the context path @param aliases the aliases @return the context, {@code null} if there is no matching context
[ "Get", "a", "context", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java#L275-L292
16,660
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java
Node.healthCheckFailed
private int healthCheckFailed() { int oldState, newState; for (;;) { oldState = this.state; if ((oldState & ERROR) != ERROR) { newState = oldState | ERROR; UndertowLogger.ROOT_LOGGER.nodeIsInError(jvmRoute); } else if ((oldState & ERROR_MASK) == ERROR_MASK) { return ERROR_MASK; } else { newState = oldState +1; } if (stateUpdater.compareAndSet(this, oldState, newState)) { return newState & ERROR_MASK; } } }
java
private int healthCheckFailed() { int oldState, newState; for (;;) { oldState = this.state; if ((oldState & ERROR) != ERROR) { newState = oldState | ERROR; UndertowLogger.ROOT_LOGGER.nodeIsInError(jvmRoute); } else if ((oldState & ERROR_MASK) == ERROR_MASK) { return ERROR_MASK; } else { newState = oldState +1; } if (stateUpdater.compareAndSet(this, oldState, newState)) { return newState & ERROR_MASK; } } }
[ "private", "int", "healthCheckFailed", "(", ")", "{", "int", "oldState", ",", "newState", ";", "for", "(", ";", ";", ")", "{", "oldState", "=", "this", ".", "state", ";", "if", "(", "(", "oldState", "&", "ERROR", ")", "!=", "ERROR", ")", "{", "newState", "=", "oldState", "|", "ERROR", ";", "UndertowLogger", ".", "ROOT_LOGGER", ".", "nodeIsInError", "(", "jvmRoute", ")", ";", "}", "else", "if", "(", "(", "oldState", "&", "ERROR_MASK", ")", "==", "ERROR_MASK", ")", "{", "return", "ERROR_MASK", ";", "}", "else", "{", "newState", "=", "oldState", "+", "1", ";", "}", "if", "(", "stateUpdater", ".", "compareAndSet", "(", "this", ",", "oldState", ",", "newState", ")", ")", "{", "return", "newState", "&", "ERROR_MASK", ";", "}", "}", "}" ]
Mark a node in error. Mod_cluster has a threshold after which broken nodes get removed. @return
[ "Mark", "a", "node", "in", "error", ".", "Mod_cluster", "has", "a", "threshold", "after", "which", "broken", "nodes", "get", "removed", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/Node.java#L386-L402
16,661
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http/HttpTransferEncoding.java
HttpTransferEncoding.parsePositiveLong
public static long parsePositiveLong(String str) { long value = 0; final int length = str.length(); if (length == 0) { throw new NumberFormatException(str); } long multiplier = 1; for (int i = length - 1; i >= 0; --i) { char c = str.charAt(i); if (c < '0' || c > '9') { throw new NumberFormatException(str); } long digit = c - '0'; value += digit * multiplier; multiplier *= 10; } return value; }
java
public static long parsePositiveLong(String str) { long value = 0; final int length = str.length(); if (length == 0) { throw new NumberFormatException(str); } long multiplier = 1; for (int i = length - 1; i >= 0; --i) { char c = str.charAt(i); if (c < '0' || c > '9') { throw new NumberFormatException(str); } long digit = c - '0'; value += digit * multiplier; multiplier *= 10; } return value; }
[ "public", "static", "long", "parsePositiveLong", "(", "String", "str", ")", "{", "long", "value", "=", "0", ";", "final", "int", "length", "=", "str", ".", "length", "(", ")", ";", "if", "(", "length", "==", "0", ")", "{", "throw", "new", "NumberFormatException", "(", "str", ")", ";", "}", "long", "multiplier", "=", "1", ";", "for", "(", "int", "i", "=", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "char", "c", "=", "str", ".", "charAt", "(", "i", ")", ";", "if", "(", "c", "<", "'", "'", "||", "c", ">", "'", "'", ")", "{", "throw", "new", "NumberFormatException", "(", "str", ")", ";", "}", "long", "digit", "=", "c", "-", "'", "'", ";", "value", "+=", "digit", "*", "multiplier", ";", "multiplier", "*=", "10", ";", "}", "return", "value", ";", "}" ]
fast long parsing algorithm @param str The string @return The long
[ "fast", "long", "parsing", "algorithm" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http/HttpTransferEncoding.java#L332-L352
16,662
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/handlers/ServletChain.java
ServletChain.forceInit
void forceInit(DispatcherType dispatcherType) throws ServletException { if(filters != null) { List<ManagedFilter> list = filters.get(dispatcherType); if(list != null && !list.isEmpty()) { for(int i = 0; i < list.size(); ++i) { ManagedFilter filter = list.get(i); filter.forceInit(); } } } managedServlet.forceInit(); }
java
void forceInit(DispatcherType dispatcherType) throws ServletException { if(filters != null) { List<ManagedFilter> list = filters.get(dispatcherType); if(list != null && !list.isEmpty()) { for(int i = 0; i < list.size(); ++i) { ManagedFilter filter = list.get(i); filter.forceInit(); } } } managedServlet.forceInit(); }
[ "void", "forceInit", "(", "DispatcherType", "dispatcherType", ")", "throws", "ServletException", "{", "if", "(", "filters", "!=", "null", ")", "{", "List", "<", "ManagedFilter", ">", "list", "=", "filters", ".", "get", "(", "dispatcherType", ")", ";", "if", "(", "list", "!=", "null", "&&", "!", "list", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "list", ".", "size", "(", ")", ";", "++", "i", ")", "{", "ManagedFilter", "filter", "=", "list", ".", "get", "(", "i", ")", ";", "filter", ".", "forceInit", "(", ")", ";", "}", "}", "}", "managedServlet", ".", "forceInit", "(", ")", ";", "}" ]
see UNDERTOW-1132
[ "see", "UNDERTOW", "-", "1132" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/handlers/ServletChain.java#L120-L131
16,663
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http/HttpServerConnection.java
HttpServerConnection.ungetRequestBytes
public void ungetRequestBytes(final PooledByteBuffer unget) { if (getExtraBytes() == null) { setExtraBytes(unget); } else { PooledByteBuffer eb = getExtraBytes(); ByteBuffer buf = eb.getBuffer(); final ByteBuffer ugBuffer = unget.getBuffer(); if (ugBuffer.limit() - ugBuffer.remaining() > buf.remaining()) { //stuff the existing data after the data we are ungetting ugBuffer.compact(); ugBuffer.put(buf); ugBuffer.flip(); eb.close(); setExtraBytes(unget); } else { //TODO: this is horrible, but should not happen often final byte[] data = new byte[ugBuffer.remaining() + buf.remaining()]; int first = ugBuffer.remaining(); ugBuffer.get(data, 0, ugBuffer.remaining()); buf.get(data, first, buf.remaining()); eb.close(); unget.close(); final ByteBuffer newBuffer = ByteBuffer.wrap(data); setExtraBytes(new ImmediatePooledByteBuffer(newBuffer)); } } }
java
public void ungetRequestBytes(final PooledByteBuffer unget) { if (getExtraBytes() == null) { setExtraBytes(unget); } else { PooledByteBuffer eb = getExtraBytes(); ByteBuffer buf = eb.getBuffer(); final ByteBuffer ugBuffer = unget.getBuffer(); if (ugBuffer.limit() - ugBuffer.remaining() > buf.remaining()) { //stuff the existing data after the data we are ungetting ugBuffer.compact(); ugBuffer.put(buf); ugBuffer.flip(); eb.close(); setExtraBytes(unget); } else { //TODO: this is horrible, but should not happen often final byte[] data = new byte[ugBuffer.remaining() + buf.remaining()]; int first = ugBuffer.remaining(); ugBuffer.get(data, 0, ugBuffer.remaining()); buf.get(data, first, buf.remaining()); eb.close(); unget.close(); final ByteBuffer newBuffer = ByteBuffer.wrap(data); setExtraBytes(new ImmediatePooledByteBuffer(newBuffer)); } } }
[ "public", "void", "ungetRequestBytes", "(", "final", "PooledByteBuffer", "unget", ")", "{", "if", "(", "getExtraBytes", "(", ")", "==", "null", ")", "{", "setExtraBytes", "(", "unget", ")", ";", "}", "else", "{", "PooledByteBuffer", "eb", "=", "getExtraBytes", "(", ")", ";", "ByteBuffer", "buf", "=", "eb", ".", "getBuffer", "(", ")", ";", "final", "ByteBuffer", "ugBuffer", "=", "unget", ".", "getBuffer", "(", ")", ";", "if", "(", "ugBuffer", ".", "limit", "(", ")", "-", "ugBuffer", ".", "remaining", "(", ")", ">", "buf", ".", "remaining", "(", ")", ")", "{", "//stuff the existing data after the data we are ungetting", "ugBuffer", ".", "compact", "(", ")", ";", "ugBuffer", ".", "put", "(", "buf", ")", ";", "ugBuffer", ".", "flip", "(", ")", ";", "eb", ".", "close", "(", ")", ";", "setExtraBytes", "(", "unget", ")", ";", "}", "else", "{", "//TODO: this is horrible, but should not happen often", "final", "byte", "[", "]", "data", "=", "new", "byte", "[", "ugBuffer", ".", "remaining", "(", ")", "+", "buf", ".", "remaining", "(", ")", "]", ";", "int", "first", "=", "ugBuffer", ".", "remaining", "(", ")", ";", "ugBuffer", ".", "get", "(", "data", ",", "0", ",", "ugBuffer", ".", "remaining", "(", ")", ")", ";", "buf", ".", "get", "(", "data", ",", "first", ",", "buf", ".", "remaining", "(", ")", ")", ";", "eb", ".", "close", "(", ")", ";", "unget", ".", "close", "(", ")", ";", "final", "ByteBuffer", "newBuffer", "=", "ByteBuffer", ".", "wrap", "(", "data", ")", ";", "setExtraBytes", "(", "new", "ImmediatePooledByteBuffer", "(", "newBuffer", ")", ")", ";", "}", "}", "}" ]
Pushes back the given data. This should only be used by transfer coding handlers that have read past the end of the request when handling pipelined requests @param unget The buffer to push back
[ "Pushes", "back", "the", "given", "data", ".", "This", "should", "only", "be", "used", "by", "transfer", "coding", "handlers", "that", "have", "read", "past", "the", "end", "of", "the", "request", "when", "handling", "pipelined", "requests" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http/HttpServerConnection.java#L147-L174
16,664
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/spec/AsyncContextImpl.java
AsyncContextImpl.initialRequestDone
public synchronized void initialRequestDone() { initialRequestDone = true; if (previousAsyncContext != null) { previousAsyncContext.onAsyncStart(this); previousAsyncContext = null; } if (!processingAsyncTask) { processAsyncTask(); } initiatingThread = null; }
java
public synchronized void initialRequestDone() { initialRequestDone = true; if (previousAsyncContext != null) { previousAsyncContext.onAsyncStart(this); previousAsyncContext = null; } if (!processingAsyncTask) { processAsyncTask(); } initiatingThread = null; }
[ "public", "synchronized", "void", "initialRequestDone", "(", ")", "{", "initialRequestDone", "=", "true", ";", "if", "(", "previousAsyncContext", "!=", "null", ")", "{", "previousAsyncContext", ".", "onAsyncStart", "(", "this", ")", ";", "previousAsyncContext", "=", "null", ";", "}", "if", "(", "!", "processingAsyncTask", ")", "{", "processAsyncTask", "(", ")", ";", "}", "initiatingThread", "=", "null", ";", "}" ]
Called by the container when the initial request is finished. If this request has a dispatch or complete call pending then this will be started.
[ "Called", "by", "the", "container", "when", "the", "initial", "request", "is", "finished", ".", "If", "this", "request", "has", "a", "dispatch", "or", "complete", "call", "pending", "then", "this", "will", "be", "started", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/spec/AsyncContextImpl.java#L459-L469
16,665
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/JDBCLogHandler.java
JDBCLogHandler.run
@Override public void run() { if (!stateUpdater.compareAndSet(this, 1, 2)) { return; } List<JDBCLogAttribute> messages = new ArrayList<>(); JDBCLogAttribute msg = null; //only grab at most 1000 messages at a time for (int i = 0; i < 1000; ++i) { msg = pendingMessages.poll(); if (msg == null) { break; } messages.add(msg); } try { if (!messages.isEmpty()) { writeMessage(messages); } } finally { Executor executor = this.executor; stateUpdater.set(this, 0); //check to see if there is still more messages //if so then run this again if (!pendingMessages.isEmpty()) { if (stateUpdater.compareAndSet(this, 0, 1)) { executor.execute(this); } } } }
java
@Override public void run() { if (!stateUpdater.compareAndSet(this, 1, 2)) { return; } List<JDBCLogAttribute> messages = new ArrayList<>(); JDBCLogAttribute msg = null; //only grab at most 1000 messages at a time for (int i = 0; i < 1000; ++i) { msg = pendingMessages.poll(); if (msg == null) { break; } messages.add(msg); } try { if (!messages.isEmpty()) { writeMessage(messages); } } finally { Executor executor = this.executor; stateUpdater.set(this, 0); //check to see if there is still more messages //if so then run this again if (!pendingMessages.isEmpty()) { if (stateUpdater.compareAndSet(this, 0, 1)) { executor.execute(this); } } } }
[ "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "!", "stateUpdater", ".", "compareAndSet", "(", "this", ",", "1", ",", "2", ")", ")", "{", "return", ";", "}", "List", "<", "JDBCLogAttribute", ">", "messages", "=", "new", "ArrayList", "<>", "(", ")", ";", "JDBCLogAttribute", "msg", "=", "null", ";", "//only grab at most 1000 messages at a time", "for", "(", "int", "i", "=", "0", ";", "i", "<", "1000", ";", "++", "i", ")", "{", "msg", "=", "pendingMessages", ".", "poll", "(", ")", ";", "if", "(", "msg", "==", "null", ")", "{", "break", ";", "}", "messages", ".", "add", "(", "msg", ")", ";", "}", "try", "{", "if", "(", "!", "messages", ".", "isEmpty", "(", ")", ")", "{", "writeMessage", "(", "messages", ")", ";", "}", "}", "finally", "{", "Executor", "executor", "=", "this", ".", "executor", ";", "stateUpdater", ".", "set", "(", "this", ",", "0", ")", ";", "//check to see if there is still more messages", "//if so then run this again", "if", "(", "!", "pendingMessages", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "stateUpdater", ".", "compareAndSet", "(", "this", ",", "0", ",", "1", ")", ")", "{", "executor", ".", "execute", "(", "this", ")", ";", "}", "}", "}", "}" ]
insert the log record to database
[ "insert", "the", "log", "record", "to", "database" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/JDBCLogHandler.java#L167-L199
16,666
undertow-io/undertow
core/src/main/java/io/undertow/util/CopyOnWriteMap.java
CopyOnWriteMap.putInternal
private V putInternal(final K key, final V value) { final Map<K, V> delegate = new HashMap<>(this.delegate); V existing = delegate.put(key, value); this.delegate = delegate; return existing; }
java
private V putInternal(final K key, final V value) { final Map<K, V> delegate = new HashMap<>(this.delegate); V existing = delegate.put(key, value); this.delegate = delegate; return existing; }
[ "private", "V", "putInternal", "(", "final", "K", "key", ",", "final", "V", "value", ")", "{", "final", "Map", "<", "K", ",", "V", ">", "delegate", "=", "new", "HashMap", "<>", "(", "this", ".", "delegate", ")", ";", "V", "existing", "=", "delegate", ".", "put", "(", "key", ",", "value", ")", ";", "this", ".", "delegate", "=", "delegate", ";", "return", "existing", ";", "}" ]
must be called under lock
[ "must", "be", "called", "under", "lock" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/CopyOnWriteMap.java#L157-L162
16,667
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/protocol/version07/UTF8Checker.java
UTF8Checker.checkUTF8
private void checkUTF8(ByteBuffer buf, int position, int length) throws UnsupportedEncodingException { int limit = position + length; for (int i = position; i < limit; i++) { checkUTF8(buf.get(i)); } }
java
private void checkUTF8(ByteBuffer buf, int position, int length) throws UnsupportedEncodingException { int limit = position + length; for (int i = position; i < limit; i++) { checkUTF8(buf.get(i)); } }
[ "private", "void", "checkUTF8", "(", "ByteBuffer", "buf", ",", "int", "position", ",", "int", "length", ")", "throws", "UnsupportedEncodingException", "{", "int", "limit", "=", "position", "+", "length", ";", "for", "(", "int", "i", "=", "position", ";", "i", "<", "limit", ";", "i", "++", ")", "{", "checkUTF8", "(", "buf", ".", "get", "(", "i", ")", ")", ";", "}", "}" ]
Check if the given ByteBuffer contains non UTF-8 data. @param buf the ByteBuffer to check @param position the index in the {@link ByteBuffer} to start from @param length the number of bytes to operate on @throws UnsupportedEncodingException is thrown if non UTF-8 data is found
[ "Check", "if", "the", "given", "ByteBuffer", "contains", "non", "UTF", "-", "8", "data", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/protocol/version07/UTF8Checker.java#L78-L83
16,668
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/handlers/security/SecurityPathMatches.java
SecurityPathMatches.mergeConstraints
private SingleConstraintMatch mergeConstraints(final RuntimeMatch currentMatch) { if (currentMatch.uncovered && denyUncoveredHttpMethods) { return new SingleConstraintMatch(SecurityInfo.EmptyRoleSemantic.DENY, Collections.<String>emptySet()); } final Set<String> allowedRoles = new HashSet<>(); for (SingleConstraintMatch match : currentMatch.constraints) { if (match.getRequiredRoles().isEmpty()) { return new SingleConstraintMatch(match.getEmptyRoleSemantic(), Collections.<String>emptySet()); } else { allowedRoles.addAll(match.getRequiredRoles()); } } return new SingleConstraintMatch(SecurityInfo.EmptyRoleSemantic.PERMIT, allowedRoles); }
java
private SingleConstraintMatch mergeConstraints(final RuntimeMatch currentMatch) { if (currentMatch.uncovered && denyUncoveredHttpMethods) { return new SingleConstraintMatch(SecurityInfo.EmptyRoleSemantic.DENY, Collections.<String>emptySet()); } final Set<String> allowedRoles = new HashSet<>(); for (SingleConstraintMatch match : currentMatch.constraints) { if (match.getRequiredRoles().isEmpty()) { return new SingleConstraintMatch(match.getEmptyRoleSemantic(), Collections.<String>emptySet()); } else { allowedRoles.addAll(match.getRequiredRoles()); } } return new SingleConstraintMatch(SecurityInfo.EmptyRoleSemantic.PERMIT, allowedRoles); }
[ "private", "SingleConstraintMatch", "mergeConstraints", "(", "final", "RuntimeMatch", "currentMatch", ")", "{", "if", "(", "currentMatch", ".", "uncovered", "&&", "denyUncoveredHttpMethods", ")", "{", "return", "new", "SingleConstraintMatch", "(", "SecurityInfo", ".", "EmptyRoleSemantic", ".", "DENY", ",", "Collections", ".", "<", "String", ">", "emptySet", "(", ")", ")", ";", "}", "final", "Set", "<", "String", ">", "allowedRoles", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "SingleConstraintMatch", "match", ":", "currentMatch", ".", "constraints", ")", "{", "if", "(", "match", ".", "getRequiredRoles", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "new", "SingleConstraintMatch", "(", "match", ".", "getEmptyRoleSemantic", "(", ")", ",", "Collections", ".", "<", "String", ">", "emptySet", "(", ")", ")", ";", "}", "else", "{", "allowedRoles", ".", "addAll", "(", "match", ".", "getRequiredRoles", "(", ")", ")", ";", "}", "}", "return", "new", "SingleConstraintMatch", "(", "SecurityInfo", ".", "EmptyRoleSemantic", ".", "PERMIT", ",", "allowedRoles", ")", ";", "}" ]
merge all constraints, as per 13.8.1 Combining Constraints
[ "merge", "all", "constraints", "as", "per", "13", ".", "8", ".", "1", "Combining", "Constraints" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/handlers/security/SecurityPathMatches.java#L148-L161
16,669
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/URLDecodingHandler.java
URLDecodingHandler.shouldDecode
private static boolean shouldDecode(final HttpServerExchange exchange) { return !exchange.getConnection().getUndertowOptions().get(UndertowOptions.DECODE_URL, true) && exchange.putAttachment(ALREADY_DECODED, Boolean.TRUE) == null; }
java
private static boolean shouldDecode(final HttpServerExchange exchange) { return !exchange.getConnection().getUndertowOptions().get(UndertowOptions.DECODE_URL, true) && exchange.putAttachment(ALREADY_DECODED, Boolean.TRUE) == null; }
[ "private", "static", "boolean", "shouldDecode", "(", "final", "HttpServerExchange", "exchange", ")", "{", "return", "!", "exchange", ".", "getConnection", "(", ")", ".", "getUndertowOptions", "(", ")", ".", "get", "(", "UndertowOptions", ".", "DECODE_URL", ",", "true", ")", "&&", "exchange", ".", "putAttachment", "(", "ALREADY_DECODED", ",", "Boolean", ".", "TRUE", ")", "==", "null", ";", "}" ]
attachment so that subsequent invocations will always return false.
[ "attachment", "so", "that", "subsequent", "invocations", "will", "always", "return", "false", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/URLDecodingHandler.java#L73-L76
16,670
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http2/Http2ReceiveListener.java
Http2ReceiveListener.handleInitialRequest
void handleInitialRequest(HttpServerExchange initial, Http2Channel channel, byte[] data) { //we have a request Http2HeadersStreamSinkChannel sink = channel.createInitialUpgradeResponseStream(); final Http2ServerConnection connection = new Http2ServerConnection(channel, sink, undertowOptions, bufferSize, rootHandler); HeaderMap requestHeaders = new HeaderMap(); for(HeaderValues hv : initial.getRequestHeaders()) { requestHeaders.putAll(hv.getHeaderName(), hv); } final HttpServerExchange exchange = new HttpServerExchange(connection, requestHeaders, sink.getHeaders(), maxEntitySize); if(initial.getRequestHeaders().contains(Headers.EXPECT)) { HttpContinue.markContinueResponseSent(exchange); } if(initial.getAttachment(HttpAttachments.REQUEST_TRAILERS) != null) { exchange.putAttachment(HttpAttachments.REQUEST_TRAILERS, initial.getAttachment(HttpAttachments.REQUEST_TRAILERS)); } Connectors.setRequestStartTime(initial, exchange); connection.setExchange(exchange); exchange.setRequestScheme(initial.getRequestScheme()); exchange.setRequestMethod(initial.getRequestMethod()); exchange.setQueryString(initial.getQueryString()); if(data != null) { Connectors.ungetRequestBytes(exchange, new ImmediatePooledByteBuffer(ByteBuffer.wrap(data))); } else { Connectors.terminateRequest(exchange); } String uri = exchange.getQueryString().isEmpty() ? initial.getRequestURI() : initial.getRequestURI() + '?' + exchange.getQueryString(); try { Connectors.setExchangeRequestPath(exchange, uri, encoding, decode, allowEncodingSlash, decodeBuffer, maxParameters); } catch (ParameterLimitException e) { exchange.setStatusCode(StatusCodes.BAD_REQUEST); exchange.endExchange(); return; } handleCommonSetup(sink, exchange, connection); Connectors.executeRootHandler(rootHandler, exchange); }
java
void handleInitialRequest(HttpServerExchange initial, Http2Channel channel, byte[] data) { //we have a request Http2HeadersStreamSinkChannel sink = channel.createInitialUpgradeResponseStream(); final Http2ServerConnection connection = new Http2ServerConnection(channel, sink, undertowOptions, bufferSize, rootHandler); HeaderMap requestHeaders = new HeaderMap(); for(HeaderValues hv : initial.getRequestHeaders()) { requestHeaders.putAll(hv.getHeaderName(), hv); } final HttpServerExchange exchange = new HttpServerExchange(connection, requestHeaders, sink.getHeaders(), maxEntitySize); if(initial.getRequestHeaders().contains(Headers.EXPECT)) { HttpContinue.markContinueResponseSent(exchange); } if(initial.getAttachment(HttpAttachments.REQUEST_TRAILERS) != null) { exchange.putAttachment(HttpAttachments.REQUEST_TRAILERS, initial.getAttachment(HttpAttachments.REQUEST_TRAILERS)); } Connectors.setRequestStartTime(initial, exchange); connection.setExchange(exchange); exchange.setRequestScheme(initial.getRequestScheme()); exchange.setRequestMethod(initial.getRequestMethod()); exchange.setQueryString(initial.getQueryString()); if(data != null) { Connectors.ungetRequestBytes(exchange, new ImmediatePooledByteBuffer(ByteBuffer.wrap(data))); } else { Connectors.terminateRequest(exchange); } String uri = exchange.getQueryString().isEmpty() ? initial.getRequestURI() : initial.getRequestURI() + '?' + exchange.getQueryString(); try { Connectors.setExchangeRequestPath(exchange, uri, encoding, decode, allowEncodingSlash, decodeBuffer, maxParameters); } catch (ParameterLimitException e) { exchange.setStatusCode(StatusCodes.BAD_REQUEST); exchange.endExchange(); return; } handleCommonSetup(sink, exchange, connection); Connectors.executeRootHandler(rootHandler, exchange); }
[ "void", "handleInitialRequest", "(", "HttpServerExchange", "initial", ",", "Http2Channel", "channel", ",", "byte", "[", "]", "data", ")", "{", "//we have a request", "Http2HeadersStreamSinkChannel", "sink", "=", "channel", ".", "createInitialUpgradeResponseStream", "(", ")", ";", "final", "Http2ServerConnection", "connection", "=", "new", "Http2ServerConnection", "(", "channel", ",", "sink", ",", "undertowOptions", ",", "bufferSize", ",", "rootHandler", ")", ";", "HeaderMap", "requestHeaders", "=", "new", "HeaderMap", "(", ")", ";", "for", "(", "HeaderValues", "hv", ":", "initial", ".", "getRequestHeaders", "(", ")", ")", "{", "requestHeaders", ".", "putAll", "(", "hv", ".", "getHeaderName", "(", ")", ",", "hv", ")", ";", "}", "final", "HttpServerExchange", "exchange", "=", "new", "HttpServerExchange", "(", "connection", ",", "requestHeaders", ",", "sink", ".", "getHeaders", "(", ")", ",", "maxEntitySize", ")", ";", "if", "(", "initial", ".", "getRequestHeaders", "(", ")", ".", "contains", "(", "Headers", ".", "EXPECT", ")", ")", "{", "HttpContinue", ".", "markContinueResponseSent", "(", "exchange", ")", ";", "}", "if", "(", "initial", ".", "getAttachment", "(", "HttpAttachments", ".", "REQUEST_TRAILERS", ")", "!=", "null", ")", "{", "exchange", ".", "putAttachment", "(", "HttpAttachments", ".", "REQUEST_TRAILERS", ",", "initial", ".", "getAttachment", "(", "HttpAttachments", ".", "REQUEST_TRAILERS", ")", ")", ";", "}", "Connectors", ".", "setRequestStartTime", "(", "initial", ",", "exchange", ")", ";", "connection", ".", "setExchange", "(", "exchange", ")", ";", "exchange", ".", "setRequestScheme", "(", "initial", ".", "getRequestScheme", "(", ")", ")", ";", "exchange", ".", "setRequestMethod", "(", "initial", ".", "getRequestMethod", "(", ")", ")", ";", "exchange", ".", "setQueryString", "(", "initial", ".", "getQueryString", "(", ")", ")", ";", "if", "(", "data", "!=", "null", ")", "{", "Connectors", ".", "ungetRequestBytes", "(", "exchange", ",", "new", "ImmediatePooledByteBuffer", "(", "ByteBuffer", ".", "wrap", "(", "data", ")", ")", ")", ";", "}", "else", "{", "Connectors", ".", "terminateRequest", "(", "exchange", ")", ";", "}", "String", "uri", "=", "exchange", ".", "getQueryString", "(", ")", ".", "isEmpty", "(", ")", "?", "initial", ".", "getRequestURI", "(", ")", ":", "initial", ".", "getRequestURI", "(", ")", "+", "'", "'", "+", "exchange", ".", "getQueryString", "(", ")", ";", "try", "{", "Connectors", ".", "setExchangeRequestPath", "(", "exchange", ",", "uri", ",", "encoding", ",", "decode", ",", "allowEncodingSlash", ",", "decodeBuffer", ",", "maxParameters", ")", ";", "}", "catch", "(", "ParameterLimitException", "e", ")", "{", "exchange", ".", "setStatusCode", "(", "StatusCodes", ".", "BAD_REQUEST", ")", ";", "exchange", ".", "endExchange", "(", ")", ";", "return", ";", "}", "handleCommonSetup", "(", "sink", ",", "exchange", ",", "connection", ")", ";", "Connectors", ".", "executeRootHandler", "(", "rootHandler", ",", "exchange", ")", ";", "}" ]
Handles the initial request when the exchange was started by a HTTP ugprade. @param initial The initial upgrade request that started the HTTP2 connection
[ "Handles", "the", "initial", "request", "when", "the", "exchange", "was", "started", "by", "a", "HTTP", "ugprade", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http2/Http2ReceiveListener.java#L224-L264
16,671
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http2/Http2ReceiveListener.java
Http2ReceiveListener.checkRequestHeaders
private boolean checkRequestHeaders(HeaderMap headers) { // :method pseudo-header must be present always exactly one time; // HTTP2 request MUST NOT contain 'connection' header if (headers.count(METHOD) != 1 || headers.contains(Headers.CONNECTION)) { return false; } // if CONNECT type is used, then we expect :method and :authority to be present only; // :scheme and :path must not be present if (headers.get(METHOD).contains(Methods.CONNECT_STRING)) { if (headers.contains(SCHEME) || headers.contains(PATH) || headers.count(AUTHORITY) != 1) { return false; } // For other HTTP methods we expect that :scheme, :method, and :path pseudo-headers are // present exactly one time. } else if (headers.count(SCHEME) != 1 || headers.count(PATH) != 1) { return false; } // HTTP2 request MAY contain TE header but if so, then only with 'trailers' value. if (headers.contains(Headers.TE)) { for (String value : headers.get(Headers.TE)) { if (!value.equals("trailers")) { return false; } } } return true; }
java
private boolean checkRequestHeaders(HeaderMap headers) { // :method pseudo-header must be present always exactly one time; // HTTP2 request MUST NOT contain 'connection' header if (headers.count(METHOD) != 1 || headers.contains(Headers.CONNECTION)) { return false; } // if CONNECT type is used, then we expect :method and :authority to be present only; // :scheme and :path must not be present if (headers.get(METHOD).contains(Methods.CONNECT_STRING)) { if (headers.contains(SCHEME) || headers.contains(PATH) || headers.count(AUTHORITY) != 1) { return false; } // For other HTTP methods we expect that :scheme, :method, and :path pseudo-headers are // present exactly one time. } else if (headers.count(SCHEME) != 1 || headers.count(PATH) != 1) { return false; } // HTTP2 request MAY contain TE header but if so, then only with 'trailers' value. if (headers.contains(Headers.TE)) { for (String value : headers.get(Headers.TE)) { if (!value.equals("trailers")) { return false; } } } return true; }
[ "private", "boolean", "checkRequestHeaders", "(", "HeaderMap", "headers", ")", "{", "// :method pseudo-header must be present always exactly one time;", "// HTTP2 request MUST NOT contain 'connection' header", "if", "(", "headers", ".", "count", "(", "METHOD", ")", "!=", "1", "||", "headers", ".", "contains", "(", "Headers", ".", "CONNECTION", ")", ")", "{", "return", "false", ";", "}", "// if CONNECT type is used, then we expect :method and :authority to be present only;", "// :scheme and :path must not be present", "if", "(", "headers", ".", "get", "(", "METHOD", ")", ".", "contains", "(", "Methods", ".", "CONNECT_STRING", ")", ")", "{", "if", "(", "headers", ".", "contains", "(", "SCHEME", ")", "||", "headers", ".", "contains", "(", "PATH", ")", "||", "headers", ".", "count", "(", "AUTHORITY", ")", "!=", "1", ")", "{", "return", "false", ";", "}", "// For other HTTP methods we expect that :scheme, :method, and :path pseudo-headers are", "// present exactly one time.", "}", "else", "if", "(", "headers", ".", "count", "(", "SCHEME", ")", "!=", "1", "||", "headers", ".", "count", "(", "PATH", ")", "!=", "1", ")", "{", "return", "false", ";", "}", "// HTTP2 request MAY contain TE header but if so, then only with 'trailers' value.", "if", "(", "headers", ".", "contains", "(", "Headers", ".", "TE", ")", ")", "{", "for", "(", "String", "value", ":", "headers", ".", "get", "(", "Headers", ".", "TE", ")", ")", "{", "if", "(", "!", "value", ".", "equals", "(", "\"trailers\"", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Performs HTTP2 specification compliance check for headers and pseudo-headers of a current request. @param headers map of the request headers @return true if check was successful, false otherwise
[ "Performs", "HTTP2", "specification", "compliance", "check", "for", "headers", "and", "pseudo", "-", "headers", "of", "a", "current", "request", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http2/Http2ReceiveListener.java#L305-L334
16,672
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2StreamSourceChannel.java
Http2StreamSourceChannel.updateContentSize
void updateContentSize(long frameLength, boolean last) { if(contentLengthRemaining != -1) { contentLengthRemaining -= frameLength; if(contentLengthRemaining < 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length exceeds content size", streamId, getFramedChannel()); getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR); } else if(last && contentLengthRemaining != 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length was less than content size", streamId, getFramedChannel()); getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR); } } }
java
void updateContentSize(long frameLength, boolean last) { if(contentLengthRemaining != -1) { contentLengthRemaining -= frameLength; if(contentLengthRemaining < 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length exceeds content size", streamId, getFramedChannel()); getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR); } else if(last && contentLengthRemaining != 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length was less than content size", streamId, getFramedChannel()); getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR); } } }
[ "void", "updateContentSize", "(", "long", "frameLength", ",", "boolean", "last", ")", "{", "if", "(", "contentLengthRemaining", "!=", "-", "1", ")", "{", "contentLengthRemaining", "-=", "frameLength", ";", "if", "(", "contentLengthRemaining", "<", "0", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "debugf", "(", "\"Closing stream %s on %s as data length exceeds content size\"", ",", "streamId", ",", "getFramedChannel", "(", ")", ")", ";", "getFramedChannel", "(", ")", ".", "sendRstStream", "(", "streamId", ",", "Http2Channel", ".", "ERROR_PROTOCOL_ERROR", ")", ";", "}", "else", "if", "(", "last", "&&", "contentLengthRemaining", "!=", "0", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "debugf", "(", "\"Closing stream %s on %s as data length was less than content size\"", ",", "streamId", ",", "getFramedChannel", "(", ")", ")", ";", "getFramedChannel", "(", ")", ".", "sendRstStream", "(", "streamId", ",", "Http2Channel", ".", "ERROR_PROTOCOL_ERROR", ")", ";", "}", "}", "}" ]
Checks that the actual content size matches the expected. We check this proactivly, rather than as the data is read @param frameLength The amount of data in the frame @param last If this is the last frame
[ "Checks", "that", "the", "actual", "content", "size", "matches", "the", "expected", ".", "We", "check", "this", "proactivly", "rather", "than", "as", "the", "data", "is", "read" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2StreamSourceChannel.java#L277-L288
16,673
undertow-io/undertow
core/src/main/java/io/undertow/conduits/FixedLengthStreamSourceConduit.java
FixedLengthStreamSourceConduit.exitRead
private void exitRead(long consumed) throws IOException { long oldVal = state; if(consumed == -1) { if (anyAreSet(oldVal, MASK_COUNT)) { invokeFinishListener(); state &= ~MASK_COUNT; throw UndertowMessages.MESSAGES.couldNotReadContentLengthData(); } return; } long newVal = oldVal - consumed; state = newVal; }
java
private void exitRead(long consumed) throws IOException { long oldVal = state; if(consumed == -1) { if (anyAreSet(oldVal, MASK_COUNT)) { invokeFinishListener(); state &= ~MASK_COUNT; throw UndertowMessages.MESSAGES.couldNotReadContentLengthData(); } return; } long newVal = oldVal - consumed; state = newVal; }
[ "private", "void", "exitRead", "(", "long", "consumed", ")", "throws", "IOException", "{", "long", "oldVal", "=", "state", ";", "if", "(", "consumed", "==", "-", "1", ")", "{", "if", "(", "anyAreSet", "(", "oldVal", ",", "MASK_COUNT", ")", ")", "{", "invokeFinishListener", "(", ")", ";", "state", "&=", "~", "MASK_COUNT", ";", "throw", "UndertowMessages", ".", "MESSAGES", ".", "couldNotReadContentLengthData", "(", ")", ";", "}", "return", ";", "}", "long", "newVal", "=", "oldVal", "-", "consumed", ";", "state", "=", "newVal", ";", "}" ]
Exit a read method. @param consumed the number of bytes consumed by this call (may be 0)
[ "Exit", "a", "read", "method", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/conduits/FixedLengthStreamSourceConduit.java#L332-L344
16,674
undertow-io/undertow
core/src/main/java/io/undertow/io/AsyncSenderImpl.java
AsyncSenderImpl.invokeOnComplete
private void invokeOnComplete() { for (; ; ) { if (pooledBuffers != null) { for (PooledByteBuffer buffer : pooledBuffers) { buffer.close(); } pooledBuffers = null; } IoCallback callback = this.callback; this.buffer = null; this.fileChannel = null; this.callback = null; inCallback = true; try { callback.onComplete(exchange, this); } finally { inCallback = false; } StreamSinkChannel channel = this.channel; if (this.buffer != null) { long t = Buffers.remaining(buffer); final long total = t; long written = 0; try { do { long res = channel.write(buffer); written += res; if (res == 0) { if(writeListener == null) { initWriteListener(); } channel.getWriteSetter().set(writeListener); channel.resumeWrites(); return; } } while (written < total); //we loop and invoke onComplete again } catch (IOException e) { invokeOnException(callback, e); } } else if (this.fileChannel != null) { if(transferTask == null) { transferTask = new TransferTask(); } if (!transferTask.run(false)) { return; } } else { return; } } }
java
private void invokeOnComplete() { for (; ; ) { if (pooledBuffers != null) { for (PooledByteBuffer buffer : pooledBuffers) { buffer.close(); } pooledBuffers = null; } IoCallback callback = this.callback; this.buffer = null; this.fileChannel = null; this.callback = null; inCallback = true; try { callback.onComplete(exchange, this); } finally { inCallback = false; } StreamSinkChannel channel = this.channel; if (this.buffer != null) { long t = Buffers.remaining(buffer); final long total = t; long written = 0; try { do { long res = channel.write(buffer); written += res; if (res == 0) { if(writeListener == null) { initWriteListener(); } channel.getWriteSetter().set(writeListener); channel.resumeWrites(); return; } } while (written < total); //we loop and invoke onComplete again } catch (IOException e) { invokeOnException(callback, e); } } else if (this.fileChannel != null) { if(transferTask == null) { transferTask = new TransferTask(); } if (!transferTask.run(false)) { return; } } else { return; } } }
[ "private", "void", "invokeOnComplete", "(", ")", "{", "for", "(", ";", ";", ")", "{", "if", "(", "pooledBuffers", "!=", "null", ")", "{", "for", "(", "PooledByteBuffer", "buffer", ":", "pooledBuffers", ")", "{", "buffer", ".", "close", "(", ")", ";", "}", "pooledBuffers", "=", "null", ";", "}", "IoCallback", "callback", "=", "this", ".", "callback", ";", "this", ".", "buffer", "=", "null", ";", "this", ".", "fileChannel", "=", "null", ";", "this", ".", "callback", "=", "null", ";", "inCallback", "=", "true", ";", "try", "{", "callback", ".", "onComplete", "(", "exchange", ",", "this", ")", ";", "}", "finally", "{", "inCallback", "=", "false", ";", "}", "StreamSinkChannel", "channel", "=", "this", ".", "channel", ";", "if", "(", "this", ".", "buffer", "!=", "null", ")", "{", "long", "t", "=", "Buffers", ".", "remaining", "(", "buffer", ")", ";", "final", "long", "total", "=", "t", ";", "long", "written", "=", "0", ";", "try", "{", "do", "{", "long", "res", "=", "channel", ".", "write", "(", "buffer", ")", ";", "written", "+=", "res", ";", "if", "(", "res", "==", "0", ")", "{", "if", "(", "writeListener", "==", "null", ")", "{", "initWriteListener", "(", ")", ";", "}", "channel", ".", "getWriteSetter", "(", ")", ".", "set", "(", "writeListener", ")", ";", "channel", ".", "resumeWrites", "(", ")", ";", "return", ";", "}", "}", "while", "(", "written", "<", "total", ")", ";", "//we loop and invoke onComplete again", "}", "catch", "(", "IOException", "e", ")", "{", "invokeOnException", "(", "callback", ",", "e", ")", ";", "}", "}", "else", "if", "(", "this", ".", "fileChannel", "!=", "null", ")", "{", "if", "(", "transferTask", "==", "null", ")", "{", "transferTask", "=", "new", "TransferTask", "(", ")", ";", "}", "if", "(", "!", "transferTask", ".", "run", "(", "false", ")", ")", "{", "return", ";", "}", "}", "else", "{", "return", ";", "}", "}", "}" ]
Invokes the onComplete method. If send is called again in onComplete then we loop and write it out. This prevents possible stack overflows due to recursion
[ "Invokes", "the", "onComplete", "method", ".", "If", "send", "is", "called", "again", "in", "onComplete", "then", "we", "loop", "and", "write", "it", "out", ".", "This", "prevents", "possible", "stack", "overflows", "due", "to", "recursion" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/io/AsyncSenderImpl.java#L399-L453
16,675
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/compat/rewrite/RewriteConfigFactory.java
RewriteConfigFactory.parseCondFlag
protected static void parseCondFlag(String line, RewriteCond condition, String flag) { if (flag.equals("NC") || flag.equals("nocase")) { condition.setNocase(true); } else if (flag.equals("OR") || flag.equals("ornext")) { condition.setOrnext(true); } else { throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteFlags(line, flag); } }
java
protected static void parseCondFlag(String line, RewriteCond condition, String flag) { if (flag.equals("NC") || flag.equals("nocase")) { condition.setNocase(true); } else if (flag.equals("OR") || flag.equals("ornext")) { condition.setOrnext(true); } else { throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteFlags(line, flag); } }
[ "protected", "static", "void", "parseCondFlag", "(", "String", "line", ",", "RewriteCond", "condition", ",", "String", "flag", ")", "{", "if", "(", "flag", ".", "equals", "(", "\"NC\"", ")", "||", "flag", ".", "equals", "(", "\"nocase\"", ")", ")", "{", "condition", ".", "setNocase", "(", "true", ")", ";", "}", "else", "if", "(", "flag", ".", "equals", "(", "\"OR\"", ")", "||", "flag", ".", "equals", "(", "\"ornext\"", ")", ")", "{", "condition", ".", "setOrnext", "(", "true", ")", ";", "}", "else", "{", "throw", "UndertowServletLogger", ".", "ROOT_LOGGER", ".", "invalidRewriteFlags", "(", "line", ",", "flag", ")", ";", "}", "}" ]
Parser for RewriteCond flags. @param condition @param flag
[ "Parser", "for", "RewriteCond", "flags", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/compat/rewrite/RewriteConfigFactory.java#L199-L207
16,676
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2PriorityTree.java
Http2PriorityTree.registerStream
public void registerStream(int streamId, int dependency, int weighting, boolean exclusive) { final Http2PriorityNode node = new Http2PriorityNode(streamId, weighting); if(exclusive) { Http2PriorityNode existing = nodesByID.get(dependency); if(existing != null) { existing.exclusive(node); } } else { Http2PriorityNode existing = nodesByID.get(dependency); if(existing != null) { existing.addDependent(node); } } nodesByID.put(streamId, node); }
java
public void registerStream(int streamId, int dependency, int weighting, boolean exclusive) { final Http2PriorityNode node = new Http2PriorityNode(streamId, weighting); if(exclusive) { Http2PriorityNode existing = nodesByID.get(dependency); if(existing != null) { existing.exclusive(node); } } else { Http2PriorityNode existing = nodesByID.get(dependency); if(existing != null) { existing.addDependent(node); } } nodesByID.put(streamId, node); }
[ "public", "void", "registerStream", "(", "int", "streamId", ",", "int", "dependency", ",", "int", "weighting", ",", "boolean", "exclusive", ")", "{", "final", "Http2PriorityNode", "node", "=", "new", "Http2PriorityNode", "(", "streamId", ",", "weighting", ")", ";", "if", "(", "exclusive", ")", "{", "Http2PriorityNode", "existing", "=", "nodesByID", ".", "get", "(", "dependency", ")", ";", "if", "(", "existing", "!=", "null", ")", "{", "existing", ".", "exclusive", "(", "node", ")", ";", "}", "}", "else", "{", "Http2PriorityNode", "existing", "=", "nodesByID", ".", "get", "(", "dependency", ")", ";", "if", "(", "existing", "!=", "null", ")", "{", "existing", ".", "addDependent", "(", "node", ")", ";", "}", "}", "nodesByID", ".", "put", "(", "streamId", ",", "node", ")", ";", "}" ]
Resisters a stream, with its dependency and dependent information @param streamId The stream id @param dependency The stream this stream depends on, if no stream is specified this should be zero @param weighting The weighting. If no weighting is specified this should be 16
[ "Resisters", "a", "stream", "with", "its", "dependency", "and", "dependent", "information" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2PriorityTree.java#L60-L74
16,677
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2PriorityTree.java
Http2PriorityTree.streamRemoved
public void streamRemoved(int streamId) { Http2PriorityNode node = nodesByID.get(streamId); if(node == null) { return; } if(!node.hasDependents()) { //add to eviction queue int toEvict = evictionQueue[evictionQueuePosition]; evictionQueue[evictionQueuePosition++] = streamId; Http2PriorityNode nodeToEvict = nodesByID.get(toEvict); //we don't remove the node if it has since got dependents since it was put into the queue //as this is the whole reason we maintain the queue in the first place if(nodeToEvict != null && !nodeToEvict.hasDependents()) { nodesByID.remove(toEvict); } } }
java
public void streamRemoved(int streamId) { Http2PriorityNode node = nodesByID.get(streamId); if(node == null) { return; } if(!node.hasDependents()) { //add to eviction queue int toEvict = evictionQueue[evictionQueuePosition]; evictionQueue[evictionQueuePosition++] = streamId; Http2PriorityNode nodeToEvict = nodesByID.get(toEvict); //we don't remove the node if it has since got dependents since it was put into the queue //as this is the whole reason we maintain the queue in the first place if(nodeToEvict != null && !nodeToEvict.hasDependents()) { nodesByID.remove(toEvict); } } }
[ "public", "void", "streamRemoved", "(", "int", "streamId", ")", "{", "Http2PriorityNode", "node", "=", "nodesByID", ".", "get", "(", "streamId", ")", ";", "if", "(", "node", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "node", ".", "hasDependents", "(", ")", ")", "{", "//add to eviction queue", "int", "toEvict", "=", "evictionQueue", "[", "evictionQueuePosition", "]", ";", "evictionQueue", "[", "evictionQueuePosition", "++", "]", "=", "streamId", ";", "Http2PriorityNode", "nodeToEvict", "=", "nodesByID", ".", "get", "(", "toEvict", ")", ";", "//we don't remove the node if it has since got dependents since it was put into the queue", "//as this is the whole reason we maintain the queue in the first place", "if", "(", "nodeToEvict", "!=", "null", "&&", "!", "nodeToEvict", ".", "hasDependents", "(", ")", ")", "{", "nodesByID", ".", "remove", "(", "toEvict", ")", ";", "}", "}", "}" ]
Method that is invoked when a stream has been removed @param streamId id of the stream removed
[ "Method", "that", "is", "invoked", "when", "a", "stream", "has", "been", "removed" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2PriorityTree.java#L81-L98
16,678
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2PriorityTree.java
Http2PriorityTree.comparator
public Comparator<Integer> comparator() { return new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { Http2PriorityNode n1 = nodesByID.get(o1); Http2PriorityNode n2 = nodesByID.get(o2); if(n1 == null && n2 == null) { return 0; } if(n1 == null) { return -1; } if(n2 == null) { return 1; } //do the comparison //this is kinda crap, but I can't really think of any better way to handle this double d1 = createWeightingProportion(n1); double d2 = createWeightingProportion(n2); return Double.compare(d1, d2); } }; }
java
public Comparator<Integer> comparator() { return new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { Http2PriorityNode n1 = nodesByID.get(o1); Http2PriorityNode n2 = nodesByID.get(o2); if(n1 == null && n2 == null) { return 0; } if(n1 == null) { return -1; } if(n2 == null) { return 1; } //do the comparison //this is kinda crap, but I can't really think of any better way to handle this double d1 = createWeightingProportion(n1); double d2 = createWeightingProportion(n2); return Double.compare(d1, d2); } }; }
[ "public", "Comparator", "<", "Integer", ">", "comparator", "(", ")", "{", "return", "new", "Comparator", "<", "Integer", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "Integer", "o1", ",", "Integer", "o2", ")", "{", "Http2PriorityNode", "n1", "=", "nodesByID", ".", "get", "(", "o1", ")", ";", "Http2PriorityNode", "n2", "=", "nodesByID", ".", "get", "(", "o2", ")", ";", "if", "(", "n1", "==", "null", "&&", "n2", "==", "null", ")", "{", "return", "0", ";", "}", "if", "(", "n1", "==", "null", ")", "{", "return", "-", "1", ";", "}", "if", "(", "n2", "==", "null", ")", "{", "return", "1", ";", "}", "//do the comparison", "//this is kinda crap, but I can't really think of any better way to handle this", "double", "d1", "=", "createWeightingProportion", "(", "n1", ")", ";", "double", "d2", "=", "createWeightingProportion", "(", "n2", ")", ";", "return", "Double", ".", "compare", "(", "d1", ",", "d2", ")", ";", "}", "}", ";", "}" ]
Creates a priority queue @return
[ "Creates", "a", "priority", "queue" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2PriorityTree.java#L104-L127
16,679
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2Channel.java
Http2Channel.updateSettings
boolean updateSettings(List<Http2Setting> settings) { for (Http2Setting setting : settings) { if (setting.getId() == Http2Setting.SETTINGS_INITIAL_WINDOW_SIZE) { synchronized (flowControlLock) { int old = initialSendWindowSize; if (setting.getValue() > Integer.MAX_VALUE) { sendGoAway(ERROR_FLOW_CONTROL_ERROR); return false; } initialSendWindowSize = (int) setting.getValue(); } } else if (setting.getId() == Http2Setting.SETTINGS_MAX_FRAME_SIZE) { if(setting.getValue() > MAX_FRAME_SIZE || setting.getValue() < DEFAULT_MAX_FRAME_SIZE) { UndertowLogger.REQUEST_IO_LOGGER.debug("Invalid value received for SETTINGS_MAX_FRAME_SIZE " + setting.getValue()); sendGoAway(ERROR_PROTOCOL_ERROR); return false; } sendMaxFrameSize = (int) setting.getValue(); } else if (setting.getId() == Http2Setting.SETTINGS_HEADER_TABLE_SIZE) { synchronized (this) { encoder.setMaxTableSize((int) setting.getValue()); } } else if (setting.getId() == Http2Setting.SETTINGS_ENABLE_PUSH) { int result = (int) setting.getValue(); //we allow the remote endpoint to disable push //but not enable it if it has been explictly disabled on this side if(result == 0) { pushEnabled = false; } else if(result != 1) { //invalid value UndertowLogger.REQUEST_IO_LOGGER.debug("Invalid value received for SETTINGS_ENABLE_PUSH " + result); sendGoAway(ERROR_PROTOCOL_ERROR); return false; } } else if (setting.getId() == Http2Setting.SETTINGS_MAX_CONCURRENT_STREAMS) { sendMaxConcurrentStreams = (int) setting.getValue(); } //ignore the rest for now } return true; }
java
boolean updateSettings(List<Http2Setting> settings) { for (Http2Setting setting : settings) { if (setting.getId() == Http2Setting.SETTINGS_INITIAL_WINDOW_SIZE) { synchronized (flowControlLock) { int old = initialSendWindowSize; if (setting.getValue() > Integer.MAX_VALUE) { sendGoAway(ERROR_FLOW_CONTROL_ERROR); return false; } initialSendWindowSize = (int) setting.getValue(); } } else if (setting.getId() == Http2Setting.SETTINGS_MAX_FRAME_SIZE) { if(setting.getValue() > MAX_FRAME_SIZE || setting.getValue() < DEFAULT_MAX_FRAME_SIZE) { UndertowLogger.REQUEST_IO_LOGGER.debug("Invalid value received for SETTINGS_MAX_FRAME_SIZE " + setting.getValue()); sendGoAway(ERROR_PROTOCOL_ERROR); return false; } sendMaxFrameSize = (int) setting.getValue(); } else if (setting.getId() == Http2Setting.SETTINGS_HEADER_TABLE_SIZE) { synchronized (this) { encoder.setMaxTableSize((int) setting.getValue()); } } else if (setting.getId() == Http2Setting.SETTINGS_ENABLE_PUSH) { int result = (int) setting.getValue(); //we allow the remote endpoint to disable push //but not enable it if it has been explictly disabled on this side if(result == 0) { pushEnabled = false; } else if(result != 1) { //invalid value UndertowLogger.REQUEST_IO_LOGGER.debug("Invalid value received for SETTINGS_ENABLE_PUSH " + result); sendGoAway(ERROR_PROTOCOL_ERROR); return false; } } else if (setting.getId() == Http2Setting.SETTINGS_MAX_CONCURRENT_STREAMS) { sendMaxConcurrentStreams = (int) setting.getValue(); } //ignore the rest for now } return true; }
[ "boolean", "updateSettings", "(", "List", "<", "Http2Setting", ">", "settings", ")", "{", "for", "(", "Http2Setting", "setting", ":", "settings", ")", "{", "if", "(", "setting", ".", "getId", "(", ")", "==", "Http2Setting", ".", "SETTINGS_INITIAL_WINDOW_SIZE", ")", "{", "synchronized", "(", "flowControlLock", ")", "{", "int", "old", "=", "initialSendWindowSize", ";", "if", "(", "setting", ".", "getValue", "(", ")", ">", "Integer", ".", "MAX_VALUE", ")", "{", "sendGoAway", "(", "ERROR_FLOW_CONTROL_ERROR", ")", ";", "return", "false", ";", "}", "initialSendWindowSize", "=", "(", "int", ")", "setting", ".", "getValue", "(", ")", ";", "}", "}", "else", "if", "(", "setting", ".", "getId", "(", ")", "==", "Http2Setting", ".", "SETTINGS_MAX_FRAME_SIZE", ")", "{", "if", "(", "setting", ".", "getValue", "(", ")", ">", "MAX_FRAME_SIZE", "||", "setting", ".", "getValue", "(", ")", "<", "DEFAULT_MAX_FRAME_SIZE", ")", "{", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "debug", "(", "\"Invalid value received for SETTINGS_MAX_FRAME_SIZE \"", "+", "setting", ".", "getValue", "(", ")", ")", ";", "sendGoAway", "(", "ERROR_PROTOCOL_ERROR", ")", ";", "return", "false", ";", "}", "sendMaxFrameSize", "=", "(", "int", ")", "setting", ".", "getValue", "(", ")", ";", "}", "else", "if", "(", "setting", ".", "getId", "(", ")", "==", "Http2Setting", ".", "SETTINGS_HEADER_TABLE_SIZE", ")", "{", "synchronized", "(", "this", ")", "{", "encoder", ".", "setMaxTableSize", "(", "(", "int", ")", "setting", ".", "getValue", "(", ")", ")", ";", "}", "}", "else", "if", "(", "setting", ".", "getId", "(", ")", "==", "Http2Setting", ".", "SETTINGS_ENABLE_PUSH", ")", "{", "int", "result", "=", "(", "int", ")", "setting", ".", "getValue", "(", ")", ";", "//we allow the remote endpoint to disable push", "//but not enable it if it has been explictly disabled on this side", "if", "(", "result", "==", "0", ")", "{", "pushEnabled", "=", "false", ";", "}", "else", "if", "(", "result", "!=", "1", ")", "{", "//invalid value", "UndertowLogger", ".", "REQUEST_IO_LOGGER", ".", "debug", "(", "\"Invalid value received for SETTINGS_ENABLE_PUSH \"", "+", "result", ")", ";", "sendGoAway", "(", "ERROR_PROTOCOL_ERROR", ")", ";", "return", "false", ";", "}", "}", "else", "if", "(", "setting", ".", "getId", "(", ")", "==", "Http2Setting", ".", "SETTINGS_MAX_CONCURRENT_STREAMS", ")", "{", "sendMaxConcurrentStreams", "=", "(", "int", ")", "setting", ".", "getValue", "(", ")", ";", "}", "//ignore the rest for now", "}", "return", "true", ";", "}" ]
Setting have been received from the client @param settings
[ "Setting", "have", "been", "received", "from", "the", "client" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2Channel.java#L667-L709
16,680
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2Channel.java
Http2Channel.createStream
public synchronized Http2HeadersStreamSinkChannel createStream(HeaderMap requestHeaders) throws IOException { if (!isClient()) { throw UndertowMessages.MESSAGES.headersStreamCanOnlyBeCreatedByClient(); } if (!isOpen()) { throw UndertowMessages.MESSAGES.channelIsClosed(); } sendConcurrentStreamsAtomicUpdater.incrementAndGet(this); if(sendMaxConcurrentStreams > 0 && sendConcurrentStreams > sendMaxConcurrentStreams) { throw UndertowMessages.MESSAGES.streamLimitExceeded(); } int streamId = streamIdCounter; streamIdCounter += 2; Http2HeadersStreamSinkChannel http2SynStreamStreamSinkChannel = new Http2HeadersStreamSinkChannel(this, streamId, requestHeaders); currentStreams.put(streamId, new StreamHolder(http2SynStreamStreamSinkChannel)); return http2SynStreamStreamSinkChannel; }
java
public synchronized Http2HeadersStreamSinkChannel createStream(HeaderMap requestHeaders) throws IOException { if (!isClient()) { throw UndertowMessages.MESSAGES.headersStreamCanOnlyBeCreatedByClient(); } if (!isOpen()) { throw UndertowMessages.MESSAGES.channelIsClosed(); } sendConcurrentStreamsAtomicUpdater.incrementAndGet(this); if(sendMaxConcurrentStreams > 0 && sendConcurrentStreams > sendMaxConcurrentStreams) { throw UndertowMessages.MESSAGES.streamLimitExceeded(); } int streamId = streamIdCounter; streamIdCounter += 2; Http2HeadersStreamSinkChannel http2SynStreamStreamSinkChannel = new Http2HeadersStreamSinkChannel(this, streamId, requestHeaders); currentStreams.put(streamId, new StreamHolder(http2SynStreamStreamSinkChannel)); return http2SynStreamStreamSinkChannel; }
[ "public", "synchronized", "Http2HeadersStreamSinkChannel", "createStream", "(", "HeaderMap", "requestHeaders", ")", "throws", "IOException", "{", "if", "(", "!", "isClient", "(", ")", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "headersStreamCanOnlyBeCreatedByClient", "(", ")", ";", "}", "if", "(", "!", "isOpen", "(", ")", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "channelIsClosed", "(", ")", ";", "}", "sendConcurrentStreamsAtomicUpdater", ".", "incrementAndGet", "(", "this", ")", ";", "if", "(", "sendMaxConcurrentStreams", ">", "0", "&&", "sendConcurrentStreams", ">", "sendMaxConcurrentStreams", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "streamLimitExceeded", "(", ")", ";", "}", "int", "streamId", "=", "streamIdCounter", ";", "streamIdCounter", "+=", "2", ";", "Http2HeadersStreamSinkChannel", "http2SynStreamStreamSinkChannel", "=", "new", "Http2HeadersStreamSinkChannel", "(", "this", ",", "streamId", ",", "requestHeaders", ")", ";", "currentStreams", ".", "put", "(", "streamId", ",", "new", "StreamHolder", "(", "http2SynStreamStreamSinkChannel", ")", ")", ";", "return", "http2SynStreamStreamSinkChannel", ";", "}" ]
Creates a strema using a HEADERS frame @param requestHeaders @return @throws IOException
[ "Creates", "a", "strema", "using", "a", "HEADERS", "frame" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2Channel.java#L881-L898
16,681
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2Channel.java
Http2Channel.grabFlowControlBytes
int grabFlowControlBytes(int bytesToGrab) { if(bytesToGrab <= 0) { return 0; } int min; synchronized (flowControlLock) { min = (int) Math.min(bytesToGrab, sendWindowSize); if (bytesToGrab > FLOW_CONTROL_MIN_WINDOW && min <= FLOW_CONTROL_MIN_WINDOW) { //this can cause problems with padding, so we just return 0 return 0; } min = Math.min(sendMaxFrameSize, min); sendWindowSize -= min; } return min; }
java
int grabFlowControlBytes(int bytesToGrab) { if(bytesToGrab <= 0) { return 0; } int min; synchronized (flowControlLock) { min = (int) Math.min(bytesToGrab, sendWindowSize); if (bytesToGrab > FLOW_CONTROL_MIN_WINDOW && min <= FLOW_CONTROL_MIN_WINDOW) { //this can cause problems with padding, so we just return 0 return 0; } min = Math.min(sendMaxFrameSize, min); sendWindowSize -= min; } return min; }
[ "int", "grabFlowControlBytes", "(", "int", "bytesToGrab", ")", "{", "if", "(", "bytesToGrab", "<=", "0", ")", "{", "return", "0", ";", "}", "int", "min", ";", "synchronized", "(", "flowControlLock", ")", "{", "min", "=", "(", "int", ")", "Math", ".", "min", "(", "bytesToGrab", ",", "sendWindowSize", ")", ";", "if", "(", "bytesToGrab", ">", "FLOW_CONTROL_MIN_WINDOW", "&&", "min", "<=", "FLOW_CONTROL_MIN_WINDOW", ")", "{", "//this can cause problems with padding, so we just return 0", "return", "0", ";", "}", "min", "=", "Math", ".", "min", "(", "sendMaxFrameSize", ",", "min", ")", ";", "sendWindowSize", "-=", "min", ";", "}", "return", "min", ";", "}" ]
Try and decrement the send window by the given amount of bytes. @param bytesToGrab The amount of bytes the sender is trying to send @return The actual amount of bytes the sender can send
[ "Try", "and", "decrement", "the", "send", "window", "by", "the", "given", "amount", "of", "bytes", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2Channel.java#L927-L942
16,682
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2Channel.java
Http2Channel.createInitialUpgradeResponseStream
public Http2HeadersStreamSinkChannel createInitialUpgradeResponseStream() { if (lastGoodStreamId != 0) { throw new IllegalStateException(); } lastGoodStreamId = 1; Http2HeadersStreamSinkChannel stream = new Http2HeadersStreamSinkChannel(this, 1); StreamHolder streamHolder = new StreamHolder(stream); streamHolder.sourceClosed = true; currentStreams.put(1, streamHolder); receiveConcurrentStreamsAtomicUpdater.getAndIncrement(this); return stream; }
java
public Http2HeadersStreamSinkChannel createInitialUpgradeResponseStream() { if (lastGoodStreamId != 0) { throw new IllegalStateException(); } lastGoodStreamId = 1; Http2HeadersStreamSinkChannel stream = new Http2HeadersStreamSinkChannel(this, 1); StreamHolder streamHolder = new StreamHolder(stream); streamHolder.sourceClosed = true; currentStreams.put(1, streamHolder); receiveConcurrentStreamsAtomicUpdater.getAndIncrement(this); return stream; }
[ "public", "Http2HeadersStreamSinkChannel", "createInitialUpgradeResponseStream", "(", ")", "{", "if", "(", "lastGoodStreamId", "!=", "0", ")", "{", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "lastGoodStreamId", "=", "1", ";", "Http2HeadersStreamSinkChannel", "stream", "=", "new", "Http2HeadersStreamSinkChannel", "(", "this", ",", "1", ")", ";", "StreamHolder", "streamHolder", "=", "new", "StreamHolder", "(", "stream", ")", ";", "streamHolder", ".", "sourceClosed", "=", "true", ";", "currentStreams", ".", "put", "(", "1", ",", "streamHolder", ")", ";", "receiveConcurrentStreamsAtomicUpdater", ".", "getAndIncrement", "(", "this", ")", ";", "return", "stream", ";", "}" ]
Creates a response stream to respond to the initial HTTP upgrade @return
[ "Creates", "a", "response", "stream", "to", "respond", "to", "the", "initial", "HTTP", "upgrade" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2Channel.java#L1085-L1097
16,683
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http/ALPNOfferedClientHelloExplorer.java
ALPNOfferedClientHelloExplorer.parseClientHello
static List<Integer> parseClientHello(ByteBuffer source) throws SSLException { ByteBuffer input = source.duplicate(); // Do we have a complete header? if (isIncompleteHeader(input)) { throw new BufferUnderflowException(); } // Is it a handshake message? byte firstByte = input.get(); byte secondByte = input.get(); byte thirdByte = input.get(); if ((firstByte & 0x80) != 0 && thirdByte == 0x01) { // looks like a V2ClientHello, we ignore it. return null; } else if (firstByte == 22) { // 22: handshake record if (secondByte == 3 && thirdByte >= 1 && thirdByte <= 3) { return exploreTLSRecord(input, firstByte, secondByte, thirdByte); } } return null; }
java
static List<Integer> parseClientHello(ByteBuffer source) throws SSLException { ByteBuffer input = source.duplicate(); // Do we have a complete header? if (isIncompleteHeader(input)) { throw new BufferUnderflowException(); } // Is it a handshake message? byte firstByte = input.get(); byte secondByte = input.get(); byte thirdByte = input.get(); if ((firstByte & 0x80) != 0 && thirdByte == 0x01) { // looks like a V2ClientHello, we ignore it. return null; } else if (firstByte == 22) { // 22: handshake record if (secondByte == 3 && thirdByte >= 1 && thirdByte <= 3) { return exploreTLSRecord(input, firstByte, secondByte, thirdByte); } } return null; }
[ "static", "List", "<", "Integer", ">", "parseClientHello", "(", "ByteBuffer", "source", ")", "throws", "SSLException", "{", "ByteBuffer", "input", "=", "source", ".", "duplicate", "(", ")", ";", "// Do we have a complete header?", "if", "(", "isIncompleteHeader", "(", "input", ")", ")", "{", "throw", "new", "BufferUnderflowException", "(", ")", ";", "}", "// Is it a handshake message?", "byte", "firstByte", "=", "input", ".", "get", "(", ")", ";", "byte", "secondByte", "=", "input", ".", "get", "(", ")", ";", "byte", "thirdByte", "=", "input", ".", "get", "(", ")", ";", "if", "(", "(", "firstByte", "&", "0x80", ")", "!=", "0", "&&", "thirdByte", "==", "0x01", ")", "{", "// looks like a V2ClientHello, we ignore it.", "return", "null", ";", "}", "else", "if", "(", "firstByte", "==", "22", ")", "{", "// 22: handshake record", "if", "(", "secondByte", "==", "3", "&&", "thirdByte", ">=", "1", "&&", "thirdByte", "<=", "3", ")", "{", "return", "exploreTLSRecord", "(", "input", ",", "firstByte", ",", "secondByte", ",", "thirdByte", ")", ";", "}", "}", "return", "null", ";", "}" ]
Checks if a client handshake is offering ALPN, and if so it returns a list of all ciphers. If ALPN is not being offered then this will return null.
[ "Checks", "if", "a", "client", "handshake", "is", "offering", "ALPN", "and", "if", "so", "it", "returns", "a", "list", "of", "all", "ciphers", ".", "If", "ALPN", "is", "not", "being", "offered", "then", "this", "will", "return", "null", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http/ALPNOfferedClientHelloExplorer.java#L53-L77
16,684
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/GracefulShutdownHandler.java
GracefulShutdownHandler.awaitShutdown
public void awaitShutdown() throws InterruptedException { synchronized (lock) { if (!shutdown) { throw UndertowMessages.MESSAGES.handlerNotShutdown(); } while (activeRequestsUpdater.get(this) > 0) { lock.wait(); } } }
java
public void awaitShutdown() throws InterruptedException { synchronized (lock) { if (!shutdown) { throw UndertowMessages.MESSAGES.handlerNotShutdown(); } while (activeRequestsUpdater.get(this) > 0) { lock.wait(); } } }
[ "public", "void", "awaitShutdown", "(", ")", "throws", "InterruptedException", "{", "synchronized", "(", "lock", ")", "{", "if", "(", "!", "shutdown", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "handlerNotShutdown", "(", ")", ";", "}", "while", "(", "activeRequestsUpdater", ".", "get", "(", "this", ")", ">", "0", ")", "{", "lock", ".", "wait", "(", ")", ";", "}", "}", "}" ]
Waits for the handler to shutdown.
[ "Waits", "for", "the", "handler", "to", "shutdown", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/GracefulShutdownHandler.java#L102-L111
16,685
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/GracefulShutdownHandler.java
GracefulShutdownHandler.awaitShutdown
public boolean awaitShutdown(long millis) throws InterruptedException { synchronized (lock) { if (!shutdown) { throw UndertowMessages.MESSAGES.handlerNotShutdown(); } long end = System.currentTimeMillis() + millis; int count = (int) activeRequestsUpdater.get(this); while (count != 0) { long left = end - System.currentTimeMillis(); if (left <= 0) { return false; } lock.wait(left); count = (int) activeRequestsUpdater.get(this); } return true; } }
java
public boolean awaitShutdown(long millis) throws InterruptedException { synchronized (lock) { if (!shutdown) { throw UndertowMessages.MESSAGES.handlerNotShutdown(); } long end = System.currentTimeMillis() + millis; int count = (int) activeRequestsUpdater.get(this); while (count != 0) { long left = end - System.currentTimeMillis(); if (left <= 0) { return false; } lock.wait(left); count = (int) activeRequestsUpdater.get(this); } return true; } }
[ "public", "boolean", "awaitShutdown", "(", "long", "millis", ")", "throws", "InterruptedException", "{", "synchronized", "(", "lock", ")", "{", "if", "(", "!", "shutdown", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "handlerNotShutdown", "(", ")", ";", "}", "long", "end", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "millis", ";", "int", "count", "=", "(", "int", ")", "activeRequestsUpdater", ".", "get", "(", "this", ")", ";", "while", "(", "count", "!=", "0", ")", "{", "long", "left", "=", "end", "-", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "left", "<=", "0", ")", "{", "return", "false", ";", "}", "lock", ".", "wait", "(", "left", ")", ";", "count", "=", "(", "int", ")", "activeRequestsUpdater", ".", "get", "(", "this", ")", ";", "}", "return", "true", ";", "}", "}" ]
Waits a set length of time for the handler to shut down @param millis The length of time @return <code>true</code> If the handler successfully shut down
[ "Waits", "a", "set", "length", "of", "time", "for", "the", "handler", "to", "shut", "down" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/GracefulShutdownHandler.java#L119-L136
16,686
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/GracefulShutdownHandler.java
GracefulShutdownHandler.addShutdownListener
public void addShutdownListener(final ShutdownListener shutdownListener) { synchronized (lock) { if (!shutdown) { throw UndertowMessages.MESSAGES.handlerNotShutdown(); } long count = activeRequestsUpdater.get(this); if (count == 0) { shutdownListener.shutdown(true); } else { shutdownListeners.add(shutdownListener); } } }
java
public void addShutdownListener(final ShutdownListener shutdownListener) { synchronized (lock) { if (!shutdown) { throw UndertowMessages.MESSAGES.handlerNotShutdown(); } long count = activeRequestsUpdater.get(this); if (count == 0) { shutdownListener.shutdown(true); } else { shutdownListeners.add(shutdownListener); } } }
[ "public", "void", "addShutdownListener", "(", "final", "ShutdownListener", "shutdownListener", ")", "{", "synchronized", "(", "lock", ")", "{", "if", "(", "!", "shutdown", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "handlerNotShutdown", "(", ")", ";", "}", "long", "count", "=", "activeRequestsUpdater", ".", "get", "(", "this", ")", ";", "if", "(", "count", "==", "0", ")", "{", "shutdownListener", ".", "shutdown", "(", "true", ")", ";", "}", "else", "{", "shutdownListeners", ".", "add", "(", "shutdownListener", ")", ";", "}", "}", "}" ]
Adds a shutdown listener that will be invoked when all requests have finished. If all requests have already been finished the listener will be invoked immediately. @param shutdownListener The shutdown listener
[ "Adds", "a", "shutdown", "listener", "that", "will", "be", "invoked", "when", "all", "requests", "have", "finished", ".", "If", "all", "requests", "have", "already", "been", "finished", "the", "listener", "will", "be", "invoked", "immediately", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/GracefulShutdownHandler.java#L144-L156
16,687
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/accesslog/DefaultAccessLogReceiver.java
DefaultAccessLogReceiver.run
@Override public void run() { if (!stateUpdater.compareAndSet(this, 1, 2)) { return; } if (forceLogRotation) { doRotate(); } else if (initialRun && Files.exists(defaultLogFile)) { //if there is an existing log file check if it should be rotated long lm = 0; try { lm = Files.getLastModifiedTime(defaultLogFile).toMillis(); } catch (IOException e) { UndertowLogger.ROOT_LOGGER.errorRotatingAccessLog(e); } Calendar c = Calendar.getInstance(); c.setTimeInMillis(changeOverPoint); c.add(Calendar.DATE, -1); if (lm <= c.getTimeInMillis()) { doRotate(); } } initialRun = false; List<String> messages = new ArrayList<>(); String msg; //only grab at most 1000 messages at a time for (int i = 0; i < 1000; ++i) { msg = pendingMessages.poll(); if (msg == null) { break; } messages.add(msg); } try { if (!messages.isEmpty()) { writeMessage(messages); } } finally { stateUpdater.set(this, 0); //check to see if there is still more messages //if so then run this again if (!pendingMessages.isEmpty() || forceLogRotation) { if (stateUpdater.compareAndSet(this, 0, 1)) { logWriteExecutor.execute(this); } } else if (closed) { try { if(writer != null) { writer.flush(); writer.close(); writer = null; } } catch (IOException e) { UndertowLogger.ROOT_LOGGER.errorWritingAccessLog(e); } } } }
java
@Override public void run() { if (!stateUpdater.compareAndSet(this, 1, 2)) { return; } if (forceLogRotation) { doRotate(); } else if (initialRun && Files.exists(defaultLogFile)) { //if there is an existing log file check if it should be rotated long lm = 0; try { lm = Files.getLastModifiedTime(defaultLogFile).toMillis(); } catch (IOException e) { UndertowLogger.ROOT_LOGGER.errorRotatingAccessLog(e); } Calendar c = Calendar.getInstance(); c.setTimeInMillis(changeOverPoint); c.add(Calendar.DATE, -1); if (lm <= c.getTimeInMillis()) { doRotate(); } } initialRun = false; List<String> messages = new ArrayList<>(); String msg; //only grab at most 1000 messages at a time for (int i = 0; i < 1000; ++i) { msg = pendingMessages.poll(); if (msg == null) { break; } messages.add(msg); } try { if (!messages.isEmpty()) { writeMessage(messages); } } finally { stateUpdater.set(this, 0); //check to see if there is still more messages //if so then run this again if (!pendingMessages.isEmpty() || forceLogRotation) { if (stateUpdater.compareAndSet(this, 0, 1)) { logWriteExecutor.execute(this); } } else if (closed) { try { if(writer != null) { writer.flush(); writer.close(); writer = null; } } catch (IOException e) { UndertowLogger.ROOT_LOGGER.errorWritingAccessLog(e); } } } }
[ "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "!", "stateUpdater", ".", "compareAndSet", "(", "this", ",", "1", ",", "2", ")", ")", "{", "return", ";", "}", "if", "(", "forceLogRotation", ")", "{", "doRotate", "(", ")", ";", "}", "else", "if", "(", "initialRun", "&&", "Files", ".", "exists", "(", "defaultLogFile", ")", ")", "{", "//if there is an existing log file check if it should be rotated", "long", "lm", "=", "0", ";", "try", "{", "lm", "=", "Files", ".", "getLastModifiedTime", "(", "defaultLogFile", ")", ".", "toMillis", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "UndertowLogger", ".", "ROOT_LOGGER", ".", "errorRotatingAccessLog", "(", "e", ")", ";", "}", "Calendar", "c", "=", "Calendar", ".", "getInstance", "(", ")", ";", "c", ".", "setTimeInMillis", "(", "changeOverPoint", ")", ";", "c", ".", "add", "(", "Calendar", ".", "DATE", ",", "-", "1", ")", ";", "if", "(", "lm", "<=", "c", ".", "getTimeInMillis", "(", ")", ")", "{", "doRotate", "(", ")", ";", "}", "}", "initialRun", "=", "false", ";", "List", "<", "String", ">", "messages", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "msg", ";", "//only grab at most 1000 messages at a time", "for", "(", "int", "i", "=", "0", ";", "i", "<", "1000", ";", "++", "i", ")", "{", "msg", "=", "pendingMessages", ".", "poll", "(", ")", ";", "if", "(", "msg", "==", "null", ")", "{", "break", ";", "}", "messages", ".", "add", "(", "msg", ")", ";", "}", "try", "{", "if", "(", "!", "messages", ".", "isEmpty", "(", ")", ")", "{", "writeMessage", "(", "messages", ")", ";", "}", "}", "finally", "{", "stateUpdater", ".", "set", "(", "this", ",", "0", ")", ";", "//check to see if there is still more messages", "//if so then run this again", "if", "(", "!", "pendingMessages", ".", "isEmpty", "(", ")", "||", "forceLogRotation", ")", "{", "if", "(", "stateUpdater", ".", "compareAndSet", "(", "this", ",", "0", ",", "1", ")", ")", "{", "logWriteExecutor", ".", "execute", "(", "this", ")", ";", "}", "}", "else", "if", "(", "closed", ")", "{", "try", "{", "if", "(", "writer", "!=", "null", ")", "{", "writer", ".", "flush", "(", ")", ";", "writer", ".", "close", "(", ")", ";", "writer", "=", "null", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "UndertowLogger", ".", "ROOT_LOGGER", ".", "errorWritingAccessLog", "(", "e", ")", ";", "}", "}", "}", "}" ]
processes all queued log messages
[ "processes", "all", "queued", "log", "messages" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/accesslog/DefaultAccessLogReceiver.java#L153-L210
16,688
undertow-io/undertow
core/src/main/java/io/undertow/util/AttachmentKey.java
AttachmentKey.createList
@SuppressWarnings("unchecked") public static <T> AttachmentKey<AttachmentList<T>> createList(final Class<? super T> valueClass) { return new ListAttachmentKey(valueClass); }
java
@SuppressWarnings("unchecked") public static <T> AttachmentKey<AttachmentList<T>> createList(final Class<? super T> valueClass) { return new ListAttachmentKey(valueClass); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "AttachmentKey", "<", "AttachmentList", "<", "T", ">", ">", "createList", "(", "final", "Class", "<", "?", "super", "T", ">", "valueClass", ")", "{", "return", "new", "ListAttachmentKey", "(", "valueClass", ")", ";", "}" ]
Construct a new list attachment key. @param valueClass the list value class @param <T> the list value type @return the new instance
[ "Construct", "a", "new", "list", "attachment", "key", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/AttachmentKey.java#L61-L64
16,689
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel.java
AbstractFramedStreamSinkChannel.getFrameHeader
final SendFrameHeader getFrameHeader() throws IOException { if (header == null) { header = createFrameHeader(); if (header == null) { header = new SendFrameHeader(0, null); } } return header; }
java
final SendFrameHeader getFrameHeader() throws IOException { if (header == null) { header = createFrameHeader(); if (header == null) { header = new SendFrameHeader(0, null); } } return header; }
[ "final", "SendFrameHeader", "getFrameHeader", "(", ")", "throws", "IOException", "{", "if", "(", "header", "==", "null", ")", "{", "header", "=", "createFrameHeader", "(", ")", ";", "if", "(", "header", "==", "null", ")", "{", "header", "=", "new", "SendFrameHeader", "(", "0", ",", "null", ")", ";", "}", "}", "return", "header", ";", "}" ]
Returns the header for the current frame. This consists of the frame data, and also an integer specifying how much data is remaining in the buffer. If this is non-zero then this method must adjust the buffers limit accordingly. It is expected that this will be used when limits on the size of a data frame prevent the whole buffer from being sent at once. @return The header for the current frame, or null
[ "Returns", "the", "header", "for", "the", "current", "frame", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel.java#L143-L151
16,690
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel.java
AbstractFramedStreamSinkChannel.send
public boolean send(PooledByteBuffer pooled) throws IOException { if(isWritesShutdown()) { throw UndertowMessages.MESSAGES.channelIsClosed(); } boolean result = sendInternal(pooled); if(result) { flush(); } return result; }
java
public boolean send(PooledByteBuffer pooled) throws IOException { if(isWritesShutdown()) { throw UndertowMessages.MESSAGES.channelIsClosed(); } boolean result = sendInternal(pooled); if(result) { flush(); } return result; }
[ "public", "boolean", "send", "(", "PooledByteBuffer", "pooled", ")", "throws", "IOException", "{", "if", "(", "isWritesShutdown", "(", ")", ")", "{", "throw", "UndertowMessages", ".", "MESSAGES", ".", "channelIsClosed", "(", ")", ";", "}", "boolean", "result", "=", "sendInternal", "(", "pooled", ")", ";", "if", "(", "result", ")", "{", "flush", "(", ")", ";", "}", "return", "result", ";", "}" ]
Send a buffer to this channel. @param pooled Pooled ByteBuffer to send. The buffer should have data available. This channel will free the buffer after sending data @return true if the buffer was accepted; false if the channel needs to first be flushed @throws IOException if this channel is closed
[ "Send", "a", "buffer", "to", "this", "channel", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel.java#L422-L431
16,691
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel.java
AbstractFramedStreamSinkChannel.flushComplete
final void flushComplete() throws IOException { synchronized (lock) { try { bufferFull = false; int remaining = header.getRemainingInBuffer(); boolean finalFrame = finalFrameQueued; boolean channelClosed = finalFrame && remaining == 0 && !header.isAnotherFrameRequired(); if (remaining > 0) { body.getBuffer().limit(body.getBuffer().limit() + remaining); if (finalFrame) { //we clear the final frame flag, as it could not actually be written out //note that we don't attempt to requeue, as whatever stopped it from being written will likely still //be an issue this.finalFrameQueued = false; } } else if (header.isAnotherFrameRequired()) { this.finalFrameQueued = false; if (body != null) { body.close(); body = null; state &= ~STATE_PRE_WRITE_CALLED; } } else if (body != null) { body.close(); body = null; state &= ~STATE_PRE_WRITE_CALLED; } if (channelClosed) { fullyFlushed = true; if (body != null) { body.close(); body = null; state &= ~STATE_PRE_WRITE_CALLED; } } else if (body != null) { // We still have a body, but since we just flushed, we transfer it to the write buffer. // This works as long as you call write() again //TODO: this code may not work if the channel has frame level compression and flow control //we don't have an implementation that needs this yet so it is ok for now body.getBuffer().compact(); writeBuffer = body; body = null; state &= ~STATE_PRE_WRITE_CALLED; } if (header.getByteBuffer() != null) { header.getByteBuffer().close(); } header = null; readyForFlush = false; if (isWriteResumed() && !channelClosed) { wakeupWrites(); } else if (isWriteResumed()) { //we need to execute the write listener one last time //we need to dispatch it back to the IO thread, so we don't invoke it recursivly ChannelListeners.invokeChannelListener(getIoThread(), (S) this, getWriteListener()); } final ChannelListener<? super S> closeListener = this.closeSetter.get(); if (channelClosed && closeListener != null) { ChannelListeners.invokeChannelListener(getIoThread(), (S) AbstractFramedStreamSinkChannel.this, closeListener); } handleFlushComplete(channelClosed); } finally { wakeupWaiters(); } } }
java
final void flushComplete() throws IOException { synchronized (lock) { try { bufferFull = false; int remaining = header.getRemainingInBuffer(); boolean finalFrame = finalFrameQueued; boolean channelClosed = finalFrame && remaining == 0 && !header.isAnotherFrameRequired(); if (remaining > 0) { body.getBuffer().limit(body.getBuffer().limit() + remaining); if (finalFrame) { //we clear the final frame flag, as it could not actually be written out //note that we don't attempt to requeue, as whatever stopped it from being written will likely still //be an issue this.finalFrameQueued = false; } } else if (header.isAnotherFrameRequired()) { this.finalFrameQueued = false; if (body != null) { body.close(); body = null; state &= ~STATE_PRE_WRITE_CALLED; } } else if (body != null) { body.close(); body = null; state &= ~STATE_PRE_WRITE_CALLED; } if (channelClosed) { fullyFlushed = true; if (body != null) { body.close(); body = null; state &= ~STATE_PRE_WRITE_CALLED; } } else if (body != null) { // We still have a body, but since we just flushed, we transfer it to the write buffer. // This works as long as you call write() again //TODO: this code may not work if the channel has frame level compression and flow control //we don't have an implementation that needs this yet so it is ok for now body.getBuffer().compact(); writeBuffer = body; body = null; state &= ~STATE_PRE_WRITE_CALLED; } if (header.getByteBuffer() != null) { header.getByteBuffer().close(); } header = null; readyForFlush = false; if (isWriteResumed() && !channelClosed) { wakeupWrites(); } else if (isWriteResumed()) { //we need to execute the write listener one last time //we need to dispatch it back to the IO thread, so we don't invoke it recursivly ChannelListeners.invokeChannelListener(getIoThread(), (S) this, getWriteListener()); } final ChannelListener<? super S> closeListener = this.closeSetter.get(); if (channelClosed && closeListener != null) { ChannelListeners.invokeChannelListener(getIoThread(), (S) AbstractFramedStreamSinkChannel.this, closeListener); } handleFlushComplete(channelClosed); } finally { wakeupWaiters(); } } }
[ "final", "void", "flushComplete", "(", ")", "throws", "IOException", "{", "synchronized", "(", "lock", ")", "{", "try", "{", "bufferFull", "=", "false", ";", "int", "remaining", "=", "header", ".", "getRemainingInBuffer", "(", ")", ";", "boolean", "finalFrame", "=", "finalFrameQueued", ";", "boolean", "channelClosed", "=", "finalFrame", "&&", "remaining", "==", "0", "&&", "!", "header", ".", "isAnotherFrameRequired", "(", ")", ";", "if", "(", "remaining", ">", "0", ")", "{", "body", ".", "getBuffer", "(", ")", ".", "limit", "(", "body", ".", "getBuffer", "(", ")", ".", "limit", "(", ")", "+", "remaining", ")", ";", "if", "(", "finalFrame", ")", "{", "//we clear the final frame flag, as it could not actually be written out", "//note that we don't attempt to requeue, as whatever stopped it from being written will likely still", "//be an issue", "this", ".", "finalFrameQueued", "=", "false", ";", "}", "}", "else", "if", "(", "header", ".", "isAnotherFrameRequired", "(", ")", ")", "{", "this", ".", "finalFrameQueued", "=", "false", ";", "if", "(", "body", "!=", "null", ")", "{", "body", ".", "close", "(", ")", ";", "body", "=", "null", ";", "state", "&=", "~", "STATE_PRE_WRITE_CALLED", ";", "}", "}", "else", "if", "(", "body", "!=", "null", ")", "{", "body", ".", "close", "(", ")", ";", "body", "=", "null", ";", "state", "&=", "~", "STATE_PRE_WRITE_CALLED", ";", "}", "if", "(", "channelClosed", ")", "{", "fullyFlushed", "=", "true", ";", "if", "(", "body", "!=", "null", ")", "{", "body", ".", "close", "(", ")", ";", "body", "=", "null", ";", "state", "&=", "~", "STATE_PRE_WRITE_CALLED", ";", "}", "}", "else", "if", "(", "body", "!=", "null", ")", "{", "// We still have a body, but since we just flushed, we transfer it to the write buffer.", "// This works as long as you call write() again", "//TODO: this code may not work if the channel has frame level compression and flow control", "//we don't have an implementation that needs this yet so it is ok for now", "body", ".", "getBuffer", "(", ")", ".", "compact", "(", ")", ";", "writeBuffer", "=", "body", ";", "body", "=", "null", ";", "state", "&=", "~", "STATE_PRE_WRITE_CALLED", ";", "}", "if", "(", "header", ".", "getByteBuffer", "(", ")", "!=", "null", ")", "{", "header", ".", "getByteBuffer", "(", ")", ".", "close", "(", ")", ";", "}", "header", "=", "null", ";", "readyForFlush", "=", "false", ";", "if", "(", "isWriteResumed", "(", ")", "&&", "!", "channelClosed", ")", "{", "wakeupWrites", "(", ")", ";", "}", "else", "if", "(", "isWriteResumed", "(", ")", ")", "{", "//we need to execute the write listener one last time", "//we need to dispatch it back to the IO thread, so we don't invoke it recursivly", "ChannelListeners", ".", "invokeChannelListener", "(", "getIoThread", "(", ")", ",", "(", "S", ")", "this", ",", "getWriteListener", "(", ")", ")", ";", "}", "final", "ChannelListener", "<", "?", "super", "S", ">", "closeListener", "=", "this", ".", "closeSetter", ".", "get", "(", ")", ";", "if", "(", "channelClosed", "&&", "closeListener", "!=", "null", ")", "{", "ChannelListeners", ".", "invokeChannelListener", "(", "getIoThread", "(", ")", ",", "(", "S", ")", "AbstractFramedStreamSinkChannel", ".", "this", ",", "closeListener", ")", ";", "}", "handleFlushComplete", "(", "channelClosed", ")", ";", "}", "finally", "{", "wakeupWaiters", "(", ")", ";", "}", "}", "}" ]
Method that is invoked when a frame has been fully flushed. This method is only invoked by the IO thread
[ "Method", "that", "is", "invoked", "when", "a", "frame", "has", "been", "fully", "flushed", ".", "This", "method", "is", "only", "invoked", "by", "the", "IO", "thread" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSinkChannel.java#L596-L666
16,692
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/AccessControlListHandler.java
AccessControlListHandler.isAllowed
boolean isAllowed(String attribute) { if (attribute != null) { for (AclMatch rule : acl) { if (rule.matches(attribute)) { return !rule.isDeny(); } } } return defaultAllow; }
java
boolean isAllowed(String attribute) { if (attribute != null) { for (AclMatch rule : acl) { if (rule.matches(attribute)) { return !rule.isDeny(); } } } return defaultAllow; }
[ "boolean", "isAllowed", "(", "String", "attribute", ")", "{", "if", "(", "attribute", "!=", "null", ")", "{", "for", "(", "AclMatch", "rule", ":", "acl", ")", "{", "if", "(", "rule", ".", "matches", "(", "attribute", ")", ")", "{", "return", "!", "rule", ".", "isDeny", "(", ")", ";", "}", "}", "}", "return", "defaultAllow", ";", "}" ]
package private for unit tests
[ "package", "private", "for", "unit", "tests" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/AccessControlListHandler.java#L75-L84
16,693
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.predicate
public static PredicateHandler predicate(final Predicate predicate, final HttpHandler trueHandler, final HttpHandler falseHandler) { return new PredicateHandler(predicate, trueHandler, falseHandler); }
java
public static PredicateHandler predicate(final Predicate predicate, final HttpHandler trueHandler, final HttpHandler falseHandler) { return new PredicateHandler(predicate, trueHandler, falseHandler); }
[ "public", "static", "PredicateHandler", "predicate", "(", "final", "Predicate", "predicate", ",", "final", "HttpHandler", "trueHandler", ",", "final", "HttpHandler", "falseHandler", ")", "{", "return", "new", "PredicateHandler", "(", "predicate", ",", "trueHandler", ",", "falseHandler", ")", ";", "}" ]
Returns a new predicate handler, that will delegate to one of the two provided handlers based on the value of the provided predicate. @param predicate The predicate @param trueHandler The handler that will be executed if the predicate is true @param falseHandler The handler that will be exected if the predicate is false @return A new predicate handler @see Predicate @see io.undertow.predicate.Predicates
[ "Returns", "a", "new", "predicate", "handler", "that", "will", "delegate", "to", "one", "of", "the", "two", "provided", "handlers", "based", "on", "the", "value", "of", "the", "provided", "predicate", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L265-L267
16,694
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.header
public static SetHeaderHandler header(final HttpHandler next, final String headerName, final ExchangeAttribute headerValue) { return new SetHeaderHandler(next, headerName, headerValue); }
java
public static SetHeaderHandler header(final HttpHandler next, final String headerName, final ExchangeAttribute headerValue) { return new SetHeaderHandler(next, headerName, headerValue); }
[ "public", "static", "SetHeaderHandler", "header", "(", "final", "HttpHandler", "next", ",", "final", "String", "headerName", ",", "final", "ExchangeAttribute", "headerValue", ")", "{", "return", "new", "SetHeaderHandler", "(", "next", ",", "headerName", ",", "headerValue", ")", ";", "}" ]
Returns a handler that sets a response header @param next The next handler in the chain @param headerName The name of the header @param headerValue The header value @return A new set header handler
[ "Returns", "a", "handler", "that", "sets", "a", "response", "header" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L306-L308
16,695
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.acl
public static final AccessControlListHandler acl(final HttpHandler next, boolean defaultAllow, ExchangeAttribute attribute) { return new AccessControlListHandler(next, attribute).setDefaultAllow(defaultAllow); }
java
public static final AccessControlListHandler acl(final HttpHandler next, boolean defaultAllow, ExchangeAttribute attribute) { return new AccessControlListHandler(next, attribute).setDefaultAllow(defaultAllow); }
[ "public", "static", "final", "AccessControlListHandler", "acl", "(", "final", "HttpHandler", "next", ",", "boolean", "defaultAllow", ",", "ExchangeAttribute", "attribute", ")", "{", "return", "new", "AccessControlListHandler", "(", "next", ",", "attribute", ")", ".", "setDefaultAllow", "(", "defaultAllow", ")", ";", "}" ]
Returns a new handler that can allow or deny access to a resource based an at attribute of the exchange @param next The next handler in the chain @param defaultAllow Determine if a non-matching user agent will be allowed by default @return A new user agent access control handler
[ "Returns", "a", "new", "handler", "that", "can", "allow", "or", "deny", "access", "to", "a", "resource", "based", "an", "at", "attribute", "of", "the", "exchange" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L329-L331
16,696
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.setAttribute
public static SetAttributeHandler setAttribute(final HttpHandler next, final String attribute, final String value, final ClassLoader classLoader) { return new SetAttributeHandler(next, attribute, value, classLoader); }
java
public static SetAttributeHandler setAttribute(final HttpHandler next, final String attribute, final String value, final ClassLoader classLoader) { return new SetAttributeHandler(next, attribute, value, classLoader); }
[ "public", "static", "SetAttributeHandler", "setAttribute", "(", "final", "HttpHandler", "next", ",", "final", "String", "attribute", ",", "final", "String", "value", ",", "final", "ClassLoader", "classLoader", ")", "{", "return", "new", "SetAttributeHandler", "(", "next", ",", "attribute", ",", "value", ",", "classLoader", ")", ";", "}" ]
Returns an attribute setting handler that can be used to set an arbitrary attribute on the exchange. This includes functions such as adding and removing headers etc. @param next The next handler @param attribute The attribute to set, specified as a string presentation of an {@link io.undertow.attribute.ExchangeAttribute} @param value The value to set, specified an a string representation of an {@link io.undertow.attribute.ExchangeAttribute} @param classLoader The class loader to use to parser the exchange attributes @return The handler
[ "Returns", "an", "attribute", "setting", "handler", "that", "can", "be", "used", "to", "set", "an", "arbitrary", "attribute", "on", "the", "exchange", ".", "This", "includes", "functions", "such", "as", "adding", "and", "removing", "headers", "etc", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L397-L399
16,697
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.rewrite
public static HttpHandler rewrite(final String condition, final String target, final ClassLoader classLoader, final HttpHandler next) { return predicateContext(predicate(PredicateParser.parse(condition, classLoader), setAttribute(next, "%R", target, classLoader), next)); }
java
public static HttpHandler rewrite(final String condition, final String target, final ClassLoader classLoader, final HttpHandler next) { return predicateContext(predicate(PredicateParser.parse(condition, classLoader), setAttribute(next, "%R", target, classLoader), next)); }
[ "public", "static", "HttpHandler", "rewrite", "(", "final", "String", "condition", ",", "final", "String", "target", ",", "final", "ClassLoader", "classLoader", ",", "final", "HttpHandler", "next", ")", "{", "return", "predicateContext", "(", "predicate", "(", "PredicateParser", ".", "parse", "(", "condition", ",", "classLoader", ")", ",", "setAttribute", "(", "next", ",", "\"%R\"", ",", "target", ",", "classLoader", ")", ",", "next", ")", ")", ";", "}" ]
Creates the set of handlers that are required to perform a simple rewrite. @param condition The rewrite condition @param target The rewrite target if the condition matches @param next The next handler @return
[ "Creates", "the", "set", "of", "handlers", "that", "are", "required", "to", "perform", "a", "simple", "rewrite", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L408-L410
16,698
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.jvmRoute
public static JvmRouteHandler jvmRoute(final String sessionCookieName, final String jvmRoute, HttpHandler next) { return new JvmRouteHandler(next, sessionCookieName, jvmRoute); }
java
public static JvmRouteHandler jvmRoute(final String sessionCookieName, final String jvmRoute, HttpHandler next) { return new JvmRouteHandler(next, sessionCookieName, jvmRoute); }
[ "public", "static", "JvmRouteHandler", "jvmRoute", "(", "final", "String", "sessionCookieName", ",", "final", "String", "jvmRoute", ",", "HttpHandler", "next", ")", "{", "return", "new", "JvmRouteHandler", "(", "next", ",", "sessionCookieName", ",", "jvmRoute", ")", ";", "}" ]
Handler that appends the JVM route to the session cookie @param sessionCookieName The session cookie name @param jvmRoute The JVM route to append @param next The next handler @return The handler
[ "Handler", "that", "appends", "the", "JVM", "route", "to", "the", "session", "cookie" ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L453-L455
16,699
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.requestLimitingHandler
public static RequestLimitingHandler requestLimitingHandler(final int maxRequest, final int queueSize, HttpHandler next) { return new RequestLimitingHandler(maxRequest, queueSize, next); }
java
public static RequestLimitingHandler requestLimitingHandler(final int maxRequest, final int queueSize, HttpHandler next) { return new RequestLimitingHandler(maxRequest, queueSize, next); }
[ "public", "static", "RequestLimitingHandler", "requestLimitingHandler", "(", "final", "int", "maxRequest", ",", "final", "int", "queueSize", ",", "HttpHandler", "next", ")", "{", "return", "new", "RequestLimitingHandler", "(", "maxRequest", ",", "queueSize", ",", "next", ")", ";", "}" ]
Returns a handler that limits the maximum number of requests that can run at a time. @param maxRequest The maximum number of requests @param queueSize The maximum number of queued requests @param next The next handler @return The handler
[ "Returns", "a", "handler", "that", "limits", "the", "maximum", "number", "of", "requests", "that", "can", "run", "at", "a", "time", "." ]
87de0b856a7a4ba8faf5b659537b9af07b763263
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L465-L467