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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
EsotericSoftware/yamlbeans | src/com/esotericsoftware/yamlbeans/YamlConfig.java | YamlConfig.setScalarSerializer | public void setScalarSerializer (Class type, ScalarSerializer serializer) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
scalarSerializers.put(type, serializer);
} | java | public void setScalarSerializer (Class type, ScalarSerializer serializer) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
scalarSerializers.put(type, serializer);
} | [
"public",
"void",
"setScalarSerializer",
"(",
"Class",
"type",
",",
"ScalarSerializer",
"serializer",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"type cannot be null.\"",
")",
";",
"if",
"(",
"serializer",
... | Adds a serializer for the specified scalar type. | [
"Adds",
"a",
"serializer",
"for",
"the",
"specified",
"scalar",
"type",
"."
] | f5610997edbc5534fc7e9f0a91654d14742345ca | https://github.com/EsotericSoftware/yamlbeans/blob/f5610997edbc5534fc7e9f0a91654d14742345ca/src/com/esotericsoftware/yamlbeans/YamlConfig.java#L77-L81 | train |
EsotericSoftware/yamlbeans | src/com/esotericsoftware/yamlbeans/YamlConfig.java | YamlConfig.setPropertyElementType | public void setPropertyElementType (Class type, String propertyName, Class elementType) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null.");
if (elementType == null) throw new IllegalArgumentException("propertyType cannot be null.");
Property property = Beans.getProperty(type, propertyName, beanProperties, privateFields, this);
if (property == null)
throw new IllegalArgumentException("The class " + type.getName() + " does not have a property named: " + propertyName);
if (!Collection.class.isAssignableFrom(property.getType()) && !Map.class.isAssignableFrom(property.getType())) {
throw new IllegalArgumentException("The '" + propertyName + "' property on the " + type.getName()
+ " class must be a Collection or Map: " + property.getType());
}
propertyToElementType.put(property, elementType);
} | java | public void setPropertyElementType (Class type, String propertyName, Class elementType) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null.");
if (elementType == null) throw new IllegalArgumentException("propertyType cannot be null.");
Property property = Beans.getProperty(type, propertyName, beanProperties, privateFields, this);
if (property == null)
throw new IllegalArgumentException("The class " + type.getName() + " does not have a property named: " + propertyName);
if (!Collection.class.isAssignableFrom(property.getType()) && !Map.class.isAssignableFrom(property.getType())) {
throw new IllegalArgumentException("The '" + propertyName + "' property on the " + type.getName()
+ " class must be a Collection or Map: " + property.getType());
}
propertyToElementType.put(property, elementType);
} | [
"public",
"void",
"setPropertyElementType",
"(",
"Class",
"type",
",",
"String",
"propertyName",
",",
"Class",
"elementType",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"type cannot be null.\"",
")",
";",
"... | Sets the default type of elements in a Collection or Map property. No tag will be output for elements of this type. This
type will be used for each element if no tag is found. | [
"Sets",
"the",
"default",
"type",
"of",
"elements",
"in",
"a",
"Collection",
"or",
"Map",
"property",
".",
"No",
"tag",
"will",
"be",
"output",
"for",
"elements",
"of",
"this",
"type",
".",
"This",
"type",
"will",
"be",
"used",
"for",
"each",
"element",
... | f5610997edbc5534fc7e9f0a91654d14742345ca | https://github.com/EsotericSoftware/yamlbeans/blob/f5610997edbc5534fc7e9f0a91654d14742345ca/src/com/esotericsoftware/yamlbeans/YamlConfig.java#L85-L97 | train |
EsotericSoftware/yamlbeans | src/com/esotericsoftware/yamlbeans/YamlConfig.java | YamlConfig.setPropertyDefaultType | public void setPropertyDefaultType (Class type, String propertyName, Class defaultType) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null.");
if (defaultType == null) throw new IllegalArgumentException("defaultType cannot be null.");
Property property = Beans.getProperty(type, propertyName, beanProperties, privateFields, this);
if (property == null)
throw new IllegalArgumentException("The class " + type.getName() + " does not have a property named: " + propertyName);
propertyToDefaultType.put(property, defaultType);
} | java | public void setPropertyDefaultType (Class type, String propertyName, Class defaultType) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null.");
if (defaultType == null) throw new IllegalArgumentException("defaultType cannot be null.");
Property property = Beans.getProperty(type, propertyName, beanProperties, privateFields, this);
if (property == null)
throw new IllegalArgumentException("The class " + type.getName() + " does not have a property named: " + propertyName);
propertyToDefaultType.put(property, defaultType);
} | [
"public",
"void",
"setPropertyDefaultType",
"(",
"Class",
"type",
",",
"String",
"propertyName",
",",
"Class",
"defaultType",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"type cannot be null.\"",
")",
";",
"... | Sets the default type of a property. No tag will be output for values of this type. This type will be used if no tag is
found. | [
"Sets",
"the",
"default",
"type",
"of",
"a",
"property",
".",
"No",
"tag",
"will",
"be",
"output",
"for",
"values",
"of",
"this",
"type",
".",
"This",
"type",
"will",
"be",
"used",
"if",
"no",
"tag",
"is",
"found",
"."
] | f5610997edbc5534fc7e9f0a91654d14742345ca | https://github.com/EsotericSoftware/yamlbeans/blob/f5610997edbc5534fc7e9f0a91654d14742345ca/src/com/esotericsoftware/yamlbeans/YamlConfig.java#L101-L109 | train |
EsotericSoftware/yamlbeans | src/com/esotericsoftware/yamlbeans/YamlReader.java | YamlReader.read | public <T> T read (Class<T> type) throws YamlException {
return read(type, null);
} | java | public <T> T read (Class<T> type) throws YamlException {
return read(type, null);
} | [
"public",
"<",
"T",
">",
"T",
"read",
"(",
"Class",
"<",
"T",
">",
"type",
")",
"throws",
"YamlException",
"{",
"return",
"read",
"(",
"type",
",",
"null",
")",
";",
"}"
] | Reads an object of the specified type from YAML.
@param type The type of object to read. If null, behaves the same as {{@link #read()}. | [
"Reads",
"an",
"object",
"of",
"the",
"specified",
"type",
"from",
"YAML",
"."
] | f5610997edbc5534fc7e9f0a91654d14742345ca | https://github.com/EsotericSoftware/yamlbeans/blob/f5610997edbc5534fc7e9f0a91654d14742345ca/src/com/esotericsoftware/yamlbeans/YamlReader.java#L91-L93 | train |
EsotericSoftware/yamlbeans | src/com/esotericsoftware/yamlbeans/YamlReader.java | YamlReader.read | public <T> T read (Class<T> type, Class elementType) throws YamlException {
try {
while (true) {
Event event = parser.getNextEvent();
if (event == null) return null;
if (event.type == STREAM_END) return null;
if (event.type == DOCUMENT_START) break;
}
return (T)readValue(type, elementType, null);
} catch (ParserException ex) {
throw new YamlException("Error parsing YAML.", ex);
} catch (TokenizerException ex) {
throw new YamlException("Error tokenizing YAML.", ex);
}
} | java | public <T> T read (Class<T> type, Class elementType) throws YamlException {
try {
while (true) {
Event event = parser.getNextEvent();
if (event == null) return null;
if (event.type == STREAM_END) return null;
if (event.type == DOCUMENT_START) break;
}
return (T)readValue(type, elementType, null);
} catch (ParserException ex) {
throw new YamlException("Error parsing YAML.", ex);
} catch (TokenizerException ex) {
throw new YamlException("Error tokenizing YAML.", ex);
}
} | [
"public",
"<",
"T",
">",
"T",
"read",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"Class",
"elementType",
")",
"throws",
"YamlException",
"{",
"try",
"{",
"while",
"(",
"true",
")",
"{",
"Event",
"event",
"=",
"parser",
".",
"getNextEvent",
"(",
")",
... | Reads an array, Map, List, or Collection object of the specified type from YAML, using the specified element type.
@param type The type of object to read. If null, behaves the same as {{@link #read()}. | [
"Reads",
"an",
"array",
"Map",
"List",
"or",
"Collection",
"object",
"of",
"the",
"specified",
"type",
"from",
"YAML",
"using",
"the",
"specified",
"element",
"type",
"."
] | f5610997edbc5534fc7e9f0a91654d14742345ca | https://github.com/EsotericSoftware/yamlbeans/blob/f5610997edbc5534fc7e9f0a91654d14742345ca/src/com/esotericsoftware/yamlbeans/YamlReader.java#L97-L111 | train |
EsotericSoftware/yamlbeans | src/com/esotericsoftware/yamlbeans/YamlReader.java | YamlReader.readValue | protected Object readValue (Class type, Class elementType, Class defaultType)
throws YamlException, ParserException, TokenizerException {
String tag = null, anchor = null;
Event event = parser.peekNextEvent();
switch (event.type) {
case ALIAS:
parser.getNextEvent();
anchor = ((AliasEvent)event).anchor;
Object value = anchors.get(anchor);
if (value == null) throw new YamlReaderException("Unknown anchor: " + anchor);
return value;
case MAPPING_START:
case SEQUENCE_START:
tag = ((CollectionStartEvent)event).tag;
anchor = ((CollectionStartEvent)event).anchor;
break;
case SCALAR:
tag = ((ScalarEvent)event).tag;
anchor = ((ScalarEvent)event).anchor;
break;
default:
}
return readValueInternal(this.chooseType(tag, defaultType, type), elementType, anchor);
} | java | protected Object readValue (Class type, Class elementType, Class defaultType)
throws YamlException, ParserException, TokenizerException {
String tag = null, anchor = null;
Event event = parser.peekNextEvent();
switch (event.type) {
case ALIAS:
parser.getNextEvent();
anchor = ((AliasEvent)event).anchor;
Object value = anchors.get(anchor);
if (value == null) throw new YamlReaderException("Unknown anchor: " + anchor);
return value;
case MAPPING_START:
case SEQUENCE_START:
tag = ((CollectionStartEvent)event).tag;
anchor = ((CollectionStartEvent)event).anchor;
break;
case SCALAR:
tag = ((ScalarEvent)event).tag;
anchor = ((ScalarEvent)event).anchor;
break;
default:
}
return readValueInternal(this.chooseType(tag, defaultType, type), elementType, anchor);
} | [
"protected",
"Object",
"readValue",
"(",
"Class",
"type",
",",
"Class",
"elementType",
",",
"Class",
"defaultType",
")",
"throws",
"YamlException",
",",
"ParserException",
",",
"TokenizerException",
"{",
"String",
"tag",
"=",
"null",
",",
"anchor",
"=",
"null",
... | Reads an object from the YAML. Can be overidden to take some action for any of the objects returned. | [
"Reads",
"an",
"object",
"from",
"the",
"YAML",
".",
"Can",
"be",
"overidden",
"to",
"take",
"some",
"action",
"for",
"any",
"of",
"the",
"objects",
"returned",
"."
] | f5610997edbc5534fc7e9f0a91654d14742345ca | https://github.com/EsotericSoftware/yamlbeans/blob/f5610997edbc5534fc7e9f0a91654d14742345ca/src/com/esotericsoftware/yamlbeans/YamlReader.java#L114-L139 | train |
EsotericSoftware/yamlbeans | src/com/esotericsoftware/yamlbeans/YamlReader.java | YamlReader.createObject | protected Object createObject (Class type) throws InvocationTargetException {
// Use deferred construction if a non-zero-arg constructor is available.
DeferredConstruction deferredConstruction = Beans.getDeferredConstruction(type, config);
if (deferredConstruction != null) return deferredConstruction;
return Beans.createObject(type, config.privateConstructors);
} | java | protected Object createObject (Class type) throws InvocationTargetException {
// Use deferred construction if a non-zero-arg constructor is available.
DeferredConstruction deferredConstruction = Beans.getDeferredConstruction(type, config);
if (deferredConstruction != null) return deferredConstruction;
return Beans.createObject(type, config.privateConstructors);
} | [
"protected",
"Object",
"createObject",
"(",
"Class",
"type",
")",
"throws",
"InvocationTargetException",
"{",
"// Use deferred construction if a non-zero-arg constructor is available.\r",
"DeferredConstruction",
"deferredConstruction",
"=",
"Beans",
".",
"getDeferredConstruction",
... | Returns a new object of the requested type. | [
"Returns",
"a",
"new",
"object",
"of",
"the",
"requested",
"type",
"."
] | f5610997edbc5534fc7e9f0a91654d14742345ca | https://github.com/EsotericSoftware/yamlbeans/blob/f5610997edbc5534fc7e9f0a91654d14742345ca/src/com/esotericsoftware/yamlbeans/YamlReader.java#L460-L465 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlStreamRenderer.java | HtmlStreamRenderer.error | private final void error(String message, CharSequence identifier) {
if (badHtmlHandler != Handler.DO_NOTHING) { // Avoid string append.
badHtmlHandler.handle(message + " : " + identifier);
}
} | java | private final void error(String message, CharSequence identifier) {
if (badHtmlHandler != Handler.DO_NOTHING) { // Avoid string append.
badHtmlHandler.handle(message + " : " + identifier);
}
} | [
"private",
"final",
"void",
"error",
"(",
"String",
"message",
",",
"CharSequence",
"identifier",
")",
"{",
"if",
"(",
"badHtmlHandler",
"!=",
"Handler",
".",
"DO_NOTHING",
")",
"{",
"// Avoid string append.",
"badHtmlHandler",
".",
"handle",
"(",
"message",
"+"... | Called when the series of calls make no sense.
May be overridden to throw an unchecked throwable, to log, or to take some
other action.
@param message for human consumption.
@param identifier an HTML identifier associated with the message. | [
"Called",
"when",
"the",
"series",
"of",
"calls",
"make",
"no",
"sense",
".",
"May",
"be",
"overridden",
"to",
"throw",
"an",
"unchecked",
"throwable",
"to",
"log",
"or",
"to",
"take",
"some",
"other",
"action",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlStreamRenderer.java#L115-L119 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlStreamRenderer.java | HtmlStreamRenderer.safeName | static String safeName(String unsafeElementName) {
String elementName = HtmlLexer.canonicalName(unsafeElementName);
// Substitute a reliably non-raw-text element for raw-text and
// plain-text elements.
switch (elementName.length()) {
case 3:
if ("xmp".equals(elementName)) { return "pre"; }
break;
case 7:
if ("listing".equals(elementName)) { return "pre"; }
break;
case 9:
if ("plaintext".equals(elementName)) { return "pre"; }
break;
}
return elementName;
} | java | static String safeName(String unsafeElementName) {
String elementName = HtmlLexer.canonicalName(unsafeElementName);
// Substitute a reliably non-raw-text element for raw-text and
// plain-text elements.
switch (elementName.length()) {
case 3:
if ("xmp".equals(elementName)) { return "pre"; }
break;
case 7:
if ("listing".equals(elementName)) { return "pre"; }
break;
case 9:
if ("plaintext".equals(elementName)) { return "pre"; }
break;
}
return elementName;
} | [
"static",
"String",
"safeName",
"(",
"String",
"unsafeElementName",
")",
"{",
"String",
"elementName",
"=",
"HtmlLexer",
".",
"canonicalName",
"(",
"unsafeElementName",
")",
";",
"// Substitute a reliably non-raw-text element for raw-text and",
"// plain-text elements.",
"swi... | Canonicalizes the element name and possibly substitutes an alternative
that has more consistent semantics. | [
"Canonicalizes",
"the",
"element",
"name",
"and",
"possibly",
"substitutes",
"an",
"alternative",
"that",
"has",
"more",
"consistent",
"semantics",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlStreamRenderer.java#L388-L405 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/Trie.java | Trie.lookup | public Trie lookup(char ch) {
int i = Arrays.binarySearch(childMap, ch);
return i >= 0 ? children[i] : null;
} | java | public Trie lookup(char ch) {
int i = Arrays.binarySearch(childMap, ch);
return i >= 0 ? children[i] : null;
} | [
"public",
"Trie",
"lookup",
"(",
"char",
"ch",
")",
"{",
"int",
"i",
"=",
"Arrays",
".",
"binarySearch",
"(",
"childMap",
",",
"ch",
")",
";",
"return",
"i",
">=",
"0",
"?",
"children",
"[",
"i",
"]",
":",
"null",
";",
"}"
] | The child corresponding to the given character.
@return null if no such trie. | [
"The",
"child",
"corresponding",
"to",
"the",
"given",
"character",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/Trie.java#L125-L128 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/Trie.java | Trie.lookup | public Trie lookup(CharSequence s) {
Trie t = this;
for (int i = 0, n = s.length(); i < n; ++i) {
t = t.lookup(s.charAt(i));
if (null == t) { break; }
}
return t;
} | java | public Trie lookup(CharSequence s) {
Trie t = this;
for (int i = 0, n = s.length(); i < n; ++i) {
t = t.lookup(s.charAt(i));
if (null == t) { break; }
}
return t;
} | [
"public",
"Trie",
"lookup",
"(",
"CharSequence",
"s",
")",
"{",
"Trie",
"t",
"=",
"this",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"s",
".",
"length",
"(",
")",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"t",
"=",
"t",
"."... | The descendant of this trie corresponding to the string for this trie
appended with s.
@param s non null.
@return null if no such trie. | [
"The",
"descendant",
"of",
"this",
"trie",
"corresponding",
"to",
"the",
"string",
"for",
"this",
"trie",
"appended",
"with",
"s",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/Trie.java#L136-L143 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/FilterUrlByProtocolAttributePolicy.java | FilterUrlByProtocolAttributePolicy.normalizeUri | static String normalizeUri(String s) {
int n = s.length();
boolean colonsIrrelevant = false;
for (int i = 0; i < n; ++i) {
char ch = s.charAt(i);
switch (ch) {
case '/': case '#': case '?': case ':':
colonsIrrelevant = true;
break;
case '(': case ')':
case '{': case '}':
return normalizeUriFrom(s, i, colonsIrrelevant);
case '\u0589':
case '\u05c3':
case '\u2236':
case '\uff1a':
if (!colonsIrrelevant) {
return normalizeUriFrom(s, i, false);
}
break;
default:
if (ch <= 0x20) {
return normalizeUriFrom(s, i, false);
}
break;
}
}
return s;
} | java | static String normalizeUri(String s) {
int n = s.length();
boolean colonsIrrelevant = false;
for (int i = 0; i < n; ++i) {
char ch = s.charAt(i);
switch (ch) {
case '/': case '#': case '?': case ':':
colonsIrrelevant = true;
break;
case '(': case ')':
case '{': case '}':
return normalizeUriFrom(s, i, colonsIrrelevant);
case '\u0589':
case '\u05c3':
case '\u2236':
case '\uff1a':
if (!colonsIrrelevant) {
return normalizeUriFrom(s, i, false);
}
break;
default:
if (ch <= 0x20) {
return normalizeUriFrom(s, i, false);
}
break;
}
}
return s;
} | [
"static",
"String",
"normalizeUri",
"(",
"String",
"s",
")",
"{",
"int",
"n",
"=",
"s",
".",
"length",
"(",
")",
";",
"boolean",
"colonsIrrelevant",
"=",
"false",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"... | Percent encodes anything that looks like a colon, or a parenthesis. | [
"Percent",
"encodes",
"anything",
"that",
"looks",
"like",
"a",
"colon",
"or",
"a",
"parenthesis",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/FilterUrlByProtocolAttributePolicy.java#L97-L125 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlElementTables.java | HtmlElementTables.canContain | public boolean canContain(int parent, int child) {
if (nofeatureElements.get(parent)) {
// It's hard to interrogate a browser about the behavior of
// <noscript> in scriptless mode using JavaScript, and the
// behavior of <noscript> is more dangerous when in that mode,
// so we hardcode that mode here as a worst case assumption.
return true;
}
return child == TEXT_NODE
? canContainText(parent)
: canContain.get(parent, child);
} | java | public boolean canContain(int parent, int child) {
if (nofeatureElements.get(parent)) {
// It's hard to interrogate a browser about the behavior of
// <noscript> in scriptless mode using JavaScript, and the
// behavior of <noscript> is more dangerous when in that mode,
// so we hardcode that mode here as a worst case assumption.
return true;
}
return child == TEXT_NODE
? canContainText(parent)
: canContain.get(parent, child);
} | [
"public",
"boolean",
"canContain",
"(",
"int",
"parent",
",",
"int",
"child",
")",
"{",
"if",
"(",
"nofeatureElements",
".",
"get",
"(",
"parent",
")",
")",
"{",
"// It's hard to interrogate a browser about the behavior of",
"// <noscript> in scriptless mode using JavaScr... | True if parent can directly contain child. | [
"True",
"if",
"parent",
"can",
"directly",
"contain",
"child",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlElementTables.java#L193-L205 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlElementTables.java | HtmlElementTables.impliedElements | int[] impliedElements(int anc, int desc) {
// <style> and <script> are allowed anywhere.
if (desc == SCRIPT_TAG || desc == STYLE_TAG) {
return ZERO_INTS;
}
// It's dangerous to allow free <li> tags because of the way an <li>
// implies a </li> if there is an <li> on the parse stack without a
// LIST_SCOPE element in the middle.
// Since we don't control the context in which sanitized HTML is embedded,
// we can't assume that there isn't a containing <li> tag before parsing
// starts, so we make sure we never produce an <li> or <td> without a
// corresponding LIST or TABLE scope element on the stack.
// <select> is not a scope for <option> elements, but we do that too for
// symmetry and as an extra degree of safety against future spec changes.
FreeWrapper wrapper = desc != TEXT_NODE && desc < FREE_WRAPPERS.length
? FREE_WRAPPERS[desc] : null;
if (wrapper != null) {
if (anc < wrapper.allowedContainers.length
&& !wrapper.allowedContainers[anc]) {
return wrapper.implied;
}
}
if (desc != TEXT_NODE) {
int[] implied = impliedElements.getElementIndexList(anc, desc);
// This handles the table case at least
if (implied.length != 0) { return implied; }
}
// If we require above that all <li>s appear in a <ul> or <ol> then
// for symmetry, we require here that all content of a <ul> or <ol> appear
// nested in a <li>.
// This does not have the same security implications as the above, but is
// symmetric.
int[] oneImplied = null;
if (anc == OL_TAG || anc == UL_TAG) {
oneImplied = LI_TAG_ARR;
} else if (anc == SELECT_TAG) {
oneImplied = OPTION_TAG_ARR;
}
if (oneImplied != null) {
if (desc != oneImplied[0]) {
return LI_TAG_ARR;
}
}
// TODO: why are we dropping OPTION_AG_ARR?
return ZERO_INTS;
} | java | int[] impliedElements(int anc, int desc) {
// <style> and <script> are allowed anywhere.
if (desc == SCRIPT_TAG || desc == STYLE_TAG) {
return ZERO_INTS;
}
// It's dangerous to allow free <li> tags because of the way an <li>
// implies a </li> if there is an <li> on the parse stack without a
// LIST_SCOPE element in the middle.
// Since we don't control the context in which sanitized HTML is embedded,
// we can't assume that there isn't a containing <li> tag before parsing
// starts, so we make sure we never produce an <li> or <td> without a
// corresponding LIST or TABLE scope element on the stack.
// <select> is not a scope for <option> elements, but we do that too for
// symmetry and as an extra degree of safety against future spec changes.
FreeWrapper wrapper = desc != TEXT_NODE && desc < FREE_WRAPPERS.length
? FREE_WRAPPERS[desc] : null;
if (wrapper != null) {
if (anc < wrapper.allowedContainers.length
&& !wrapper.allowedContainers[anc]) {
return wrapper.implied;
}
}
if (desc != TEXT_NODE) {
int[] implied = impliedElements.getElementIndexList(anc, desc);
// This handles the table case at least
if (implied.length != 0) { return implied; }
}
// If we require above that all <li>s appear in a <ul> or <ol> then
// for symmetry, we require here that all content of a <ul> or <ol> appear
// nested in a <li>.
// This does not have the same security implications as the above, but is
// symmetric.
int[] oneImplied = null;
if (anc == OL_TAG || anc == UL_TAG) {
oneImplied = LI_TAG_ARR;
} else if (anc == SELECT_TAG) {
oneImplied = OPTION_TAG_ARR;
}
if (oneImplied != null) {
if (desc != oneImplied[0]) {
return LI_TAG_ARR;
}
}
// TODO: why are we dropping OPTION_AG_ARR?
return ZERO_INTS;
} | [
"int",
"[",
"]",
"impliedElements",
"(",
"int",
"anc",
",",
"int",
"desc",
")",
"{",
"// <style> and <script> are allowed anywhere.",
"if",
"(",
"desc",
"==",
"SCRIPT_TAG",
"||",
"desc",
"==",
"STYLE_TAG",
")",
"{",
"return",
"ZERO_INTS",
";",
"}",
"// It's da... | Elements in order which are implicitly opened when a descendant tag is
lexically nested within an ancestor. | [
"Elements",
"in",
"order",
"which",
"are",
"implicitly",
"opened",
"when",
"a",
"descendant",
"tag",
"is",
"lexically",
"nested",
"within",
"an",
"ancestor",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlElementTables.java#L325-L374 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlLexer.java | HtmlLexer.canonicalName | static String canonicalName(String elementOrAttribName) {
return elementOrAttribName.indexOf(':') >= 0
? elementOrAttribName : Strings.toLowerCase(elementOrAttribName);
} | java | static String canonicalName(String elementOrAttribName) {
return elementOrAttribName.indexOf(':') >= 0
? elementOrAttribName : Strings.toLowerCase(elementOrAttribName);
} | [
"static",
"String",
"canonicalName",
"(",
"String",
"elementOrAttribName",
")",
"{",
"return",
"elementOrAttribName",
".",
"indexOf",
"(",
"'",
"'",
")",
">=",
"0",
"?",
"elementOrAttribName",
":",
"Strings",
".",
"toLowerCase",
"(",
"elementOrAttribName",
")",
... | Normalize case of names that are not name-spaced. This lower-cases HTML
element and attribute names, but not ones for embedded SVG or MATHML. | [
"Normalize",
"case",
"of",
"names",
"that",
"are",
"not",
"name",
"-",
"spaced",
".",
"This",
"lower",
"-",
"cases",
"HTML",
"element",
"and",
"attribute",
"names",
"but",
"not",
"ones",
"for",
"embedded",
"SVG",
"or",
"MATHML",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlLexer.java#L60-L63 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlLexer.java | HtmlLexer.produce | @Override
protected HtmlToken produce() {
HtmlToken token = readToken();
if (token == null) { return null; }
switch (token.type) {
// Keep track of whether we're inside a tag or not.
case TAGBEGIN:
state = State.IN_TAG;
break;
case TAGEND:
if (state == State.SAW_EQ && HtmlTokenType.TAGEND == token.type) {
// Distinguish <input type=checkbox checked=> from
// <input type=checkbox checked>
pushbackToken(token);
state = State.IN_TAG;
return HtmlToken.instance(
token.start, token.start, HtmlTokenType.ATTRVALUE);
}
state = State.OUTSIDE_TAG;
break;
// Drop ignorable tokens by zeroing out the one received and recursing
case IGNORABLE:
return produce();
// collapse adjacent text nodes if we're outside a tag, or otherwise,
// Recognize attribute names and values.
default:
switch (state) {
case OUTSIDE_TAG:
if (HtmlTokenType.TEXT == token.type
|| HtmlTokenType.UNESCAPED == token.type) {
token = collapseSubsequent(token);
}
break;
case IN_TAG:
if (HtmlTokenType.TEXT == token.type
&& !token.tokenInContextMatches(input, "=")) {
// Reclassify as attribute name
token = HtmlInputSplitter.reclassify(
token, HtmlTokenType.ATTRNAME);
state = State.SAW_NAME;
}
break;
case SAW_NAME:
if (HtmlTokenType.TEXT == token.type) {
if (token.tokenInContextMatches(input, "=")) {
state = State.SAW_EQ;
// Skip the '=' token
return produce();
} else {
// Reclassify as attribute name
token = HtmlInputSplitter.reclassify(
token, HtmlTokenType.ATTRNAME);
}
} else {
state = State.IN_TAG;
}
break;
case SAW_EQ:
if (HtmlTokenType.TEXT == token.type
|| HtmlTokenType.QSTRING == token.type) {
if (HtmlTokenType.TEXT == token.type) {
// Collapse adjacent text nodes to properly handle
// <a onclick=this.clicked=true>
// <a title=foo bar>
token = collapseAttributeName(token);
}
// Reclassify as value
token = HtmlInputSplitter.reclassify(
token, HtmlTokenType.ATTRVALUE);
state = State.IN_TAG;
}
break;
}
break;
}
return token;
} | java | @Override
protected HtmlToken produce() {
HtmlToken token = readToken();
if (token == null) { return null; }
switch (token.type) {
// Keep track of whether we're inside a tag or not.
case TAGBEGIN:
state = State.IN_TAG;
break;
case TAGEND:
if (state == State.SAW_EQ && HtmlTokenType.TAGEND == token.type) {
// Distinguish <input type=checkbox checked=> from
// <input type=checkbox checked>
pushbackToken(token);
state = State.IN_TAG;
return HtmlToken.instance(
token.start, token.start, HtmlTokenType.ATTRVALUE);
}
state = State.OUTSIDE_TAG;
break;
// Drop ignorable tokens by zeroing out the one received and recursing
case IGNORABLE:
return produce();
// collapse adjacent text nodes if we're outside a tag, or otherwise,
// Recognize attribute names and values.
default:
switch (state) {
case OUTSIDE_TAG:
if (HtmlTokenType.TEXT == token.type
|| HtmlTokenType.UNESCAPED == token.type) {
token = collapseSubsequent(token);
}
break;
case IN_TAG:
if (HtmlTokenType.TEXT == token.type
&& !token.tokenInContextMatches(input, "=")) {
// Reclassify as attribute name
token = HtmlInputSplitter.reclassify(
token, HtmlTokenType.ATTRNAME);
state = State.SAW_NAME;
}
break;
case SAW_NAME:
if (HtmlTokenType.TEXT == token.type) {
if (token.tokenInContextMatches(input, "=")) {
state = State.SAW_EQ;
// Skip the '=' token
return produce();
} else {
// Reclassify as attribute name
token = HtmlInputSplitter.reclassify(
token, HtmlTokenType.ATTRNAME);
}
} else {
state = State.IN_TAG;
}
break;
case SAW_EQ:
if (HtmlTokenType.TEXT == token.type
|| HtmlTokenType.QSTRING == token.type) {
if (HtmlTokenType.TEXT == token.type) {
// Collapse adjacent text nodes to properly handle
// <a onclick=this.clicked=true>
// <a title=foo bar>
token = collapseAttributeName(token);
}
// Reclassify as value
token = HtmlInputSplitter.reclassify(
token, HtmlTokenType.ATTRVALUE);
state = State.IN_TAG;
}
break;
}
break;
}
return token;
} | [
"@",
"Override",
"protected",
"HtmlToken",
"produce",
"(",
")",
"{",
"HtmlToken",
"token",
"=",
"readToken",
"(",
")",
";",
"if",
"(",
"token",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"switch",
"(",
"token",
".",
"type",
")",
"{",
"// Kee... | Makes sure that this.token contains a token if one is available.
This may require fetching and combining multiple tokens from the underlying
splitter. | [
"Makes",
"sure",
"that",
"this",
".",
"token",
"contains",
"a",
"token",
"if",
"one",
"is",
"available",
".",
"This",
"may",
"require",
"fetching",
"and",
"combining",
"multiple",
"tokens",
"from",
"the",
"underlying",
"splitter",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlLexer.java#L82-L164 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlLexer.java | HtmlLexer.collapseSubsequent | private HtmlToken collapseSubsequent(HtmlToken token) {
HtmlToken collapsed = token;
for (HtmlToken next;
(next= peekToken(0)) != null && next.type == token.type;
readToken()) {
collapsed = join(collapsed, next);
}
return collapsed;
} | java | private HtmlToken collapseSubsequent(HtmlToken token) {
HtmlToken collapsed = token;
for (HtmlToken next;
(next= peekToken(0)) != null && next.type == token.type;
readToken()) {
collapsed = join(collapsed, next);
}
return collapsed;
} | [
"private",
"HtmlToken",
"collapseSubsequent",
"(",
"HtmlToken",
"token",
")",
"{",
"HtmlToken",
"collapsed",
"=",
"token",
";",
"for",
"(",
"HtmlToken",
"next",
";",
"(",
"next",
"=",
"peekToken",
"(",
"0",
")",
")",
"!=",
"null",
"&&",
"next",
".",
"typ... | Collapses all the following tokens of the same type into this.token. | [
"Collapses",
"all",
"the",
"following",
"tokens",
"of",
"the",
"same",
"type",
"into",
"this",
".",
"token",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlLexer.java#L169-L177 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlLexer.java | HtmlLexer.isValuelessAttribute | private static boolean isValuelessAttribute(String attribName) {
boolean valueless = VALUELESS_ATTRIB_NAMES.contains(
Strings.toLowerCase(attribName));
return valueless;
} | java | private static boolean isValuelessAttribute(String attribName) {
boolean valueless = VALUELESS_ATTRIB_NAMES.contains(
Strings.toLowerCase(attribName));
return valueless;
} | [
"private",
"static",
"boolean",
"isValuelessAttribute",
"(",
"String",
"attribName",
")",
"{",
"boolean",
"valueless",
"=",
"VALUELESS_ATTRIB_NAMES",
".",
"contains",
"(",
"Strings",
".",
"toLowerCase",
"(",
"attribName",
")",
")",
";",
"return",
"valueless",
";",... | Can the attribute appear in HTML without a value. | [
"Can",
"the",
"attribute",
"appear",
"in",
"HTML",
"without",
"a",
"value",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlLexer.java#L245-L249 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlLexer.java | HtmlInputSplitter.produce | @Override
protected HtmlToken produce() {
HtmlToken token = parseToken();
if (null == token) { return null; }
// Handle escape-exempt blocks.
// The parse() method is only dimly aware of escape-excempt blocks, so
// here we detect the beginning and ends of escape exempt blocks, and
// reclassify as UNESCAPED, any tokens that appear in the middle.
if (inEscapeExemptBlock) {
if (token.type != HtmlTokenType.SERVERCODE) {
// classify RCDATA as text since it can contain entities
token = reclassify(
token, (this.textEscapingMode == HtmlTextEscapingMode.RCDATA
? HtmlTokenType.TEXT
: HtmlTokenType.UNESCAPED));
}
} else {
switch (token.type) {
case TAGBEGIN:
{
String canonTagName = canonicalName(
token.start + 1, token.end);
if (HtmlTextEscapingMode.isTagFollowedByLiteralContent(
canonTagName)) {
this.escapeExemptTagName = canonTagName;
this.textEscapingMode = HtmlTextEscapingMode.getModeForTag(
canonTagName);
}
break;
}
case TAGEND:
this.inEscapeExemptBlock = null != this.escapeExemptTagName;
break;
default:
break;
}
}
return token;
} | java | @Override
protected HtmlToken produce() {
HtmlToken token = parseToken();
if (null == token) { return null; }
// Handle escape-exempt blocks.
// The parse() method is only dimly aware of escape-excempt blocks, so
// here we detect the beginning and ends of escape exempt blocks, and
// reclassify as UNESCAPED, any tokens that appear in the middle.
if (inEscapeExemptBlock) {
if (token.type != HtmlTokenType.SERVERCODE) {
// classify RCDATA as text since it can contain entities
token = reclassify(
token, (this.textEscapingMode == HtmlTextEscapingMode.RCDATA
? HtmlTokenType.TEXT
: HtmlTokenType.UNESCAPED));
}
} else {
switch (token.type) {
case TAGBEGIN:
{
String canonTagName = canonicalName(
token.start + 1, token.end);
if (HtmlTextEscapingMode.isTagFollowedByLiteralContent(
canonTagName)) {
this.escapeExemptTagName = canonTagName;
this.textEscapingMode = HtmlTextEscapingMode.getModeForTag(
canonTagName);
}
break;
}
case TAGEND:
this.inEscapeExemptBlock = null != this.escapeExemptTagName;
break;
default:
break;
}
}
return token;
} | [
"@",
"Override",
"protected",
"HtmlToken",
"produce",
"(",
")",
"{",
"HtmlToken",
"token",
"=",
"parseToken",
"(",
")",
";",
"if",
"(",
"null",
"==",
"token",
")",
"{",
"return",
"null",
";",
"}",
"// Handle escape-exempt blocks.",
"// The parse() method is only... | Make sure that there is a token ready to yield in this.token. | [
"Make",
"sure",
"that",
"there",
"is",
"a",
"token",
"ready",
"to",
"yield",
"in",
"this",
".",
"token",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlLexer.java#L293-L332 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlPolicyBuilder.java | HtmlPolicyBuilder.allowElements | public HtmlPolicyBuilder allowElements(
ElementPolicy policy, String... elementNames) {
invalidateCompiledState();
for (String elementName : elementNames) {
elementName = HtmlLexer.canonicalName(elementName);
ElementPolicy newPolicy = ElementPolicy.Util.join(
elPolicies.get(elementName), policy);
// Don't remove if newPolicy is the always reject policy since we want
// that to infect later allowElement calls for this particular element
// name. rejects should have higher priority than allows.
elPolicies.put(elementName, newPolicy);
if (!textContainers.containsKey(elementName)) {
if (METADATA.canContainPlainText(METADATA.indexForName(elementName))) {
textContainers.put(elementName, true);
}
}
}
return this;
} | java | public HtmlPolicyBuilder allowElements(
ElementPolicy policy, String... elementNames) {
invalidateCompiledState();
for (String elementName : elementNames) {
elementName = HtmlLexer.canonicalName(elementName);
ElementPolicy newPolicy = ElementPolicy.Util.join(
elPolicies.get(elementName), policy);
// Don't remove if newPolicy is the always reject policy since we want
// that to infect later allowElement calls for this particular element
// name. rejects should have higher priority than allows.
elPolicies.put(elementName, newPolicy);
if (!textContainers.containsKey(elementName)) {
if (METADATA.canContainPlainText(METADATA.indexForName(elementName))) {
textContainers.put(elementName, true);
}
}
}
return this;
} | [
"public",
"HtmlPolicyBuilder",
"allowElements",
"(",
"ElementPolicy",
"policy",
",",
"String",
"...",
"elementNames",
")",
"{",
"invalidateCompiledState",
"(",
")",
";",
"for",
"(",
"String",
"elementName",
":",
"elementNames",
")",
"{",
"elementName",
"=",
"HtmlL... | Allow the given elements with the given policy.
@param policy May remove or add attributes, change the element name, or
deny the element. | [
"Allow",
"the",
"given",
"elements",
"with",
"the",
"given",
"policy",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlPolicyBuilder.java#L229-L247 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlPolicyBuilder.java | HtmlPolicyBuilder.allowWithoutAttributes | public HtmlPolicyBuilder allowWithoutAttributes(String... elementNames) {
invalidateCompiledState();
for (String elementName : elementNames) {
elementName = HtmlLexer.canonicalName(elementName);
skipIfEmpty.remove(elementName);
}
return this;
} | java | public HtmlPolicyBuilder allowWithoutAttributes(String... elementNames) {
invalidateCompiledState();
for (String elementName : elementNames) {
elementName = HtmlLexer.canonicalName(elementName);
skipIfEmpty.remove(elementName);
}
return this;
} | [
"public",
"HtmlPolicyBuilder",
"allowWithoutAttributes",
"(",
"String",
"...",
"elementNames",
")",
"{",
"invalidateCompiledState",
"(",
")",
";",
"for",
"(",
"String",
"elementName",
":",
"elementNames",
")",
"{",
"elementName",
"=",
"HtmlLexer",
".",
"canonicalNam... | Assuming the given elements are allowed, allows them to appear without
attributes.
@see #DEFAULT_SKIP_IF_EMPTY
@see #disallowWithoutAttributes | [
"Assuming",
"the",
"given",
"elements",
"are",
"allowed",
"allows",
"them",
"to",
"appear",
"without",
"attributes",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlPolicyBuilder.java#L313-L320 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlPolicyBuilder.java | HtmlPolicyBuilder.disallowWithoutAttributes | public HtmlPolicyBuilder disallowWithoutAttributes(String... elementNames) {
invalidateCompiledState();
for (String elementName : elementNames) {
elementName = HtmlLexer.canonicalName(elementName);
skipIfEmpty.add(elementName);
}
return this;
} | java | public HtmlPolicyBuilder disallowWithoutAttributes(String... elementNames) {
invalidateCompiledState();
for (String elementName : elementNames) {
elementName = HtmlLexer.canonicalName(elementName);
skipIfEmpty.add(elementName);
}
return this;
} | [
"public",
"HtmlPolicyBuilder",
"disallowWithoutAttributes",
"(",
"String",
"...",
"elementNames",
")",
"{",
"invalidateCompiledState",
"(",
")",
";",
"for",
"(",
"String",
"elementName",
":",
"elementNames",
")",
"{",
"elementName",
"=",
"HtmlLexer",
".",
"canonical... | Disallows the given elements from appearing without attributes.
@see #DEFAULT_SKIP_IF_EMPTY
@see #allowWithoutAttributes | [
"Disallows",
"the",
"given",
"elements",
"from",
"appearing",
"without",
"attributes",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlPolicyBuilder.java#L328-L335 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlPolicyBuilder.java | HtmlPolicyBuilder.allowAttributes | public AttributeBuilder allowAttributes(String... attributeNames) {
ImmutableList.Builder<String> b = ImmutableList.builder();
for (String attributeName : attributeNames) {
b.add(HtmlLexer.canonicalName(attributeName));
}
return new AttributeBuilder(b.build());
} | java | public AttributeBuilder allowAttributes(String... attributeNames) {
ImmutableList.Builder<String> b = ImmutableList.builder();
for (String attributeName : attributeNames) {
b.add(HtmlLexer.canonicalName(attributeName));
}
return new AttributeBuilder(b.build());
} | [
"public",
"AttributeBuilder",
"allowAttributes",
"(",
"String",
"...",
"attributeNames",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"String",
">",
"b",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"for",
"(",
"String",
"attributeName",
":",
"attri... | Returns an object that lets you associate policies with the given
attributes, and allow them globally or on specific elements. | [
"Returns",
"an",
"object",
"that",
"lets",
"you",
"associate",
"policies",
"with",
"the",
"given",
"attributes",
"and",
"allow",
"them",
"globally",
"or",
"on",
"specific",
"elements",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlPolicyBuilder.java#L341-L347 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/HtmlPolicyBuilder.java | HtmlPolicyBuilder.withPreprocessor | public HtmlPolicyBuilder withPreprocessor(HtmlStreamEventProcessor pp) {
this.preprocessor = HtmlStreamEventProcessor.Processors.compose(
this.preprocessor, pp);
return this;
} | java | public HtmlPolicyBuilder withPreprocessor(HtmlStreamEventProcessor pp) {
this.preprocessor = HtmlStreamEventProcessor.Processors.compose(
this.preprocessor, pp);
return this;
} | [
"public",
"HtmlPolicyBuilder",
"withPreprocessor",
"(",
"HtmlStreamEventProcessor",
"pp",
")",
"{",
"this",
".",
"preprocessor",
"=",
"HtmlStreamEventProcessor",
".",
"Processors",
".",
"compose",
"(",
"this",
".",
"preprocessor",
",",
"pp",
")",
";",
"return",
"t... | Inserts a pre-processor into the pipeline between the lexer and the policy.
Pre-processors receive HTML events before the policy, so the policy will
be applied to anything they add.
Pre-processors are not in the TCB since they cannot bypass the policy. | [
"Inserts",
"a",
"pre",
"-",
"processor",
"into",
"the",
"pipeline",
"between",
"the",
"lexer",
"and",
"the",
"policy",
".",
"Pre",
"-",
"processors",
"receive",
"HTML",
"events",
"before",
"the",
"policy",
"so",
"the",
"policy",
"will",
"be",
"applied",
"t... | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/HtmlPolicyBuilder.java#L567-L571 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/examples/SlashdotPolicyExample.java | SlashdotPolicyExample.main | public static void main(String[] args) throws IOException {
if (args.length != 0) {
System.err.println("Reads from STDIN and writes to STDOUT");
System.exit(-1);
}
System.err.println("[Reading from STDIN]");
// Fetch the HTML to sanitize.
String html = CharStreams.toString(
new InputStreamReader(System.in, Charsets.UTF_8));
// Set up an output channel to receive the sanitized HTML.
HtmlStreamRenderer renderer = HtmlStreamRenderer.create(
System.out,
// Receives notifications on a failure to write to the output.
new Handler<IOException>() {
public void handle(IOException ex) {
// System.out suppresses IOExceptions
throw new AssertionError(null, ex);
}
},
// Our HTML parser is very lenient, but this receives notifications on
// truly bizarre inputs.
new Handler<String>() {
public void handle(String x) {
throw new AssertionError(x);
}
});
// Use the policy defined above to sanitize the HTML.
HtmlSanitizer.sanitize(html, POLICY_DEFINITION.apply(renderer));
} | java | public static void main(String[] args) throws IOException {
if (args.length != 0) {
System.err.println("Reads from STDIN and writes to STDOUT");
System.exit(-1);
}
System.err.println("[Reading from STDIN]");
// Fetch the HTML to sanitize.
String html = CharStreams.toString(
new InputStreamReader(System.in, Charsets.UTF_8));
// Set up an output channel to receive the sanitized HTML.
HtmlStreamRenderer renderer = HtmlStreamRenderer.create(
System.out,
// Receives notifications on a failure to write to the output.
new Handler<IOException>() {
public void handle(IOException ex) {
// System.out suppresses IOExceptions
throw new AssertionError(null, ex);
}
},
// Our HTML parser is very lenient, but this receives notifications on
// truly bizarre inputs.
new Handler<String>() {
public void handle(String x) {
throw new AssertionError(x);
}
});
// Use the policy defined above to sanitize the HTML.
HtmlSanitizer.sanitize(html, POLICY_DEFINITION.apply(renderer));
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"IOException",
"{",
"if",
"(",
"args",
".",
"length",
"!=",
"0",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"Reads from STDIN and writes to STDOUT\"",
")",
";",... | A test-bed that reads HTML from stdin and writes sanitized content to
stdout. | [
"A",
"test",
"-",
"bed",
"that",
"reads",
"HTML",
"from",
"stdin",
"and",
"writes",
"sanitized",
"content",
"to",
"stdout",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/examples/SlashdotPolicyExample.java#L95-L123 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/Encoding.java | Encoding.decodeHtml | public static String decodeHtml(String s) {
int firstAmp = s.indexOf('&');
int safeLimit = longestPrefixOfGoodCodeunits(s);
if ((firstAmp & safeLimit) < 0) { return s; }
StringBuilder sb;
{
int n = s.length();
sb = new StringBuilder(n);
int pos = 0;
int amp = firstAmp;
while (amp >= 0) {
long endAndCodepoint = HtmlEntities.decodeEntityAt(s, amp, n);
int end = (int) (endAndCodepoint >>> 32);
int codepoint = (int) endAndCodepoint;
sb.append(s, pos, amp).appendCodePoint(codepoint);
pos = end;
amp = s.indexOf('&', end);
}
sb.append(s, pos, n);
}
stripBannedCodeunits(
sb,
firstAmp < 0
? safeLimit : safeLimit < 0
? firstAmp : Math.min(firstAmp, safeLimit));
return sb.toString();
} | java | public static String decodeHtml(String s) {
int firstAmp = s.indexOf('&');
int safeLimit = longestPrefixOfGoodCodeunits(s);
if ((firstAmp & safeLimit) < 0) { return s; }
StringBuilder sb;
{
int n = s.length();
sb = new StringBuilder(n);
int pos = 0;
int amp = firstAmp;
while (amp >= 0) {
long endAndCodepoint = HtmlEntities.decodeEntityAt(s, amp, n);
int end = (int) (endAndCodepoint >>> 32);
int codepoint = (int) endAndCodepoint;
sb.append(s, pos, amp).appendCodePoint(codepoint);
pos = end;
amp = s.indexOf('&', end);
}
sb.append(s, pos, n);
}
stripBannedCodeunits(
sb,
firstAmp < 0
? safeLimit : safeLimit < 0
? firstAmp : Math.min(firstAmp, safeLimit));
return sb.toString();
} | [
"public",
"static",
"String",
"decodeHtml",
"(",
"String",
"s",
")",
"{",
"int",
"firstAmp",
"=",
"s",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"int",
"safeLimit",
"=",
"longestPrefixOfGoodCodeunits",
"(",
"s",
")",
";",
"if",
"(",
"(",
"firstAmp",
"&"... | Decodes HTML entities to produce a string containing only valid
Unicode scalar values. | [
"Decodes",
"HTML",
"entities",
"to",
"produce",
"a",
"string",
"containing",
"only",
"valid",
"Unicode",
"scalar",
"values",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/Encoding.java#L42-L71 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/Encoding.java | Encoding.stripBannedCodeunits | @TCB
static String stripBannedCodeunits(String s) {
int safeLimit = longestPrefixOfGoodCodeunits(s);
if (safeLimit < 0) { return s; }
StringBuilder sb = new StringBuilder(s);
stripBannedCodeunits(sb, safeLimit);
return sb.toString();
} | java | @TCB
static String stripBannedCodeunits(String s) {
int safeLimit = longestPrefixOfGoodCodeunits(s);
if (safeLimit < 0) { return s; }
StringBuilder sb = new StringBuilder(s);
stripBannedCodeunits(sb, safeLimit);
return sb.toString();
} | [
"@",
"TCB",
"static",
"String",
"stripBannedCodeunits",
"(",
"String",
"s",
")",
"{",
"int",
"safeLimit",
"=",
"longestPrefixOfGoodCodeunits",
"(",
"s",
")",
";",
"if",
"(",
"safeLimit",
"<",
"0",
")",
"{",
"return",
"s",
";",
"}",
"StringBuilder",
"sb",
... | Returns the portion of its input that consists of XML safe chars.
@see <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#charsets">XML Ch. 2.2 - Characters</a> | [
"Returns",
"the",
"portion",
"of",
"its",
"input",
"that",
"consists",
"of",
"XML",
"safe",
"chars",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/Encoding.java#L77-L85 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/Encoding.java | Encoding.longestPrefixOfGoodCodeunits | @TCB
private static int longestPrefixOfGoodCodeunits(String s) {
int n = s.length(), i;
for (i = 0; i < n; ++i) {
char ch = s.charAt(i);
if (ch < 0x20) {
if (IS_BANNED_ASCII[ch]) {
return i;
}
} else if (0xd800 <= ch) {
if (ch <= 0xdfff) {
if (i+1 < n && Character.isSurrogatePair(ch, s.charAt(i+1))) {
++i; // Skip over low surrogate since we know it's ok.
} else {
return i;
}
} else if ((ch & 0xfffe) == 0xfffe) {
return i;
}
}
}
return -1;
} | java | @TCB
private static int longestPrefixOfGoodCodeunits(String s) {
int n = s.length(), i;
for (i = 0; i < n; ++i) {
char ch = s.charAt(i);
if (ch < 0x20) {
if (IS_BANNED_ASCII[ch]) {
return i;
}
} else if (0xd800 <= ch) {
if (ch <= 0xdfff) {
if (i+1 < n && Character.isSurrogatePair(ch, s.charAt(i+1))) {
++i; // Skip over low surrogate since we know it's ok.
} else {
return i;
}
} else if ((ch & 0xfffe) == 0xfffe) {
return i;
}
}
}
return -1;
} | [
"@",
"TCB",
"private",
"static",
"int",
"longestPrefixOfGoodCodeunits",
"(",
"String",
"s",
")",
"{",
"int",
"n",
"=",
"s",
".",
"length",
"(",
")",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"char",... | The number of code-units at the front of s that form code-points in the
XML Character production.
@return -1 if all of s is in the XML Character production. | [
"The",
"number",
"of",
"code",
"-",
"units",
"at",
"the",
"front",
"of",
"s",
"that",
"form",
"code",
"-",
"points",
"in",
"the",
"XML",
"Character",
"production",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/Encoding.java#L130-L152 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/TagBalancingHtmlStreamEventReceiver.java | TagBalancingHtmlStreamEventReceiver.canContain | private boolean canContain(
int child, int container, int containerIndexOnStack) {
Preconditions.checkArgument(containerIndexOnStack >= 0);
int anc = container;
int ancIndexOnStack = containerIndexOnStack;
while (true) {
if (METADATA.canContain(anc, child)) {
return true;
}
if (!TRANSPARENT.get(anc)) {
return false;
}
if (ancIndexOnStack == 0) {
return METADATA.canContain(BODY_TAG, child);
}
--ancIndexOnStack;
anc = openElements.get(ancIndexOnStack);
}
} | java | private boolean canContain(
int child, int container, int containerIndexOnStack) {
Preconditions.checkArgument(containerIndexOnStack >= 0);
int anc = container;
int ancIndexOnStack = containerIndexOnStack;
while (true) {
if (METADATA.canContain(anc, child)) {
return true;
}
if (!TRANSPARENT.get(anc)) {
return false;
}
if (ancIndexOnStack == 0) {
return METADATA.canContain(BODY_TAG, child);
}
--ancIndexOnStack;
anc = openElements.get(ancIndexOnStack);
}
} | [
"private",
"boolean",
"canContain",
"(",
"int",
"child",
",",
"int",
"container",
",",
"int",
"containerIndexOnStack",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"containerIndexOnStack",
">=",
"0",
")",
";",
"int",
"anc",
"=",
"container",
";",
"int... | Takes into account transparency when figuring out what
can be contained. | [
"Takes",
"into",
"account",
"transparency",
"when",
"figuring",
"out",
"what",
"can",
"be",
"contained",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/TagBalancingHtmlStreamEventReceiver.java#L217-L235 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/examples/UrlTextExample.java | UrlTextExample.run | public static void run(Appendable out, String... inputs) throws IOException {
PolicyFactory policyBuilder = new HtmlPolicyBuilder()
.allowAttributes("src").onElements("img")
.allowAttributes("href").onElements("a")
// Allow some URLs through.
.allowStandardUrlProtocols()
.allowElements(
"a", "label", "h1", "h2", "h3", "h4", "h5", "h6",
"p", "i", "b", "u", "strong", "em", "small", "big", "pre", "code",
"cite", "samp", "sub", "sup", "strike", "center", "blockquote",
"hr", "br", "col", "font", "span", "div", "img",
"ul", "ol", "li", "dd", "dt", "dl", "tbody", "thead", "tfoot",
"table", "td", "th", "tr", "colgroup", "fieldset", "legend"
)
.withPostprocessor(
new HtmlStreamEventProcessor() {
public HtmlStreamEventReceiver wrap(HtmlStreamEventReceiver sink) {
return new AppendDomainAfterText(sink);
}
}
).toFactory();
out.append(policyBuilder.sanitize(Joiner.on('\n').join(inputs)));
} | java | public static void run(Appendable out, String... inputs) throws IOException {
PolicyFactory policyBuilder = new HtmlPolicyBuilder()
.allowAttributes("src").onElements("img")
.allowAttributes("href").onElements("a")
// Allow some URLs through.
.allowStandardUrlProtocols()
.allowElements(
"a", "label", "h1", "h2", "h3", "h4", "h5", "h6",
"p", "i", "b", "u", "strong", "em", "small", "big", "pre", "code",
"cite", "samp", "sub", "sup", "strike", "center", "blockquote",
"hr", "br", "col", "font", "span", "div", "img",
"ul", "ol", "li", "dd", "dt", "dl", "tbody", "thead", "tfoot",
"table", "td", "th", "tr", "colgroup", "fieldset", "legend"
)
.withPostprocessor(
new HtmlStreamEventProcessor() {
public HtmlStreamEventReceiver wrap(HtmlStreamEventReceiver sink) {
return new AppendDomainAfterText(sink);
}
}
).toFactory();
out.append(policyBuilder.sanitize(Joiner.on('\n').join(inputs)));
} | [
"public",
"static",
"void",
"run",
"(",
"Appendable",
"out",
",",
"String",
"...",
"inputs",
")",
"throws",
"IOException",
"{",
"PolicyFactory",
"policyBuilder",
"=",
"new",
"HtmlPolicyBuilder",
"(",
")",
".",
"allowAttributes",
"(",
"\"src\"",
")",
".",
"onEl... | Sanitizes inputs to out. | [
"Sanitizes",
"inputs",
"to",
"out",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/examples/UrlTextExample.java#L115-L138 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/PolicyFactory.java | PolicyFactory.and | public PolicyFactory and(PolicyFactory f) {
ImmutableMap.Builder<String, ElementAndAttributePolicies> b
= ImmutableMap.builder();
// Merge this and f into a map of element names to attribute policies.
for (Map.Entry<String, ElementAndAttributePolicies> e
: policies.entrySet()) {
String elName = e.getKey();
ElementAndAttributePolicies p = e.getValue();
ElementAndAttributePolicies q = f.policies.get(elName);
if (q != null) {
p = p.and(q);
} else {
// Mix in any globals that are not already taken into account in this.
p = p.andGlobals(f.globalAttrPolicies);
}
b.put(elName, p);
}
// Handle keys that are in f but not in this.
for (Map.Entry<String, ElementAndAttributePolicies> e
: f.policies.entrySet()) {
String elName = e.getKey();
if (!policies.containsKey(elName)) {
ElementAndAttributePolicies p = e.getValue();
// Mix in any globals that are not already taken into account in this.
p = p.andGlobals(globalAttrPolicies);
b.put(elName, p);
}
}
ImmutableSet<String> allTextContainers;
if (this.textContainers.containsAll(f.textContainers)) {
allTextContainers = this.textContainers;
} else if (f.textContainers.containsAll(this.textContainers)) {
allTextContainers = f.textContainers;
} else {
allTextContainers = ImmutableSet.<String>builder()
.addAll(this.textContainers)
.addAll(f.textContainers)
.build();
}
ImmutableMap<String, AttributePolicy> allGlobalAttrPolicies;
if (f.globalAttrPolicies.isEmpty()) {
allGlobalAttrPolicies = this.globalAttrPolicies;
} else if (this.globalAttrPolicies.isEmpty()) {
allGlobalAttrPolicies = f.globalAttrPolicies;
} else {
ImmutableMap.Builder<String, AttributePolicy> ab = ImmutableMap.builder();
for (Map.Entry<String, AttributePolicy> e
: this.globalAttrPolicies.entrySet()) {
String attrName = e.getKey();
ab.put(
attrName,
AttributePolicy.Util.join(
e.getValue(), f.globalAttrPolicies.get(attrName)));
}
for (Map.Entry<String, AttributePolicy> e
: f.globalAttrPolicies.entrySet()) {
String attrName = e.getKey();
if (!this.globalAttrPolicies.containsKey(attrName)) {
ab.put(attrName, e.getValue());
}
}
allGlobalAttrPolicies = ab.build();
}
HtmlStreamEventProcessor compositionOfPreprocessors
= HtmlStreamEventProcessor.Processors.compose(
this.preprocessor, f.preprocessor);
HtmlStreamEventProcessor compositionOfPostprocessors
= HtmlStreamEventProcessor.Processors.compose(
this.postprocessor, f.postprocessor);
return new PolicyFactory(
b.build(), allTextContainers, allGlobalAttrPolicies,
compositionOfPreprocessors, compositionOfPostprocessors);
} | java | public PolicyFactory and(PolicyFactory f) {
ImmutableMap.Builder<String, ElementAndAttributePolicies> b
= ImmutableMap.builder();
// Merge this and f into a map of element names to attribute policies.
for (Map.Entry<String, ElementAndAttributePolicies> e
: policies.entrySet()) {
String elName = e.getKey();
ElementAndAttributePolicies p = e.getValue();
ElementAndAttributePolicies q = f.policies.get(elName);
if (q != null) {
p = p.and(q);
} else {
// Mix in any globals that are not already taken into account in this.
p = p.andGlobals(f.globalAttrPolicies);
}
b.put(elName, p);
}
// Handle keys that are in f but not in this.
for (Map.Entry<String, ElementAndAttributePolicies> e
: f.policies.entrySet()) {
String elName = e.getKey();
if (!policies.containsKey(elName)) {
ElementAndAttributePolicies p = e.getValue();
// Mix in any globals that are not already taken into account in this.
p = p.andGlobals(globalAttrPolicies);
b.put(elName, p);
}
}
ImmutableSet<String> allTextContainers;
if (this.textContainers.containsAll(f.textContainers)) {
allTextContainers = this.textContainers;
} else if (f.textContainers.containsAll(this.textContainers)) {
allTextContainers = f.textContainers;
} else {
allTextContainers = ImmutableSet.<String>builder()
.addAll(this.textContainers)
.addAll(f.textContainers)
.build();
}
ImmutableMap<String, AttributePolicy> allGlobalAttrPolicies;
if (f.globalAttrPolicies.isEmpty()) {
allGlobalAttrPolicies = this.globalAttrPolicies;
} else if (this.globalAttrPolicies.isEmpty()) {
allGlobalAttrPolicies = f.globalAttrPolicies;
} else {
ImmutableMap.Builder<String, AttributePolicy> ab = ImmutableMap.builder();
for (Map.Entry<String, AttributePolicy> e
: this.globalAttrPolicies.entrySet()) {
String attrName = e.getKey();
ab.put(
attrName,
AttributePolicy.Util.join(
e.getValue(), f.globalAttrPolicies.get(attrName)));
}
for (Map.Entry<String, AttributePolicy> e
: f.globalAttrPolicies.entrySet()) {
String attrName = e.getKey();
if (!this.globalAttrPolicies.containsKey(attrName)) {
ab.put(attrName, e.getValue());
}
}
allGlobalAttrPolicies = ab.build();
}
HtmlStreamEventProcessor compositionOfPreprocessors
= HtmlStreamEventProcessor.Processors.compose(
this.preprocessor, f.preprocessor);
HtmlStreamEventProcessor compositionOfPostprocessors
= HtmlStreamEventProcessor.Processors.compose(
this.postprocessor, f.postprocessor);
return new PolicyFactory(
b.build(), allTextContainers, allGlobalAttrPolicies,
compositionOfPreprocessors, compositionOfPostprocessors);
} | [
"public",
"PolicyFactory",
"and",
"(",
"PolicyFactory",
"f",
")",
"{",
"ImmutableMap",
".",
"Builder",
"<",
"String",
",",
"ElementAndAttributePolicies",
">",
"b",
"=",
"ImmutableMap",
".",
"builder",
"(",
")",
";",
"// Merge this and f into a map of element names to ... | Produces a factory that allows the union of the grants, and intersects
policies where they overlap on a particular granted attribute or element
name. | [
"Produces",
"a",
"factory",
"that",
"allows",
"the",
"union",
"of",
"the",
"grants",
"and",
"intersects",
"policies",
"where",
"they",
"overlap",
"on",
"a",
"particular",
"granted",
"attribute",
"or",
"element",
"name",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/PolicyFactory.java#L142-L214 | train |
OWASP/java-html-sanitizer | src/main/java/org/owasp/html/CssGrammar.java | CssGrammar.cssContent | static String cssContent(String token) {
int n = token.length();
int pos = 0;
StringBuilder sb = null;
if (n >= 2) {
char ch0 = token.charAt(0);
if (ch0 == '"' || ch0 == '\'') {
if (ch0 == token.charAt(n - 1)) {
pos = 1;
--n;
sb = new StringBuilder(n);
}
}
}
for (int esc; (esc = token.indexOf('\\', pos)) >= 0;) {
int end = esc + 2;
if (esc > n) { break; }
if (sb == null) { sb = new StringBuilder(n); }
sb.append(token, pos, esc);
int codepoint = token.charAt(end - 1);
if (isHex(codepoint)) {
// Parse \hhhhh<opt-break> where hhhhh is one or more hex digits
// and <opt-break> is an optional space or tab character that can be
// used to separate an escape sequence from a following literal hex
// digit.
while (end < n && isHex(token.charAt(end))) { ++end; }
try {
codepoint = Integer.parseInt(token.substring(esc + 1, end), 16);
} catch (RuntimeException ex) {
ignore(ex);
codepoint = 0xfffd; // Unknown codepoint.
}
if (end < n) {
char ch = token.charAt(end);
if (ch == ' ' || ch == '\t') { // Ignorable hex follower.
++end;
}
}
}
sb.appendCodePoint(codepoint);
pos = end;
}
if (sb == null) { return token; }
return sb.append(token, pos, n).toString();
} | java | static String cssContent(String token) {
int n = token.length();
int pos = 0;
StringBuilder sb = null;
if (n >= 2) {
char ch0 = token.charAt(0);
if (ch0 == '"' || ch0 == '\'') {
if (ch0 == token.charAt(n - 1)) {
pos = 1;
--n;
sb = new StringBuilder(n);
}
}
}
for (int esc; (esc = token.indexOf('\\', pos)) >= 0;) {
int end = esc + 2;
if (esc > n) { break; }
if (sb == null) { sb = new StringBuilder(n); }
sb.append(token, pos, esc);
int codepoint = token.charAt(end - 1);
if (isHex(codepoint)) {
// Parse \hhhhh<opt-break> where hhhhh is one or more hex digits
// and <opt-break> is an optional space or tab character that can be
// used to separate an escape sequence from a following literal hex
// digit.
while (end < n && isHex(token.charAt(end))) { ++end; }
try {
codepoint = Integer.parseInt(token.substring(esc + 1, end), 16);
} catch (RuntimeException ex) {
ignore(ex);
codepoint = 0xfffd; // Unknown codepoint.
}
if (end < n) {
char ch = token.charAt(end);
if (ch == ' ' || ch == '\t') { // Ignorable hex follower.
++end;
}
}
}
sb.appendCodePoint(codepoint);
pos = end;
}
if (sb == null) { return token; }
return sb.append(token, pos, n).toString();
} | [
"static",
"String",
"cssContent",
"(",
"String",
"token",
")",
"{",
"int",
"n",
"=",
"token",
".",
"length",
"(",
")",
";",
"int",
"pos",
"=",
"0",
";",
"StringBuilder",
"sb",
"=",
"null",
";",
"if",
"(",
"n",
">=",
"2",
")",
"{",
"char",
"ch0",
... | Decodes any escape sequences and strips any quotes from the input. | [
"Decodes",
"any",
"escape",
"sequences",
"and",
"strips",
"any",
"quotes",
"from",
"the",
"input",
"."
] | a30315fe9a41e19c449628e7ef3488b3a7856009 | https://github.com/OWASP/java-html-sanitizer/blob/a30315fe9a41e19c449628e7ef3488b3a7856009/src/main/java/org/owasp/html/CssGrammar.java#L154-L198 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/Sort.java | Sort.quickSort | private static void quickSort(int[] order, double[] values, int start, int end, int limit) {
// the while loop implements tail-recursion to avoid excessive stack calls on nasty cases
while (end - start > limit) {
// pivot by a random element
int pivotIndex = start + prng.nextInt(end - start);
double pivotValue = values[order[pivotIndex]];
// move pivot to beginning of array
swap(order, start, pivotIndex);
// we use a three way partition because many duplicate values is an important case
int low = start + 1; // low points to first value not known to be equal to pivotValue
int high = end; // high points to first value > pivotValue
int i = low; // i scans the array
while (i < high) {
// invariant: values[order[k]] == pivotValue for k in [0..low)
// invariant: values[order[k]] < pivotValue for k in [low..i)
// invariant: values[order[k]] > pivotValue for k in [high..end)
// in-loop: i < high
// in-loop: low < high
// in-loop: i >= low
double vi = values[order[i]];
if (vi == pivotValue) {
if (low != i) {
swap(order, low, i);
} else {
i++;
}
low++;
} else if (vi > pivotValue) {
high--;
swap(order, i, high);
} else {
// vi < pivotValue
i++;
}
}
// invariant: values[order[k]] == pivotValue for k in [0..low)
// invariant: values[order[k]] < pivotValue for k in [low..i)
// invariant: values[order[k]] > pivotValue for k in [high..end)
// assert i == high || low == high therefore, we are done with partition
// at this point, i==high, from [start,low) are == pivot, [low,high) are < and [high,end) are >
// we have to move the values equal to the pivot into the middle. To do this, we swap pivot
// values into the top end of the [low,high) range stopping when we run out of destinations
// or when we run out of values to copy
int from = start;
int to = high - 1;
for (i = 0; from < low && to >= low; i++) {
swap(order, from++, to--);
}
if (from == low) {
// ran out of things to copy. This means that the the last destination is the boundary
low = to + 1;
} else {
// ran out of places to copy to. This means that there are uncopied pivots and the
// boundary is at the beginning of those
low = from;
}
// checkPartition(order, values, pivotValue, start, low, high, end);
// now recurse, but arrange it so we handle the longer limit by tail recursion
if (low - start < end - high) {
quickSort(order, values, start, low, limit);
// this is really a way to do
// quickSort(order, values, high, end, limit);
start = high;
} else {
quickSort(order, values, high, end, limit);
// this is really a way to do
// quickSort(order, values, start, low, limit);
end = low;
}
}
} | java | private static void quickSort(int[] order, double[] values, int start, int end, int limit) {
// the while loop implements tail-recursion to avoid excessive stack calls on nasty cases
while (end - start > limit) {
// pivot by a random element
int pivotIndex = start + prng.nextInt(end - start);
double pivotValue = values[order[pivotIndex]];
// move pivot to beginning of array
swap(order, start, pivotIndex);
// we use a three way partition because many duplicate values is an important case
int low = start + 1; // low points to first value not known to be equal to pivotValue
int high = end; // high points to first value > pivotValue
int i = low; // i scans the array
while (i < high) {
// invariant: values[order[k]] == pivotValue for k in [0..low)
// invariant: values[order[k]] < pivotValue for k in [low..i)
// invariant: values[order[k]] > pivotValue for k in [high..end)
// in-loop: i < high
// in-loop: low < high
// in-loop: i >= low
double vi = values[order[i]];
if (vi == pivotValue) {
if (low != i) {
swap(order, low, i);
} else {
i++;
}
low++;
} else if (vi > pivotValue) {
high--;
swap(order, i, high);
} else {
// vi < pivotValue
i++;
}
}
// invariant: values[order[k]] == pivotValue for k in [0..low)
// invariant: values[order[k]] < pivotValue for k in [low..i)
// invariant: values[order[k]] > pivotValue for k in [high..end)
// assert i == high || low == high therefore, we are done with partition
// at this point, i==high, from [start,low) are == pivot, [low,high) are < and [high,end) are >
// we have to move the values equal to the pivot into the middle. To do this, we swap pivot
// values into the top end of the [low,high) range stopping when we run out of destinations
// or when we run out of values to copy
int from = start;
int to = high - 1;
for (i = 0; from < low && to >= low; i++) {
swap(order, from++, to--);
}
if (from == low) {
// ran out of things to copy. This means that the the last destination is the boundary
low = to + 1;
} else {
// ran out of places to copy to. This means that there are uncopied pivots and the
// boundary is at the beginning of those
low = from;
}
// checkPartition(order, values, pivotValue, start, low, high, end);
// now recurse, but arrange it so we handle the longer limit by tail recursion
if (low - start < end - high) {
quickSort(order, values, start, low, limit);
// this is really a way to do
// quickSort(order, values, high, end, limit);
start = high;
} else {
quickSort(order, values, high, end, limit);
// this is really a way to do
// quickSort(order, values, start, low, limit);
end = low;
}
}
} | [
"private",
"static",
"void",
"quickSort",
"(",
"int",
"[",
"]",
"order",
",",
"double",
"[",
"]",
"values",
",",
"int",
"start",
",",
"int",
"end",
",",
"int",
"limit",
")",
"{",
"// the while loop implements tail-recursion to avoid excessive stack calls on nasty ca... | Standard quick sort except that sorting is done on an index array rather than the values themselves
@param order The pre-allocated index array
@param values The values to sort
@param start The beginning of the values to sort
@param end The value after the last value to sort
@param limit The minimum size to recurse down to. | [
"Standard",
"quick",
"sort",
"except",
"that",
"sorting",
"is",
"done",
"on",
"an",
"index",
"array",
"rather",
"than",
"the",
"values",
"themselves"
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/Sort.java#L79-L157 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/Sort.java | Sort.quickSort | private static void quickSort(double[] key, double[][] values, int start, int end, int limit) {
// the while loop implements tail-recursion to avoid excessive stack calls on nasty cases
while (end - start > limit) {
// median of three values for the pivot
int a = start;
int b = (start + end) / 2;
int c = end - 1;
int pivotIndex;
double pivotValue;
double va = key[a];
double vb = key[b];
double vc = key[c];
//noinspection Duplicates
if (va > vb) {
if (vc > va) {
// vc > va > vb
pivotIndex = a;
pivotValue = va;
} else {
// va > vb, va >= vc
if (vc < vb) {
// va > vb > vc
pivotIndex = b;
pivotValue = vb;
} else {
// va >= vc >= vb
pivotIndex = c;
pivotValue = vc;
}
}
} else {
// vb >= va
if (vc > vb) {
// vc > vb >= va
pivotIndex = b;
pivotValue = vb;
} else {
// vb >= va, vb >= vc
if (vc < va) {
// vb >= va > vc
pivotIndex = a;
pivotValue = va;
} else {
// vb >= vc >= va
pivotIndex = c;
pivotValue = vc;
}
}
}
// move pivot to beginning of array
swap(start, pivotIndex, key, values);
// we use a three way partition because many duplicate values is an important case
int low = start + 1; // low points to first value not known to be equal to pivotValue
int high = end; // high points to first value > pivotValue
int i = low; // i scans the array
while (i < high) {
// invariant: values[order[k]] == pivotValue for k in [0..low)
// invariant: values[order[k]] < pivotValue for k in [low..i)
// invariant: values[order[k]] > pivotValue for k in [high..end)
// in-loop: i < high
// in-loop: low < high
// in-loop: i >= low
double vi = key[i];
if (vi == pivotValue) {
if (low != i) {
swap(low, i, key, values);
} else {
i++;
}
low++;
} else if (vi > pivotValue) {
high--;
swap(i, high, key, values);
} else {
// vi < pivotValue
i++;
}
}
// invariant: values[order[k]] == pivotValue for k in [0..low)
// invariant: values[order[k]] < pivotValue for k in [low..i)
// invariant: values[order[k]] > pivotValue for k in [high..end)
// assert i == high || low == high therefore, we are done with partition
// at this point, i==high, from [start,low) are == pivot, [low,high) are < and [high,end) are >
// we have to move the values equal to the pivot into the middle. To do this, we swap pivot
// values into the top end of the [low,high) range stopping when we run out of destinations
// or when we run out of values to copy
int from = start;
int to = high - 1;
for (i = 0; from < low && to >= low; i++) {
swap(from++, to--, key, values);
}
if (from == low) {
// ran out of things to copy. This means that the the last destination is the boundary
low = to + 1;
} else {
// ran out of places to copy to. This means that there are uncopied pivots and the
// boundary is at the beginning of those
low = from;
}
// checkPartition(order, values, pivotValue, start, low, high, end);
// now recurse, but arrange it so we handle the longer limit by tail recursion
if (low - start < end - high) {
quickSort(key, values, start, low, limit);
// this is really a way to do
// quickSort(order, values, high, end, limit);
start = high;
} else {
quickSort(key, values, high, end, limit);
// this is really a way to do
// quickSort(order, values, start, low, limit);
end = low;
}
}
} | java | private static void quickSort(double[] key, double[][] values, int start, int end, int limit) {
// the while loop implements tail-recursion to avoid excessive stack calls on nasty cases
while (end - start > limit) {
// median of three values for the pivot
int a = start;
int b = (start + end) / 2;
int c = end - 1;
int pivotIndex;
double pivotValue;
double va = key[a];
double vb = key[b];
double vc = key[c];
//noinspection Duplicates
if (va > vb) {
if (vc > va) {
// vc > va > vb
pivotIndex = a;
pivotValue = va;
} else {
// va > vb, va >= vc
if (vc < vb) {
// va > vb > vc
pivotIndex = b;
pivotValue = vb;
} else {
// va >= vc >= vb
pivotIndex = c;
pivotValue = vc;
}
}
} else {
// vb >= va
if (vc > vb) {
// vc > vb >= va
pivotIndex = b;
pivotValue = vb;
} else {
// vb >= va, vb >= vc
if (vc < va) {
// vb >= va > vc
pivotIndex = a;
pivotValue = va;
} else {
// vb >= vc >= va
pivotIndex = c;
pivotValue = vc;
}
}
}
// move pivot to beginning of array
swap(start, pivotIndex, key, values);
// we use a three way partition because many duplicate values is an important case
int low = start + 1; // low points to first value not known to be equal to pivotValue
int high = end; // high points to first value > pivotValue
int i = low; // i scans the array
while (i < high) {
// invariant: values[order[k]] == pivotValue for k in [0..low)
// invariant: values[order[k]] < pivotValue for k in [low..i)
// invariant: values[order[k]] > pivotValue for k in [high..end)
// in-loop: i < high
// in-loop: low < high
// in-loop: i >= low
double vi = key[i];
if (vi == pivotValue) {
if (low != i) {
swap(low, i, key, values);
} else {
i++;
}
low++;
} else if (vi > pivotValue) {
high--;
swap(i, high, key, values);
} else {
// vi < pivotValue
i++;
}
}
// invariant: values[order[k]] == pivotValue for k in [0..low)
// invariant: values[order[k]] < pivotValue for k in [low..i)
// invariant: values[order[k]] > pivotValue for k in [high..end)
// assert i == high || low == high therefore, we are done with partition
// at this point, i==high, from [start,low) are == pivot, [low,high) are < and [high,end) are >
// we have to move the values equal to the pivot into the middle. To do this, we swap pivot
// values into the top end of the [low,high) range stopping when we run out of destinations
// or when we run out of values to copy
int from = start;
int to = high - 1;
for (i = 0; from < low && to >= low; i++) {
swap(from++, to--, key, values);
}
if (from == low) {
// ran out of things to copy. This means that the the last destination is the boundary
low = to + 1;
} else {
// ran out of places to copy to. This means that there are uncopied pivots and the
// boundary is at the beginning of those
low = from;
}
// checkPartition(order, values, pivotValue, start, low, high, end);
// now recurse, but arrange it so we handle the longer limit by tail recursion
if (low - start < end - high) {
quickSort(key, values, start, low, limit);
// this is really a way to do
// quickSort(order, values, high, end, limit);
start = high;
} else {
quickSort(key, values, high, end, limit);
// this is really a way to do
// quickSort(order, values, start, low, limit);
end = low;
}
}
} | [
"private",
"static",
"void",
"quickSort",
"(",
"double",
"[",
"]",
"key",
",",
"double",
"[",
"]",
"[",
"]",
"values",
",",
"int",
"start",
",",
"int",
"end",
",",
"int",
"limit",
")",
"{",
"// the while loop implements tail-recursion to avoid excessive stack ca... | Standard quick sort except that sorting rearranges parallel arrays
@param key Values to sort on
@param values The auxilliary values to sort.
@param start The beginning of the values to sort
@param end The value after the last value to sort
@param limit The minimum size to recurse down to. | [
"Standard",
"quick",
"sort",
"except",
"that",
"sorting",
"rearranges",
"parallel",
"arrays"
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/Sort.java#L195-L317 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/Sort.java | Sort.insertionSort | @SuppressWarnings("SameParameterValue")
private static void insertionSort(double[] key, double[][] values, int start, int end, int limit) {
// loop invariant: all values start ... i-1 are ordered
for (int i = start + 1; i < end; i++) {
double v = key[i];
int m = Math.max(i - limit, start);
for (int j = i; j >= m; j--) {
if (j == m || key[j - 1] <= v) {
if (j < i) {
System.arraycopy(key, j, key, j + 1, i - j);
key[j] = v;
for (double[] value : values) {
double tmp = value[i];
System.arraycopy(value, j, value, j + 1, i - j);
value[j] = tmp;
}
}
break;
}
}
}
} | java | @SuppressWarnings("SameParameterValue")
private static void insertionSort(double[] key, double[][] values, int start, int end, int limit) {
// loop invariant: all values start ... i-1 are ordered
for (int i = start + 1; i < end; i++) {
double v = key[i];
int m = Math.max(i - limit, start);
for (int j = i; j >= m; j--) {
if (j == m || key[j - 1] <= v) {
if (j < i) {
System.arraycopy(key, j, key, j + 1, i - j);
key[j] = v;
for (double[] value : values) {
double tmp = value[i];
System.arraycopy(value, j, value, j + 1, i - j);
value[j] = tmp;
}
}
break;
}
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"SameParameterValue\"",
")",
"private",
"static",
"void",
"insertionSort",
"(",
"double",
"[",
"]",
"key",
",",
"double",
"[",
"]",
"[",
"]",
"values",
",",
"int",
"start",
",",
"int",
"end",
",",
"int",
"limit",
")",
"{",... | Limited range insertion sort. We assume that no element has to move more than limit steps
because quick sort has done its thing. This version works on parallel arrays of keys and values.
@param key The array of keys
@param values The values we are sorting
@param start The starting point of the sort
@param end The ending point of the sort
@param limit The largest amount of disorder | [
"Limited",
"range",
"insertion",
"sort",
".",
"We",
"assume",
"that",
"no",
"element",
"has",
"to",
"move",
"more",
"than",
"limit",
"steps",
"because",
"quick",
"sort",
"has",
"done",
"its",
"thing",
".",
"This",
"version",
"works",
"on",
"parallel",
"arr... | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/Sort.java#L330-L351 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/Sort.java | Sort.checkPartition | @SuppressWarnings("UnusedDeclaration")
public static void checkPartition(int[] order, double[] values, double pivotValue, int start, int low, int high, int end) {
if (order.length != values.length) {
throw new IllegalArgumentException("Arguments must be same size");
}
if (!(start >= 0 && low >= start && high >= low && end >= high)) {
throw new IllegalArgumentException(String.format("Invalid indices %d, %d, %d, %d", start, low, high, end));
}
for (int i = 0; i < low; i++) {
double v = values[order[i]];
if (v >= pivotValue) {
throw new IllegalArgumentException(String.format("Value greater than pivot at %d", i));
}
}
for (int i = low; i < high; i++) {
if (values[order[i]] != pivotValue) {
throw new IllegalArgumentException(String.format("Non-pivot at %d", i));
}
}
for (int i = high; i < end; i++) {
double v = values[order[i]];
if (v <= pivotValue) {
throw new IllegalArgumentException(String.format("Value less than pivot at %d", i));
}
}
} | java | @SuppressWarnings("UnusedDeclaration")
public static void checkPartition(int[] order, double[] values, double pivotValue, int start, int low, int high, int end) {
if (order.length != values.length) {
throw new IllegalArgumentException("Arguments must be same size");
}
if (!(start >= 0 && low >= start && high >= low && end >= high)) {
throw new IllegalArgumentException(String.format("Invalid indices %d, %d, %d, %d", start, low, high, end));
}
for (int i = 0; i < low; i++) {
double v = values[order[i]];
if (v >= pivotValue) {
throw new IllegalArgumentException(String.format("Value greater than pivot at %d", i));
}
}
for (int i = low; i < high; i++) {
if (values[order[i]] != pivotValue) {
throw new IllegalArgumentException(String.format("Non-pivot at %d", i));
}
}
for (int i = high; i < end; i++) {
double v = values[order[i]];
if (v <= pivotValue) {
throw new IllegalArgumentException(String.format("Value less than pivot at %d", i));
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"UnusedDeclaration\"",
")",
"public",
"static",
"void",
"checkPartition",
"(",
"int",
"[",
"]",
"order",
",",
"double",
"[",
"]",
"values",
",",
"double",
"pivotValue",
",",
"int",
"start",
",",
"int",
"low",
",",
"int",
"hi... | Check that a partition step was done correctly. For debugging and testing.
@param order The array of indexes representing a permutation of the keys.
@param values The keys to sort.
@param pivotValue The value that splits the data
@param start The beginning of the data of interest.
@param low Values from start (inclusive) to low (exclusive) are < pivotValue.
@param high Values from low to high are equal to the pivot.
@param end Values from high to end are above the pivot. | [
"Check",
"that",
"a",
"partition",
"step",
"was",
"done",
"correctly",
".",
"For",
"debugging",
"and",
"testing",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/Sort.java#L382-L411 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/Sort.java | Sort.insertionSort | @SuppressWarnings("SameParameterValue")
private static void insertionSort(int[] order, double[] values, int start, int n, int limit) {
for (int i = start + 1; i < n; i++) {
int t = order[i];
double v = values[order[i]];
int m = Math.max(i - limit, start);
for (int j = i; j >= m; j--) {
if (j == 0 || values[order[j - 1]] <= v) {
if (j < i) {
System.arraycopy(order, j, order, j + 1, i - j);
order[j] = t;
}
break;
}
}
}
} | java | @SuppressWarnings("SameParameterValue")
private static void insertionSort(int[] order, double[] values, int start, int n, int limit) {
for (int i = start + 1; i < n; i++) {
int t = order[i];
double v = values[order[i]];
int m = Math.max(i - limit, start);
for (int j = i; j >= m; j--) {
if (j == 0 || values[order[j - 1]] <= v) {
if (j < i) {
System.arraycopy(order, j, order, j + 1, i - j);
order[j] = t;
}
break;
}
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"SameParameterValue\"",
")",
"private",
"static",
"void",
"insertionSort",
"(",
"int",
"[",
"]",
"order",
",",
"double",
"[",
"]",
"values",
",",
"int",
"start",
",",
"int",
"n",
",",
"int",
"limit",
")",
"{",
"for",
"(",
... | Limited range insertion sort. We assume that no element has to move more than limit steps
because quick sort has done its thing.
@param order The permutation index
@param values The values we are sorting
@param start Where to start the sort
@param n How many elements to sort
@param limit The largest amount of disorder | [
"Limited",
"range",
"insertion",
"sort",
".",
"We",
"assume",
"that",
"no",
"element",
"has",
"to",
"move",
"more",
"than",
"limit",
"steps",
"because",
"quick",
"sort",
"has",
"done",
"its",
"thing",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/Sort.java#L423-L439 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/AbstractTDigest.java | AbstractTDigest.quantile | static double quantile(double index, double previousIndex, double nextIndex, double previousMean, double nextMean) {
final double delta = nextIndex - previousIndex;
final double previousWeight = (nextIndex - index) / delta;
final double nextWeight = (index - previousIndex) / delta;
return previousMean * previousWeight + nextMean * nextWeight;
} | java | static double quantile(double index, double previousIndex, double nextIndex, double previousMean, double nextMean) {
final double delta = nextIndex - previousIndex;
final double previousWeight = (nextIndex - index) / delta;
final double nextWeight = (index - previousIndex) / delta;
return previousMean * previousWeight + nextMean * nextWeight;
} | [
"static",
"double",
"quantile",
"(",
"double",
"index",
",",
"double",
"previousIndex",
",",
"double",
"nextIndex",
",",
"double",
"previousMean",
",",
"double",
"nextMean",
")",
"{",
"final",
"double",
"delta",
"=",
"nextIndex",
"-",
"previousIndex",
";",
"fi... | Computes an interpolated value of a quantile that is between two centroids.
Index is the quantile desired multiplied by the total number of samples - 1.
@param index Denormalized quantile desired
@param previousIndex The denormalized quantile corresponding to the center of the previous centroid.
@param nextIndex The denormalized quantile corresponding to the center of the following centroid.
@param previousMean The mean of the previous centroid.
@param nextMean The mean of the following centroid.
@return The interpolated mean. | [
"Computes",
"an",
"interpolated",
"value",
"of",
"a",
"quantile",
"that",
"is",
"between",
"two",
"centroids",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/AbstractTDigest.java#L103-L108 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/AVLGroupTree.java | AVLGroupTree.add | public void add(double centroid, int count, List<Double> data) {
this.centroid = centroid;
this.count = count;
this.data = data;
tree.add();
} | java | public void add(double centroid, int count, List<Double> data) {
this.centroid = centroid;
this.count = count;
this.data = data;
tree.add();
} | [
"public",
"void",
"add",
"(",
"double",
"centroid",
",",
"int",
"count",
",",
"List",
"<",
"Double",
">",
"data",
")",
"{",
"this",
".",
"centroid",
"=",
"centroid",
";",
"this",
".",
"count",
"=",
"count",
";",
"this",
".",
"data",
"=",
"data",
";... | Add the provided centroid to the tree. | [
"Add",
"the",
"provided",
"centroid",
"to",
"the",
"tree",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/AVLGroupTree.java#L154-L159 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/AVLGroupTree.java | AVLGroupTree.update | @SuppressWarnings("WeakerAccess")
public void update(int node, double centroid, int count, List<Double> data, boolean forceInPlace) {
if (centroid == centroids[node]||forceInPlace) {
// we prefer to update in place so repeated values don't shuffle around and for merging
centroids[node] = centroid;
counts[node] = count;
if (datas != null) {
datas[node] = data;
}
} else {
// have to do full scale update
this.centroid = centroid;
this.count = count;
this.data = data;
tree.update(node);
}
} | java | @SuppressWarnings("WeakerAccess")
public void update(int node, double centroid, int count, List<Double> data, boolean forceInPlace) {
if (centroid == centroids[node]||forceInPlace) {
// we prefer to update in place so repeated values don't shuffle around and for merging
centroids[node] = centroid;
counts[node] = count;
if (datas != null) {
datas[node] = data;
}
} else {
// have to do full scale update
this.centroid = centroid;
this.count = count;
this.data = data;
tree.update(node);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"void",
"update",
"(",
"int",
"node",
",",
"double",
"centroid",
",",
"int",
"count",
",",
"List",
"<",
"Double",
">",
"data",
",",
"boolean",
"forceInPlace",
")",
"{",
"if",
"(",
"centroid",... | Update values associated with a node, readjusting the tree if necessary. | [
"Update",
"values",
"associated",
"with",
"a",
"node",
"readjusting",
"the",
"tree",
"if",
"necessary",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/AVLGroupTree.java#L170-L186 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/AVLTreeDigest.java | AVLTreeDigest.smallByteSize | @Override
public int smallByteSize() {
int bound = byteSize();
ByteBuffer buf = ByteBuffer.allocate(bound);
asSmallBytes(buf);
return buf.position();
} | java | @Override
public int smallByteSize() {
int bound = byteSize();
ByteBuffer buf = ByteBuffer.allocate(bound);
asSmallBytes(buf);
return buf.position();
} | [
"@",
"Override",
"public",
"int",
"smallByteSize",
"(",
")",
"{",
"int",
"bound",
"=",
"byteSize",
"(",
")",
";",
"ByteBuffer",
"buf",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"bound",
")",
";",
"asSmallBytes",
"(",
"buf",
")",
";",
"return",
"buf",
".... | Returns an upper bound on the number of bytes that will be required to represent this histogram in
the tighter representation. | [
"Returns",
"an",
"upper",
"bound",
"on",
"the",
"number",
"of",
"bytes",
"that",
"will",
"be",
"required",
"to",
"represent",
"this",
"histogram",
"in",
"the",
"tighter",
"representation",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/AVLTreeDigest.java#L491-L497 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/AVLTreeDigest.java | AVLTreeDigest.asBytes | @Override
public void asBytes(ByteBuffer buf) {
buf.putInt(VERBOSE_ENCODING);
buf.putDouble(min);
buf.putDouble(max);
buf.putDouble((float) compression());
buf.putInt(summary.size());
for (Centroid centroid : summary) {
buf.putDouble(centroid.mean());
}
for (Centroid centroid : summary) {
buf.putInt(centroid.count());
}
} | java | @Override
public void asBytes(ByteBuffer buf) {
buf.putInt(VERBOSE_ENCODING);
buf.putDouble(min);
buf.putDouble(max);
buf.putDouble((float) compression());
buf.putInt(summary.size());
for (Centroid centroid : summary) {
buf.putDouble(centroid.mean());
}
for (Centroid centroid : summary) {
buf.putInt(centroid.count());
}
} | [
"@",
"Override",
"public",
"void",
"asBytes",
"(",
"ByteBuffer",
"buf",
")",
"{",
"buf",
".",
"putInt",
"(",
"VERBOSE_ENCODING",
")",
";",
"buf",
".",
"putDouble",
"(",
"min",
")",
";",
"buf",
".",
"putDouble",
"(",
"max",
")",
";",
"buf",
".",
"putD... | Outputs a histogram as bytes using a particularly cheesy encoding. | [
"Outputs",
"a",
"histogram",
"as",
"bytes",
"using",
"a",
"particularly",
"cheesy",
"encoding",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/AVLTreeDigest.java#L505-L519 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/AVLTreeDigest.java | AVLTreeDigest.fromBytes | @SuppressWarnings("WeakerAccess")
public static AVLTreeDigest fromBytes(ByteBuffer buf) {
int encoding = buf.getInt();
if (encoding == VERBOSE_ENCODING) {
double min = buf.getDouble();
double max = buf.getDouble();
double compression = buf.getDouble();
AVLTreeDigest r = new AVLTreeDigest(compression);
r.setMinMax(min, max);
int n = buf.getInt();
double[] means = new double[n];
for (int i = 0; i < n; i++) {
means[i] = buf.getDouble();
}
for (int i = 0; i < n; i++) {
r.add(means[i], buf.getInt());
}
return r;
} else if (encoding == SMALL_ENCODING) {
double min = buf.getDouble();
double max = buf.getDouble();
double compression = buf.getDouble();
AVLTreeDigest r = new AVLTreeDigest(compression);
r.setMinMax(min, max);
int n = buf.getInt();
double[] means = new double[n];
double x = 0;
for (int i = 0; i < n; i++) {
double delta = buf.getFloat();
x += delta;
means[i] = x;
}
for (int i = 0; i < n; i++) {
int z = decode(buf);
r.add(means[i], z);
}
return r;
} else {
throw new IllegalStateException("Invalid format for serialized histogram");
}
} | java | @SuppressWarnings("WeakerAccess")
public static AVLTreeDigest fromBytes(ByteBuffer buf) {
int encoding = buf.getInt();
if (encoding == VERBOSE_ENCODING) {
double min = buf.getDouble();
double max = buf.getDouble();
double compression = buf.getDouble();
AVLTreeDigest r = new AVLTreeDigest(compression);
r.setMinMax(min, max);
int n = buf.getInt();
double[] means = new double[n];
for (int i = 0; i < n; i++) {
means[i] = buf.getDouble();
}
for (int i = 0; i < n; i++) {
r.add(means[i], buf.getInt());
}
return r;
} else if (encoding == SMALL_ENCODING) {
double min = buf.getDouble();
double max = buf.getDouble();
double compression = buf.getDouble();
AVLTreeDigest r = new AVLTreeDigest(compression);
r.setMinMax(min, max);
int n = buf.getInt();
double[] means = new double[n];
double x = 0;
for (int i = 0; i < n; i++) {
double delta = buf.getFloat();
x += delta;
means[i] = x;
}
for (int i = 0; i < n; i++) {
int z = decode(buf);
r.add(means[i], z);
}
return r;
} else {
throw new IllegalStateException("Invalid format for serialized histogram");
}
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"static",
"AVLTreeDigest",
"fromBytes",
"(",
"ByteBuffer",
"buf",
")",
"{",
"int",
"encoding",
"=",
"buf",
".",
"getInt",
"(",
")",
";",
"if",
"(",
"encoding",
"==",
"VERBOSE_ENCODING",
")",
"{... | Reads a histogram from a byte buffer
@param buf The buffer to read from.
@return The new histogram structure | [
"Reads",
"a",
"histogram",
"from",
"a",
"byte",
"buffer"
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/AVLTreeDigest.java#L548-L589 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/Comparison.java | Comparison.compareChi2 | @SuppressWarnings("WeakerAccess")
public static double compareChi2(TDigest dist1, TDigest dist2, double[] qCuts) {
double[][] count = new double[2][];
count[0] = new double[qCuts.length + 1];
count[1] = new double[qCuts.length + 1];
double oldQ = 0;
double oldQ2 = 0;
for (int i = 0; i <= qCuts.length; i++) {
double newQ;
double x;
if (i == qCuts.length) {
newQ = 1;
x = Math.max(dist1.getMax(), dist2.getMax()) + 1;
} else {
newQ = qCuts[i];
x = dist1.quantile(newQ);
}
count[0][i] = dist1.size() * (newQ - oldQ);
double q2 = dist2.cdf(x);
count[1][i] = dist2.size() * (q2 - oldQ2);
oldQ = newQ;
oldQ2 = q2;
}
return llr(count);
} | java | @SuppressWarnings("WeakerAccess")
public static double compareChi2(TDigest dist1, TDigest dist2, double[] qCuts) {
double[][] count = new double[2][];
count[0] = new double[qCuts.length + 1];
count[1] = new double[qCuts.length + 1];
double oldQ = 0;
double oldQ2 = 0;
for (int i = 0; i <= qCuts.length; i++) {
double newQ;
double x;
if (i == qCuts.length) {
newQ = 1;
x = Math.max(dist1.getMax(), dist2.getMax()) + 1;
} else {
newQ = qCuts[i];
x = dist1.quantile(newQ);
}
count[0][i] = dist1.size() * (newQ - oldQ);
double q2 = dist2.cdf(x);
count[1][i] = dist2.size() * (q2 - oldQ2);
oldQ = newQ;
oldQ2 = q2;
}
return llr(count);
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"static",
"double",
"compareChi2",
"(",
"TDigest",
"dist1",
",",
"TDigest",
"dist2",
",",
"double",
"[",
"]",
"qCuts",
")",
"{",
"double",
"[",
"]",
"[",
"]",
"count",
"=",
"new",
"double",
... | Use a log-likelihood ratio test to compare two distributions.
This is done by estimating counts in quantile ranges from each
distribution and then comparing those counts using a multinomial
test. The result should be asymptotically chi^2 distributed if
the data comes from the same distribution, but this isn't so
much useful as a traditional test of a null hypothesis as it is
just a reasonably well-behaved score that is bigger when the
distributions are more different, subject to having enough data
to tell.
@param dist1 First distribution (usually the reference)
@param dist2 Second distribution to compare (usually the test case)
@param qCuts The quantiles that define the bin boundaries. Values ≤0 or ≥1
may result in zero counts. Note that the actual cuts are
defined loosely as <pre>dist1.quantile(qCuts[i])</pre>.
@return A score that is big when dist1 and dist2 are discernibly different.
A small score does not mean similarity. Instead, it could just mean insufficient
data. | [
"Use",
"a",
"log",
"-",
"likelihood",
"ratio",
"test",
"to",
"compare",
"two",
"distributions",
".",
"This",
"is",
"done",
"by",
"estimating",
"counts",
"in",
"quantile",
"ranges",
"from",
"each",
"distribution",
"and",
"then",
"comparing",
"those",
"counts",
... | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/Comparison.java#L48-L75 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/IntAVLTree.java | IntAVLTree.find | public int find() {
for (int node = root; node != NIL; ) {
final int cmp = compare(node);
if (cmp < 0) {
node = left(node);
} else if (cmp > 0) {
node = right(node);
} else {
return node;
}
}
return NIL;
} | java | public int find() {
for (int node = root; node != NIL; ) {
final int cmp = compare(node);
if (cmp < 0) {
node = left(node);
} else if (cmp > 0) {
node = right(node);
} else {
return node;
}
}
return NIL;
} | [
"public",
"int",
"find",
"(",
")",
"{",
"for",
"(",
"int",
"node",
"=",
"root",
";",
"node",
"!=",
"NIL",
";",
")",
"{",
"final",
"int",
"cmp",
"=",
"compare",
"(",
"node",
")",
";",
"if",
"(",
"cmp",
"<",
"0",
")",
"{",
"node",
"=",
"left",
... | Find a node in this tree. | [
"Find",
"a",
"node",
"in",
"this",
"tree",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/IntAVLTree.java#L255-L267 | train |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/IntAVLTree.java | IntAVLTree.remove | public void remove(int node) {
if (node == NIL) {
throw new IllegalArgumentException();
}
if (left(node) != NIL && right(node) != NIL) {
// inner node
final int next = next(node);
assert next != NIL;
swap(node, next);
}
assert left(node) == NIL || right(node) == NIL;
final int parent = parent(node);
int child = left(node);
if (child == NIL) {
child = right(node);
}
if (child == NIL) {
// no children
if (node == root) {
assert size() == 1 : size();
root = NIL;
} else {
if (node == left(parent)) {
left(parent, NIL);
} else {
assert node == right(parent);
right(parent, NIL);
}
}
} else {
// one single child
if (node == root) {
assert size() == 2;
root = child;
} else if (node == left(parent)) {
left(parent, child);
} else {
assert node == right(parent);
right(parent, child);
}
parent(child, parent);
}
release(node);
rebalance(parent);
} | java | public void remove(int node) {
if (node == NIL) {
throw new IllegalArgumentException();
}
if (left(node) != NIL && right(node) != NIL) {
// inner node
final int next = next(node);
assert next != NIL;
swap(node, next);
}
assert left(node) == NIL || right(node) == NIL;
final int parent = parent(node);
int child = left(node);
if (child == NIL) {
child = right(node);
}
if (child == NIL) {
// no children
if (node == root) {
assert size() == 1 : size();
root = NIL;
} else {
if (node == left(parent)) {
left(parent, NIL);
} else {
assert node == right(parent);
right(parent, NIL);
}
}
} else {
// one single child
if (node == root) {
assert size() == 2;
root = child;
} else if (node == left(parent)) {
left(parent, child);
} else {
assert node == right(parent);
right(parent, child);
}
parent(child, parent);
}
release(node);
rebalance(parent);
} | [
"public",
"void",
"remove",
"(",
"int",
"node",
")",
"{",
"if",
"(",
"node",
"==",
"NIL",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"if",
"(",
"left",
"(",
"node",
")",
"!=",
"NIL",
"&&",
"right",
"(",
"node",
")",
... | Remove the specified node from the tree. | [
"Remove",
"the",
"specified",
"node",
"from",
"the",
"tree",
"."
] | 0820b016fefc1f66fe3b089cec9b4ba220da4ef1 | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/IntAVLTree.java#L292-L339 | train |
citrusframework/citrus | modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java | JmsMessage.getMessageId | public String getMessageId() {
Object messageId = getHeader(JmsMessageHeaders.MESSAGE_ID);
if (messageId != null) {
return messageId.toString();
}
return null;
} | java | public String getMessageId() {
Object messageId = getHeader(JmsMessageHeaders.MESSAGE_ID);
if (messageId != null) {
return messageId.toString();
}
return null;
} | [
"public",
"String",
"getMessageId",
"(",
")",
"{",
"Object",
"messageId",
"=",
"getHeader",
"(",
"JmsMessageHeaders",
".",
"MESSAGE_ID",
")",
";",
"if",
"(",
"messageId",
"!=",
"null",
")",
"{",
"return",
"messageId",
".",
"toString",
"(",
")",
";",
"}",
... | Gets the JMS messageId header.
@return | [
"Gets",
"the",
"JMS",
"messageId",
"header",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java#L111-L119 | train |
citrusframework/citrus | modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java | JmsMessage.getCorrelationId | public String getCorrelationId() {
Object correlationId = getHeader(JmsMessageHeaders.CORRELATION_ID);
if (correlationId != null) {
return correlationId.toString();
}
return null;
} | java | public String getCorrelationId() {
Object correlationId = getHeader(JmsMessageHeaders.CORRELATION_ID);
if (correlationId != null) {
return correlationId.toString();
}
return null;
} | [
"public",
"String",
"getCorrelationId",
"(",
")",
"{",
"Object",
"correlationId",
"=",
"getHeader",
"(",
"JmsMessageHeaders",
".",
"CORRELATION_ID",
")",
";",
"if",
"(",
"correlationId",
"!=",
"null",
")",
"{",
"return",
"correlationId",
".",
"toString",
"(",
... | Gets the JMS correlationId header.
@return | [
"Gets",
"the",
"JMS",
"correlationId",
"header",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java#L139-L147 | train |
citrusframework/citrus | modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java | JmsMessage.getReplyTo | public Destination getReplyTo() {
Object replyTo = getHeader(JmsMessageHeaders.REPLY_TO);
if (replyTo != null) {
return (Destination) replyTo;
}
return null;
} | java | public Destination getReplyTo() {
Object replyTo = getHeader(JmsMessageHeaders.REPLY_TO);
if (replyTo != null) {
return (Destination) replyTo;
}
return null;
} | [
"public",
"Destination",
"getReplyTo",
"(",
")",
"{",
"Object",
"replyTo",
"=",
"getHeader",
"(",
"JmsMessageHeaders",
".",
"REPLY_TO",
")",
";",
"if",
"(",
"replyTo",
"!=",
"null",
")",
"{",
"return",
"(",
"Destination",
")",
"replyTo",
";",
"}",
"return"... | Gets the JMS reply to header.
@return | [
"Gets",
"the",
"JMS",
"reply",
"to",
"header",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java#L153-L161 | train |
citrusframework/citrus | modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java | JmsMessage.getRedelivered | public String getRedelivered() {
Object redelivered = getHeader(JmsMessageHeaders.REDELIVERED);
if (redelivered != null) {
return redelivered.toString();
}
return null;
} | java | public String getRedelivered() {
Object redelivered = getHeader(JmsMessageHeaders.REDELIVERED);
if (redelivered != null) {
return redelivered.toString();
}
return null;
} | [
"public",
"String",
"getRedelivered",
"(",
")",
"{",
"Object",
"redelivered",
"=",
"getHeader",
"(",
"JmsMessageHeaders",
".",
"REDELIVERED",
")",
";",
"if",
"(",
"redelivered",
"!=",
"null",
")",
"{",
"return",
"redelivered",
".",
"toString",
"(",
")",
";",... | Gets the JMS redelivered header.
@return | [
"Gets",
"the",
"JMS",
"redelivered",
"header",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java#L167-L175 | train |
citrusframework/citrus | modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java | JmsMessage.getType | public String getType() {
Object type = getHeader(JmsMessageHeaders.TYPE);
if (type != null) {
return type.toString();
}
return null;
} | java | public String getType() {
Object type = getHeader(JmsMessageHeaders.TYPE);
if (type != null) {
return type.toString();
}
return null;
} | [
"public",
"String",
"getType",
"(",
")",
"{",
"Object",
"type",
"=",
"getHeader",
"(",
"JmsMessageHeaders",
".",
"TYPE",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"return",
"type",
".",
"toString",
"(",
")",
";",
"}",
"return",
"null",
";"... | Gets the JMS type header.
@return | [
"Gets",
"the",
"JMS",
"type",
"header",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/message/JmsMessage.java#L181-L189 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonTextMessageValidator.java | JsonTextMessageValidator.performSchemaValidation | private void performSchemaValidation(Message receivedMessage, JsonMessageValidationContext validationContext) {
log.debug("Starting Json schema validation ...");
ProcessingReport report = jsonSchemaValidation.validate(receivedMessage,
schemaRepositories,
validationContext,
applicationContext);
if (!report.isSuccess()) {
log.error("Failed to validate Json schema for message:\n" + receivedMessage.getPayload(String.class));
throw new ValidationException(constructErrorMessage(report));
}
log.info("Json schema validation successful: All values OK");
} | java | private void performSchemaValidation(Message receivedMessage, JsonMessageValidationContext validationContext) {
log.debug("Starting Json schema validation ...");
ProcessingReport report = jsonSchemaValidation.validate(receivedMessage,
schemaRepositories,
validationContext,
applicationContext);
if (!report.isSuccess()) {
log.error("Failed to validate Json schema for message:\n" + receivedMessage.getPayload(String.class));
throw new ValidationException(constructErrorMessage(report));
}
log.info("Json schema validation successful: All values OK");
} | [
"private",
"void",
"performSchemaValidation",
"(",
"Message",
"receivedMessage",
",",
"JsonMessageValidationContext",
"validationContext",
")",
"{",
"log",
".",
"debug",
"(",
"\"Starting Json schema validation ...\"",
")",
";",
"ProcessingReport",
"report",
"=",
"jsonSchema... | Performs the schema validation for the given message under consideration of the given validation context
@param receivedMessage The message to be validated
@param validationContext The validation context of the current test | [
"Performs",
"the",
"schema",
"validation",
"for",
"the",
"given",
"message",
"under",
"consideration",
"of",
"the",
"given",
"validation",
"context"
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonTextMessageValidator.java#L140-L154 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonTextMessageValidator.java | JsonTextMessageValidator.constructErrorMessage | private String constructErrorMessage(ProcessingReport report) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Json validation failed: ");
report.forEach(processingMessage -> stringBuilder.append(processingMessage.getMessage()));
return stringBuilder.toString();
} | java | private String constructErrorMessage(ProcessingReport report) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Json validation failed: ");
report.forEach(processingMessage -> stringBuilder.append(processingMessage.getMessage()));
return stringBuilder.toString();
} | [
"private",
"String",
"constructErrorMessage",
"(",
"ProcessingReport",
"report",
")",
"{",
"StringBuilder",
"stringBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"stringBuilder",
".",
"append",
"(",
"\"Json validation failed: \"",
")",
";",
"report",
".",
"fo... | Constructs the error message of a failed validation based on the processing report passed from
com.github.fge.jsonschema.core.report
@param report The report containing the error message
@return A string representation of all messages contained in the report | [
"Constructs",
"the",
"error",
"message",
"of",
"a",
"failed",
"validation",
"based",
"on",
"the",
"processing",
"report",
"passed",
"from",
"com",
".",
"github",
".",
"fge",
".",
"jsonschema",
".",
"core",
".",
"report"
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonTextMessageValidator.java#L348-L353 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/message/MessageHeaderUtils.java | MessageHeaderUtils.isSpringInternalHeader | public static boolean isSpringInternalHeader(String headerName) {
// "springintegration_" makes Citrus work with Spring Integration 1.x release
if (headerName.startsWith("springintegration_")) {
return true;
} else if (headerName.equals(MessageHeaders.ID)) {
return true;
} else if (headerName.equals(MessageHeaders.TIMESTAMP)) {
return true;
} else if (headerName.equals(MessageHeaders.REPLY_CHANNEL)) {
return true;
} else if (headerName.equals(MessageHeaders.ERROR_CHANNEL)) {
return true;
} else if (headerName.equals(MessageHeaders.CONTENT_TYPE)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.PRIORITY)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.CORRELATION_ID)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.ROUTING_SLIP)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.DUPLICATE_MESSAGE)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.EXPIRATION_DATE)) {
return true;
} else if (headerName.startsWith("jms_")) {
return true;
}
return false;
} | java | public static boolean isSpringInternalHeader(String headerName) {
// "springintegration_" makes Citrus work with Spring Integration 1.x release
if (headerName.startsWith("springintegration_")) {
return true;
} else if (headerName.equals(MessageHeaders.ID)) {
return true;
} else if (headerName.equals(MessageHeaders.TIMESTAMP)) {
return true;
} else if (headerName.equals(MessageHeaders.REPLY_CHANNEL)) {
return true;
} else if (headerName.equals(MessageHeaders.ERROR_CHANNEL)) {
return true;
} else if (headerName.equals(MessageHeaders.CONTENT_TYPE)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.PRIORITY)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.CORRELATION_ID)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.ROUTING_SLIP)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.DUPLICATE_MESSAGE)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)) {
return true;
} else if (headerName.equals(IntegrationMessageHeaderAccessor.EXPIRATION_DATE)) {
return true;
} else if (headerName.startsWith("jms_")) {
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"isSpringInternalHeader",
"(",
"String",
"headerName",
")",
"{",
"// \"springintegration_\" makes Citrus work with Spring Integration 1.x release",
"if",
"(",
"headerName",
".",
"startsWith",
"(",
"\"springintegration_\"",
")",
")",
"{",
"return... | Check if given header name belongs to Spring Integration internal headers.
This is given if header name starts with internal header prefix or
matches one of Spring's internal header names.
@param headerName
@return | [
"Check",
"if",
"given",
"header",
"name",
"belongs",
"to",
"Spring",
"Integration",
"internal",
"headers",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/message/MessageHeaderUtils.java#L45-L80 | train |
citrusframework/citrus | modules/citrus-ws/src/main/java/com/consol/citrus/ws/config/xml/SoapAttachmentParser.java | SoapAttachmentParser.parseAttachment | public static SoapAttachment parseAttachment(Element attachmentElement) {
SoapAttachment soapAttachment = new SoapAttachment();
if (attachmentElement.hasAttribute("content-id")) {
soapAttachment.setContentId(attachmentElement.getAttribute("content-id"));
}
if (attachmentElement.hasAttribute("content-type")) {
soapAttachment.setContentType(attachmentElement.getAttribute("content-type"));
}
if (attachmentElement.hasAttribute("charset-name")) {
soapAttachment.setCharsetName(attachmentElement.getAttribute("charset-name"));
}
if (attachmentElement.hasAttribute("mtom-inline")) {
soapAttachment.setMtomInline(Boolean.parseBoolean(attachmentElement.getAttribute("mtom-inline")));
}
if (attachmentElement.hasAttribute("encoding-type")) {
soapAttachment.setEncodingType(attachmentElement.getAttribute("encoding-type"));
}
Element attachmentDataElement = DomUtils.getChildElementByTagName(attachmentElement, "data");
if (attachmentDataElement != null) {
soapAttachment.setContent(DomUtils.getTextValue(attachmentDataElement));
}
Element attachmentResourceElement = DomUtils.getChildElementByTagName(attachmentElement, "resource");
if (attachmentResourceElement != null) {
soapAttachment.setContentResourcePath(attachmentResourceElement.getAttribute("file"));
}
return soapAttachment;
} | java | public static SoapAttachment parseAttachment(Element attachmentElement) {
SoapAttachment soapAttachment = new SoapAttachment();
if (attachmentElement.hasAttribute("content-id")) {
soapAttachment.setContentId(attachmentElement.getAttribute("content-id"));
}
if (attachmentElement.hasAttribute("content-type")) {
soapAttachment.setContentType(attachmentElement.getAttribute("content-type"));
}
if (attachmentElement.hasAttribute("charset-name")) {
soapAttachment.setCharsetName(attachmentElement.getAttribute("charset-name"));
}
if (attachmentElement.hasAttribute("mtom-inline")) {
soapAttachment.setMtomInline(Boolean.parseBoolean(attachmentElement.getAttribute("mtom-inline")));
}
if (attachmentElement.hasAttribute("encoding-type")) {
soapAttachment.setEncodingType(attachmentElement.getAttribute("encoding-type"));
}
Element attachmentDataElement = DomUtils.getChildElementByTagName(attachmentElement, "data");
if (attachmentDataElement != null) {
soapAttachment.setContent(DomUtils.getTextValue(attachmentDataElement));
}
Element attachmentResourceElement = DomUtils.getChildElementByTagName(attachmentElement, "resource");
if (attachmentResourceElement != null) {
soapAttachment.setContentResourcePath(attachmentResourceElement.getAttribute("file"));
}
return soapAttachment;
} | [
"public",
"static",
"SoapAttachment",
"parseAttachment",
"(",
"Element",
"attachmentElement",
")",
"{",
"SoapAttachment",
"soapAttachment",
"=",
"new",
"SoapAttachment",
"(",
")",
";",
"if",
"(",
"attachmentElement",
".",
"hasAttribute",
"(",
"\"content-id\"",
")",
... | Parse the attachment element with all children and attributes.
@param attachmentElement | [
"Parse",
"the",
"attachment",
"element",
"with",
"all",
"children",
"and",
"attributes",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-ws/src/main/java/com/consol/citrus/ws/config/xml/SoapAttachmentParser.java#L40-L74 | train |
citrusframework/citrus | modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java | ManagedBeanDefinition.createObjectName | public ObjectName createObjectName() {
try {
if (StringUtils.hasText(objectName)) {
return new ObjectName(objectDomain + ":" + objectName);
}
if (type != null) {
if (StringUtils.hasText(objectDomain)) {
return new ObjectName(objectDomain, "type", type.getSimpleName());
}
return new ObjectName(type.getPackage().getName(), "type", type.getSimpleName());
}
return new ObjectName(objectDomain, "name", name);
} catch (NullPointerException | MalformedObjectNameException e) {
throw new CitrusRuntimeException("Failed to create proper object name for managed bean", e);
}
} | java | public ObjectName createObjectName() {
try {
if (StringUtils.hasText(objectName)) {
return new ObjectName(objectDomain + ":" + objectName);
}
if (type != null) {
if (StringUtils.hasText(objectDomain)) {
return new ObjectName(objectDomain, "type", type.getSimpleName());
}
return new ObjectName(type.getPackage().getName(), "type", type.getSimpleName());
}
return new ObjectName(objectDomain, "name", name);
} catch (NullPointerException | MalformedObjectNameException e) {
throw new CitrusRuntimeException("Failed to create proper object name for managed bean", e);
}
} | [
"public",
"ObjectName",
"createObjectName",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"StringUtils",
".",
"hasText",
"(",
"objectName",
")",
")",
"{",
"return",
"new",
"ObjectName",
"(",
"objectDomain",
"+",
"\":\"",
"+",
"objectName",
")",
";",
"}",
"if",
"... | Constructs proper object name either from given domain and name property or
by evaluating the mbean type class information.
@return | [
"Constructs",
"proper",
"object",
"name",
"either",
"from",
"given",
"domain",
"and",
"name",
"property",
"or",
"by",
"evaluating",
"the",
"mbean",
"type",
"class",
"information",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java#L51-L69 | train |
citrusframework/citrus | modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java | ManagedBeanDefinition.createMBeanInfo | public MBeanInfo createMBeanInfo() {
if (type != null) {
return new MBeanInfo(type.getName(), description, getAttributeInfo(), getConstructorInfo(), getOperationInfo(), getNotificationInfo());
} else {
return new MBeanInfo(name, description, getAttributeInfo(), getConstructorInfo(), getOperationInfo(), getNotificationInfo());
}
} | java | public MBeanInfo createMBeanInfo() {
if (type != null) {
return new MBeanInfo(type.getName(), description, getAttributeInfo(), getConstructorInfo(), getOperationInfo(), getNotificationInfo());
} else {
return new MBeanInfo(name, description, getAttributeInfo(), getConstructorInfo(), getOperationInfo(), getNotificationInfo());
}
} | [
"public",
"MBeanInfo",
"createMBeanInfo",
"(",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"return",
"new",
"MBeanInfo",
"(",
"type",
".",
"getName",
"(",
")",
",",
"description",
",",
"getAttributeInfo",
"(",
")",
",",
"getConstructorInfo",
"(",
... | Create managed bean info with all constructors, operations, notifications and attributes.
@return | [
"Create",
"managed",
"bean",
"info",
"with",
"all",
"constructors",
"operations",
"notifications",
"and",
"attributes",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java#L75-L81 | train |
citrusframework/citrus | modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java | ManagedBeanDefinition.getOperationInfo | private MBeanOperationInfo[] getOperationInfo() {
final List<MBeanOperationInfo> infoList = new ArrayList<>();
if (type != null) {
ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
infoList.add(new MBeanOperationInfo(OPERATION_DESCRIPTION, method));
}
}, new ReflectionUtils.MethodFilter() {
@Override
public boolean matches(Method method) {
return method.getDeclaringClass().equals(type)
&& !method.getName().startsWith("set")
&& !method.getName().startsWith("get")
&& !method.getName().startsWith("is")
&& !method.getName().startsWith("$jacoco"); // Fix for code coverage
}
});
} else {
for (ManagedBeanInvocation.Operation operation : operations) {
List<MBeanParameterInfo> parameterInfo = new ArrayList<>();
int i = 1;
for (OperationParam parameter : operation.getParameter().getParameter()) {
parameterInfo.add(new MBeanParameterInfo("p" + i++, parameter.getType(), "Parameter #" + i));
}
infoList.add(new MBeanOperationInfo(operation.getName(), OPERATION_DESCRIPTION, parameterInfo.toArray(new MBeanParameterInfo[operation.getParameter().getParameter().size()]), operation.getReturnType(), MBeanOperationInfo.UNKNOWN));
}
}
return infoList.toArray(new MBeanOperationInfo[infoList.size()]);
} | java | private MBeanOperationInfo[] getOperationInfo() {
final List<MBeanOperationInfo> infoList = new ArrayList<>();
if (type != null) {
ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
infoList.add(new MBeanOperationInfo(OPERATION_DESCRIPTION, method));
}
}, new ReflectionUtils.MethodFilter() {
@Override
public boolean matches(Method method) {
return method.getDeclaringClass().equals(type)
&& !method.getName().startsWith("set")
&& !method.getName().startsWith("get")
&& !method.getName().startsWith("is")
&& !method.getName().startsWith("$jacoco"); // Fix for code coverage
}
});
} else {
for (ManagedBeanInvocation.Operation operation : operations) {
List<MBeanParameterInfo> parameterInfo = new ArrayList<>();
int i = 1;
for (OperationParam parameter : operation.getParameter().getParameter()) {
parameterInfo.add(new MBeanParameterInfo("p" + i++, parameter.getType(), "Parameter #" + i));
}
infoList.add(new MBeanOperationInfo(operation.getName(), OPERATION_DESCRIPTION, parameterInfo.toArray(new MBeanParameterInfo[operation.getParameter().getParameter().size()]), operation.getReturnType(), MBeanOperationInfo.UNKNOWN));
}
}
return infoList.toArray(new MBeanOperationInfo[infoList.size()]);
} | [
"private",
"MBeanOperationInfo",
"[",
"]",
"getOperationInfo",
"(",
")",
"{",
"final",
"List",
"<",
"MBeanOperationInfo",
">",
"infoList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"ReflectionUtils",
".",
"doW... | Create this managed bean operations info.
@return | [
"Create",
"this",
"managed",
"bean",
"operations",
"info",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java#L95-L128 | train |
citrusframework/citrus | modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java | ManagedBeanDefinition.getConstructorInfo | private MBeanConstructorInfo[] getConstructorInfo() {
final List<MBeanConstructorInfo> infoList = new ArrayList<>();
if (type != null) {
for (Constructor constructor : type.getConstructors()) {
infoList.add(new MBeanConstructorInfo(constructor.toGenericString(), constructor));
}
}
return infoList.toArray(new MBeanConstructorInfo[infoList.size()]);
} | java | private MBeanConstructorInfo[] getConstructorInfo() {
final List<MBeanConstructorInfo> infoList = new ArrayList<>();
if (type != null) {
for (Constructor constructor : type.getConstructors()) {
infoList.add(new MBeanConstructorInfo(constructor.toGenericString(), constructor));
}
}
return infoList.toArray(new MBeanConstructorInfo[infoList.size()]);
} | [
"private",
"MBeanConstructorInfo",
"[",
"]",
"getConstructorInfo",
"(",
")",
"{",
"final",
"List",
"<",
"MBeanConstructorInfo",
">",
"infoList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"for",
"(",
"Construct... | Create this managed bean constructor info.
@return | [
"Create",
"this",
"managed",
"bean",
"constructor",
"info",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java#L134-L144 | train |
citrusframework/citrus | modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java | ManagedBeanDefinition.getAttributeInfo | private MBeanAttributeInfo[] getAttributeInfo() {
final List<MBeanAttributeInfo> infoList = new ArrayList<>();
if (type != null) {
final List<String> attributes = new ArrayList<>();
if (type.isInterface()) {
ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
String attributeName;
if (method.getName().startsWith("get")) {
attributeName = method.getName().substring(3);
} else if (method.getName().startsWith("is")) {
attributeName = method.getName().substring(2);
} else {
attributeName = method.getName();
}
if (!attributes.contains(attributeName)) {
infoList.add(new MBeanAttributeInfo(attributeName, method.getReturnType().getName(), ATTRIBUTE_DESCRIPTION, true, true, method.getName().startsWith("is")));
attributes.add(attributeName);
}
}
}, new ReflectionUtils.MethodFilter() {
@Override
public boolean matches(Method method) {
return method.getDeclaringClass().equals(type) && (method.getName().startsWith("get") || method.getName().startsWith("is"));
}
});
} else {
ReflectionUtils.doWithFields(type, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
infoList.add(new MBeanAttributeInfo(field.getName(), field.getType().getName(), ATTRIBUTE_DESCRIPTION, true, true, field.getType().equals(Boolean.class)));
}
}, new ReflectionUtils.FieldFilter() {
@Override
public boolean matches(Field field) {
return !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers());
}
});
}
} else {
int i = 1;
for (ManagedBeanInvocation.Attribute attribute : attributes) {
infoList.add(new MBeanAttributeInfo(attribute.getName(), attribute.getType(), ATTRIBUTE_DESCRIPTION, true, true, attribute.getType().equals(Boolean.class.getName())));
}
}
return infoList.toArray(new MBeanAttributeInfo[infoList.size()]);
} | java | private MBeanAttributeInfo[] getAttributeInfo() {
final List<MBeanAttributeInfo> infoList = new ArrayList<>();
if (type != null) {
final List<String> attributes = new ArrayList<>();
if (type.isInterface()) {
ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
String attributeName;
if (method.getName().startsWith("get")) {
attributeName = method.getName().substring(3);
} else if (method.getName().startsWith("is")) {
attributeName = method.getName().substring(2);
} else {
attributeName = method.getName();
}
if (!attributes.contains(attributeName)) {
infoList.add(new MBeanAttributeInfo(attributeName, method.getReturnType().getName(), ATTRIBUTE_DESCRIPTION, true, true, method.getName().startsWith("is")));
attributes.add(attributeName);
}
}
}, new ReflectionUtils.MethodFilter() {
@Override
public boolean matches(Method method) {
return method.getDeclaringClass().equals(type) && (method.getName().startsWith("get") || method.getName().startsWith("is"));
}
});
} else {
ReflectionUtils.doWithFields(type, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
infoList.add(new MBeanAttributeInfo(field.getName(), field.getType().getName(), ATTRIBUTE_DESCRIPTION, true, true, field.getType().equals(Boolean.class)));
}
}, new ReflectionUtils.FieldFilter() {
@Override
public boolean matches(Field field) {
return !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers());
}
});
}
} else {
int i = 1;
for (ManagedBeanInvocation.Attribute attribute : attributes) {
infoList.add(new MBeanAttributeInfo(attribute.getName(), attribute.getType(), ATTRIBUTE_DESCRIPTION, true, true, attribute.getType().equals(Boolean.class.getName())));
}
}
return infoList.toArray(new MBeanAttributeInfo[infoList.size()]);
} | [
"private",
"MBeanAttributeInfo",
"[",
"]",
"getAttributeInfo",
"(",
")",
"{",
"final",
"List",
"<",
"MBeanAttributeInfo",
">",
"infoList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"final",
"List",
"<",
"Str... | Create this managed bean attributes info.
@return | [
"Create",
"this",
"managed",
"bean",
"attributes",
"info",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jmx/src/main/java/com/consol/citrus/jmx/model/ManagedBeanDefinition.java#L150-L202 | train |
citrusframework/citrus | modules/citrus-http/src/main/java/com/consol/citrus/http/servlet/GzipHttpServletResponseWrapper.java | GzipHttpServletResponseWrapper.finish | public void finish() throws IOException {
if (printWriter != null) {
printWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
} | java | public void finish() throws IOException {
if (printWriter != null) {
printWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
} | [
"public",
"void",
"finish",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"printWriter",
"!=",
"null",
")",
"{",
"printWriter",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"outputStream",
"!=",
"null",
")",
"{",
"outputStream",
".",
"close",
"(",... | Finish response stream by closing.
@throws IOException | [
"Finish",
"response",
"stream",
"by",
"closing",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-http/src/main/java/com/consol/citrus/http/servlet/GzipHttpServletResponseWrapper.java#L56-L64 | train |
citrusframework/citrus | modules/citrus-websocket/src/main/java/com/consol/citrus/websocket/handler/WebSocketUrlHandlerMapping.java | WebSocketUrlHandlerMapping.postRegisterUrlHandlers | public void postRegisterUrlHandlers(Map<String, Object> wsHandlers) {
registerHandlers(wsHandlers);
for (Object handler : wsHandlers.values()) {
if (handler instanceof Lifecycle) {
((Lifecycle) handler).start();
}
}
} | java | public void postRegisterUrlHandlers(Map<String, Object> wsHandlers) {
registerHandlers(wsHandlers);
for (Object handler : wsHandlers.values()) {
if (handler instanceof Lifecycle) {
((Lifecycle) handler).start();
}
}
} | [
"public",
"void",
"postRegisterUrlHandlers",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"wsHandlers",
")",
"{",
"registerHandlers",
"(",
"wsHandlers",
")",
";",
"for",
"(",
"Object",
"handler",
":",
"wsHandlers",
".",
"values",
"(",
")",
")",
"{",
"if"... | Workaround for registering the WebSocket request handlers, after the spring context has been
initialised.
@param wsHandlers | [
"Workaround",
"for",
"registering",
"the",
"WebSocket",
"request",
"handlers",
"after",
"the",
"spring",
"context",
"has",
"been",
"initialised",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-websocket/src/main/java/com/consol/citrus/websocket/handler/WebSocketUrlHandlerMapping.java#L36-L44 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractMessageActionParser.java | AbstractMessageActionParser.constructMessageBuilder | public AbstractMessageContentBuilder constructMessageBuilder(Element messageElement) {
AbstractMessageContentBuilder messageBuilder = null;
if (messageElement != null) {
messageBuilder = parsePayloadTemplateBuilder(messageElement);
if (messageBuilder == null) {
messageBuilder = parseScriptBuilder(messageElement);
}
}
if (messageBuilder == null) {
messageBuilder = new PayloadTemplateMessageBuilder();
}
if (messageElement != null && messageElement.hasAttribute("name")) {
messageBuilder.setMessageName(messageElement.getAttribute("name"));
}
return messageBuilder;
} | java | public AbstractMessageContentBuilder constructMessageBuilder(Element messageElement) {
AbstractMessageContentBuilder messageBuilder = null;
if (messageElement != null) {
messageBuilder = parsePayloadTemplateBuilder(messageElement);
if (messageBuilder == null) {
messageBuilder = parseScriptBuilder(messageElement);
}
}
if (messageBuilder == null) {
messageBuilder = new PayloadTemplateMessageBuilder();
}
if (messageElement != null && messageElement.hasAttribute("name")) {
messageBuilder.setMessageName(messageElement.getAttribute("name"));
}
return messageBuilder;
} | [
"public",
"AbstractMessageContentBuilder",
"constructMessageBuilder",
"(",
"Element",
"messageElement",
")",
"{",
"AbstractMessageContentBuilder",
"messageBuilder",
"=",
"null",
";",
"if",
"(",
"messageElement",
"!=",
"null",
")",
"{",
"messageBuilder",
"=",
"parsePayload... | Static parse method taking care of basic message element parsing.
@param messageElement | [
"Static",
"parse",
"method",
"taking",
"care",
"of",
"basic",
"message",
"element",
"parsing",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractMessageActionParser.java#L51-L71 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractMessageActionParser.java | AbstractMessageActionParser.parsePayloadTemplateBuilder | private PayloadTemplateMessageBuilder parsePayloadTemplateBuilder(Element messageElement) {
PayloadTemplateMessageBuilder messageBuilder;
messageBuilder = parsePayloadElement(messageElement);
Element xmlDataElement = DomUtils.getChildElementByTagName(messageElement, "data");
if (xmlDataElement != null) {
messageBuilder = new PayloadTemplateMessageBuilder();
messageBuilder.setPayloadData(DomUtils.getTextValue(xmlDataElement).trim());
}
Element xmlResourceElement = DomUtils.getChildElementByTagName(messageElement, "resource");
if (xmlResourceElement != null) {
messageBuilder = new PayloadTemplateMessageBuilder();
messageBuilder.setPayloadResourcePath(xmlResourceElement.getAttribute("file"));
if (xmlResourceElement.hasAttribute("charset")) {
messageBuilder.setPayloadResourceCharset(xmlResourceElement.getAttribute("charset"));
}
}
if (messageBuilder != null) {
Map<String, String> overwriteXpath = new HashMap<>();
Map<String, String> overwriteJsonPath = new HashMap<>();
List<?> messageValueElements = DomUtils.getChildElementsByTagName(messageElement, "element");
for (Iterator<?> iter = messageValueElements.iterator(); iter.hasNext();) {
Element messageValue = (Element) iter.next();
String pathExpression = messageValue.getAttribute("path");
if (JsonPathMessageValidationContext.isJsonPathExpression(pathExpression)) {
overwriteJsonPath.put(pathExpression, messageValue.getAttribute("value"));
} else {
overwriteXpath.put(pathExpression, messageValue.getAttribute("value"));
}
}
if (!overwriteXpath.isEmpty()) {
XpathMessageConstructionInterceptor interceptor = new XpathMessageConstructionInterceptor(overwriteXpath);
messageBuilder.add(interceptor);
}
if (!overwriteJsonPath.isEmpty()) {
JsonPathMessageConstructionInterceptor interceptor = new JsonPathMessageConstructionInterceptor(overwriteJsonPath);
messageBuilder.add(interceptor);
}
}
return messageBuilder;
} | java | private PayloadTemplateMessageBuilder parsePayloadTemplateBuilder(Element messageElement) {
PayloadTemplateMessageBuilder messageBuilder;
messageBuilder = parsePayloadElement(messageElement);
Element xmlDataElement = DomUtils.getChildElementByTagName(messageElement, "data");
if (xmlDataElement != null) {
messageBuilder = new PayloadTemplateMessageBuilder();
messageBuilder.setPayloadData(DomUtils.getTextValue(xmlDataElement).trim());
}
Element xmlResourceElement = DomUtils.getChildElementByTagName(messageElement, "resource");
if (xmlResourceElement != null) {
messageBuilder = new PayloadTemplateMessageBuilder();
messageBuilder.setPayloadResourcePath(xmlResourceElement.getAttribute("file"));
if (xmlResourceElement.hasAttribute("charset")) {
messageBuilder.setPayloadResourceCharset(xmlResourceElement.getAttribute("charset"));
}
}
if (messageBuilder != null) {
Map<String, String> overwriteXpath = new HashMap<>();
Map<String, String> overwriteJsonPath = new HashMap<>();
List<?> messageValueElements = DomUtils.getChildElementsByTagName(messageElement, "element");
for (Iterator<?> iter = messageValueElements.iterator(); iter.hasNext();) {
Element messageValue = (Element) iter.next();
String pathExpression = messageValue.getAttribute("path");
if (JsonPathMessageValidationContext.isJsonPathExpression(pathExpression)) {
overwriteJsonPath.put(pathExpression, messageValue.getAttribute("value"));
} else {
overwriteXpath.put(pathExpression, messageValue.getAttribute("value"));
}
}
if (!overwriteXpath.isEmpty()) {
XpathMessageConstructionInterceptor interceptor = new XpathMessageConstructionInterceptor(overwriteXpath);
messageBuilder.add(interceptor);
}
if (!overwriteJsonPath.isEmpty()) {
JsonPathMessageConstructionInterceptor interceptor = new JsonPathMessageConstructionInterceptor(overwriteJsonPath);
messageBuilder.add(interceptor);
}
}
return messageBuilder;
} | [
"private",
"PayloadTemplateMessageBuilder",
"parsePayloadTemplateBuilder",
"(",
"Element",
"messageElement",
")",
"{",
"PayloadTemplateMessageBuilder",
"messageBuilder",
";",
"messageBuilder",
"=",
"parsePayloadElement",
"(",
"messageElement",
")",
";",
"Element",
"xmlDataEleme... | Parses message payload template information given in message element.
@param messageElement | [
"Parses",
"message",
"payload",
"template",
"information",
"given",
"in",
"message",
"element",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractMessageActionParser.java#L115-L162 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractMessageActionParser.java | AbstractMessageActionParser.parseHeaderElements | protected void parseHeaderElements(Element actionElement, AbstractMessageContentBuilder messageBuilder, List<ValidationContext> validationContexts) {
Element headerElement = DomUtils.getChildElementByTagName(actionElement, "header");
Map<String, Object> messageHeaders = new LinkedHashMap<>();
if (headerElement != null) {
List<?> elements = DomUtils.getChildElementsByTagName(headerElement, "element");
for (Iterator<?> iter = elements.iterator(); iter.hasNext();) {
Element headerValue = (Element) iter.next();
String name = headerValue.getAttribute("name");
String value = headerValue.getAttribute("value");
String type = headerValue.getAttribute("type");
if (StringUtils.hasText(type)) {
value = MessageHeaderType.createTypedValue(type, value);
}
messageHeaders.put(name, value);
}
List<Element> headerDataElements = DomUtils.getChildElementsByTagName(headerElement, "data");
for (Element headerDataElement : headerDataElements) {
messageBuilder.getHeaderData().add(DomUtils.getTextValue(headerDataElement).trim());
}
List<Element> headerResourceElements = DomUtils.getChildElementsByTagName(headerElement, "resource");
for (Element headerResourceElement : headerResourceElements) {
String charset = headerResourceElement.getAttribute("charset");
messageBuilder.getHeaderResources().add(headerResourceElement.getAttribute("file") + (StringUtils.hasText(charset) ? FileUtils.FILE_PATH_CHARSET_PARAMETER + charset : ""));
}
// parse fragment with xs-any element
List<Element> headerFragmentElements = DomUtils.getChildElementsByTagName(headerElement, "fragment");
for (Element headerFragmentElement : headerFragmentElements) {
List<Element> fragment = DomUtils.getChildElements(headerFragmentElement);
if (!CollectionUtils.isEmpty(fragment)) {
messageBuilder.getHeaderData().add(PayloadElementParser.parseMessagePayload(fragment.get(0)));
}
}
messageBuilder.setMessageHeaders(messageHeaders);
if (headerElement.hasAttribute("ignore-case")) {
boolean ignoreCase = Boolean.valueOf(headerElement.getAttribute("ignore-case"));
validationContexts.stream().filter(context -> context instanceof HeaderValidationContext)
.map(context -> (HeaderValidationContext) context)
.forEach(context -> context.setHeaderNameIgnoreCase(ignoreCase));
}
}
} | java | protected void parseHeaderElements(Element actionElement, AbstractMessageContentBuilder messageBuilder, List<ValidationContext> validationContexts) {
Element headerElement = DomUtils.getChildElementByTagName(actionElement, "header");
Map<String, Object> messageHeaders = new LinkedHashMap<>();
if (headerElement != null) {
List<?> elements = DomUtils.getChildElementsByTagName(headerElement, "element");
for (Iterator<?> iter = elements.iterator(); iter.hasNext();) {
Element headerValue = (Element) iter.next();
String name = headerValue.getAttribute("name");
String value = headerValue.getAttribute("value");
String type = headerValue.getAttribute("type");
if (StringUtils.hasText(type)) {
value = MessageHeaderType.createTypedValue(type, value);
}
messageHeaders.put(name, value);
}
List<Element> headerDataElements = DomUtils.getChildElementsByTagName(headerElement, "data");
for (Element headerDataElement : headerDataElements) {
messageBuilder.getHeaderData().add(DomUtils.getTextValue(headerDataElement).trim());
}
List<Element> headerResourceElements = DomUtils.getChildElementsByTagName(headerElement, "resource");
for (Element headerResourceElement : headerResourceElements) {
String charset = headerResourceElement.getAttribute("charset");
messageBuilder.getHeaderResources().add(headerResourceElement.getAttribute("file") + (StringUtils.hasText(charset) ? FileUtils.FILE_PATH_CHARSET_PARAMETER + charset : ""));
}
// parse fragment with xs-any element
List<Element> headerFragmentElements = DomUtils.getChildElementsByTagName(headerElement, "fragment");
for (Element headerFragmentElement : headerFragmentElements) {
List<Element> fragment = DomUtils.getChildElements(headerFragmentElement);
if (!CollectionUtils.isEmpty(fragment)) {
messageBuilder.getHeaderData().add(PayloadElementParser.parseMessagePayload(fragment.get(0)));
}
}
messageBuilder.setMessageHeaders(messageHeaders);
if (headerElement.hasAttribute("ignore-case")) {
boolean ignoreCase = Boolean.valueOf(headerElement.getAttribute("ignore-case"));
validationContexts.stream().filter(context -> context instanceof HeaderValidationContext)
.map(context -> (HeaderValidationContext) context)
.forEach(context -> context.setHeaderNameIgnoreCase(ignoreCase));
}
}
} | [
"protected",
"void",
"parseHeaderElements",
"(",
"Element",
"actionElement",
",",
"AbstractMessageContentBuilder",
"messageBuilder",
",",
"List",
"<",
"ValidationContext",
">",
"validationContexts",
")",
"{",
"Element",
"headerElement",
"=",
"DomUtils",
".",
"getChildElem... | Parse message header elements in action and add headers to
message content builder.
@param actionElement the action DOM element.
@param messageBuilder the message content builder.
@param validationContexts list of validation contexts. | [
"Parse",
"message",
"header",
"elements",
"in",
"action",
"and",
"add",
"headers",
"to",
"message",
"content",
"builder",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractMessageActionParser.java#L199-L248 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractMessageActionParser.java | AbstractMessageActionParser.parseExtractHeaderElements | protected void parseExtractHeaderElements(Element element, List<VariableExtractor> variableExtractors) {
Element extractElement = DomUtils.getChildElementByTagName(element, "extract");
Map<String, String> extractHeaderValues = new HashMap<>();
if (extractElement != null) {
List<?> headerValueElements = DomUtils.getChildElementsByTagName(extractElement, "header");
for (Iterator<?> iter = headerValueElements.iterator(); iter.hasNext();) {
Element headerValue = (Element) iter.next();
extractHeaderValues.put(headerValue.getAttribute("name"), headerValue.getAttribute("variable"));
}
MessageHeaderVariableExtractor headerVariableExtractor = new MessageHeaderVariableExtractor();
headerVariableExtractor.setHeaderMappings(extractHeaderValues);
if (!CollectionUtils.isEmpty(extractHeaderValues)) {
variableExtractors.add(headerVariableExtractor);
}
}
} | java | protected void parseExtractHeaderElements(Element element, List<VariableExtractor> variableExtractors) {
Element extractElement = DomUtils.getChildElementByTagName(element, "extract");
Map<String, String> extractHeaderValues = new HashMap<>();
if (extractElement != null) {
List<?> headerValueElements = DomUtils.getChildElementsByTagName(extractElement, "header");
for (Iterator<?> iter = headerValueElements.iterator(); iter.hasNext();) {
Element headerValue = (Element) iter.next();
extractHeaderValues.put(headerValue.getAttribute("name"), headerValue.getAttribute("variable"));
}
MessageHeaderVariableExtractor headerVariableExtractor = new MessageHeaderVariableExtractor();
headerVariableExtractor.setHeaderMappings(extractHeaderValues);
if (!CollectionUtils.isEmpty(extractHeaderValues)) {
variableExtractors.add(headerVariableExtractor);
}
}
} | [
"protected",
"void",
"parseExtractHeaderElements",
"(",
"Element",
"element",
",",
"List",
"<",
"VariableExtractor",
">",
"variableExtractors",
")",
"{",
"Element",
"extractElement",
"=",
"DomUtils",
".",
"getChildElementByTagName",
"(",
"element",
",",
"\"extract\"",
... | Parses header extract information.
@param element the root action element.
@param variableExtractors the variable extractors to add new extractors to. | [
"Parses",
"header",
"extract",
"information",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/xml/AbstractMessageActionParser.java#L255-L272 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/script/TemplateBasedScriptBuilder.java | TemplateBasedScriptBuilder.build | public String build() {
StringBuilder scriptBuilder = new StringBuilder();
StringBuilder scriptBody = new StringBuilder();
String importStmt = "import ";
try {
if (scriptCode.contains(importStmt)) {
BufferedReader reader = new BufferedReader(new StringReader(scriptCode));
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().startsWith(importStmt)) {
scriptBuilder.append(line);
scriptBuilder.append("\n");
} else {
scriptBody.append((scriptBody.length() == 0 ? "" : "\n"));
scriptBody.append(line);
}
}
} else {
scriptBody.append(scriptCode);
}
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to construct script from template", e);
}
scriptBuilder.append(scriptHead);
scriptBuilder.append(scriptBody.toString());
scriptBuilder.append(scriptTail);
return scriptBuilder.toString();
} | java | public String build() {
StringBuilder scriptBuilder = new StringBuilder();
StringBuilder scriptBody = new StringBuilder();
String importStmt = "import ";
try {
if (scriptCode.contains(importStmt)) {
BufferedReader reader = new BufferedReader(new StringReader(scriptCode));
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().startsWith(importStmt)) {
scriptBuilder.append(line);
scriptBuilder.append("\n");
} else {
scriptBody.append((scriptBody.length() == 0 ? "" : "\n"));
scriptBody.append(line);
}
}
} else {
scriptBody.append(scriptCode);
}
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to construct script from template", e);
}
scriptBuilder.append(scriptHead);
scriptBuilder.append(scriptBody.toString());
scriptBuilder.append(scriptTail);
return scriptBuilder.toString();
} | [
"public",
"String",
"build",
"(",
")",
"{",
"StringBuilder",
"scriptBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"StringBuilder",
"scriptBody",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"String",
"importStmt",
"=",
"\"import \"",
";",
"try",
"{",
... | Builds the final script. | [
"Builds",
"the",
"final",
"script",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/script/TemplateBasedScriptBuilder.java#L60-L90 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/script/TemplateBasedScriptBuilder.java | TemplateBasedScriptBuilder.fromTemplateResource | public static TemplateBasedScriptBuilder fromTemplateResource(Resource scriptTemplateResource) {
try {
return new TemplateBasedScriptBuilder(FileUtils.readToString(scriptTemplateResource.getInputStream()));
} catch (IOException e) {
throw new CitrusRuntimeException("Error loading script template from file resource", e);
}
} | java | public static TemplateBasedScriptBuilder fromTemplateResource(Resource scriptTemplateResource) {
try {
return new TemplateBasedScriptBuilder(FileUtils.readToString(scriptTemplateResource.getInputStream()));
} catch (IOException e) {
throw new CitrusRuntimeException("Error loading script template from file resource", e);
}
} | [
"public",
"static",
"TemplateBasedScriptBuilder",
"fromTemplateResource",
"(",
"Resource",
"scriptTemplateResource",
")",
"{",
"try",
"{",
"return",
"new",
"TemplateBasedScriptBuilder",
"(",
"FileUtils",
".",
"readToString",
"(",
"scriptTemplateResource",
".",
"getInputStre... | Static construction method returning a fully qualified instance of this builder.
@param scriptTemplateResource external file resource holding script template code.
@return instance of this builder. | [
"Static",
"construction",
"method",
"returning",
"a",
"fully",
"qualified",
"instance",
"of",
"this",
"builder",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/script/TemplateBasedScriptBuilder.java#L117-L123 | train |
citrusframework/citrus | modules/citrus-http/src/main/java/com/consol/citrus/http/controller/HttpMessageController.java | HttpMessageController.handleRequestInternal | private ResponseEntity<?> handleRequestInternal(HttpMethod method, HttpEntity<?> requestEntity) {
HttpMessage request = endpointConfiguration.getMessageConverter().convertInbound(requestEntity, endpointConfiguration, null);
HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
UrlPathHelper pathHelper = new UrlPathHelper();
Enumeration allHeaders = servletRequest.getHeaderNames();
for (String headerName : CollectionUtils.toArray(allHeaders, new String[] {})) {
if (request.getHeader(headerName) == null) {
String headerValue = servletRequest.getHeader(headerName);
request.header(headerName, headerValue != null ? headerValue : "");
}
}
if (endpointConfiguration.isHandleCookies()) {
request.setCookies(servletRequest.getCookies());
}
if (endpointConfiguration.isHandleAttributeHeaders()) {
Enumeration<String> attributeNames = servletRequest.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
Object attribute = servletRequest.getAttribute(attributeName);
request.setHeader(attributeName, attribute);
}
}
request.path(pathHelper.getRequestUri(servletRequest))
.uri(pathHelper.getRequestUri(servletRequest))
.contextPath(pathHelper.getContextPath(servletRequest))
.queryParams(Optional.ofNullable(pathHelper.getOriginatingQueryString(servletRequest))
.map(queryString -> queryString.replaceAll("&", ","))
.orElse(""))
.version(servletRequest.getProtocol())
.method(method);
Message response = endpointAdapter.handleMessage(request);
ResponseEntity<?> responseEntity;
if (response == null) {
responseEntity = new ResponseEntity<>(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
} else {
HttpMessage httpResponse;
if (response instanceof HttpMessage) {
httpResponse = (HttpMessage) response;
} else {
httpResponse = new HttpMessage(response);
}
if (httpResponse.getStatusCode() == null) {
httpResponse.status(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
}
responseEntity = (ResponseEntity<?>) endpointConfiguration.getMessageConverter().convertOutbound(httpResponse, endpointConfiguration, null);
if (endpointConfiguration.isHandleCookies() && httpResponse.getCookies() != null) {
HttpServletResponse servletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
for (Cookie cookie : httpResponse.getCookies()) {
servletResponse.addCookie(cookie);
}
}
}
responseCache.add(responseEntity);
return responseEntity;
} | java | private ResponseEntity<?> handleRequestInternal(HttpMethod method, HttpEntity<?> requestEntity) {
HttpMessage request = endpointConfiguration.getMessageConverter().convertInbound(requestEntity, endpointConfiguration, null);
HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
UrlPathHelper pathHelper = new UrlPathHelper();
Enumeration allHeaders = servletRequest.getHeaderNames();
for (String headerName : CollectionUtils.toArray(allHeaders, new String[] {})) {
if (request.getHeader(headerName) == null) {
String headerValue = servletRequest.getHeader(headerName);
request.header(headerName, headerValue != null ? headerValue : "");
}
}
if (endpointConfiguration.isHandleCookies()) {
request.setCookies(servletRequest.getCookies());
}
if (endpointConfiguration.isHandleAttributeHeaders()) {
Enumeration<String> attributeNames = servletRequest.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
Object attribute = servletRequest.getAttribute(attributeName);
request.setHeader(attributeName, attribute);
}
}
request.path(pathHelper.getRequestUri(servletRequest))
.uri(pathHelper.getRequestUri(servletRequest))
.contextPath(pathHelper.getContextPath(servletRequest))
.queryParams(Optional.ofNullable(pathHelper.getOriginatingQueryString(servletRequest))
.map(queryString -> queryString.replaceAll("&", ","))
.orElse(""))
.version(servletRequest.getProtocol())
.method(method);
Message response = endpointAdapter.handleMessage(request);
ResponseEntity<?> responseEntity;
if (response == null) {
responseEntity = new ResponseEntity<>(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
} else {
HttpMessage httpResponse;
if (response instanceof HttpMessage) {
httpResponse = (HttpMessage) response;
} else {
httpResponse = new HttpMessage(response);
}
if (httpResponse.getStatusCode() == null) {
httpResponse.status(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
}
responseEntity = (ResponseEntity<?>) endpointConfiguration.getMessageConverter().convertOutbound(httpResponse, endpointConfiguration, null);
if (endpointConfiguration.isHandleCookies() && httpResponse.getCookies() != null) {
HttpServletResponse servletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
for (Cookie cookie : httpResponse.getCookies()) {
servletResponse.addCookie(cookie);
}
}
}
responseCache.add(responseEntity);
return responseEntity;
} | [
"private",
"ResponseEntity",
"<",
"?",
">",
"handleRequestInternal",
"(",
"HttpMethod",
"method",
",",
"HttpEntity",
"<",
"?",
">",
"requestEntity",
")",
"{",
"HttpMessage",
"request",
"=",
"endpointConfiguration",
".",
"getMessageConverter",
"(",
")",
".",
"conve... | Handles requests with endpoint adapter implementation. Previously sets Http request method as header parameter.
@param method
@param requestEntity
@return | [
"Handles",
"requests",
"with",
"endpoint",
"adapter",
"implementation",
".",
"Previously",
"sets",
"Http",
"request",
"method",
"as",
"header",
"parameter",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-http/src/main/java/com/consol/citrus/http/controller/HttpMessageController.java#L110-L175 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java | AbstractMessageContentBuilder.buildMessageContent | @Override
public Message buildMessageContent(
final TestContext context,
final String messageType,
final MessageDirection direction) {
final Object payload = buildMessagePayload(context, messageType);
try {
Message message = new DefaultMessage(payload, buildMessageHeaders(context, messageType));
message.setName(messageName);
if (payload != null) {
for (final MessageConstructionInterceptor interceptor: context.getGlobalMessageConstructionInterceptors().getMessageConstructionInterceptors()) {
if (direction.equals(MessageDirection.UNBOUND)
|| interceptor.getDirection().equals(MessageDirection.UNBOUND)
|| direction.equals(interceptor.getDirection())) {
message = interceptor.interceptMessageConstruction(message, messageType, context);
}
}
if (dataDictionary != null) {
message = dataDictionary.interceptMessageConstruction(message, messageType, context);
}
for (final MessageConstructionInterceptor interceptor : messageInterceptors) {
if (direction.equals(MessageDirection.UNBOUND)
|| interceptor.getDirection().equals(MessageDirection.UNBOUND)
|| direction.equals(interceptor.getDirection())) {
message = interceptor.interceptMessageConstruction(message, messageType, context);
}
}
}
message.getHeaderData().addAll(buildMessageHeaderData(context));
return message;
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new CitrusRuntimeException("Failed to build message content", e);
}
} | java | @Override
public Message buildMessageContent(
final TestContext context,
final String messageType,
final MessageDirection direction) {
final Object payload = buildMessagePayload(context, messageType);
try {
Message message = new DefaultMessage(payload, buildMessageHeaders(context, messageType));
message.setName(messageName);
if (payload != null) {
for (final MessageConstructionInterceptor interceptor: context.getGlobalMessageConstructionInterceptors().getMessageConstructionInterceptors()) {
if (direction.equals(MessageDirection.UNBOUND)
|| interceptor.getDirection().equals(MessageDirection.UNBOUND)
|| direction.equals(interceptor.getDirection())) {
message = interceptor.interceptMessageConstruction(message, messageType, context);
}
}
if (dataDictionary != null) {
message = dataDictionary.interceptMessageConstruction(message, messageType, context);
}
for (final MessageConstructionInterceptor interceptor : messageInterceptors) {
if (direction.equals(MessageDirection.UNBOUND)
|| interceptor.getDirection().equals(MessageDirection.UNBOUND)
|| direction.equals(interceptor.getDirection())) {
message = interceptor.interceptMessageConstruction(message, messageType, context);
}
}
}
message.getHeaderData().addAll(buildMessageHeaderData(context));
return message;
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new CitrusRuntimeException("Failed to build message content", e);
}
} | [
"@",
"Override",
"public",
"Message",
"buildMessageContent",
"(",
"final",
"TestContext",
"context",
",",
"final",
"String",
"messageType",
",",
"final",
"MessageDirection",
"direction",
")",
"{",
"final",
"Object",
"payload",
"=",
"buildMessagePayload",
"(",
"conte... | Constructs the control message with headers and payload coming from
subclass implementation. | [
"Constructs",
"the",
"control",
"message",
"with",
"headers",
"and",
"payload",
"coming",
"from",
"subclass",
"implementation",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java#L68-L110 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java | AbstractMessageContentBuilder.buildMessageHeaders | public Map<String, Object> buildMessageHeaders(final TestContext context, final String messageType) {
try {
final Map<String, Object> headers = context.resolveDynamicValuesInMap(messageHeaders);
headers.put(MessageHeaders.MESSAGE_TYPE, messageType);
for (final Map.Entry<String, Object> entry : headers.entrySet()) {
final String value = entry.getValue().toString();
if (MessageHeaderType.isTyped(value)) {
final MessageHeaderType type = MessageHeaderType.fromTypedValue(value);
final Constructor<?> constr = type.getHeaderClass().getConstructor(String.class);
entry.setValue(constr.newInstance(MessageHeaderType.removeTypeDefinition(value)));
}
}
MessageHeaderUtils.checkHeaderTypes(headers);
return headers;
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new CitrusRuntimeException("Failed to build message content", e);
}
} | java | public Map<String, Object> buildMessageHeaders(final TestContext context, final String messageType) {
try {
final Map<String, Object> headers = context.resolveDynamicValuesInMap(messageHeaders);
headers.put(MessageHeaders.MESSAGE_TYPE, messageType);
for (final Map.Entry<String, Object> entry : headers.entrySet()) {
final String value = entry.getValue().toString();
if (MessageHeaderType.isTyped(value)) {
final MessageHeaderType type = MessageHeaderType.fromTypedValue(value);
final Constructor<?> constr = type.getHeaderClass().getConstructor(String.class);
entry.setValue(constr.newInstance(MessageHeaderType.removeTypeDefinition(value)));
}
}
MessageHeaderUtils.checkHeaderTypes(headers);
return headers;
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new CitrusRuntimeException("Failed to build message content", e);
}
} | [
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"buildMessageHeaders",
"(",
"final",
"TestContext",
"context",
",",
"final",
"String",
"messageType",
")",
"{",
"try",
"{",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"headers",
"=",
"context",
".... | Build message headers.
@param context The test context of the message
@param messageType The message type of the Message
@return A Map containing all headers as key value pairs | [
"Build",
"message",
"headers",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java#L126-L149 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java | AbstractMessageContentBuilder.buildMessageHeaderData | public List<String> buildMessageHeaderData(final TestContext context) {
final List<String> headerDataList = new ArrayList<>();
for (final String headerResourcePath : headerResources) {
try {
headerDataList.add(
context.replaceDynamicContentInString(
FileUtils.readToString(
FileUtils.getFileResource(headerResourcePath, context),
FileUtils.getCharset(headerResourcePath))));
} catch (final IOException e) {
throw new CitrusRuntimeException("Failed to read message header data resource", e);
}
}
for (final String data : headerData) {
headerDataList.add(context.replaceDynamicContentInString(data.trim()));
}
return headerDataList;
} | java | public List<String> buildMessageHeaderData(final TestContext context) {
final List<String> headerDataList = new ArrayList<>();
for (final String headerResourcePath : headerResources) {
try {
headerDataList.add(
context.replaceDynamicContentInString(
FileUtils.readToString(
FileUtils.getFileResource(headerResourcePath, context),
FileUtils.getCharset(headerResourcePath))));
} catch (final IOException e) {
throw new CitrusRuntimeException("Failed to read message header data resource", e);
}
}
for (final String data : headerData) {
headerDataList.add(context.replaceDynamicContentInString(data.trim()));
}
return headerDataList;
} | [
"public",
"List",
"<",
"String",
">",
"buildMessageHeaderData",
"(",
"final",
"TestContext",
"context",
")",
"{",
"final",
"List",
"<",
"String",
">",
"headerDataList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"final",
"String",
"headerResou... | Build message header data.
@param context
@return | [
"Build",
"message",
"header",
"data",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java#L156-L175 | train |
citrusframework/citrus | modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapServerFaultResponseActionBuilder.java | SoapServerFaultResponseActionBuilder.attachment | public SoapServerFaultResponseActionBuilder attachment(String contentId, String contentType, String content) {
SoapAttachment attachment = new SoapAttachment();
attachment.setContentId(contentId);
attachment.setContentType(contentType);
attachment.setContent(content);
getAction().getAttachments().add(attachment);
return this;
} | java | public SoapServerFaultResponseActionBuilder attachment(String contentId, String contentType, String content) {
SoapAttachment attachment = new SoapAttachment();
attachment.setContentId(contentId);
attachment.setContentType(contentType);
attachment.setContent(content);
getAction().getAttachments().add(attachment);
return this;
} | [
"public",
"SoapServerFaultResponseActionBuilder",
"attachment",
"(",
"String",
"contentId",
",",
"String",
"contentType",
",",
"String",
"content",
")",
"{",
"SoapAttachment",
"attachment",
"=",
"new",
"SoapAttachment",
"(",
")",
";",
"attachment",
".",
"setContentId"... | Sets the attachment with string content.
@param contentId
@param contentType
@param content
@return | [
"Sets",
"the",
"attachment",
"with",
"string",
"content",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapServerFaultResponseActionBuilder.java#L66-L74 | train |
citrusframework/citrus | modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapServerFaultResponseActionBuilder.java | SoapServerFaultResponseActionBuilder.charset | public SoapServerFaultResponseActionBuilder charset(String charsetName) {
if (!getAction().getAttachments().isEmpty()) {
getAction().getAttachments().get(getAction().getAttachments().size() - 1).setCharsetName(charsetName);
}
return this;
} | java | public SoapServerFaultResponseActionBuilder charset(String charsetName) {
if (!getAction().getAttachments().isEmpty()) {
getAction().getAttachments().get(getAction().getAttachments().size() - 1).setCharsetName(charsetName);
}
return this;
} | [
"public",
"SoapServerFaultResponseActionBuilder",
"charset",
"(",
"String",
"charsetName",
")",
"{",
"if",
"(",
"!",
"getAction",
"(",
")",
".",
"getAttachments",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"getAction",
"(",
")",
".",
"getAttachments",
"("... | Sets the charset name for this send action builder's attachment.
@param charsetName
@return | [
"Sets",
"the",
"charset",
"name",
"for",
"this",
"send",
"action",
"builder",
"s",
"attachment",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapServerFaultResponseActionBuilder.java#L116-L121 | train |
citrusframework/citrus | modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapServerFaultResponseActionBuilder.java | SoapServerFaultResponseActionBuilder.faultDetailResource | public SoapServerFaultResponseActionBuilder faultDetailResource(Resource resource, Charset charset) {
try {
getAction().getFaultDetails().add(FileUtils.readToString(resource, charset));
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read fault detail resource", e);
}
return this;
} | java | public SoapServerFaultResponseActionBuilder faultDetailResource(Resource resource, Charset charset) {
try {
getAction().getFaultDetails().add(FileUtils.readToString(resource, charset));
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read fault detail resource", e);
}
return this;
} | [
"public",
"SoapServerFaultResponseActionBuilder",
"faultDetailResource",
"(",
"Resource",
"resource",
",",
"Charset",
"charset",
")",
"{",
"try",
"{",
"getAction",
"(",
")",
".",
"getFaultDetails",
"(",
")",
".",
"add",
"(",
"FileUtils",
".",
"readToString",
"(",
... | Adds a fault detail from file resource.
@param resource
@param charset
@return | [
"Adds",
"a",
"fault",
"detail",
"from",
"file",
"resource",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapServerFaultResponseActionBuilder.java#L218-L225 | train |
citrusframework/citrus | modules/citrus-arquillian/src/main/java/com/consol/citrus/arquillian/configuration/CitrusConfiguration.java | CitrusConfiguration.from | public static CitrusConfiguration from(Properties extensionProperties) {
CitrusConfiguration configuration = new CitrusConfiguration(extensionProperties);
configuration.setCitrusVersion(getProperty(extensionProperties, "citrusVersion"));
if (extensionProperties.containsKey("autoPackage")) {
configuration.setAutoPackage(Boolean.valueOf(getProperty(extensionProperties, "autoPackage")));
}
if (extensionProperties.containsKey("suiteName")) {
configuration.setSuiteName(getProperty(extensionProperties, "suiteName"));
}
if (extensionProperties.containsKey("configurationClass")) {
String configurationClass = getProperty(extensionProperties, "configurationClass");
try {
Class<?> configType = Class.forName(configurationClass);
if (CitrusSpringConfig.class.isAssignableFrom(configType)) {
configuration.setConfigurationClass((Class<? extends CitrusSpringConfig>) configType);
} else {
log.warn(String.format("Found invalid Citrus configuration class: %s, must be a subclass of %s", configurationClass, CitrusSpringConfig.class));
}
} catch (ClassNotFoundException e) {
log.warn(String.format("Unable to access Citrus configuration class: %s", configurationClass), e);
}
}
log.debug(String.format("Using Citrus configuration:%n%s", configuration.toString()));
return configuration;
} | java | public static CitrusConfiguration from(Properties extensionProperties) {
CitrusConfiguration configuration = new CitrusConfiguration(extensionProperties);
configuration.setCitrusVersion(getProperty(extensionProperties, "citrusVersion"));
if (extensionProperties.containsKey("autoPackage")) {
configuration.setAutoPackage(Boolean.valueOf(getProperty(extensionProperties, "autoPackage")));
}
if (extensionProperties.containsKey("suiteName")) {
configuration.setSuiteName(getProperty(extensionProperties, "suiteName"));
}
if (extensionProperties.containsKey("configurationClass")) {
String configurationClass = getProperty(extensionProperties, "configurationClass");
try {
Class<?> configType = Class.forName(configurationClass);
if (CitrusSpringConfig.class.isAssignableFrom(configType)) {
configuration.setConfigurationClass((Class<? extends CitrusSpringConfig>) configType);
} else {
log.warn(String.format("Found invalid Citrus configuration class: %s, must be a subclass of %s", configurationClass, CitrusSpringConfig.class));
}
} catch (ClassNotFoundException e) {
log.warn(String.format("Unable to access Citrus configuration class: %s", configurationClass), e);
}
}
log.debug(String.format("Using Citrus configuration:%n%s", configuration.toString()));
return configuration;
} | [
"public",
"static",
"CitrusConfiguration",
"from",
"(",
"Properties",
"extensionProperties",
")",
"{",
"CitrusConfiguration",
"configuration",
"=",
"new",
"CitrusConfiguration",
"(",
"extensionProperties",
")",
";",
"configuration",
".",
"setCitrusVersion",
"(",
"getPrope... | Constructs Citrus configuration instance from given property set.
@param extensionProperties
@return | [
"Constructs",
"Citrus",
"configuration",
"instance",
"from",
"given",
"property",
"set",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-arquillian/src/main/java/com/consol/citrus/arquillian/configuration/CitrusConfiguration.java#L75-L105 | train |
citrusframework/citrus | modules/citrus-arquillian/src/main/java/com/consol/citrus/arquillian/configuration/CitrusConfiguration.java | CitrusConfiguration.getProperty | private static String getProperty(Properties extensionProperties, String propertyName) {
if (extensionProperties.containsKey(propertyName)) {
Object value = extensionProperties.get(propertyName);
if (value != null) {
return value.toString();
}
}
return null;
} | java | private static String getProperty(Properties extensionProperties, String propertyName) {
if (extensionProperties.containsKey(propertyName)) {
Object value = extensionProperties.get(propertyName);
if (value != null) {
return value.toString();
}
}
return null;
} | [
"private",
"static",
"String",
"getProperty",
"(",
"Properties",
"extensionProperties",
",",
"String",
"propertyName",
")",
"{",
"if",
"(",
"extensionProperties",
".",
"containsKey",
"(",
"propertyName",
")",
")",
"{",
"Object",
"value",
"=",
"extensionProperties",
... | Try to read property from property set. When not set or null value return null else
return String representation of value object.
@param extensionProperties
@param propertyName
@return | [
"Try",
"to",
"read",
"property",
"from",
"property",
"set",
".",
"When",
"not",
"set",
"or",
"null",
"value",
"return",
"null",
"else",
"return",
"String",
"representation",
"of",
"value",
"object",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-arquillian/src/main/java/com/consol/citrus/arquillian/configuration/CitrusConfiguration.java#L114-L123 | train |
citrusframework/citrus | modules/citrus-arquillian/src/main/java/com/consol/citrus/arquillian/configuration/CitrusConfiguration.java | CitrusConfiguration.readPropertiesFromDescriptor | private static Properties readPropertiesFromDescriptor(ArquillianDescriptor descriptor) {
for (ExtensionDef extension : descriptor.getExtensions()) {
if (CitrusExtensionConstants.CITRUS_EXTENSION_QUALIFIER.equals(extension.getExtensionName())) {
Properties properties = new Properties();
properties.putAll(extension.getExtensionProperties());
return properties;
}
}
return new Properties();
} | java | private static Properties readPropertiesFromDescriptor(ArquillianDescriptor descriptor) {
for (ExtensionDef extension : descriptor.getExtensions()) {
if (CitrusExtensionConstants.CITRUS_EXTENSION_QUALIFIER.equals(extension.getExtensionName())) {
Properties properties = new Properties();
properties.putAll(extension.getExtensionProperties());
return properties;
}
}
return new Properties();
} | [
"private",
"static",
"Properties",
"readPropertiesFromDescriptor",
"(",
"ArquillianDescriptor",
"descriptor",
")",
"{",
"for",
"(",
"ExtensionDef",
"extension",
":",
"descriptor",
".",
"getExtensions",
"(",
")",
")",
"{",
"if",
"(",
"CitrusExtensionConstants",
".",
... | Find Citrus extension configuration in descriptor and read properties.
@param descriptor
@return | [
"Find",
"Citrus",
"extension",
"configuration",
"in",
"descriptor",
"and",
"read",
"properties",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-arquillian/src/main/java/com/consol/citrus/arquillian/configuration/CitrusConfiguration.java#L130-L140 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/xml/schema/XsdSchemaCollection.java | XsdSchemaCollection.loadSchemaResources | protected Resource loadSchemaResources() {
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
for (String location : schemas) {
try {
Resource[] findings = resourcePatternResolver.getResources(location);
for (Resource finding : findings) {
if (finding.getFilename().endsWith(".xsd") || finding.getFilename().endsWith(".wsdl")) {
schemaResources.add(finding);
}
}
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read schema resources for location: " + location, e);
}
}
return schemaResources.get(0);
} | java | protected Resource loadSchemaResources() {
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
for (String location : schemas) {
try {
Resource[] findings = resourcePatternResolver.getResources(location);
for (Resource finding : findings) {
if (finding.getFilename().endsWith(".xsd") || finding.getFilename().endsWith(".wsdl")) {
schemaResources.add(finding);
}
}
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read schema resources for location: " + location, e);
}
}
return schemaResources.get(0);
} | [
"protected",
"Resource",
"loadSchemaResources",
"(",
")",
"{",
"PathMatchingResourcePatternResolver",
"resourcePatternResolver",
"=",
"new",
"PathMatchingResourcePatternResolver",
"(",
")",
";",
"for",
"(",
"String",
"location",
":",
"schemas",
")",
"{",
"try",
"{",
"... | Loads all schema resource files from schema locations. | [
"Loads",
"all",
"schema",
"resource",
"files",
"from",
"schema",
"locations",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/schema/XsdSchemaCollection.java#L40-L57 | train |
citrusframework/citrus | modules/citrus-websocket/src/main/java/com/consol/citrus/websocket/message/WebSocketMessage.java | WebSocketMessage.isLast | public boolean isLast() {
Object isLast = getHeader(WebSocketMessageHeaders.WEB_SOCKET_IS_LAST);
if (isLast != null) {
if (isLast instanceof String) {
return Boolean.valueOf(isLast.toString());
} else {
return (Boolean) isLast;
}
}
return true;
} | java | public boolean isLast() {
Object isLast = getHeader(WebSocketMessageHeaders.WEB_SOCKET_IS_LAST);
if (isLast != null) {
if (isLast instanceof String) {
return Boolean.valueOf(isLast.toString());
} else {
return (Boolean) isLast;
}
}
return true;
} | [
"public",
"boolean",
"isLast",
"(",
")",
"{",
"Object",
"isLast",
"=",
"getHeader",
"(",
"WebSocketMessageHeaders",
".",
"WEB_SOCKET_IS_LAST",
")",
";",
"if",
"(",
"isLast",
"!=",
"null",
")",
"{",
"if",
"(",
"isLast",
"instanceof",
"String",
")",
"{",
"re... | Gets the isLast flag from message headers.
@return | [
"Gets",
"the",
"isLast",
"flag",
"from",
"message",
"headers",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-websocket/src/main/java/com/consol/citrus/websocket/message/WebSocketMessage.java#L78-L90 | train |
citrusframework/citrus | modules/citrus-jdbc/src/main/java/com/consol/citrus/jdbc/message/JdbcMessage.java | JdbcMessage.getOperationResult | private OperationResult getOperationResult() {
if (operationResult == null) {
this.operationResult = (OperationResult) marshaller.unmarshal(new StringSource(getPayload(String.class)));
}
return operationResult;
} | java | private OperationResult getOperationResult() {
if (operationResult == null) {
this.operationResult = (OperationResult) marshaller.unmarshal(new StringSource(getPayload(String.class)));
}
return operationResult;
} | [
"private",
"OperationResult",
"getOperationResult",
"(",
")",
"{",
"if",
"(",
"operationResult",
"==",
"null",
")",
"{",
"this",
".",
"operationResult",
"=",
"(",
"OperationResult",
")",
"marshaller",
".",
"unmarshal",
"(",
"new",
"StringSource",
"(",
"getPayloa... | Gets the operation result if any or tries to unmarshal String payload representation to an operation result model.
@return | [
"Gets",
"the",
"operation",
"result",
"if",
"any",
"or",
"tries",
"to",
"unmarshal",
"String",
"payload",
"representation",
"to",
"an",
"operation",
"result",
"model",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jdbc/src/main/java/com/consol/citrus/jdbc/message/JdbcMessage.java#L219-L225 | train |
citrusframework/citrus | modules/citrus-jdbc/src/main/java/com/consol/citrus/jdbc/message/JdbcMessage.java | JdbcMessage.getOperation | private Operation getOperation() {
if (operation == null) {
this.operation = (Operation) marshaller.unmarshal(new StringSource(getPayload(String.class)));
}
return operation;
} | java | private Operation getOperation() {
if (operation == null) {
this.operation = (Operation) marshaller.unmarshal(new StringSource(getPayload(String.class)));
}
return operation;
} | [
"private",
"Operation",
"getOperation",
"(",
")",
"{",
"if",
"(",
"operation",
"==",
"null",
")",
"{",
"this",
".",
"operation",
"=",
"(",
"Operation",
")",
"marshaller",
".",
"unmarshal",
"(",
"new",
"StringSource",
"(",
"getPayload",
"(",
"String",
".",
... | Gets the operation if any or tries to unmarshal String payload representation to an operation model.
@return | [
"Gets",
"the",
"operation",
"if",
"any",
"or",
"tries",
"to",
"unmarshal",
"String",
"payload",
"representation",
"to",
"an",
"operation",
"model",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jdbc/src/main/java/com/consol/citrus/jdbc/message/JdbcMessage.java#L231-L237 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/channel/selector/AbstractMessageSelector.java | AbstractMessageSelector.getPayloadAsString | String getPayloadAsString(Message<?> message) {
if (message.getPayload() instanceof com.consol.citrus.message.Message) {
return ((com.consol.citrus.message.Message) message.getPayload()).getPayload(String.class);
} else {
return message.getPayload().toString();
}
} | java | String getPayloadAsString(Message<?> message) {
if (message.getPayload() instanceof com.consol.citrus.message.Message) {
return ((com.consol.citrus.message.Message) message.getPayload()).getPayload(String.class);
} else {
return message.getPayload().toString();
}
} | [
"String",
"getPayloadAsString",
"(",
"Message",
"<",
"?",
">",
"message",
")",
"{",
"if",
"(",
"message",
".",
"getPayload",
"(",
")",
"instanceof",
"com",
".",
"consol",
".",
"citrus",
".",
"message",
".",
"Message",
")",
"{",
"return",
"(",
"(",
"com... | Reads message payload as String either from message object directly or from nested Citrus message representation.
@param message
@return | [
"Reads",
"message",
"payload",
"as",
"String",
"either",
"from",
"message",
"object",
"directly",
"or",
"from",
"nested",
"Citrus",
"message",
"representation",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/channel/selector/AbstractMessageSelector.java#L55-L61 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/channel/selector/AbstractMessageSelector.java | AbstractMessageSelector.evaluate | protected boolean evaluate(String value) {
if (ValidationMatcherUtils.isValidationMatcherExpression(matchingValue)) {
try {
ValidationMatcherUtils.resolveValidationMatcher(selectKey, value, matchingValue, context);
return true;
} catch (ValidationException e) {
return false;
}
} else {
return value.equals(matchingValue);
}
} | java | protected boolean evaluate(String value) {
if (ValidationMatcherUtils.isValidationMatcherExpression(matchingValue)) {
try {
ValidationMatcherUtils.resolveValidationMatcher(selectKey, value, matchingValue, context);
return true;
} catch (ValidationException e) {
return false;
}
} else {
return value.equals(matchingValue);
}
} | [
"protected",
"boolean",
"evaluate",
"(",
"String",
"value",
")",
"{",
"if",
"(",
"ValidationMatcherUtils",
".",
"isValidationMatcherExpression",
"(",
"matchingValue",
")",
")",
"{",
"try",
"{",
"ValidationMatcherUtils",
".",
"resolveValidationMatcher",
"(",
"selectKey... | Evaluates given value to match this selectors matching condition. Automatically supports validation matcher expressions.
@param value
@return | [
"Evaluates",
"given",
"value",
"to",
"match",
"this",
"selectors",
"matching",
"condition",
".",
"Automatically",
"supports",
"validation",
"matcher",
"expressions",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/channel/selector/AbstractMessageSelector.java#L68-L79 | train |
citrusframework/citrus | modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/client/SftpClient.java | SftpClient.createDir | protected FtpMessage createDir(CommandType ftpCommand) {
try {
sftp.mkdir(ftpCommand.getArguments());
return FtpMessage.result(FTPReply.PATHNAME_CREATED, "Pathname created", true);
} catch (SftpException e) {
throw new CitrusRuntimeException("Failed to execute ftp command", e);
}
} | java | protected FtpMessage createDir(CommandType ftpCommand) {
try {
sftp.mkdir(ftpCommand.getArguments());
return FtpMessage.result(FTPReply.PATHNAME_CREATED, "Pathname created", true);
} catch (SftpException e) {
throw new CitrusRuntimeException("Failed to execute ftp command", e);
}
} | [
"protected",
"FtpMessage",
"createDir",
"(",
"CommandType",
"ftpCommand",
")",
"{",
"try",
"{",
"sftp",
".",
"mkdir",
"(",
"ftpCommand",
".",
"getArguments",
"(",
")",
")",
";",
"return",
"FtpMessage",
".",
"result",
"(",
"FTPReply",
".",
"PATHNAME_CREATED",
... | Execute mkDir command and create new directory.
@param ftpCommand
@return | [
"Execute",
"mkDir",
"command",
"and",
"create",
"new",
"directory",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/client/SftpClient.java#L97-L104 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java | XmlConfigurer.createLSParser | public LSParser createLSParser() {
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
configureParser(parser);
return parser;
} | java | public LSParser createLSParser() {
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
configureParser(parser);
return parser;
} | [
"public",
"LSParser",
"createLSParser",
"(",
")",
"{",
"LSParser",
"parser",
"=",
"domImpl",
".",
"createLSParser",
"(",
"DOMImplementationLS",
".",
"MODE_SYNCHRONOUS",
",",
"null",
")",
";",
"configureParser",
"(",
"parser",
")",
";",
"return",
"parser",
";",
... | Creates basic LSParser instance and sets common
properties and configuration parameters.
@return | [
"Creates",
"basic",
"LSParser",
"instance",
"and",
"sets",
"common",
"properties",
"and",
"configuration",
"parameters",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java#L88-L93 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java | XmlConfigurer.configureParser | protected void configureParser(LSParser parser) {
for (Map.Entry<String, Object> setting : parseSettings.entrySet()) {
setParserConfigParameter(parser, setting.getKey(), setting.getValue());
}
} | java | protected void configureParser(LSParser parser) {
for (Map.Entry<String, Object> setting : parseSettings.entrySet()) {
setParserConfigParameter(parser, setting.getKey(), setting.getValue());
}
} | [
"protected",
"void",
"configureParser",
"(",
"LSParser",
"parser",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
"setting",
":",
"parseSettings",
".",
"entrySet",
"(",
")",
")",
"{",
"setParserConfigParameter",
"(",
"parser",
... | Set parser configuration based on this configurers settings.
@param parser | [
"Set",
"parser",
"configuration",
"based",
"on",
"this",
"configurers",
"settings",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java#L99-L103 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java | XmlConfigurer.configureSerializer | protected void configureSerializer(LSSerializer serializer) {
for (Map.Entry<String, Object> setting : serializeSettings.entrySet()) {
setSerializerConfigParameter(serializer, setting.getKey(), setting.getValue());
}
} | java | protected void configureSerializer(LSSerializer serializer) {
for (Map.Entry<String, Object> setting : serializeSettings.entrySet()) {
setSerializerConfigParameter(serializer, setting.getKey(), setting.getValue());
}
} | [
"protected",
"void",
"configureSerializer",
"(",
"LSSerializer",
"serializer",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
"setting",
":",
"serializeSettings",
".",
"entrySet",
"(",
")",
")",
"{",
"setSerializerConfigParameter",... | Set serializer configuration based on this configurers settings.
@param serializer | [
"Set",
"serializer",
"configuration",
"based",
"on",
"this",
"configurers",
"settings",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java#L121-L125 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java | XmlConfigurer.setDefaultParseSettings | private void setDefaultParseSettings() {
if (!parseSettings.containsKey(CDATA_SECTIONS)) {
parseSettings.put(CDATA_SECTIONS, true);
}
if (!parseSettings.containsKey(SPLIT_CDATA_SECTIONS)) {
parseSettings.put(SPLIT_CDATA_SECTIONS, false);
}
if (!parseSettings.containsKey(VALIDATE_IF_SCHEMA)) {
parseSettings.put(VALIDATE_IF_SCHEMA, true);
}
if (!parseSettings.containsKey(RESOURCE_RESOLVER)) {
parseSettings.put(RESOURCE_RESOLVER, createLSResourceResolver());
}
if (!parseSettings.containsKey(ELEMENT_CONTENT_WHITESPACE)) {
parseSettings.put(ELEMENT_CONTENT_WHITESPACE, false);
}
} | java | private void setDefaultParseSettings() {
if (!parseSettings.containsKey(CDATA_SECTIONS)) {
parseSettings.put(CDATA_SECTIONS, true);
}
if (!parseSettings.containsKey(SPLIT_CDATA_SECTIONS)) {
parseSettings.put(SPLIT_CDATA_SECTIONS, false);
}
if (!parseSettings.containsKey(VALIDATE_IF_SCHEMA)) {
parseSettings.put(VALIDATE_IF_SCHEMA, true);
}
if (!parseSettings.containsKey(RESOURCE_RESOLVER)) {
parseSettings.put(RESOURCE_RESOLVER, createLSResourceResolver());
}
if (!parseSettings.containsKey(ELEMENT_CONTENT_WHITESPACE)) {
parseSettings.put(ELEMENT_CONTENT_WHITESPACE, false);
}
} | [
"private",
"void",
"setDefaultParseSettings",
"(",
")",
"{",
"if",
"(",
"!",
"parseSettings",
".",
"containsKey",
"(",
"CDATA_SECTIONS",
")",
")",
"{",
"parseSettings",
".",
"put",
"(",
"CDATA_SECTIONS",
",",
"true",
")",
";",
"}",
"if",
"(",
"!",
"parseSe... | Sets the default parse settings. | [
"Sets",
"the",
"default",
"parse",
"settings",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java#L155-L175 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java | XmlConfigurer.setDefaultSerializeSettings | private void setDefaultSerializeSettings() {
if (!serializeSettings.containsKey(ELEMENT_CONTENT_WHITESPACE)) {
serializeSettings.put(ELEMENT_CONTENT_WHITESPACE, true);
}
if (!serializeSettings.containsKey(SPLIT_CDATA_SECTIONS)) {
serializeSettings.put(SPLIT_CDATA_SECTIONS, false);
}
if (!serializeSettings.containsKey(FORMAT_PRETTY_PRINT)) {
serializeSettings.put(FORMAT_PRETTY_PRINT, true);
}
if (!serializeSettings.containsKey(XML_DECLARATION)) {
serializeSettings.put(XML_DECLARATION, true);
}
} | java | private void setDefaultSerializeSettings() {
if (!serializeSettings.containsKey(ELEMENT_CONTENT_WHITESPACE)) {
serializeSettings.put(ELEMENT_CONTENT_WHITESPACE, true);
}
if (!serializeSettings.containsKey(SPLIT_CDATA_SECTIONS)) {
serializeSettings.put(SPLIT_CDATA_SECTIONS, false);
}
if (!serializeSettings.containsKey(FORMAT_PRETTY_PRINT)) {
serializeSettings.put(FORMAT_PRETTY_PRINT, true);
}
if (!serializeSettings.containsKey(XML_DECLARATION)) {
serializeSettings.put(XML_DECLARATION, true);
}
} | [
"private",
"void",
"setDefaultSerializeSettings",
"(",
")",
"{",
"if",
"(",
"!",
"serializeSettings",
".",
"containsKey",
"(",
"ELEMENT_CONTENT_WHITESPACE",
")",
")",
"{",
"serializeSettings",
".",
"put",
"(",
"ELEMENT_CONTENT_WHITESPACE",
",",
"true",
")",
";",
"... | Sets the default serialize settings. | [
"Sets",
"the",
"default",
"serialize",
"settings",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/XmlConfigurer.java#L180-L196 | train |
citrusframework/citrus | modules/citrus-mail/src/main/java/com/consol/citrus/mail/model/BodyPart.java | BodyPart.addPart | public void addPart(AttachmentPart part) {
if (attachments == null) {
attachments = new BodyPart.Attachments();
}
this.attachments.add(part);
} | java | public void addPart(AttachmentPart part) {
if (attachments == null) {
attachments = new BodyPart.Attachments();
}
this.attachments.add(part);
} | [
"public",
"void",
"addPart",
"(",
"AttachmentPart",
"part",
")",
"{",
"if",
"(",
"attachments",
"==",
"null",
")",
"{",
"attachments",
"=",
"new",
"BodyPart",
".",
"Attachments",
"(",
")",
";",
"}",
"this",
".",
"attachments",
".",
"add",
"(",
"part",
... | Adds new attachment part.
@param part | [
"Adds",
"new",
"attachment",
"part",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-mail/src/main/java/com/consol/citrus/mail/model/BodyPart.java#L69-L75 | train |
citrusframework/citrus | modules/citrus-rmi/src/main/java/com/consol/citrus/rmi/endpoint/RmiEndpointUtils.java | RmiEndpointUtils.getBinding | public static String getBinding(String resourcePath) {
if (resourcePath.contains("/")) {
return resourcePath.substring(resourcePath.indexOf('/') + 1);
}
return null;
} | java | public static String getBinding(String resourcePath) {
if (resourcePath.contains("/")) {
return resourcePath.substring(resourcePath.indexOf('/') + 1);
}
return null;
} | [
"public",
"static",
"String",
"getBinding",
"(",
"String",
"resourcePath",
")",
"{",
"if",
"(",
"resourcePath",
".",
"contains",
"(",
"\"/\"",
")",
")",
"{",
"return",
"resourcePath",
".",
"substring",
"(",
"resourcePath",
".",
"indexOf",
"(",
"'",
"'",
")... | Extract service binding information from endpoint resource path. This is usualle the path after the port specification.
@param resourcePath
@return | [
"Extract",
"service",
"binding",
"information",
"from",
"endpoint",
"resource",
"path",
".",
"This",
"is",
"usualle",
"the",
"path",
"after",
"the",
"port",
"specification",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-rmi/src/main/java/com/consol/citrus/rmi/endpoint/RmiEndpointUtils.java#L37-L43 | train |
citrusframework/citrus | modules/citrus-rmi/src/main/java/com/consol/citrus/rmi/endpoint/RmiEndpointUtils.java | RmiEndpointUtils.getHost | public static String getHost(String resourcePath) {
String hostSpec;
if (resourcePath.contains(":")) {
hostSpec = resourcePath.split(":")[0];
} else {
hostSpec = resourcePath;
}
if (hostSpec.contains("/")) {
hostSpec = hostSpec.substring(0, hostSpec.indexOf('/'));
}
return hostSpec;
} | java | public static String getHost(String resourcePath) {
String hostSpec;
if (resourcePath.contains(":")) {
hostSpec = resourcePath.split(":")[0];
} else {
hostSpec = resourcePath;
}
if (hostSpec.contains("/")) {
hostSpec = hostSpec.substring(0, hostSpec.indexOf('/'));
}
return hostSpec;
} | [
"public",
"static",
"String",
"getHost",
"(",
"String",
"resourcePath",
")",
"{",
"String",
"hostSpec",
";",
"if",
"(",
"resourcePath",
".",
"contains",
"(",
"\":\"",
")",
")",
"{",
"hostSpec",
"=",
"resourcePath",
".",
"split",
"(",
"\":\"",
")",
"[",
"... | Extract host name from resource path.
@param resourcePath
@return | [
"Extract",
"host",
"name",
"from",
"resource",
"path",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-rmi/src/main/java/com/consol/citrus/rmi/endpoint/RmiEndpointUtils.java#L70-L83 | train |
citrusframework/citrus | modules/citrus-ws/src/main/java/com/consol/citrus/ws/message/SoapAttachment.java | SoapAttachment.from | public static SoapAttachment from(Attachment attachment) {
SoapAttachment soapAttachment = new SoapAttachment();
String contentId = attachment.getContentId();
if (contentId.startsWith("<") && contentId.endsWith(">")) {
contentId = contentId.substring(1, contentId.length() - 1);
}
soapAttachment.setContentId(contentId);
soapAttachment.setContentType(attachment.getContentType());
if (attachment.getContentType().startsWith("text")) {
try {
soapAttachment.setContent(FileUtils.readToString(attachment.getInputStream()).trim());
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read SOAP attachment content", e);
}
} else {
// Binary content
soapAttachment.setDataHandler(attachment.getDataHandler());
}
soapAttachment.setCharsetName(Citrus.CITRUS_FILE_ENCODING);
return soapAttachment;
} | java | public static SoapAttachment from(Attachment attachment) {
SoapAttachment soapAttachment = new SoapAttachment();
String contentId = attachment.getContentId();
if (contentId.startsWith("<") && contentId.endsWith(">")) {
contentId = contentId.substring(1, contentId.length() - 1);
}
soapAttachment.setContentId(contentId);
soapAttachment.setContentType(attachment.getContentType());
if (attachment.getContentType().startsWith("text")) {
try {
soapAttachment.setContent(FileUtils.readToString(attachment.getInputStream()).trim());
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read SOAP attachment content", e);
}
} else {
// Binary content
soapAttachment.setDataHandler(attachment.getDataHandler());
}
soapAttachment.setCharsetName(Citrus.CITRUS_FILE_ENCODING);
return soapAttachment;
} | [
"public",
"static",
"SoapAttachment",
"from",
"(",
"Attachment",
"attachment",
")",
"{",
"SoapAttachment",
"soapAttachment",
"=",
"new",
"SoapAttachment",
"(",
")",
";",
"String",
"contentId",
"=",
"attachment",
".",
"getContentId",
"(",
")",
";",
"if",
"(",
"... | Static construction method from Spring mime attachment.
@param attachment
@return | [
"Static",
"construction",
"method",
"from",
"Spring",
"mime",
"attachment",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-ws/src/main/java/com/consol/citrus/ws/message/SoapAttachment.java#L87-L111 | train |
citrusframework/citrus | modules/citrus-ws/src/main/java/com/consol/citrus/ws/message/SoapAttachment.java | SoapAttachment.getContent | public String getContent() {
if (content != null) {
return context != null ? context.replaceDynamicContentInString(content) : content;
} else if (StringUtils.hasText(getContentResourcePath()) && getContentType().startsWith("text")) {
try {
String fileContent = FileUtils.readToString(new PathMatchingResourcePatternResolver().getResource(getContentResourcePath()).getInputStream(), Charset.forName(charsetName));
return context != null ? context.replaceDynamicContentInString(fileContent) : fileContent;
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read SOAP attachment file resource", e);
}
} else {
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(getDataHandler().getInputStream());
if (encodingType.equals(SoapAttachment.ENCODING_BASE64_BINARY)) {
return Base64.encodeBase64String(binaryData);
} else if (encodingType.equals(SoapAttachment.ENCODING_HEX_BINARY)) {
return Hex.encodeHexString(binaryData).toUpperCase();
} else {
throw new CitrusRuntimeException(String.format("Unsupported encoding type '%s' for SOAP attachment - choose one of %s or %s",
encodingType, SoapAttachment.ENCODING_BASE64_BINARY, SoapAttachment.ENCODING_HEX_BINARY));
}
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read SOAP attachment data input stream", e);
}
}
} | java | public String getContent() {
if (content != null) {
return context != null ? context.replaceDynamicContentInString(content) : content;
} else if (StringUtils.hasText(getContentResourcePath()) && getContentType().startsWith("text")) {
try {
String fileContent = FileUtils.readToString(new PathMatchingResourcePatternResolver().getResource(getContentResourcePath()).getInputStream(), Charset.forName(charsetName));
return context != null ? context.replaceDynamicContentInString(fileContent) : fileContent;
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read SOAP attachment file resource", e);
}
} else {
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(getDataHandler().getInputStream());
if (encodingType.equals(SoapAttachment.ENCODING_BASE64_BINARY)) {
return Base64.encodeBase64String(binaryData);
} else if (encodingType.equals(SoapAttachment.ENCODING_HEX_BINARY)) {
return Hex.encodeHexString(binaryData).toUpperCase();
} else {
throw new CitrusRuntimeException(String.format("Unsupported encoding type '%s' for SOAP attachment - choose one of %s or %s",
encodingType, SoapAttachment.ENCODING_BASE64_BINARY, SoapAttachment.ENCODING_HEX_BINARY));
}
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read SOAP attachment data input stream", e);
}
}
} | [
"public",
"String",
"getContent",
"(",
")",
"{",
"if",
"(",
"content",
"!=",
"null",
")",
"{",
"return",
"context",
"!=",
"null",
"?",
"context",
".",
"replaceDynamicContentInString",
"(",
"content",
")",
":",
"content",
";",
"}",
"else",
"if",
"(",
"Str... | Get the content body.
@return the content | [
"Get",
"the",
"content",
"body",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-ws/src/main/java/com/consol/citrus/ws/message/SoapAttachment.java#L189-L214 | train |
citrusframework/citrus | modules/citrus-ws/src/main/java/com/consol/citrus/ws/message/SoapAttachment.java | SoapAttachment.getContentResourcePath | public String getContentResourcePath() {
if (contentResourcePath != null && context != null) {
return context.replaceDynamicContentInString(contentResourcePath);
} else {
return contentResourcePath;
}
} | java | public String getContentResourcePath() {
if (contentResourcePath != null && context != null) {
return context.replaceDynamicContentInString(contentResourcePath);
} else {
return contentResourcePath;
}
} | [
"public",
"String",
"getContentResourcePath",
"(",
")",
"{",
"if",
"(",
"contentResourcePath",
"!=",
"null",
"&&",
"context",
"!=",
"null",
")",
"{",
"return",
"context",
".",
"replaceDynamicContentInString",
"(",
"contentResourcePath",
")",
";",
"}",
"else",
"{... | Get the content file resource path.
@return the content resource path | [
"Get",
"the",
"content",
"file",
"resource",
"path",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-ws/src/main/java/com/consol/citrus/ws/message/SoapAttachment.java#L228-L234 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/variable/MessageHeaderVariableExtractor.java | MessageHeaderVariableExtractor.extractVariables | public void extractVariables(Message message, TestContext context) {
if (CollectionUtils.isEmpty(headerMappings)) { return; }
for (Entry<String, String> entry : headerMappings.entrySet()) {
String headerElementName = entry.getKey();
String targetVariableName = entry.getValue();
if (message.getHeader(headerElementName) == null) {
throw new UnknownElementException("Could not find header element " + headerElementName + " in received header");
}
context.setVariable(targetVariableName, message.getHeader(headerElementName).toString());
}
} | java | public void extractVariables(Message message, TestContext context) {
if (CollectionUtils.isEmpty(headerMappings)) { return; }
for (Entry<String, String> entry : headerMappings.entrySet()) {
String headerElementName = entry.getKey();
String targetVariableName = entry.getValue();
if (message.getHeader(headerElementName) == null) {
throw new UnknownElementException("Could not find header element " + headerElementName + " in received header");
}
context.setVariable(targetVariableName, message.getHeader(headerElementName).toString());
}
} | [
"public",
"void",
"extractVariables",
"(",
"Message",
"message",
",",
"TestContext",
"context",
")",
"{",
"if",
"(",
"CollectionUtils",
".",
"isEmpty",
"(",
"headerMappings",
")",
")",
"{",
"return",
";",
"}",
"for",
"(",
"Entry",
"<",
"String",
",",
"Stri... | Reads header information and saves new test variables. | [
"Reads",
"header",
"information",
"and",
"saves",
"new",
"test",
"variables",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/variable/MessageHeaderVariableExtractor.java#L41-L54 | train |
citrusframework/citrus | modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/KubernetesActionBuilder.java | KubernetesActionBuilder.command | public <T extends KubernetesCommand> T command(T command) {
action.setCommand(command);
return command;
} | java | public <T extends KubernetesCommand> T command(T command) {
action.setCommand(command);
return command;
} | [
"public",
"<",
"T",
"extends",
"KubernetesCommand",
">",
"T",
"command",
"(",
"T",
"command",
")",
"{",
"action",
".",
"setCommand",
"(",
"command",
")",
";",
"return",
"command",
";",
"}"
] | Use a kubernetes command. | [
"Use",
"a",
"kubernetes",
"command",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/KubernetesActionBuilder.java#L59-L62 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/actions/ReceiveMessageAction.java | ReceiveMessageAction.receive | private Message receive(TestContext context) {
Endpoint messageEndpoint = getOrCreateEndpoint(context);
return receiveTimeout > 0 ? messageEndpoint.createConsumer().receive(context, receiveTimeout) :
messageEndpoint.createConsumer().receive(context, messageEndpoint.getEndpointConfiguration().getTimeout());
} | java | private Message receive(TestContext context) {
Endpoint messageEndpoint = getOrCreateEndpoint(context);
return receiveTimeout > 0 ? messageEndpoint.createConsumer().receive(context, receiveTimeout) :
messageEndpoint.createConsumer().receive(context, messageEndpoint.getEndpointConfiguration().getTimeout());
} | [
"private",
"Message",
"receive",
"(",
"TestContext",
"context",
")",
"{",
"Endpoint",
"messageEndpoint",
"=",
"getOrCreateEndpoint",
"(",
"context",
")",
";",
"return",
"receiveTimeout",
">",
"0",
"?",
"messageEndpoint",
".",
"createConsumer",
"(",
")",
".",
"re... | Receives the message with respective message receiver implementation.
@return | [
"Receives",
"the",
"message",
"with",
"respective",
"message",
"receiver",
"implementation",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/actions/ReceiveMessageAction.java#L138-L142 | train |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/actions/ReceiveMessageAction.java | ReceiveMessageAction.receiveSelected | private Message receiveSelected(TestContext context, String selectorString) {
if (log.isDebugEnabled()) {
log.debug("Setting message selector: '" + selectorString + "'");
}
Endpoint messageEndpoint = getOrCreateEndpoint(context);
Consumer consumer = messageEndpoint.createConsumer();
if (consumer instanceof SelectiveConsumer) {
if (receiveTimeout > 0) {
return ((SelectiveConsumer) messageEndpoint.createConsumer()).receive(
context.replaceDynamicContentInString(selectorString),
context, receiveTimeout);
} else {
return ((SelectiveConsumer) messageEndpoint.createConsumer()).receive(
context.replaceDynamicContentInString(selectorString),
context, messageEndpoint.getEndpointConfiguration().getTimeout());
}
} else {
log.warn(String.format("Unable to receive selective with consumer implementation: '%s'", consumer.getClass()));
return receive(context);
}
} | java | private Message receiveSelected(TestContext context, String selectorString) {
if (log.isDebugEnabled()) {
log.debug("Setting message selector: '" + selectorString + "'");
}
Endpoint messageEndpoint = getOrCreateEndpoint(context);
Consumer consumer = messageEndpoint.createConsumer();
if (consumer instanceof SelectiveConsumer) {
if (receiveTimeout > 0) {
return ((SelectiveConsumer) messageEndpoint.createConsumer()).receive(
context.replaceDynamicContentInString(selectorString),
context, receiveTimeout);
} else {
return ((SelectiveConsumer) messageEndpoint.createConsumer()).receive(
context.replaceDynamicContentInString(selectorString),
context, messageEndpoint.getEndpointConfiguration().getTimeout());
}
} else {
log.warn(String.format("Unable to receive selective with consumer implementation: '%s'", consumer.getClass()));
return receive(context);
}
} | [
"private",
"Message",
"receiveSelected",
"(",
"TestContext",
"context",
",",
"String",
"selectorString",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Setting message selector: '\"",
"+",
"selectorString",
"+... | Receives the message with the respective message receiver implementation
also using a message selector.
@param context the test context.
@param selectorString the message selector string.
@return | [
"Receives",
"the",
"message",
"with",
"the",
"respective",
"message",
"receiver",
"implementation",
"also",
"using",
"a",
"message",
"selector",
"."
] | 55c58ef74c01d511615e43646ca25c1b2301c56d | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/actions/ReceiveMessageAction.java#L151-L172 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.