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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.buildMarkdown | void buildMarkdown(Node parent) throws InvalidInputException {
for (Element child : this.children) {
Node node = child.asMarkdown();
if (node != null) {
parent.appendChild(node);
} else {
node = parent;
}
child.buildMarkdown(node);
}
} | java | void buildMarkdown(Node parent) throws InvalidInputException {
for (Element child : this.children) {
Node node = child.asMarkdown();
if (node != null) {
parent.appendChild(node);
} else {
node = parent;
}
child.buildMarkdown(node);
}
} | [
"void",
"buildMarkdown",
"(",
"Node",
"parent",
")",
"throws",
"InvalidInputException",
"{",
"for",
"(",
"Element",
"child",
":",
"this",
".",
"children",
")",
"{",
"Node",
"node",
"=",
"child",
".",
"asMarkdown",
"(",
")",
";",
"if",
"(",
"node",
"!=",
... | Traverse the element and its children to construct its representation as a Markdown tree. | [
"Traverse",
"the",
"element",
"and",
"its",
"children",
"to",
"construct",
"its",
"representation",
"as",
"a",
"Markdown",
"tree",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L154-L165 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.buildEntityJson | void buildEntityJson(ObjectNode parent) {
for (Element child : this.children) {
ObjectNode node = child.asEntityJson(parent);
if (node != null) {
child.buildEntityJson(node);
} else {
child.buildEntityJson(parent);
}
}
} | java | void buildEntityJson(ObjectNode parent) {
for (Element child : this.children) {
ObjectNode node = child.asEntityJson(parent);
if (node != null) {
child.buildEntityJson(node);
} else {
child.buildEntityJson(parent);
}
}
} | [
"void",
"buildEntityJson",
"(",
"ObjectNode",
"parent",
")",
"{",
"for",
"(",
"Element",
"child",
":",
"this",
".",
"children",
")",
"{",
"ObjectNode",
"node",
"=",
"child",
".",
"asEntityJson",
"(",
"parent",
")",
";",
"if",
"(",
"node",
"!=",
"null",
... | Traverse the element and its children to construct its representation as EntityJSON nodes. | [
"Traverse",
"the",
"element",
"and",
"its",
"children",
"to",
"construct",
"its",
"representation",
"as",
"EntityJSON",
"nodes",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L170-L180 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.asPresentationML | void asPresentationML(XmlPrintStream out) {
out.openElement(getMessageMLTag(), getAttributes());
for (Element child : getChildren()) {
child.asPresentationML(out);
}
out.closeElement();
} | java | void asPresentationML(XmlPrintStream out) {
out.openElement(getMessageMLTag(), getAttributes());
for (Element child : getChildren()) {
child.asPresentationML(out);
}
out.closeElement();
} | [
"void",
"asPresentationML",
"(",
"XmlPrintStream",
"out",
")",
"{",
"out",
".",
"openElement",
"(",
"getMessageMLTag",
"(",
")",
",",
"getAttributes",
"(",
")",
")",
";",
"for",
"(",
"Element",
"child",
":",
"getChildren",
"(",
")",
")",
"{",
"child",
".... | Print a PresentationML representation of the element and its children to the provided PrintStream. | [
"Print",
"a",
"PresentationML",
"representation",
"of",
"the",
"element",
"and",
"its",
"children",
"to",
"the",
"provided",
"PrintStream",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L192-L200 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.asText | public String asText() {
StringBuilder b = new StringBuilder();
for (Element child : children) {
b.append(child.asText());
}
return b.toString();
} | java | public String asText() {
StringBuilder b = new StringBuilder();
for (Element child : children) {
b.append(child.asText());
}
return b.toString();
} | [
"public",
"String",
"asText",
"(",
")",
"{",
"StringBuilder",
"b",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Element",
"child",
":",
"children",
")",
"{",
"b",
".",
"append",
"(",
"child",
".",
"asText",
"(",
")",
")",
";",
"}",
"ret... | Return a text representation of the element, descending into its children. | [
"Return",
"a",
"text",
"representation",
"of",
"the",
"element",
"descending",
"into",
"its",
"children",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L205-L213 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.getLongAttribute | Long getLongAttribute(org.w3c.dom.Node attribute) throws InvalidInputException {
String s = getStringAttribute(attribute);
if (s == null) {
return null;
}
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
throw new InvalidInputException("Invalid input: " + attribute.getNodeName()
+ " must be a int64 value not \"" + s + "\"");
}
} | java | Long getLongAttribute(org.w3c.dom.Node attribute) throws InvalidInputException {
String s = getStringAttribute(attribute);
if (s == null) {
return null;
}
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
throw new InvalidInputException("Invalid input: " + attribute.getNodeName()
+ " must be a int64 value not \"" + s + "\"");
}
} | [
"Long",
"getLongAttribute",
"(",
"org",
".",
"w3c",
".",
"dom",
".",
"Node",
"attribute",
")",
"throws",
"InvalidInputException",
"{",
"String",
"s",
"=",
"getStringAttribute",
"(",
"attribute",
")",
";",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"return",
... | Get a DOM attribute as a Long value. | [
"Get",
"a",
"DOM",
"attribute",
"as",
"a",
"Long",
"value",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L238-L251 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.getBooleanAttribute | Boolean getBooleanAttribute(org.w3c.dom.Node attribute) {
String s = getStringAttribute(attribute);
if (s == null) {
return null;
}
return Boolean.parseBoolean(s);
} | java | Boolean getBooleanAttribute(org.w3c.dom.Node attribute) {
String s = getStringAttribute(attribute);
if (s == null) {
return null;
}
return Boolean.parseBoolean(s);
} | [
"Boolean",
"getBooleanAttribute",
"(",
"org",
".",
"w3c",
".",
"dom",
".",
"Node",
"attribute",
")",
"{",
"String",
"s",
"=",
"getStringAttribute",
"(",
"attribute",
")",
";",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return"... | Get a DOM attribute as a Boolean value. | [
"Get",
"a",
"DOM",
"attribute",
"as",
"a",
"Boolean",
"value",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L256-L264 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.getUrlAttribute | URI getUrlAttribute(org.w3c.dom.Node attribute) throws InvalidInputException {
String s = getStringAttribute(attribute);
if (s == null) {
return null;
}
try {
return new URI(s);
} catch (URISyntaxException e) {
throw new InvalidInputException("Invalid input: " + attribute.getLocalName()
+ " must be a URI value not \"" + s + "\"");
}
} | java | URI getUrlAttribute(org.w3c.dom.Node attribute) throws InvalidInputException {
String s = getStringAttribute(attribute);
if (s == null) {
return null;
}
try {
return new URI(s);
} catch (URISyntaxException e) {
throw new InvalidInputException("Invalid input: " + attribute.getLocalName()
+ " must be a URI value not \"" + s + "\"");
}
} | [
"URI",
"getUrlAttribute",
"(",
"org",
".",
"w3c",
".",
"dom",
".",
"Node",
"attribute",
")",
"throws",
"InvalidInputException",
"{",
"String",
"s",
"=",
"getStringAttribute",
"(",
"attribute",
")",
";",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"return",
"... | Get a DOM attribute as a URI. | [
"Get",
"a",
"DOM",
"attribute",
"as",
"a",
"URI",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L269-L282 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.assertNoText | void assertNoText() throws InvalidInputException {
for (Element child : this.getChildren())
if (child instanceof TextNode && StringUtils.isNotBlank(((TextNode) child).getText())) {
throw new InvalidInputException("Element \"" + this.getMessageMLTag() + "\" may not have text content");
}
} | java | void assertNoText() throws InvalidInputException {
for (Element child : this.getChildren())
if (child instanceof TextNode && StringUtils.isNotBlank(((TextNode) child).getText())) {
throw new InvalidInputException("Element \"" + this.getMessageMLTag() + "\" may not have text content");
}
} | [
"void",
"assertNoText",
"(",
")",
"throws",
"InvalidInputException",
"{",
"for",
"(",
"Element",
"child",
":",
"this",
".",
"getChildren",
"(",
")",
")",
"if",
"(",
"child",
"instanceof",
"TextNode",
"&&",
"StringUtils",
".",
"isNotBlank",
"(",
"(",
"(",
"... | Check that the element has no text content. | [
"Check",
"that",
"the",
"element",
"has",
"no",
"text",
"content",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L306-L311 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.assertPhrasingContent | void assertPhrasingContent() throws InvalidInputException {
assertContentModel(Arrays.asList(TextNode.class, Link.class, Chime.class, Bold.class, Italic.class, Image.class,
LineBreak.class, Span.class, Emoji.class, HashTag.class, CashTag.class, Mention.class));
} | java | void assertPhrasingContent() throws InvalidInputException {
assertContentModel(Arrays.asList(TextNode.class, Link.class, Chime.class, Bold.class, Italic.class, Image.class,
LineBreak.class, Span.class, Emoji.class, HashTag.class, CashTag.class, Mention.class));
} | [
"void",
"assertPhrasingContent",
"(",
")",
"throws",
"InvalidInputException",
"{",
"assertContentModel",
"(",
"Arrays",
".",
"asList",
"(",
"TextNode",
".",
"class",
",",
"Link",
".",
"class",
",",
"Chime",
".",
"class",
",",
"Bold",
".",
"class",
",",
"Ital... | Check that the element's children are limited to phrasing content.
@throws InvalidInputException | [
"Check",
"that",
"the",
"element",
"s",
"children",
"are",
"limited",
"to",
"phrasing",
"content",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L317-L320 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.assertContentModel | void assertContentModel(Collection<Class<? extends Element>> permittedChildren) throws InvalidInputException {
for (Element child : this.getChildren()) {
if (!permittedChildren.contains(child.getClass())) {
//Permit whitespace
if (child instanceof TextNode && StringUtils.isBlank(((TextNode) child).getText())) {
continue;
}
throw new InvalidInputException("Element \"" + child.getMessageMLTag() + "\" is not allowed in \""
+ this.getMessageMLTag() + "\"");
}
}
} | java | void assertContentModel(Collection<Class<? extends Element>> permittedChildren) throws InvalidInputException {
for (Element child : this.getChildren()) {
if (!permittedChildren.contains(child.getClass())) {
//Permit whitespace
if (child instanceof TextNode && StringUtils.isBlank(((TextNode) child).getText())) {
continue;
}
throw new InvalidInputException("Element \"" + child.getMessageMLTag() + "\" is not allowed in \""
+ this.getMessageMLTag() + "\"");
}
}
} | [
"void",
"assertContentModel",
"(",
"Collection",
"<",
"Class",
"<",
"?",
"extends",
"Element",
">",
">",
"permittedChildren",
")",
"throws",
"InvalidInputException",
"{",
"for",
"(",
"Element",
"child",
":",
"this",
".",
"getChildren",
"(",
")",
")",
"{",
"i... | Check that the element's children are limited to allowed element types. | [
"Check",
"that",
"the",
"element",
"s",
"children",
"are",
"limited",
"to",
"allowed",
"element",
"types",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L325-L338 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java | Element.assertParent | void assertParent(Collection<Class<? extends Element>> permittedParents) throws InvalidInputException {
if (!permittedParents.contains(this.getParent().getClass())) {
throw new InvalidInputException("Element \"" + this.getMessageMLTag() + "\" is not allowed as a child of \""
+ this.getParent().getMessageMLTag() + "\"");
}
} | java | void assertParent(Collection<Class<? extends Element>> permittedParents) throws InvalidInputException {
if (!permittedParents.contains(this.getParent().getClass())) {
throw new InvalidInputException("Element \"" + this.getMessageMLTag() + "\" is not allowed as a child of \""
+ this.getParent().getMessageMLTag() + "\"");
}
} | [
"void",
"assertParent",
"(",
"Collection",
"<",
"Class",
"<",
"?",
"extends",
"Element",
">",
">",
"permittedParents",
")",
"throws",
"InvalidInputException",
"{",
"if",
"(",
"!",
"permittedParents",
".",
"contains",
"(",
"this",
".",
"getParent",
"(",
")",
... | Check that the element's allowed parents are limited to the specified element types. | [
"Check",
"that",
"the",
"element",
"s",
"allowed",
"parents",
"are",
"limited",
"to",
"the",
"specified",
"element",
"types",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Element.java#L343-L348 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownRenderer.java | MarkdownRenderer.visitChildren | private void visitChildren(Node parent, Collection<Class<? extends Node>> includeNodes) {
Node child = parent.getFirstChild();
while (child != null) {
// A subclass of this visitor might modify the node, resulting in getNext returning a different node or no
// node after visiting it. So get the next node before visiting.
Node next = child.getNext();
if (includeNodes.contains(child.getClass())) {
child.accept(this);
} else {
visitChildren(child, includeNodes);
}
child = next;
}
} | java | private void visitChildren(Node parent, Collection<Class<? extends Node>> includeNodes) {
Node child = parent.getFirstChild();
while (child != null) {
// A subclass of this visitor might modify the node, resulting in getNext returning a different node or no
// node after visiting it. So get the next node before visiting.
Node next = child.getNext();
if (includeNodes.contains(child.getClass())) {
child.accept(this);
} else {
visitChildren(child, includeNodes);
}
child = next;
}
} | [
"private",
"void",
"visitChildren",
"(",
"Node",
"parent",
",",
"Collection",
"<",
"Class",
"<",
"?",
"extends",
"Node",
">",
">",
"includeNodes",
")",
"{",
"Node",
"child",
"=",
"parent",
".",
"getFirstChild",
"(",
")",
";",
"while",
"(",
"child",
"!=",... | Recursively visit the children of the node, processing only those specified by the parameter "includeNodes". | [
"Recursively",
"visit",
"the",
"children",
"of",
"the",
"node",
"processing",
"only",
"those",
"specified",
"by",
"the",
"parameter",
"includeNodes",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownRenderer.java#L341-L354 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/entityjson/StructuredObject.java | StructuredObject.validate | public IEntityJsonSchemaContext validate(EntityJsonParser parser) throws SchemaValidationException, NoSchemaException, InvalidSchemaException
{
StringBuffer ubuf = new StringBuffer("https://symphonyosf.github.io/symphony-object/proposed");
for(String part : type_.split("\\."))
{
ubuf.append("/");
ubuf.append(part);
}
ubuf.append("-v");
ubuf.append(majorVersion_);
ubuf.append("_");
ubuf.append(minorVersion_);
ubuf.append(".json");
try
{
return parser.validate(new URL(ubuf.toString()), instanceSource_, jsonNode_);
}
catch (MalformedURLException e)
{
throw new InvalidSchemaException(null, e);
}
} | java | public IEntityJsonSchemaContext validate(EntityJsonParser parser) throws SchemaValidationException, NoSchemaException, InvalidSchemaException
{
StringBuffer ubuf = new StringBuffer("https://symphonyosf.github.io/symphony-object/proposed");
for(String part : type_.split("\\."))
{
ubuf.append("/");
ubuf.append(part);
}
ubuf.append("-v");
ubuf.append(majorVersion_);
ubuf.append("_");
ubuf.append(minorVersion_);
ubuf.append(".json");
try
{
return parser.validate(new URL(ubuf.toString()), instanceSource_, jsonNode_);
}
catch (MalformedURLException e)
{
throw new InvalidSchemaException(null, e);
}
} | [
"public",
"IEntityJsonSchemaContext",
"validate",
"(",
"EntityJsonParser",
"parser",
")",
"throws",
"SchemaValidationException",
",",
"NoSchemaException",
",",
"InvalidSchemaException",
"{",
"StringBuffer",
"ubuf",
"=",
"new",
"StringBuffer",
"(",
"\"https://symphonyosf.githu... | Validate this object against the specific schema for this type from the official repo.
@param parser A parser to do the validation.
@return A context containing the detailed error report if any.
@throws SchemaValidationException If this object is not valid according to it's schema.
@throws NoSchemaException If there is no official schema for this type.
@throws InvalidSchemaException If the schema exists but is not itself valid or cannot be read. | [
"Validate",
"this",
"object",
"against",
"the",
"specific",
"schema",
"for",
"this",
"type",
"from",
"the",
"official",
"repo",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/entityjson/StructuredObject.java#L143-L167 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownParser.java | MarkdownParser.enrichMarkdown | private String enrichMarkdown(String message, JsonNode entitiesNode, JsonNode mediaNode) throws InvalidInputException {
TreeMap<Integer, JsonNode> entities = new TreeMap<>();
TreeMap<Integer, JsonNode> media = new TreeMap<>();
if (entitiesNode != null) {
validateEntities(entitiesNode);
for (JsonNode node : entitiesNode.findParents(INDEX_START)) {
entities.put(node.get(INDEX_START).intValue(), node);
}
}
if (mediaNode != null) {
validateMedia(mediaNode);
for (JsonNode node : mediaNode.findParents(INDEX)) {
media.put(node.get(INDEX).intValue(), node.get(TEXT));
}
}
// If entity indices are outside the message, pad the message to the necessary length
int lastIndex = Math.max((!entities.isEmpty()) ? entities.lastKey() : 0, (!media.isEmpty()) ? media.lastKey() : 0);
if (message.length() <= lastIndex) {
message = StringUtils.rightPad(message, lastIndex + 1);
}
StringBuilder output = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (entities.containsKey(i)) {
JsonNode entity = entities.get(i);
String entityType = entity.get(TYPE).asText().toUpperCase();
String id = entity.get(ID).asText();
output.append(ENTITY_DELIMITER);
output.append(entityType).append(FIELD_DELIMITER);
output.append(id);
output.append(ENTITY_DELIMITER);
// We explicitly check the entity indices above, but make double sure that we don't get into an infinite loop here
int endIndex = entity.get(INDEX_END).intValue() - 1;
i = Math.max(endIndex, i);
} else if (media.containsKey(i)) {
JsonNode table = media.get(i);
output.append(ENTITY_DELIMITER);
output.append(TABLE).append(FIELD_DELIMITER);
for (JsonNode row : table) {
for (JsonNode cell : row) {
String text = cell.asText();
output.append(text).append(RECORD_DELIMITER);
}
output.append(GROUP_DELIMITER);
}
output.append(ENTITY_DELIMITER);
output.append(c);
} else {
output.append(c);
}
}
return output.toString();
} | java | private String enrichMarkdown(String message, JsonNode entitiesNode, JsonNode mediaNode) throws InvalidInputException {
TreeMap<Integer, JsonNode> entities = new TreeMap<>();
TreeMap<Integer, JsonNode> media = new TreeMap<>();
if (entitiesNode != null) {
validateEntities(entitiesNode);
for (JsonNode node : entitiesNode.findParents(INDEX_START)) {
entities.put(node.get(INDEX_START).intValue(), node);
}
}
if (mediaNode != null) {
validateMedia(mediaNode);
for (JsonNode node : mediaNode.findParents(INDEX)) {
media.put(node.get(INDEX).intValue(), node.get(TEXT));
}
}
// If entity indices are outside the message, pad the message to the necessary length
int lastIndex = Math.max((!entities.isEmpty()) ? entities.lastKey() : 0, (!media.isEmpty()) ? media.lastKey() : 0);
if (message.length() <= lastIndex) {
message = StringUtils.rightPad(message, lastIndex + 1);
}
StringBuilder output = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (entities.containsKey(i)) {
JsonNode entity = entities.get(i);
String entityType = entity.get(TYPE).asText().toUpperCase();
String id = entity.get(ID).asText();
output.append(ENTITY_DELIMITER);
output.append(entityType).append(FIELD_DELIMITER);
output.append(id);
output.append(ENTITY_DELIMITER);
// We explicitly check the entity indices above, but make double sure that we don't get into an infinite loop here
int endIndex = entity.get(INDEX_END).intValue() - 1;
i = Math.max(endIndex, i);
} else if (media.containsKey(i)) {
JsonNode table = media.get(i);
output.append(ENTITY_DELIMITER);
output.append(TABLE).append(FIELD_DELIMITER);
for (JsonNode row : table) {
for (JsonNode cell : row) {
String text = cell.asText();
output.append(text).append(RECORD_DELIMITER);
}
output.append(GROUP_DELIMITER);
}
output.append(ENTITY_DELIMITER);
output.append(c);
} else {
output.append(c);
}
}
return output.toString();
} | [
"private",
"String",
"enrichMarkdown",
"(",
"String",
"message",
",",
"JsonNode",
"entitiesNode",
",",
"JsonNode",
"mediaNode",
")",
"throws",
"InvalidInputException",
"{",
"TreeMap",
"<",
"Integer",
",",
"JsonNode",
">",
"entities",
"=",
"new",
"TreeMap",
"<>",
... | Generate intermediate markup to delimit custom nodes representing entities for further processing by the
Markdown parser. | [
"Generate",
"intermediate",
"markup",
"to",
"delimit",
"custom",
"nodes",
"representing",
"entities",
"for",
"further",
"processing",
"by",
"the",
"Markdown",
"parser",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownParser.java#L282-L346 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownParser.java | MarkdownParser.validateEntities | private void validateEntities(JsonNode data) throws InvalidInputException {
for (JsonNode node : data.findParents(INDEX_START)) {
for (String key : new String[] {INDEX_START, INDEX_END, ID, TYPE}) {
if (node.path(key).isMissingNode()) {
throw new InvalidInputException("Required field \"" + key + "\" missing from the entity payload");
}
}
int startIndex = node.get(INDEX_START).intValue();
int endIndex = node.get(INDEX_END).intValue();
if (endIndex <= startIndex) {
throw new InvalidInputException(String.format("Invalid entity payload: %s (start index: %s, end index: %s)",
node.get(ID).textValue(), startIndex, endIndex));
}
}
} | java | private void validateEntities(JsonNode data) throws InvalidInputException {
for (JsonNode node : data.findParents(INDEX_START)) {
for (String key : new String[] {INDEX_START, INDEX_END, ID, TYPE}) {
if (node.path(key).isMissingNode()) {
throw new InvalidInputException("Required field \"" + key + "\" missing from the entity payload");
}
}
int startIndex = node.get(INDEX_START).intValue();
int endIndex = node.get(INDEX_END).intValue();
if (endIndex <= startIndex) {
throw new InvalidInputException(String.format("Invalid entity payload: %s (start index: %s, end index: %s)",
node.get(ID).textValue(), startIndex, endIndex));
}
}
} | [
"private",
"void",
"validateEntities",
"(",
"JsonNode",
"data",
")",
"throws",
"InvalidInputException",
"{",
"for",
"(",
"JsonNode",
"node",
":",
"data",
".",
"findParents",
"(",
"INDEX_START",
")",
")",
"{",
"for",
"(",
"String",
"key",
":",
"new",
"String"... | Verify that JSON entities contain the required fields and that entity indices are correct. | [
"Verify",
"that",
"JSON",
"entities",
"contain",
"the",
"required",
"fields",
"and",
"that",
"entity",
"indices",
"are",
"correct",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownParser.java#L351-L369 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownParser.java | MarkdownParser.validateMedia | private void validateMedia(JsonNode data) throws InvalidInputException {
for (JsonNode node : data.findParents(INDEX)) {
JsonNode text = node.path(TEXT);
if (!text.isMissingNode() && (!text.isArray() || !text.get(0).isArray())) {
throw new InvalidInputException(String.format("Invalid table payload: %s (index: %s)", text.asText(), node.get(INDEX)));
}
}
} | java | private void validateMedia(JsonNode data) throws InvalidInputException {
for (JsonNode node : data.findParents(INDEX)) {
JsonNode text = node.path(TEXT);
if (!text.isMissingNode() && (!text.isArray() || !text.get(0).isArray())) {
throw new InvalidInputException(String.format("Invalid table payload: %s (index: %s)", text.asText(), node.get(INDEX)));
}
}
} | [
"private",
"void",
"validateMedia",
"(",
"JsonNode",
"data",
")",
"throws",
"InvalidInputException",
"{",
"for",
"(",
"JsonNode",
"node",
":",
"data",
".",
"findParents",
"(",
"INDEX",
")",
")",
"{",
"JsonNode",
"text",
"=",
"node",
".",
"path",
"(",
"TEXT... | Verify that JSON media node contains valid table payload. | [
"Verify",
"that",
"JSON",
"media",
"node",
"contains",
"valid",
"table",
"payload",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownParser.java#L374-L381 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownParser.java | MarkdownParser.parse | public MessageML parse(String message, JsonNode entities, JsonNode media) throws InvalidInputException {
this.index = 0;
message = message.replace((char) 160, (char) 32);
String enriched = enrichMarkdown(message, entities, media);
Node markdown = MARKDOWN_PARSER.parse(enriched);
markdown.accept(this);
return messageML;
} | java | public MessageML parse(String message, JsonNode entities, JsonNode media) throws InvalidInputException {
this.index = 0;
message = message.replace((char) 160, (char) 32);
String enriched = enrichMarkdown(message, entities, media);
Node markdown = MARKDOWN_PARSER.parse(enriched);
markdown.accept(this);
return messageML;
} | [
"public",
"MessageML",
"parse",
"(",
"String",
"message",
",",
"JsonNode",
"entities",
",",
"JsonNode",
"media",
")",
"throws",
"InvalidInputException",
"{",
"this",
".",
"index",
"=",
"0",
";",
"message",
"=",
"message",
".",
"replace",
"(",
"(",
"char",
... | Parse the Markdown message and entity JSON into a MessageML document. | [
"Parse",
"the",
"Markdown",
"message",
"and",
"entity",
"JSON",
"into",
"a",
"MessageML",
"document",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/markdown/MarkdownParser.java#L386-L394 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/AlignedBlock.java | AlignedBlock.align | public void align(Object... o) {
int i = 0;
String s[] = new String[o.length];
for (int ii = 0; ii < o.length; ii++) { if (o[ii] != null) { s[ii] = o[ii].toString(); } }
while (i < s.length && i < maxColumnLength.size()) {
int l = (s[i] == null ? 0 : s[i].length());
if (maxColumnLength.get(i) < l) {
maxColumnLength.set(i, l);
}
i++;
}
while (i < s.length) {
maxColumnLength.add((s[i] == null ? 0 : s[i].length()));
i++;
}
rows.add(s);
} | java | public void align(Object... o) {
int i = 0;
String s[] = new String[o.length];
for (int ii = 0; ii < o.length; ii++) { if (o[ii] != null) { s[ii] = o[ii].toString(); } }
while (i < s.length && i < maxColumnLength.size()) {
int l = (s[i] == null ? 0 : s[i].length());
if (maxColumnLength.get(i) < l) {
maxColumnLength.set(i, l);
}
i++;
}
while (i < s.length) {
maxColumnLength.add((s[i] == null ? 0 : s[i].length()));
i++;
}
rows.add(s);
} | [
"public",
"void",
"align",
"(",
"Object",
"...",
"o",
")",
"{",
"int",
"i",
"=",
"0",
";",
"String",
"s",
"[",
"]",
"=",
"new",
"String",
"[",
"o",
".",
"length",
"]",
";",
"for",
"(",
"int",
"ii",
"=",
"0",
";",
"ii",
"<",
"o",
".",
"lengt... | Add a row to the block, each String represents a piece of text which should be aligned.
@param o Variable number of Strings to align. | [
"Add",
"a",
"row",
"to",
"the",
"block",
"each",
"String",
"represents",
"a",
"piece",
"of",
"text",
"which",
"should",
"be",
"aligned",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/AlignedBlock.java#L46-L68 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/AlignedBlock.java | AlignedBlock.print | public void print(String separator, String terminator) {
for (int i = 0; i < maxColumnLength.size(); i++) {
maxColumnLength.set(i, (((maxColumnLength.get(i) / TAB_SIZE) + 1) * TAB_SIZE));
}
for (int r = 0; r < rows.size(); r++) {
String[] s = rows.get(r);
for (int i = 0; i < s.length; i++) {
out.print(s[i]);
if (i < s.length - 1) {
for (int l = (s[i] == null ? 0 : s[i].length()); l < maxColumnLength.get(i); l++) {
out.print(' ');
}
}
}
if (separator != null && r < rows.size() - 1) { out.println(separator); } else if (terminator != null
&& r == rows.size() - 1) { out.println(terminator); } else { out.println(); }
}
} | java | public void print(String separator, String terminator) {
for (int i = 0; i < maxColumnLength.size(); i++) {
maxColumnLength.set(i, (((maxColumnLength.get(i) / TAB_SIZE) + 1) * TAB_SIZE));
}
for (int r = 0; r < rows.size(); r++) {
String[] s = rows.get(r);
for (int i = 0; i < s.length; i++) {
out.print(s[i]);
if (i < s.length - 1) {
for (int l = (s[i] == null ? 0 : s[i].length()); l < maxColumnLength.get(i); l++) {
out.print(' ');
}
}
}
if (separator != null && r < rows.size() - 1) { out.println(separator); } else if (terminator != null
&& r == rows.size() - 1) { out.println(terminator); } else { out.println(); }
}
} | [
"public",
"void",
"print",
"(",
"String",
"separator",
",",
"String",
"terminator",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"maxColumnLength",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"maxColumnLength",
".",
"set",
"(",
"... | Outputs the block, with the given separator appended to each line except the last, and the given
terminator appended to the last line.
@param separator text added to each line except the last/
@param terminator text added to the last line. | [
"Outputs",
"the",
"block",
"with",
"the",
"given",
"separator",
"appended",
"to",
"each",
"line",
"except",
"the",
"last",
"and",
"the",
"given",
"terminator",
"appended",
"to",
"the",
"last",
"line",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/AlignedBlock.java#L76-L96 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/MessageMLContext.java | MessageMLContext.getPresentationML | public String getPresentationML() throws IllegalStateException {
if (messageML == null) {
throw new IllegalStateException("The message hasn't been parsed yet. "
+ "Please call MessageMLContext.parse() first.");
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
XmlPrintStream out = new XmlPrintStream(bout);
out.setNoIndent(true);
out.setNoNl(true);
messageML.asPresentationML(out);
out.close();
return bout.toString();
} | java | public String getPresentationML() throws IllegalStateException {
if (messageML == null) {
throw new IllegalStateException("The message hasn't been parsed yet. "
+ "Please call MessageMLContext.parse() first.");
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
XmlPrintStream out = new XmlPrintStream(bout);
out.setNoIndent(true);
out.setNoNl(true);
messageML.asPresentationML(out);
out.close();
return bout.toString();
} | [
"public",
"String",
"getPresentationML",
"(",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"messageML",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"The message hasn't been parsed yet. \"",
"+",
"\"Please call MessageMLContext.parse() ... | Retrieve a string representation of the message in PresentationML.
@throws IllegalStateException thrown if the message hasn't been parsed yet | [
"Retrieve",
"a",
"string",
"representation",
"of",
"the",
"message",
"in",
"PresentationML",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/MessageMLContext.java#L106-L123 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/elements/Styles.java | Styles.validate | public static void validate(String styleAttribute) throws InvalidInputException {
try {
final Map<String, String> styleMap = Splitter.on(";").omitEmptyStrings().withKeyValueSeparator(":").split(styleAttribute);
final HashSet<String> inputStyleProperties = new HashSet<>(styleMap.keySet());
inputStyleProperties.removeAll(ALLOWED_PROPERTIES);
if (!inputStyleProperties.isEmpty()) {
throw new InvalidInputException("Invalid property(s): [" + Joiner.on(",").join(inputStyleProperties) + "] in the \"style\" attribute");
}
} catch (IllegalArgumentException ex) {
throw new InvalidInputException("Unparseable \"style\" attribute: " + styleAttribute, ex);
}
} | java | public static void validate(String styleAttribute) throws InvalidInputException {
try {
final Map<String, String> styleMap = Splitter.on(";").omitEmptyStrings().withKeyValueSeparator(":").split(styleAttribute);
final HashSet<String> inputStyleProperties = new HashSet<>(styleMap.keySet());
inputStyleProperties.removeAll(ALLOWED_PROPERTIES);
if (!inputStyleProperties.isEmpty()) {
throw new InvalidInputException("Invalid property(s): [" + Joiner.on(",").join(inputStyleProperties) + "] in the \"style\" attribute");
}
} catch (IllegalArgumentException ex) {
throw new InvalidInputException("Unparseable \"style\" attribute: " + styleAttribute, ex);
}
} | [
"public",
"static",
"void",
"validate",
"(",
"String",
"styleAttribute",
")",
"throws",
"InvalidInputException",
"{",
"try",
"{",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"styleMap",
"=",
"Splitter",
".",
"on",
"(",
"\";\"",
")",
".",
"omitEmptyStr... | Validate that the input style attribute is allowed
@param styleAttribute input style string
@throws InvalidInputException if the styleAttribute is allowed | [
"Validate",
"that",
"the",
"input",
"style",
"attribute",
"is",
"allowed"
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/elements/Styles.java#L135-L146 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java | MessageMLParser.parse | MessageML parse(String message, String entityJson, String version) throws InvalidInputException, ProcessingException,
IOException {
this.index = 0;
String expandedMessage;
if (StringUtils.isBlank(message)) {
throw new InvalidInputException("Error parsing message: the message cannot be null or empty");
}
if (StringUtils.isNotBlank(entityJson)) {
try {
this.entityJson = (ObjectNode) MAPPER.readTree(entityJson);
} catch (JsonProcessingException e) {
throw new InvalidInputException("Error parsing EntityJSON: " + e.getMessage());
}
} else {
this.entityJson = new ObjectNode(JsonNodeFactory.instance);
}
try {
expandedMessage = expandTemplates(message, this.entityJson);
} catch (IOException e) {
throw new InvalidInputException("Error parsing EntityJSON: " + e.getMessage());
} catch (TemplateException e) {
throw new InvalidInputException(String.format("Error parsing Freemarker template: invalid input at line %s, "
+ "column %s", e.getLineNumber(), e.getColumnNumber()));
}
this.messageML = parseMessageML(expandedMessage, version);
if (this.messageML != null) {
this.entityJson = this.messageML.asEntityJson(this.entityJson);
return this.messageML;
}
throw new ProcessingException("Internal error. Generated null MessageML from valid input");
} | java | MessageML parse(String message, String entityJson, String version) throws InvalidInputException, ProcessingException,
IOException {
this.index = 0;
String expandedMessage;
if (StringUtils.isBlank(message)) {
throw new InvalidInputException("Error parsing message: the message cannot be null or empty");
}
if (StringUtils.isNotBlank(entityJson)) {
try {
this.entityJson = (ObjectNode) MAPPER.readTree(entityJson);
} catch (JsonProcessingException e) {
throw new InvalidInputException("Error parsing EntityJSON: " + e.getMessage());
}
} else {
this.entityJson = new ObjectNode(JsonNodeFactory.instance);
}
try {
expandedMessage = expandTemplates(message, this.entityJson);
} catch (IOException e) {
throw new InvalidInputException("Error parsing EntityJSON: " + e.getMessage());
} catch (TemplateException e) {
throw new InvalidInputException(String.format("Error parsing Freemarker template: invalid input at line %s, "
+ "column %s", e.getLineNumber(), e.getColumnNumber()));
}
this.messageML = parseMessageML(expandedMessage, version);
if (this.messageML != null) {
this.entityJson = this.messageML.asEntityJson(this.entityJson);
return this.messageML;
}
throw new ProcessingException("Internal error. Generated null MessageML from valid input");
} | [
"MessageML",
"parse",
"(",
"String",
"message",
",",
"String",
"entityJson",
",",
"String",
"version",
")",
"throws",
"InvalidInputException",
",",
"ProcessingException",
",",
"IOException",
"{",
"this",
".",
"index",
"=",
"0",
";",
"String",
"expandedMessage",
... | Parse the text contents of the message and optionally EntityJSON into a MessageMLV2 message. Expands
Freemarker templates and generates a MessageML document tree.
@param message string containing a MessageMLV2 message with optional Freemarker templates
@param entityJson string containing EntityJSON data
@param version string containing the version of the message format
@throws InvalidInputException thrown on invalid MessageMLV2 input
@throws ProcessingException thrown on errors generating the document tree
@throws IOException thrown on invalid EntityJSON input | [
"Parse",
"the",
"text",
"contents",
"of",
"the",
"message",
"and",
"optionally",
"EntityJSON",
"into",
"a",
"MessageMLV2",
"message",
".",
"Expands",
"Freemarker",
"templates",
"and",
"generates",
"a",
"MessageML",
"document",
"tree",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java#L80-L117 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java | MessageMLParser.validateMessageText | private static void validateMessageText(String messageML) throws InvalidInputException {
if (messageML == null) { throw new InvalidInputException("Message input is NULL"); }
for (char ch : messageML.toCharArray()) {
if (ch != '\n' && ch != '\r' && ch != '\t' && (ch < ' ')) {
throw new InvalidInputException("Invalid control characters in message");
}
}
} | java | private static void validateMessageText(String messageML) throws InvalidInputException {
if (messageML == null) { throw new InvalidInputException("Message input is NULL"); }
for (char ch : messageML.toCharArray()) {
if (ch != '\n' && ch != '\r' && ch != '\t' && (ch < ' ')) {
throw new InvalidInputException("Invalid control characters in message");
}
}
} | [
"private",
"static",
"void",
"validateMessageText",
"(",
"String",
"messageML",
")",
"throws",
"InvalidInputException",
"{",
"if",
"(",
"messageML",
"==",
"null",
")",
"{",
"throw",
"new",
"InvalidInputException",
"(",
"\"Message input is NULL\"",
")",
";",
"}",
"... | Check the input message text for null value and restricted characters. | [
"Check",
"the",
"input",
"message",
"text",
"for",
"null",
"value",
"and",
"restricted",
"characters",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java#L129-L137 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java | MessageMLParser.expandTemplates | private String expandTemplates(String message, JsonNode entityJson) throws IOException, TemplateException {
// Read entityJSON data
Map<String, Object> data = new HashMap<>();
data.put("data", MAPPER.convertValue(entityJson, Map.class));
data.put("entity", MAPPER.convertValue(entityJson, Map.class));
// Read MessageMLV2 template
StringWriter sw = new StringWriter();
Template template = new Template("messageML", message, FREEMARKER);
// Expand the template
template.process(data, sw);
return sw.toString();
} | java | private String expandTemplates(String message, JsonNode entityJson) throws IOException, TemplateException {
// Read entityJSON data
Map<String, Object> data = new HashMap<>();
data.put("data", MAPPER.convertValue(entityJson, Map.class));
data.put("entity", MAPPER.convertValue(entityJson, Map.class));
// Read MessageMLV2 template
StringWriter sw = new StringWriter();
Template template = new Template("messageML", message, FREEMARKER);
// Expand the template
template.process(data, sw);
return sw.toString();
} | [
"private",
"String",
"expandTemplates",
"(",
"String",
"message",
",",
"JsonNode",
"entityJson",
")",
"throws",
"IOException",
",",
"TemplateException",
"{",
"// Read entityJSON data",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
"=",
"new",
"HashMap",
"<>",
... | Expand Freemarker templates. | [
"Expand",
"Freemarker",
"templates",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java#L182-L196 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java | MessageMLParser.parseMessageML | private MessageML parseMessageML(String messageML, String version) throws InvalidInputException, ProcessingException {
validateMessageText(messageML);
org.w3c.dom.Element docElement = parseDocument(messageML);
validateEntities(docElement, entityJson);
switch (docElement.getTagName()) {
case MessageML.MESSAGEML_TAG:
this.messageFormat = FormatEnum.MESSAGEML;
if (StringUtils.isBlank(version)) {
version = MessageML.MESSAGEML_VERSION;
}
break;
case MessageML.PRESENTATIONML_TAG:
this.messageFormat = FormatEnum.PRESENTATIONML;
break;
default:
throw new InvalidInputException("Root tag must be <" + MessageML.MESSAGEML_TAG + ">"
+ " or <" + MessageML.PRESENTATIONML_TAG + ">");
}
MessageML result = new MessageML(messageFormat, version);
result.buildAll(this, docElement);
result.validate();
return result;
} | java | private MessageML parseMessageML(String messageML, String version) throws InvalidInputException, ProcessingException {
validateMessageText(messageML);
org.w3c.dom.Element docElement = parseDocument(messageML);
validateEntities(docElement, entityJson);
switch (docElement.getTagName()) {
case MessageML.MESSAGEML_TAG:
this.messageFormat = FormatEnum.MESSAGEML;
if (StringUtils.isBlank(version)) {
version = MessageML.MESSAGEML_VERSION;
}
break;
case MessageML.PRESENTATIONML_TAG:
this.messageFormat = FormatEnum.PRESENTATIONML;
break;
default:
throw new InvalidInputException("Root tag must be <" + MessageML.MESSAGEML_TAG + ">"
+ " or <" + MessageML.PRESENTATIONML_TAG + ">");
}
MessageML result = new MessageML(messageFormat, version);
result.buildAll(this, docElement);
result.validate();
return result;
} | [
"private",
"MessageML",
"parseMessageML",
"(",
"String",
"messageML",
",",
"String",
"version",
")",
"throws",
"InvalidInputException",
",",
"ProcessingException",
"{",
"validateMessageText",
"(",
"messageML",
")",
";",
"org",
".",
"w3c",
".",
"dom",
".",
"Element... | Parse the message string into its MessageML representation. | [
"Parse",
"the",
"message",
"string",
"into",
"its",
"MessageML",
"representation",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java#L201-L230 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java | MessageMLParser.parseDocument | org.w3c.dom.Element parseDocument(String messageML) throws InvalidInputException, ProcessingException {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
//XXE prevention as per https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
dbFactory.setXIncludeAware(false);
dbFactory.setExpandEntityReferences(false);
dbFactory.setIgnoringElementContentWhitespace(true);
dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
dBuilder.setErrorHandler(new NullErrorHandler()); // default handler prints to stderr
dBuilder.setEntityResolver(new NoOpEntityResolver());
StringReader sr = new StringReader(messageML);
ReaderInputStream ris = new ReaderInputStream(sr);
Document doc = dBuilder.parse(ris);
doc.getDocumentElement().normalize();
return doc.getDocumentElement();
} catch (SAXException e) {
throw new InvalidInputException("Invalid messageML: " + e.getMessage(), e);
} catch (ParserConfigurationException | IOException e) {
throw new ProcessingException("Failed to parse messageML", e);
}
} | java | org.w3c.dom.Element parseDocument(String messageML) throws InvalidInputException, ProcessingException {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
//XXE prevention as per https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
dbFactory.setXIncludeAware(false);
dbFactory.setExpandEntityReferences(false);
dbFactory.setIgnoringElementContentWhitespace(true);
dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
dBuilder.setErrorHandler(new NullErrorHandler()); // default handler prints to stderr
dBuilder.setEntityResolver(new NoOpEntityResolver());
StringReader sr = new StringReader(messageML);
ReaderInputStream ris = new ReaderInputStream(sr);
Document doc = dBuilder.parse(ris);
doc.getDocumentElement().normalize();
return doc.getDocumentElement();
} catch (SAXException e) {
throw new InvalidInputException("Invalid messageML: " + e.getMessage(), e);
} catch (ParserConfigurationException | IOException e) {
throw new ProcessingException("Failed to parse messageML", e);
}
} | [
"org",
".",
"w3c",
".",
"dom",
".",
"Element",
"parseDocument",
"(",
"String",
"messageML",
")",
"throws",
"InvalidInputException",
",",
"ProcessingException",
"{",
"try",
"{",
"DocumentBuilderFactory",
"dbFactory",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
... | Parse the message string into a DOM element tree. | [
"Parse",
"the",
"message",
"string",
"into",
"a",
"DOM",
"element",
"tree",
"."
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java#L235-L262 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java | IndentedPrintStream.align | public void align(Object... s) {
if (alignedBlock == null) {
alignedBlock = new AlignedBlock(this);
}
alignedBlock.align(s);
} | java | public void align(Object... s) {
if (alignedBlock == null) {
alignedBlock = new AlignedBlock(this);
}
alignedBlock.align(s);
} | [
"public",
"void",
"align",
"(",
"Object",
"...",
"s",
")",
"{",
"if",
"(",
"alignedBlock",
"==",
"null",
")",
"{",
"alignedBlock",
"=",
"new",
"AlignedBlock",
"(",
"this",
")",
";",
"}",
"alignedBlock",
".",
"align",
"(",
"s",
")",
";",
"}"
] | Takes an array of strings to be aligned in separate columns, and adds them to the alignedblock | [
"Takes",
"an",
"array",
"of",
"strings",
"to",
"be",
"aligned",
"in",
"separate",
"columns",
"and",
"adds",
"them",
"to",
"the",
"alignedblock"
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java#L64-L69 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java | IndentedPrintStream.printAlignedBlock | private void printAlignedBlock(String separator, String terminator) {
if (alignedBlock != null) {
alignedBlock.print(separator, terminator);
alignedBlock = null;
}
} | java | private void printAlignedBlock(String separator, String terminator) {
if (alignedBlock != null) {
alignedBlock.print(separator, terminator);
alignedBlock = null;
}
} | [
"private",
"void",
"printAlignedBlock",
"(",
"String",
"separator",
",",
"String",
"terminator",
")",
"{",
"if",
"(",
"alignedBlock",
"!=",
"null",
")",
"{",
"alignedBlock",
".",
"print",
"(",
"separator",
",",
"terminator",
")",
";",
"alignedBlock",
"=",
"n... | Prints the alignedblock, with all strings aligned in columns dependent on the order in which they were declared in Align
@param separator text added to the end of each line except the last line
@param terminator text added to the end of the last line of the block | [
"Prints",
"the",
"alignedblock",
"with",
"all",
"strings",
"aligned",
"in",
"columns",
"dependent",
"on",
"the",
"order",
"in",
"which",
"they",
"were",
"declared",
"in",
"Align"
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java#L76-L81 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java | IndentedPrintStream.println | public void println(int tempIndent, char x) {
if (startOfLine) {
doIndent(tempIndent);
}
super.println(x);
startOfLine = true;
} | java | public void println(int tempIndent, char x) {
if (startOfLine) {
doIndent(tempIndent);
}
super.println(x);
startOfLine = true;
} | [
"public",
"void",
"println",
"(",
"int",
"tempIndent",
",",
"char",
"x",
")",
"{",
"if",
"(",
"startOfLine",
")",
"{",
"doIndent",
"(",
"tempIndent",
")",
";",
"}",
"super",
".",
"println",
"(",
"x",
")",
";",
"startOfLine",
"=",
"true",
";",
"}"
] | Indent the current line and print a character on the same line,
then print a line break
@param tempIndent magnitude of the indent (number of tab spaces)
@param x character to be printed | [
"Indent",
"the",
"current",
"line",
"and",
"print",
"a",
"character",
"on",
"the",
"same",
"line",
"then",
"print",
"a",
"line",
"break"
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java#L302-L308 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java | IndentedPrintStream.println | public void println(int tempIndent, String x) {
if (startOfLine) {
doIndent(tempIndent);
}
if (noNl) {
super.print(x);
} else {
super.println(x);
if (oNlCr) { super.write('\r'); }
}
startOfLine = true;
} | java | public void println(int tempIndent, String x) {
if (startOfLine) {
doIndent(tempIndent);
}
if (noNl) {
super.print(x);
} else {
super.println(x);
if (oNlCr) { super.write('\r'); }
}
startOfLine = true;
} | [
"public",
"void",
"println",
"(",
"int",
"tempIndent",
",",
"String",
"x",
")",
"{",
"if",
"(",
"startOfLine",
")",
"{",
"doIndent",
"(",
"tempIndent",
")",
";",
"}",
"if",
"(",
"noNl",
")",
"{",
"super",
".",
"print",
"(",
"x",
")",
";",
"}",
"e... | Indent the current line and print a string on the same line,
then print a line break
@param tempIndent magnitude of the indent (number of tab spaces)
@param x string to be printed | [
"Indent",
"the",
"current",
"line",
"and",
"print",
"a",
"string",
"on",
"the",
"same",
"line",
"then",
"print",
"a",
"line",
"break"
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java#L370-L382 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java | IndentedPrintStream.print | public void print(String pattern, Object... arguments) {
print(String.format(pattern, arguments));
} | java | public void print(String pattern, Object... arguments) {
print(String.format(pattern, arguments));
} | [
"public",
"void",
"print",
"(",
"String",
"pattern",
",",
"Object",
"...",
"arguments",
")",
"{",
"print",
"(",
"String",
".",
"format",
"(",
"pattern",
",",
"arguments",
")",
")",
";",
"}"
] | Convenience method for calling string.format and printing | [
"Convenience",
"method",
"for",
"calling",
"string",
".",
"format",
"and",
"printing"
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java#L577-L579 | train |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java | IndentedPrintStream.println | public void println(String pattern, Object... arguments) {
println(String.format(pattern, arguments));
} | java | public void println(String pattern, Object... arguments) {
println(String.format(pattern, arguments));
} | [
"public",
"void",
"println",
"(",
"String",
"pattern",
",",
"Object",
"...",
"arguments",
")",
"{",
"println",
"(",
"String",
".",
"format",
"(",
"pattern",
",",
"arguments",
")",
")",
";",
"}"
] | Convenience method for calling string.format and printing
with line breaks | [
"Convenience",
"method",
"for",
"calling",
"string",
".",
"format",
"and",
"printing",
"with",
"line",
"breaks"
] | 68daed66267062d144a05b3ee9a9bf4b715e3f95 | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/util/IndentedPrintStream.java#L585-L587 | train |
irmen/Serpent | java/src/main/java/net/razorvine/serpent/SeekableStringReader.java | SeekableStringReader.peek | public String peek(int count)
{
return str.substring(cursor, cursor+Math.min(count, str.length()-cursor));
} | java | public String peek(int count)
{
return str.substring(cursor, cursor+Math.min(count, str.length()-cursor));
} | [
"public",
"String",
"peek",
"(",
"int",
"count",
")",
"{",
"return",
"str",
".",
"substring",
"(",
"cursor",
",",
"cursor",
"+",
"Math",
".",
"min",
"(",
"count",
",",
"str",
".",
"length",
"(",
")",
"-",
"cursor",
")",
")",
";",
"}"
] | What are the next characters that will be read? | [
"What",
"are",
"the",
"next",
"characters",
"that",
"will",
"be",
"read?"
] | 763a6e15f75c4d5937cd16dfc70b0930a442b541 | https://github.com/irmen/Serpent/blob/763a6e15f75c4d5937cd16dfc70b0930a442b541/java/src/main/java/net/razorvine/serpent/SeekableStringReader.java#L58-L61 | train |
irmen/Serpent | java/src/main/java/net/razorvine/serpent/SeekableStringReader.java | SeekableStringReader.read | public String read(int count)
{
if(count<0)
throw new ParseException("use Rewind to seek back");
int safecount = Math.min(count, str.length()-cursor);
if(safecount==0 && count>0)
throw new ParseException("no more data");
String result = str.substring(cursor, cursor+safecount);
cursor += safecount;
return result;
} | java | public String read(int count)
{
if(count<0)
throw new ParseException("use Rewind to seek back");
int safecount = Math.min(count, str.length()-cursor);
if(safecount==0 && count>0)
throw new ParseException("no more data");
String result = str.substring(cursor, cursor+safecount);
cursor += safecount;
return result;
} | [
"public",
"String",
"read",
"(",
"int",
"count",
")",
"{",
"if",
"(",
"count",
"<",
"0",
")",
"throw",
"new",
"ParseException",
"(",
"\"use Rewind to seek back\"",
")",
";",
"int",
"safecount",
"=",
"Math",
".",
"min",
"(",
"count",
",",
"str",
".",
"l... | Read a number of characters. | [
"Read",
"a",
"number",
"of",
"characters",
"."
] | 763a6e15f75c4d5937cd16dfc70b0930a442b541 | https://github.com/irmen/Serpent/blob/763a6e15f75c4d5937cd16dfc70b0930a442b541/java/src/main/java/net/razorvine/serpent/SeekableStringReader.java#L74-L85 | train |
irmen/Serpent | java/src/main/java/net/razorvine/serpent/SeekableStringReader.java | SeekableStringReader.readUntil | public String readUntil(char sentinel)
{
int i = str.indexOf(sentinel, cursor);
if(i>=0) {
int from = cursor;
cursor = i+1;
return str.substring(from, i);
}
throw new ParseException("terminator not found");
} | java | public String readUntil(char sentinel)
{
int i = str.indexOf(sentinel, cursor);
if(i>=0) {
int from = cursor;
cursor = i+1;
return str.substring(from, i);
}
throw new ParseException("terminator not found");
} | [
"public",
"String",
"readUntil",
"(",
"char",
"sentinel",
")",
"{",
"int",
"i",
"=",
"str",
".",
"indexOf",
"(",
"sentinel",
",",
"cursor",
")",
";",
"if",
"(",
"i",
">=",
"0",
")",
"{",
"int",
"from",
"=",
"cursor",
";",
"cursor",
"=",
"i",
"+",... | Read everything until one the sentinel, which must exist in the string.
Sentinel char is read but not returned in the result. | [
"Read",
"everything",
"until",
"one",
"the",
"sentinel",
"which",
"must",
"exist",
"in",
"the",
"string",
".",
"Sentinel",
"char",
"is",
"read",
"but",
"not",
"returned",
"in",
"the",
"result",
"."
] | 763a6e15f75c4d5937cd16dfc70b0930a442b541 | https://github.com/irmen/Serpent/blob/763a6e15f75c4d5937cd16dfc70b0930a442b541/java/src/main/java/net/razorvine/serpent/SeekableStringReader.java#L91-L100 | train |
irmen/Serpent | java/src/main/java/net/razorvine/serpent/SeekableStringReader.java | SeekableStringReader.readWhile | public String readWhile(String accepted)
{
int start = cursor;
while(cursor < str.length())
{
if(accepted.indexOf(str.charAt(cursor))>=0)
++cursor;
else
break;
}
return str.substring(start, cursor);
} | java | public String readWhile(String accepted)
{
int start = cursor;
while(cursor < str.length())
{
if(accepted.indexOf(str.charAt(cursor))>=0)
++cursor;
else
break;
}
return str.substring(start, cursor);
} | [
"public",
"String",
"readWhile",
"(",
"String",
"accepted",
")",
"{",
"int",
"start",
"=",
"cursor",
";",
"while",
"(",
"cursor",
"<",
"str",
".",
"length",
"(",
")",
")",
"{",
"if",
"(",
"accepted",
".",
"indexOf",
"(",
"str",
".",
"charAt",
"(",
... | Read everything as long as the char occurs in the accepted characters. | [
"Read",
"everything",
"as",
"long",
"as",
"the",
"char",
"occurs",
"in",
"the",
"accepted",
"characters",
"."
] | 763a6e15f75c4d5937cd16dfc70b0930a442b541 | https://github.com/irmen/Serpent/blob/763a6e15f75c4d5937cd16dfc70b0930a442b541/java/src/main/java/net/razorvine/serpent/SeekableStringReader.java#L128-L139 | train |
irmen/Serpent | java/src/main/java/net/razorvine/serpent/SeekableStringReader.java | SeekableStringReader.rest | public String rest()
{
if(cursor>=str.length())
throw new ParseException("no more data");
String result=str.substring(cursor);
cursor = str.length();
return result;
} | java | public String rest()
{
if(cursor>=str.length())
throw new ParseException("no more data");
String result=str.substring(cursor);
cursor = str.length();
return result;
} | [
"public",
"String",
"rest",
"(",
")",
"{",
"if",
"(",
"cursor",
">=",
"str",
".",
"length",
"(",
")",
")",
"throw",
"new",
"ParseException",
"(",
"\"no more data\"",
")",
";",
"String",
"result",
"=",
"str",
".",
"substring",
"(",
"cursor",
")",
";",
... | Returns the rest of the data until the end. | [
"Returns",
"the",
"rest",
"of",
"the",
"data",
"until",
"the",
"end",
"."
] | 763a6e15f75c4d5937cd16dfc70b0930a442b541 | https://github.com/irmen/Serpent/blob/763a6e15f75c4d5937cd16dfc70b0930a442b541/java/src/main/java/net/razorvine/serpent/SeekableStringReader.java#L166-L173 | train |
irmen/Serpent | java/src/main/java/net/razorvine/serpent/ast/Ast.java | Ast.getData | public Object getData(IDictToInstance dictConverter)
{
ObjectifyVisitor v = new ObjectifyVisitor(dictConverter);
this.accept(v);
return v.getObject();
} | java | public Object getData(IDictToInstance dictConverter)
{
ObjectifyVisitor v = new ObjectifyVisitor(dictConverter);
this.accept(v);
return v.getObject();
} | [
"public",
"Object",
"getData",
"(",
"IDictToInstance",
"dictConverter",
")",
"{",
"ObjectifyVisitor",
"v",
"=",
"new",
"ObjectifyVisitor",
"(",
"dictConverter",
")",
";",
"this",
".",
"accept",
"(",
"v",
")",
";",
"return",
"v",
".",
"getObject",
"(",
")",
... | get the actual data as Java objects.
@param dictConverter object to convert dicts to actual instances for a class,
instead of leaving them as dictionaries. Requires the __class__ key to be present
in the dict node. If it returns null, the normal processing is done. | [
"get",
"the",
"actual",
"data",
"as",
"Java",
"objects",
"."
] | 763a6e15f75c4d5937cd16dfc70b0930a442b541 | https://github.com/irmen/Serpent/blob/763a6e15f75c4d5937cd16dfc70b0930a442b541/java/src/main/java/net/razorvine/serpent/ast/Ast.java#L42-L47 | train |
irmen/Serpent | java/src/main/java/net/razorvine/serpent/Parser.java | Parser.parse | public Ast parse(String expression)
{
Ast ast=new Ast();
if(expression==null || expression.length()==0)
return ast;
SeekableStringReader sr = new SeekableStringReader(expression);
if(sr.peek()=='#')
sr.readUntil('\n'); // skip comment line
try {
ast.root = parseExpr(sr);
sr.skipWhitespace();
if(sr.hasMore())
throw new ParseException("garbage at end of expression");
return ast;
} catch (ParseException x) {
String faultLocation = extractFaultLocation(sr);
throw new ParseException(x.getMessage() + " (at position "+sr.bookmark()+"; '"+faultLocation+"')", x);
}
} | java | public Ast parse(String expression)
{
Ast ast=new Ast();
if(expression==null || expression.length()==0)
return ast;
SeekableStringReader sr = new SeekableStringReader(expression);
if(sr.peek()=='#')
sr.readUntil('\n'); // skip comment line
try {
ast.root = parseExpr(sr);
sr.skipWhitespace();
if(sr.hasMore())
throw new ParseException("garbage at end of expression");
return ast;
} catch (ParseException x) {
String faultLocation = extractFaultLocation(sr);
throw new ParseException(x.getMessage() + " (at position "+sr.bookmark()+"; '"+faultLocation+"')", x);
}
} | [
"public",
"Ast",
"parse",
"(",
"String",
"expression",
")",
"{",
"Ast",
"ast",
"=",
"new",
"Ast",
"(",
")",
";",
"if",
"(",
"expression",
"==",
"null",
"||",
"expression",
".",
"length",
"(",
")",
"==",
"0",
")",
"return",
"ast",
";",
"SeekableString... | Parse from a string with the Python literal expression | [
"Parse",
"from",
"a",
"string",
"with",
"the",
"Python",
"literal",
"expression"
] | 763a6e15f75c4d5937cd16dfc70b0930a442b541 | https://github.com/irmen/Serpent/blob/763a6e15f75c4d5937cd16dfc70b0930a442b541/java/src/main/java/net/razorvine/serpent/Parser.java#L43-L63 | train |
XiaoMi/galaxy-fds-sdk-java | src/main/java/com/xiaomi/infra/galaxy/fds/client/GalaxyFDSClient.java | GalaxyFDSClient.getObject | @Override
public FDSObject getObject(String bucketName, String objectName, long pos)
throws GalaxyFDSClientException {
return this.getObject(bucketName, objectName, null, pos);
} | java | @Override
public FDSObject getObject(String bucketName, String objectName, long pos)
throws GalaxyFDSClientException {
return this.getObject(bucketName, objectName, null, pos);
} | [
"@",
"Override",
"public",
"FDSObject",
"getObject",
"(",
"String",
"bucketName",
",",
"String",
"objectName",
",",
"long",
"pos",
")",
"throws",
"GalaxyFDSClientException",
"{",
"return",
"this",
".",
"getObject",
"(",
"bucketName",
",",
"objectName",
",",
"nul... | range mode for getobject while not be autoReConnection
@param bucketName The name of the bucket where the object stores
@param objectName The name of the object to get
@param pos The position to start read
@return
@throws GalaxyFDSClientException | [
"range",
"mode",
"for",
"getobject",
"while",
"not",
"be",
"autoReConnection"
] | 5e93bc2b574dfa51e47451a0efa80c018ff2c48f | https://github.com/XiaoMi/galaxy-fds-sdk-java/blob/5e93bc2b574dfa51e47451a0efa80c018ff2c48f/src/main/java/com/xiaomi/infra/galaxy/fds/client/GalaxyFDSClient.java#L1177-L1181 | train |
XiaoMi/galaxy-fds-sdk-java | src/main/java/com/xiaomi/infra/galaxy/fds/client/GalaxyFDSClient.java | GalaxyFDSClient.putClientMetrics | public void putClientMetrics(ClientMetrics clientMetrics)
throws GalaxyFDSClientException {
URI uri = formatUri(fdsConfig.getBaseUri(), "", (SubResource[]) null);
ContentType contentType = ContentType.APPLICATION_JSON;
HashMap<String, String> params = new HashMap<String, String>();
params.put("clientMetrics", "");
HttpEntity requestEntity = getJsonStringEntity(clientMetrics, contentType);
HttpUriRequest httpRequest = prepareRequestMethod(uri, HttpMethod.PUT,
contentType, null, params, null, requestEntity);
HttpResponse response = executeHttpRequest(httpRequest, Action.PutClientMetrics);
processResponse(response, null, "put client metrics");
} | java | public void putClientMetrics(ClientMetrics clientMetrics)
throws GalaxyFDSClientException {
URI uri = formatUri(fdsConfig.getBaseUri(), "", (SubResource[]) null);
ContentType contentType = ContentType.APPLICATION_JSON;
HashMap<String, String> params = new HashMap<String, String>();
params.put("clientMetrics", "");
HttpEntity requestEntity = getJsonStringEntity(clientMetrics, contentType);
HttpUriRequest httpRequest = prepareRequestMethod(uri, HttpMethod.PUT,
contentType, null, params, null, requestEntity);
HttpResponse response = executeHttpRequest(httpRequest, Action.PutClientMetrics);
processResponse(response, null, "put client metrics");
} | [
"public",
"void",
"putClientMetrics",
"(",
"ClientMetrics",
"clientMetrics",
")",
"throws",
"GalaxyFDSClientException",
"{",
"URI",
"uri",
"=",
"formatUri",
"(",
"fdsConfig",
".",
"getBaseUri",
"(",
")",
",",
"\"\"",
",",
"(",
"SubResource",
"[",
"]",
")",
"nu... | Put client metrics to server. This method should only be used internally.
@param clientMetrics Metrics to be pushed to server.
@throws GalaxyFDSClientException | [
"Put",
"client",
"metrics",
"to",
"server",
".",
"This",
"method",
"should",
"only",
"be",
"used",
"internally",
"."
] | 5e93bc2b574dfa51e47451a0efa80c018ff2c48f | https://github.com/XiaoMi/galaxy-fds-sdk-java/blob/5e93bc2b574dfa51e47451a0efa80c018ff2c48f/src/main/java/com/xiaomi/infra/galaxy/fds/client/GalaxyFDSClient.java#L2289-L2302 | train |
XiaoMi/galaxy-fds-sdk-java | src/main/java/com/xiaomi/infra/galaxy/fds/client/model/FDSPutObjectRequest.java | FDSPutObjectRequest.setInputStream | public void setInputStream(InputStream inputStream, long inputStreamLength) {
// close last file when set a new inputStream
if (this.isUploadFile){
try{
this.inputStream.close();
}
catch (Exception e){
}
}
if (inputStream instanceof FDSProgressInputStream){
this.inputStream = (FDSProgressInputStream) inputStream;
}
else {
this.inputStream = new FDSProgressInputStream(inputStream, this.progressListener);
}
if (this.progressListener != null){
this.progressListener.setTransferred(0);
this.progressListener.setTotal(inputStreamLength);
}
this.isUploadFile = false;
this.inputStreamLength = inputStreamLength;
} | java | public void setInputStream(InputStream inputStream, long inputStreamLength) {
// close last file when set a new inputStream
if (this.isUploadFile){
try{
this.inputStream.close();
}
catch (Exception e){
}
}
if (inputStream instanceof FDSProgressInputStream){
this.inputStream = (FDSProgressInputStream) inputStream;
}
else {
this.inputStream = new FDSProgressInputStream(inputStream, this.progressListener);
}
if (this.progressListener != null){
this.progressListener.setTransferred(0);
this.progressListener.setTotal(inputStreamLength);
}
this.isUploadFile = false;
this.inputStreamLength = inputStreamLength;
} | [
"public",
"void",
"setInputStream",
"(",
"InputStream",
"inputStream",
",",
"long",
"inputStreamLength",
")",
"{",
"// close last file when set a new inputStream",
"if",
"(",
"this",
".",
"isUploadFile",
")",
"{",
"try",
"{",
"this",
".",
"inputStream",
".",
"close"... | Auto convert inputStream to FDSProgressInputStream in order to invoke progress listener
@param inputStream
@param inputStreamLength the length of inputStream, set -1 if the length is uncertain | [
"Auto",
"convert",
"inputStream",
"to",
"FDSProgressInputStream",
"in",
"order",
"to",
"invoke",
"progress",
"listener"
] | 5e93bc2b574dfa51e47451a0efa80c018ff2c48f | https://github.com/XiaoMi/galaxy-fds-sdk-java/blob/5e93bc2b574dfa51e47451a0efa80c018ff2c48f/src/main/java/com/xiaomi/infra/galaxy/fds/client/model/FDSPutObjectRequest.java#L117-L139 | train |
XiaoMi/galaxy-fds-sdk-java | src/main/java/com/xiaomi/infra/galaxy/fds/client/model/FDSPutObjectRequest.java | FDSPutObjectRequest.setFile | public void setFile(File file) throws FileNotFoundException{
this.setInputStream(new BufferedInputStream(new FileInputStream(file)), file.length());
this.isUploadFile = true;
} | java | public void setFile(File file) throws FileNotFoundException{
this.setInputStream(new BufferedInputStream(new FileInputStream(file)), file.length());
this.isUploadFile = true;
} | [
"public",
"void",
"setFile",
"(",
"File",
"file",
")",
"throws",
"FileNotFoundException",
"{",
"this",
".",
"setInputStream",
"(",
"new",
"BufferedInputStream",
"(",
"new",
"FileInputStream",
"(",
"file",
")",
")",
",",
"file",
".",
"length",
"(",
")",
")",
... | Upload file as inputStream
@param file
@throws FileNotFoundException | [
"Upload",
"file",
"as",
"inputStream"
] | 5e93bc2b574dfa51e47451a0efa80c018ff2c48f | https://github.com/XiaoMi/galaxy-fds-sdk-java/blob/5e93bc2b574dfa51e47451a0efa80c018ff2c48f/src/main/java/com/xiaomi/infra/galaxy/fds/client/model/FDSPutObjectRequest.java#L151-L154 | train |
uber/rides-java-sdk | samples/servlet-sample/src/main/java/com/uber/sdk/rides/samples/servlet/SampleServlet.java | SampleServlet.service | @Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
SessionConfiguration config = Server.createSessionConfiguration();
if (oAuth2Credentials == null) {
oAuth2Credentials = Server.createOAuth2Credentials(config);
}
// Load the user from their user ID (derived from the request).
HttpSession httpSession = req.getSession(true);
if (httpSession.getAttribute(Server.USER_SESSION_ID) == null) {
httpSession.setAttribute(Server.USER_SESSION_ID, new Random().nextLong());
}
credential = oAuth2Credentials.loadCredential(httpSession.getAttribute(Server.USER_SESSION_ID).toString());
if (credential != null && credential.getAccessToken() != null) {
if (uberRidesService == null) {
CredentialsSession session = new CredentialsSession(config, credential);
// Set up the Uber API Service once the user is authenticated.
UberRidesApi api = UberRidesApi.with(session).build();
uberRidesService = api.createService();
}
super.service(req, resp);
} else {
resp.sendRedirect(oAuth2Credentials.getAuthorizationUrl());
}
} | java | @Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
SessionConfiguration config = Server.createSessionConfiguration();
if (oAuth2Credentials == null) {
oAuth2Credentials = Server.createOAuth2Credentials(config);
}
// Load the user from their user ID (derived from the request).
HttpSession httpSession = req.getSession(true);
if (httpSession.getAttribute(Server.USER_SESSION_ID) == null) {
httpSession.setAttribute(Server.USER_SESSION_ID, new Random().nextLong());
}
credential = oAuth2Credentials.loadCredential(httpSession.getAttribute(Server.USER_SESSION_ID).toString());
if (credential != null && credential.getAccessToken() != null) {
if (uberRidesService == null) {
CredentialsSession session = new CredentialsSession(config, credential);
// Set up the Uber API Service once the user is authenticated.
UberRidesApi api = UberRidesApi.with(session).build();
uberRidesService = api.createService();
}
super.service(req, resp);
} else {
resp.sendRedirect(oAuth2Credentials.getAuthorizationUrl());
}
} | [
"@",
"Override",
"protected",
"void",
"service",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"SessionConfiguration",
"config",
"=",
"Server",
".",
"createSessionConfiguration",
"(",
... | Before each request, fetch an OAuth2 credential for the user or redirect them to the
OAuth2 login page instead. | [
"Before",
"each",
"request",
"fetch",
"an",
"OAuth2",
"credential",
"for",
"the",
"user",
"or",
"redirect",
"them",
"to",
"the",
"OAuth2",
"login",
"page",
"instead",
"."
] | 6c75570ab7884f8ecafaad312ef471dd33f64c42 | https://github.com/uber/rides-java-sdk/blob/6c75570ab7884f8ecafaad312ef471dd33f64c42/samples/servlet-sample/src/main/java/com/uber/sdk/rides/samples/servlet/SampleServlet.java#L66-L95 | train |
uber/rides-java-sdk | samples/cmdline-sample/src/main/java/com/uber/sdk/rides/samples/cmdline/GetUserProfile.java | GetUserProfile.authenticate | private static Credential authenticate(String userId, SessionConfiguration config) throws Exception {
OAuth2Credentials oAuth2Credentials = createOAuth2Credentials(config);
// First try to load an existing Credential. If that credential is null, authenticate the user.
Credential credential = oAuth2Credentials.loadCredential(userId);
if (credential == null || credential.getAccessToken() == null) {
// Send user to authorize your application.
System.out.printf("Add the following redirect URI to your developer.uber.com application: %s%n",
oAuth2Credentials.getRedirectUri());
System.out.println("Press Enter when done.");
System.in.read();
// Generate an authorization URL.
String authorizationUrl = oAuth2Credentials.getAuthorizationUrl();
System.out.printf("In your browser, navigate to: %s%n", authorizationUrl);
System.out.println("Waiting for authentication...");
// Wait for the authorization code.
String authorizationCode = localServerReceiver.waitForCode();
System.out.println("Authentication received.");
// Authenticate the user with the authorization code.
credential = oAuth2Credentials.authenticate(authorizationCode, userId);
}
localServerReceiver.stop();
return credential;
} | java | private static Credential authenticate(String userId, SessionConfiguration config) throws Exception {
OAuth2Credentials oAuth2Credentials = createOAuth2Credentials(config);
// First try to load an existing Credential. If that credential is null, authenticate the user.
Credential credential = oAuth2Credentials.loadCredential(userId);
if (credential == null || credential.getAccessToken() == null) {
// Send user to authorize your application.
System.out.printf("Add the following redirect URI to your developer.uber.com application: %s%n",
oAuth2Credentials.getRedirectUri());
System.out.println("Press Enter when done.");
System.in.read();
// Generate an authorization URL.
String authorizationUrl = oAuth2Credentials.getAuthorizationUrl();
System.out.printf("In your browser, navigate to: %s%n", authorizationUrl);
System.out.println("Waiting for authentication...");
// Wait for the authorization code.
String authorizationCode = localServerReceiver.waitForCode();
System.out.println("Authentication received.");
// Authenticate the user with the authorization code.
credential = oAuth2Credentials.authenticate(authorizationCode, userId);
}
localServerReceiver.stop();
return credential;
} | [
"private",
"static",
"Credential",
"authenticate",
"(",
"String",
"userId",
",",
"SessionConfiguration",
"config",
")",
"throws",
"Exception",
"{",
"OAuth2Credentials",
"oAuth2Credentials",
"=",
"createOAuth2Credentials",
"(",
"config",
")",
";",
"// First try to load an ... | Authenticate the given user. If you are distributing an installed application, this method
should exist on your server so that the client ID and secret are not shared with the end
user. | [
"Authenticate",
"the",
"given",
"user",
".",
"If",
"you",
"are",
"distributing",
"an",
"installed",
"application",
"this",
"method",
"should",
"exist",
"on",
"your",
"server",
"so",
"that",
"the",
"client",
"ID",
"and",
"secret",
"are",
"not",
"shared",
"wit... | 6c75570ab7884f8ecafaad312ef471dd33f64c42 | https://github.com/uber/rides-java-sdk/blob/6c75570ab7884f8ecafaad312ef471dd33f64c42/samples/cmdline-sample/src/main/java/com/uber/sdk/rides/samples/cmdline/GetUserProfile.java#L90-L118 | train |
uber/rides-java-sdk | uber-core-oauth-client-adapter/src/main/java/com/uber/sdk/core/auth/OAuth2Credentials.java | OAuth2Credentials.getAuthorizationUrl | @Nullable
public String getAuthorizationUrl() throws UnsupportedEncodingException {
String authorizationCodeRequestUrl =
authorizationCodeFlow.newAuthorizationUrl().setScopes(scopes).build();
if (redirectUri != null) {
authorizationCodeRequestUrl += "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8");
}
return authorizationCodeRequestUrl;
} | java | @Nullable
public String getAuthorizationUrl() throws UnsupportedEncodingException {
String authorizationCodeRequestUrl =
authorizationCodeFlow.newAuthorizationUrl().setScopes(scopes).build();
if (redirectUri != null) {
authorizationCodeRequestUrl += "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8");
}
return authorizationCodeRequestUrl;
} | [
"@",
"Nullable",
"public",
"String",
"getAuthorizationUrl",
"(",
")",
"throws",
"UnsupportedEncodingException",
"{",
"String",
"authorizationCodeRequestUrl",
"=",
"authorizationCodeFlow",
".",
"newAuthorizationUrl",
"(",
")",
".",
"setScopes",
"(",
"scopes",
")",
".",
... | Gets the authorization URL to retrieve the authorization code. | [
"Gets",
"the",
"authorization",
"URL",
"to",
"retrieve",
"the",
"authorization",
"code",
"."
] | 6c75570ab7884f8ecafaad312ef471dd33f64c42 | https://github.com/uber/rides-java-sdk/blob/6c75570ab7884f8ecafaad312ef471dd33f64c42/uber-core-oauth-client-adapter/src/main/java/com/uber/sdk/core/auth/OAuth2Credentials.java#L229-L237 | train |
uber/rides-java-sdk | uber-core-oauth-client-adapter/src/main/java/com/uber/sdk/core/auth/OAuth2Credentials.java | OAuth2Credentials.clearCredential | public void clearCredential(String userId) throws AuthException {
try {
authorizationCodeFlow.getCredentialDataStore().delete(userId);
} catch (IOException e) {
throw new AuthException("Unable to clear credential.", e);
}
} | java | public void clearCredential(String userId) throws AuthException {
try {
authorizationCodeFlow.getCredentialDataStore().delete(userId);
} catch (IOException e) {
throw new AuthException("Unable to clear credential.", e);
}
} | [
"public",
"void",
"clearCredential",
"(",
"String",
"userId",
")",
"throws",
"AuthException",
"{",
"try",
"{",
"authorizationCodeFlow",
".",
"getCredentialDataStore",
"(",
")",
".",
"delete",
"(",
"userId",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",... | Clears the credential for the user in the underlying (@link DateStore}.
@throws AuthException If the credential could not be cleared. | [
"Clears",
"the",
"credential",
"for",
"the",
"user",
"in",
"the",
"underlying",
"("
] | 6c75570ab7884f8ecafaad312ef471dd33f64c42 | https://github.com/uber/rides-java-sdk/blob/6c75570ab7884f8ecafaad312ef471dd33f64c42/uber-core-oauth-client-adapter/src/main/java/com/uber/sdk/core/auth/OAuth2Credentials.java#L287-L293 | train |
google/gwteventbinder | eventbinder/src/main/java/com/google/web/bindery/event/shared/binder/impl/AbstractEventBinder.java | AbstractEventBinder.bind | protected final <U extends GenericEvent> void bind(
EventBus eventBus,
List<HandlerRegistration> registrations,
Class<U> type,
GenericEventHandler handler) {
registrations.add(eventBus.addHandler(GenericEventType.getTypeOf(type), handler));
} | java | protected final <U extends GenericEvent> void bind(
EventBus eventBus,
List<HandlerRegistration> registrations,
Class<U> type,
GenericEventHandler handler) {
registrations.add(eventBus.addHandler(GenericEventType.getTypeOf(type), handler));
} | [
"protected",
"final",
"<",
"U",
"extends",
"GenericEvent",
">",
"void",
"bind",
"(",
"EventBus",
"eventBus",
",",
"List",
"<",
"HandlerRegistration",
">",
"registrations",
",",
"Class",
"<",
"U",
">",
"type",
",",
"GenericEventHandler",
"handler",
")",
"{",
... | Registers the given handler for the given event class on the given event bus. Factored out
into a method here instead of generated directly in order to simplify the generated code and
save a little space. | [
"Registers",
"the",
"given",
"handler",
"for",
"the",
"given",
"event",
"class",
"on",
"the",
"given",
"event",
"bus",
".",
"Factored",
"out",
"into",
"a",
"method",
"here",
"instead",
"of",
"generated",
"directly",
"in",
"order",
"to",
"simplify",
"the",
... | 46d3e72e9006a4c7801c077b1b83ffb11bf687f7 | https://github.com/google/gwteventbinder/blob/46d3e72e9006a4c7801c077b1b83ffb11bf687f7/eventbinder/src/main/java/com/google/web/bindery/event/shared/binder/impl/AbstractEventBinder.java#L59-L65 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/DefaultGeneratorRunner.java | DefaultGeneratorRunner.findTopLevelTypes | private static Set<ClassTemplateSpec> findTopLevelTypes(ClassTemplateSpec spec) {
Set<ClassTemplateSpec> specs =
new HashSet<ClassTemplateSpec>(ClassTemplateSpecs.allReferencedTypes(spec));
specs.add(spec);
Iterator<ClassTemplateSpec> iterator = specs.iterator();
while (iterator.hasNext()) {
ClassTemplateSpec entry = iterator.next();
if (entry.getEnclosingClass() != null) {
iterator.remove();
}
}
return specs;
} | java | private static Set<ClassTemplateSpec> findTopLevelTypes(ClassTemplateSpec spec) {
Set<ClassTemplateSpec> specs =
new HashSet<ClassTemplateSpec>(ClassTemplateSpecs.allReferencedTypes(spec));
specs.add(spec);
Iterator<ClassTemplateSpec> iterator = specs.iterator();
while (iterator.hasNext()) {
ClassTemplateSpec entry = iterator.next();
if (entry.getEnclosingClass() != null) {
iterator.remove();
}
}
return specs;
} | [
"private",
"static",
"Set",
"<",
"ClassTemplateSpec",
">",
"findTopLevelTypes",
"(",
"ClassTemplateSpec",
"spec",
")",
"{",
"Set",
"<",
"ClassTemplateSpec",
">",
"specs",
"=",
"new",
"HashSet",
"<",
"ClassTemplateSpec",
">",
"(",
"ClassTemplateSpecs",
".",
"allRef... | Currently, one ClassDefinition is provided per .pdsc file. But some of those .pdsc contain
inline schema definitions that should be generated into top level classes.
This method traverses the spec hierarchy, finding all specs that should be generated as top
level classes.
I've asked the rest.li team to consider restructuring the generator utilities so that one
ClassDefinition per top level class is provided. If they restructure the utilities, this
method should no longer be needed. | [
"Currently",
"one",
"ClassDefinition",
"is",
"provided",
"per",
".",
"pdsc",
"file",
".",
"But",
"some",
"of",
"those",
".",
"pdsc",
"contain",
"inline",
"schema",
"definitions",
"that",
"should",
"be",
"generated",
"into",
"top",
"level",
"classes",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/DefaultGeneratorRunner.java#L152-L165 | train |
coursera/courier | typescript-lite/generator/src/main/java/org/coursera/courier/tslite/TSSyntax.java | TSSyntax.escapeKeyword | private static String escapeKeyword(String symbol, EscapeStrategy strategy) {
if (tsKeywords.contains(symbol)) {
if (strategy.equals(EscapeStrategy.MANGLE)) {
return symbol + "$";
} else {
return "\"" + symbol + "\"";
}
} else {
return symbol;
}
} | java | private static String escapeKeyword(String symbol, EscapeStrategy strategy) {
if (tsKeywords.contains(symbol)) {
if (strategy.equals(EscapeStrategy.MANGLE)) {
return symbol + "$";
} else {
return "\"" + symbol + "\"";
}
} else {
return symbol;
}
} | [
"private",
"static",
"String",
"escapeKeyword",
"(",
"String",
"symbol",
",",
"EscapeStrategy",
"strategy",
")",
"{",
"if",
"(",
"tsKeywords",
".",
"contains",
"(",
"symbol",
")",
")",
"{",
"if",
"(",
"strategy",
".",
"equals",
"(",
"EscapeStrategy",
".",
... | Returns the escaped Pegasus symbol for use in Typescript source code.
Pegasus symbols must be of the form [A-Za-z_], so this routine simply checks if the
symbol collides with a typescript keyword, and if so, escapes it.
@param symbol the symbol to escape
@param strategy which strategy to use in escaping
@return the escaped Pegasus symbol. | [
"Returns",
"the",
"escaped",
"Pegasus",
"symbol",
"for",
"use",
"in",
"Typescript",
"source",
"code",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/typescript-lite/generator/src/main/java/org/coursera/courier/tslite/TSSyntax.java#L161-L171 | train |
coursera/courier | typescript-lite/generator/src/main/java/org/coursera/courier/tslite/TSSyntax.java | TSSyntax.docComment | private static String docComment(String doc, Object deprecation /* nullable */) {
StringBuilder docStr = new StringBuilder();
if (doc != null) {
docStr.append(doc.trim());
}
if (deprecation != null) {
docStr.append("\n\n").append("@deprecated");
if (deprecation instanceof String) {
docStr.append(" ").append(((String)deprecation).trim());
}
}
return DocEscaping.stringToDocComment(docStr.toString(), DocCommentStyle.ASTRISK_MARGIN);
} | java | private static String docComment(String doc, Object deprecation /* nullable */) {
StringBuilder docStr = new StringBuilder();
if (doc != null) {
docStr.append(doc.trim());
}
if (deprecation != null) {
docStr.append("\n\n").append("@deprecated");
if (deprecation instanceof String) {
docStr.append(" ").append(((String)deprecation).trim());
}
}
return DocEscaping.stringToDocComment(docStr.toString(), DocCommentStyle.ASTRISK_MARGIN);
} | [
"private",
"static",
"String",
"docComment",
"(",
"String",
"doc",
",",
"Object",
"deprecation",
"/* nullable */",
")",
"{",
"StringBuilder",
"docStr",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"doc",
"!=",
"null",
")",
"{",
"docStr",
".",
"ap... | Return a full tsdoc for a type.
@param doc the doc string in the type's DataSchema.
@param deprecation the object listed under the schema's "deprecation" property
@return a fully formed tsdoc for the type. | [
"Return",
"a",
"full",
"tsdoc",
"for",
"a",
"type",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/typescript-lite/generator/src/main/java/org/coursera/courier/tslite/TSSyntax.java#L202-L216 | train |
coursera/courier | typescript-lite/generator/src/main/java/org/coursera/courier/tslite/TSSyntax.java | TSSyntax.typeNameQualifiedByEnclosingClass | String typeNameQualifiedByEnclosingClass(TSTypeSyntax syntax) {
if (syntax instanceof TSEnclosedTypeSyntax) {
return ((TSEnclosedTypeSyntax) syntax).typeNameQualifiedByEnclosedType();
} else {
return syntax.typeName();
}
} | java | String typeNameQualifiedByEnclosingClass(TSTypeSyntax syntax) {
if (syntax instanceof TSEnclosedTypeSyntax) {
return ((TSEnclosedTypeSyntax) syntax).typeNameQualifiedByEnclosedType();
} else {
return syntax.typeName();
}
} | [
"String",
"typeNameQualifiedByEnclosingClass",
"(",
"TSTypeSyntax",
"syntax",
")",
"{",
"if",
"(",
"syntax",
"instanceof",
"TSEnclosedTypeSyntax",
")",
"{",
"return",
"(",
"(",
"TSEnclosedTypeSyntax",
")",
"syntax",
")",
".",
"typeNameQualifiedByEnclosedType",
"(",
")... | Returns the type name, prefaced with the enclosing class name if there was one.
For example, a standalone union called MyUnion will just return "MyUnion".
If that same union were enclosed within MyRecord, this would return "MyRecord.MyUnion". | [
"Returns",
"the",
"type",
"name",
"prefaced",
"with",
"the",
"enclosing",
"class",
"name",
"if",
"there",
"was",
"one",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/typescript-lite/generator/src/main/java/org/coursera/courier/tslite/TSSyntax.java#L298-L304 | train |
coursera/courier | typescript-lite/generator/src/main/java/org/coursera/courier/tslite/TSSyntax.java | TSSyntax.TSTyperefSyntaxCreate | public TSTyperefSyntax TSTyperefSyntaxCreate(TyperefTemplateSpec template) {
return new TSTyperefSyntax(template, template.getSchema(), new TSNamedTypeSyntax(template.getSchema()));
} | java | public TSTyperefSyntax TSTyperefSyntaxCreate(TyperefTemplateSpec template) {
return new TSTyperefSyntax(template, template.getSchema(), new TSNamedTypeSyntax(template.getSchema()));
} | [
"public",
"TSTyperefSyntax",
"TSTyperefSyntaxCreate",
"(",
"TyperefTemplateSpec",
"template",
")",
"{",
"return",
"new",
"TSTyperefSyntax",
"(",
"template",
",",
"template",
".",
"getSchema",
"(",
")",
",",
"new",
"TSNamedTypeSyntax",
"(",
"template",
".",
"getSchem... | Create a new TyperefSyntax | [
"Create",
"a",
"new",
"TyperefSyntax"
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/typescript-lite/generator/src/main/java/org/coursera/courier/tslite/TSSyntax.java#L915-L917 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/CourierTemplateSpecGenerator.java | CourierTemplateSpecGenerator.allowCustomClass | private static boolean allowCustomClass(DataSchema schema)
{
boolean result = false;
final DataSchema.Type type = schema.getType();
if (type == DataSchema.Type.TYPEREF || type == DataSchema.Type.RECORD)
{
// allow custom class only if the dereferenced type is a record or a primitive types that are not enums
final DataSchema dereferencedSchema = schema.getDereferencedDataSchema();
if (dereferencedSchema.getType() == DataSchema.Type.RECORD || (CodeUtil.isDirectType(dereferencedSchema) && dereferencedSchema.getType() != DataSchema.Type.ENUM))
{
result = true;
}
}
return result;
} | java | private static boolean allowCustomClass(DataSchema schema)
{
boolean result = false;
final DataSchema.Type type = schema.getType();
if (type == DataSchema.Type.TYPEREF || type == DataSchema.Type.RECORD)
{
// allow custom class only if the dereferenced type is a record or a primitive types that are not enums
final DataSchema dereferencedSchema = schema.getDereferencedDataSchema();
if (dereferencedSchema.getType() == DataSchema.Type.RECORD || (CodeUtil.isDirectType(dereferencedSchema) && dereferencedSchema.getType() != DataSchema.Type.ENUM))
{
result = true;
}
}
return result;
} | [
"private",
"static",
"boolean",
"allowCustomClass",
"(",
"DataSchema",
"schema",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"final",
"DataSchema",
".",
"Type",
"type",
"=",
"schema",
".",
"getType",
"(",
")",
";",
"if",
"(",
"type",
"==",
"DataSchem... | Allow custom class to to bound to record or typeref of primitive types that are not enums. | [
"Allow",
"custom",
"class",
"to",
"to",
"bound",
"to",
"record",
"or",
"typeref",
"of",
"primitive",
"types",
"that",
"are",
"not",
"enums",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/CourierTemplateSpecGenerator.java#L226-L240 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/CourierTemplateSpecGenerator.java | CourierTemplateSpecGenerator.createFromDataSchema | private ClassTemplateSpec createFromDataSchema(DataSchema schema)
{
if (schema instanceof MapDataSchema)
{
return new CourierMapTemplateSpec((MapDataSchema) schema);
}
return ClassTemplateSpec.createFromDataSchema(schema);
} | java | private ClassTemplateSpec createFromDataSchema(DataSchema schema)
{
if (schema instanceof MapDataSchema)
{
return new CourierMapTemplateSpec((MapDataSchema) schema);
}
return ClassTemplateSpec.createFromDataSchema(schema);
} | [
"private",
"ClassTemplateSpec",
"createFromDataSchema",
"(",
"DataSchema",
"schema",
")",
"{",
"if",
"(",
"schema",
"instanceof",
"MapDataSchema",
")",
"{",
"return",
"new",
"CourierMapTemplateSpec",
"(",
"(",
"MapDataSchema",
")",
"schema",
")",
";",
"}",
"return... | For Courier, use CourierMapTemplateSpec for maps. | [
"For",
"Courier",
"use",
"CourierMapTemplateSpec",
"for",
"maps",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/CourierTemplateSpecGenerator.java#L877-L884 | train |
coursera/courier | idea-plugin/src/org/coursera/courier/CourierBraceMatcher.java | CourierBraceMatcher.getPairs | @Override
public BracePair[] getPairs() {
return new BracePair[] {
new BracePair(CourierTypes.OPEN_BRACE, CourierTypes.CLOSE_BRACE, true),
new BracePair(CourierTypes.OPEN_BRACKET, CourierTypes.CLOSE_BRACKET, false),
new BracePair(CourierTypes.OPEN_PAREN, CourierTypes.CLOSE_PAREN, false)
//new BracePair(SchemadocTypes.DOC_COMMENT_START, SchemadocTypes.DOC_COMMENT_END, false)
};
} | java | @Override
public BracePair[] getPairs() {
return new BracePair[] {
new BracePair(CourierTypes.OPEN_BRACE, CourierTypes.CLOSE_BRACE, true),
new BracePair(CourierTypes.OPEN_BRACKET, CourierTypes.CLOSE_BRACKET, false),
new BracePair(CourierTypes.OPEN_PAREN, CourierTypes.CLOSE_PAREN, false)
//new BracePair(SchemadocTypes.DOC_COMMENT_START, SchemadocTypes.DOC_COMMENT_END, false)
};
} | [
"@",
"Override",
"public",
"BracePair",
"[",
"]",
"getPairs",
"(",
")",
"{",
"return",
"new",
"BracePair",
"[",
"]",
"{",
"new",
"BracePair",
"(",
"CourierTypes",
".",
"OPEN_BRACE",
",",
"CourierTypes",
".",
"CLOSE_BRACE",
",",
"true",
")",
",",
"new",
"... | Returns the array of definitions for brace pairs that need to be matched when
editing code in the language.
@return the array of brace pair definitions. | [
"Returns",
"the",
"array",
"of",
"definitions",
"for",
"brace",
"pairs",
"that",
"need",
"to",
"be",
"matched",
"when",
"editing",
"code",
"in",
"the",
"language",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/idea-plugin/src/org/coursera/courier/CourierBraceMatcher.java#L20-L28 | train |
coursera/courier | schema-language/src/main/java/org/coursera/courier/grammar/CourierSchemaParser.java | CourierSchemaParser.parse | private String parse(DocumentContext document) throws ParseException {
if (document.namespaceDeclaration() != null) {
setCurrentNamespace(
document.namespaceDeclaration().qualifiedIdentifier().value);
} else {
setCurrentNamespace("");
}
setCurrentImports(document.importDeclarations());
NamedDataSchema schema = parseNamedType(document.namedTypeDeclaration());
topLevelSchemas.add(schema);
return schema.getFullName();
} | java | private String parse(DocumentContext document) throws ParseException {
if (document.namespaceDeclaration() != null) {
setCurrentNamespace(
document.namespaceDeclaration().qualifiedIdentifier().value);
} else {
setCurrentNamespace("");
}
setCurrentImports(document.importDeclarations());
NamedDataSchema schema = parseNamedType(document.namedTypeDeclaration());
topLevelSchemas.add(schema);
return schema.getFullName();
} | [
"private",
"String",
"parse",
"(",
"DocumentContext",
"document",
")",
"throws",
"ParseException",
"{",
"if",
"(",
"document",
".",
"namespaceDeclaration",
"(",
")",
"!=",
"null",
")",
"{",
"setCurrentNamespace",
"(",
"document",
".",
"namespaceDeclaration",
"(",
... | Parse list of Data objects.
The {{DataSchema}'s parsed are in {{#topLevelDataSchemas}.
Parse errors are in {{#errorMessageBuilder} and indicated
by {{#hasError()}.
@param document provides the source code in AST form | [
"Parse",
"list",
"of",
"Data",
"objects",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/schema-language/src/main/java/org/coursera/courier/grammar/CourierSchemaParser.java#L284-L296 | train |
coursera/courier | schema-language/src/main/java/org/coursera/courier/grammar/CourierSchemaParser.java | CourierSchemaParser.addPropertiesAtPath | private void addPropertiesAtPath(
Map<String, Object> existingProperties, PropDeclarationContext prop) throws ParseException{
addPropertiesAtPath(prop, existingProperties, prop.path, parsePropValue(prop));
} | java | private void addPropertiesAtPath(
Map<String, Object> existingProperties, PropDeclarationContext prop) throws ParseException{
addPropertiesAtPath(prop, existingProperties, prop.path, parsePropValue(prop));
} | [
"private",
"void",
"addPropertiesAtPath",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"existingProperties",
",",
"PropDeclarationContext",
"prop",
")",
"throws",
"ParseException",
"{",
"addPropertiesAtPath",
"(",
"prop",
",",
"existingProperties",
",",
"prop",
".... | Adds additional properties to an existing properties map at the location identified by
the given PropDeclarationContexts path.
@param existingProperties provides the existing properties to add the additional properties to.
@param prop provides the ANTLR property AST node to add the properties for. | [
"Adds",
"additional",
"properties",
"to",
"an",
"existing",
"properties",
"map",
"at",
"the",
"location",
"identified",
"by",
"the",
"given",
"PropDeclarationContexts",
"path",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/schema-language/src/main/java/org/coursera/courier/grammar/CourierSchemaParser.java#L512-L515 | train |
coursera/courier | schema-language/src/main/java/org/coursera/courier/grammar/CourierSchemaParser.java | CourierSchemaParser.addPropertiesAtPath | private void addPropertiesAtPath(
ParserRuleContext context,
Map<String, Object> existingProperties,
Iterable<String> path,
Object value) throws ParseException {
Map<String, Object> current = existingProperties;
Iterator<String> iter = path.iterator();
while (iter.hasNext()) {
String pathPart = iter.next();
if (iter.hasNext()) {
if (existingProperties.containsKey(pathPart)) {
Object val = existingProperties.get(pathPart);
if (!(val instanceof DataMap)) {
throw new ParseException(
new ParseError(
new ParseErrorLocation(context),
"Conflicting property: " + path.toString()));
}
current = (DataMap) val;
} else {
DataMap next = new DataMap();
current.put(pathPart, next);
current = next;
}
} else {
if (current.containsKey(pathPart)) {
throw new ParseException(
new ParseError(
new ParseErrorLocation(context),
"Property already defined: " + path.toString()));
} else {
current.put(pathPart, value);
}
}
}
} | java | private void addPropertiesAtPath(
ParserRuleContext context,
Map<String, Object> existingProperties,
Iterable<String> path,
Object value) throws ParseException {
Map<String, Object> current = existingProperties;
Iterator<String> iter = path.iterator();
while (iter.hasNext()) {
String pathPart = iter.next();
if (iter.hasNext()) {
if (existingProperties.containsKey(pathPart)) {
Object val = existingProperties.get(pathPart);
if (!(val instanceof DataMap)) {
throw new ParseException(
new ParseError(
new ParseErrorLocation(context),
"Conflicting property: " + path.toString()));
}
current = (DataMap) val;
} else {
DataMap next = new DataMap();
current.put(pathPart, next);
current = next;
}
} else {
if (current.containsKey(pathPart)) {
throw new ParseException(
new ParseError(
new ParseErrorLocation(context),
"Property already defined: " + path.toString()));
} else {
current.put(pathPart, value);
}
}
}
} | [
"private",
"void",
"addPropertiesAtPath",
"(",
"ParserRuleContext",
"context",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"existingProperties",
",",
"Iterable",
"<",
"String",
">",
"path",
",",
"Object",
"value",
")",
"throws",
"ParseException",
"{",
"Map",
... | Adds additional properties to an existing properties map at the location identified by
the given path.
This allows for properties defined with paths such as:
{@literal @}a.b = "x"
{@literal @}a.c = "y"
to be merged together into a property map like:
{ "a": { "b": "x", "c": "y" }}
Examples:
<pre>
existing properties | path | value | result
---------------------------|-------|---------------|----------------------------------------
{} | a.b.c | true | { "a": { "b": { "c": true } } }
{ "a": {} } | a.b | true | { "a": { "b": true } }
{ "a": {} } | a.b | { "z": "x" } | { "a": { "b": { "z": "x" } } }
{ "a": { "c": "x"}} } | a.b | true | { "a": { "b": true, "c": "x"} } }
{ "a": { "b": "x"}} } | a.b | "y" | ParseError "Conflicting property: a.b"
</pre>
The existing properties are traversed using the given path, adding DataMaps as needed to
complete the traversal. If any of data elements in the existing properties along the path are
not DataMaps, a ParseError is thrown to report the conflict.
@param context provides the parsing context for error reporting purposes.
@param existingProperties provides the properties to add to.
@param path provides the path of the property to insert.
@param value provides the value of the property to insert.
@throws ParseException if the path of the properties to add conflicts with data already
in the properties map or if a property is already exists at the path. | [
"Adds",
"additional",
"properties",
"to",
"an",
"existing",
"properties",
"map",
"at",
"the",
"location",
"identified",
"by",
"the",
"given",
"path",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/schema-language/src/main/java/org/coursera/courier/grammar/CourierSchemaParser.java#L553-L588 | train |
coursera/courier | schema-language/src/main/java/org/coursera/courier/grammar/CourierSchemaParser.java | CourierSchemaParser.computeFullName | @Override
public String computeFullName(String name) {
String fullname;
DataSchema schema = DataSchemaUtil.typeStringToPrimitiveDataSchema(name);
if (schema != null)
{
fullname = name;
}
else if (Name.isFullName(name) || getCurrentNamespace().isEmpty())
{
fullname = name; // already a fullname
}
else if (currentImports.containsKey(name)) {
// imported names are higher precedence than names in current namespace
fullname = currentImports.get(name).getFullName();
}
else
{
fullname = getCurrentNamespace() + "." + name; // assumed to be in current namespace
}
return fullname;
} | java | @Override
public String computeFullName(String name) {
String fullname;
DataSchema schema = DataSchemaUtil.typeStringToPrimitiveDataSchema(name);
if (schema != null)
{
fullname = name;
}
else if (Name.isFullName(name) || getCurrentNamespace().isEmpty())
{
fullname = name; // already a fullname
}
else if (currentImports.containsKey(name)) {
// imported names are higher precedence than names in current namespace
fullname = currentImports.get(name).getFullName();
}
else
{
fullname = getCurrentNamespace() + "." + name; // assumed to be in current namespace
}
return fullname;
} | [
"@",
"Override",
"public",
"String",
"computeFullName",
"(",
"String",
"name",
")",
"{",
"String",
"fullname",
";",
"DataSchema",
"schema",
"=",
"DataSchemaUtil",
".",
"typeStringToPrimitiveDataSchema",
"(",
"name",
")",
";",
"if",
"(",
"schema",
"!=",
"null",
... | Extended fullname computation to handle imports | [
"Extended",
"fullname",
"computation",
"to",
"handle",
"imports"
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/schema-language/src/main/java/org/coursera/courier/grammar/CourierSchemaParser.java#L735-L756 | train |
coursera/courier | schema-language/src/main/java/org/coursera/courier/grammar/ParseUtils.java | ParseUtils.toNumber | public static Number toNumber(String string) {
BigDecimal value = new BigDecimal(string);
try {
long l = value.longValueExact();
int i = (int) l;
if ((long) i == l) {
return i;
} else {
return l;
}
} catch (ArithmeticException e) {
double d = value.doubleValue();
if (BigDecimal.valueOf(d).equals(value)) {
float f = (float) d;
if ((double) f == d) {
return (float) d;
} else {
return d;
}
} else {
return null;
}
}
} | java | public static Number toNumber(String string) {
BigDecimal value = new BigDecimal(string);
try {
long l = value.longValueExact();
int i = (int) l;
if ((long) i == l) {
return i;
} else {
return l;
}
} catch (ArithmeticException e) {
double d = value.doubleValue();
if (BigDecimal.valueOf(d).equals(value)) {
float f = (float) d;
if ((double) f == d) {
return (float) d;
} else {
return d;
}
} else {
return null;
}
}
} | [
"public",
"static",
"Number",
"toNumber",
"(",
"String",
"string",
")",
"{",
"BigDecimal",
"value",
"=",
"new",
"BigDecimal",
"(",
"string",
")",
";",
"try",
"{",
"long",
"l",
"=",
"value",
".",
"longValueExact",
"(",
")",
";",
"int",
"i",
"=",
"(",
... | There must be a better way. | [
"There",
"must",
"be",
"a",
"better",
"way",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/schema-language/src/main/java/org/coursera/courier/grammar/ParseUtils.java#L88-L111 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/FileFormatDataSchemaParser.java | FileFormatDataSchemaParser.validateSchemaWithFilePath | private void validateSchemaWithFilePath(File schemaSourceFile, DataSchema schema)
{
if (schemaSourceFile != null && schemaSourceFile.isFile() && schema instanceof NamedDataSchema)
{
final NamedDataSchema namedDataSchema = (NamedDataSchema) schema;
final String namespace = namedDataSchema.getNamespace();
if (!FileUtil.removeFileExtension(schemaSourceFile.getName()).equalsIgnoreCase(namedDataSchema.getName()))
{
throw new IllegalArgumentException(namedDataSchema.getFullName() + " has name that does not match filename '" +
schemaSourceFile.getAbsolutePath() + "'");
}
final String directory = schemaSourceFile.getParentFile().getAbsolutePath();
if (!directory.endsWith(namespace.replace('.', File.separatorChar)))
{
throw new IllegalArgumentException(namedDataSchema.getFullName() + " has namespace that does not match " +
"file path '" + schemaSourceFile.getAbsolutePath() + "'");
}
}
} | java | private void validateSchemaWithFilePath(File schemaSourceFile, DataSchema schema)
{
if (schemaSourceFile != null && schemaSourceFile.isFile() && schema instanceof NamedDataSchema)
{
final NamedDataSchema namedDataSchema = (NamedDataSchema) schema;
final String namespace = namedDataSchema.getNamespace();
if (!FileUtil.removeFileExtension(schemaSourceFile.getName()).equalsIgnoreCase(namedDataSchema.getName()))
{
throw new IllegalArgumentException(namedDataSchema.getFullName() + " has name that does not match filename '" +
schemaSourceFile.getAbsolutePath() + "'");
}
final String directory = schemaSourceFile.getParentFile().getAbsolutePath();
if (!directory.endsWith(namespace.replace('.', File.separatorChar)))
{
throw new IllegalArgumentException(namedDataSchema.getFullName() + " has namespace that does not match " +
"file path '" + schemaSourceFile.getAbsolutePath() + "'");
}
}
} | [
"private",
"void",
"validateSchemaWithFilePath",
"(",
"File",
"schemaSourceFile",
",",
"DataSchema",
"schema",
")",
"{",
"if",
"(",
"schemaSourceFile",
"!=",
"null",
"&&",
"schemaSourceFile",
".",
"isFile",
"(",
")",
"&&",
"schema",
"instanceof",
"NamedDataSchema",
... | Checks that the schema name and namespace match the file name and path. These must match for FileDataSchemaResolver to find a schema pdscs by fully qualified name. | [
"Checks",
"that",
"the",
"schema",
"name",
"and",
"namespace",
"match",
"the",
"file",
"name",
"and",
"path",
".",
"These",
"must",
"match",
"for",
"FileDataSchemaResolver",
"to",
"find",
"a",
"schema",
"pdscs",
"by",
"fully",
"qualified",
"name",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/FileFormatDataSchemaParser.java#L195-L215 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/FileFormatDataSchemaParser.java | FileFormatDataSchemaParser.wasResolved | private boolean wasResolved(File schemaSourceFile)
{
final FileDataSchemaLocation schemaLocation = new FileDataSchemaLocation(schemaSourceFile);
return _schemaResolver.locationResolved(schemaLocation);
} | java | private boolean wasResolved(File schemaSourceFile)
{
final FileDataSchemaLocation schemaLocation = new FileDataSchemaLocation(schemaSourceFile);
return _schemaResolver.locationResolved(schemaLocation);
} | [
"private",
"boolean",
"wasResolved",
"(",
"File",
"schemaSourceFile",
")",
"{",
"final",
"FileDataSchemaLocation",
"schemaLocation",
"=",
"new",
"FileDataSchemaLocation",
"(",
"schemaSourceFile",
")",
";",
"return",
"_schemaResolver",
".",
"locationResolved",
"(",
"sche... | Whether a source file has already been resolved to data schemas.
@param schemaSourceFile provides the source file.
@return true if this source file has already been resolved to data schemas. | [
"Whether",
"a",
"source",
"file",
"has",
"already",
"been",
"resolved",
"to",
"data",
"schemas",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/FileFormatDataSchemaParser.java#L224-L228 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/FileFormatDataSchemaParser.java | FileFormatDataSchemaParser.parseSchema | private List<DataSchema> parseSchema(final File schemaSourceFile, CourierParseResult result)
throws IOException
{
SchemaParser parser = _schemaParserFactory.create(_schemaResolver);
final FileInputStream schemaStream = new SchemaFileInputStream(schemaSourceFile);
try
{
parser.setLocation(new FileDataSchemaLocation(schemaSourceFile));
parser.parse(schemaStream);
if (parser.hasError())
{
return Collections.emptyList();
}
return parser.topLevelDataSchemas();
}
finally
{
schemaStream.close();
if (parser.hasError())
{
result.addMessage(schemaSourceFile.getPath() + ",");
result.addMessage(parser.errorMessage());
}
}
} | java | private List<DataSchema> parseSchema(final File schemaSourceFile, CourierParseResult result)
throws IOException
{
SchemaParser parser = _schemaParserFactory.create(_schemaResolver);
final FileInputStream schemaStream = new SchemaFileInputStream(schemaSourceFile);
try
{
parser.setLocation(new FileDataSchemaLocation(schemaSourceFile));
parser.parse(schemaStream);
if (parser.hasError())
{
return Collections.emptyList();
}
return parser.topLevelDataSchemas();
}
finally
{
schemaStream.close();
if (parser.hasError())
{
result.addMessage(schemaSourceFile.getPath() + ",");
result.addMessage(parser.errorMessage());
}
}
} | [
"private",
"List",
"<",
"DataSchema",
">",
"parseSchema",
"(",
"final",
"File",
"schemaSourceFile",
",",
"CourierParseResult",
"result",
")",
"throws",
"IOException",
"{",
"SchemaParser",
"parser",
"=",
"_schemaParserFactory",
".",
"create",
"(",
"_schemaResolver",
... | Parse a source file to obtain the data schemas contained within.
@param schemaSourceFile provides the source file.
@param result {@link ParseResult} to update.
@return the data schemas within the source file.
@throws IOException if there is a file access error. | [
"Parse",
"a",
"source",
"file",
"to",
"obtain",
"the",
"data",
"schemas",
"contained",
"within",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/FileFormatDataSchemaParser.java#L241-L265 | train |
coursera/courier | swift/generator/src/main/java/org/coursera/courier/swift/SwiftSyntax.java | SwiftSyntax.escapeKeyword | public static String escapeKeyword(String symbol) {
if (swiftKeywords.contains(symbol)) {
return "`" + symbol + "`";
} else if (reservedSymbols.contains(symbol)) {
return symbol + "$";
} else {
return symbol;
}
} | java | public static String escapeKeyword(String symbol) {
if (swiftKeywords.contains(symbol)) {
return "`" + symbol + "`";
} else if (reservedSymbols.contains(symbol)) {
return symbol + "$";
} else {
return symbol;
}
} | [
"public",
"static",
"String",
"escapeKeyword",
"(",
"String",
"symbol",
")",
"{",
"if",
"(",
"swiftKeywords",
".",
"contains",
"(",
"symbol",
")",
")",
"{",
"return",
"\"`\"",
"+",
"symbol",
"+",
"\"`\"",
";",
"}",
"else",
"if",
"(",
"reservedSymbols",
"... | Returns the escaped Pegasus symbol for use in Swift source code.
Pegasus symbols must be of the form [A-Za-z_], so this routine simply checks if the
symbol collides with a swift keyword, and if so, escapes it.
(Because only fields are generated, symbols like hashCode do not collide with method names
from Object and may be used).
@param symbol the symbol to escape
@return the escaped Pegasus symbol. | [
"Returns",
"the",
"escaped",
"Pegasus",
"symbol",
"for",
"use",
"in",
"Swift",
"source",
"code",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/swift/generator/src/main/java/org/coursera/courier/swift/SwiftSyntax.java#L97-L105 | train |
coursera/courier | swift/generator/src/main/java/org/coursera/courier/swift/SwiftSyntax.java | SwiftSyntax.toTypeString | private String toTypeString(ClassTemplateSpec spec) {
// If we're supporting projections, all fields, even required ones, may be absent.
// To support this, we box all primitive field types.
if (spec.getSchema() == null) { // custom type
return escapedFullname(spec);
}
Type schemaType = spec.getSchema().getType();
if (schemaType == Type.INT) {
return "Int"; // TODO: just use Int32 here? (On a 32-bit platform, Int is the same size as Int32.)
} else if (schemaType == Type.LONG) {
return "Int"; // TODO: just use Int32 here? (On a 64-bit platform, Int is the same size as Int64.)
} else if (schemaType == Type.FLOAT) {
return "Float";
} else if (schemaType == Type.DOUBLE) {
return "Double";
} else if (schemaType == Type.STRING) {
return "String";
} else if (schemaType == Type.BOOLEAN) {
return "Bool";
} else if (schemaType == Type.BYTES) {
return "String"; // TODO(jbetz): provide an adapter for converting pegasus byte strings to swift byte[]
} else if (schemaType == Type.FIXED) {
return "String"; // TODO(jbetz): provide an adapter for converting pegasus byte strings to swift byte[]
} else if (schemaType == Type.ENUM) {
return escapedFullname(spec);
} else if (schemaType == Type.RECORD) {
return escapedFullname(spec);
} else if (schemaType == Type.UNION) {
return escapedFullname(spec);
} else if (schemaType == Type.MAP) {
return "[String: " + toTypeString(((CourierMapTemplateSpec) spec).getValueClass()) + "]";
} else if (schemaType == Type.ARRAY) {
return "[" + toTypeString(((ArrayTemplateSpec) spec).getItemClass()) + "]";
} else {
throw new IllegalArgumentException("unrecognized type: " + schemaType);
}
} | java | private String toTypeString(ClassTemplateSpec spec) {
// If we're supporting projections, all fields, even required ones, may be absent.
// To support this, we box all primitive field types.
if (spec.getSchema() == null) { // custom type
return escapedFullname(spec);
}
Type schemaType = spec.getSchema().getType();
if (schemaType == Type.INT) {
return "Int"; // TODO: just use Int32 here? (On a 32-bit platform, Int is the same size as Int32.)
} else if (schemaType == Type.LONG) {
return "Int"; // TODO: just use Int32 here? (On a 64-bit platform, Int is the same size as Int64.)
} else if (schemaType == Type.FLOAT) {
return "Float";
} else if (schemaType == Type.DOUBLE) {
return "Double";
} else if (schemaType == Type.STRING) {
return "String";
} else if (schemaType == Type.BOOLEAN) {
return "Bool";
} else if (schemaType == Type.BYTES) {
return "String"; // TODO(jbetz): provide an adapter for converting pegasus byte strings to swift byte[]
} else if (schemaType == Type.FIXED) {
return "String"; // TODO(jbetz): provide an adapter for converting pegasus byte strings to swift byte[]
} else if (schemaType == Type.ENUM) {
return escapedFullname(spec);
} else if (schemaType == Type.RECORD) {
return escapedFullname(spec);
} else if (schemaType == Type.UNION) {
return escapedFullname(spec);
} else if (schemaType == Type.MAP) {
return "[String: " + toTypeString(((CourierMapTemplateSpec) spec).getValueClass()) + "]";
} else if (schemaType == Type.ARRAY) {
return "[" + toTypeString(((ArrayTemplateSpec) spec).getItemClass()) + "]";
} else {
throw new IllegalArgumentException("unrecognized type: " + schemaType);
}
} | [
"private",
"String",
"toTypeString",
"(",
"ClassTemplateSpec",
"spec",
")",
"{",
"// If we're supporting projections, all fields, even required ones, may be absent.",
"// To support this, we box all primitive field types.",
"if",
"(",
"spec",
".",
"getSchema",
"(",
")",
"==",
"nu... | emit string representing type | [
"emit",
"string",
"representing",
"type"
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/swift/generator/src/main/java/org/coursera/courier/swift/SwiftSyntax.java#L164-L200 | train |
coursera/courier | swift/generator/src/main/java/org/coursera/courier/swift/SwiftDocEscaping.java | SwiftDocEscaping.stringToDocComment | public static String stringToDocComment(String doc) {
boolean emptyDoc = (doc == null || doc.trim().isEmpty());
if (emptyDoc) return "";
return DocEscaping.stringToDocComment(doc, DocCommentStyle.NO_MARGIN);
} | java | public static String stringToDocComment(String doc) {
boolean emptyDoc = (doc == null || doc.trim().isEmpty());
if (emptyDoc) return "";
return DocEscaping.stringToDocComment(doc, DocCommentStyle.NO_MARGIN);
} | [
"public",
"static",
"String",
"stringToDocComment",
"(",
"String",
"doc",
")",
"{",
"boolean",
"emptyDoc",
"=",
"(",
"doc",
"==",
"null",
"||",
"doc",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
";",
"if",
"(",
"emptyDoc",
")",
"return",
"\... | Returns a doc comment, as a string of Swift source, for the given documentation string.
@param doc provides the javadoc for the symbol, if any. May be null.
@return an escaped doc comment string. | [
"Returns",
"a",
"doc",
"comment",
"as",
"a",
"string",
"of",
"Swift",
"source",
"for",
"the",
"given",
"documentation",
"string",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/swift/generator/src/main/java/org/coursera/courier/swift/SwiftDocEscaping.java#L29-L34 | train |
coursera/courier | idea-plugin/src/org/coursera/courier/CourierScalaToCourierAction.java | CourierScalaToCourierAction.getScalaClassName | private String getScalaClassName(PsiClass c) {
String baseName = c.getName();
return baseName.replaceAll("\\$", "");
} | java | private String getScalaClassName(PsiClass c) {
String baseName = c.getName();
return baseName.replaceAll("\\$", "");
} | [
"private",
"String",
"getScalaClassName",
"(",
"PsiClass",
"c",
")",
"{",
"String",
"baseName",
"=",
"c",
".",
"getName",
"(",
")",
";",
"return",
"baseName",
".",
"replaceAll",
"(",
"\"\\\\$\"",
",",
"\"\"",
")",
";",
"}"
] | Given a Java class or a Scala class OR object, gets the underlying class name.
Object names have $ appended | [
"Given",
"a",
"Java",
"class",
"or",
"a",
"Scala",
"class",
"OR",
"object",
"gets",
"the",
"underlying",
"class",
"name",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/idea-plugin/src/org/coursera/courier/CourierScalaToCourierAction.java#L71-L74 | train |
coursera/courier | idea-plugin/src/org/coursera/courier/psi/CourierFile.java | CourierFile.addFirstImport | private CourierImportDeclarations addFirstImport(CourierImportDeclaration importDecl) {
TypeName first = importDecl.getFullname();
CourierTopLevel root = getRoot();
CourierImportDeclarations importDecls = root.getImportDeclarations();
if (importDecls.getImportDeclarationList().size() == 0) {
importDecls.delete();
CourierImportDeclarations emptyImports =
CourierElementFactory.createImports(getProject(), Collections.singleton(first));
CourierNamespaceDeclaration namespaceDecl = root.getNamespaceDeclaration();
if (namespaceDecl != null) {
root.addAfter(emptyImports, namespaceDecl);
} else {
PsiElement firstChild = root.getFirstChild();
if (firstChild != null) {
root.addBefore(emptyImports, firstChild);
} else {
root.add(emptyImports);
}
}
return emptyImports;
} else {
return importDecls;
}
} | java | private CourierImportDeclarations addFirstImport(CourierImportDeclaration importDecl) {
TypeName first = importDecl.getFullname();
CourierTopLevel root = getRoot();
CourierImportDeclarations importDecls = root.getImportDeclarations();
if (importDecls.getImportDeclarationList().size() == 0) {
importDecls.delete();
CourierImportDeclarations emptyImports =
CourierElementFactory.createImports(getProject(), Collections.singleton(first));
CourierNamespaceDeclaration namespaceDecl = root.getNamespaceDeclaration();
if (namespaceDecl != null) {
root.addAfter(emptyImports, namespaceDecl);
} else {
PsiElement firstChild = root.getFirstChild();
if (firstChild != null) {
root.addBefore(emptyImports, firstChild);
} else {
root.add(emptyImports);
}
}
return emptyImports;
} else {
return importDecls;
}
} | [
"private",
"CourierImportDeclarations",
"addFirstImport",
"(",
"CourierImportDeclaration",
"importDecl",
")",
"{",
"TypeName",
"first",
"=",
"importDecl",
".",
"getFullname",
"(",
")",
";",
"CourierTopLevel",
"root",
"=",
"getRoot",
"(",
")",
";",
"CourierImportDeclar... | Position imports correctly when adding the first import. | [
"Position",
"imports",
"correctly",
"when",
"adding",
"the",
"first",
"import",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/idea-plugin/src/org/coursera/courier/psi/CourierFile.java#L70-L94 | train |
coursera/courier | idea-plugin/src/org/coursera/courier/psi/CourierFile.java | CourierFile.addNthImport | private CourierImportDeclarations addNthImport(CourierImportDeclaration importDecl) {
CourierTopLevel root = getRoot();
CourierImportDeclarations importDecls = root.getImportDeclarations();
if (importDecl.getFullname() == null) {
return importDecls;
}
boolean added = false;
for (CourierImportDeclaration existing : importDecls.getImportDeclarationList()) {
if (existing.getFullname() != null && importDecl.getFullname().toString().compareTo(existing.getFullname().toString()) < 0) {
importDecls.addBefore(importDecl, existing);
added = true;
break;
}
}
if (!added) {
importDecls.add(importDecl);
}
return importDecls;
} | java | private CourierImportDeclarations addNthImport(CourierImportDeclaration importDecl) {
CourierTopLevel root = getRoot();
CourierImportDeclarations importDecls = root.getImportDeclarations();
if (importDecl.getFullname() == null) {
return importDecls;
}
boolean added = false;
for (CourierImportDeclaration existing : importDecls.getImportDeclarationList()) {
if (existing.getFullname() != null && importDecl.getFullname().toString().compareTo(existing.getFullname().toString()) < 0) {
importDecls.addBefore(importDecl, existing);
added = true;
break;
}
}
if (!added) {
importDecls.add(importDecl);
}
return importDecls;
} | [
"private",
"CourierImportDeclarations",
"addNthImport",
"(",
"CourierImportDeclaration",
"importDecl",
")",
"{",
"CourierTopLevel",
"root",
"=",
"getRoot",
"(",
")",
";",
"CourierImportDeclarations",
"importDecls",
"=",
"root",
".",
"getImportDeclarations",
"(",
")",
";... | Add an import to an existing import list, attempting to keep the list sorted.
Note: this does not change the sort order of the existing import list. It only attempts
to keep the list sorted if it already is by adding the import at the correct position. | [
"Add",
"an",
"import",
"to",
"an",
"existing",
"import",
"list",
"attempting",
"to",
"keep",
"the",
"list",
"sorted",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/idea-plugin/src/org/coursera/courier/psi/CourierFile.java#L103-L122 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/lang/DocEscaping.java | DocEscaping.stringToDocComment | public static String stringToDocComment(String doc, DocCommentStyle style) {
if (doc == null || doc.trim().isEmpty()) return "";
String commentNewline = (style == DocCommentStyle.ASTRISK_MARGIN) ? "\n * " : "\n";
String schemadoc = wrap(escape(doc)).replaceAll("\\n", commentNewline);
StringBuilder builder = new StringBuilder();
builder.append("/**\n");
if (style == DocCommentStyle.ASTRISK_MARGIN) builder.append(" * ");
builder.append(schemadoc).append("\n");
if (style == DocCommentStyle.ASTRISK_MARGIN) builder.append(" ");
builder.append("*/");
return builder.toString();
} | java | public static String stringToDocComment(String doc, DocCommentStyle style) {
if (doc == null || doc.trim().isEmpty()) return "";
String commentNewline = (style == DocCommentStyle.ASTRISK_MARGIN) ? "\n * " : "\n";
String schemadoc = wrap(escape(doc)).replaceAll("\\n", commentNewline);
StringBuilder builder = new StringBuilder();
builder.append("/**\n");
if (style == DocCommentStyle.ASTRISK_MARGIN) builder.append(" * ");
builder.append(schemadoc).append("\n");
if (style == DocCommentStyle.ASTRISK_MARGIN) builder.append(" ");
builder.append("*/");
return builder.toString();
} | [
"public",
"static",
"String",
"stringToDocComment",
"(",
"String",
"doc",
",",
"DocCommentStyle",
"style",
")",
"{",
"if",
"(",
"doc",
"==",
"null",
"||",
"doc",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"return",
"\"\"",
";",
"String",
"co... | Returns a doc comment, as a string of source, for the given documentation string
and deprecated property.
@param doc provides the schemadoc for the symbol, if any. May be null.
@return an escaped schemadoc string. | [
"Returns",
"a",
"doc",
"comment",
"as",
"a",
"string",
"of",
"source",
"for",
"the",
"given",
"documentation",
"string",
"and",
"deprecated",
"property",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/lang/DocEscaping.java#L30-L42 | train |
coursera/courier | android/generator/src/main/java/org/coursera/courier/android/JavadocEscaping.java | JavadocEscaping.stringToJavadoc | public static String stringToJavadoc(String doc, Object deprecatedProp) {
boolean emptyDoc = (doc == null || doc.trim().isEmpty());
boolean emptyDeprecated = (deprecatedProp == null || !(deprecatedProp instanceof String));
if (emptyDoc && emptyDeprecated) return "";
String javadocBody = emptyDoc ? "" : (doc + "\n");
String deprecated = (emptyDeprecated) ? "" : ("@deprecated " + deprecatedProp + "\n");
String text = javadocBody + deprecated;
return DocEscaping.stringToDocComment(text, DocCommentStyle.ASTRISK_MARGIN);
} | java | public static String stringToJavadoc(String doc, Object deprecatedProp) {
boolean emptyDoc = (doc == null || doc.trim().isEmpty());
boolean emptyDeprecated = (deprecatedProp == null || !(deprecatedProp instanceof String));
if (emptyDoc && emptyDeprecated) return "";
String javadocBody = emptyDoc ? "" : (doc + "\n");
String deprecated = (emptyDeprecated) ? "" : ("@deprecated " + deprecatedProp + "\n");
String text = javadocBody + deprecated;
return DocEscaping.stringToDocComment(text, DocCommentStyle.ASTRISK_MARGIN);
} | [
"public",
"static",
"String",
"stringToJavadoc",
"(",
"String",
"doc",
",",
"Object",
"deprecatedProp",
")",
"{",
"boolean",
"emptyDoc",
"=",
"(",
"doc",
"==",
"null",
"||",
"doc",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
";",
"boolean",
"... | Returns a javadoc comment, as a string of java source, for the given documentation string
and deprecated property.
@param doc provides the javadoc for the symbol, if any. May be null.
@param deprecatedProp provides the deprecated Pegasus schema property, if any. May be a
Boolean, a String, or null.
@return an escaped javadoc string. | [
"Returns",
"a",
"javadoc",
"comment",
"as",
"a",
"string",
"of",
"java",
"source",
"for",
"the",
"given",
"documentation",
"string",
"and",
"deprecated",
"property",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/android/generator/src/main/java/org/coursera/courier/android/JavadocEscaping.java#L34-L45 | train |
coursera/courier | android/generator/src/main/java/org/coursera/courier/android/JavaSyntax.java | JavaSyntax.hashCodeList | public String hashCodeList(List<RecordTemplateSpec.Field> fields) {
StringBuilder sb = new StringBuilder();
Iterator<RecordTemplateSpec.Field> iter = fields.iterator();
while(iter.hasNext()) {
RecordTemplateSpec.Field field = iter.next();
Type schemaType = field.getSchemaField().getType().getType();
sb.append(escapeKeyword(field.getSchemaField().getName()));
if (iter.hasNext()) sb.append(", ");
}
return sb.toString();
} | java | public String hashCodeList(List<RecordTemplateSpec.Field> fields) {
StringBuilder sb = new StringBuilder();
Iterator<RecordTemplateSpec.Field> iter = fields.iterator();
while(iter.hasNext()) {
RecordTemplateSpec.Field field = iter.next();
Type schemaType = field.getSchemaField().getType().getType();
sb.append(escapeKeyword(field.getSchemaField().getName()));
if (iter.hasNext()) sb.append(", ");
}
return sb.toString();
} | [
"public",
"String",
"hashCodeList",
"(",
"List",
"<",
"RecordTemplateSpec",
".",
"Field",
">",
"fields",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"Iterator",
"<",
"RecordTemplateSpec",
".",
"Field",
">",
"iter",
"=",
"fiel... | Returns Java source code that computes the hashCodes of each of the fields, as a list of
parameters.
This is the same as {@link #fieldList} except when the fields are Java arrays, in which
case they are wrapped with a utilty method to hash them correctly. E.g.
<code>
intField, stringField, mapField, Arrays.deepHashCode(javaArrayField), recordField
</code>
@param fields provides the fields to include in the hashcode expression.
@return a java expression that calculates a hash code. | [
"Returns",
"Java",
"source",
"code",
"that",
"computes",
"the",
"hashCodes",
"of",
"each",
"of",
"the",
"fields",
"as",
"a",
"list",
"of",
"parameters",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/android/generator/src/main/java/org/coursera/courier/android/JavaSyntax.java#L293-L303 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/ClassTemplateSpecs.java | ClassTemplateSpecs.allReferencedTypes | public static Set<ClassTemplateSpec> allReferencedTypes(ClassTemplateSpec spec) {
return findAllReferencedTypes(
directReferencedTypes(spec),
Collections.<ClassTemplateSpec>emptySet(),
Collections.<ClassTemplateSpec>emptySet());
} | java | public static Set<ClassTemplateSpec> allReferencedTypes(ClassTemplateSpec spec) {
return findAllReferencedTypes(
directReferencedTypes(spec),
Collections.<ClassTemplateSpec>emptySet(),
Collections.<ClassTemplateSpec>emptySet());
} | [
"public",
"static",
"Set",
"<",
"ClassTemplateSpec",
">",
"allReferencedTypes",
"(",
"ClassTemplateSpec",
"spec",
")",
"{",
"return",
"findAllReferencedTypes",
"(",
"directReferencedTypes",
"(",
"spec",
")",
",",
"Collections",
".",
"<",
"ClassTemplateSpec",
">",
"e... | Return all types directly or transitively referenced by this type. | [
"Return",
"all",
"types",
"directly",
"or",
"transitively",
"referenced",
"by",
"this",
"type",
"."
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/ClassTemplateSpecs.java#L113-L118 | train |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/ClassTemplateSpecs.java | ClassTemplateSpecs.findAllReferencedTypes | private static Set<ClassTemplateSpec> findAllReferencedTypes(
Set<ClassTemplateSpec> current,
Set<ClassTemplateSpec> visited,
Set<ClassTemplateSpec> acc) {
//val nextUnvisited = current.flatMap(_.directReferencedTypes).filterNot(visited.contains);
Set<ClassTemplateSpec> nextUnvisited = new HashSet<ClassTemplateSpec>();
for (ClassTemplateSpec currentSpec: current) {
for (ClassTemplateSpec maybeNext: directReferencedTypes(currentSpec)) {
if (!visited.contains(maybeNext)) {
nextUnvisited.add(maybeNext);
}
}
}
Set<ClassTemplateSpec> accAndCurrent = new HashSet<ClassTemplateSpec>(acc);
accAndCurrent.addAll(current);
if (nextUnvisited.size() > 0) {
Set<ClassTemplateSpec> currentAndVisited = new HashSet<ClassTemplateSpec>(current);
currentAndVisited.addAll(visited);
return findAllReferencedTypes(nextUnvisited, currentAndVisited, accAndCurrent);
} else {
return accAndCurrent;
}
} | java | private static Set<ClassTemplateSpec> findAllReferencedTypes(
Set<ClassTemplateSpec> current,
Set<ClassTemplateSpec> visited,
Set<ClassTemplateSpec> acc) {
//val nextUnvisited = current.flatMap(_.directReferencedTypes).filterNot(visited.contains);
Set<ClassTemplateSpec> nextUnvisited = new HashSet<ClassTemplateSpec>();
for (ClassTemplateSpec currentSpec: current) {
for (ClassTemplateSpec maybeNext: directReferencedTypes(currentSpec)) {
if (!visited.contains(maybeNext)) {
nextUnvisited.add(maybeNext);
}
}
}
Set<ClassTemplateSpec> accAndCurrent = new HashSet<ClassTemplateSpec>(acc);
accAndCurrent.addAll(current);
if (nextUnvisited.size() > 0) {
Set<ClassTemplateSpec> currentAndVisited = new HashSet<ClassTemplateSpec>(current);
currentAndVisited.addAll(visited);
return findAllReferencedTypes(nextUnvisited, currentAndVisited, accAndCurrent);
} else {
return accAndCurrent;
}
} | [
"private",
"static",
"Set",
"<",
"ClassTemplateSpec",
">",
"findAllReferencedTypes",
"(",
"Set",
"<",
"ClassTemplateSpec",
">",
"current",
",",
"Set",
"<",
"ClassTemplateSpec",
">",
"visited",
",",
"Set",
"<",
"ClassTemplateSpec",
">",
"acc",
")",
"{",
"//val ne... | traverses the directReferencedTypes graph, keeping track of already visited ClassTemplateSpecs | [
"traverses",
"the",
"directReferencedTypes",
"graph",
"keeping",
"track",
"of",
"already",
"visited",
"ClassTemplateSpecs"
] | 749674fa7ee33804ad11b6c8ecb560f455cb4c22 | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/ClassTemplateSpecs.java#L121-L147 | train |
guardtime/ksi-java-sdk | ksi-blocksigner/src/main/java/com/guardtime/ksi/tree/BlindingMaskLinkingHashTreeBuilder.java | BlindingMaskLinkingHashTreeBuilder.add | @Override
public void add(ImprintNode node) {
Util.notNull(node, "Node");
if (node.getLevel() != 0) {
throw new IllegalArgumentException("ImprintNode with level greater than 0 is not supported by BlindingMaskLinkingHashTreeBuilder");
}
ImprintNode newNode = calculateNewNode(node);
hashTreeBuilder.add(newNode);
previousBlockHash = new DataHash(newNode.getValue());
} | java | @Override
public void add(ImprintNode node) {
Util.notNull(node, "Node");
if (node.getLevel() != 0) {
throw new IllegalArgumentException("ImprintNode with level greater than 0 is not supported by BlindingMaskLinkingHashTreeBuilder");
}
ImprintNode newNode = calculateNewNode(node);
hashTreeBuilder.add(newNode);
previousBlockHash = new DataHash(newNode.getValue());
} | [
"@",
"Override",
"public",
"void",
"add",
"(",
"ImprintNode",
"node",
")",
"{",
"Util",
".",
"notNull",
"(",
"node",
",",
"\"Node\"",
")",
";",
"if",
"(",
"node",
".",
"getLevel",
"(",
")",
"!=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException... | Adds a new node to the tree.
@param node a leaf to add to the tree, must not be null. The level of the node must be 0.
@throws IllegalArgumentException if node level is greater than 0. | [
"Adds",
"a",
"new",
"node",
"to",
"the",
"tree",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-blocksigner/src/main/java/com/guardtime/ksi/tree/BlindingMaskLinkingHashTreeBuilder.java#L129-L138 | train |
guardtime/ksi-java-sdk | ksi-blocksigner/src/main/java/com/guardtime/ksi/tree/BlindingMaskLinkingHashTreeBuilder.java | BlindingMaskLinkingHashTreeBuilder.calculateHeight | @Override
public long calculateHeight(ImprintNode node) {
Util.notNull(node, "Node");
return hashTreeBuilder.calculateHeight(calculateNewNode(node));
} | java | @Override
public long calculateHeight(ImprintNode node) {
Util.notNull(node, "Node");
return hashTreeBuilder.calculateHeight(calculateNewNode(node));
} | [
"@",
"Override",
"public",
"long",
"calculateHeight",
"(",
"ImprintNode",
"node",
")",
"{",
"Util",
".",
"notNull",
"(",
"node",
",",
"\"Node\"",
")",
";",
"return",
"hashTreeBuilder",
".",
"calculateHeight",
"(",
"calculateNewNode",
"(",
"node",
")",
")",
"... | Calculates the binary tree height if new leaf would be added.
@param node a leaf to be added to the tree, must not be null. The level of the node must be 0.
@return Hash tree height.
@throws IllegalArgumentException if node level is greater than 0. | [
"Calculates",
"the",
"binary",
"tree",
"height",
"if",
"new",
"leaf",
"would",
"be",
"added",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-blocksigner/src/main/java/com/guardtime/ksi/tree/BlindingMaskLinkingHashTreeBuilder.java#L156-L160 | train |
guardtime/ksi-java-sdk | ksi-blocksigner/src/main/java/com/guardtime/ksi/tree/BlindingMaskLinkingHashTreeBuilder.java | BlindingMaskLinkingHashTreeBuilder.add | @Override
public void add(ImprintNode... nodes) {
Util.notNull(nodes, "Nodes");
for (ImprintNode node : nodes) {
add(node);
}
} | java | @Override
public void add(ImprintNode... nodes) {
Util.notNull(nodes, "Nodes");
for (ImprintNode node : nodes) {
add(node);
}
} | [
"@",
"Override",
"public",
"void",
"add",
"(",
"ImprintNode",
"...",
"nodes",
")",
"{",
"Util",
".",
"notNull",
"(",
"nodes",
",",
"\"Nodes\"",
")",
";",
"for",
"(",
"ImprintNode",
"node",
":",
"nodes",
")",
"{",
"add",
"(",
"node",
")",
";",
"}",
... | Adds a new list of leaves to the binary tree.
@param nodes a list of leaves to be added to the tree, must not be null.
@throws IllegalArgumentException if node level is greater than 0. | [
"Adds",
"a",
"new",
"list",
"of",
"leaves",
"to",
"the",
"binary",
"tree",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-blocksigner/src/main/java/com/guardtime/ksi/tree/BlindingMaskLinkingHashTreeBuilder.java#L177-L183 | train |
guardtime/ksi-java-sdk | ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/SigningHAServiceConfigurationListener.java | SigningHAServiceConfigurationListener.getAggregationConfiguration | Future<AggregatorConfiguration> getAggregationConfiguration() {
return new HAConfFuture<>(invokeSubServiceConfUpdates(),
new HAConfFuture.ConfResultSupplier<ConsolidatedResult<AggregatorConfiguration>>() {
public ConsolidatedResult<AggregatorConfiguration> get() {
return lastConsolidatedConfiguration;
}
});
} | java | Future<AggregatorConfiguration> getAggregationConfiguration() {
return new HAConfFuture<>(invokeSubServiceConfUpdates(),
new HAConfFuture.ConfResultSupplier<ConsolidatedResult<AggregatorConfiguration>>() {
public ConsolidatedResult<AggregatorConfiguration> get() {
return lastConsolidatedConfiguration;
}
});
} | [
"Future",
"<",
"AggregatorConfiguration",
">",
"getAggregationConfiguration",
"(",
")",
"{",
"return",
"new",
"HAConfFuture",
"<>",
"(",
"invokeSubServiceConfUpdates",
"(",
")",
",",
"new",
"HAConfFuture",
".",
"ConfResultSupplier",
"<",
"ConsolidatedResult",
"<",
"Ag... | Gets the aggregator's configuration. Invokes configuration updates for all the subclients.
@return {@link Future} which eventually provides subconfiguration's consolidation result. | [
"Gets",
"the",
"aggregator",
"s",
"configuration",
".",
"Invokes",
"configuration",
"updates",
"for",
"all",
"the",
"subclients",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/SigningHAServiceConfigurationListener.java#L70-L77 | train |
guardtime/ksi-java-sdk | ksi-api/src/main/java/com/guardtime/ksi/publication/inmemory/InMemoryPublicationsFileFactory.java | InMemoryPublicationsFileFactory.create | public PublicationsFile create(InputStream input) throws KSIException {
InMemoryPublicationsFile publicationsFile = new InMemoryPublicationsFile(input);
CMSSignature signature = publicationsFile.getSignature();
CMSSignatureVerifier verifier = new CMSSignatureVerifier(trustStore);
verifier.verify(signature);
return publicationsFile;
} | java | public PublicationsFile create(InputStream input) throws KSIException {
InMemoryPublicationsFile publicationsFile = new InMemoryPublicationsFile(input);
CMSSignature signature = publicationsFile.getSignature();
CMSSignatureVerifier verifier = new CMSSignatureVerifier(trustStore);
verifier.verify(signature);
return publicationsFile;
} | [
"public",
"PublicationsFile",
"create",
"(",
"InputStream",
"input",
")",
"throws",
"KSIException",
"{",
"InMemoryPublicationsFile",
"publicationsFile",
"=",
"new",
"InMemoryPublicationsFile",
"(",
"input",
")",
";",
"CMSSignature",
"signature",
"=",
"publicationsFile",
... | This method is used to read publications file from input stream. Input stream must be present and must be signed
by trusted PKI certificate.
@param input
input stream to be used to read publications file data
@return returns instance of {@link PublicationsFile}
@throws KSIException
when error occurs | [
"This",
"method",
"is",
"used",
"to",
"read",
"publications",
"file",
"from",
"input",
"stream",
".",
"Input",
"stream",
"must",
"be",
"present",
"and",
"must",
"be",
"signed",
"by",
"trusted",
"PKI",
"certificate",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/publication/inmemory/InMemoryPublicationsFileFactory.java#L58-L65 | train |
guardtime/ksi-java-sdk | ksi-api/src/main/java/com/guardtime/ksi/unisignature/inmemory/InMemoryKsiSignature.java | InMemoryKsiSignature.calculateCalendarHashChainOutput | private void calculateCalendarHashChainOutput() throws KSIException {
ChainResult lastRes = null;
for (AggregationHashChain chain : aggregationChains) {
if (lastRes == null) {
lastRes = chain.calculateOutputHash(0L);
} else {
lastRes = chain.calculateOutputHash(lastRes.getLevel());
}
LOGGER.debug("Output hash of chain: {} is {}", chain, lastRes.getOutputHash());
}
} | java | private void calculateCalendarHashChainOutput() throws KSIException {
ChainResult lastRes = null;
for (AggregationHashChain chain : aggregationChains) {
if (lastRes == null) {
lastRes = chain.calculateOutputHash(0L);
} else {
lastRes = chain.calculateOutputHash(lastRes.getLevel());
}
LOGGER.debug("Output hash of chain: {} is {}", chain, lastRes.getOutputHash());
}
} | [
"private",
"void",
"calculateCalendarHashChainOutput",
"(",
")",
"throws",
"KSIException",
"{",
"ChainResult",
"lastRes",
"=",
"null",
";",
"for",
"(",
"AggregationHashChain",
"chain",
":",
"aggregationChains",
")",
"{",
"if",
"(",
"lastRes",
"==",
"null",
")",
... | This method is used to verify signature consistency. | [
"This",
"method",
"is",
"used",
"to",
"verify",
"signature",
"consistency",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/unisignature/inmemory/InMemoryKsiSignature.java#L140-L150 | train |
guardtime/ksi-java-sdk | ksi-api/src/main/java/com/guardtime/ksi/unisignature/inmemory/InMemoryKsiSignature.java | InMemoryKsiSignature.sortAggregationHashChains | private List<AggregationHashChain> sortAggregationHashChains(List<AggregationHashChain> chains) throws InvalidSignatureException {
Collections.sort(chains, new Comparator<AggregationHashChain>() {
public int compare(AggregationHashChain chain1, AggregationHashChain chain2) {
return chain2.getChainIndex().size() - chain1.getChainIndex().size();
}
});
return chains;
} | java | private List<AggregationHashChain> sortAggregationHashChains(List<AggregationHashChain> chains) throws InvalidSignatureException {
Collections.sort(chains, new Comparator<AggregationHashChain>() {
public int compare(AggregationHashChain chain1, AggregationHashChain chain2) {
return chain2.getChainIndex().size() - chain1.getChainIndex().size();
}
});
return chains;
} | [
"private",
"List",
"<",
"AggregationHashChain",
">",
"sortAggregationHashChains",
"(",
"List",
"<",
"AggregationHashChain",
">",
"chains",
")",
"throws",
"InvalidSignatureException",
"{",
"Collections",
".",
"sort",
"(",
"chains",
",",
"new",
"Comparator",
"<",
"Agg... | Orders aggregation chains.
@param chains
aggregation chains to be ordered.
@return ordered list of aggregation chains | [
"Orders",
"aggregation",
"chains",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/unisignature/inmemory/InMemoryKsiSignature.java#L230-L237 | train |
guardtime/ksi-java-sdk | ksi-service-client/src/main/java/com/guardtime/ksi/pdu/v1/AbstractKSIResponse.java | AbstractKSIResponse.validateMac | private void validateMac(byte[] key, HashAlgorithm hmacAlgorithm) throws KSIException {
try {
HashAlgorithm receivedHmacAlgorithm = mac.getAlgorithm();
if (receivedHmacAlgorithm != hmacAlgorithm) {
throw new KSIException(
"HMAC algorithm mismatch. Expected " + hmacAlgorithm.getName() + ", received " + receivedHmacAlgorithm.getName());
}
// calculate and set the MAC value
DataHash macValue = new DataHash(hmacAlgorithm, Util.calculateHMAC(getContent(), key, hmacAlgorithm.getName()));
if (!mac.equals(macValue)) {
throw new InvalidMessageAuthenticationCodeException("Invalid MAC code. Expected " + mac + ", calculated " + macValue);
}
} catch (IOException e) {
throw new InvalidMessageAuthenticationCodeException("IO Exception occurred turning MAC calculation", e);
} catch (InvalidKeyException e) {
throw new InvalidMessageAuthenticationCodeException("Problem with HMAC key.", e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidMessageAuthenticationCodeException("Unsupported HMAC algorithm.", e);
} catch (HashException e) {
throw new KSIProtocolException("Hashing exception occurred when calculating KSI service response HMAC", e);
}
} | java | private void validateMac(byte[] key, HashAlgorithm hmacAlgorithm) throws KSIException {
try {
HashAlgorithm receivedHmacAlgorithm = mac.getAlgorithm();
if (receivedHmacAlgorithm != hmacAlgorithm) {
throw new KSIException(
"HMAC algorithm mismatch. Expected " + hmacAlgorithm.getName() + ", received " + receivedHmacAlgorithm.getName());
}
// calculate and set the MAC value
DataHash macValue = new DataHash(hmacAlgorithm, Util.calculateHMAC(getContent(), key, hmacAlgorithm.getName()));
if (!mac.equals(macValue)) {
throw new InvalidMessageAuthenticationCodeException("Invalid MAC code. Expected " + mac + ", calculated " + macValue);
}
} catch (IOException e) {
throw new InvalidMessageAuthenticationCodeException("IO Exception occurred turning MAC calculation", e);
} catch (InvalidKeyException e) {
throw new InvalidMessageAuthenticationCodeException("Problem with HMAC key.", e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidMessageAuthenticationCodeException("Unsupported HMAC algorithm.", e);
} catch (HashException e) {
throw new KSIProtocolException("Hashing exception occurred when calculating KSI service response HMAC", e);
}
} | [
"private",
"void",
"validateMac",
"(",
"byte",
"[",
"]",
"key",
",",
"HashAlgorithm",
"hmacAlgorithm",
")",
"throws",
"KSIException",
"{",
"try",
"{",
"HashAlgorithm",
"receivedHmacAlgorithm",
"=",
"mac",
".",
"getAlgorithm",
"(",
")",
";",
"if",
"(",
"receive... | Checks the MAC code.
@param key
key to be used to calculate MAC code.
@param hmacAlgorithm
algorithm for verifying the HMAC of incoming messages.
@throws KSIException
when MAC code doesn't validate | [
"Checks",
"the",
"MAC",
"code",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client/src/main/java/com/guardtime/ksi/pdu/v1/AbstractKSIResponse.java#L147-L168 | train |
guardtime/ksi-java-sdk | ksi-service-client/src/main/java/com/guardtime/ksi/pdu/v1/AbstractKSIResponse.java | AbstractKSIResponse.throwErrorPayloadException | private void throwErrorPayloadException(TLVElement child) throws KSIException {
TLVElement errorCodeElement = child.getFirstChildElement(ELEMENT_TYPE_ERROR_CODE);
TLVElement messageElement = child.getFirstChildElement(ELEMENT_TYPE_ERROR_MESSAGE);
throw new KSIProtocolException(errorCodeElement.getDecodedLong(), "Response error " + errorCodeElement.getDecodedLong() + ": "
+ messageElement.getDecodedString());
} | java | private void throwErrorPayloadException(TLVElement child) throws KSIException {
TLVElement errorCodeElement = child.getFirstChildElement(ELEMENT_TYPE_ERROR_CODE);
TLVElement messageElement = child.getFirstChildElement(ELEMENT_TYPE_ERROR_MESSAGE);
throw new KSIProtocolException(errorCodeElement.getDecodedLong(), "Response error " + errorCodeElement.getDecodedLong() + ": "
+ messageElement.getDecodedString());
} | [
"private",
"void",
"throwErrorPayloadException",
"(",
"TLVElement",
"child",
")",
"throws",
"KSIException",
"{",
"TLVElement",
"errorCodeElement",
"=",
"child",
".",
"getFirstChildElement",
"(",
"ELEMENT_TYPE_ERROR_CODE",
")",
";",
"TLVElement",
"messageElement",
"=",
"... | Reads error code and error message elements from given TLV element and throws KSI protocol exception containing
error information.
@param child
KSI protocol error element.
@throws KSIProtocolException
will always be thrown. | [
"Reads",
"error",
"code",
"and",
"error",
"message",
"elements",
"from",
"given",
"TLV",
"element",
"and",
"throws",
"KSI",
"protocol",
"exception",
"containing",
"error",
"information",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client/src/main/java/com/guardtime/ksi/pdu/v1/AbstractKSIResponse.java#L179-L184 | train |
guardtime/ksi-java-sdk | ksi-api/src/main/java/com/guardtime/ksi/unisignature/verifier/rules/CalendarHashChainRegistrationTimeRule.java | CalendarHashChainRegistrationTimeRule.calculateRegistrationTime | private Date calculateRegistrationTime(CalendarHashChain calendarHashChain) throws InvalidCalendarHashChainException {
List<CalendarHashChainLink> chain = calendarHashChain.getChainLinks();
long r = calendarHashChain.getPublicationTime().getTime() / 1000; // publication time in seconds
long t = 0;
// iterate over the chain in reverse
ListIterator<CalendarHashChainLink> li = chain.listIterator(chain.size());
while (li.hasPrevious()) {
if (r <= 0) {
LOGGER.warn("Calendar hash chain shape is inconsistent with publication time");
r = 0;
return new Date(0);
}
CalendarHashChainLink link = li.previous();
if (!link.isRightLink()) {
r = highBit(r) - 1;
} else {
t = t + highBit(r);
r = r - highBit(r);
}
}
if (r != 0) {
LOGGER.warn("Calendar hash chain shape inconsistent with publication time");
t = 0;
}
return new Date(t*1000);
} | java | private Date calculateRegistrationTime(CalendarHashChain calendarHashChain) throws InvalidCalendarHashChainException {
List<CalendarHashChainLink> chain = calendarHashChain.getChainLinks();
long r = calendarHashChain.getPublicationTime().getTime() / 1000; // publication time in seconds
long t = 0;
// iterate over the chain in reverse
ListIterator<CalendarHashChainLink> li = chain.listIterator(chain.size());
while (li.hasPrevious()) {
if (r <= 0) {
LOGGER.warn("Calendar hash chain shape is inconsistent with publication time");
r = 0;
return new Date(0);
}
CalendarHashChainLink link = li.previous();
if (!link.isRightLink()) {
r = highBit(r) - 1;
} else {
t = t + highBit(r);
r = r - highBit(r);
}
}
if (r != 0) {
LOGGER.warn("Calendar hash chain shape inconsistent with publication time");
t = 0;
}
return new Date(t*1000);
} | [
"private",
"Date",
"calculateRegistrationTime",
"(",
"CalendarHashChain",
"calendarHashChain",
")",
"throws",
"InvalidCalendarHashChainException",
"{",
"List",
"<",
"CalendarHashChainLink",
">",
"chain",
"=",
"calendarHashChain",
".",
"getChainLinks",
"(",
")",
";",
"long... | Calculates the time when the signature was registered in the KSI hash calendar. | [
"Calculates",
"the",
"time",
"when",
"the",
"signature",
"was",
"registered",
"in",
"the",
"KSI",
"hash",
"calendar",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/unisignature/verifier/rules/CalendarHashChainRegistrationTimeRule.java#L67-L95 | train |
guardtime/ksi-java-sdk | ksi-api/src/main/java/com/guardtime/ksi/unisignature/inmemory/InMemoryAggregationHashChain.java | InMemoryAggregationHashChain.calculateOutputHash | public final ChainResult calculateOutputHash(long level) throws KSIException {
// TODO task KSIJAVAAPI-207 If the aggregation hash chain component contains the `input data' field, hash the value part of the field
// using the hash algorithm specified by the first octet of the `input hash' field and verify that the result of
// hashing `input data' equals `input hash'; terminate with a consistency error if they do not match.(spec. 4.1.1.2)
// TODO task KSIJAVAAPI-207 if current aggregation hash chain isn't the first component of the hash chain and the chain
// contains 'input data' field then terminate with a format error. (spec 4.1.1.2)
DataHash lastHash = inputHash;
long currentLevel = level;
for (AggregationChainLink aggregationChainLink : chain) {
ChainResult step = aggregationChainLink.calculateChainStep(lastHash.getImprint(), currentLevel, aggregationAlgorithm);
lastHash = step.getOutputHash();
currentLevel = step.getLevel();
}
this.outputHash = lastHash;
return new InMemoryChainResult(lastHash, currentLevel);
} | java | public final ChainResult calculateOutputHash(long level) throws KSIException {
// TODO task KSIJAVAAPI-207 If the aggregation hash chain component contains the `input data' field, hash the value part of the field
// using the hash algorithm specified by the first octet of the `input hash' field and verify that the result of
// hashing `input data' equals `input hash'; terminate with a consistency error if they do not match.(spec. 4.1.1.2)
// TODO task KSIJAVAAPI-207 if current aggregation hash chain isn't the first component of the hash chain and the chain
// contains 'input data' field then terminate with a format error. (spec 4.1.1.2)
DataHash lastHash = inputHash;
long currentLevel = level;
for (AggregationChainLink aggregationChainLink : chain) {
ChainResult step = aggregationChainLink.calculateChainStep(lastHash.getImprint(), currentLevel, aggregationAlgorithm);
lastHash = step.getOutputHash();
currentLevel = step.getLevel();
}
this.outputHash = lastHash;
return new InMemoryChainResult(lastHash, currentLevel);
} | [
"public",
"final",
"ChainResult",
"calculateOutputHash",
"(",
"long",
"level",
")",
"throws",
"KSIException",
"{",
"// TODO task KSIJAVAAPI-207 If the aggregation hash chain component contains the `input data' field, hash the value part of the field",
"// using the hash algorithm specified b... | Calculate hash chain output hash.
@param level
hash chain level
@return hash chain result | [
"Calculate",
"hash",
"chain",
"output",
"hash",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/unisignature/inmemory/InMemoryAggregationHashChain.java#L140-L157 | train |
guardtime/ksi-java-sdk | ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/ExtendingHAServiceConfigurationListener.java | ExtendingHAServiceConfigurationListener.getExtensionConfiguration | Future<ExtenderConfiguration> getExtensionConfiguration() {
return new HAConfFuture<>(invokeSubserviceConfUpdates(),
new HAConfFuture.ConfResultSupplier<ConsolidatedResult<ExtenderConfiguration>>() {
public ConsolidatedResult<ExtenderConfiguration> get() {
return lastConsolidatedConfiguration;
}
});
} | java | Future<ExtenderConfiguration> getExtensionConfiguration() {
return new HAConfFuture<>(invokeSubserviceConfUpdates(),
new HAConfFuture.ConfResultSupplier<ConsolidatedResult<ExtenderConfiguration>>() {
public ConsolidatedResult<ExtenderConfiguration> get() {
return lastConsolidatedConfiguration;
}
});
} | [
"Future",
"<",
"ExtenderConfiguration",
">",
"getExtensionConfiguration",
"(",
")",
"{",
"return",
"new",
"HAConfFuture",
"<>",
"(",
"invokeSubserviceConfUpdates",
"(",
")",
",",
"new",
"HAConfFuture",
".",
"ConfResultSupplier",
"<",
"ConsolidatedResult",
"<",
"Extend... | Gets the extender's configuration. Invokes configuration updates for all the subclients.
@return {@link Future} which eventually provides subconfigurations consolidation result. | [
"Gets",
"the",
"extender",
"s",
"configuration",
".",
"Invokes",
"configuration",
"updates",
"for",
"all",
"the",
"subclients",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/ExtendingHAServiceConfigurationListener.java#L70-L77 | train |
guardtime/ksi-java-sdk | ksi-service-client/src/main/java/com/guardtime/ksi/service/ConfigurationHandler.java | ConfigurationHandler.doConfigurationUpdate | public Future<T> doConfigurationUpdate(final ConfigurationRequest<T> configurationRequest) {
Util.notNull(configurationRequest, "ConfigurationRequest passed to ConfigurationHandler");
return executorService.submit(new Callable<T>() {
public T call() throws Exception {
try {
T conf = configurationRequest.invoke();
updateListenersWithNewConfiguration(conf);
return conf;
} catch (Exception e) {
updateListenersWithFailure(e);
throw e;
}
}
});
} | java | public Future<T> doConfigurationUpdate(final ConfigurationRequest<T> configurationRequest) {
Util.notNull(configurationRequest, "ConfigurationRequest passed to ConfigurationHandler");
return executorService.submit(new Callable<T>() {
public T call() throws Exception {
try {
T conf = configurationRequest.invoke();
updateListenersWithNewConfiguration(conf);
return conf;
} catch (Exception e) {
updateListenersWithFailure(e);
throw e;
}
}
});
} | [
"public",
"Future",
"<",
"T",
">",
"doConfigurationUpdate",
"(",
"final",
"ConfigurationRequest",
"<",
"T",
">",
"configurationRequest",
")",
"{",
"Util",
".",
"notNull",
"(",
"configurationRequest",
",",
"\"ConfigurationRequest passed to ConfigurationHandler\"",
")",
"... | Invokes a configuration request and updates listeners asynchronously.
@param configurationRequest may not be null. | [
"Invokes",
"a",
"configuration",
"request",
"and",
"updates",
"listeners",
"asynchronously",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client/src/main/java/com/guardtime/ksi/service/ConfigurationHandler.java#L69-L83 | train |
guardtime/ksi-java-sdk | ksi-service-client/src/main/java/com/guardtime/ksi/service/ConfigurationHandler.java | ConfigurationHandler.updateListenersWithNewConfiguration | void updateListenersWithNewConfiguration(T newConfiguration) {
for (ConfigurationListener<T> listener : listeners) {
try {
listener.updated(newConfiguration);
} catch (Exception e) {
logger.error("Updating a listener with new configuration failed.", e);
}
}
} | java | void updateListenersWithNewConfiguration(T newConfiguration) {
for (ConfigurationListener<T> listener : listeners) {
try {
listener.updated(newConfiguration);
} catch (Exception e) {
logger.error("Updating a listener with new configuration failed.", e);
}
}
} | [
"void",
"updateListenersWithNewConfiguration",
"(",
"T",
"newConfiguration",
")",
"{",
"for",
"(",
"ConfigurationListener",
"<",
"T",
">",
"listener",
":",
"listeners",
")",
"{",
"try",
"{",
"listener",
".",
"updated",
"(",
"newConfiguration",
")",
";",
"}",
"... | Updates listeners with provided configuration
@param newConfiguration configuration to be applied | [
"Updates",
"listeners",
"with",
"provided",
"configuration"
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client/src/main/java/com/guardtime/ksi/service/ConfigurationHandler.java#L90-L98 | train |
guardtime/ksi-java-sdk | ksi-service-client/src/main/java/com/guardtime/ksi/service/ConfigurationHandler.java | ConfigurationHandler.updateListenersWithFailure | void updateListenersWithFailure(Throwable t) {
for (ConfigurationListener<T> listener : listeners) {
try {
listener.updateFailed(t);
} catch (Exception e) {
logger.error("Updating a listener with configuration request failure failed.", e);
}
}
} | java | void updateListenersWithFailure(Throwable t) {
for (ConfigurationListener<T> listener : listeners) {
try {
listener.updateFailed(t);
} catch (Exception e) {
logger.error("Updating a listener with configuration request failure failed.", e);
}
}
} | [
"void",
"updateListenersWithFailure",
"(",
"Throwable",
"t",
")",
"{",
"for",
"(",
"ConfigurationListener",
"<",
"T",
">",
"listener",
":",
"listeners",
")",
"{",
"try",
"{",
"listener",
".",
"updateFailed",
"(",
"t",
")",
";",
"}",
"catch",
"(",
"Exceptio... | Updates listeners with failure
@param t reason | [
"Updates",
"listeners",
"with",
"failure"
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client/src/main/java/com/guardtime/ksi/service/ConfigurationHandler.java#L105-L113 | train |
guardtime/ksi-java-sdk | ksi-service-client-apache-http/src/main/java/com/guardtime/ksi/service/client/http/apache/AbstractApacheHttpClient.java | AbstractApacheHttpClient.createClient | private CloseableHttpAsyncClient createClient(HttpSettings settings, ApacheHttpClientConfiguration conf) {
IOReactorConfig ioReactor = IOReactorConfig.custom().setIoThreadCount(conf.getMaxThreadCount()).build();
HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom()
.useSystemProperties()
// allow POST redirects
.setRedirectStrategy(new LaxRedirectStrategy()).setMaxConnTotal(conf.getMaxTotalConnectionCount()).setMaxConnPerRoute(conf.getMaxRouteConnectionCount()).setDefaultIOReactorConfig(ioReactor)
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setDefaultRequestConfig(createDefaultRequestConfig(settings));
if (settings.getProxyUrl() != null) {
DefaultProxyRoutePlanner routePlanner = createProxyRoutePlanner(settings, httpClientBuilder);
httpClientBuilder.setRoutePlanner(routePlanner);
}
CloseableHttpAsyncClient httpClient = httpClientBuilder.build();
httpClient.start();
return httpClient;
} | java | private CloseableHttpAsyncClient createClient(HttpSettings settings, ApacheHttpClientConfiguration conf) {
IOReactorConfig ioReactor = IOReactorConfig.custom().setIoThreadCount(conf.getMaxThreadCount()).build();
HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom()
.useSystemProperties()
// allow POST redirects
.setRedirectStrategy(new LaxRedirectStrategy()).setMaxConnTotal(conf.getMaxTotalConnectionCount()).setMaxConnPerRoute(conf.getMaxRouteConnectionCount()).setDefaultIOReactorConfig(ioReactor)
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setDefaultRequestConfig(createDefaultRequestConfig(settings));
if (settings.getProxyUrl() != null) {
DefaultProxyRoutePlanner routePlanner = createProxyRoutePlanner(settings, httpClientBuilder);
httpClientBuilder.setRoutePlanner(routePlanner);
}
CloseableHttpAsyncClient httpClient = httpClientBuilder.build();
httpClient.start();
return httpClient;
} | [
"private",
"CloseableHttpAsyncClient",
"createClient",
"(",
"HttpSettings",
"settings",
",",
"ApacheHttpClientConfiguration",
"conf",
")",
"{",
"IOReactorConfig",
"ioReactor",
"=",
"IOReactorConfig",
".",
"custom",
"(",
")",
".",
"setIoThreadCount",
"(",
"conf",
".",
... | Creates asynchronous Apache HTTP client.
@param settings
settings to use to create client.
@param conf
configuration related to async connection.
@return Instance of {@link CloseableHttpAsyncClient}. | [
"Creates",
"asynchronous",
"Apache",
"HTTP",
"client",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client-apache-http/src/main/java/com/guardtime/ksi/service/client/http/apache/AbstractApacheHttpClient.java#L128-L142 | train |
guardtime/ksi-java-sdk | ksi-service-client-apache-http/src/main/java/com/guardtime/ksi/service/client/http/apache/AbstractApacheHttpClient.java | AbstractApacheHttpClient.createProxyRoutePlanner | private DefaultProxyRoutePlanner createProxyRoutePlanner(HttpSettings settings, HttpAsyncClientBuilder httpClientBuilder) {
HttpHost proxy = new HttpHost(settings.getProxyUrl().getHost(), settings.getProxyUrl().getPort());
if (settings.getProxyUser() != null) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
String proxyUser = settings.getProxyUser();
String proxyPassword = settings.getProxyPassword();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
credentialsProvider.setCredentials(new AuthScope(proxy), credentials);
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
return new DefaultProxyRoutePlanner(proxy);
} | java | private DefaultProxyRoutePlanner createProxyRoutePlanner(HttpSettings settings, HttpAsyncClientBuilder httpClientBuilder) {
HttpHost proxy = new HttpHost(settings.getProxyUrl().getHost(), settings.getProxyUrl().getPort());
if (settings.getProxyUser() != null) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
String proxyUser = settings.getProxyUser();
String proxyPassword = settings.getProxyPassword();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
credentialsProvider.setCredentials(new AuthScope(proxy), credentials);
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
return new DefaultProxyRoutePlanner(proxy);
} | [
"private",
"DefaultProxyRoutePlanner",
"createProxyRoutePlanner",
"(",
"HttpSettings",
"settings",
",",
"HttpAsyncClientBuilder",
"httpClientBuilder",
")",
"{",
"HttpHost",
"proxy",
"=",
"new",
"HttpHost",
"(",
"settings",
".",
"getProxyUrl",
"(",
")",
".",
"getHost",
... | Creates default proxy route planner.
@param settings
settings to use.
@param httpClientBuilder
http client builder.
@return Instance of {@link DefaultProxyRoutePlanner}. | [
"Creates",
"default",
"proxy",
"route",
"planner",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client-apache-http/src/main/java/com/guardtime/ksi/service/client/http/apache/AbstractApacheHttpClient.java#L153-L164 | train |
guardtime/ksi-java-sdk | ksi-service-client-apache-http/src/main/java/com/guardtime/ksi/service/client/http/apache/AbstractApacheHttpClient.java | AbstractApacheHttpClient.createDefaultRequestConfig | private RequestConfig createDefaultRequestConfig(HttpSettings settings) {
int connectionTimeout = settings.getConnectionTimeout();
int socketTimeout = settings.getReadTimeout();
return RequestConfig.custom().setConnectionRequestTimeout(connectionTimeout).setSocketTimeout(socketTimeout).build();
} | java | private RequestConfig createDefaultRequestConfig(HttpSettings settings) {
int connectionTimeout = settings.getConnectionTimeout();
int socketTimeout = settings.getReadTimeout();
return RequestConfig.custom().setConnectionRequestTimeout(connectionTimeout).setSocketTimeout(socketTimeout).build();
} | [
"private",
"RequestConfig",
"createDefaultRequestConfig",
"(",
"HttpSettings",
"settings",
")",
"{",
"int",
"connectionTimeout",
"=",
"settings",
".",
"getConnectionTimeout",
"(",
")",
";",
"int",
"socketTimeout",
"=",
"settings",
".",
"getReadTimeout",
"(",
")",
";... | Creates default request config.
@param settings
settings to use.
@return instance of {@link RequestConfig}. | [
"Creates",
"default",
"request",
"config",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client-apache-http/src/main/java/com/guardtime/ksi/service/client/http/apache/AbstractApacheHttpClient.java#L173-L177 | train |
guardtime/ksi-java-sdk | ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/ExtendingHAService.java | ExtendingHAService.extend | public Future<ExtensionResponse> extend(Date aggregationTime, Date publicationTime) throws KSIException {
Util.notNull(aggregationTime, "aggregationTime");
Collection<KSIExtendingService> services = subservices;
Collection<Callable<ExtensionResponse>> tasks = new ArrayList<>(services.size());
for (KSIExtendingService service : services) {
tasks.add(new ExtendingTask(service, aggregationTime, publicationTime));
}
return new ServiceCallFuture<>(
executorService.submit(new ServiceCallsTask<>(executorService, tasks))
);
} | java | public Future<ExtensionResponse> extend(Date aggregationTime, Date publicationTime) throws KSIException {
Util.notNull(aggregationTime, "aggregationTime");
Collection<KSIExtendingService> services = subservices;
Collection<Callable<ExtensionResponse>> tasks = new ArrayList<>(services.size());
for (KSIExtendingService service : services) {
tasks.add(new ExtendingTask(service, aggregationTime, publicationTime));
}
return new ServiceCallFuture<>(
executorService.submit(new ServiceCallsTask<>(executorService, tasks))
);
} | [
"public",
"Future",
"<",
"ExtensionResponse",
">",
"extend",
"(",
"Date",
"aggregationTime",
",",
"Date",
"publicationTime",
")",
"throws",
"KSIException",
"{",
"Util",
".",
"notNull",
"(",
"aggregationTime",
",",
"\"aggregationTime\"",
")",
";",
"Collection",
"<"... | Creates a non-blocking extending request. Sends the request to all the subservices in parallel. First successful response is
used, others are cancelled. Request fails only if all the subservices fail.
@see KSIExtendingService#extend(Date, Date) | [
"Creates",
"a",
"non",
"-",
"blocking",
"extending",
"request",
".",
"Sends",
"the",
"request",
"to",
"all",
"the",
"subservices",
"in",
"parallel",
".",
"First",
"successful",
"response",
"is",
"used",
"others",
"are",
"cancelled",
".",
"Request",
"fails",
... | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/ExtendingHAService.java#L71-L81 | train |
guardtime/ksi-java-sdk | ksi-service-client-tcp/src/main/java/com/guardtime/ksi/service/tcp/KSITCPRequestFuture.java | KSITCPRequestFuture.getResult | public synchronized TLVElement getResult() throws KSITCPTransactionException {
if (finished) {
if (response != null) {
return response;
}
if (exception != null) {
throw exception;
}
}
return blockUntilTransactionFinished();
} | java | public synchronized TLVElement getResult() throws KSITCPTransactionException {
if (finished) {
if (response != null) {
return response;
}
if (exception != null) {
throw exception;
}
}
return blockUntilTransactionFinished();
} | [
"public",
"synchronized",
"TLVElement",
"getResult",
"(",
")",
"throws",
"KSITCPTransactionException",
"{",
"if",
"(",
"finished",
")",
"{",
"if",
"(",
"response",
"!=",
"null",
")",
"{",
"return",
"response",
";",
"}",
"if",
"(",
"exception",
"!=",
"null",
... | Blocks until response timeout occurs or the response arrives.
@return Bytes of the TCP response. | [
"Blocks",
"until",
"response",
"timeout",
"occurs",
"or",
"the",
"response",
"arrives",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client-tcp/src/main/java/com/guardtime/ksi/service/tcp/KSITCPRequestFuture.java#L66-L76 | train |
guardtime/ksi-java-sdk | ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java | HAConfUtil.isBigger | static boolean isBigger(Long a, Long b) {
return a == null || (b != null && b > a);
} | java | static boolean isBigger(Long a, Long b) {
return a == null || (b != null && b > a);
} | [
"static",
"boolean",
"isBigger",
"(",
"Long",
"a",
",",
"Long",
"b",
")",
"{",
"return",
"a",
"==",
"null",
"||",
"(",
"b",
"!=",
"null",
"&&",
"b",
">",
"a",
")",
";",
"}"
] | Is value of b bigger than value of a.
@return True, if b is bigger than a. Always true, if value of a is null. | [
"Is",
"value",
"of",
"b",
"bigger",
"than",
"value",
"of",
"a",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java#L34-L36 | train |
guardtime/ksi-java-sdk | ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java | HAConfUtil.isSmaller | static boolean isSmaller(Long a, Long b) {
return a == null || (b != null && b < a);
} | java | static boolean isSmaller(Long a, Long b) {
return a == null || (b != null && b < a);
} | [
"static",
"boolean",
"isSmaller",
"(",
"Long",
"a",
",",
"Long",
"b",
")",
"{",
"return",
"a",
"==",
"null",
"||",
"(",
"b",
"!=",
"null",
"&&",
"b",
"<",
"a",
")",
";",
"}"
] | Is value of b smaller than value of a.
@return True, if b is smaller than a. Always true, if value of a is null. | [
"Is",
"value",
"of",
"b",
"smaller",
"than",
"value",
"of",
"a",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java#L43-L45 | train |
guardtime/ksi-java-sdk | ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java | HAConfUtil.isAfter | static boolean isAfter(Date a, Date b) {
return a == null || (b != null && b.after(a));
} | java | static boolean isAfter(Date a, Date b) {
return a == null || (b != null && b.after(a));
} | [
"static",
"boolean",
"isAfter",
"(",
"Date",
"a",
",",
"Date",
"b",
")",
"{",
"return",
"a",
"==",
"null",
"||",
"(",
"b",
"!=",
"null",
"&&",
"b",
".",
"after",
"(",
"a",
")",
")",
";",
"}"
] | Is value of b after value of a.
@return True, if b is after a. Always true, if value of a is null. | [
"Is",
"value",
"of",
"b",
"after",
"value",
"of",
"a",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java#L52-L54 | train |
guardtime/ksi-java-sdk | ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java | HAConfUtil.isBefore | static boolean isBefore(Date a, Date b) {
return a == null || (b != null && b.before(a));
} | java | static boolean isBefore(Date a, Date b) {
return a == null || (b != null && b.before(a));
} | [
"static",
"boolean",
"isBefore",
"(",
"Date",
"a",
",",
"Date",
"b",
")",
"{",
"return",
"a",
"==",
"null",
"||",
"(",
"b",
"!=",
"null",
"&&",
"b",
".",
"before",
"(",
"a",
")",
")",
";",
"}"
] | Is value of b before value of a.
@return True, if b is before a. Always true, if value of a is null. | [
"Is",
"value",
"of",
"b",
"before",
"value",
"of",
"a",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java#L61-L63 | train |
guardtime/ksi-java-sdk | ksi-blocksigner/src/main/java/com/guardtime/ksi/blocksigner/KsiBlockSigner.java | KsiBlockSigner.sign | public List<KSISignature> sign() throws KSIException {
TreeNode rootNode = treeBuilder.build();
logger.debug("Root node calculated. {}(level={})", new DataHash(rootNode.getValue()), rootNode.getLevel());
KSISignature rootNodeSignature = signRootNode(rootNode);
if (leafs.size() == 1 && !leafs.get(0).hasMetadata()) {
return Collections.singletonList(rootNodeSignature);
}
List<KSISignature> signatures = new LinkedList<>();
AggregationHashChainBuilder chainBuilder = new AggregationHashChainBuilder();
for (ImprintNode leaf : leafs) {
signatures.add(signatureFactory.createSignature(rootNodeSignature, chainBuilder.build(leaf), new DataHash(leaf.getValue())));
}
return signatures;
} | java | public List<KSISignature> sign() throws KSIException {
TreeNode rootNode = treeBuilder.build();
logger.debug("Root node calculated. {}(level={})", new DataHash(rootNode.getValue()), rootNode.getLevel());
KSISignature rootNodeSignature = signRootNode(rootNode);
if (leafs.size() == 1 && !leafs.get(0).hasMetadata()) {
return Collections.singletonList(rootNodeSignature);
}
List<KSISignature> signatures = new LinkedList<>();
AggregationHashChainBuilder chainBuilder = new AggregationHashChainBuilder();
for (ImprintNode leaf : leafs) {
signatures.add(signatureFactory.createSignature(rootNodeSignature, chainBuilder.build(leaf), new DataHash(leaf.getValue())));
}
return signatures;
} | [
"public",
"List",
"<",
"KSISignature",
">",
"sign",
"(",
")",
"throws",
"KSIException",
"{",
"TreeNode",
"rootNode",
"=",
"treeBuilder",
".",
"build",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"\"Root node calculated. {}(level={})\"",
",",
"new",
"DataHash",
... | Creates a block of multiple signatures.
@return Multiple signatures, according to number of input hashes.
@throws KSIException | [
"Creates",
"a",
"block",
"of",
"multiple",
"signatures",
"."
] | b2cd877050f0f392657c724452318d10a1002171 | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-blocksigner/src/main/java/com/guardtime/ksi/blocksigner/KsiBlockSigner.java#L268-L281 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.