id
int32 0
165k
| repo
stringlengths 7
58
| path
stringlengths 12
218
| func_name
stringlengths 3
140
| original_string
stringlengths 73
34.1k
| language
stringclasses 1
value | code
stringlengths 73
34.1k
| code_tokens
sequence | docstring
stringlengths 3
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 105
339
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,000 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/CMMLHelper.java | CMMLHelper.getFirstNode | public static Node getFirstNode(String mathml) {
try {
// get the apply node of the ContentMathML root
return getFirstNode(new CMMLInfo(mathml));
} catch (Exception e) {
logger.error("failed to get apply node", e);
return null;
}
} | java | public static Node getFirstNode(String mathml) {
try {
// get the apply node of the ContentMathML root
return getFirstNode(new CMMLInfo(mathml));
} catch (Exception e) {
logger.error("failed to get apply node", e);
return null;
}
} | [
"public",
"static",
"Node",
"getFirstNode",
"(",
"String",
"mathml",
")",
"{",
"try",
"{",
"// get the apply node of the ContentMathML root",
"return",
"getFirstNode",
"(",
"new",
"CMMLInfo",
"(",
"mathml",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"failed to get apply node\"",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Get the first node of the MathML-Content annotations within a MathML document.
@param mathml full MathML document
@return first node of the MathML-Content annotations within a MathML document | [
"Get",
"the",
"first",
"node",
"of",
"the",
"MathML",
"-",
"Content",
"annotations",
"within",
"a",
"MathML",
"document",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/CMMLHelper.java#L48-L56 |
2,001 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/CMMLHelper.java | CMMLHelper.getStrictCmml | public static Node getStrictCmml(String mathml) {
try {
// get ContentMathML to Strict ContentMathML and finally the abstract CD
CMMLInfo cmmlInfo = new CMMLInfo(mathml).toStrictCmml();
/*
Don't use:
Abstract2CD nicht benutzen! Sobald ein Knoten tatsächlich umbenannt
wird, verliert dieser Knoten alle Kinder! Stattdessen kann auf dem
späteren MathNode ein separater toAbstract aufruf erfolgen.
*/
// and finally only get the first apply node of the ContentMathML
return getFirstApplyNode(cmmlInfo);
} catch (Exception e) {
logger.error("failed to get apply node", e);
return null;
}
} | java | public static Node getStrictCmml(String mathml) {
try {
// get ContentMathML to Strict ContentMathML and finally the abstract CD
CMMLInfo cmmlInfo = new CMMLInfo(mathml).toStrictCmml();
/*
Don't use:
Abstract2CD nicht benutzen! Sobald ein Knoten tatsächlich umbenannt
wird, verliert dieser Knoten alle Kinder! Stattdessen kann auf dem
späteren MathNode ein separater toAbstract aufruf erfolgen.
*/
// and finally only get the first apply node of the ContentMathML
return getFirstApplyNode(cmmlInfo);
} catch (Exception e) {
logger.error("failed to get apply node", e);
return null;
}
} | [
"public",
"static",
"Node",
"getStrictCmml",
"(",
"String",
"mathml",
")",
"{",
"try",
"{",
"// get ContentMathML to Strict ContentMathML and finally the abstract CD",
"CMMLInfo",
"cmmlInfo",
"=",
"new",
"CMMLInfo",
"(",
"mathml",
")",
".",
"toStrictCmml",
"(",
")",
";",
"/*\n Don't use:\n Abstract2CD nicht benutzen! Sobald ein Knoten tatsächlich umbenannt\n wird, verliert dieser Knoten alle Kinder! Stattdessen kann auf dem\n späteren MathNode ein separater toAbstract aufruf erfolgen.\n */",
"// and finally only get the first apply node of the ContentMathML",
"return",
"getFirstApplyNode",
"(",
"cmmlInfo",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"failed to get apply node\"",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Get the first node of the MathML-Content annotations within a MathML document.
Before, the MathML document was converted to strict CMML and subsequently also converted
to display only the abstract variation of the content dictionary.
@param mathml full MathML document
@return first node of the MathML-Content annotations within a MathML document | [
"Get",
"the",
"first",
"node",
"of",
"the",
"MathML",
"-",
"Content",
"annotations",
"within",
"a",
"MathML",
"document",
".",
"Before",
"the",
"MathML",
"document",
"was",
"converted",
"to",
"strict",
"CMML",
"and",
"subsequently",
"also",
"converted",
"to",
"display",
"only",
"the",
"abstract",
"variation",
"of",
"the",
"content",
"dictionary",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/CMMLHelper.java#L66-L84 |
2,002 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/CMMLHelper.java | CMMLHelper.getElement | public static Node getElement(Node node, String xExpr, XPath xPath) throws XPathExpressionException {
return (Node) xPath.compile(xExpr).evaluate(node, XPathConstants.NODE);
} | java | public static Node getElement(Node node, String xExpr, XPath xPath) throws XPathExpressionException {
return (Node) xPath.compile(xExpr).evaluate(node, XPathConstants.NODE);
} | [
"public",
"static",
"Node",
"getElement",
"(",
"Node",
"node",
",",
"String",
"xExpr",
",",
"XPath",
"xPath",
")",
"throws",
"XPathExpressionException",
"{",
"return",
"(",
"Node",
")",
"xPath",
".",
"compile",
"(",
"xExpr",
")",
".",
"evaluate",
"(",
"node",
",",
"XPathConstants",
".",
"NODE",
")",
";",
"}"
] | Extracts a single node for the specified XPath expression.
@param node the node
@param xExpr expression
@param xPath the x path
@return Node
@throws XPathExpressionException the xpath expression exception | [
"Extracts",
"a",
"single",
"node",
"for",
"the",
"specified",
"XPath",
"expression",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/CMMLHelper.java#L144-L146 |
2,003 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java | MathMLConverter.transform | public String transform(Element formulaNode) throws Exception, MathConverterException {
// 1a. consolidate on the default mathml namespace
formulaNode = consolidateMathMLNamespace(formulaNode);
// 1b. scan the inner content format
Content content = scanFormulaNode(formulaNode);
String rawMathML;
if (content == Content.pmml || content == Content.cmml || content == Content.mathml) {
// 2a. grab the "math" root element
Element mathEle = grabMathElement(formulaNode);
formulaId = mathEle.getAttribute("id");
if (formulaId.equals("")) {
try {
Element applyNode = (Element) XMLHelper.getElementB(formulaNode, xPath.compile("//m:apply"));
formulaId = applyNode.getAttribute("id");
} catch (Exception e) {
logger.trace("can not find apply node ", e);
}
}
formulaName = mathEle.getAttribute("name");
// 2b. try to bring the content into our desired well formatted mathml
rawMathML = transformMML(mathEle, content);
} else if (content == Content.latex) {
// 3a. per default we try to convert it via LaTeXML
rawMathML = convertLatex(formulaNode.getTextContent());
} else {
throw new MathConverterException("formula contains unknown or not recognized content");
}
// 4. canonicalize and verify the mathml output
return verifyMathML(canonicalize(rawMathML));
} | java | public String transform(Element formulaNode) throws Exception, MathConverterException {
// 1a. consolidate on the default mathml namespace
formulaNode = consolidateMathMLNamespace(formulaNode);
// 1b. scan the inner content format
Content content = scanFormulaNode(formulaNode);
String rawMathML;
if (content == Content.pmml || content == Content.cmml || content == Content.mathml) {
// 2a. grab the "math" root element
Element mathEle = grabMathElement(formulaNode);
formulaId = mathEle.getAttribute("id");
if (formulaId.equals("")) {
try {
Element applyNode = (Element) XMLHelper.getElementB(formulaNode, xPath.compile("//m:apply"));
formulaId = applyNode.getAttribute("id");
} catch (Exception e) {
logger.trace("can not find apply node ", e);
}
}
formulaName = mathEle.getAttribute("name");
// 2b. try to bring the content into our desired well formatted mathml
rawMathML = transformMML(mathEle, content);
} else if (content == Content.latex) {
// 3a. per default we try to convert it via LaTeXML
rawMathML = convertLatex(formulaNode.getTextContent());
} else {
throw new MathConverterException("formula contains unknown or not recognized content");
}
// 4. canonicalize and verify the mathml output
return verifyMathML(canonicalize(rawMathML));
} | [
"public",
"String",
"transform",
"(",
"Element",
"formulaNode",
")",
"throws",
"Exception",
",",
"MathConverterException",
"{",
"// 1a. consolidate on the default mathml namespace",
"formulaNode",
"=",
"consolidateMathMLNamespace",
"(",
"formulaNode",
")",
";",
"// 1b. scan the inner content format",
"Content",
"content",
"=",
"scanFormulaNode",
"(",
"formulaNode",
")",
";",
"String",
"rawMathML",
";",
"if",
"(",
"content",
"==",
"Content",
".",
"pmml",
"||",
"content",
"==",
"Content",
".",
"cmml",
"||",
"content",
"==",
"Content",
".",
"mathml",
")",
"{",
"// 2a. grab the \"math\" root element",
"Element",
"mathEle",
"=",
"grabMathElement",
"(",
"formulaNode",
")",
";",
"formulaId",
"=",
"mathEle",
".",
"getAttribute",
"(",
"\"id\"",
")",
";",
"if",
"(",
"formulaId",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"try",
"{",
"Element",
"applyNode",
"=",
"(",
"Element",
")",
"XMLHelper",
".",
"getElementB",
"(",
"formulaNode",
",",
"xPath",
".",
"compile",
"(",
"\"//m:apply\"",
")",
")",
";",
"formulaId",
"=",
"applyNode",
".",
"getAttribute",
"(",
"\"id\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"trace",
"(",
"\"can not find apply node \"",
",",
"e",
")",
";",
"}",
"}",
"formulaName",
"=",
"mathEle",
".",
"getAttribute",
"(",
"\"name\"",
")",
";",
"// 2b. try to bring the content into our desired well formatted mathml",
"rawMathML",
"=",
"transformMML",
"(",
"mathEle",
",",
"content",
")",
";",
"}",
"else",
"if",
"(",
"content",
"==",
"Content",
".",
"latex",
")",
"{",
"// 3a. per default we try to convert it via LaTeXML",
"rawMathML",
"=",
"convertLatex",
"(",
"formulaNode",
".",
"getTextContent",
"(",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"MathConverterException",
"(",
"\"formula contains unknown or not recognized content\"",
")",
";",
"}",
"// 4. canonicalize and verify the mathml output",
"return",
"verifyMathML",
"(",
"canonicalize",
"(",
"rawMathML",
")",
")",
";",
"}"
] | This method will scan the formula node, extract necessary information
and transform is into a well formatted MathML string containing the
desired pMML and cMML semantics.
@param formulaNode formula node to be inspected and transformed.
@return MathML string
@throws Exception fatal error in the process
@throws MathConverterException transformation process failed | [
"This",
"method",
"will",
"scan",
"the",
"formula",
"node",
"extract",
"necessary",
"information",
"and",
"transform",
"is",
"into",
"a",
"well",
"formatted",
"MathML",
"string",
"containing",
"the",
"desired",
"pMML",
"and",
"cMML",
"semantics",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java#L84-L115 |
2,004 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java | MathMLConverter.verifyMathML | String verifyMathML(String canMathML) throws MathConverterException {
try {
Document tempDoc = XMLHelper.string2Doc(canMathML, true);
Content content = scanFormulaNode((Element) tempDoc.getFirstChild());
//verify the formula
if (content == Content.mathml) {
return canMathML;
} else {
throw new MathConverterException("could not verify produced mathml, content was: " + content.name());
}
} catch (Exception e) {
logger.error("could not verify mathml", e);
throw new MathConverterException("could not verify mathml");
}
} | java | String verifyMathML(String canMathML) throws MathConverterException {
try {
Document tempDoc = XMLHelper.string2Doc(canMathML, true);
Content content = scanFormulaNode((Element) tempDoc.getFirstChild());
//verify the formula
if (content == Content.mathml) {
return canMathML;
} else {
throw new MathConverterException("could not verify produced mathml, content was: " + content.name());
}
} catch (Exception e) {
logger.error("could not verify mathml", e);
throw new MathConverterException("could not verify mathml");
}
} | [
"String",
"verifyMathML",
"(",
"String",
"canMathML",
")",
"throws",
"MathConverterException",
"{",
"try",
"{",
"Document",
"tempDoc",
"=",
"XMLHelper",
".",
"string2Doc",
"(",
"canMathML",
",",
"true",
")",
";",
"Content",
"content",
"=",
"scanFormulaNode",
"(",
"(",
"Element",
")",
"tempDoc",
".",
"getFirstChild",
"(",
")",
")",
";",
"//verify the formula",
"if",
"(",
"content",
"==",
"Content",
".",
"mathml",
")",
"{",
"return",
"canMathML",
";",
"}",
"else",
"{",
"throw",
"new",
"MathConverterException",
"(",
"\"could not verify produced mathml, content was: \"",
"+",
"content",
".",
"name",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"could not verify mathml\"",
",",
"e",
")",
";",
"throw",
"new",
"MathConverterException",
"(",
"\"could not verify mathml\"",
")",
";",
"}",
"}"
] | Just a quick scan over.
@param canMathML final mathml to be inspected
@return returns input string
@throws MathConverterException if it is not a well-structured mathml | [
"Just",
"a",
"quick",
"scan",
"over",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java#L125-L139 |
2,005 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java | MathMLConverter.grabMathElement | private Element grabMathElement(Element formulaNode) throws XPathExpressionException, MathConverterException {
Element mathEle = Optional.ofNullable((Element) XMLHelper.getElementB(formulaNode, xPath.compile("./*[1]")))
.orElseThrow(() -> new MathConverterException("no math element found"));
// check for the "math" root element
if (mathEle.getNodeName().toLowerCase().contains("math")) {
// no math element present
return mathEle;
}
throw new MathConverterException("no math element found");
} | java | private Element grabMathElement(Element formulaNode) throws XPathExpressionException, MathConverterException {
Element mathEle = Optional.ofNullable((Element) XMLHelper.getElementB(formulaNode, xPath.compile("./*[1]")))
.orElseThrow(() -> new MathConverterException("no math element found"));
// check for the "math" root element
if (mathEle.getNodeName().toLowerCase().contains("math")) {
// no math element present
return mathEle;
}
throw new MathConverterException("no math element found");
} | [
"private",
"Element",
"grabMathElement",
"(",
"Element",
"formulaNode",
")",
"throws",
"XPathExpressionException",
",",
"MathConverterException",
"{",
"Element",
"mathEle",
"=",
"Optional",
".",
"ofNullable",
"(",
"(",
"Element",
")",
"XMLHelper",
".",
"getElementB",
"(",
"formulaNode",
",",
"xPath",
".",
"compile",
"(",
"\"./*[1]\"",
")",
")",
")",
".",
"orElseThrow",
"(",
"(",
")",
"->",
"new",
"MathConverterException",
"(",
"\"no math element found\"",
")",
")",
";",
"// check for the \"math\" root element",
"if",
"(",
"mathEle",
".",
"getNodeName",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"contains",
"(",
"\"math\"",
")",
")",
"{",
"// no math element present",
"return",
"mathEle",
";",
"}",
"throw",
"new",
"MathConverterException",
"(",
"\"no math element found\"",
")",
";",
"}"
] | Tries to get the math element which should be next child
following the formula node.
@param formulaNode formula element
@return the subsequent math element
@throws XPathExpressionException should not happen or code error
@throws MathConverterException math element not found | [
"Tries",
"to",
"get",
"the",
"math",
"element",
"which",
"should",
"be",
"next",
"child",
"following",
"the",
"formula",
"node",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java#L150-L159 |
2,006 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java | MathMLConverter.consolidateMathMLNamespace | Element consolidateMathMLNamespace(Element mathNode) throws MathConverterException {
try {
Document tempDoc;
if (isNsAware(mathNode)) {
tempDoc = mathNode.getOwnerDocument();
} else {
tempDoc = XMLHelper.string2Doc(XMLHelper.printDocument(mathNode), true);
}
// rename namespaces and set a new default namespace
new XmlNamespaceTranslator()
.setDefaultNamespace(DEFAULT_NAMESPACE)
.addTranslation("m", "http://www.w3.org/1998/Math/MathML")
.addTranslation("mml", "http://www.w3.org/1998/Math/MathML")
.translateNamespaces(tempDoc, "");
Element root = (Element) tempDoc.getFirstChild();
removeAttribute(root, "xmlns:mml");
removeAttribute(root, "xmlns:m");
return root;
} catch (Exception e) {
logger.error("namespace consolidation failed", e);
throw new MathConverterException("namespace consolidation failed");
}
} | java | Element consolidateMathMLNamespace(Element mathNode) throws MathConverterException {
try {
Document tempDoc;
if (isNsAware(mathNode)) {
tempDoc = mathNode.getOwnerDocument();
} else {
tempDoc = XMLHelper.string2Doc(XMLHelper.printDocument(mathNode), true);
}
// rename namespaces and set a new default namespace
new XmlNamespaceTranslator()
.setDefaultNamespace(DEFAULT_NAMESPACE)
.addTranslation("m", "http://www.w3.org/1998/Math/MathML")
.addTranslation("mml", "http://www.w3.org/1998/Math/MathML")
.translateNamespaces(tempDoc, "");
Element root = (Element) tempDoc.getFirstChild();
removeAttribute(root, "xmlns:mml");
removeAttribute(root, "xmlns:m");
return root;
} catch (Exception e) {
logger.error("namespace consolidation failed", e);
throw new MathConverterException("namespace consolidation failed");
}
} | [
"Element",
"consolidateMathMLNamespace",
"(",
"Element",
"mathNode",
")",
"throws",
"MathConverterException",
"{",
"try",
"{",
"Document",
"tempDoc",
";",
"if",
"(",
"isNsAware",
"(",
"mathNode",
")",
")",
"{",
"tempDoc",
"=",
"mathNode",
".",
"getOwnerDocument",
"(",
")",
";",
"}",
"else",
"{",
"tempDoc",
"=",
"XMLHelper",
".",
"string2Doc",
"(",
"XMLHelper",
".",
"printDocument",
"(",
"mathNode",
")",
",",
"true",
")",
";",
"}",
"// rename namespaces and set a new default namespace",
"new",
"XmlNamespaceTranslator",
"(",
")",
".",
"setDefaultNamespace",
"(",
"DEFAULT_NAMESPACE",
")",
".",
"addTranslation",
"(",
"\"m\"",
",",
"\"http://www.w3.org/1998/Math/MathML\"",
")",
".",
"addTranslation",
"(",
"\"mml\"",
",",
"\"http://www.w3.org/1998/Math/MathML\"",
")",
".",
"translateNamespaces",
"(",
"tempDoc",
",",
"\"\"",
")",
";",
"Element",
"root",
"=",
"(",
"Element",
")",
"tempDoc",
".",
"getFirstChild",
"(",
")",
";",
"removeAttribute",
"(",
"root",
",",
"\"xmlns:mml\"",
")",
";",
"removeAttribute",
"(",
"root",
",",
"\"xmlns:m\"",
")",
";",
"return",
"root",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"namespace consolidation failed\"",
",",
"e",
")",
";",
"throw",
"new",
"MathConverterException",
"(",
"\"namespace consolidation failed\"",
")",
";",
"}",
"}"
] | Should consolidate onto the default MathML namespace.
@param mathNode root element of the document
@return return the root element of a new document
@throws MathConverterException namespace consolidation failed | [
"Should",
"consolidate",
"onto",
"the",
"default",
"MathML",
"namespace",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java#L168-L191 |
2,007 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java | MathMLConverter.scanFormulaNode | Content scanFormulaNode(Element formulaNode) throws Exception {
// first off, try scanning for a semantic split, this indicates multiple semantics
Boolean containsSemantic = XMLHelper.getElementB(formulaNode, xPath.compile("//m:semantics")) != null;
// check if there is an annotationNode and if so check which semantics are present
Element annotationNode = (Element) XMLHelper.getElementB(formulaNode, xPath.compile("//m:annotation-xml"));
Boolean containsCMML = annotationNode != null && annotationNode.getAttribute("encoding").equals("MathML-Content");
Boolean containsPMML = annotationNode != null && annotationNode.getAttribute("encoding").equals("MathML-Presentation");
// if apply are present, the content semantics is used somewhere
NonWhitespaceNodeList applyNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(formulaNode, xPath.compile("//m:apply")));
containsCMML |= applyNodes.getLength() > 0;
// if mrow nodes are present, the presentation semantic is used somewhere
NonWhitespaceNodeList mrowNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(formulaNode, xPath.compile("//m:mrow")));
containsPMML |= mrowNodes.getLength() > 0;
// TODO the containCMML and -PMML can be more specific, e.g. check if identifiers of each semantics is present
if (containsSemantic) {
// if semantic separator is present plus one opposite semantic, we assume a LaTeXML produced content
return containsCMML || containsPMML ? Content.mathml : Content.unknown;
} else {
if (containsCMML && containsPMML) {
// both semantics without semantic separator suggests broken syntax
return Content.unknown;
} else if (containsCMML) {
return Content.cmml;
} else if (containsPMML) {
return Content.pmml;
}
}
// next, try to identify latex
Element child = (Element) XMLHelper.getElementB(formulaNode, "./*[1]");
// if there is no child node, we currently anticipate some form of latex formula
if (child == null && StringUtils.isNotEmpty(formulaNode.getTextContent())) {
return Content.latex;
}
// found nothing comprehensible
return Content.unknown;
} | java | Content scanFormulaNode(Element formulaNode) throws Exception {
// first off, try scanning for a semantic split, this indicates multiple semantics
Boolean containsSemantic = XMLHelper.getElementB(formulaNode, xPath.compile("//m:semantics")) != null;
// check if there is an annotationNode and if so check which semantics are present
Element annotationNode = (Element) XMLHelper.getElementB(formulaNode, xPath.compile("//m:annotation-xml"));
Boolean containsCMML = annotationNode != null && annotationNode.getAttribute("encoding").equals("MathML-Content");
Boolean containsPMML = annotationNode != null && annotationNode.getAttribute("encoding").equals("MathML-Presentation");
// if apply are present, the content semantics is used somewhere
NonWhitespaceNodeList applyNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(formulaNode, xPath.compile("//m:apply")));
containsCMML |= applyNodes.getLength() > 0;
// if mrow nodes are present, the presentation semantic is used somewhere
NonWhitespaceNodeList mrowNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(formulaNode, xPath.compile("//m:mrow")));
containsPMML |= mrowNodes.getLength() > 0;
// TODO the containCMML and -PMML can be more specific, e.g. check if identifiers of each semantics is present
if (containsSemantic) {
// if semantic separator is present plus one opposite semantic, we assume a LaTeXML produced content
return containsCMML || containsPMML ? Content.mathml : Content.unknown;
} else {
if (containsCMML && containsPMML) {
// both semantics without semantic separator suggests broken syntax
return Content.unknown;
} else if (containsCMML) {
return Content.cmml;
} else if (containsPMML) {
return Content.pmml;
}
}
// next, try to identify latex
Element child = (Element) XMLHelper.getElementB(formulaNode, "./*[1]");
// if there is no child node, we currently anticipate some form of latex formula
if (child == null && StringUtils.isNotEmpty(formulaNode.getTextContent())) {
return Content.latex;
}
// found nothing comprehensible
return Content.unknown;
} | [
"Content",
"scanFormulaNode",
"(",
"Element",
"formulaNode",
")",
"throws",
"Exception",
"{",
"// first off, try scanning for a semantic split, this indicates multiple semantics",
"Boolean",
"containsSemantic",
"=",
"XMLHelper",
".",
"getElementB",
"(",
"formulaNode",
",",
"xPath",
".",
"compile",
"(",
"\"//m:semantics\"",
")",
")",
"!=",
"null",
";",
"// check if there is an annotationNode and if so check which semantics are present",
"Element",
"annotationNode",
"=",
"(",
"Element",
")",
"XMLHelper",
".",
"getElementB",
"(",
"formulaNode",
",",
"xPath",
".",
"compile",
"(",
"\"//m:annotation-xml\"",
")",
")",
";",
"Boolean",
"containsCMML",
"=",
"annotationNode",
"!=",
"null",
"&&",
"annotationNode",
".",
"getAttribute",
"(",
"\"encoding\"",
")",
".",
"equals",
"(",
"\"MathML-Content\"",
")",
";",
"Boolean",
"containsPMML",
"=",
"annotationNode",
"!=",
"null",
"&&",
"annotationNode",
".",
"getAttribute",
"(",
"\"encoding\"",
")",
".",
"equals",
"(",
"\"MathML-Presentation\"",
")",
";",
"// if apply are present, the content semantics is used somewhere",
"NonWhitespaceNodeList",
"applyNodes",
"=",
"new",
"NonWhitespaceNodeList",
"(",
"XMLHelper",
".",
"getElementsB",
"(",
"formulaNode",
",",
"xPath",
".",
"compile",
"(",
"\"//m:apply\"",
")",
")",
")",
";",
"containsCMML",
"|=",
"applyNodes",
".",
"getLength",
"(",
")",
">",
"0",
";",
"// if mrow nodes are present, the presentation semantic is used somewhere",
"NonWhitespaceNodeList",
"mrowNodes",
"=",
"new",
"NonWhitespaceNodeList",
"(",
"XMLHelper",
".",
"getElementsB",
"(",
"formulaNode",
",",
"xPath",
".",
"compile",
"(",
"\"//m:mrow\"",
")",
")",
")",
";",
"containsPMML",
"|=",
"mrowNodes",
".",
"getLength",
"(",
")",
">",
"0",
";",
"// TODO the containCMML and -PMML can be more specific, e.g. check if identifiers of each semantics is present",
"if",
"(",
"containsSemantic",
")",
"{",
"// if semantic separator is present plus one opposite semantic, we assume a LaTeXML produced content",
"return",
"containsCMML",
"||",
"containsPMML",
"?",
"Content",
".",
"mathml",
":",
"Content",
".",
"unknown",
";",
"}",
"else",
"{",
"if",
"(",
"containsCMML",
"&&",
"containsPMML",
")",
"{",
"// both semantics without semantic separator suggests broken syntax",
"return",
"Content",
".",
"unknown",
";",
"}",
"else",
"if",
"(",
"containsCMML",
")",
"{",
"return",
"Content",
".",
"cmml",
";",
"}",
"else",
"if",
"(",
"containsPMML",
")",
"{",
"return",
"Content",
".",
"pmml",
";",
"}",
"}",
"// next, try to identify latex",
"Element",
"child",
"=",
"(",
"Element",
")",
"XMLHelper",
".",
"getElementB",
"(",
"formulaNode",
",",
"\"./*[1]\"",
")",
";",
"// if there is no child node, we currently anticipate some form of latex formula",
"if",
"(",
"child",
"==",
"null",
"&&",
"StringUtils",
".",
"isNotEmpty",
"(",
"formulaNode",
".",
"getTextContent",
"(",
")",
")",
")",
"{",
"return",
"Content",
".",
"latex",
";",
"}",
"// found nothing comprehensible",
"return",
"Content",
".",
"unknown",
";",
"}"
] | Tries to scan and interpret a formula node and guess its content format.
@param formulaNode formula to be inspected
@return sse {@link Content} format
@throws Exception parsing error | [
"Tries",
"to",
"scan",
"and",
"interpret",
"a",
"formula",
"node",
"and",
"guess",
"its",
"content",
"format",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java#L230-L271 |
2,008 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/canonicalize/MathMLCanUtil.java | MathMLCanUtil.canonicalize | public static String canonicalize(String mathml) throws IOException, JDOMException, XMLStreamException, ModuleException {
InputStream input = IOUtils.toInputStream(mathml, StandardCharsets.UTF_8.toString());
final ByteArrayOutputStream output = new ByteArrayOutputStream();
CANONICALIZER.canonicalize(input, output);
String result = output.toString(StandardCharsets.UTF_8.toString());
// since we can't properly configure the canonicalizer we need to adjust the result string
// 1. omit xml header since it will not be used
// result = StringUtils.remove(result, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
// 2. switch to the line separator used by the system
result = result.replaceAll("\\r\\n|\\r|\\n", System.getProperty("line.separator"));
return result;
} | java | public static String canonicalize(String mathml) throws IOException, JDOMException, XMLStreamException, ModuleException {
InputStream input = IOUtils.toInputStream(mathml, StandardCharsets.UTF_8.toString());
final ByteArrayOutputStream output = new ByteArrayOutputStream();
CANONICALIZER.canonicalize(input, output);
String result = output.toString(StandardCharsets.UTF_8.toString());
// since we can't properly configure the canonicalizer we need to adjust the result string
// 1. omit xml header since it will not be used
// result = StringUtils.remove(result, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
// 2. switch to the line separator used by the system
result = result.replaceAll("\\r\\n|\\r|\\n", System.getProperty("line.separator"));
return result;
} | [
"public",
"static",
"String",
"canonicalize",
"(",
"String",
"mathml",
")",
"throws",
"IOException",
",",
"JDOMException",
",",
"XMLStreamException",
",",
"ModuleException",
"{",
"InputStream",
"input",
"=",
"IOUtils",
".",
"toInputStream",
"(",
"mathml",
",",
"StandardCharsets",
".",
"UTF_8",
".",
"toString",
"(",
")",
")",
";",
"final",
"ByteArrayOutputStream",
"output",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"CANONICALIZER",
".",
"canonicalize",
"(",
"input",
",",
"output",
")",
";",
"String",
"result",
"=",
"output",
".",
"toString",
"(",
"StandardCharsets",
".",
"UTF_8",
".",
"toString",
"(",
")",
")",
";",
"// since we can't properly configure the canonicalizer we need to adjust the result string",
"// 1. omit xml header since it will not be used",
"// result = StringUtils.remove(result, \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");",
"// 2. switch to the line separator used by the system",
"result",
"=",
"result",
".",
"replaceAll",
"(",
"\"\\\\r\\\\n|\\\\r|\\\\n\"",
",",
"System",
".",
"getProperty",
"(",
"\"line.separator\"",
")",
")",
";",
"return",
"result",
";",
"}"
] | Canonicalize an input MathML string.
Line separators are system dependant.
@param mathml MathML string
@return Canonicalized MathML string
@throws JDOMException problem with DOM
@throws IOException problem with streams
@throws ModuleException some module cannot canonicalize the input
@throws XMLStreamException an error with XML processing occurs | [
"Canonicalize",
"an",
"input",
"MathML",
"string",
".",
"Line",
"separators",
"are",
"system",
"dependant",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/canonicalize/MathMLCanUtil.java#L60-L74 |
2,009 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/XMLHelper.java | XMLHelper.getIdentifiersFrom | @SuppressWarnings("JavaDoc")
public static Multiset<String> getIdentifiersFrom(String mathml) {
Multiset<String> list = HashMultiset.create();
Pattern p = Pattern.compile("<((m:)?[mc][ion])(.*?)>(.{1,4}?)</\\1>", Pattern.DOTALL);
Matcher m = p.matcher(mathml);
while (m.find()) {
String identifier = m.group(4);
list.add(identifier);
}
return list;
} | java | @SuppressWarnings("JavaDoc")
public static Multiset<String> getIdentifiersFrom(String mathml) {
Multiset<String> list = HashMultiset.create();
Pattern p = Pattern.compile("<((m:)?[mc][ion])(.*?)>(.{1,4}?)</\\1>", Pattern.DOTALL);
Matcher m = p.matcher(mathml);
while (m.find()) {
String identifier = m.group(4);
list.add(identifier);
}
return list;
} | [
"@",
"SuppressWarnings",
"(",
"\"JavaDoc\"",
")",
"public",
"static",
"Multiset",
"<",
"String",
">",
"getIdentifiersFrom",
"(",
"String",
"mathml",
")",
"{",
"Multiset",
"<",
"String",
">",
"list",
"=",
"HashMultiset",
".",
"create",
"(",
")",
";",
"Pattern",
"p",
"=",
"Pattern",
".",
"compile",
"(",
"\"<((m:)?[mc][ion])(.*?)>(.{1,4}?)</\\\\1>\"",
",",
"Pattern",
".",
"DOTALL",
")",
";",
"Matcher",
"m",
"=",
"p",
".",
"matcher",
"(",
"mathml",
")",
";",
"while",
"(",
"m",
".",
"find",
"(",
")",
")",
"{",
"String",
"identifier",
"=",
"m",
".",
"group",
"(",
"4",
")",
";",
"list",
".",
"add",
"(",
"identifier",
")",
";",
"}",
"return",
"list",
";",
"}"
] | Returns a list of unique identifiers from a MathML string.
This function searches for all mi- or ci-tags within
the string.
@param mathml
@return a list of unique identifiers. When no identifiers were
found, an empty list will be returned. | [
"Returns",
"a",
"list",
"of",
"unique",
"identifiers",
"from",
"a",
"MathML",
"string",
".",
"This",
"function",
"searches",
"for",
"all",
"mi",
"-",
"or",
"ci",
"-",
"tags",
"within",
"the",
"string",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/XMLHelper.java#L244-L254 |
2,010 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/XMLHelper.java | XMLHelper.getMainElement | public static Node getMainElement(Document xml) {
// Try to get main mws:expr first
NodeList expr = xml.getElementsByTagName("mws:expr");
if (expr.getLength() > 0) {
return new NonWhitespaceNodeList(expr).item(0);
}
// if that fails try to get content MathML from an annotation tag
Node node = getContentMathMLNode(xml);
if (node != null) {
return node;
}
// if that fails too interprete content of first semantic element as content MathML
expr = xml.getElementsByTagNameNS("*", "semantics");
if (expr.getLength() > 0) {
return new NonWhitespaceNodeList(expr).item(0);
}
// if that fails too interprete content of root MathML element as content MathML
expr = xml.getElementsByTagName("math");
if (expr.getLength() > 0) {
return new NonWhitespaceNodeList(expr).item(0);
}
return null;
} | java | public static Node getMainElement(Document xml) {
// Try to get main mws:expr first
NodeList expr = xml.getElementsByTagName("mws:expr");
if (expr.getLength() > 0) {
return new NonWhitespaceNodeList(expr).item(0);
}
// if that fails try to get content MathML from an annotation tag
Node node = getContentMathMLNode(xml);
if (node != null) {
return node;
}
// if that fails too interprete content of first semantic element as content MathML
expr = xml.getElementsByTagNameNS("*", "semantics");
if (expr.getLength() > 0) {
return new NonWhitespaceNodeList(expr).item(0);
}
// if that fails too interprete content of root MathML element as content MathML
expr = xml.getElementsByTagName("math");
if (expr.getLength() > 0) {
return new NonWhitespaceNodeList(expr).item(0);
}
return null;
} | [
"public",
"static",
"Node",
"getMainElement",
"(",
"Document",
"xml",
")",
"{",
"// Try to get main mws:expr first",
"NodeList",
"expr",
"=",
"xml",
".",
"getElementsByTagName",
"(",
"\"mws:expr\"",
")",
";",
"if",
"(",
"expr",
".",
"getLength",
"(",
")",
">",
"0",
")",
"{",
"return",
"new",
"NonWhitespaceNodeList",
"(",
"expr",
")",
".",
"item",
"(",
"0",
")",
";",
"}",
"// if that fails try to get content MathML from an annotation tag",
"Node",
"node",
"=",
"getContentMathMLNode",
"(",
"xml",
")",
";",
"if",
"(",
"node",
"!=",
"null",
")",
"{",
"return",
"node",
";",
"}",
"// if that fails too interprete content of first semantic element as content MathML",
"expr",
"=",
"xml",
".",
"getElementsByTagNameNS",
"(",
"\"*\"",
",",
"\"semantics\"",
")",
";",
"if",
"(",
"expr",
".",
"getLength",
"(",
")",
">",
"0",
")",
"{",
"return",
"new",
"NonWhitespaceNodeList",
"(",
"expr",
")",
".",
"item",
"(",
"0",
")",
";",
"}",
"// if that fails too interprete content of root MathML element as content MathML",
"expr",
"=",
"xml",
".",
"getElementsByTagName",
"(",
"\"math\"",
")",
";",
"if",
"(",
"expr",
".",
"getLength",
"(",
")",
">",
"0",
")",
"{",
"return",
"new",
"NonWhitespaceNodeList",
"(",
"expr",
")",
".",
"item",
"(",
"0",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Returns the main element for which to begin generating the XQuery
@param xml XML Document to find main element of
@return Node for main element | [
"Returns",
"the",
"main",
"element",
"for",
"which",
"to",
"begin",
"generating",
"the",
"XQuery"
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/helper/XMLHelper.java#L403-L426 |
2,011 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/LaTeXMLConverter.java | LaTeXMLConverter.preLatexmlFixes | private static String preLatexmlFixes(String rawTex) {
Matcher matcher = LTXML_PATTERN.matcher(rawTex);
if (matcher.find()) {
rawTex = "{" + rawTex + "}";
}
return rawTex;
} | java | private static String preLatexmlFixes(String rawTex) {
Matcher matcher = LTXML_PATTERN.matcher(rawTex);
if (matcher.find()) {
rawTex = "{" + rawTex + "}";
}
return rawTex;
} | [
"private",
"static",
"String",
"preLatexmlFixes",
"(",
"String",
"rawTex",
")",
"{",
"Matcher",
"matcher",
"=",
"LTXML_PATTERN",
".",
"matcher",
"(",
"rawTex",
")",
";",
"if",
"(",
"matcher",
".",
"find",
"(",
")",
")",
"{",
"rawTex",
"=",
"\"{\"",
"+",
"rawTex",
"+",
"\"}\"",
";",
"}",
"return",
"rawTex",
";",
"}"
] | LaTeXML Bug if there is "\math" command at the beginning of the
tex expression, it needs to be wrapped in curly brackets.
@param rawTex
@return | [
"LaTeXML",
"Bug",
"if",
"there",
"is",
"\\",
"math",
"command",
"at",
"the",
"beginning",
"of",
"the",
"tex",
"expression",
"it",
"needs",
"to",
"be",
"wrapped",
"in",
"curly",
"brackets",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/LaTeXMLConverter.java#L69-L75 |
2,012 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/LaTeXMLConverter.java | LaTeXMLConverter.parseAsService | public LaTeXMLServiceResponse parseAsService(String latex) {
try {
latex = UriComponentsBuilder.newInstance().queryParam("tex", latex).build().encode(StandardCharsets.UTF_8.toString()).getQuery();
} catch (UnsupportedEncodingException ignore) {
LOG.warn("encoding not supported", ignore);
}
String serviceArguments = config.buildServiceRequest();
String payload = serviceArguments + "&" + latex;
RestTemplate restTemplate = new RestTemplate();
try {
LaTeXMLServiceResponse rep = restTemplate.postForObject(config.getUrl(), payload, LaTeXMLServiceResponse.class);
LOG.debug(String.format("LaTeXMLServiceResponse:\n"
+ "statusCode: %s\nstatus: %s\nlog: %s\nresult: %s",
rep.getStatusCode(), rep.getStatus(), rep.getLog(), rep.getResult()));
return rep;
} catch (HttpClientErrorException e) {
LOG.error(e.getResponseBodyAsString());
throw e;
}
} | java | public LaTeXMLServiceResponse parseAsService(String latex) {
try {
latex = UriComponentsBuilder.newInstance().queryParam("tex", latex).build().encode(StandardCharsets.UTF_8.toString()).getQuery();
} catch (UnsupportedEncodingException ignore) {
LOG.warn("encoding not supported", ignore);
}
String serviceArguments = config.buildServiceRequest();
String payload = serviceArguments + "&" + latex;
RestTemplate restTemplate = new RestTemplate();
try {
LaTeXMLServiceResponse rep = restTemplate.postForObject(config.getUrl(), payload, LaTeXMLServiceResponse.class);
LOG.debug(String.format("LaTeXMLServiceResponse:\n"
+ "statusCode: %s\nstatus: %s\nlog: %s\nresult: %s",
rep.getStatusCode(), rep.getStatus(), rep.getLog(), rep.getResult()));
return rep;
} catch (HttpClientErrorException e) {
LOG.error(e.getResponseBodyAsString());
throw e;
}
} | [
"public",
"LaTeXMLServiceResponse",
"parseAsService",
"(",
"String",
"latex",
")",
"{",
"try",
"{",
"latex",
"=",
"UriComponentsBuilder",
".",
"newInstance",
"(",
")",
".",
"queryParam",
"(",
"\"tex\"",
",",
"latex",
")",
".",
"build",
"(",
")",
".",
"encode",
"(",
"StandardCharsets",
".",
"UTF_8",
".",
"toString",
"(",
")",
")",
".",
"getQuery",
"(",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"ignore",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"encoding not supported\"",
",",
"ignore",
")",
";",
"}",
"String",
"serviceArguments",
"=",
"config",
".",
"buildServiceRequest",
"(",
")",
";",
"String",
"payload",
"=",
"serviceArguments",
"+",
"\"&\"",
"+",
"latex",
";",
"RestTemplate",
"restTemplate",
"=",
"new",
"RestTemplate",
"(",
")",
";",
"try",
"{",
"LaTeXMLServiceResponse",
"rep",
"=",
"restTemplate",
".",
"postForObject",
"(",
"config",
".",
"getUrl",
"(",
")",
",",
"payload",
",",
"LaTeXMLServiceResponse",
".",
"class",
")",
";",
"LOG",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"LaTeXMLServiceResponse:\\n\"",
"+",
"\"statusCode: %s\\nstatus: %s\\nlog: %s\\nresult: %s\"",
",",
"rep",
".",
"getStatusCode",
"(",
")",
",",
"rep",
".",
"getStatus",
"(",
")",
",",
"rep",
".",
"getLog",
"(",
")",
",",
"rep",
".",
"getResult",
"(",
")",
")",
")",
";",
"return",
"rep",
";",
"}",
"catch",
"(",
"HttpClientErrorException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"e",
".",
"getResponseBodyAsString",
"(",
")",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | Call a LaTeXML service.
@param latex LaTeX formula
@return MathML String | [
"Call",
"a",
"LaTeXML",
"service",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/LaTeXMLConverter.java#L215-L236 |
2,013 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/io/XmlDocumentReader.java | XmlDocumentReader.stringToSource | private static InputSource stringToSource(String str) {
InputSource is = new InputSource(new StringReader(str));
is.setEncoding("UTF-8");
return is;
} | java | private static InputSource stringToSource(String str) {
InputSource is = new InputSource(new StringReader(str));
is.setEncoding("UTF-8");
return is;
} | [
"private",
"static",
"InputSource",
"stringToSource",
"(",
"String",
"str",
")",
"{",
"InputSource",
"is",
"=",
"new",
"InputSource",
"(",
"new",
"StringReader",
"(",
"str",
")",
")",
";",
"is",
".",
"setEncoding",
"(",
"\"UTF-8\"",
")",
";",
"return",
"is",
";",
"}"
] | Convert a string to an InputSource object
@param str string
@return InputSource of input | [
"Convert",
"a",
"string",
"to",
"an",
"InputSource",
"object"
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/io/XmlDocumentReader.java#L201-L205 |
2,014 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/io/XmlDocumentReader.java | XmlDocumentReader.getStandardDocumentBuilderFactory | public static DocumentBuilderFactory getStandardDocumentBuilderFactory(boolean validating) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// enable validation (must specify a grammar)
dbf.setValidating(validating);
dbf.setFeature("http://xml.org/sax/features/validation", validating);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", validating);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", validating);
dbf.setFeature("http://apache.org/xml/features/validation/schema", true);
dbf.setFeature("http://xml.org/sax/features/namespaces", true);
dbf.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
} catch (ParserConfigurationException pce) {
throw new RuntimeException("Cannot load standard DocumentBuilderFactory. " + pce.getMessage(), pce);
}
dbf.setNamespaceAware(true);
dbf.setIgnoringComments(true);
dbf.setExpandEntityReferences(true);
return dbf;
} | java | public static DocumentBuilderFactory getStandardDocumentBuilderFactory(boolean validating) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// enable validation (must specify a grammar)
dbf.setValidating(validating);
dbf.setFeature("http://xml.org/sax/features/validation", validating);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", validating);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", validating);
dbf.setFeature("http://apache.org/xml/features/validation/schema", true);
dbf.setFeature("http://xml.org/sax/features/namespaces", true);
dbf.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
} catch (ParserConfigurationException pce) {
throw new RuntimeException("Cannot load standard DocumentBuilderFactory. " + pce.getMessage(), pce);
}
dbf.setNamespaceAware(true);
dbf.setIgnoringComments(true);
dbf.setExpandEntityReferences(true);
return dbf;
} | [
"public",
"static",
"DocumentBuilderFactory",
"getStandardDocumentBuilderFactory",
"(",
"boolean",
"validating",
")",
"{",
"DocumentBuilderFactory",
"dbf",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
"(",
")",
";",
"try",
"{",
"// enable validation (must specify a grammar)",
"dbf",
".",
"setValidating",
"(",
"validating",
")",
";",
"dbf",
".",
"setFeature",
"(",
"\"http://xml.org/sax/features/validation\"",
",",
"validating",
")",
";",
"dbf",
".",
"setFeature",
"(",
"\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\"",
",",
"validating",
")",
";",
"dbf",
".",
"setFeature",
"(",
"\"http://apache.org/xml/features/nonvalidating/load-external-dtd\"",
",",
"validating",
")",
";",
"dbf",
".",
"setFeature",
"(",
"\"http://apache.org/xml/features/validation/schema\"",
",",
"true",
")",
";",
"dbf",
".",
"setFeature",
"(",
"\"http://xml.org/sax/features/namespaces\"",
",",
"true",
")",
";",
"dbf",
".",
"setFeature",
"(",
"\"http://apache.org/xml/features/dom/include-ignorable-whitespace\"",
",",
"false",
")",
";",
"}",
"catch",
"(",
"ParserConfigurationException",
"pce",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot load standard DocumentBuilderFactory. \"",
"+",
"pce",
".",
"getMessage",
"(",
")",
",",
"pce",
")",
";",
"}",
"dbf",
".",
"setNamespaceAware",
"(",
"true",
")",
";",
"dbf",
".",
"setIgnoringComments",
"(",
"true",
")",
";",
"dbf",
".",
"setExpandEntityReferences",
"(",
"true",
")",
";",
"return",
"dbf",
";",
"}"
] | This method creates a DocumentBuilderFactory that we will always need.
@see <a href="http://xerces.apache.org/xerces-j/features.html">Apache XML Features</a>
@return the standard document builder factory we usually use | [
"This",
"method",
"creates",
"a",
"DocumentBuilderFactory",
"that",
"we",
"will",
"always",
"need",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/io/XmlDocumentReader.java#L235-L259 |
2,015 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/querygenerator/NtcirTopicReader.java | NtcirTopicReader.extractPatterns | public final List<NtcirPattern> extractPatterns() throws XPathExpressionException {
final XPath xpath = XMLHelper.namespaceAwareXpath("t", NS_NII);
final XPathExpression xNum = xpath.compile("./t:num");
final XPathExpression xFormula = xpath.compile("./t:query/t:formula");
final NonWhitespaceNodeList topicList = new NonWhitespaceNodeList(
topics.getElementsByTagNameNS(NS_NII, "topic"));
for (final Node node : topicList) {
final String num = xNum.evaluate(node);
final NonWhitespaceNodeList formulae = new NonWhitespaceNodeList((NodeList)
xFormula.evaluate(node, XPathConstants.NODESET));
for (final Node formula : formulae) {
final String id = formula.getAttributes().getNamedItem("id").getTextContent();
final Node mathMLNode = NonWhitespaceNodeList.getFirstChild(formula);
queryGenerator.setMainElement(NonWhitespaceNodeList.getFirstChild(mathMLNode));
patterns.add(new NtcirPattern(num, id, queryGenerator.toString(), mathMLNode));
}
}
return patterns;
} | java | public final List<NtcirPattern> extractPatterns() throws XPathExpressionException {
final XPath xpath = XMLHelper.namespaceAwareXpath("t", NS_NII);
final XPathExpression xNum = xpath.compile("./t:num");
final XPathExpression xFormula = xpath.compile("./t:query/t:formula");
final NonWhitespaceNodeList topicList = new NonWhitespaceNodeList(
topics.getElementsByTagNameNS(NS_NII, "topic"));
for (final Node node : topicList) {
final String num = xNum.evaluate(node);
final NonWhitespaceNodeList formulae = new NonWhitespaceNodeList((NodeList)
xFormula.evaluate(node, XPathConstants.NODESET));
for (final Node formula : formulae) {
final String id = formula.getAttributes().getNamedItem("id").getTextContent();
final Node mathMLNode = NonWhitespaceNodeList.getFirstChild(formula);
queryGenerator.setMainElement(NonWhitespaceNodeList.getFirstChild(mathMLNode));
patterns.add(new NtcirPattern(num, id, queryGenerator.toString(), mathMLNode));
}
}
return patterns;
} | [
"public",
"final",
"List",
"<",
"NtcirPattern",
">",
"extractPatterns",
"(",
")",
"throws",
"XPathExpressionException",
"{",
"final",
"XPath",
"xpath",
"=",
"XMLHelper",
".",
"namespaceAwareXpath",
"(",
"\"t\"",
",",
"NS_NII",
")",
";",
"final",
"XPathExpression",
"xNum",
"=",
"xpath",
".",
"compile",
"(",
"\"./t:num\"",
")",
";",
"final",
"XPathExpression",
"xFormula",
"=",
"xpath",
".",
"compile",
"(",
"\"./t:query/t:formula\"",
")",
";",
"final",
"NonWhitespaceNodeList",
"topicList",
"=",
"new",
"NonWhitespaceNodeList",
"(",
"topics",
".",
"getElementsByTagNameNS",
"(",
"NS_NII",
",",
"\"topic\"",
")",
")",
";",
"for",
"(",
"final",
"Node",
"node",
":",
"topicList",
")",
"{",
"final",
"String",
"num",
"=",
"xNum",
".",
"evaluate",
"(",
"node",
")",
";",
"final",
"NonWhitespaceNodeList",
"formulae",
"=",
"new",
"NonWhitespaceNodeList",
"(",
"(",
"NodeList",
")",
"xFormula",
".",
"evaluate",
"(",
"node",
",",
"XPathConstants",
".",
"NODESET",
")",
")",
";",
"for",
"(",
"final",
"Node",
"formula",
":",
"formulae",
")",
"{",
"final",
"String",
"id",
"=",
"formula",
".",
"getAttributes",
"(",
")",
".",
"getNamedItem",
"(",
"\"id\"",
")",
".",
"getTextContent",
"(",
")",
";",
"final",
"Node",
"mathMLNode",
"=",
"NonWhitespaceNodeList",
".",
"getFirstChild",
"(",
"formula",
")",
";",
"queryGenerator",
".",
"setMainElement",
"(",
"NonWhitespaceNodeList",
".",
"getFirstChild",
"(",
"mathMLNode",
")",
")",
";",
"patterns",
".",
"add",
"(",
"new",
"NtcirPattern",
"(",
"num",
",",
"id",
",",
"queryGenerator",
".",
"toString",
"(",
")",
",",
"mathMLNode",
")",
")",
";",
"}",
"}",
"return",
"patterns",
";",
"}"
] | Splits the given NTCIR query file into individual queries, converts each query into an XQuery using
QVarXQueryGenerator, and returns the result as a list of NtcirPatterns for each individual query.
@return List of NtcirPatterns for each query
@throws XPathExpressionException Thrown if xpaths fail to compile or fail to evaluate
+ | [
"Splits",
"the",
"given",
"NTCIR",
"query",
"file",
"into",
"individual",
"queries",
"converts",
"each",
"query",
"into",
"an",
"XQuery",
"using",
"QVarXQueryGenerator",
"and",
"returns",
"the",
"result",
"as",
"a",
"list",
"of",
"NtcirPatterns",
"for",
"each",
"individual",
"query",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/querygenerator/NtcirTopicReader.java#L86-L104 |
2,016 | ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/util/XMLUtils.java | XMLUtils.getChildElements | public static ArrayList<Element> getChildElements(Node node) {
ArrayList<Element> childElements = new ArrayList<>();
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i) instanceof Element) {
childElements.add((Element) childNodes.item(i));
}
}
return childElements;
} | java | public static ArrayList<Element> getChildElements(Node node) {
ArrayList<Element> childElements = new ArrayList<>();
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i) instanceof Element) {
childElements.add((Element) childNodes.item(i));
}
}
return childElements;
} | [
"public",
"static",
"ArrayList",
"<",
"Element",
">",
"getChildElements",
"(",
"Node",
"node",
")",
"{",
"ArrayList",
"<",
"Element",
">",
"childElements",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"NodeList",
"childNodes",
"=",
"node",
".",
"getChildNodes",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"childNodes",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"childNodes",
".",
"item",
"(",
"i",
")",
"instanceof",
"Element",
")",
"{",
"childElements",
".",
"add",
"(",
"(",
"Element",
")",
"childNodes",
".",
"item",
"(",
"i",
")",
")",
";",
"}",
"}",
"return",
"childElements",
";",
"}"
] | Only return child nodes that are elements - text nodes are ignored.
@param node We will take the children from this node.
@return New ordered list of child elements. | [
"Only",
"return",
"child",
"nodes",
"that",
"are",
"elements",
"-",
"text",
"nodes",
"are",
"ignored",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/util/XMLUtils.java#L34-L43 |
2,017 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/querygenerator/QVarXQueryGenerator.java | QVarXQueryGenerator.generateQvarConstraints | private void generateQvarConstraints() {
final StringBuilder qvarConstrBuilder = new StringBuilder();
final StringBuilder qvarMapStrBuilder = new StringBuilder();
final Iterator<Map.Entry<String, ArrayList<String>>> entryIterator = qvar.entrySet().iterator();
if (entryIterator.hasNext()) {
qvarMapStrBuilder.append("declare function local:qvarMap($x) {\n map {");
while (entryIterator.hasNext()) {
final Map.Entry<String, ArrayList<String>> currentEntry = entryIterator.next();
final Iterator<String> valueIterator = currentEntry.getValue().iterator();
final String firstValue = valueIterator.next();
qvarMapStrBuilder.append('"').append(currentEntry.getKey()).append('"')
.append(" : (data($x").append(firstValue).append("/@xml:id)");
//check if there are additional values that we need to constrain
if (valueIterator.hasNext()) {
if (qvarConstrBuilder.length() > 0) {
//only add beginning and if it's an additional constraint in the aggregate qvar string
qvarConstrBuilder.append("\n and ");
}
while (valueIterator.hasNext()) {
//process second value onwards
final String currentValue = valueIterator.next();
qvarMapStrBuilder.append(",data($x").append(currentValue).append("/@xml-id)");
//These constraints specify that the same qvars must refer to the same nodes,
//using the XQuery "=" equality
//This is equality based on: same text, same node names, and same children nodes
qvarConstrBuilder.append("$x").append(firstValue).append(" = $x").append(currentValue);
if (valueIterator.hasNext()) {
qvarConstrBuilder.append(" and ");
}
}
}
qvarMapStrBuilder.append(')');
if (entryIterator.hasNext()) {
qvarMapStrBuilder.append(',');
}
}
qvarMapStrBuilder.append("}\n};");
}
qvarMapVariable = qvarMapStrBuilder.toString();
qvarConstraint = qvarConstrBuilder.toString();
} | java | private void generateQvarConstraints() {
final StringBuilder qvarConstrBuilder = new StringBuilder();
final StringBuilder qvarMapStrBuilder = new StringBuilder();
final Iterator<Map.Entry<String, ArrayList<String>>> entryIterator = qvar.entrySet().iterator();
if (entryIterator.hasNext()) {
qvarMapStrBuilder.append("declare function local:qvarMap($x) {\n map {");
while (entryIterator.hasNext()) {
final Map.Entry<String, ArrayList<String>> currentEntry = entryIterator.next();
final Iterator<String> valueIterator = currentEntry.getValue().iterator();
final String firstValue = valueIterator.next();
qvarMapStrBuilder.append('"').append(currentEntry.getKey()).append('"')
.append(" : (data($x").append(firstValue).append("/@xml:id)");
//check if there are additional values that we need to constrain
if (valueIterator.hasNext()) {
if (qvarConstrBuilder.length() > 0) {
//only add beginning and if it's an additional constraint in the aggregate qvar string
qvarConstrBuilder.append("\n and ");
}
while (valueIterator.hasNext()) {
//process second value onwards
final String currentValue = valueIterator.next();
qvarMapStrBuilder.append(",data($x").append(currentValue).append("/@xml-id)");
//These constraints specify that the same qvars must refer to the same nodes,
//using the XQuery "=" equality
//This is equality based on: same text, same node names, and same children nodes
qvarConstrBuilder.append("$x").append(firstValue).append(" = $x").append(currentValue);
if (valueIterator.hasNext()) {
qvarConstrBuilder.append(" and ");
}
}
}
qvarMapStrBuilder.append(')');
if (entryIterator.hasNext()) {
qvarMapStrBuilder.append(',');
}
}
qvarMapStrBuilder.append("}\n};");
}
qvarMapVariable = qvarMapStrBuilder.toString();
qvarConstraint = qvarConstrBuilder.toString();
} | [
"private",
"void",
"generateQvarConstraints",
"(",
")",
"{",
"final",
"StringBuilder",
"qvarConstrBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"final",
"StringBuilder",
"qvarMapStrBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"final",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"ArrayList",
"<",
"String",
">",
">",
">",
"entryIterator",
"=",
"qvar",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"if",
"(",
"entryIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"qvarMapStrBuilder",
".",
"append",
"(",
"\"declare function local:qvarMap($x) {\\n map {\"",
")",
";",
"while",
"(",
"entryIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"Map",
".",
"Entry",
"<",
"String",
",",
"ArrayList",
"<",
"String",
">",
">",
"currentEntry",
"=",
"entryIterator",
".",
"next",
"(",
")",
";",
"final",
"Iterator",
"<",
"String",
">",
"valueIterator",
"=",
"currentEntry",
".",
"getValue",
"(",
")",
".",
"iterator",
"(",
")",
";",
"final",
"String",
"firstValue",
"=",
"valueIterator",
".",
"next",
"(",
")",
";",
"qvarMapStrBuilder",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"currentEntry",
".",
"getKey",
"(",
")",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"\" : (data($x\"",
")",
".",
"append",
"(",
"firstValue",
")",
".",
"append",
"(",
"\"/@xml:id)\"",
")",
";",
"//check if there are additional values that we need to constrain",
"if",
"(",
"valueIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"if",
"(",
"qvarConstrBuilder",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"//only add beginning and if it's an additional constraint in the aggregate qvar string",
"qvarConstrBuilder",
".",
"append",
"(",
"\"\\n and \"",
")",
";",
"}",
"while",
"(",
"valueIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"//process second value onwards",
"final",
"String",
"currentValue",
"=",
"valueIterator",
".",
"next",
"(",
")",
";",
"qvarMapStrBuilder",
".",
"append",
"(",
"\",data($x\"",
")",
".",
"append",
"(",
"currentValue",
")",
".",
"append",
"(",
"\"/@xml-id)\"",
")",
";",
"//These constraints specify that the same qvars must refer to the same nodes,",
"//using the XQuery \"=\" equality",
"//This is equality based on: same text, same node names, and same children nodes",
"qvarConstrBuilder",
".",
"append",
"(",
"\"$x\"",
")",
".",
"append",
"(",
"firstValue",
")",
".",
"append",
"(",
"\" = $x\"",
")",
".",
"append",
"(",
"currentValue",
")",
";",
"if",
"(",
"valueIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"qvarConstrBuilder",
".",
"append",
"(",
"\" and \"",
")",
";",
"}",
"}",
"}",
"qvarMapStrBuilder",
".",
"append",
"(",
"'",
"'",
")",
";",
"if",
"(",
"entryIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"qvarMapStrBuilder",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"}",
"qvarMapStrBuilder",
".",
"append",
"(",
"\"}\\n};\"",
")",
";",
"}",
"qvarMapVariable",
"=",
"qvarMapStrBuilder",
".",
"toString",
"(",
")",
";",
"qvarConstraint",
"=",
"qvarConstrBuilder",
".",
"toString",
"(",
")",
";",
"}"
] | Uses the qvar map to generate a XQuery string containing qvar constraints,
and the qvar map variable which maps qvar names to their respective formula ID's in the result. | [
"Uses",
"the",
"qvar",
"map",
"to",
"generate",
"a",
"XQuery",
"string",
"containing",
"qvar",
"constraints",
"and",
"the",
"qvar",
"map",
"variable",
"which",
"maps",
"qvar",
"names",
"to",
"their",
"respective",
"formula",
"ID",
"s",
"in",
"the",
"result",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/querygenerator/QVarXQueryGenerator.java#L80-L124 |
2,018 | ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/distances/Distances.java | Distances.computeEarthMoverAbsoluteDistance | public static double computeEarthMoverAbsoluteDistance(Map<String, Double> h1, Map<String, Double> h2) {
Signature s1 = EarthMoverDistanceWrapper.histogramToSignature(h1);
Signature s2 = EarthMoverDistanceWrapper.histogramToSignature(h2);
return JFastEMD.distance(s1, s2, 0.0);
} | java | public static double computeEarthMoverAbsoluteDistance(Map<String, Double> h1, Map<String, Double> h2) {
Signature s1 = EarthMoverDistanceWrapper.histogramToSignature(h1);
Signature s2 = EarthMoverDistanceWrapper.histogramToSignature(h2);
return JFastEMD.distance(s1, s2, 0.0);
} | [
"public",
"static",
"double",
"computeEarthMoverAbsoluteDistance",
"(",
"Map",
"<",
"String",
",",
"Double",
">",
"h1",
",",
"Map",
"<",
"String",
",",
"Double",
">",
"h2",
")",
"{",
"Signature",
"s1",
"=",
"EarthMoverDistanceWrapper",
".",
"histogramToSignature",
"(",
"h1",
")",
";",
"Signature",
"s2",
"=",
"EarthMoverDistanceWrapper",
".",
"histogramToSignature",
"(",
"h2",
")",
";",
"return",
"JFastEMD",
".",
"distance",
"(",
"s1",
",",
"s2",
",",
"0.0",
")",
";",
"}"
] | probably only makes sense to compute this on CI
@param h1
@param h2
@return | [
"probably",
"only",
"makes",
"sense",
"to",
"compute",
"this",
"on",
"CI"
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/distances/Distances.java#L36-L41 |
2,019 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/querygenerator/BasicXQueryGenerator.java | BasicXQueryGenerator.generateSimpleConstraints | private String generateSimpleConstraints(Node node, boolean isRoot) {
//Index of child node
int childElementIndex = 0;
final StringBuilder out = new StringBuilder();
boolean queryHasText = false;
final NonWhitespaceNodeList nodeList = new NonWhitespaceNodeList(node.getChildNodes());
for (final Node child : nodeList) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
//If an element node and not an attribute or text node, add to xquery and increment index
childElementIndex++;
boolean wasSpecialElement = handleSpecialElements(child, childElementIndex);
if (wasSpecialElement) {
continue; // this was a special element and was handled otherwise (e.g. qvar)
}
// We only want to consider elements below the content mathml semantics,
// a deeper lying annotation-node should be ignored
boolean annotationNode = child.getLocalName() != null
&& XMLHelper.ANNOTATION_XML_PATTERN.matcher(child.getLocalName()).matches();
if (!annotationNode) {
if (queryHasText) {
//Add another condition on top of existing condition in query
out.append(" and ");
} else {
queryHasText = true;
}
//The first direct child of the root element is added as a constraint in getString()
//so ignore it here
if (!isRoot) {
//Add constraint for current child element
out.append("*[").append(childElementIndex).append("]/name() = '").
append(child.getLocalName()).append("'");
}
if (child.hasChildNodes()) {
if (!isRoot) {
setRelativeXPath(getRelativeXPath() + "/*[" + childElementIndex + "]");
//Add relative constraint so this can be recursively called
out.append(" and *[").append(childElementIndex).append("]");
}
final String constraint = generateSimpleConstraints(child);
if (!constraint.isEmpty()) {
//This constraint appears as a child of the relative constraint above (e.g. [*1][constraint])
out.append("[").append(constraint).append("]");
}
}
}
} else if (child.getNodeType() == Node.TEXT_NODE) {
//Text nodes are always leaf nodes
out.append("./text() = '").append(child.getNodeValue().trim()).append("'");
}
} //for child : nodelist
if (!isRoot && isRestrictLength()) {
// Initialize constraint or add as additional constraint
setLengthConstraint(
(getLengthConstraint().isEmpty() ? "" : getLengthConstraint() + "\n and ")
+ "fn:count($x" + getRelativeXPath() + "/*) = " + childElementIndex
);
}
if (!getRelativeXPath().isEmpty()) {
String tmpRelativeXPath = getRelativeXPath().substring(0, getRelativeXPath().lastIndexOf("/"));
setRelativeXPath(tmpRelativeXPath);
}
return out.toString();
} | java | private String generateSimpleConstraints(Node node, boolean isRoot) {
//Index of child node
int childElementIndex = 0;
final StringBuilder out = new StringBuilder();
boolean queryHasText = false;
final NonWhitespaceNodeList nodeList = new NonWhitespaceNodeList(node.getChildNodes());
for (final Node child : nodeList) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
//If an element node and not an attribute or text node, add to xquery and increment index
childElementIndex++;
boolean wasSpecialElement = handleSpecialElements(child, childElementIndex);
if (wasSpecialElement) {
continue; // this was a special element and was handled otherwise (e.g. qvar)
}
// We only want to consider elements below the content mathml semantics,
// a deeper lying annotation-node should be ignored
boolean annotationNode = child.getLocalName() != null
&& XMLHelper.ANNOTATION_XML_PATTERN.matcher(child.getLocalName()).matches();
if (!annotationNode) {
if (queryHasText) {
//Add another condition on top of existing condition in query
out.append(" and ");
} else {
queryHasText = true;
}
//The first direct child of the root element is added as a constraint in getString()
//so ignore it here
if (!isRoot) {
//Add constraint for current child element
out.append("*[").append(childElementIndex).append("]/name() = '").
append(child.getLocalName()).append("'");
}
if (child.hasChildNodes()) {
if (!isRoot) {
setRelativeXPath(getRelativeXPath() + "/*[" + childElementIndex + "]");
//Add relative constraint so this can be recursively called
out.append(" and *[").append(childElementIndex).append("]");
}
final String constraint = generateSimpleConstraints(child);
if (!constraint.isEmpty()) {
//This constraint appears as a child of the relative constraint above (e.g. [*1][constraint])
out.append("[").append(constraint).append("]");
}
}
}
} else if (child.getNodeType() == Node.TEXT_NODE) {
//Text nodes are always leaf nodes
out.append("./text() = '").append(child.getNodeValue().trim()).append("'");
}
} //for child : nodelist
if (!isRoot && isRestrictLength()) {
// Initialize constraint or add as additional constraint
setLengthConstraint(
(getLengthConstraint().isEmpty() ? "" : getLengthConstraint() + "\n and ")
+ "fn:count($x" + getRelativeXPath() + "/*) = " + childElementIndex
);
}
if (!getRelativeXPath().isEmpty()) {
String tmpRelativeXPath = getRelativeXPath().substring(0, getRelativeXPath().lastIndexOf("/"));
setRelativeXPath(tmpRelativeXPath);
}
return out.toString();
} | [
"private",
"String",
"generateSimpleConstraints",
"(",
"Node",
"node",
",",
"boolean",
"isRoot",
")",
"{",
"//Index of child node",
"int",
"childElementIndex",
"=",
"0",
";",
"final",
"StringBuilder",
"out",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"boolean",
"queryHasText",
"=",
"false",
";",
"final",
"NonWhitespaceNodeList",
"nodeList",
"=",
"new",
"NonWhitespaceNodeList",
"(",
"node",
".",
"getChildNodes",
"(",
")",
")",
";",
"for",
"(",
"final",
"Node",
"child",
":",
"nodeList",
")",
"{",
"if",
"(",
"child",
".",
"getNodeType",
"(",
")",
"==",
"Node",
".",
"ELEMENT_NODE",
")",
"{",
"//If an element node and not an attribute or text node, add to xquery and increment index",
"childElementIndex",
"++",
";",
"boolean",
"wasSpecialElement",
"=",
"handleSpecialElements",
"(",
"child",
",",
"childElementIndex",
")",
";",
"if",
"(",
"wasSpecialElement",
")",
"{",
"continue",
";",
"// this was a special element and was handled otherwise (e.g. qvar)",
"}",
"// We only want to consider elements below the content mathml semantics,",
"// a deeper lying annotation-node should be ignored",
"boolean",
"annotationNode",
"=",
"child",
".",
"getLocalName",
"(",
")",
"!=",
"null",
"&&",
"XMLHelper",
".",
"ANNOTATION_XML_PATTERN",
".",
"matcher",
"(",
"child",
".",
"getLocalName",
"(",
")",
")",
".",
"matches",
"(",
")",
";",
"if",
"(",
"!",
"annotationNode",
")",
"{",
"if",
"(",
"queryHasText",
")",
"{",
"//Add another condition on top of existing condition in query",
"out",
".",
"append",
"(",
"\" and \"",
")",
";",
"}",
"else",
"{",
"queryHasText",
"=",
"true",
";",
"}",
"//The first direct child of the root element is added as a constraint in getString()",
"//so ignore it here",
"if",
"(",
"!",
"isRoot",
")",
"{",
"//Add constraint for current child element",
"out",
".",
"append",
"(",
"\"*[\"",
")",
".",
"append",
"(",
"childElementIndex",
")",
".",
"append",
"(",
"\"]/name() = '\"",
")",
".",
"append",
"(",
"child",
".",
"getLocalName",
"(",
")",
")",
".",
"append",
"(",
"\"'\"",
")",
";",
"}",
"if",
"(",
"child",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"if",
"(",
"!",
"isRoot",
")",
"{",
"setRelativeXPath",
"(",
"getRelativeXPath",
"(",
")",
"+",
"\"/*[\"",
"+",
"childElementIndex",
"+",
"\"]\"",
")",
";",
"//Add relative constraint so this can be recursively called",
"out",
".",
"append",
"(",
"\" and *[\"",
")",
".",
"append",
"(",
"childElementIndex",
")",
".",
"append",
"(",
"\"]\"",
")",
";",
"}",
"final",
"String",
"constraint",
"=",
"generateSimpleConstraints",
"(",
"child",
")",
";",
"if",
"(",
"!",
"constraint",
".",
"isEmpty",
"(",
")",
")",
"{",
"//This constraint appears as a child of the relative constraint above (e.g. [*1][constraint])",
"out",
".",
"append",
"(",
"\"[\"",
")",
".",
"append",
"(",
"constraint",
")",
".",
"append",
"(",
"\"]\"",
")",
";",
"}",
"}",
"}",
"}",
"else",
"if",
"(",
"child",
".",
"getNodeType",
"(",
")",
"==",
"Node",
".",
"TEXT_NODE",
")",
"{",
"//Text nodes are always leaf nodes",
"out",
".",
"append",
"(",
"\"./text() = '\"",
")",
".",
"append",
"(",
"child",
".",
"getNodeValue",
"(",
")",
".",
"trim",
"(",
")",
")",
".",
"append",
"(",
"\"'\"",
")",
";",
"}",
"}",
"//for child : nodelist",
"if",
"(",
"!",
"isRoot",
"&&",
"isRestrictLength",
"(",
")",
")",
"{",
"// Initialize constraint or add as additional constraint",
"setLengthConstraint",
"(",
"(",
"getLengthConstraint",
"(",
")",
".",
"isEmpty",
"(",
")",
"?",
"\"\"",
":",
"getLengthConstraint",
"(",
")",
"+",
"\"\\n and \"",
")",
"+",
"\"fn:count($x\"",
"+",
"getRelativeXPath",
"(",
")",
"+",
"\"/*) = \"",
"+",
"childElementIndex",
")",
";",
"}",
"if",
"(",
"!",
"getRelativeXPath",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"String",
"tmpRelativeXPath",
"=",
"getRelativeXPath",
"(",
")",
".",
"substring",
"(",
"0",
",",
"getRelativeXPath",
"(",
")",
".",
"lastIndexOf",
"(",
"\"/\"",
")",
")",
";",
"setRelativeXPath",
"(",
"tmpRelativeXPath",
")",
";",
"}",
"return",
"out",
".",
"toString",
"(",
")",
";",
"}"
] | Generates qvar map, length constraint, and returns exact match XQuery query for all child nodes of the given node.
Called recursively to generate the query for the entire query document.
@param node Element from which to get children to generate constraints.
@param isRoot Whether or not node should be treated as the root element of the document (the root element
is not added as a constraint here, but in getString())
@return Exact match XQuery string | [
"Generates",
"qvar",
"map",
"length",
"constraint",
"and",
"returns",
"exact",
"match",
"XQuery",
"query",
"for",
"all",
"child",
"nodes",
"of",
"the",
"given",
"node",
".",
"Called",
"recursively",
"to",
"generate",
"the",
"query",
"for",
"the",
"entire",
"query",
"document",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/querygenerator/BasicXQueryGenerator.java#L69-L138 |
2,020 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/mathoid/EnrichedMathMLTransformer.java | EnrichedMathMLTransformer.copyIdField | void copyIdField(Element readNode) {
String newId = readNode.getAttribute("data-semantic-id");
if (!StringUtils.isEmpty(newId)) {
readNode.setAttribute("id", "p" + newId);
}
for (Node child : new NonWhitespaceNodeList(readNode.getChildNodes())) {
if (child instanceof Element) {
copyIdField((Element) child);
}
}
} | java | void copyIdField(Element readNode) {
String newId = readNode.getAttribute("data-semantic-id");
if (!StringUtils.isEmpty(newId)) {
readNode.setAttribute("id", "p" + newId);
}
for (Node child : new NonWhitespaceNodeList(readNode.getChildNodes())) {
if (child instanceof Element) {
copyIdField((Element) child);
}
}
} | [
"void",
"copyIdField",
"(",
"Element",
"readNode",
")",
"{",
"String",
"newId",
"=",
"readNode",
".",
"getAttribute",
"(",
"\"data-semantic-id\"",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"newId",
")",
")",
"{",
"readNode",
".",
"setAttribute",
"(",
"\"id\"",
",",
"\"p\"",
"+",
"newId",
")",
";",
"}",
"for",
"(",
"Node",
"child",
":",
"new",
"NonWhitespaceNodeList",
"(",
"readNode",
".",
"getChildNodes",
"(",
")",
")",
")",
"{",
"if",
"(",
"child",
"instanceof",
"Element",
")",
"{",
"copyIdField",
"(",
"(",
"Element",
")",
"child",
")",
";",
"}",
"}",
"}"
] | Copy the "data-semantic-id" attribute to "id", if it does not exist.
Will recursively go over every child.
@param readNode element to change | [
"Copy",
"the",
"data",
"-",
"semantic",
"-",
"id",
"attribute",
"to",
"id",
"if",
"it",
"does",
"not",
"exist",
".",
"Will",
"recursively",
"go",
"over",
"every",
"child",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/mathoid/EnrichedMathMLTransformer.java#L105-L115 |
2,021 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathoidConverter.java | MathoidConverter.convert | public String convert(String input, String type) {
// set necessary header: request per form
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// pack the latex string as the parameter q (q for query ;) )
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("q", input);
if (!type.isEmpty()) {
map.add("type", type);
}
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
try {
String rep = new RestTemplate().postForObject(mathoidConfig.getUrl(), request, String.class);
logger.info(rep);
return rep;
} catch (HttpClientErrorException e) {
logger.error(e.getResponseBodyAsString());
throw e;
}
} | java | public String convert(String input, String type) {
// set necessary header: request per form
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// pack the latex string as the parameter q (q for query ;) )
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("q", input);
if (!type.isEmpty()) {
map.add("type", type);
}
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
try {
String rep = new RestTemplate().postForObject(mathoidConfig.getUrl(), request, String.class);
logger.info(rep);
return rep;
} catch (HttpClientErrorException e) {
logger.error(e.getResponseBodyAsString());
throw e;
}
} | [
"public",
"String",
"convert",
"(",
"String",
"input",
",",
"String",
"type",
")",
"{",
"// set necessary header: request per form",
"HttpHeaders",
"headers",
"=",
"new",
"HttpHeaders",
"(",
")",
";",
"headers",
".",
"setContentType",
"(",
"MediaType",
".",
"APPLICATION_FORM_URLENCODED",
")",
";",
"// pack the latex string as the parameter q (q for query ;) )",
"MultiValueMap",
"<",
"String",
",",
"String",
">",
"map",
"=",
"new",
"LinkedMultiValueMap",
"<>",
"(",
")",
";",
"map",
".",
"add",
"(",
"\"q\"",
",",
"input",
")",
";",
"if",
"(",
"!",
"type",
".",
"isEmpty",
"(",
")",
")",
"{",
"map",
".",
"add",
"(",
"\"type\"",
",",
"type",
")",
";",
"}",
"HttpEntity",
"<",
"MultiValueMap",
"<",
"String",
",",
"String",
">",
">",
"request",
"=",
"new",
"HttpEntity",
"<>",
"(",
"map",
",",
"headers",
")",
";",
"try",
"{",
"String",
"rep",
"=",
"new",
"RestTemplate",
"(",
")",
".",
"postForObject",
"(",
"mathoidConfig",
".",
"getUrl",
"(",
")",
",",
"request",
",",
"String",
".",
"class",
")",
";",
"logger",
".",
"info",
"(",
"rep",
")",
";",
"return",
"rep",
";",
"}",
"catch",
"(",
"HttpClientErrorException",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"e",
".",
"getResponseBodyAsString",
"(",
")",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | Request against Mathoid to receive an enriched MathML.
Input format can be chosen.
@param input LaTeX formula to be converted
@param type input format
@return Enrichted MathML String from mathoid | [
"Request",
"against",
"Mathoid",
"to",
"receive",
"an",
"enriched",
"MathML",
".",
"Input",
"format",
"can",
"be",
"chosen",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathoidConverter.java#L122-L143 |
2,022 | ag-gipp/MathMLTools | mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathoidConverter.java | MathoidConverter.isReachable | public boolean isReachable() {
try {
URL url = new URL(mathoidConfig.getUrl() + "/mml");
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
ClientHttpRequest req = factory.createRequest(url.toURI(), HttpMethod.POST);
req.execute();
return true;
} catch (Exception e) {
return false;
}
} | java | public boolean isReachable() {
try {
URL url = new URL(mathoidConfig.getUrl() + "/mml");
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
ClientHttpRequest req = factory.createRequest(url.toURI(), HttpMethod.POST);
req.execute();
return true;
} catch (Exception e) {
return false;
}
} | [
"public",
"boolean",
"isReachable",
"(",
")",
"{",
"try",
"{",
"URL",
"url",
"=",
"new",
"URL",
"(",
"mathoidConfig",
".",
"getUrl",
"(",
")",
"+",
"\"/mml\"",
")",
";",
"SimpleClientHttpRequestFactory",
"factory",
"=",
"new",
"SimpleClientHttpRequestFactory",
"(",
")",
";",
"ClientHttpRequest",
"req",
"=",
"factory",
".",
"createRequest",
"(",
"url",
".",
"toURI",
"(",
")",
",",
"HttpMethod",
".",
"POST",
")",
";",
"req",
".",
"execute",
"(",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | Returns true if the Mathoid service is reachable, otherwise false.
@return | [
"Returns",
"true",
"if",
"the",
"Mathoid",
"service",
"is",
"reachable",
"otherwise",
"false",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathoidConverter.java#L150-L160 |
2,023 | ag-gipp/MathMLTools | mathml-gold/src/main/java/com/formulasearchengine/mathmltools/gold/GoldUtils.java | GoldUtils.readGoldFile | public static JsonGouldiBean readGoldFile(Path pathToSingleGoldFile) throws IOException {
File f = pathToSingleGoldFile.toFile();
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(f, JsonGouldiBean.class);
} | java | public static JsonGouldiBean readGoldFile(Path pathToSingleGoldFile) throws IOException {
File f = pathToSingleGoldFile.toFile();
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(f, JsonGouldiBean.class);
} | [
"public",
"static",
"JsonGouldiBean",
"readGoldFile",
"(",
"Path",
"pathToSingleGoldFile",
")",
"throws",
"IOException",
"{",
"File",
"f",
"=",
"pathToSingleGoldFile",
".",
"toFile",
"(",
")",
";",
"ObjectMapper",
"mapper",
"=",
"new",
"ObjectMapper",
"(",
")",
";",
"return",
"mapper",
".",
"readValue",
"(",
"f",
",",
"JsonGouldiBean",
".",
"class",
")",
";",
"}"
] | Reads a gold file in json format from the given path. It will be stored as Java objects.
@param pathToSingleGoldFile path to the json format gouldi entry
@return java object representing the gouldi entry
@throws IOException will be thrown if we cannot read from the file | [
"Reads",
"a",
"gold",
"file",
"in",
"json",
"format",
"from",
"the",
"given",
"path",
".",
"It",
"will",
"be",
"stored",
"as",
"Java",
"objects",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-gold/src/main/java/com/formulasearchengine/mathmltools/gold/GoldUtils.java#L28-L32 |
2,024 | ag-gipp/MathMLTools | mathml-gold/src/main/java/com/formulasearchengine/mathmltools/gold/GoldUtils.java | GoldUtils.writeGoldFile | public static void writeGoldFile(Path outputPath, JsonGouldiBean goldEntry) {
try {
try {
Files.createFile(outputPath);
} catch (FileAlreadyExistsException e) {
LOG.warn("File already exists!");
}
try (Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputPath.toFile()), "UTF-8"))) {
out.write(goldEntry.toString());
}
} catch (IOException e) {
LOG.error(e);
throw new RuntimeException(e);
}
} | java | public static void writeGoldFile(Path outputPath, JsonGouldiBean goldEntry) {
try {
try {
Files.createFile(outputPath);
} catch (FileAlreadyExistsException e) {
LOG.warn("File already exists!");
}
try (Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputPath.toFile()), "UTF-8"))) {
out.write(goldEntry.toString());
}
} catch (IOException e) {
LOG.error(e);
throw new RuntimeException(e);
}
} | [
"public",
"static",
"void",
"writeGoldFile",
"(",
"Path",
"outputPath",
",",
"JsonGouldiBean",
"goldEntry",
")",
"{",
"try",
"{",
"try",
"{",
"Files",
".",
"createFile",
"(",
"outputPath",
")",
";",
"}",
"catch",
"(",
"FileAlreadyExistsException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"File already exists!\"",
")",
";",
"}",
"try",
"(",
"Writer",
"out",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"new",
"FileOutputStream",
"(",
"outputPath",
".",
"toFile",
"(",
")",
")",
",",
"\"UTF-8\"",
")",
")",
")",
"{",
"out",
".",
"write",
"(",
"goldEntry",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"e",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Writes a gouldi entry to the given path. Note that if the file already exists, it will be
overwritten and logging a warning message.
@param outputPath where the gouldi entry will be stored
@param goldEntry the gouldi entry as java object
@throws IOException | [
"Writes",
"a",
"gouldi",
"entry",
"to",
"the",
"given",
"path",
".",
"Note",
"that",
"if",
"the",
"file",
"already",
"exists",
"it",
"will",
"be",
"overwritten",
"and",
"logging",
"a",
"warning",
"message",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-gold/src/main/java/com/formulasearchengine/mathmltools/gold/GoldUtils.java#L42-L57 |
2,025 | ag-gipp/MathMLTools | mathml-gold/src/main/java/com/formulasearchengine/mathmltools/gold/pojo/JsonGouldiBean.java | JsonGouldiBean.deserializeDefinitionsField | @SuppressWarnings("unchecked") // bla bla, we know what we are doing here...
@JsonProperty("definitions")
private void deserializeDefinitionsField(Map<String, Object> defs) {
definitionsBean = new JsonGouldiDefinitionsBean();
LinkedList<JsonGouldiIdentifierDefinienBean> list = new LinkedList<>();
definitionsBean.setIdentifierDefiniens(list);
for (String key : defs.keySet()) {
JsonGouldiIdentifierDefinienBean bean = new JsonGouldiIdentifierDefinienBean();
ArrayList<JsonGouldiWikidataDefinienBean> arrList = new ArrayList<>();
bean.setName(key);
ArrayList<Object> identifierList = (ArrayList<Object>) defs.get(key);
for (Object obj : identifierList) {
if (obj instanceof String) {
JsonGouldiTextDefinienBean textBean = new JsonGouldiTextDefinienBean();
textBean.setDiscription((String) obj);
arrList.add(textBean);
} else {
Map<String, String> qidMappings = (Map<String, String>) obj;
for (String qID : qidMappings.keySet()) {
JsonGouldiWikidataDefinienBean wikidefbean = new JsonGouldiWikidataDefinienBean();
wikidefbean.setWikiID(qID);
wikidefbean.setDiscription(qidMappings.get(qID));
arrList.add(wikidefbean);
}
}
}
JsonGouldiWikidataDefinienBean[] arr = new JsonGouldiWikidataDefinienBean[arrList.size()];
arr = arrList.toArray(arr);
bean.setDefiniens(arr);
list.add(bean);
}
} | java | @SuppressWarnings("unchecked") // bla bla, we know what we are doing here...
@JsonProperty("definitions")
private void deserializeDefinitionsField(Map<String, Object> defs) {
definitionsBean = new JsonGouldiDefinitionsBean();
LinkedList<JsonGouldiIdentifierDefinienBean> list = new LinkedList<>();
definitionsBean.setIdentifierDefiniens(list);
for (String key : defs.keySet()) {
JsonGouldiIdentifierDefinienBean bean = new JsonGouldiIdentifierDefinienBean();
ArrayList<JsonGouldiWikidataDefinienBean> arrList = new ArrayList<>();
bean.setName(key);
ArrayList<Object> identifierList = (ArrayList<Object>) defs.get(key);
for (Object obj : identifierList) {
if (obj instanceof String) {
JsonGouldiTextDefinienBean textBean = new JsonGouldiTextDefinienBean();
textBean.setDiscription((String) obj);
arrList.add(textBean);
} else {
Map<String, String> qidMappings = (Map<String, String>) obj;
for (String qID : qidMappings.keySet()) {
JsonGouldiWikidataDefinienBean wikidefbean = new JsonGouldiWikidataDefinienBean();
wikidefbean.setWikiID(qID);
wikidefbean.setDiscription(qidMappings.get(qID));
arrList.add(wikidefbean);
}
}
}
JsonGouldiWikidataDefinienBean[] arr = new JsonGouldiWikidataDefinienBean[arrList.size()];
arr = arrList.toArray(arr);
bean.setDefiniens(arr);
list.add(bean);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// bla bla, we know what we are doing here...",
"@",
"JsonProperty",
"(",
"\"definitions\"",
")",
"private",
"void",
"deserializeDefinitionsField",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"defs",
")",
"{",
"definitionsBean",
"=",
"new",
"JsonGouldiDefinitionsBean",
"(",
")",
";",
"LinkedList",
"<",
"JsonGouldiIdentifierDefinienBean",
">",
"list",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"definitionsBean",
".",
"setIdentifierDefiniens",
"(",
"list",
")",
";",
"for",
"(",
"String",
"key",
":",
"defs",
".",
"keySet",
"(",
")",
")",
"{",
"JsonGouldiIdentifierDefinienBean",
"bean",
"=",
"new",
"JsonGouldiIdentifierDefinienBean",
"(",
")",
";",
"ArrayList",
"<",
"JsonGouldiWikidataDefinienBean",
">",
"arrList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"bean",
".",
"setName",
"(",
"key",
")",
";",
"ArrayList",
"<",
"Object",
">",
"identifierList",
"=",
"(",
"ArrayList",
"<",
"Object",
">",
")",
"defs",
".",
"get",
"(",
"key",
")",
";",
"for",
"(",
"Object",
"obj",
":",
"identifierList",
")",
"{",
"if",
"(",
"obj",
"instanceof",
"String",
")",
"{",
"JsonGouldiTextDefinienBean",
"textBean",
"=",
"new",
"JsonGouldiTextDefinienBean",
"(",
")",
";",
"textBean",
".",
"setDiscription",
"(",
"(",
"String",
")",
"obj",
")",
";",
"arrList",
".",
"add",
"(",
"textBean",
")",
";",
"}",
"else",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"qidMappings",
"=",
"(",
"Map",
"<",
"String",
",",
"String",
">",
")",
"obj",
";",
"for",
"(",
"String",
"qID",
":",
"qidMappings",
".",
"keySet",
"(",
")",
")",
"{",
"JsonGouldiWikidataDefinienBean",
"wikidefbean",
"=",
"new",
"JsonGouldiWikidataDefinienBean",
"(",
")",
";",
"wikidefbean",
".",
"setWikiID",
"(",
"qID",
")",
";",
"wikidefbean",
".",
"setDiscription",
"(",
"qidMappings",
".",
"get",
"(",
"qID",
")",
")",
";",
"arrList",
".",
"add",
"(",
"wikidefbean",
")",
";",
"}",
"}",
"}",
"JsonGouldiWikidataDefinienBean",
"[",
"]",
"arr",
"=",
"new",
"JsonGouldiWikidataDefinienBean",
"[",
"arrList",
".",
"size",
"(",
")",
"]",
";",
"arr",
"=",
"arrList",
".",
"toArray",
"(",
"arr",
")",
";",
"bean",
".",
"setDefiniens",
"(",
"arr",
")",
";",
"list",
".",
"add",
"(",
"bean",
")",
";",
"}",
"}"
] | Provide a custom deserialization for definitions
@param defs the generic object for definitions field in gouldi | [
"Provide",
"a",
"custom",
"deserialization",
"for",
"definitions"
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-gold/src/main/java/com/formulasearchengine/mathmltools/gold/pojo/JsonGouldiBean.java#L79-L113 |
2,026 | ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/mml/MathDoc.java | MathDoc.highlightConsecutiveIdentifiers | public void highlightConsecutiveIdentifiers(List<Integer> hashes, boolean backward) {
final int startPos = highlightFirstIdentifier(hashes.get(0), backward);
if (startPos >= 0) {
highlightRemainingIdentifiers(hashes.subList(1, hashes.size()), startPos);
}
} | java | public void highlightConsecutiveIdentifiers(List<Integer> hashes, boolean backward) {
final int startPos = highlightFirstIdentifier(hashes.get(0), backward);
if (startPos >= 0) {
highlightRemainingIdentifiers(hashes.subList(1, hashes.size()), startPos);
}
} | [
"public",
"void",
"highlightConsecutiveIdentifiers",
"(",
"List",
"<",
"Integer",
">",
"hashes",
",",
"boolean",
"backward",
")",
"{",
"final",
"int",
"startPos",
"=",
"highlightFirstIdentifier",
"(",
"hashes",
".",
"get",
"(",
"0",
")",
",",
"backward",
")",
";",
"if",
"(",
"startPos",
">=",
"0",
")",
"{",
"highlightRemainingIdentifiers",
"(",
"hashes",
".",
"subList",
"(",
"1",
",",
"hashes",
".",
"size",
"(",
")",
")",
",",
"startPos",
")",
";",
"}",
"}"
] | Highlights consecutive occurrences of identifiers.
@param hashes list of content identifier hashes to highlight
@param backward if true the first identifier is searched from the end of the expression | [
"Highlights",
"consecutive",
"occurrences",
"of",
"identifiers",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/mml/MathDoc.java#L290-L295 |
2,027 | ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/SubTreeComparison.java | SubTreeComparison.getSimilarities | @NotNull
public List<Match> getSimilarities(MathNode refTree, MathNode compTree, boolean onlyOperators) {
List<Match> similarities = new ArrayList<>();
findSimilarities(refTree, compTree, similarities, false, onlyOperators);
return similarities;
} | java | @NotNull
public List<Match> getSimilarities(MathNode refTree, MathNode compTree, boolean onlyOperators) {
List<Match> similarities = new ArrayList<>();
findSimilarities(refTree, compTree, similarities, false, onlyOperators);
return similarities;
} | [
"@",
"NotNull",
"public",
"List",
"<",
"Match",
">",
"getSimilarities",
"(",
"MathNode",
"refTree",
",",
"MathNode",
"compTree",
",",
"boolean",
"onlyOperators",
")",
"{",
"List",
"<",
"Match",
">",
"similarities",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"findSimilarities",
"(",
"refTree",
",",
"compTree",
",",
"similarities",
",",
"false",
",",
"onlyOperators",
")",
";",
"return",
"similarities",
";",
"}"
] | Get a list of similarities between the reference and comparison tree.
@param refTree Reference MathNode tree
@param compTree Comparison MathNode tree
@param onlyOperators find similarities only between operations, leafs are not checked
@return list of similarities, list can be empty but never null | [
"Get",
"a",
"list",
"of",
"similarities",
"between",
"the",
"reference",
"and",
"comparison",
"tree",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/SubTreeComparison.java#L41-L46 |
2,028 | ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/SubTreeComparison.java | SubTreeComparison.findSimilarities | boolean findSimilarities(MathNode refTree, MathNode comTree, List<Match> similarities, boolean holdRefTree, boolean onlyOperators) {
if (isIdenticalTree(refTree, comTree)) {
// hit!
comTree.setMarked();
similarities.add(new Match(refTree, comTree, type));
return true;
}
// iterate the comparison tree over the current node from the ref tree
for (MathNode compChild : comTree.getChildren()) {
// don't look at leafs if it is already marked
// or we only want to compare branching nodes
if (compChild.isMarked() || onlyOperators && compChild.isLeaf()) {
continue;
}
// go deeper in the comp. tree but hold the ref tree
if (findSimilarities(refTree, compChild, similarities, true, onlyOperators)) {
return true;
}
}
if (!holdRefTree) {
// go deeper in the reference tree
for (MathNode refChild : refTree.getChildren()) {
if (onlyOperators && refChild.isLeaf()) {
continue;
}
findSimilarities(refChild, comTree, similarities, false, onlyOperators);
}
}
return false;
} | java | boolean findSimilarities(MathNode refTree, MathNode comTree, List<Match> similarities, boolean holdRefTree, boolean onlyOperators) {
if (isIdenticalTree(refTree, comTree)) {
// hit!
comTree.setMarked();
similarities.add(new Match(refTree, comTree, type));
return true;
}
// iterate the comparison tree over the current node from the ref tree
for (MathNode compChild : comTree.getChildren()) {
// don't look at leafs if it is already marked
// or we only want to compare branching nodes
if (compChild.isMarked() || onlyOperators && compChild.isLeaf()) {
continue;
}
// go deeper in the comp. tree but hold the ref tree
if (findSimilarities(refTree, compChild, similarities, true, onlyOperators)) {
return true;
}
}
if (!holdRefTree) {
// go deeper in the reference tree
for (MathNode refChild : refTree.getChildren()) {
if (onlyOperators && refChild.isLeaf()) {
continue;
}
findSimilarities(refChild, comTree, similarities, false, onlyOperators);
}
}
return false;
} | [
"boolean",
"findSimilarities",
"(",
"MathNode",
"refTree",
",",
"MathNode",
"comTree",
",",
"List",
"<",
"Match",
">",
"similarities",
",",
"boolean",
"holdRefTree",
",",
"boolean",
"onlyOperators",
")",
"{",
"if",
"(",
"isIdenticalTree",
"(",
"refTree",
",",
"comTree",
")",
")",
"{",
"// hit!",
"comTree",
".",
"setMarked",
"(",
")",
";",
"similarities",
".",
"add",
"(",
"new",
"Match",
"(",
"refTree",
",",
"comTree",
",",
"type",
")",
")",
";",
"return",
"true",
";",
"}",
"// iterate the comparison tree over the current node from the ref tree",
"for",
"(",
"MathNode",
"compChild",
":",
"comTree",
".",
"getChildren",
"(",
")",
")",
"{",
"// don't look at leafs if it is already marked",
"// or we only want to compare branching nodes",
"if",
"(",
"compChild",
".",
"isMarked",
"(",
")",
"||",
"onlyOperators",
"&&",
"compChild",
".",
"isLeaf",
"(",
")",
")",
"{",
"continue",
";",
"}",
"// go deeper in the comp. tree but hold the ref tree",
"if",
"(",
"findSimilarities",
"(",
"refTree",
",",
"compChild",
",",
"similarities",
",",
"true",
",",
"onlyOperators",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"holdRefTree",
")",
"{",
"// go deeper in the reference tree",
"for",
"(",
"MathNode",
"refChild",
":",
"refTree",
".",
"getChildren",
"(",
")",
")",
"{",
"if",
"(",
"onlyOperators",
"&&",
"refChild",
".",
"isLeaf",
"(",
")",
")",
"{",
"continue",
";",
"}",
"findSimilarities",
"(",
"refChild",
",",
"comTree",
",",
"similarities",
",",
"false",
",",
"onlyOperators",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Recursive method that goes along every node of the reference tree and tries to find
identical subtree with the comparison tree.
@param refTree Reference MathNode tree
@param comTree Comparison MathNode tree
@param similarities List of similarities, will be filled during process.
@param holdRefTree Hold the reference tree in position and only iterate over the comparison tree
@param onlyOperators Find similarities only between operations, no single identifier (end leafs) are checked
@return true - if the current aTree ad bTree are identical subtrees, false otherwise | [
"Recursive",
"method",
"that",
"goes",
"along",
"every",
"node",
"of",
"the",
"reference",
"tree",
"and",
"tries",
"to",
"find",
"identical",
"subtree",
"with",
"the",
"comparison",
"tree",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/SubTreeComparison.java#L59-L89 |
2,029 | ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/SubTreeComparison.java | SubTreeComparison.isIdenticalTree | boolean isIdenticalTree(MathNode aTree, MathNode bTree) {
// first check if they have the same number of children
if (aTree.equals(bTree) && aTree.getChildren().size() == bTree.getChildren().size()) {
if (aTree.isOrderSensitive()) {
// all children order sensitive
for (int i = 0; i < aTree.getChildren().size(); i++) {
if (!isIdenticalTree(aTree.getChildren().get(i), bTree.getChildren().get(i))) {
return false;
}
}
} else {
// order insensitive
List<MathNode> bChildren = new ArrayList<>(bTree.getChildren());
OUTER:
for (MathNode aChild : aTree.getChildren()) {
for (MathNode bChild : filterSameChildren(aChild, bChildren)) {
if (isIdenticalTree(aChild, bChild)) {
// found an identical child
bChildren.remove(bChild);
continue OUTER;
}
}
// aChild is missing in bChildren
return false;
}
}
return true;
}
return false;
} | java | boolean isIdenticalTree(MathNode aTree, MathNode bTree) {
// first check if they have the same number of children
if (aTree.equals(bTree) && aTree.getChildren().size() == bTree.getChildren().size()) {
if (aTree.isOrderSensitive()) {
// all children order sensitive
for (int i = 0; i < aTree.getChildren().size(); i++) {
if (!isIdenticalTree(aTree.getChildren().get(i), bTree.getChildren().get(i))) {
return false;
}
}
} else {
// order insensitive
List<MathNode> bChildren = new ArrayList<>(bTree.getChildren());
OUTER:
for (MathNode aChild : aTree.getChildren()) {
for (MathNode bChild : filterSameChildren(aChild, bChildren)) {
if (isIdenticalTree(aChild, bChild)) {
// found an identical child
bChildren.remove(bChild);
continue OUTER;
}
}
// aChild is missing in bChildren
return false;
}
}
return true;
}
return false;
} | [
"boolean",
"isIdenticalTree",
"(",
"MathNode",
"aTree",
",",
"MathNode",
"bTree",
")",
"{",
"// first check if they have the same number of children",
"if",
"(",
"aTree",
".",
"equals",
"(",
"bTree",
")",
"&&",
"aTree",
".",
"getChildren",
"(",
")",
".",
"size",
"(",
")",
"==",
"bTree",
".",
"getChildren",
"(",
")",
".",
"size",
"(",
")",
")",
"{",
"if",
"(",
"aTree",
".",
"isOrderSensitive",
"(",
")",
")",
"{",
"// all children order sensitive",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"aTree",
".",
"getChildren",
"(",
")",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"isIdenticalTree",
"(",
"aTree",
".",
"getChildren",
"(",
")",
".",
"get",
"(",
"i",
")",
",",
"bTree",
".",
"getChildren",
"(",
")",
".",
"get",
"(",
"i",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"else",
"{",
"// order insensitive",
"List",
"<",
"MathNode",
">",
"bChildren",
"=",
"new",
"ArrayList",
"<>",
"(",
"bTree",
".",
"getChildren",
"(",
")",
")",
";",
"OUTER",
":",
"for",
"(",
"MathNode",
"aChild",
":",
"aTree",
".",
"getChildren",
"(",
")",
")",
"{",
"for",
"(",
"MathNode",
"bChild",
":",
"filterSameChildren",
"(",
"aChild",
",",
"bChildren",
")",
")",
"{",
"if",
"(",
"isIdenticalTree",
"(",
"aChild",
",",
"bChild",
")",
")",
"{",
"// found an identical child",
"bChildren",
".",
"remove",
"(",
"bChild",
")",
";",
"continue",
"OUTER",
";",
"}",
"}",
"// aChild is missing in bChildren",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Are aTree and bTree identical subtrees? If the root node is equal,
all subsequent children will be compared.
@param aTree first MathNode tree
@param bTree second MathNode tree
@return true - if both trees are identical subtrees, false otherwise | [
"Are",
"aTree",
"and",
"bTree",
"identical",
"subtrees?",
"If",
"the",
"root",
"node",
"is",
"equal",
"all",
"subsequent",
"children",
"will",
"be",
"compared",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/SubTreeComparison.java#L99-L128 |
2,030 | ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/SubTreeComparison.java | SubTreeComparison.getCoverage | public static double getCoverage(List<MathNode> refLeafs, List<MathNode> compLeafs) {
if (compLeafs.size() == 0) {
return 1.;
}
HashMultiset<MathNode> tmp = HashMultiset.create();
tmp.addAll(compLeafs);
tmp.removeAll(refLeafs);
return 1 - (double) tmp.size() / (double) compLeafs.size();
} | java | public static double getCoverage(List<MathNode> refLeafs, List<MathNode> compLeafs) {
if (compLeafs.size() == 0) {
return 1.;
}
HashMultiset<MathNode> tmp = HashMultiset.create();
tmp.addAll(compLeafs);
tmp.removeAll(refLeafs);
return 1 - (double) tmp.size() / (double) compLeafs.size();
} | [
"public",
"static",
"double",
"getCoverage",
"(",
"List",
"<",
"MathNode",
">",
"refLeafs",
",",
"List",
"<",
"MathNode",
">",
"compLeafs",
")",
"{",
"if",
"(",
"compLeafs",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"return",
"1.",
";",
"}",
"HashMultiset",
"<",
"MathNode",
">",
"tmp",
"=",
"HashMultiset",
".",
"create",
"(",
")",
";",
"tmp",
".",
"addAll",
"(",
"compLeafs",
")",
";",
"tmp",
".",
"removeAll",
"(",
"refLeafs",
")",
";",
"return",
"1",
"-",
"(",
"double",
")",
"tmp",
".",
"size",
"(",
")",
"/",
"(",
"double",
")",
"compLeafs",
".",
"size",
"(",
")",
";",
"}"
] | Calculate the coverage factor between two trees, whereas only their leafs
are considered. Leafs are typically identifiers or constants.
@param refLeafs all leafs from the partial (or full) reference tree
@param compLeafs all leafs from the partial (or full) comparison tree
@return coverage factor between 0 to 1, 1 is a full-match | [
"Calculate",
"the",
"coverage",
"factor",
"between",
"two",
"trees",
"whereas",
"only",
"their",
"leafs",
"are",
"considered",
".",
"Leafs",
"are",
"typically",
"identifiers",
"or",
"constants",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/SubTreeComparison.java#L153-L161 |
2,031 | ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/node/MathNodeGenerator.java | MathNodeGenerator.printMathNode | public static String printMathNode(MathNode node, String indent) {
StringBuilder sb = new StringBuilder(indent + node.toString() + "\n");
node.getChildren().forEach(n -> sb.append(printMathNode(n, indent + " ")));
return sb.toString();
} | java | public static String printMathNode(MathNode node, String indent) {
StringBuilder sb = new StringBuilder(indent + node.toString() + "\n");
node.getChildren().forEach(n -> sb.append(printMathNode(n, indent + " ")));
return sb.toString();
} | [
"public",
"static",
"String",
"printMathNode",
"(",
"MathNode",
"node",
",",
"String",
"indent",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"indent",
"+",
"node",
".",
"toString",
"(",
")",
"+",
"\"\\n\"",
")",
";",
"node",
".",
"getChildren",
"(",
")",
".",
"forEach",
"(",
"n",
"->",
"sb",
".",
"append",
"(",
"printMathNode",
"(",
"n",
",",
"indent",
"+",
"\" \"",
")",
")",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Converts a MathNode into a an simplistic indented tree
representation of itself.
@param node Node to begin with and onwards for all children of it.
@param indent starting line used as an indent (e.g. start with "")
@return return a tree representation of itself | [
"Converts",
"a",
"MathNode",
"into",
"a",
"an",
"simplistic",
"indented",
"tree",
"representation",
"of",
"itself",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/node/MathNodeGenerator.java#L124-L128 |
2,032 | ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/MathPlag.java | MathPlag.compareOriginalFactors | public static Map<String, Object> compareOriginalFactors(String refMathML, String compMathML) throws XPathExpressionException {
try {
CMMLInfo refDoc = new CMMLInfo(refMathML);
CMMLInfo compDoc = new CMMLInfo(compMathML);
// compute factors
final Integer depth = compDoc.getDepth(refDoc.getXQuery());
final Double coverage = compDoc.getCoverage(refDoc.getElements());
Boolean formula = compDoc.isEquation(true);
Boolean structMatch = compDoc.toStrictCmml().abstract2CDs()
.isMatch(refDoc.toStrictCmml().abstract2CDs().getXQuery());
Boolean dataMatch = new CMMLInfo(compMathML).toStrictCmml().abstract2DTs()
.isMatch(new CMMLInfo(refMathML).toStrictCmml().abstract2DTs().getXQuery());
HashMap<String, Object> result = new HashMap<>();
result.put("depth", depth);
result.put("coverage", coverage);
result.put("structureMatch", structMatch);
result.put("dataMatch", dataMatch);
result.put("isEquation", formula);
return result;
} catch (Exception e) {
// log and throw in this case
logger.error(String.format("mathml comparison failed (refMathML: %s) (compMathML: %s)", refMathML, compMathML), e);
throw e;
}
} | java | public static Map<String, Object> compareOriginalFactors(String refMathML, String compMathML) throws XPathExpressionException {
try {
CMMLInfo refDoc = new CMMLInfo(refMathML);
CMMLInfo compDoc = new CMMLInfo(compMathML);
// compute factors
final Integer depth = compDoc.getDepth(refDoc.getXQuery());
final Double coverage = compDoc.getCoverage(refDoc.getElements());
Boolean formula = compDoc.isEquation(true);
Boolean structMatch = compDoc.toStrictCmml().abstract2CDs()
.isMatch(refDoc.toStrictCmml().abstract2CDs().getXQuery());
Boolean dataMatch = new CMMLInfo(compMathML).toStrictCmml().abstract2DTs()
.isMatch(new CMMLInfo(refMathML).toStrictCmml().abstract2DTs().getXQuery());
HashMap<String, Object> result = new HashMap<>();
result.put("depth", depth);
result.put("coverage", coverage);
result.put("structureMatch", structMatch);
result.put("dataMatch", dataMatch);
result.put("isEquation", formula);
return result;
} catch (Exception e) {
// log and throw in this case
logger.error(String.format("mathml comparison failed (refMathML: %s) (compMathML: %s)", refMathML, compMathML), e);
throw e;
}
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"compareOriginalFactors",
"(",
"String",
"refMathML",
",",
"String",
"compMathML",
")",
"throws",
"XPathExpressionException",
"{",
"try",
"{",
"CMMLInfo",
"refDoc",
"=",
"new",
"CMMLInfo",
"(",
"refMathML",
")",
";",
"CMMLInfo",
"compDoc",
"=",
"new",
"CMMLInfo",
"(",
"compMathML",
")",
";",
"// compute factors",
"final",
"Integer",
"depth",
"=",
"compDoc",
".",
"getDepth",
"(",
"refDoc",
".",
"getXQuery",
"(",
")",
")",
";",
"final",
"Double",
"coverage",
"=",
"compDoc",
".",
"getCoverage",
"(",
"refDoc",
".",
"getElements",
"(",
")",
")",
";",
"Boolean",
"formula",
"=",
"compDoc",
".",
"isEquation",
"(",
"true",
")",
";",
"Boolean",
"structMatch",
"=",
"compDoc",
".",
"toStrictCmml",
"(",
")",
".",
"abstract2CDs",
"(",
")",
".",
"isMatch",
"(",
"refDoc",
".",
"toStrictCmml",
"(",
")",
".",
"abstract2CDs",
"(",
")",
".",
"getXQuery",
"(",
")",
")",
";",
"Boolean",
"dataMatch",
"=",
"new",
"CMMLInfo",
"(",
"compMathML",
")",
".",
"toStrictCmml",
"(",
")",
".",
"abstract2DTs",
"(",
")",
".",
"isMatch",
"(",
"new",
"CMMLInfo",
"(",
"refMathML",
")",
".",
"toStrictCmml",
"(",
")",
".",
"abstract2DTs",
"(",
")",
".",
"getXQuery",
"(",
")",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"result",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"result",
".",
"put",
"(",
"\"depth\"",
",",
"depth",
")",
";",
"result",
".",
"put",
"(",
"\"coverage\"",
",",
"coverage",
")",
";",
"result",
".",
"put",
"(",
"\"structureMatch\"",
",",
"structMatch",
")",
";",
"result",
".",
"put",
"(",
"\"dataMatch\"",
",",
"dataMatch",
")",
";",
"result",
".",
"put",
"(",
"\"isEquation\"",
",",
"formula",
")",
";",
"return",
"result",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// log and throw in this case",
"logger",
".",
"error",
"(",
"String",
".",
"format",
"(",
"\"mathml comparison failed (refMathML: %s) (compMathML: %s)\"",
",",
"refMathML",
",",
"compMathML",
")",
",",
"e",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | Compare two MathML formulas. The return value is a map of similarity factors like matching depth,
element coverage, indicator for structural or data match and if the comparison formula holds an
equation.
@param refMathML Reference MathML string (must contain pMML and cMML)
@param compMathML Comparison MathML string (must contain pMML and cMML)
@return map of all found factors (depth, coverage, structureMatch, dataMatch, isEquation)
@throws XPathExpressionException could hint towards a bug | [
"Compare",
"two",
"MathML",
"formulas",
".",
"The",
"return",
"value",
"is",
"a",
"map",
"of",
"similarity",
"factors",
"like",
"matching",
"depth",
"element",
"coverage",
"indicator",
"for",
"structural",
"or",
"data",
"match",
"and",
"if",
"the",
"comparison",
"formula",
"holds",
"an",
"equation",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/MathPlag.java#L99-L124 |
2,033 | ag-gipp/MathMLTools | mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java | CommandExecutor.exec | public NativeResponse exec(long timeoutMs, Level logLevel) {
return exec(timeoutMs, TimeUnit.MILLISECONDS, logLevel);
} | java | public NativeResponse exec(long timeoutMs, Level logLevel) {
return exec(timeoutMs, TimeUnit.MILLISECONDS, logLevel);
} | [
"public",
"NativeResponse",
"exec",
"(",
"long",
"timeoutMs",
",",
"Level",
"logLevel",
")",
"{",
"return",
"exec",
"(",
"timeoutMs",
",",
"TimeUnit",
".",
"MILLISECONDS",
",",
"logLevel",
")",
";",
"}"
] | Execute with a given timeout and sets the log level for the
error output stream.
@param timeoutMs a
@param logLevel a
@return a | [
"Execute",
"with",
"a",
"given",
"timeout",
"and",
"sets",
"the",
"log",
"level",
"for",
"the",
"error",
"output",
"stream",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java#L143-L145 |
2,034 | ag-gipp/MathMLTools | mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java | CommandExecutor.exec | public NativeResponse exec(long timeout, TimeUnit unit, Level logLevel) {
return internalexec(timeout, unit, logLevel);
} | java | public NativeResponse exec(long timeout, TimeUnit unit, Level logLevel) {
return internalexec(timeout, unit, logLevel);
} | [
"public",
"NativeResponse",
"exec",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
",",
"Level",
"logLevel",
")",
"{",
"return",
"internalexec",
"(",
"timeout",
",",
"unit",
",",
"logLevel",
")",
";",
"}"
] | Combination of everything before.
@param timeout a
@param unit a
@param logLevel a
@return a | [
"Combination",
"of",
"everything",
"before",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java#L186-L188 |
2,035 | ag-gipp/MathMLTools | mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java | CommandExecutor.safetyExit | private void safetyExit(Process process) throws IOException {
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
} | java | private void safetyExit(Process process) throws IOException {
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
} | [
"private",
"void",
"safetyExit",
"(",
"Process",
"process",
")",
"throws",
"IOException",
"{",
"process",
".",
"getErrorStream",
"(",
")",
".",
"close",
"(",
")",
";",
"process",
".",
"getInputStream",
"(",
")",
".",
"close",
"(",
")",
";",
"process",
".",
"getOutputStream",
"(",
")",
".",
"close",
"(",
")",
";",
"}"
] | Has to be done in the end manually. Close all streams manually.
@param process process with open streams
@throws IOException if something went wrong due closing streams | [
"Has",
"to",
"be",
"done",
"in",
"the",
"end",
"manually",
".",
"Close",
"all",
"streams",
"manually",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java#L253-L257 |
2,036 | ag-gipp/MathMLTools | mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java | CommandExecutor.commandCheck | public static boolean commandCheck(String nativeCommand) {
CommandExecutor executor = new CommandExecutor(
"DefinitionCheck", "which", nativeCommand
);
NativeResponse res = executor.exec(100);
return res.getStatusCode() == 0;
} | java | public static boolean commandCheck(String nativeCommand) {
CommandExecutor executor = new CommandExecutor(
"DefinitionCheck", "which", nativeCommand
);
NativeResponse res = executor.exec(100);
return res.getStatusCode() == 0;
} | [
"public",
"static",
"boolean",
"commandCheck",
"(",
"String",
"nativeCommand",
")",
"{",
"CommandExecutor",
"executor",
"=",
"new",
"CommandExecutor",
"(",
"\"DefinitionCheck\"",
",",
"\"which\"",
",",
"nativeCommand",
")",
";",
"NativeResponse",
"res",
"=",
"executor",
".",
"exec",
"(",
"100",
")",
";",
"return",
"res",
".",
"getStatusCode",
"(",
")",
"==",
"0",
";",
"}"
] | Checks if the given native command exists. No error will be thrown.
The program waits for 100 milliseconds. That's enough to find out if
the program exists or not.
@param nativeCommand The command you want to check
@return true if the command can be executed or false if not. | [
"Checks",
"if",
"the",
"given",
"native",
"command",
"exists",
".",
"No",
"error",
"will",
"be",
"thrown",
".",
"The",
"program",
"waits",
"for",
"100",
"milliseconds",
".",
"That",
"s",
"enough",
"to",
"find",
"out",
"if",
"the",
"program",
"exists",
"or",
"not",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-utils/src/main/java/com/formulasearchengine/mathmltools/nativetools/CommandExecutor.java#L267-L273 |
2,037 | ag-gipp/MathMLTools | mathml-utils/src/main/java/com/formulasearchengine/mathmltools/utils/Utility.java | Utility.latexPreProcessing | public static String latexPreProcessing(String latex) {
LOG.debug(" Pre-Processing for: " + latex);
if (latex.contains("subarray")) {
latex = latex.replaceAll("subarray", "array");
LOG.trace(" Eval replacement of subarray: " + latex);
}
latex = latex.replaceAll(POM_BUG_AVOIDANCE_UNDERSCORE, "_{$1}");
LOG.trace("Surround underscore: " + latex);
latex = latex.replaceAll(SINGLE_AND, TMP_SINGLE_AND);
latex = HtmlEscape.unescapeHtml(latex);
latex = latex.replaceAll(TMP_SINGLE_AND, " & ");
LOG.trace("HTML Unescaped: " + latex);
latex = latex.replaceAll(LATEX_COMMENTED_LINEBREAK, "");
LOG.trace("Commented linebreaks: " + latex);
latex = latex.replaceAll(ELEMINATE_ENDINGS, "");
latex = latex.replaceAll(ELEMINATE_STARTS, "");
latex = latex.replaceAll(ELEMINATE_SIMPLE_STARTS, "");
latex = latex.replaceAll(ELEMINATE_SIMPLE_ENDS, "");
LOG.trace("Replace bad end/start:" + latex);
LOG.debug("Finalize Pre-Processing for POM-Tagger: " + latex);
return latex;
} | java | public static String latexPreProcessing(String latex) {
LOG.debug(" Pre-Processing for: " + latex);
if (latex.contains("subarray")) {
latex = latex.replaceAll("subarray", "array");
LOG.trace(" Eval replacement of subarray: " + latex);
}
latex = latex.replaceAll(POM_BUG_AVOIDANCE_UNDERSCORE, "_{$1}");
LOG.trace("Surround underscore: " + latex);
latex = latex.replaceAll(SINGLE_AND, TMP_SINGLE_AND);
latex = HtmlEscape.unescapeHtml(latex);
latex = latex.replaceAll(TMP_SINGLE_AND, " & ");
LOG.trace("HTML Unescaped: " + latex);
latex = latex.replaceAll(LATEX_COMMENTED_LINEBREAK, "");
LOG.trace("Commented linebreaks: " + latex);
latex = latex.replaceAll(ELEMINATE_ENDINGS, "");
latex = latex.replaceAll(ELEMINATE_STARTS, "");
latex = latex.replaceAll(ELEMINATE_SIMPLE_STARTS, "");
latex = latex.replaceAll(ELEMINATE_SIMPLE_ENDS, "");
LOG.trace("Replace bad end/start:" + latex);
LOG.debug("Finalize Pre-Processing for POM-Tagger: " + latex);
return latex;
} | [
"public",
"static",
"String",
"latexPreProcessing",
"(",
"String",
"latex",
")",
"{",
"LOG",
".",
"debug",
"(",
"\" Pre-Processing for: \"",
"+",
"latex",
")",
";",
"if",
"(",
"latex",
".",
"contains",
"(",
"\"subarray\"",
")",
")",
"{",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"\"subarray\"",
",",
"\"array\"",
")",
";",
"LOG",
".",
"trace",
"(",
"\" Eval replacement of subarray: \"",
"+",
"latex",
")",
";",
"}",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"POM_BUG_AVOIDANCE_UNDERSCORE",
",",
"\"_{$1}\"",
")",
";",
"LOG",
".",
"trace",
"(",
"\"Surround underscore: \"",
"+",
"latex",
")",
";",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"SINGLE_AND",
",",
"TMP_SINGLE_AND",
")",
";",
"latex",
"=",
"HtmlEscape",
".",
"unescapeHtml",
"(",
"latex",
")",
";",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"TMP_SINGLE_AND",
",",
"\" & \"",
")",
";",
"LOG",
".",
"trace",
"(",
"\"HTML Unescaped: \"",
"+",
"latex",
")",
";",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"LATEX_COMMENTED_LINEBREAK",
",",
"\"\"",
")",
";",
"LOG",
".",
"trace",
"(",
"\"Commented linebreaks: \"",
"+",
"latex",
")",
";",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"ELEMINATE_ENDINGS",
",",
"\"\"",
")",
";",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"ELEMINATE_STARTS",
",",
"\"\"",
")",
";",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"ELEMINATE_SIMPLE_STARTS",
",",
"\"\"",
")",
";",
"latex",
"=",
"latex",
".",
"replaceAll",
"(",
"ELEMINATE_SIMPLE_ENDS",
",",
"\"\"",
")",
";",
"LOG",
".",
"trace",
"(",
"\"Replace bad end/start:\"",
"+",
"latex",
")",
";",
"LOG",
".",
"debug",
"(",
"\"Finalize Pre-Processing for POM-Tagger: \"",
"+",
"latex",
")",
";",
"return",
"latex",
";",
"}"
] | Pre processing mathematical latex expressions with
several methods.
@param latex raw latex input
@return pre processed latex string | [
"Pre",
"processing",
"mathematical",
"latex",
"expressions",
"with",
"several",
"methods",
"."
] | 77c69b6366a5b8720796d1cd9d155ba26c2f1b20 | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-utils/src/main/java/com/formulasearchengine/mathmltools/utils/Utility.java#L59-L86 |
2,038 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/XmlDoclet.java | XmlDoclet.save | public static void save(CommandLine commandLine, Root root) {
if (commandLine.hasOption("dryrun")) {
return;
}
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
JAXBContext contextObj = JAXBContext.newInstance(Root.class);
Marshaller marshaller = contextObj.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
if (commandLine.hasOption("docencoding")) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, commandLine.getOptionValue("docencoding"));
}
String filename = "javadoc.xml";
if (commandLine.hasOption("filename")) {
filename = commandLine.getOptionValue("filename");
}
if (commandLine.hasOption("d")) {
filename = commandLine.getOptionValue("d") + File.separator + filename;
}
fileOutputStream = new FileOutputStream(filename);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream, 1024 * 1024);
marshaller.marshal(root, bufferedOutputStream);
bufferedOutputStream.flush();
fileOutputStream.flush();
} catch (JAXBException e) {
log.error(e.getMessage(), e);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
if (bufferedOutputStream != null) {
bufferedOutputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
} | java | public static void save(CommandLine commandLine, Root root) {
if (commandLine.hasOption("dryrun")) {
return;
}
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
JAXBContext contextObj = JAXBContext.newInstance(Root.class);
Marshaller marshaller = contextObj.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
if (commandLine.hasOption("docencoding")) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, commandLine.getOptionValue("docencoding"));
}
String filename = "javadoc.xml";
if (commandLine.hasOption("filename")) {
filename = commandLine.getOptionValue("filename");
}
if (commandLine.hasOption("d")) {
filename = commandLine.getOptionValue("d") + File.separator + filename;
}
fileOutputStream = new FileOutputStream(filename);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream, 1024 * 1024);
marshaller.marshal(root, bufferedOutputStream);
bufferedOutputStream.flush();
fileOutputStream.flush();
} catch (JAXBException e) {
log.error(e.getMessage(), e);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
if (bufferedOutputStream != null) {
bufferedOutputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
} | [
"public",
"static",
"void",
"save",
"(",
"CommandLine",
"commandLine",
",",
"Root",
"root",
")",
"{",
"if",
"(",
"commandLine",
".",
"hasOption",
"(",
"\"dryrun\"",
")",
")",
"{",
"return",
";",
"}",
"FileOutputStream",
"fileOutputStream",
"=",
"null",
";",
"BufferedOutputStream",
"bufferedOutputStream",
"=",
"null",
";",
"try",
"{",
"JAXBContext",
"contextObj",
"=",
"JAXBContext",
".",
"newInstance",
"(",
"Root",
".",
"class",
")",
";",
"Marshaller",
"marshaller",
"=",
"contextObj",
".",
"createMarshaller",
"(",
")",
";",
"marshaller",
".",
"setProperty",
"(",
"Marshaller",
".",
"JAXB_FORMATTED_OUTPUT",
",",
"true",
")",
";",
"if",
"(",
"commandLine",
".",
"hasOption",
"(",
"\"docencoding\"",
")",
")",
"{",
"marshaller",
".",
"setProperty",
"(",
"Marshaller",
".",
"JAXB_ENCODING",
",",
"commandLine",
".",
"getOptionValue",
"(",
"\"docencoding\"",
")",
")",
";",
"}",
"String",
"filename",
"=",
"\"javadoc.xml\"",
";",
"if",
"(",
"commandLine",
".",
"hasOption",
"(",
"\"filename\"",
")",
")",
"{",
"filename",
"=",
"commandLine",
".",
"getOptionValue",
"(",
"\"filename\"",
")",
";",
"}",
"if",
"(",
"commandLine",
".",
"hasOption",
"(",
"\"d\"",
")",
")",
"{",
"filename",
"=",
"commandLine",
".",
"getOptionValue",
"(",
"\"d\"",
")",
"+",
"File",
".",
"separator",
"+",
"filename",
";",
"}",
"fileOutputStream",
"=",
"new",
"FileOutputStream",
"(",
"filename",
")",
";",
"bufferedOutputStream",
"=",
"new",
"BufferedOutputStream",
"(",
"fileOutputStream",
",",
"1024",
"*",
"1024",
")",
";",
"marshaller",
".",
"marshal",
"(",
"root",
",",
"bufferedOutputStream",
")",
";",
"bufferedOutputStream",
".",
"flush",
"(",
")",
";",
"fileOutputStream",
".",
"flush",
"(",
")",
";",
"}",
"catch",
"(",
"JAXBException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"if",
"(",
"bufferedOutputStream",
"!=",
"null",
")",
"{",
"bufferedOutputStream",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"fileOutputStream",
"!=",
"null",
")",
"{",
"fileOutputStream",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Save XML object model to a file via JAXB.
@param commandLine
the parsed command line arguments
@param root
the document root | [
"Save",
"XML",
"object",
"model",
"to",
"a",
"file",
"via",
"JAXB",
"."
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/XmlDoclet.java#L157-L206 |
2,039 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/XmlDoclet.java | XmlDoclet.parseCommandLine | public static CommandLine parseCommandLine(String[][] optionsArrayArray) {
try {
List<String> argumentList = new ArrayList<String>();
for (String[] optionsArray : optionsArrayArray) {
argumentList.addAll(Arrays.asList(optionsArray));
}
CommandLineParser commandLineParser = new BasicParser() {
@Override
protected void processOption(final String arg, @SuppressWarnings("rawtypes") final ListIterator iter)
throws ParseException {
boolean hasOption = getOptions().hasOption(arg);
if (hasOption) {
super.processOption(arg, iter);
}
}
};
CommandLine commandLine = commandLineParser.parse(options, argumentList.toArray(new String[] {}));
return commandLine;
} catch (ParseException e) {
LoggingOutputStream loggingOutputStream = new LoggingOutputStream(log, LoggingLevelEnum.INFO);
PrintWriter printWriter = new PrintWriter(loggingOutputStream);
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(printWriter, 74, "javadoc -doclet " + XmlDoclet.class.getName() + " [options]",
null, options, 1, 3, null, false);
return null;
}
} | java | public static CommandLine parseCommandLine(String[][] optionsArrayArray) {
try {
List<String> argumentList = new ArrayList<String>();
for (String[] optionsArray : optionsArrayArray) {
argumentList.addAll(Arrays.asList(optionsArray));
}
CommandLineParser commandLineParser = new BasicParser() {
@Override
protected void processOption(final String arg, @SuppressWarnings("rawtypes") final ListIterator iter)
throws ParseException {
boolean hasOption = getOptions().hasOption(arg);
if (hasOption) {
super.processOption(arg, iter);
}
}
};
CommandLine commandLine = commandLineParser.parse(options, argumentList.toArray(new String[] {}));
return commandLine;
} catch (ParseException e) {
LoggingOutputStream loggingOutputStream = new LoggingOutputStream(log, LoggingLevelEnum.INFO);
PrintWriter printWriter = new PrintWriter(loggingOutputStream);
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(printWriter, 74, "javadoc -doclet " + XmlDoclet.class.getName() + " [options]",
null, options, 1, 3, null, false);
return null;
}
} | [
"public",
"static",
"CommandLine",
"parseCommandLine",
"(",
"String",
"[",
"]",
"[",
"]",
"optionsArrayArray",
")",
"{",
"try",
"{",
"List",
"<",
"String",
">",
"argumentList",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"for",
"(",
"String",
"[",
"]",
"optionsArray",
":",
"optionsArrayArray",
")",
"{",
"argumentList",
".",
"addAll",
"(",
"Arrays",
".",
"asList",
"(",
"optionsArray",
")",
")",
";",
"}",
"CommandLineParser",
"commandLineParser",
"=",
"new",
"BasicParser",
"(",
")",
"{",
"@",
"Override",
"protected",
"void",
"processOption",
"(",
"final",
"String",
"arg",
",",
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"final",
"ListIterator",
"iter",
")",
"throws",
"ParseException",
"{",
"boolean",
"hasOption",
"=",
"getOptions",
"(",
")",
".",
"hasOption",
"(",
"arg",
")",
";",
"if",
"(",
"hasOption",
")",
"{",
"super",
".",
"processOption",
"(",
"arg",
",",
"iter",
")",
";",
"}",
"}",
"}",
";",
"CommandLine",
"commandLine",
"=",
"commandLineParser",
".",
"parse",
"(",
"options",
",",
"argumentList",
".",
"toArray",
"(",
"new",
"String",
"[",
"]",
"{",
"}",
")",
")",
";",
"return",
"commandLine",
";",
"}",
"catch",
"(",
"ParseException",
"e",
")",
"{",
"LoggingOutputStream",
"loggingOutputStream",
"=",
"new",
"LoggingOutputStream",
"(",
"log",
",",
"LoggingLevelEnum",
".",
"INFO",
")",
";",
"PrintWriter",
"printWriter",
"=",
"new",
"PrintWriter",
"(",
"loggingOutputStream",
")",
";",
"HelpFormatter",
"helpFormatter",
"=",
"new",
"HelpFormatter",
"(",
")",
";",
"helpFormatter",
".",
"printHelp",
"(",
"printWriter",
",",
"74",
",",
"\"javadoc -doclet \"",
"+",
"XmlDoclet",
".",
"class",
".",
"getName",
"(",
")",
"+",
"\" [options]\"",
",",
"null",
",",
"options",
",",
"1",
",",
"3",
",",
"null",
",",
"false",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Parse the given options.
@param optionsArrayArray
The two dimensional array of options.
@return the parsed command line arguments. | [
"Parse",
"the",
"given",
"options",
"."
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/XmlDoclet.java#L232-L260 |
2,040 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java | Parser.parseRootDoc | public Root parseRootDoc(RootDoc rootDoc) {
Root rootNode = objectFactory.createRoot();
for (ClassDoc classDoc : rootDoc.classes()) {
PackageDoc packageDoc = classDoc.containingPackage();
Package packageNode = packages.get(packageDoc.name());
if (packageNode == null) {
packageNode = parsePackage(packageDoc);
packages.put(packageDoc.name(), packageNode);
rootNode.getPackage().add(packageNode);
}
if (classDoc instanceof AnnotationTypeDoc) {
packageNode.getAnnotation().add(parseAnnotationTypeDoc((AnnotationTypeDoc) classDoc));
} else if (classDoc.isEnum()) {
packageNode.getEnum().add(parseEnum(classDoc));
} else if (classDoc.isInterface()) {
packageNode.getInterface().add(parseInterface(classDoc));
} else {
packageNode.getClazz().add(parseClass(classDoc));
}
}
return rootNode;
} | java | public Root parseRootDoc(RootDoc rootDoc) {
Root rootNode = objectFactory.createRoot();
for (ClassDoc classDoc : rootDoc.classes()) {
PackageDoc packageDoc = classDoc.containingPackage();
Package packageNode = packages.get(packageDoc.name());
if (packageNode == null) {
packageNode = parsePackage(packageDoc);
packages.put(packageDoc.name(), packageNode);
rootNode.getPackage().add(packageNode);
}
if (classDoc instanceof AnnotationTypeDoc) {
packageNode.getAnnotation().add(parseAnnotationTypeDoc((AnnotationTypeDoc) classDoc));
} else if (classDoc.isEnum()) {
packageNode.getEnum().add(parseEnum(classDoc));
} else if (classDoc.isInterface()) {
packageNode.getInterface().add(parseInterface(classDoc));
} else {
packageNode.getClazz().add(parseClass(classDoc));
}
}
return rootNode;
} | [
"public",
"Root",
"parseRootDoc",
"(",
"RootDoc",
"rootDoc",
")",
"{",
"Root",
"rootNode",
"=",
"objectFactory",
".",
"createRoot",
"(",
")",
";",
"for",
"(",
"ClassDoc",
"classDoc",
":",
"rootDoc",
".",
"classes",
"(",
")",
")",
"{",
"PackageDoc",
"packageDoc",
"=",
"classDoc",
".",
"containingPackage",
"(",
")",
";",
"Package",
"packageNode",
"=",
"packages",
".",
"get",
"(",
"packageDoc",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"packageNode",
"==",
"null",
")",
"{",
"packageNode",
"=",
"parsePackage",
"(",
"packageDoc",
")",
";",
"packages",
".",
"put",
"(",
"packageDoc",
".",
"name",
"(",
")",
",",
"packageNode",
")",
";",
"rootNode",
".",
"getPackage",
"(",
")",
".",
"add",
"(",
"packageNode",
")",
";",
"}",
"if",
"(",
"classDoc",
"instanceof",
"AnnotationTypeDoc",
")",
"{",
"packageNode",
".",
"getAnnotation",
"(",
")",
".",
"add",
"(",
"parseAnnotationTypeDoc",
"(",
"(",
"AnnotationTypeDoc",
")",
"classDoc",
")",
")",
";",
"}",
"else",
"if",
"(",
"classDoc",
".",
"isEnum",
"(",
")",
")",
"{",
"packageNode",
".",
"getEnum",
"(",
")",
".",
"add",
"(",
"parseEnum",
"(",
"classDoc",
")",
")",
";",
"}",
"else",
"if",
"(",
"classDoc",
".",
"isInterface",
"(",
")",
")",
"{",
"packageNode",
".",
"getInterface",
"(",
")",
".",
"add",
"(",
"parseInterface",
"(",
"classDoc",
")",
")",
";",
"}",
"else",
"{",
"packageNode",
".",
"getClazz",
"(",
")",
".",
"add",
"(",
"parseClass",
"(",
"classDoc",
")",
")",
";",
"}",
"}",
"return",
"rootNode",
";",
"}"
] | The entry point into parsing the javadoc.
@param rootDoc
The RootDoc intstance obtained via the doclet API
@return The root node, containing everything parsed from javadoc doclet | [
"The",
"entry",
"point",
"into",
"parsing",
"the",
"javadoc",
"."
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java#L67-L92 |
2,041 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java | Parser.parseAnnotationTypeDoc | protected Annotation parseAnnotationTypeDoc(AnnotationTypeDoc annotationTypeDoc) {
Annotation annotationNode = objectFactory.createAnnotation();
annotationNode.setName(annotationTypeDoc.name());
annotationNode.setQualified(annotationTypeDoc.qualifiedName());
String comment = annotationTypeDoc.commentText();
if (comment.length() > 0) {
annotationNode.setComment(comment);
}
annotationNode.setIncluded(annotationTypeDoc.isIncluded());
annotationNode.setScope(parseScope(annotationTypeDoc));
for (AnnotationTypeElementDoc annotationTypeElementDoc : annotationTypeDoc.elements()) {
annotationNode.getElement().add(parseAnnotationTypeElementDoc(annotationTypeElementDoc));
}
for (AnnotationDesc annotationDesc : annotationTypeDoc.annotations()) {
annotationNode.getAnnotation().add(parseAnnotationDesc(annotationDesc, annotationTypeDoc.qualifiedName()));
}
for (Tag tag : annotationTypeDoc.tags()) {
annotationNode.getTag().add(parseTag(tag));
}
return annotationNode;
} | java | protected Annotation parseAnnotationTypeDoc(AnnotationTypeDoc annotationTypeDoc) {
Annotation annotationNode = objectFactory.createAnnotation();
annotationNode.setName(annotationTypeDoc.name());
annotationNode.setQualified(annotationTypeDoc.qualifiedName());
String comment = annotationTypeDoc.commentText();
if (comment.length() > 0) {
annotationNode.setComment(comment);
}
annotationNode.setIncluded(annotationTypeDoc.isIncluded());
annotationNode.setScope(parseScope(annotationTypeDoc));
for (AnnotationTypeElementDoc annotationTypeElementDoc : annotationTypeDoc.elements()) {
annotationNode.getElement().add(parseAnnotationTypeElementDoc(annotationTypeElementDoc));
}
for (AnnotationDesc annotationDesc : annotationTypeDoc.annotations()) {
annotationNode.getAnnotation().add(parseAnnotationDesc(annotationDesc, annotationTypeDoc.qualifiedName()));
}
for (Tag tag : annotationTypeDoc.tags()) {
annotationNode.getTag().add(parseTag(tag));
}
return annotationNode;
} | [
"protected",
"Annotation",
"parseAnnotationTypeDoc",
"(",
"AnnotationTypeDoc",
"annotationTypeDoc",
")",
"{",
"Annotation",
"annotationNode",
"=",
"objectFactory",
".",
"createAnnotation",
"(",
")",
";",
"annotationNode",
".",
"setName",
"(",
"annotationTypeDoc",
".",
"name",
"(",
")",
")",
";",
"annotationNode",
".",
"setQualified",
"(",
"annotationTypeDoc",
".",
"qualifiedName",
"(",
")",
")",
";",
"String",
"comment",
"=",
"annotationTypeDoc",
".",
"commentText",
"(",
")",
";",
"if",
"(",
"comment",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"annotationNode",
".",
"setComment",
"(",
"comment",
")",
";",
"}",
"annotationNode",
".",
"setIncluded",
"(",
"annotationTypeDoc",
".",
"isIncluded",
"(",
")",
")",
";",
"annotationNode",
".",
"setScope",
"(",
"parseScope",
"(",
"annotationTypeDoc",
")",
")",
";",
"for",
"(",
"AnnotationTypeElementDoc",
"annotationTypeElementDoc",
":",
"annotationTypeDoc",
".",
"elements",
"(",
")",
")",
"{",
"annotationNode",
".",
"getElement",
"(",
")",
".",
"add",
"(",
"parseAnnotationTypeElementDoc",
"(",
"annotationTypeElementDoc",
")",
")",
";",
"}",
"for",
"(",
"AnnotationDesc",
"annotationDesc",
":",
"annotationTypeDoc",
".",
"annotations",
"(",
")",
")",
"{",
"annotationNode",
".",
"getAnnotation",
"(",
")",
".",
"add",
"(",
"parseAnnotationDesc",
"(",
"annotationDesc",
",",
"annotationTypeDoc",
".",
"qualifiedName",
"(",
")",
")",
")",
";",
"}",
"for",
"(",
"Tag",
"tag",
":",
"annotationTypeDoc",
".",
"tags",
"(",
")",
")",
"{",
"annotationNode",
".",
"getTag",
"(",
")",
".",
"add",
"(",
"parseTag",
"(",
"tag",
")",
")",
";",
"}",
"return",
"annotationNode",
";",
"}"
] | Parse an annotation.
@param annotationTypeDoc
A AnnotationTypeDoc instance
@return the annotation node | [
"Parse",
"an",
"annotation",
"."
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java#L116-L140 |
2,042 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java | Parser.parseAnnotationTypeElementDoc | protected AnnotationElement parseAnnotationTypeElementDoc(AnnotationTypeElementDoc annotationTypeElementDoc) {
AnnotationElement annotationElementNode = objectFactory.createAnnotationElement();
annotationElementNode.setName(annotationTypeElementDoc.name());
annotationElementNode.setQualified(annotationTypeElementDoc.qualifiedName());
annotationElementNode.setType(parseTypeInfo(annotationTypeElementDoc.returnType()));
AnnotationValue value = annotationTypeElementDoc.defaultValue();
if (value != null) {
annotationElementNode.setDefault(value.toString());
}
return annotationElementNode;
} | java | protected AnnotationElement parseAnnotationTypeElementDoc(AnnotationTypeElementDoc annotationTypeElementDoc) {
AnnotationElement annotationElementNode = objectFactory.createAnnotationElement();
annotationElementNode.setName(annotationTypeElementDoc.name());
annotationElementNode.setQualified(annotationTypeElementDoc.qualifiedName());
annotationElementNode.setType(parseTypeInfo(annotationTypeElementDoc.returnType()));
AnnotationValue value = annotationTypeElementDoc.defaultValue();
if (value != null) {
annotationElementNode.setDefault(value.toString());
}
return annotationElementNode;
} | [
"protected",
"AnnotationElement",
"parseAnnotationTypeElementDoc",
"(",
"AnnotationTypeElementDoc",
"annotationTypeElementDoc",
")",
"{",
"AnnotationElement",
"annotationElementNode",
"=",
"objectFactory",
".",
"createAnnotationElement",
"(",
")",
";",
"annotationElementNode",
".",
"setName",
"(",
"annotationTypeElementDoc",
".",
"name",
"(",
")",
")",
";",
"annotationElementNode",
".",
"setQualified",
"(",
"annotationTypeElementDoc",
".",
"qualifiedName",
"(",
")",
")",
";",
"annotationElementNode",
".",
"setType",
"(",
"parseTypeInfo",
"(",
"annotationTypeElementDoc",
".",
"returnType",
"(",
")",
")",
")",
";",
"AnnotationValue",
"value",
"=",
"annotationTypeElementDoc",
".",
"defaultValue",
"(",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"annotationElementNode",
".",
"setDefault",
"(",
"value",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"annotationElementNode",
";",
"}"
] | Parse the elements of an annotation
@param annotationTypeElementDoc
A AnnotationTypeElementDoc instance
@return the annotation element node | [
"Parse",
"the",
"elements",
"of",
"an",
"annotation"
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java#L149-L161 |
2,043 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java | Parser.parseAnnotationDesc | protected AnnotationInstance parseAnnotationDesc(AnnotationDesc annotationDesc, String programElement) {
AnnotationInstance annotationInstanceNode = objectFactory.createAnnotationInstance();
try {
AnnotationTypeDoc annotTypeInfo = annotationDesc.annotationType();
annotationInstanceNode.setName(annotTypeInfo.name());
annotationInstanceNode.setQualified(annotTypeInfo.qualifiedTypeName());
} catch (ClassCastException castException) {
log.error("Unable to obtain type data about an annotation found on: " + programElement);
log.error("Add to the classpath the class/jar that defines this annotation.");
}
for (AnnotationDesc.ElementValuePair elementValuesPair : annotationDesc.elementValues()) {
AnnotationArgument annotationArgumentNode = objectFactory.createAnnotationArgument();
annotationArgumentNode.setName(elementValuesPair.element().name());
Type annotationArgumentType = elementValuesPair.element().returnType();
annotationArgumentNode.setType(parseTypeInfo(annotationArgumentType));
annotationArgumentNode.setPrimitive(annotationArgumentType.isPrimitive());
annotationArgumentNode.setArray(annotationArgumentType.dimension().length() > 0);
Object objValue = elementValuesPair.value().value();
if (objValue instanceof AnnotationValue[]) {
for (AnnotationValue annotationValue : (AnnotationValue[]) objValue) {
if (annotationValue.value() instanceof AnnotationDesc) {
AnnotationDesc annoDesc = (AnnotationDesc) annotationValue.value();
annotationArgumentNode.getAnnotation().add(parseAnnotationDesc(annoDesc, programElement));
} else {
annotationArgumentNode.getValue().add(annotationValue.value().toString());
}
}
} else if (objValue instanceof FieldDoc) {
annotationArgumentNode.getValue().add(((FieldDoc) objValue).name());
} else if (objValue instanceof ClassDoc) {
annotationArgumentNode.getValue().add(((ClassDoc) objValue).qualifiedTypeName());
} else {
annotationArgumentNode.getValue().add(objValue.toString());
}
annotationInstanceNode.getArgument().add(annotationArgumentNode);
}
return annotationInstanceNode;
} | java | protected AnnotationInstance parseAnnotationDesc(AnnotationDesc annotationDesc, String programElement) {
AnnotationInstance annotationInstanceNode = objectFactory.createAnnotationInstance();
try {
AnnotationTypeDoc annotTypeInfo = annotationDesc.annotationType();
annotationInstanceNode.setName(annotTypeInfo.name());
annotationInstanceNode.setQualified(annotTypeInfo.qualifiedTypeName());
} catch (ClassCastException castException) {
log.error("Unable to obtain type data about an annotation found on: " + programElement);
log.error("Add to the classpath the class/jar that defines this annotation.");
}
for (AnnotationDesc.ElementValuePair elementValuesPair : annotationDesc.elementValues()) {
AnnotationArgument annotationArgumentNode = objectFactory.createAnnotationArgument();
annotationArgumentNode.setName(elementValuesPair.element().name());
Type annotationArgumentType = elementValuesPair.element().returnType();
annotationArgumentNode.setType(parseTypeInfo(annotationArgumentType));
annotationArgumentNode.setPrimitive(annotationArgumentType.isPrimitive());
annotationArgumentNode.setArray(annotationArgumentType.dimension().length() > 0);
Object objValue = elementValuesPair.value().value();
if (objValue instanceof AnnotationValue[]) {
for (AnnotationValue annotationValue : (AnnotationValue[]) objValue) {
if (annotationValue.value() instanceof AnnotationDesc) {
AnnotationDesc annoDesc = (AnnotationDesc) annotationValue.value();
annotationArgumentNode.getAnnotation().add(parseAnnotationDesc(annoDesc, programElement));
} else {
annotationArgumentNode.getValue().add(annotationValue.value().toString());
}
}
} else if (objValue instanceof FieldDoc) {
annotationArgumentNode.getValue().add(((FieldDoc) objValue).name());
} else if (objValue instanceof ClassDoc) {
annotationArgumentNode.getValue().add(((ClassDoc) objValue).qualifiedTypeName());
} else {
annotationArgumentNode.getValue().add(objValue.toString());
}
annotationInstanceNode.getArgument().add(annotationArgumentNode);
}
return annotationInstanceNode;
} | [
"protected",
"AnnotationInstance",
"parseAnnotationDesc",
"(",
"AnnotationDesc",
"annotationDesc",
",",
"String",
"programElement",
")",
"{",
"AnnotationInstance",
"annotationInstanceNode",
"=",
"objectFactory",
".",
"createAnnotationInstance",
"(",
")",
";",
"try",
"{",
"AnnotationTypeDoc",
"annotTypeInfo",
"=",
"annotationDesc",
".",
"annotationType",
"(",
")",
";",
"annotationInstanceNode",
".",
"setName",
"(",
"annotTypeInfo",
".",
"name",
"(",
")",
")",
";",
"annotationInstanceNode",
".",
"setQualified",
"(",
"annotTypeInfo",
".",
"qualifiedTypeName",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ClassCastException",
"castException",
")",
"{",
"log",
".",
"error",
"(",
"\"Unable to obtain type data about an annotation found on: \"",
"+",
"programElement",
")",
";",
"log",
".",
"error",
"(",
"\"Add to the classpath the class/jar that defines this annotation.\"",
")",
";",
"}",
"for",
"(",
"AnnotationDesc",
".",
"ElementValuePair",
"elementValuesPair",
":",
"annotationDesc",
".",
"elementValues",
"(",
")",
")",
"{",
"AnnotationArgument",
"annotationArgumentNode",
"=",
"objectFactory",
".",
"createAnnotationArgument",
"(",
")",
";",
"annotationArgumentNode",
".",
"setName",
"(",
"elementValuesPair",
".",
"element",
"(",
")",
".",
"name",
"(",
")",
")",
";",
"Type",
"annotationArgumentType",
"=",
"elementValuesPair",
".",
"element",
"(",
")",
".",
"returnType",
"(",
")",
";",
"annotationArgumentNode",
".",
"setType",
"(",
"parseTypeInfo",
"(",
"annotationArgumentType",
")",
")",
";",
"annotationArgumentNode",
".",
"setPrimitive",
"(",
"annotationArgumentType",
".",
"isPrimitive",
"(",
")",
")",
";",
"annotationArgumentNode",
".",
"setArray",
"(",
"annotationArgumentType",
".",
"dimension",
"(",
")",
".",
"length",
"(",
")",
">",
"0",
")",
";",
"Object",
"objValue",
"=",
"elementValuesPair",
".",
"value",
"(",
")",
".",
"value",
"(",
")",
";",
"if",
"(",
"objValue",
"instanceof",
"AnnotationValue",
"[",
"]",
")",
"{",
"for",
"(",
"AnnotationValue",
"annotationValue",
":",
"(",
"AnnotationValue",
"[",
"]",
")",
"objValue",
")",
"{",
"if",
"(",
"annotationValue",
".",
"value",
"(",
")",
"instanceof",
"AnnotationDesc",
")",
"{",
"AnnotationDesc",
"annoDesc",
"=",
"(",
"AnnotationDesc",
")",
"annotationValue",
".",
"value",
"(",
")",
";",
"annotationArgumentNode",
".",
"getAnnotation",
"(",
")",
".",
"add",
"(",
"parseAnnotationDesc",
"(",
"annoDesc",
",",
"programElement",
")",
")",
";",
"}",
"else",
"{",
"annotationArgumentNode",
".",
"getValue",
"(",
")",
".",
"add",
"(",
"annotationValue",
".",
"value",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"objValue",
"instanceof",
"FieldDoc",
")",
"{",
"annotationArgumentNode",
".",
"getValue",
"(",
")",
".",
"add",
"(",
"(",
"(",
"FieldDoc",
")",
"objValue",
")",
".",
"name",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"objValue",
"instanceof",
"ClassDoc",
")",
"{",
"annotationArgumentNode",
".",
"getValue",
"(",
")",
".",
"add",
"(",
"(",
"(",
"ClassDoc",
")",
"objValue",
")",
".",
"qualifiedTypeName",
"(",
")",
")",
";",
"}",
"else",
"{",
"annotationArgumentNode",
".",
"getValue",
"(",
")",
".",
"add",
"(",
"objValue",
".",
"toString",
"(",
")",
")",
";",
"}",
"annotationInstanceNode",
".",
"getArgument",
"(",
")",
".",
"add",
"(",
"annotationArgumentNode",
")",
";",
"}",
"return",
"annotationInstanceNode",
";",
"}"
] | Parses annotation instances of an annotable program element
@param annotationDesc
annotationDesc
@param programElement
programElement
@return representation of annotations | [
"Parses",
"annotation",
"instances",
"of",
"an",
"annotable",
"program",
"element"
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java#L172-L214 |
2,044 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java | Parser.parseEnumConstant | protected EnumConstant parseEnumConstant(FieldDoc fieldDoc) {
EnumConstant enumConstant = objectFactory.createEnumConstant();
enumConstant.setName(fieldDoc.name());
String comment = fieldDoc.commentText();
if (comment.length() > 0) {
enumConstant.setComment(comment);
}
for (AnnotationDesc annotationDesc : fieldDoc.annotations()) {
enumConstant.getAnnotation().add(parseAnnotationDesc(annotationDesc, fieldDoc.qualifiedName()));
}
for (Tag tag : fieldDoc.tags()) {
enumConstant.getTag().add(parseTag(tag));
}
return enumConstant;
} | java | protected EnumConstant parseEnumConstant(FieldDoc fieldDoc) {
EnumConstant enumConstant = objectFactory.createEnumConstant();
enumConstant.setName(fieldDoc.name());
String comment = fieldDoc.commentText();
if (comment.length() > 0) {
enumConstant.setComment(comment);
}
for (AnnotationDesc annotationDesc : fieldDoc.annotations()) {
enumConstant.getAnnotation().add(parseAnnotationDesc(annotationDesc, fieldDoc.qualifiedName()));
}
for (Tag tag : fieldDoc.tags()) {
enumConstant.getTag().add(parseTag(tag));
}
return enumConstant;
} | [
"protected",
"EnumConstant",
"parseEnumConstant",
"(",
"FieldDoc",
"fieldDoc",
")",
"{",
"EnumConstant",
"enumConstant",
"=",
"objectFactory",
".",
"createEnumConstant",
"(",
")",
";",
"enumConstant",
".",
"setName",
"(",
"fieldDoc",
".",
"name",
"(",
")",
")",
";",
"String",
"comment",
"=",
"fieldDoc",
".",
"commentText",
"(",
")",
";",
"if",
"(",
"comment",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"enumConstant",
".",
"setComment",
"(",
"comment",
")",
";",
"}",
"for",
"(",
"AnnotationDesc",
"annotationDesc",
":",
"fieldDoc",
".",
"annotations",
"(",
")",
")",
"{",
"enumConstant",
".",
"getAnnotation",
"(",
")",
".",
"add",
"(",
"parseAnnotationDesc",
"(",
"annotationDesc",
",",
"fieldDoc",
".",
"qualifiedName",
"(",
")",
")",
")",
";",
"}",
"for",
"(",
"Tag",
"tag",
":",
"fieldDoc",
".",
"tags",
"(",
")",
")",
"{",
"enumConstant",
".",
"getTag",
"(",
")",
".",
"add",
"(",
"parseTag",
"(",
"tag",
")",
")",
";",
"}",
"return",
"enumConstant",
";",
"}"
] | Parses an enum type definition
@param fieldDoc
@return | [
"Parses",
"an",
"enum",
"type",
"definition"
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java#L257-L274 |
2,045 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java | Parser.parseTypeParameter | protected TypeParameter parseTypeParameter(TypeVariable typeVariable) {
TypeParameter typeParameter = objectFactory.createTypeParameter();
typeParameter.setName(typeVariable.typeName());
for (Type bound : typeVariable.bounds()) {
typeParameter.getBound().add(bound.qualifiedTypeName());
}
return typeParameter;
} | java | protected TypeParameter parseTypeParameter(TypeVariable typeVariable) {
TypeParameter typeParameter = objectFactory.createTypeParameter();
typeParameter.setName(typeVariable.typeName());
for (Type bound : typeVariable.bounds()) {
typeParameter.getBound().add(bound.qualifiedTypeName());
}
return typeParameter;
} | [
"protected",
"TypeParameter",
"parseTypeParameter",
"(",
"TypeVariable",
"typeVariable",
")",
"{",
"TypeParameter",
"typeParameter",
"=",
"objectFactory",
".",
"createTypeParameter",
"(",
")",
";",
"typeParameter",
".",
"setName",
"(",
"typeVariable",
".",
"typeName",
"(",
")",
")",
";",
"for",
"(",
"Type",
"bound",
":",
"typeVariable",
".",
"bounds",
"(",
")",
")",
"{",
"typeParameter",
".",
"getBound",
"(",
")",
".",
"add",
"(",
"bound",
".",
"qualifiedTypeName",
"(",
")",
")",
";",
"}",
"return",
"typeParameter",
";",
"}"
] | Parse type variables for generics
@param typeVariable
@return | [
"Parse",
"type",
"variables",
"for",
"generics"
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java#L526-L535 |
2,046 | MarkusBernhardt/xml-doclet | src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java | Parser.parseScope | protected String parseScope(ProgramElementDoc doc) {
if (doc.isPrivate()) {
return "private";
} else if (doc.isProtected()) {
return "protected";
} else if (doc.isPublic()) {
return "public";
}
return "";
} | java | protected String parseScope(ProgramElementDoc doc) {
if (doc.isPrivate()) {
return "private";
} else if (doc.isProtected()) {
return "protected";
} else if (doc.isPublic()) {
return "public";
}
return "";
} | [
"protected",
"String",
"parseScope",
"(",
"ProgramElementDoc",
"doc",
")",
"{",
"if",
"(",
"doc",
".",
"isPrivate",
"(",
")",
")",
"{",
"return",
"\"private\"",
";",
"}",
"else",
"if",
"(",
"doc",
".",
"isProtected",
"(",
")",
")",
"{",
"return",
"\"protected\"",
";",
"}",
"else",
"if",
"(",
"doc",
".",
"isPublic",
"(",
")",
")",
"{",
"return",
"\"public\"",
";",
"}",
"return",
"\"\"",
";",
"}"
] | Returns string representation of scope
@param doc
@return | [
"Returns",
"string",
"representation",
"of",
"scope"
] | 6bb0cc1ff82b2e20787b93252c6b294d0eb31622 | https://github.com/MarkusBernhardt/xml-doclet/blob/6bb0cc1ff82b2e20787b93252c6b294d0eb31622/src/main/java/com/github/markusbernhardt/xmldoclet/Parser.java#L550-L559 |
2,047 | andrehertwig/admintool | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/service/validation/AbstractValidator.java | AbstractValidator.sortInterceptors | protected <I extends AdminToolValidationInterceptor<O>> void sortInterceptors(List<I> interceptors) {
if (!CollectionUtils.isEmpty(interceptors)) {
int amount = interceptors != null ? interceptors.size() : 0;
LOGGER.debug(amount + " interceptors configured for " + getMessageArea());
Collections.sort(interceptors, new Comparator<I>() {
@Override
public int compare(I o1, I o2) {
return Integer.compare(o1.getPrecedence(), o2.getPrecedence());
}
});
for (AdminToolValidationInterceptor<O> interceptor : interceptors) {
LOGGER.debug(" precedence: " + interceptor.getPrecedence() + ", class: " + interceptor.getClass().getSimpleName());
}
}
} | java | protected <I extends AdminToolValidationInterceptor<O>> void sortInterceptors(List<I> interceptors) {
if (!CollectionUtils.isEmpty(interceptors)) {
int amount = interceptors != null ? interceptors.size() : 0;
LOGGER.debug(amount + " interceptors configured for " + getMessageArea());
Collections.sort(interceptors, new Comparator<I>() {
@Override
public int compare(I o1, I o2) {
return Integer.compare(o1.getPrecedence(), o2.getPrecedence());
}
});
for (AdminToolValidationInterceptor<O> interceptor : interceptors) {
LOGGER.debug(" precedence: " + interceptor.getPrecedence() + ", class: " + interceptor.getClass().getSimpleName());
}
}
} | [
"protected",
"<",
"I",
"extends",
"AdminToolValidationInterceptor",
"<",
"O",
">",
">",
"void",
"sortInterceptors",
"(",
"List",
"<",
"I",
">",
"interceptors",
")",
"{",
"if",
"(",
"!",
"CollectionUtils",
".",
"isEmpty",
"(",
"interceptors",
")",
")",
"{",
"int",
"amount",
"=",
"interceptors",
"!=",
"null",
"?",
"interceptors",
".",
"size",
"(",
")",
":",
"0",
";",
"LOGGER",
".",
"debug",
"(",
"amount",
"+",
"\" interceptors configured for \"",
"+",
"getMessageArea",
"(",
")",
")",
";",
"Collections",
".",
"sort",
"(",
"interceptors",
",",
"new",
"Comparator",
"<",
"I",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"I",
"o1",
",",
"I",
"o2",
")",
"{",
"return",
"Integer",
".",
"compare",
"(",
"o1",
".",
"getPrecedence",
"(",
")",
",",
"o2",
".",
"getPrecedence",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"for",
"(",
"AdminToolValidationInterceptor",
"<",
"O",
">",
"interceptor",
":",
"interceptors",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\" precedence: \"",
"+",
"interceptor",
".",
"getPrecedence",
"(",
")",
"+",
"\", class: \"",
"+",
"interceptor",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
";",
"}",
"}",
"}"
] | sorts the interceptors against its precedence
@param interceptors | [
"sorts",
"the",
"interceptors",
"against",
"its",
"precedence"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/service/validation/AbstractValidator.java#L59-L74 |
2,048 | andrehertwig/admintool | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/service/validation/AbstractValidator.java | AbstractValidator.intercept | protected <I extends AdminToolValidationInterceptor<O>> void intercept(List<I> interceptors, O user, Set<ATError> errors) {
if (!CollectionUtils.isEmpty(interceptors)) {
for (AdminToolValidationInterceptor<O> interceptor : interceptors) {
LOGGER.trace("calling validation interceptor's validate for: " + interceptor.getClass());
interceptor.validate(user, errors, this);
}
}
} | java | protected <I extends AdminToolValidationInterceptor<O>> void intercept(List<I> interceptors, O user, Set<ATError> errors) {
if (!CollectionUtils.isEmpty(interceptors)) {
for (AdminToolValidationInterceptor<O> interceptor : interceptors) {
LOGGER.trace("calling validation interceptor's validate for: " + interceptor.getClass());
interceptor.validate(user, errors, this);
}
}
} | [
"protected",
"<",
"I",
"extends",
"AdminToolValidationInterceptor",
"<",
"O",
">",
">",
"void",
"intercept",
"(",
"List",
"<",
"I",
">",
"interceptors",
",",
"O",
"user",
",",
"Set",
"<",
"ATError",
">",
"errors",
")",
"{",
"if",
"(",
"!",
"CollectionUtils",
".",
"isEmpty",
"(",
"interceptors",
")",
")",
"{",
"for",
"(",
"AdminToolValidationInterceptor",
"<",
"O",
">",
"interceptor",
":",
"interceptors",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"calling validation interceptor's validate for: \"",
"+",
"interceptor",
".",
"getClass",
"(",
")",
")",
";",
"interceptor",
".",
"validate",
"(",
"user",
",",
"errors",
",",
"this",
")",
";",
"}",
"}",
"}"
] | calls the validate method on interceptors if not empty
@param interceptors
@param user
@param errors | [
"calls",
"the",
"validate",
"method",
"on",
"interceptors",
"if",
"not",
"empty"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/service/validation/AbstractValidator.java#L83-L90 |
2,049 | andrehertwig/admintool | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/service/validation/AbstractValidator.java | AbstractValidator.validateDomainObject | protected <S extends Serializable> void validateDomainObject(S domainObject, Set<ATError> errors) {
Set<ConstraintViolation<S>> constraintViolations = validator.validate( domainObject );
if (CollectionUtils.isEmpty(constraintViolations)) {
return;
}
for ( ConstraintViolation<S> violation : constraintViolations ) {
String type = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
String attrPath = violation.getPropertyPath().toString();
String msgKey = attrPath + "." + type;
if (null != violation.getMessage() && violation.getMessage().startsWith(MSG_KEY_PREFIX)) {
msgKey = violation.getMessage();
}
errors.add(new ATError((attrPath + "." + type), getMessage(msgKey, new Object[]{attrPath}, violation.getMessage()), attrPath));
}
} | java | protected <S extends Serializable> void validateDomainObject(S domainObject, Set<ATError> errors) {
Set<ConstraintViolation<S>> constraintViolations = validator.validate( domainObject );
if (CollectionUtils.isEmpty(constraintViolations)) {
return;
}
for ( ConstraintViolation<S> violation : constraintViolations ) {
String type = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
String attrPath = violation.getPropertyPath().toString();
String msgKey = attrPath + "." + type;
if (null != violation.getMessage() && violation.getMessage().startsWith(MSG_KEY_PREFIX)) {
msgKey = violation.getMessage();
}
errors.add(new ATError((attrPath + "." + type), getMessage(msgKey, new Object[]{attrPath}, violation.getMessage()), attrPath));
}
} | [
"protected",
"<",
"S",
"extends",
"Serializable",
">",
"void",
"validateDomainObject",
"(",
"S",
"domainObject",
",",
"Set",
"<",
"ATError",
">",
"errors",
")",
"{",
"Set",
"<",
"ConstraintViolation",
"<",
"S",
">>",
"constraintViolations",
"=",
"validator",
".",
"validate",
"(",
"domainObject",
")",
";",
"if",
"(",
"CollectionUtils",
".",
"isEmpty",
"(",
"constraintViolations",
")",
")",
"{",
"return",
";",
"}",
"for",
"(",
"ConstraintViolation",
"<",
"S",
">",
"violation",
":",
"constraintViolations",
")",
"{",
"String",
"type",
"=",
"violation",
".",
"getConstraintDescriptor",
"(",
")",
".",
"getAnnotation",
"(",
")",
".",
"annotationType",
"(",
")",
".",
"getSimpleName",
"(",
")",
";",
"String",
"attrPath",
"=",
"violation",
".",
"getPropertyPath",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"msgKey",
"=",
"attrPath",
"+",
"\".\"",
"+",
"type",
";",
"if",
"(",
"null",
"!=",
"violation",
".",
"getMessage",
"(",
")",
"&&",
"violation",
".",
"getMessage",
"(",
")",
".",
"startsWith",
"(",
"MSG_KEY_PREFIX",
")",
")",
"{",
"msgKey",
"=",
"violation",
".",
"getMessage",
"(",
")",
";",
"}",
"errors",
".",
"add",
"(",
"new",
"ATError",
"(",
"(",
"attrPath",
"+",
"\".\"",
"+",
"type",
")",
",",
"getMessage",
"(",
"msgKey",
",",
"new",
"Object",
"[",
"]",
"{",
"attrPath",
"}",
",",
"violation",
".",
"getMessage",
"(",
")",
")",
",",
"attrPath",
")",
")",
";",
"}",
"}"
] | validates a domain object with javax.validation annotations
@param domainObject
@param errors | [
"validates",
"a",
"domain",
"object",
"with",
"javax",
".",
"validation",
"annotations"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/service/validation/AbstractValidator.java#L105-L119 |
2,050 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java | AdminToolMenuUtils.getComponents | public List<AdminComponent> getComponents() {
List<AdminComponent> result = new ArrayList<>();
for (AdminComponent adminComponent : adminTool.getComponents()) {
if (null != adminComponent.getMainMenu()) {
Stream<MenuEntry> nonHiddenMenues = adminComponent.getMainMenu().flattened().filter(me -> !me.isHide());
if (nonHiddenMenues.count() == 0L) {
LOGGER.trace("all menu entries hidden for component: " + adminComponent.getDisplayName());
//do not return this menu item, because all entries are hidden
continue;
}
result.add(adminComponent);
}
}
return result;
} | java | public List<AdminComponent> getComponents() {
List<AdminComponent> result = new ArrayList<>();
for (AdminComponent adminComponent : adminTool.getComponents()) {
if (null != adminComponent.getMainMenu()) {
Stream<MenuEntry> nonHiddenMenues = adminComponent.getMainMenu().flattened().filter(me -> !me.isHide());
if (nonHiddenMenues.count() == 0L) {
LOGGER.trace("all menu entries hidden for component: " + adminComponent.getDisplayName());
//do not return this menu item, because all entries are hidden
continue;
}
result.add(adminComponent);
}
}
return result;
} | [
"public",
"List",
"<",
"AdminComponent",
">",
"getComponents",
"(",
")",
"{",
"List",
"<",
"AdminComponent",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"AdminComponent",
"adminComponent",
":",
"adminTool",
".",
"getComponents",
"(",
")",
")",
"{",
"if",
"(",
"null",
"!=",
"adminComponent",
".",
"getMainMenu",
"(",
")",
")",
"{",
"Stream",
"<",
"MenuEntry",
">",
"nonHiddenMenues",
"=",
"adminComponent",
".",
"getMainMenu",
"(",
")",
".",
"flattened",
"(",
")",
".",
"filter",
"(",
"me",
"->",
"!",
"me",
".",
"isHide",
"(",
")",
")",
";",
"if",
"(",
"nonHiddenMenues",
".",
"count",
"(",
")",
"==",
"0L",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"all menu entries hidden for component: \"",
"+",
"adminComponent",
".",
"getDisplayName",
"(",
")",
")",
";",
"//do not return this menu item, because all entries are hidden",
"continue",
";",
"}",
"result",
".",
"add",
"(",
"adminComponent",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | collects the components from adminTool
@return all AdminComponents with a main menu and at least one non-hidden (visible) menu entry | [
"collects",
"the",
"components",
"from",
"adminTool"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java#L54-L69 |
2,051 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java | AdminToolMenuUtils.getMenuName | public String getMenuName(HttpServletRequest request, String overrideName) {
if (!StringUtils.isEmpty(overrideName)) {
return overrideName;
}
String name = request.getRequestURI().replaceFirst(AdminTool.ROOTCONTEXT, "");
if (!StringUtils.isEmpty(request.getContextPath())) {
name = name.replaceFirst(request.getContextPath(), "");
}
if (name.startsWith("/")) {
name = name.substring(1, name.length());
}
return name;
} | java | public String getMenuName(HttpServletRequest request, String overrideName) {
if (!StringUtils.isEmpty(overrideName)) {
return overrideName;
}
String name = request.getRequestURI().replaceFirst(AdminTool.ROOTCONTEXT, "");
if (!StringUtils.isEmpty(request.getContextPath())) {
name = name.replaceFirst(request.getContextPath(), "");
}
if (name.startsWith("/")) {
name = name.substring(1, name.length());
}
return name;
} | [
"public",
"String",
"getMenuName",
"(",
"HttpServletRequest",
"request",
",",
"String",
"overrideName",
")",
"{",
"if",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"overrideName",
")",
")",
"{",
"return",
"overrideName",
";",
"}",
"String",
"name",
"=",
"request",
".",
"getRequestURI",
"(",
")",
".",
"replaceFirst",
"(",
"AdminTool",
".",
"ROOTCONTEXT",
",",
"\"\"",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"request",
".",
"getContextPath",
"(",
")",
")",
")",
"{",
"name",
"=",
"name",
".",
"replaceFirst",
"(",
"request",
".",
"getContextPath",
"(",
")",
",",
"\"\"",
")",
";",
"}",
"if",
"(",
"name",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"name",
"=",
"name",
".",
"substring",
"(",
"1",
",",
"name",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"name",
";",
"}"
] | retuns the menu name for given requestUrl or the overrideName if set.
@param request
@param overrideName (optional)
@return | [
"retuns",
"the",
"menu",
"name",
"for",
"given",
"requestUrl",
"or",
"the",
"overrideName",
"if",
"set",
"."
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java#L77-L89 |
2,052 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java | AdminToolMenuUtils.isActiveInMenuTree | public boolean isActiveInMenuTree(MenuEntry activeMenu, MenuEntry actualEntry) {
return actualEntry.flattened().anyMatch(
entry -> checkForNull(entry, activeMenu) ? entry.getName().equals(activeMenu.getName()): false);
} | java | public boolean isActiveInMenuTree(MenuEntry activeMenu, MenuEntry actualEntry) {
return actualEntry.flattened().anyMatch(
entry -> checkForNull(entry, activeMenu) ? entry.getName().equals(activeMenu.getName()): false);
} | [
"public",
"boolean",
"isActiveInMenuTree",
"(",
"MenuEntry",
"activeMenu",
",",
"MenuEntry",
"actualEntry",
")",
"{",
"return",
"actualEntry",
".",
"flattened",
"(",
")",
".",
"anyMatch",
"(",
"entry",
"->",
"checkForNull",
"(",
"entry",
",",
"activeMenu",
")",
"?",
"entry",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"activeMenu",
".",
"getName",
"(",
")",
")",
":",
"false",
")",
";",
"}"
] | checks if actualEntry contains the activeMenuName in entry itself and its
sub entries
@param activeMenuName
@param actualEntry current iterated object
@return | [
"checks",
"if",
"actualEntry",
"contains",
"the",
"activeMenuName",
"in",
"entry",
"itself",
"and",
"its",
"sub",
"entries"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java#L119-L122 |
2,053 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java | AdminToolMenuUtils.getBreadcrumbList | public List<MenuEntry> getBreadcrumbList(MenuEntry actualEntry) {
List<MenuEntry> result = new LinkedList<>();
if (null != actualEntry) {
actualEntry.reverseFlattened().collect(toListReversed()).forEach(entry -> {
if(null != entry) result.add(entry);
});
}
return result;
} | java | public List<MenuEntry> getBreadcrumbList(MenuEntry actualEntry) {
List<MenuEntry> result = new LinkedList<>();
if (null != actualEntry) {
actualEntry.reverseFlattened().collect(toListReversed()).forEach(entry -> {
if(null != entry) result.add(entry);
});
}
return result;
} | [
"public",
"List",
"<",
"MenuEntry",
">",
"getBreadcrumbList",
"(",
"MenuEntry",
"actualEntry",
")",
"{",
"List",
"<",
"MenuEntry",
">",
"result",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"actualEntry",
")",
"{",
"actualEntry",
".",
"reverseFlattened",
"(",
")",
".",
"collect",
"(",
"toListReversed",
"(",
")",
")",
".",
"forEach",
"(",
"entry",
"->",
"{",
"if",
"(",
"null",
"!=",
"entry",
")",
"result",
".",
"add",
"(",
"entry",
")",
";",
"}",
")",
";",
"}",
"return",
"result",
";",
"}"
] | returns a linked list of reverse resolution o menu structure
@param actualEntry
@return | [
"returns",
"a",
"linked",
"list",
"of",
"reverse",
"resolution",
"o",
"menu",
"structure"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java#L154-L162 |
2,054 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java | AdminToolMenuUtils.hasMenuEntry | public boolean hasMenuEntry(AdminComponent component, MenuEntry activeMenue) {
if (null != component && null != component.getMainMenu()) {
Optional<MenuEntry> result = component.getMainMenu().flattened()
.filter(menu -> checkForNull(menu, activeMenue) ? menu.getName().equals(activeMenue.getName()): false)
.findFirst();
return result.isPresent();
}
return false;
} | java | public boolean hasMenuEntry(AdminComponent component, MenuEntry activeMenue) {
if (null != component && null != component.getMainMenu()) {
Optional<MenuEntry> result = component.getMainMenu().flattened()
.filter(menu -> checkForNull(menu, activeMenue) ? menu.getName().equals(activeMenue.getName()): false)
.findFirst();
return result.isPresent();
}
return false;
} | [
"public",
"boolean",
"hasMenuEntry",
"(",
"AdminComponent",
"component",
",",
"MenuEntry",
"activeMenue",
")",
"{",
"if",
"(",
"null",
"!=",
"component",
"&&",
"null",
"!=",
"component",
".",
"getMainMenu",
"(",
")",
")",
"{",
"Optional",
"<",
"MenuEntry",
">",
"result",
"=",
"component",
".",
"getMainMenu",
"(",
")",
".",
"flattened",
"(",
")",
".",
"filter",
"(",
"menu",
"->",
"checkForNull",
"(",
"menu",
",",
"activeMenue",
")",
"?",
"menu",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"activeMenue",
".",
"getName",
"(",
")",
")",
":",
"false",
")",
".",
"findFirst",
"(",
")",
";",
"return",
"result",
".",
"isPresent",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] | checks if the activeMenue is part of given component
@param component the AdminComponent which should contain the activeMenue
@param activeMenue the menue to check
@return | [
"checks",
"if",
"the",
"activeMenue",
"is",
"part",
"of",
"given",
"component"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolMenuUtils.java#L182-L190 |
2,055 | andrehertwig/admintool | admin-tools-filebrowser/src/main/java/de/chandre/admintool/filebrowser/AdminToolFilebrowserServiceImpl.java | AdminToolFilebrowserServiceImpl.formatFileSize | protected String formatFileSize(BigInteger fileLength, BigInteger divisor, String unit) {
BigDecimal size = new BigDecimal(fileLength);
size = size.setScale(config.getFileSizeDisplayScale()).divide(new BigDecimal(divisor), BigDecimal.ROUND_HALF_EVEN);
return String.format("%s %s", size.doubleValue(), unit);
} | java | protected String formatFileSize(BigInteger fileLength, BigInteger divisor, String unit) {
BigDecimal size = new BigDecimal(fileLength);
size = size.setScale(config.getFileSizeDisplayScale()).divide(new BigDecimal(divisor), BigDecimal.ROUND_HALF_EVEN);
return String.format("%s %s", size.doubleValue(), unit);
} | [
"protected",
"String",
"formatFileSize",
"(",
"BigInteger",
"fileLength",
",",
"BigInteger",
"divisor",
",",
"String",
"unit",
")",
"{",
"BigDecimal",
"size",
"=",
"new",
"BigDecimal",
"(",
"fileLength",
")",
";",
"size",
"=",
"size",
".",
"setScale",
"(",
"config",
".",
"getFileSizeDisplayScale",
"(",
")",
")",
".",
"divide",
"(",
"new",
"BigDecimal",
"(",
"divisor",
")",
",",
"BigDecimal",
".",
"ROUND_HALF_EVEN",
")",
";",
"return",
"String",
".",
"format",
"(",
"\"%s %s\"",
",",
"size",
".",
"doubleValue",
"(",
")",
",",
"unit",
")",
";",
"}"
] | calculates the and formats files size
@see #getFileSize(long)
@param fileLength
@param divisor
@param unit the Unit for the divisor
@return | [
"calculates",
"the",
"and",
"formats",
"files",
"size"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-filebrowser/src/main/java/de/chandre/admintool/filebrowser/AdminToolFilebrowserServiceImpl.java#L341-L345 |
2,056 | andrehertwig/admintool | admin-tools-filebrowser/src/main/java/de/chandre/admintool/filebrowser/AdminToolFilebrowserServiceImpl.java | AdminToolFilebrowserServiceImpl.isAllowed | protected boolean isAllowed(File path, boolean write) throws IOException {
return isAllowedInternal(path, write, config.isReadOnly());
} | java | protected boolean isAllowed(File path, boolean write) throws IOException {
return isAllowedInternal(path, write, config.isReadOnly());
} | [
"protected",
"boolean",
"isAllowed",
"(",
"File",
"path",
",",
"boolean",
"write",
")",
"throws",
"IOException",
"{",
"return",
"isAllowedInternal",
"(",
"path",
",",
"write",
",",
"config",
".",
"isReadOnly",
"(",
")",
")",
";",
"}"
] | checks if file is allowed for access
@param path
@param write
@return
@throws IOException | [
"checks",
"if",
"file",
"is",
"allowed",
"for",
"access"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-filebrowser/src/main/java/de/chandre/admintool/filebrowser/AdminToolFilebrowserServiceImpl.java#L516-L518 |
2,057 | andrehertwig/admintool | admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserExampleLoader.java | AdminToolDBBrowserExampleLoader.addExamples | public void addExamples(ExampleStatements exampleStatements)
{
this.statements.put(exampleStatements.getDatasourceName(), exampleStatements.getClusters());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("converted json object" + new JSONObject(statements));
}
} | java | public void addExamples(ExampleStatements exampleStatements)
{
this.statements.put(exampleStatements.getDatasourceName(), exampleStatements.getClusters());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("converted json object" + new JSONObject(statements));
}
} | [
"public",
"void",
"addExamples",
"(",
"ExampleStatements",
"exampleStatements",
")",
"{",
"this",
".",
"statements",
".",
"put",
"(",
"exampleStatements",
".",
"getDatasourceName",
"(",
")",
",",
"exampleStatements",
".",
"getClusters",
"(",
")",
")",
";",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"converted json object\"",
"+",
"new",
"JSONObject",
"(",
"statements",
")",
")",
";",
"}",
"}"
] | vendor must be set
@param exampleStatements | [
"vendor",
"must",
"be",
"set"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserExampleLoader.java#L39-L45 |
2,058 | andrehertwig/admintool | admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java | AdminToolLog4j2Util.getParentLoggers | public Collection<Logger> getParentLoggers() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
List<Logger> loggers = new ArrayList<>(ctx.getLoggers());
Map<String, Logger> parentMap = new HashMap<>();
try {
for (Logger logger : loggers) {
if (null != logger.getParent() && parentMap.get(logger.getParent().getName()) == null) {
parentMap.put(logger.getParent().getName(), logger.getParent());
}
}
List<Logger> parents = new ArrayList<>(parentMap.values());
Collections.sort(parents, LOGGER_COMP);
return parents;
} finally {
loggers.clear();
parentMap.clear();
}
} | java | public Collection<Logger> getParentLoggers() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
List<Logger> loggers = new ArrayList<>(ctx.getLoggers());
Map<String, Logger> parentMap = new HashMap<>();
try {
for (Logger logger : loggers) {
if (null != logger.getParent() && parentMap.get(logger.getParent().getName()) == null) {
parentMap.put(logger.getParent().getName(), logger.getParent());
}
}
List<Logger> parents = new ArrayList<>(parentMap.values());
Collections.sort(parents, LOGGER_COMP);
return parents;
} finally {
loggers.clear();
parentMap.clear();
}
} | [
"public",
"Collection",
"<",
"Logger",
">",
"getParentLoggers",
"(",
")",
"{",
"LoggerContext",
"ctx",
"=",
"(",
"LoggerContext",
")",
"LogManager",
".",
"getContext",
"(",
"false",
")",
";",
"List",
"<",
"Logger",
">",
"loggers",
"=",
"new",
"ArrayList",
"<>",
"(",
"ctx",
".",
"getLoggers",
"(",
")",
")",
";",
"Map",
"<",
"String",
",",
"Logger",
">",
"parentMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"try",
"{",
"for",
"(",
"Logger",
"logger",
":",
"loggers",
")",
"{",
"if",
"(",
"null",
"!=",
"logger",
".",
"getParent",
"(",
")",
"&&",
"parentMap",
".",
"get",
"(",
"logger",
".",
"getParent",
"(",
")",
".",
"getName",
"(",
")",
")",
"==",
"null",
")",
"{",
"parentMap",
".",
"put",
"(",
"logger",
".",
"getParent",
"(",
")",
".",
"getName",
"(",
")",
",",
"logger",
".",
"getParent",
"(",
")",
")",
";",
"}",
"}",
"List",
"<",
"Logger",
">",
"parents",
"=",
"new",
"ArrayList",
"<>",
"(",
"parentMap",
".",
"values",
"(",
")",
")",
";",
"Collections",
".",
"sort",
"(",
"parents",
",",
"LOGGER_COMP",
")",
";",
"return",
"parents",
";",
"}",
"finally",
"{",
"loggers",
".",
"clear",
"(",
")",
";",
"parentMap",
".",
"clear",
"(",
")",
";",
"}",
"}"
] | returns all parent loggers
@return | [
"returns",
"all",
"parent",
"loggers"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java#L88-L105 |
2,059 | andrehertwig/admintool | admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java | AdminToolLog4j2Util.getLoggers | public Collection<Logger> getLoggers() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
List<Logger> loggers = new ArrayList<>(ctx.getLoggers());
Collections.sort(loggers, LOGGER_COMP);
return loggers;
} | java | public Collection<Logger> getLoggers() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
List<Logger> loggers = new ArrayList<>(ctx.getLoggers());
Collections.sort(loggers, LOGGER_COMP);
return loggers;
} | [
"public",
"Collection",
"<",
"Logger",
">",
"getLoggers",
"(",
")",
"{",
"LoggerContext",
"ctx",
"=",
"(",
"LoggerContext",
")",
"LogManager",
".",
"getContext",
"(",
"false",
")",
";",
"List",
"<",
"Logger",
">",
"loggers",
"=",
"new",
"ArrayList",
"<>",
"(",
"ctx",
".",
"getLoggers",
"(",
")",
")",
";",
"Collections",
".",
"sort",
"(",
"loggers",
",",
"LOGGER_COMP",
")",
";",
"return",
"loggers",
";",
"}"
] | returns all loggers
@return | [
"returns",
"all",
"loggers"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java#L119-L124 |
2,060 | andrehertwig/admintool | admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java | AdminToolLog4j2Util.getAllLoggerNames | public Collection<String> getAllLoggerNames() {
Set<String> loggerNames = new TreeSet<>();
for (Logger logger : getParentLoggers()) {
loggerNames.add(logger.getName());
}
for (Logger logger : getLoggers()) {
loggerNames.add(logger.getName());
}
if (!customLoggers.isEmpty()) {
for (Entry<LoggerConfig, String> entry : customLoggers.entrySet()) {
loggerNames.add(entry.getKey().getName());
}
}
if (!customParentLoggers.isEmpty()) {
for (Entry<LoggerConfig, String> entry : customParentLoggers.entrySet()) {
loggerNames.add(entry.getKey().getName());
}
}
return loggerNames;
} | java | public Collection<String> getAllLoggerNames() {
Set<String> loggerNames = new TreeSet<>();
for (Logger logger : getParentLoggers()) {
loggerNames.add(logger.getName());
}
for (Logger logger : getLoggers()) {
loggerNames.add(logger.getName());
}
if (!customLoggers.isEmpty()) {
for (Entry<LoggerConfig, String> entry : customLoggers.entrySet()) {
loggerNames.add(entry.getKey().getName());
}
}
if (!customParentLoggers.isEmpty()) {
for (Entry<LoggerConfig, String> entry : customParentLoggers.entrySet()) {
loggerNames.add(entry.getKey().getName());
}
}
return loggerNames;
} | [
"public",
"Collection",
"<",
"String",
">",
"getAllLoggerNames",
"(",
")",
"{",
"Set",
"<",
"String",
">",
"loggerNames",
"=",
"new",
"TreeSet",
"<>",
"(",
")",
";",
"for",
"(",
"Logger",
"logger",
":",
"getParentLoggers",
"(",
")",
")",
"{",
"loggerNames",
".",
"add",
"(",
"logger",
".",
"getName",
"(",
")",
")",
";",
"}",
"for",
"(",
"Logger",
"logger",
":",
"getLoggers",
"(",
")",
")",
"{",
"loggerNames",
".",
"add",
"(",
"logger",
".",
"getName",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"customLoggers",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"Entry",
"<",
"LoggerConfig",
",",
"String",
">",
"entry",
":",
"customLoggers",
".",
"entrySet",
"(",
")",
")",
"{",
"loggerNames",
".",
"add",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"if",
"(",
"!",
"customParentLoggers",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"Entry",
"<",
"LoggerConfig",
",",
"String",
">",
"entry",
":",
"customParentLoggers",
".",
"entrySet",
"(",
")",
")",
"{",
"loggerNames",
".",
"add",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"return",
"loggerNames",
";",
"}"
] | returns all logger names including custom loggers
@since 1.1.1
@return | [
"returns",
"all",
"logger",
"names",
"including",
"custom",
"loggers"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java#L132-L151 |
2,061 | andrehertwig/admintool | admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java | AdminToolLog4j2Util.changeLogger | public void changeLogger(final String name, final String levelStr, boolean parent) throws IllegalArgumentException
{
Level level = getLevel(levelStr);
changeLogger(name, level, parent);
} | java | public void changeLogger(final String name, final String levelStr, boolean parent) throws IllegalArgumentException
{
Level level = getLevel(levelStr);
changeLogger(name, level, parent);
} | [
"public",
"void",
"changeLogger",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"levelStr",
",",
"boolean",
"parent",
")",
"throws",
"IllegalArgumentException",
"{",
"Level",
"level",
"=",
"getLevel",
"(",
"levelStr",
")",
";",
"changeLogger",
"(",
"name",
",",
"level",
",",
"parent",
")",
";",
"}"
] | changes the level of an logger
@param name logger name
@param levelStr level as string
@param parent if the logger is a parent logger
@throws IllegalArgumentException | [
"changes",
"the",
"level",
"of",
"an",
"logger"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java#L215-L219 |
2,062 | andrehertwig/admintool | admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java | AdminToolLog4j2Util.createOutputStreamAppender | public String createOutputStreamAppender(String name, String pattern, String encoding, Collection<String> loggerNames,
String levelStr, boolean recursive, boolean overrideLogLevel) {
Level level = getLevel(levelStr);
String encodingToUse = StringUtils.isEmpty(encoding) ? "UTF-8" : encoding;
PatternLayout layout = PatternLayout.newBuilder()
.withPattern(StringUtils.isEmpty(pattern) ? DEFAULT_PATTERN : pattern)
.withCharset(Charset.forName(encodingToUse))
.build();
String appenderName = StringUtils.isEmpty(name) ? UUID.randomUUID().toString() : name;
AdminToolLog4j2OutputStream baos = new AdminToolLog4j2OutputStream(4096, encodingToUse);
outputStreams.put(appenderName, baos);
OutputStreamAppender appender = OutputStreamAppender.newBuilder()
.setName(appenderName)
.setTarget(baos)
.setLayout(layout)
.setFollow(false)
.build();
appender.start();
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
config.addAppender(appender);
Collection<String> parentLoggerNames = getParentLoggerNames();
Map<String, LoggerConfig> configs = getRecursiveLoggerConfigs(loggerNames, recursive, config);
configs.entrySet().forEach(configEntry ->{
configEntry.getValue().addAppender(appender, level, null);
if (overrideLogLevel) {
baos.addOriginalLevel(configEntry.getKey(), configEntry.getValue().getLevel());
changeLogger(configEntry.getKey(), level, parentLoggerNames.contains(configEntry.getKey()));
}
});
ctx.updateLoggers();
return appenderName;
} | java | public String createOutputStreamAppender(String name, String pattern, String encoding, Collection<String> loggerNames,
String levelStr, boolean recursive, boolean overrideLogLevel) {
Level level = getLevel(levelStr);
String encodingToUse = StringUtils.isEmpty(encoding) ? "UTF-8" : encoding;
PatternLayout layout = PatternLayout.newBuilder()
.withPattern(StringUtils.isEmpty(pattern) ? DEFAULT_PATTERN : pattern)
.withCharset(Charset.forName(encodingToUse))
.build();
String appenderName = StringUtils.isEmpty(name) ? UUID.randomUUID().toString() : name;
AdminToolLog4j2OutputStream baos = new AdminToolLog4j2OutputStream(4096, encodingToUse);
outputStreams.put(appenderName, baos);
OutputStreamAppender appender = OutputStreamAppender.newBuilder()
.setName(appenderName)
.setTarget(baos)
.setLayout(layout)
.setFollow(false)
.build();
appender.start();
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
config.addAppender(appender);
Collection<String> parentLoggerNames = getParentLoggerNames();
Map<String, LoggerConfig> configs = getRecursiveLoggerConfigs(loggerNames, recursive, config);
configs.entrySet().forEach(configEntry ->{
configEntry.getValue().addAppender(appender, level, null);
if (overrideLogLevel) {
baos.addOriginalLevel(configEntry.getKey(), configEntry.getValue().getLevel());
changeLogger(configEntry.getKey(), level, parentLoggerNames.contains(configEntry.getKey()));
}
});
ctx.updateLoggers();
return appenderName;
} | [
"public",
"String",
"createOutputStreamAppender",
"(",
"String",
"name",
",",
"String",
"pattern",
",",
"String",
"encoding",
",",
"Collection",
"<",
"String",
">",
"loggerNames",
",",
"String",
"levelStr",
",",
"boolean",
"recursive",
",",
"boolean",
"overrideLogLevel",
")",
"{",
"Level",
"level",
"=",
"getLevel",
"(",
"levelStr",
")",
";",
"String",
"encodingToUse",
"=",
"StringUtils",
".",
"isEmpty",
"(",
"encoding",
")",
"?",
"\"UTF-8\"",
":",
"encoding",
";",
"PatternLayout",
"layout",
"=",
"PatternLayout",
".",
"newBuilder",
"(",
")",
".",
"withPattern",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"pattern",
")",
"?",
"DEFAULT_PATTERN",
":",
"pattern",
")",
".",
"withCharset",
"(",
"Charset",
".",
"forName",
"(",
"encodingToUse",
")",
")",
".",
"build",
"(",
")",
";",
"String",
"appenderName",
"=",
"StringUtils",
".",
"isEmpty",
"(",
"name",
")",
"?",
"UUID",
".",
"randomUUID",
"(",
")",
".",
"toString",
"(",
")",
":",
"name",
";",
"AdminToolLog4j2OutputStream",
"baos",
"=",
"new",
"AdminToolLog4j2OutputStream",
"(",
"4096",
",",
"encodingToUse",
")",
";",
"outputStreams",
".",
"put",
"(",
"appenderName",
",",
"baos",
")",
";",
"OutputStreamAppender",
"appender",
"=",
"OutputStreamAppender",
".",
"newBuilder",
"(",
")",
".",
"setName",
"(",
"appenderName",
")",
".",
"setTarget",
"(",
"baos",
")",
".",
"setLayout",
"(",
"layout",
")",
".",
"setFollow",
"(",
"false",
")",
".",
"build",
"(",
")",
";",
"appender",
".",
"start",
"(",
")",
";",
"final",
"LoggerContext",
"ctx",
"=",
"(",
"LoggerContext",
")",
"LogManager",
".",
"getContext",
"(",
"false",
")",
";",
"final",
"Configuration",
"config",
"=",
"ctx",
".",
"getConfiguration",
"(",
")",
";",
"config",
".",
"addAppender",
"(",
"appender",
")",
";",
"Collection",
"<",
"String",
">",
"parentLoggerNames",
"=",
"getParentLoggerNames",
"(",
")",
";",
"Map",
"<",
"String",
",",
"LoggerConfig",
">",
"configs",
"=",
"getRecursiveLoggerConfigs",
"(",
"loggerNames",
",",
"recursive",
",",
"config",
")",
";",
"configs",
".",
"entrySet",
"(",
")",
".",
"forEach",
"(",
"configEntry",
"->",
"{",
"configEntry",
".",
"getValue",
"(",
")",
".",
"addAppender",
"(",
"appender",
",",
"level",
",",
"null",
")",
";",
"if",
"(",
"overrideLogLevel",
")",
"{",
"baos",
".",
"addOriginalLevel",
"(",
"configEntry",
".",
"getKey",
"(",
")",
",",
"configEntry",
".",
"getValue",
"(",
")",
".",
"getLevel",
"(",
")",
")",
";",
"changeLogger",
"(",
"configEntry",
".",
"getKey",
"(",
")",
",",
"level",
",",
"parentLoggerNames",
".",
"contains",
"(",
"configEntry",
".",
"getKey",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"ctx",
".",
"updateLoggers",
"(",
")",
";",
"return",
"appenderName",
";",
"}"
] | creates the custom output steam appender and returns the name
@param name
@param pattern
@param encoding
@param loggerNames
@param levelStr
@return
@since 1.1.1 | [
"creates",
"the",
"custom",
"output",
"steam",
"appender",
"and",
"returns",
"the",
"name"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java#L426-L466 |
2,063 | andrehertwig/admintool | admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java | AdminToolLog4j2Util.getStringOutput | public String getStringOutput(String appenderName, String encoding) throws UnsupportedEncodingException {
AdminToolLog4j2OutputStream baos = outputStreams.get(appenderName);
String output = "";
if (null != baos) {
output = baos.getAndReset(encoding);
}
return output.trim().isEmpty() ? null : output;
} | java | public String getStringOutput(String appenderName, String encoding) throws UnsupportedEncodingException {
AdminToolLog4j2OutputStream baos = outputStreams.get(appenderName);
String output = "";
if (null != baos) {
output = baos.getAndReset(encoding);
}
return output.trim().isEmpty() ? null : output;
} | [
"public",
"String",
"getStringOutput",
"(",
"String",
"appenderName",
",",
"String",
"encoding",
")",
"throws",
"UnsupportedEncodingException",
"{",
"AdminToolLog4j2OutputStream",
"baos",
"=",
"outputStreams",
".",
"get",
"(",
"appenderName",
")",
";",
"String",
"output",
"=",
"\"\"",
";",
"if",
"(",
"null",
"!=",
"baos",
")",
"{",
"output",
"=",
"baos",
".",
"getAndReset",
"(",
"encoding",
")",
";",
"}",
"return",
"output",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"output",
";",
"}"
] | returns the log messages from custom appenders output stream
@param appenderName
@param encoding
@return
@throws UnsupportedEncodingException
@since 1.1.1 | [
"returns",
"the",
"log",
"messages",
"from",
"custom",
"appenders",
"output",
"stream"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java#L500-L508 |
2,064 | andrehertwig/admintool | admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java | AdminToolLog4j2Util.closeOutputStreamAppender | public void closeOutputStreamAppender(String appenderName) throws IOException {
if (null == appenderName) {
return;
}
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
AdminToolLog4j2OutputStream baos = outputStreams.get(appenderName);
if (null != config && null != config.getAppenders()) {
OutputStreamAppender appender = config.getAppender(appenderName);
if (null != appender) {
appender.stop();
Collection<String> parentLoggerNames = getParentLoggerNames();
for (String configuredLoggerName : getAllLoggerNames()) {
LoggerConfig loggerConfig = config.getLoggerConfig(configuredLoggerName);
loggerConfig.removeAppender(appender.getName());
if (null != baos.getOriginalLevel(configuredLoggerName)) {
changeLogger(configuredLoggerName, baos.getOriginalLevel(configuredLoggerName),
parentLoggerNames.contains(configuredLoggerName));
}
}
//unsure about, if removing the appender from logger config if it gets also removed from logger instance too...
removeAppender(appender, getParentLoggers());
removeAppender(appender, getLoggers());
appender.getManager().getByteBuffer().clear();
ctx.updateLoggers();
}
}
if (null != baos) {
try {
baos.close();
baos.clearOriginalLevels();
} catch (Exception ignore) {
} finally {
outputStreams.remove(appenderName);
}
}
} | java | public void closeOutputStreamAppender(String appenderName) throws IOException {
if (null == appenderName) {
return;
}
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
AdminToolLog4j2OutputStream baos = outputStreams.get(appenderName);
if (null != config && null != config.getAppenders()) {
OutputStreamAppender appender = config.getAppender(appenderName);
if (null != appender) {
appender.stop();
Collection<String> parentLoggerNames = getParentLoggerNames();
for (String configuredLoggerName : getAllLoggerNames()) {
LoggerConfig loggerConfig = config.getLoggerConfig(configuredLoggerName);
loggerConfig.removeAppender(appender.getName());
if (null != baos.getOriginalLevel(configuredLoggerName)) {
changeLogger(configuredLoggerName, baos.getOriginalLevel(configuredLoggerName),
parentLoggerNames.contains(configuredLoggerName));
}
}
//unsure about, if removing the appender from logger config if it gets also removed from logger instance too...
removeAppender(appender, getParentLoggers());
removeAppender(appender, getLoggers());
appender.getManager().getByteBuffer().clear();
ctx.updateLoggers();
}
}
if (null != baos) {
try {
baos.close();
baos.clearOriginalLevels();
} catch (Exception ignore) {
} finally {
outputStreams.remove(appenderName);
}
}
} | [
"public",
"void",
"closeOutputStreamAppender",
"(",
"String",
"appenderName",
")",
"throws",
"IOException",
"{",
"if",
"(",
"null",
"==",
"appenderName",
")",
"{",
"return",
";",
"}",
"final",
"LoggerContext",
"ctx",
"=",
"(",
"LoggerContext",
")",
"LogManager",
".",
"getContext",
"(",
"false",
")",
";",
"final",
"Configuration",
"config",
"=",
"ctx",
".",
"getConfiguration",
"(",
")",
";",
"AdminToolLog4j2OutputStream",
"baos",
"=",
"outputStreams",
".",
"get",
"(",
"appenderName",
")",
";",
"if",
"(",
"null",
"!=",
"config",
"&&",
"null",
"!=",
"config",
".",
"getAppenders",
"(",
")",
")",
"{",
"OutputStreamAppender",
"appender",
"=",
"config",
".",
"getAppender",
"(",
"appenderName",
")",
";",
"if",
"(",
"null",
"!=",
"appender",
")",
"{",
"appender",
".",
"stop",
"(",
")",
";",
"Collection",
"<",
"String",
">",
"parentLoggerNames",
"=",
"getParentLoggerNames",
"(",
")",
";",
"for",
"(",
"String",
"configuredLoggerName",
":",
"getAllLoggerNames",
"(",
")",
")",
"{",
"LoggerConfig",
"loggerConfig",
"=",
"config",
".",
"getLoggerConfig",
"(",
"configuredLoggerName",
")",
";",
"loggerConfig",
".",
"removeAppender",
"(",
"appender",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"null",
"!=",
"baos",
".",
"getOriginalLevel",
"(",
"configuredLoggerName",
")",
")",
"{",
"changeLogger",
"(",
"configuredLoggerName",
",",
"baos",
".",
"getOriginalLevel",
"(",
"configuredLoggerName",
")",
",",
"parentLoggerNames",
".",
"contains",
"(",
"configuredLoggerName",
")",
")",
";",
"}",
"}",
"//unsure about, if removing the appender from logger config if it gets also removed from logger instance too...\r",
"removeAppender",
"(",
"appender",
",",
"getParentLoggers",
"(",
")",
")",
";",
"removeAppender",
"(",
"appender",
",",
"getLoggers",
"(",
")",
")",
";",
"appender",
".",
"getManager",
"(",
")",
".",
"getByteBuffer",
"(",
")",
".",
"clear",
"(",
")",
";",
"ctx",
".",
"updateLoggers",
"(",
")",
";",
"}",
"}",
"if",
"(",
"null",
"!=",
"baos",
")",
"{",
"try",
"{",
"baos",
".",
"close",
"(",
")",
";",
"baos",
".",
"clearOriginalLevels",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"ignore",
")",
"{",
"}",
"finally",
"{",
"outputStreams",
".",
"remove",
"(",
"appenderName",
")",
";",
"}",
"}",
"}"
] | closes output stream and removes appender from loggers
@param appenderName
@throws IOException
@since 1.1.1 | [
"closes",
"output",
"stream",
"and",
"removes",
"appender",
"from",
"loggers"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java#L516-L557 |
2,065 | andrehertwig/admintool | admin-tools-properties/src/main/java/de/chandre/admintool/properties/AdminToolPropertiesService.java | AdminToolPropertiesService.getEnvProperty | public Map<String, String> getEnvProperty() {
Map<String, String> res = new TreeMap<String, String>();
MutablePropertySources mps = env.getPropertySources();
Iterator<PropertySource<?>> iter = mps.iterator();
while (iter.hasNext()) {
PropertySource<?> ps = iter.next();
if (ps instanceof EnumerablePropertySource<?>) {
for (String propName : ((EnumerablePropertySource<?>) ps).getPropertyNames()) {
try {
res.put(propName, env.getProperty(propName));
} catch (Exception e) {
LOGGER.warn("unresolveable property: " + propName);
res.put(propName, "UNRESOLVEABLE");
}
}
}
}
return res;
} | java | public Map<String, String> getEnvProperty() {
Map<String, String> res = new TreeMap<String, String>();
MutablePropertySources mps = env.getPropertySources();
Iterator<PropertySource<?>> iter = mps.iterator();
while (iter.hasNext()) {
PropertySource<?> ps = iter.next();
if (ps instanceof EnumerablePropertySource<?>) {
for (String propName : ((EnumerablePropertySource<?>) ps).getPropertyNames()) {
try {
res.put(propName, env.getProperty(propName));
} catch (Exception e) {
LOGGER.warn("unresolveable property: " + propName);
res.put(propName, "UNRESOLVEABLE");
}
}
}
}
return res;
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"getEnvProperty",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"res",
"=",
"new",
"TreeMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"MutablePropertySources",
"mps",
"=",
"env",
".",
"getPropertySources",
"(",
")",
";",
"Iterator",
"<",
"PropertySource",
"<",
"?",
">",
">",
"iter",
"=",
"mps",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"PropertySource",
"<",
"?",
">",
"ps",
"=",
"iter",
".",
"next",
"(",
")",
";",
"if",
"(",
"ps",
"instanceof",
"EnumerablePropertySource",
"<",
"?",
">",
")",
"{",
"for",
"(",
"String",
"propName",
":",
"(",
"(",
"EnumerablePropertySource",
"<",
"?",
">",
")",
"ps",
")",
".",
"getPropertyNames",
"(",
")",
")",
"{",
"try",
"{",
"res",
".",
"put",
"(",
"propName",
",",
"env",
".",
"getProperty",
"(",
"propName",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"unresolveable property: \"",
"+",
"propName",
")",
";",
"res",
".",
"put",
"(",
"propName",
",",
"\"UNRESOLVEABLE\"",
")",
";",
"}",
"}",
"}",
"}",
"return",
"res",
";",
"}"
] | returns the spring environment properties
@return | [
"returns",
"the",
"spring",
"environment",
"properties"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-properties/src/main/java/de/chandre/admintool/properties/AdminToolPropertiesService.java#L88-L107 |
2,066 | andrehertwig/admintool | admin-tools-demo-core/src/main/java/de/chandre/admintool/Beans.java | Beans.adminToolMbeansExported | @Bean
public boolean adminToolMbeansExported(MBeanServer server, BeanFactory beanFactory, List<AdminToolConfig> configs) throws MalformedObjectNameException {
MBeanExporter mbeanExporter = new MBeanExporter();
mbeanExporter.setServer(server);
mbeanExporter.setBeanFactory(beanFactory);
SimpleReflectiveMBeanInfoAssembler assembler = new SimpleReflectiveMBeanInfoAssembler();
mbeanExporter.setAssembler(assembler);
mbeanExporter.setAutodetect(true);
LOGGER.info("registering %s managed admintool config resources", configs.size());
for (AdminToolConfig adminToolConfig : configs) {
LOGGER.info("registering managed resource: %s", adminToolConfig.getClass().getName());
ObjectName name = new ObjectName(String.format("de.chandre.admintool:type=Config,name=%s", adminToolConfig.getClass().getSimpleName()));
mbeanExporter.registerManagedResource(adminToolConfig, name);
}
return true;
} | java | @Bean
public boolean adminToolMbeansExported(MBeanServer server, BeanFactory beanFactory, List<AdminToolConfig> configs) throws MalformedObjectNameException {
MBeanExporter mbeanExporter = new MBeanExporter();
mbeanExporter.setServer(server);
mbeanExporter.setBeanFactory(beanFactory);
SimpleReflectiveMBeanInfoAssembler assembler = new SimpleReflectiveMBeanInfoAssembler();
mbeanExporter.setAssembler(assembler);
mbeanExporter.setAutodetect(true);
LOGGER.info("registering %s managed admintool config resources", configs.size());
for (AdminToolConfig adminToolConfig : configs) {
LOGGER.info("registering managed resource: %s", adminToolConfig.getClass().getName());
ObjectName name = new ObjectName(String.format("de.chandre.admintool:type=Config,name=%s", adminToolConfig.getClass().getSimpleName()));
mbeanExporter.registerManagedResource(adminToolConfig, name);
}
return true;
} | [
"@",
"Bean",
"public",
"boolean",
"adminToolMbeansExported",
"(",
"MBeanServer",
"server",
",",
"BeanFactory",
"beanFactory",
",",
"List",
"<",
"AdminToolConfig",
">",
"configs",
")",
"throws",
"MalformedObjectNameException",
"{",
"MBeanExporter",
"mbeanExporter",
"=",
"new",
"MBeanExporter",
"(",
")",
";",
"mbeanExporter",
".",
"setServer",
"(",
"server",
")",
";",
"mbeanExporter",
".",
"setBeanFactory",
"(",
"beanFactory",
")",
";",
"SimpleReflectiveMBeanInfoAssembler",
"assembler",
"=",
"new",
"SimpleReflectiveMBeanInfoAssembler",
"(",
")",
";",
"mbeanExporter",
".",
"setAssembler",
"(",
"assembler",
")",
";",
"mbeanExporter",
".",
"setAutodetect",
"(",
"true",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"registering %s managed admintool config resources\"",
",",
"configs",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"AdminToolConfig",
"adminToolConfig",
":",
"configs",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"registering managed resource: %s\"",
",",
"adminToolConfig",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"ObjectName",
"name",
"=",
"new",
"ObjectName",
"(",
"String",
".",
"format",
"(",
"\"de.chandre.admintool:type=Config,name=%s\"",
",",
"adminToolConfig",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
")",
";",
"mbeanExporter",
".",
"registerManagedResource",
"(",
"adminToolConfig",
",",
"name",
")",
";",
"}",
"return",
"true",
";",
"}"
] | maybe not reasonable to export all configuration beans as mbeans, especially configurations like fileBrowser or dbBrowser
@param mbeanExporter
@param configs
@return
@throws MalformedObjectNameException | [
"maybe",
"not",
"reasonable",
"to",
"export",
"all",
"configuration",
"beans",
"as",
"mbeans",
"especially",
"configurations",
"like",
"fileBrowser",
"or",
"dbBrowser"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-demo-core/src/main/java/de/chandre/admintool/Beans.java#L107-L122 |
2,067 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/component/MenuEntry.java | MenuEntry.setSubmenu | public void setSubmenu(List<MenuEntry> submenu) {
submenu.stream().forEach(entry -> entry.setParent(this));
this.submenu = submenu;
} | java | public void setSubmenu(List<MenuEntry> submenu) {
submenu.stream().forEach(entry -> entry.setParent(this));
this.submenu = submenu;
} | [
"public",
"void",
"setSubmenu",
"(",
"List",
"<",
"MenuEntry",
">",
"submenu",
")",
"{",
"submenu",
".",
"stream",
"(",
")",
".",
"forEach",
"(",
"entry",
"->",
"entry",
".",
"setParent",
"(",
"this",
")",
")",
";",
"this",
".",
"submenu",
"=",
"submenu",
";",
"}"
] | list of sub menu entries.
@param submenu the submenu to set | [
"list",
"of",
"sub",
"menu",
"entries",
"."
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/component/MenuEntry.java#L234-L237 |
2,068 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/component/MenuEntry.java | MenuEntry.getAdditionalJSReverse | public Map<String, Boolean> getAdditionalJSReverse() {
Map<String, Boolean> result = new LinkedHashMap<>();
List<MenuEntry> parents = reverseFlattened().collect(AdminToolMenuUtils.toListReversed());
parents.forEach(menuEntry -> {
if (null != menuEntry.getAdditionalJS()) {
result.putAll(menuEntry.getAdditionalJS());
}
});
return result;
} | java | public Map<String, Boolean> getAdditionalJSReverse() {
Map<String, Boolean> result = new LinkedHashMap<>();
List<MenuEntry> parents = reverseFlattened().collect(AdminToolMenuUtils.toListReversed());
parents.forEach(menuEntry -> {
if (null != menuEntry.getAdditionalJS()) {
result.putAll(menuEntry.getAdditionalJS());
}
});
return result;
} | [
"public",
"Map",
"<",
"String",
",",
"Boolean",
">",
"getAdditionalJSReverse",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Boolean",
">",
"result",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"List",
"<",
"MenuEntry",
">",
"parents",
"=",
"reverseFlattened",
"(",
")",
".",
"collect",
"(",
"AdminToolMenuUtils",
".",
"toListReversed",
"(",
")",
")",
";",
"parents",
".",
"forEach",
"(",
"menuEntry",
"->",
"{",
"if",
"(",
"null",
"!=",
"menuEntry",
".",
"getAdditionalJS",
"(",
")",
")",
"{",
"result",
".",
"putAll",
"(",
"menuEntry",
".",
"getAdditionalJS",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] | returns all additional js from this to upper menu item hierarchy beginning with the root.
@return
@since 1.1.4 | [
"returns",
"all",
"additional",
"js",
"from",
"this",
"to",
"upper",
"menu",
"item",
"hierarchy",
"beginning",
"with",
"the",
"root",
"."
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/component/MenuEntry.java#L379-L388 |
2,069 | andrehertwig/admintool | admin-tools-security/admin-tools-security-simple/src/main/java/de/chandre/admintool/security/simple/auth/AbstractAdminToolSecurityViewLoader.java | AbstractAdminToolSecurityViewLoader.addUsersMenu | protected void addUsersMenu() {
LOGGER.info("adding Authentication component");
MenuEntry mainMenu = new MenuEntry("users", "Users", "security/content/users", securityRolesConfig);
mainMenu.addAdditionalJS("/static/admintool/security/users.js", true);
mainMenu.addAdditionalJS("/static/admintool/security/validator.min.js", true);
mainMenu.setResouceMessageKey(AdminTool.RESOURCE_MESSAGE_KEY_PREFIX + "security.users.displayName");
String adminLtePrefix = getAdminLTEPrefixUri();
boolean relative = !shouldCDNsUsed();
//select 2 plugin
component.addAdditionalJS(adminLtePrefix + "plugins/select2/select2.min.js", relative);
component.addAdditionalCSS(adminLtePrefix + "plugins/select2/select2.min.css", relative);
//mustache js
component.addAdditionalJS(getWebjarsPrefixUri() + "mustache/" + mustacheVersion + "/mustache.min.js", relative);
component.setMainMenu(mainMenu);
component.setPosition(componentPosition);
component.getSecurityRoles().addAll(securityRolesConfig);
component.setDisplayName("Authentication");
adminTool.addComponent(component);
} | java | protected void addUsersMenu() {
LOGGER.info("adding Authentication component");
MenuEntry mainMenu = new MenuEntry("users", "Users", "security/content/users", securityRolesConfig);
mainMenu.addAdditionalJS("/static/admintool/security/users.js", true);
mainMenu.addAdditionalJS("/static/admintool/security/validator.min.js", true);
mainMenu.setResouceMessageKey(AdminTool.RESOURCE_MESSAGE_KEY_PREFIX + "security.users.displayName");
String adminLtePrefix = getAdminLTEPrefixUri();
boolean relative = !shouldCDNsUsed();
//select 2 plugin
component.addAdditionalJS(adminLtePrefix + "plugins/select2/select2.min.js", relative);
component.addAdditionalCSS(adminLtePrefix + "plugins/select2/select2.min.css", relative);
//mustache js
component.addAdditionalJS(getWebjarsPrefixUri() + "mustache/" + mustacheVersion + "/mustache.min.js", relative);
component.setMainMenu(mainMenu);
component.setPosition(componentPosition);
component.getSecurityRoles().addAll(securityRolesConfig);
component.setDisplayName("Authentication");
adminTool.addComponent(component);
} | [
"protected",
"void",
"addUsersMenu",
"(",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"adding Authentication component\"",
")",
";",
"MenuEntry",
"mainMenu",
"=",
"new",
"MenuEntry",
"(",
"\"users\"",
",",
"\"Users\"",
",",
"\"security/content/users\"",
",",
"securityRolesConfig",
")",
";",
"mainMenu",
".",
"addAdditionalJS",
"(",
"\"/static/admintool/security/users.js\"",
",",
"true",
")",
";",
"mainMenu",
".",
"addAdditionalJS",
"(",
"\"/static/admintool/security/validator.min.js\"",
",",
"true",
")",
";",
"mainMenu",
".",
"setResouceMessageKey",
"(",
"AdminTool",
".",
"RESOURCE_MESSAGE_KEY_PREFIX",
"+",
"\"security.users.displayName\"",
")",
";",
"String",
"adminLtePrefix",
"=",
"getAdminLTEPrefixUri",
"(",
")",
";",
"boolean",
"relative",
"=",
"!",
"shouldCDNsUsed",
"(",
")",
";",
"//select 2 plugin",
"component",
".",
"addAdditionalJS",
"(",
"adminLtePrefix",
"+",
"\"plugins/select2/select2.min.js\"",
",",
"relative",
")",
";",
"component",
".",
"addAdditionalCSS",
"(",
"adminLtePrefix",
"+",
"\"plugins/select2/select2.min.css\"",
",",
"relative",
")",
";",
"//mustache js",
"component",
".",
"addAdditionalJS",
"(",
"getWebjarsPrefixUri",
"(",
")",
"+",
"\"mustache/\"",
"+",
"mustacheVersion",
"+",
"\"/mustache.min.js\"",
",",
"relative",
")",
";",
"component",
".",
"setMainMenu",
"(",
"mainMenu",
")",
";",
"component",
".",
"setPosition",
"(",
"componentPosition",
")",
";",
"component",
".",
"getSecurityRoles",
"(",
")",
".",
"addAll",
"(",
"securityRolesConfig",
")",
";",
"component",
".",
"setDisplayName",
"(",
"\"Authentication\"",
")",
";",
"adminTool",
".",
"addComponent",
"(",
"component",
")",
";",
"}"
] | adds the users view to admin tool | [
"adds",
"the",
"users",
"view",
"to",
"admin",
"tool"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-simple/src/main/java/de/chandre/admintool/security/simple/auth/AbstractAdminToolSecurityViewLoader.java#L45-L69 |
2,070 | andrehertwig/admintool | admin-tools-security/admin-tools-security-simple/src/main/java/de/chandre/admintool/security/simple/auth/AbstractAdminToolSecurityViewController.java | AbstractAdminToolSecurityViewController.transformToSimpleAuthorities | protected Collection<GrantedAuthority> transformToSimpleAuthorities(Set<String> strAuthorities, boolean appendRolePrefix) {
if (null != strAuthorities) {
Collection<GrantedAuthority> authorities = new HashSet<>(strAuthorities.size());
for (String authority : strAuthorities) {
if (!StringUtils.isEmpty(authority)) {
String role = authority.trim().toUpperCase(Locale.ENGLISH);
if (appendRolePrefix) {
authorities.add(new SimpleGrantedAuthority(getRolePrefix() + role));
} else {
authorities.add(new SimpleGrantedAuthority(role));
}
}
}
return authorities;
}
return Collections.emptyList();
} | java | protected Collection<GrantedAuthority> transformToSimpleAuthorities(Set<String> strAuthorities, boolean appendRolePrefix) {
if (null != strAuthorities) {
Collection<GrantedAuthority> authorities = new HashSet<>(strAuthorities.size());
for (String authority : strAuthorities) {
if (!StringUtils.isEmpty(authority)) {
String role = authority.trim().toUpperCase(Locale.ENGLISH);
if (appendRolePrefix) {
authorities.add(new SimpleGrantedAuthority(getRolePrefix() + role));
} else {
authorities.add(new SimpleGrantedAuthority(role));
}
}
}
return authorities;
}
return Collections.emptyList();
} | [
"protected",
"Collection",
"<",
"GrantedAuthority",
">",
"transformToSimpleAuthorities",
"(",
"Set",
"<",
"String",
">",
"strAuthorities",
",",
"boolean",
"appendRolePrefix",
")",
"{",
"if",
"(",
"null",
"!=",
"strAuthorities",
")",
"{",
"Collection",
"<",
"GrantedAuthority",
">",
"authorities",
"=",
"new",
"HashSet",
"<>",
"(",
"strAuthorities",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"String",
"authority",
":",
"strAuthorities",
")",
"{",
"if",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"authority",
")",
")",
"{",
"String",
"role",
"=",
"authority",
".",
"trim",
"(",
")",
".",
"toUpperCase",
"(",
"Locale",
".",
"ENGLISH",
")",
";",
"if",
"(",
"appendRolePrefix",
")",
"{",
"authorities",
".",
"add",
"(",
"new",
"SimpleGrantedAuthority",
"(",
"getRolePrefix",
"(",
")",
"+",
"role",
")",
")",
";",
"}",
"else",
"{",
"authorities",
".",
"add",
"(",
"new",
"SimpleGrantedAuthority",
"(",
"role",
")",
")",
";",
"}",
"}",
"}",
"return",
"authorities",
";",
"}",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}"
] | transforms all authorities to upper case and append the prefix if appendRolePrefix = true
@param strAuthorities
@param appendRolePrefix
@return Empty collection or collection of {@link SimpleGrantedAuthority} | [
"transforms",
"all",
"authorities",
"to",
"upper",
"case",
"and",
"append",
"the",
"prefix",
"if",
"appendRolePrefix",
"=",
"true"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-simple/src/main/java/de/chandre/admintool/security/simple/auth/AbstractAdminToolSecurityViewController.java#L122-L138 |
2,071 | andrehertwig/admintool | admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserServiceImpl.java | AdminToolDBBrowserServiceImpl.iterateResult | protected void iterateResult(ResultSet resSet, QueryResultTO resultTO, StatementTO statementTO) {
try {
if (resSet != null && !resSet.isClosed()) {
ResultSetMetaData metaData = resSet.getMetaData();
int cols = metaData.getColumnCount();
Map<Integer, Integer> type = new HashMap<Integer, Integer>();
List<String> columnsNames = new ArrayList<>();
for (int i = 1; i < (cols+1); i++)
{
String colName = metaData.getColumnName(i);
columnsNames.add(colName);
type.put(i, metaData.getColumnType(i));
}
List<List<String>> tableResult = new ArrayList<>();
String clobEncoding = statementTO.getClobEncoding() != null ? statementTO.getClobEncoding() : DEFAULT_CLOB_ENCODING;
while (resSet.next())
{
List<String> row = new ArrayList<>();
for (int i = 1; i < (cols+1); i++)
{
if (type.get(i) != null && type.get(i) == Types.BLOB) {
if (statementTO.isShowBlobs()) {
row.add(String.valueOf(new String(resSet.getBytes(i))));
} else {
row.add(String.valueOf(resSet.getObject(i)));
}
} else if (type.get(i) != null && type.get(i) == Types.CLOB) {
if (statementTO.isShowClobs()) {
row.add(getClobString(resSet.getClob(i), clobEncoding ));
} else {
row.add("CLOB content");
}
} else {
row.add(String.valueOf(resSet.getObject(i)));
}
}
tableResult.add(row);
}
resultTO.setSqlWarnings(null != resSet.getWarnings() ? resSet.getWarnings().toString() : null);
resultTO.setAffectedRows(tableResult.size());
resultTO.setColumnsNames(columnsNames);
resultTO.setTableResult(tableResult);
} else {
resultTO.setSqlWarnings("resultSet was " + (null != resSet ? "closed already" : "null"));
}
resultTO.setSelect(true);
} catch (Exception e) {
resultTO.setExceptionMessage(e.getMessage());
resultTO.setExceptionCause(null != e.getCause() ? e.getCause().toString() : null);
resultTO.setExceptionTrace(printException(e));
}
} | java | protected void iterateResult(ResultSet resSet, QueryResultTO resultTO, StatementTO statementTO) {
try {
if (resSet != null && !resSet.isClosed()) {
ResultSetMetaData metaData = resSet.getMetaData();
int cols = metaData.getColumnCount();
Map<Integer, Integer> type = new HashMap<Integer, Integer>();
List<String> columnsNames = new ArrayList<>();
for (int i = 1; i < (cols+1); i++)
{
String colName = metaData.getColumnName(i);
columnsNames.add(colName);
type.put(i, metaData.getColumnType(i));
}
List<List<String>> tableResult = new ArrayList<>();
String clobEncoding = statementTO.getClobEncoding() != null ? statementTO.getClobEncoding() : DEFAULT_CLOB_ENCODING;
while (resSet.next())
{
List<String> row = new ArrayList<>();
for (int i = 1; i < (cols+1); i++)
{
if (type.get(i) != null && type.get(i) == Types.BLOB) {
if (statementTO.isShowBlobs()) {
row.add(String.valueOf(new String(resSet.getBytes(i))));
} else {
row.add(String.valueOf(resSet.getObject(i)));
}
} else if (type.get(i) != null && type.get(i) == Types.CLOB) {
if (statementTO.isShowClobs()) {
row.add(getClobString(resSet.getClob(i), clobEncoding ));
} else {
row.add("CLOB content");
}
} else {
row.add(String.valueOf(resSet.getObject(i)));
}
}
tableResult.add(row);
}
resultTO.setSqlWarnings(null != resSet.getWarnings() ? resSet.getWarnings().toString() : null);
resultTO.setAffectedRows(tableResult.size());
resultTO.setColumnsNames(columnsNames);
resultTO.setTableResult(tableResult);
} else {
resultTO.setSqlWarnings("resultSet was " + (null != resSet ? "closed already" : "null"));
}
resultTO.setSelect(true);
} catch (Exception e) {
resultTO.setExceptionMessage(e.getMessage());
resultTO.setExceptionCause(null != e.getCause() ? e.getCause().toString() : null);
resultTO.setExceptionTrace(printException(e));
}
} | [
"protected",
"void",
"iterateResult",
"(",
"ResultSet",
"resSet",
",",
"QueryResultTO",
"resultTO",
",",
"StatementTO",
"statementTO",
")",
"{",
"try",
"{",
"if",
"(",
"resSet",
"!=",
"null",
"&&",
"!",
"resSet",
".",
"isClosed",
"(",
")",
")",
"{",
"ResultSetMetaData",
"metaData",
"=",
"resSet",
".",
"getMetaData",
"(",
")",
";",
"int",
"cols",
"=",
"metaData",
".",
"getColumnCount",
"(",
")",
";",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"type",
"=",
"new",
"HashMap",
"<",
"Integer",
",",
"Integer",
">",
"(",
")",
";",
"List",
"<",
"String",
">",
"columnsNames",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"(",
"cols",
"+",
"1",
")",
";",
"i",
"++",
")",
"{",
"String",
"colName",
"=",
"metaData",
".",
"getColumnName",
"(",
"i",
")",
";",
"columnsNames",
".",
"add",
"(",
"colName",
")",
";",
"type",
".",
"put",
"(",
"i",
",",
"metaData",
".",
"getColumnType",
"(",
"i",
")",
")",
";",
"}",
"List",
"<",
"List",
"<",
"String",
">",
">",
"tableResult",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"String",
"clobEncoding",
"=",
"statementTO",
".",
"getClobEncoding",
"(",
")",
"!=",
"null",
"?",
"statementTO",
".",
"getClobEncoding",
"(",
")",
":",
"DEFAULT_CLOB_ENCODING",
";",
"while",
"(",
"resSet",
".",
"next",
"(",
")",
")",
"{",
"List",
"<",
"String",
">",
"row",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"(",
"cols",
"+",
"1",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"type",
".",
"get",
"(",
"i",
")",
"!=",
"null",
"&&",
"type",
".",
"get",
"(",
"i",
")",
"==",
"Types",
".",
"BLOB",
")",
"{",
"if",
"(",
"statementTO",
".",
"isShowBlobs",
"(",
")",
")",
"{",
"row",
".",
"add",
"(",
"String",
".",
"valueOf",
"(",
"new",
"String",
"(",
"resSet",
".",
"getBytes",
"(",
"i",
")",
")",
")",
")",
";",
"}",
"else",
"{",
"row",
".",
"add",
"(",
"String",
".",
"valueOf",
"(",
"resSet",
".",
"getObject",
"(",
"i",
")",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"type",
".",
"get",
"(",
"i",
")",
"!=",
"null",
"&&",
"type",
".",
"get",
"(",
"i",
")",
"==",
"Types",
".",
"CLOB",
")",
"{",
"if",
"(",
"statementTO",
".",
"isShowClobs",
"(",
")",
")",
"{",
"row",
".",
"add",
"(",
"getClobString",
"(",
"resSet",
".",
"getClob",
"(",
"i",
")",
",",
"clobEncoding",
")",
")",
";",
"}",
"else",
"{",
"row",
".",
"add",
"(",
"\"CLOB content\"",
")",
";",
"}",
"}",
"else",
"{",
"row",
".",
"add",
"(",
"String",
".",
"valueOf",
"(",
"resSet",
".",
"getObject",
"(",
"i",
")",
")",
")",
";",
"}",
"}",
"tableResult",
".",
"add",
"(",
"row",
")",
";",
"}",
"resultTO",
".",
"setSqlWarnings",
"(",
"null",
"!=",
"resSet",
".",
"getWarnings",
"(",
")",
"?",
"resSet",
".",
"getWarnings",
"(",
")",
".",
"toString",
"(",
")",
":",
"null",
")",
";",
"resultTO",
".",
"setAffectedRows",
"(",
"tableResult",
".",
"size",
"(",
")",
")",
";",
"resultTO",
".",
"setColumnsNames",
"(",
"columnsNames",
")",
";",
"resultTO",
".",
"setTableResult",
"(",
"tableResult",
")",
";",
"}",
"else",
"{",
"resultTO",
".",
"setSqlWarnings",
"(",
"\"resultSet was \"",
"+",
"(",
"null",
"!=",
"resSet",
"?",
"\"closed already\"",
":",
"\"null\"",
")",
")",
";",
"}",
"resultTO",
".",
"setSelect",
"(",
"true",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"resultTO",
".",
"setExceptionMessage",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"resultTO",
".",
"setExceptionCause",
"(",
"null",
"!=",
"e",
".",
"getCause",
"(",
")",
"?",
"e",
".",
"getCause",
"(",
")",
".",
"toString",
"(",
")",
":",
"null",
")",
";",
"resultTO",
".",
"setExceptionTrace",
"(",
"printException",
"(",
"e",
")",
")",
";",
"}",
"}"
] | iterates the resultSet and fills resultTO
@param resSet
@param resultTO
@param statementTO | [
"iterates",
"the",
"resultSet",
"and",
"fills",
"resultTO"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserServiceImpl.java#L320-L378 |
2,072 | andrehertwig/admintool | admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserServiceImpl.java | AdminToolDBBrowserServiceImpl.getClobString | protected String getClobString(Clob clobObject, String encoding) throws IOException, SQLException, UnsupportedEncodingException
{
if (null == clobObject) {
return "";
}
InputStream in = clobObject.getAsciiStream();
Reader read = new InputStreamReader(in, encoding);
StringWriter write = new StringWriter();
String result = null;
try {
int c = -1;
while ((c = read.read()) != -1) {
write.write(c);
}
write.flush();
result = write.toString();
} finally {
closeStream(write);
closeStream(read);
//should we close the ascii stream from database? or is it handled by connection
// closeStream(in);
}
return result;
} | java | protected String getClobString(Clob clobObject, String encoding) throws IOException, SQLException, UnsupportedEncodingException
{
if (null == clobObject) {
return "";
}
InputStream in = clobObject.getAsciiStream();
Reader read = new InputStreamReader(in, encoding);
StringWriter write = new StringWriter();
String result = null;
try {
int c = -1;
while ((c = read.read()) != -1) {
write.write(c);
}
write.flush();
result = write.toString();
} finally {
closeStream(write);
closeStream(read);
//should we close the ascii stream from database? or is it handled by connection
// closeStream(in);
}
return result;
} | [
"protected",
"String",
"getClobString",
"(",
"Clob",
"clobObject",
",",
"String",
"encoding",
")",
"throws",
"IOException",
",",
"SQLException",
",",
"UnsupportedEncodingException",
"{",
"if",
"(",
"null",
"==",
"clobObject",
")",
"{",
"return",
"\"\"",
";",
"}",
"InputStream",
"in",
"=",
"clobObject",
".",
"getAsciiStream",
"(",
")",
";",
"Reader",
"read",
"=",
"new",
"InputStreamReader",
"(",
"in",
",",
"encoding",
")",
";",
"StringWriter",
"write",
"=",
"new",
"StringWriter",
"(",
")",
";",
"String",
"result",
"=",
"null",
";",
"try",
"{",
"int",
"c",
"=",
"-",
"1",
";",
"while",
"(",
"(",
"c",
"=",
"read",
".",
"read",
"(",
")",
")",
"!=",
"-",
"1",
")",
"{",
"write",
".",
"write",
"(",
"c",
")",
";",
"}",
"write",
".",
"flush",
"(",
")",
";",
"result",
"=",
"write",
".",
"toString",
"(",
")",
";",
"}",
"finally",
"{",
"closeStream",
"(",
"write",
")",
";",
"closeStream",
"(",
"read",
")",
";",
"//should we close the ascii stream from database? or is it handled by connection\r",
"// closeStream(in);\r",
"}",
"return",
"result",
";",
"}"
] | turns clob into a string
@param clobObject
@param encoding
@return
@throws IOException
@throws SQLException
@throws UnsupportedEncodingException | [
"turns",
"clob",
"into",
"a",
"string"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserServiceImpl.java#L391-L414 |
2,073 | andrehertwig/admintool | admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserServiceImpl.java | AdminToolDBBrowserServiceImpl.printException | protected static String printException(final Throwable throwable)
{
if (null == throwable) {
return null;
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(baos);
throwable.printStackTrace(printStream);
String exceptionStr = "";
try {
exceptionStr = baos.toString("UTF-8");
} catch (Exception ex) {
exceptionStr = "Unavailable";
} finally {
closeStream(printStream);
closeStream(baos);
}
return exceptionStr;
} | java | protected static String printException(final Throwable throwable)
{
if (null == throwable) {
return null;
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(baos);
throwable.printStackTrace(printStream);
String exceptionStr = "";
try {
exceptionStr = baos.toString("UTF-8");
} catch (Exception ex) {
exceptionStr = "Unavailable";
} finally {
closeStream(printStream);
closeStream(baos);
}
return exceptionStr;
} | [
"protected",
"static",
"String",
"printException",
"(",
"final",
"Throwable",
"throwable",
")",
"{",
"if",
"(",
"null",
"==",
"throwable",
")",
"{",
"return",
"null",
";",
"}",
"final",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"final",
"PrintStream",
"printStream",
"=",
"new",
"PrintStream",
"(",
"baos",
")",
";",
"throwable",
".",
"printStackTrace",
"(",
"printStream",
")",
";",
"String",
"exceptionStr",
"=",
"\"\"",
";",
"try",
"{",
"exceptionStr",
"=",
"baos",
".",
"toString",
"(",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"exceptionStr",
"=",
"\"Unavailable\"",
";",
"}",
"finally",
"{",
"closeStream",
"(",
"printStream",
")",
";",
"closeStream",
"(",
"baos",
")",
";",
"}",
"return",
"exceptionStr",
";",
"}"
] | prints a exception into a string
@param throwable
@return | [
"prints",
"a",
"exception",
"into",
"a",
"string"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserServiceImpl.java#L421-L439 |
2,074 | andrehertwig/admintool | admin-tools-filebrowser/src/main/java/de/chandre/admintool/filebrowser/AbstractFileBrowserService.java | AbstractFileBrowserService.getExtension | public String getExtension(String fileName) {
if (fileName.lastIndexOf('.') > -1) {
return (fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length())).toLowerCase();
}
return null;
} | java | public String getExtension(String fileName) {
if (fileName.lastIndexOf('.') > -1) {
return (fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length())).toLowerCase();
}
return null;
} | [
"public",
"String",
"getExtension",
"(",
"String",
"fileName",
")",
"{",
"if",
"(",
"fileName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
">",
"-",
"1",
")",
"{",
"return",
"(",
"fileName",
".",
"substring",
"(",
"fileName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
"+",
"1",
",",
"fileName",
".",
"length",
"(",
")",
")",
")",
".",
"toLowerCase",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] | returns the file extension by filename separated by last dot
@param fileName
@return null or extension | [
"returns",
"the",
"file",
"extension",
"by",
"filename",
"separated",
"by",
"last",
"dot"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-filebrowser/src/main/java/de/chandre/admintool/filebrowser/AbstractFileBrowserService.java#L70-L75 |
2,075 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/thymeleaf/OrderedClassLoaderResourceResolver.java | OrderedClassLoaderResourceResolver.getResourceAsStream | protected InputStream getResourceAsStream(String paramString) throws MalformedURLException {
URL localURL = new URL(paramString);
try {
if (null != localURL) {
URLConnection localURLConnection = localURL.openConnection();
return localURLConnection.getInputStream();
}
} catch (IOException localIOException) {
}
return null;
} | java | protected InputStream getResourceAsStream(String paramString) throws MalformedURLException {
URL localURL = new URL(paramString);
try {
if (null != localURL) {
URLConnection localURLConnection = localURL.openConnection();
return localURLConnection.getInputStream();
}
} catch (IOException localIOException) {
}
return null;
} | [
"protected",
"InputStream",
"getResourceAsStream",
"(",
"String",
"paramString",
")",
"throws",
"MalformedURLException",
"{",
"URL",
"localURL",
"=",
"new",
"URL",
"(",
"paramString",
")",
";",
"try",
"{",
"if",
"(",
"null",
"!=",
"localURL",
")",
"{",
"URLConnection",
"localURLConnection",
"=",
"localURL",
".",
"openConnection",
"(",
")",
";",
"return",
"localURLConnection",
".",
"getInputStream",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"localIOException",
")",
"{",
"}",
"return",
"null",
";",
"}"
] | loads the input stream of an url
@param paramString
@return
@throws MalformedURLException | [
"loads",
"the",
"input",
"stream",
"of",
"an",
"url"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/thymeleaf/OrderedClassLoaderResourceResolver.java#L150-L160 |
2,076 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolIntegrityUtil.java | AdminToolIntegrityUtil.checkMenuIntegrity | public List<MenuIntegrityError> checkMenuIntegrity() {
List<MenuIntegrityError> errorList = new ArrayList<>();
Map<String, MenuEntry> links = new HashMap<>();
Map<String, MenuEntry> templates = new HashMap<>();
// check for duplicates, but only if menu has no submenu, otherwise o
// link will be generated
for (AdminComponent comp : adminTool.getComponents()) {
if (null != comp.getMainMenu()) {
comp.getMainMenu().flattened().forEach(menu -> {
if (links.containsKey(menu.getName()) && CollectionUtils.isEmpty(menu.getSubmenu())) {
findErrorAndAddEntry("duplicate link name on menu item",
MSG_KEY_DUPLICATE_LINK, errorList, menu, links.get(menu.getName()));
} else {
links.put(menu.getName(), menu);
}
if (templates.containsKey(menu.getTarget()) && CollectionUtils.isEmpty(menu.getSubmenu())) {
findErrorAndAddEntry("duplicate template reference on menu item",
MSG_KEY_DUPLICATE_TPL_REF, errorList, menu, templates.get(menu.getTarget()));
} else {
templates.put(menu.getTarget(), menu);
}
if(config.isInternationalizationEnabled() && StringUtils.isEmpty(menu.getResouceMessageKey())) {
findErrorAndAddEntry("missing message resource key on menu item",
MSG_KEY_MISSING_RESOURCE_KEY, errorList, menu, templates.get(menu.getTarget()));
}
});
} else {
findErrorAndAddEntry(String.format("the component '%s' has no main menu", comp.getDisplayName()),
MSG_KEY_COMPONENT_NO_MAINMENU, errorList, null, null);
}
}
links.clear();
templates.clear();
return errorList;
} | java | public List<MenuIntegrityError> checkMenuIntegrity() {
List<MenuIntegrityError> errorList = new ArrayList<>();
Map<String, MenuEntry> links = new HashMap<>();
Map<String, MenuEntry> templates = new HashMap<>();
// check for duplicates, but only if menu has no submenu, otherwise o
// link will be generated
for (AdminComponent comp : adminTool.getComponents()) {
if (null != comp.getMainMenu()) {
comp.getMainMenu().flattened().forEach(menu -> {
if (links.containsKey(menu.getName()) && CollectionUtils.isEmpty(menu.getSubmenu())) {
findErrorAndAddEntry("duplicate link name on menu item",
MSG_KEY_DUPLICATE_LINK, errorList, menu, links.get(menu.getName()));
} else {
links.put(menu.getName(), menu);
}
if (templates.containsKey(menu.getTarget()) && CollectionUtils.isEmpty(menu.getSubmenu())) {
findErrorAndAddEntry("duplicate template reference on menu item",
MSG_KEY_DUPLICATE_TPL_REF, errorList, menu, templates.get(menu.getTarget()));
} else {
templates.put(menu.getTarget(), menu);
}
if(config.isInternationalizationEnabled() && StringUtils.isEmpty(menu.getResouceMessageKey())) {
findErrorAndAddEntry("missing message resource key on menu item",
MSG_KEY_MISSING_RESOURCE_KEY, errorList, menu, templates.get(menu.getTarget()));
}
});
} else {
findErrorAndAddEntry(String.format("the component '%s' has no main menu", comp.getDisplayName()),
MSG_KEY_COMPONENT_NO_MAINMENU, errorList, null, null);
}
}
links.clear();
templates.clear();
return errorList;
} | [
"public",
"List",
"<",
"MenuIntegrityError",
">",
"checkMenuIntegrity",
"(",
")",
"{",
"List",
"<",
"MenuIntegrityError",
">",
"errorList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Map",
"<",
"String",
",",
"MenuEntry",
">",
"links",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"Map",
"<",
"String",
",",
"MenuEntry",
">",
"templates",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"// check for duplicates, but only if menu has no submenu, otherwise o",
"// link will be generated",
"for",
"(",
"AdminComponent",
"comp",
":",
"adminTool",
".",
"getComponents",
"(",
")",
")",
"{",
"if",
"(",
"null",
"!=",
"comp",
".",
"getMainMenu",
"(",
")",
")",
"{",
"comp",
".",
"getMainMenu",
"(",
")",
".",
"flattened",
"(",
")",
".",
"forEach",
"(",
"menu",
"->",
"{",
"if",
"(",
"links",
".",
"containsKey",
"(",
"menu",
".",
"getName",
"(",
")",
")",
"&&",
"CollectionUtils",
".",
"isEmpty",
"(",
"menu",
".",
"getSubmenu",
"(",
")",
")",
")",
"{",
"findErrorAndAddEntry",
"(",
"\"duplicate link name on menu item\"",
",",
"MSG_KEY_DUPLICATE_LINK",
",",
"errorList",
",",
"menu",
",",
"links",
".",
"get",
"(",
"menu",
".",
"getName",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"links",
".",
"put",
"(",
"menu",
".",
"getName",
"(",
")",
",",
"menu",
")",
";",
"}",
"if",
"(",
"templates",
".",
"containsKey",
"(",
"menu",
".",
"getTarget",
"(",
")",
")",
"&&",
"CollectionUtils",
".",
"isEmpty",
"(",
"menu",
".",
"getSubmenu",
"(",
")",
")",
")",
"{",
"findErrorAndAddEntry",
"(",
"\"duplicate template reference on menu item\"",
",",
"MSG_KEY_DUPLICATE_TPL_REF",
",",
"errorList",
",",
"menu",
",",
"templates",
".",
"get",
"(",
"menu",
".",
"getTarget",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"templates",
".",
"put",
"(",
"menu",
".",
"getTarget",
"(",
")",
",",
"menu",
")",
";",
"}",
"if",
"(",
"config",
".",
"isInternationalizationEnabled",
"(",
")",
"&&",
"StringUtils",
".",
"isEmpty",
"(",
"menu",
".",
"getResouceMessageKey",
"(",
")",
")",
")",
"{",
"findErrorAndAddEntry",
"(",
"\"missing message resource key on menu item\"",
",",
"MSG_KEY_MISSING_RESOURCE_KEY",
",",
"errorList",
",",
"menu",
",",
"templates",
".",
"get",
"(",
"menu",
".",
"getTarget",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"findErrorAndAddEntry",
"(",
"String",
".",
"format",
"(",
"\"the component '%s' has no main menu\"",
",",
"comp",
".",
"getDisplayName",
"(",
")",
")",
",",
"MSG_KEY_COMPONENT_NO_MAINMENU",
",",
"errorList",
",",
"null",
",",
"null",
")",
";",
"}",
"}",
"links",
".",
"clear",
"(",
")",
";",
"templates",
".",
"clear",
"(",
")",
";",
"return",
"errorList",
";",
"}"
] | checks for integrity errors
@return empty list or errors | [
"checks",
"for",
"integrity",
"errors"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/AdminToolIntegrityUtil.java#L60-L97 |
2,077 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/ReflectUtils.java | ReflectUtils.toSetter | public static String toSetter(final String fieldName) {
return "set" + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(1, fieldName.length());
} | java | public static String toSetter(final String fieldName) {
return "set" + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(1, fieldName.length());
} | [
"public",
"static",
"String",
"toSetter",
"(",
"final",
"String",
"fieldName",
")",
"{",
"return",
"\"set\"",
"+",
"fieldName",
".",
"substring",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
"Locale",
".",
"ENGLISH",
")",
"+",
"fieldName",
".",
"substring",
"(",
"1",
",",
"fieldName",
".",
"length",
"(",
")",
")",
";",
"}"
] | creates setter out of field name
@param fieldName
@return | [
"creates",
"setter",
"out",
"of",
"field",
"name"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/ReflectUtils.java#L101-L103 |
2,078 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/ReflectUtils.java | ReflectUtils.copy | public static void copy(Object object, Object clone, String fieldName, boolean ignoreNonExisting)
{
invokeSetter(clone, fieldName, invokeGetter(object, fieldName), ignoreNonExisting);
} | java | public static void copy(Object object, Object clone, String fieldName, boolean ignoreNonExisting)
{
invokeSetter(clone, fieldName, invokeGetter(object, fieldName), ignoreNonExisting);
} | [
"public",
"static",
"void",
"copy",
"(",
"Object",
"object",
",",
"Object",
"clone",
",",
"String",
"fieldName",
",",
"boolean",
"ignoreNonExisting",
")",
"{",
"invokeSetter",
"(",
"clone",
",",
"fieldName",
",",
"invokeGetter",
"(",
"object",
",",
"fieldName",
")",
",",
"ignoreNonExisting",
")",
";",
"}"
] | copys a value from one to another object with same field name!
@param object
@param clone
@param fieldName | [
"copys",
"a",
"value",
"from",
"one",
"to",
"another",
"object",
"with",
"same",
"field",
"name!"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/ReflectUtils.java#L200-L203 |
2,079 | andrehertwig/admintool | admin-tools-core/src/main/java/de/chandre/admintool/core/utils/ReflectUtils.java | ReflectUtils.copy | public static void copy(Object object, Field field, Object clone, Field cloneField, boolean ignoreNonExisting)
{
invokeSetter(clone, cloneField, invokeGetter(object, field), ignoreNonExisting);
} | java | public static void copy(Object object, Field field, Object clone, Field cloneField, boolean ignoreNonExisting)
{
invokeSetter(clone, cloneField, invokeGetter(object, field), ignoreNonExisting);
} | [
"public",
"static",
"void",
"copy",
"(",
"Object",
"object",
",",
"Field",
"field",
",",
"Object",
"clone",
",",
"Field",
"cloneField",
",",
"boolean",
"ignoreNonExisting",
")",
"{",
"invokeSetter",
"(",
"clone",
",",
"cloneField",
",",
"invokeGetter",
"(",
"object",
",",
"field",
")",
",",
"ignoreNonExisting",
")",
";",
"}"
] | copys a value from one to another object !
@param object
@param field
@param clone
@param cloneField | [
"copys",
"a",
"value",
"from",
"one",
"to",
"another",
"object",
"!"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/utils/ReflectUtils.java#L213-L216 |
2,080 | andrehertwig/admintool | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/auth/AdminToolSecDBBeans.java | AdminToolSecDBBeans.auditorProvider | public static AuditorAware<String> auditorProvider(ATUser systemUser, ATUser anonymousUser) {
return new AuditorAware<String>() {
private final Log LOGGER = LogFactory.getLog(AuditorAware.class);
public String getCurrentAuditor() {
SecurityContext secCtx = SecurityContextHolder.getContext();
if (null == secCtx) {
return systemUser.getUsername();
}
Authentication authentication = secCtx.getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
LOGGER.debug(String.format("using %s user for auditing", systemUser.getUsername()));
return systemUser.getUsername();
}
else if (authentication.isAuthenticated() && !ATUser.class.isAssignableFrom(authentication.getPrincipal().getClass())) {
LOGGER.debug(String.format("using %s user for auditing", anonymousUser.getUsername()));
return anonymousUser.getUsername();
}
return ((ATUser) authentication.getPrincipal()).getUsername();
}
};
} | java | public static AuditorAware<String> auditorProvider(ATUser systemUser, ATUser anonymousUser) {
return new AuditorAware<String>() {
private final Log LOGGER = LogFactory.getLog(AuditorAware.class);
public String getCurrentAuditor() {
SecurityContext secCtx = SecurityContextHolder.getContext();
if (null == secCtx) {
return systemUser.getUsername();
}
Authentication authentication = secCtx.getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
LOGGER.debug(String.format("using %s user for auditing", systemUser.getUsername()));
return systemUser.getUsername();
}
else if (authentication.isAuthenticated() && !ATUser.class.isAssignableFrom(authentication.getPrincipal().getClass())) {
LOGGER.debug(String.format("using %s user for auditing", anonymousUser.getUsername()));
return anonymousUser.getUsername();
}
return ((ATUser) authentication.getPrincipal()).getUsername();
}
};
} | [
"public",
"static",
"AuditorAware",
"<",
"String",
">",
"auditorProvider",
"(",
"ATUser",
"systemUser",
",",
"ATUser",
"anonymousUser",
")",
"{",
"return",
"new",
"AuditorAware",
"<",
"String",
">",
"(",
")",
"{",
"private",
"final",
"Log",
"LOGGER",
"=",
"LogFactory",
".",
"getLog",
"(",
"AuditorAware",
".",
"class",
")",
";",
"public",
"String",
"getCurrentAuditor",
"(",
")",
"{",
"SecurityContext",
"secCtx",
"=",
"SecurityContextHolder",
".",
"getContext",
"(",
")",
";",
"if",
"(",
"null",
"==",
"secCtx",
")",
"{",
"return",
"systemUser",
".",
"getUsername",
"(",
")",
";",
"}",
"Authentication",
"authentication",
"=",
"secCtx",
".",
"getAuthentication",
"(",
")",
";",
"if",
"(",
"authentication",
"==",
"null",
"||",
"!",
"authentication",
".",
"isAuthenticated",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"using %s user for auditing\"",
",",
"systemUser",
".",
"getUsername",
"(",
")",
")",
")",
";",
"return",
"systemUser",
".",
"getUsername",
"(",
")",
";",
"}",
"else",
"if",
"(",
"authentication",
".",
"isAuthenticated",
"(",
")",
"&&",
"!",
"ATUser",
".",
"class",
".",
"isAssignableFrom",
"(",
"authentication",
".",
"getPrincipal",
"(",
")",
".",
"getClass",
"(",
")",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"using %s user for auditing\"",
",",
"anonymousUser",
".",
"getUsername",
"(",
")",
")",
")",
";",
"return",
"anonymousUser",
".",
"getUsername",
"(",
")",
";",
"}",
"return",
"(",
"(",
"ATUser",
")",
"authentication",
".",
"getPrincipal",
"(",
")",
")",
".",
"getUsername",
"(",
")",
";",
"}",
"}",
";",
"}"
] | creates a auditor provider
@param systemUser
@param anonymousUser
@return | [
"creates",
"a",
"auditor",
"provider"
] | 6d391e2d26969b70e3ccabfc34202abe8d915080 | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/auth/AdminToolSecDBBeans.java#L40-L62 |
2,081 | fernandospr/javapns-jdk16 | src/main/java/javapns/notification/PushedNotification.java | PushedNotification.findSuccessfulNotifications | public static List<PushedNotification> findSuccessfulNotifications(List<PushedNotification> notifications) {
List<PushedNotification> filteredList = new Vector<PushedNotification>();
for (PushedNotification notification : notifications) {
if (notification.isSuccessful()) filteredList.add(notification);
}
return filteredList;
} | java | public static List<PushedNotification> findSuccessfulNotifications(List<PushedNotification> notifications) {
List<PushedNotification> filteredList = new Vector<PushedNotification>();
for (PushedNotification notification : notifications) {
if (notification.isSuccessful()) filteredList.add(notification);
}
return filteredList;
} | [
"public",
"static",
"List",
"<",
"PushedNotification",
">",
"findSuccessfulNotifications",
"(",
"List",
"<",
"PushedNotification",
">",
"notifications",
")",
"{",
"List",
"<",
"PushedNotification",
">",
"filteredList",
"=",
"new",
"Vector",
"<",
"PushedNotification",
">",
"(",
")",
";",
"for",
"(",
"PushedNotification",
"notification",
":",
"notifications",
")",
"{",
"if",
"(",
"notification",
".",
"isSuccessful",
"(",
")",
")",
"filteredList",
".",
"add",
"(",
"notification",
")",
";",
"}",
"return",
"filteredList",
";",
"}"
] | Filters a list of pushed notifications and returns only the ones that were successful.
@param notifications a list of pushed notifications
@return a filtered list containing only notifications that were succcessful | [
"Filters",
"a",
"list",
"of",
"pushed",
"notifications",
"and",
"returns",
"only",
"the",
"ones",
"that",
"were",
"successful",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/notification/PushedNotification.java#L217-L223 |
2,082 | fernandospr/javapns-jdk16 | src/main/java/javapns/Push.java | Push.alert | public static PushedNotifications alert(String message, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException {
return sendPayload(PushNotificationPayload.alert(message), keystore, password, production, devices);
} | java | public static PushedNotifications alert(String message, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException {
return sendPayload(PushNotificationPayload.alert(message), keystore, password, production, devices);
} | [
"public",
"static",
"PushedNotifications",
"alert",
"(",
"String",
"message",
",",
"Object",
"keystore",
",",
"String",
"password",
",",
"boolean",
"production",
",",
"Object",
"devices",
")",
"throws",
"CommunicationException",
",",
"KeystoreException",
"{",
"return",
"sendPayload",
"(",
"PushNotificationPayload",
".",
"alert",
"(",
"message",
")",
",",
"keystore",
",",
"password",
",",
"production",
",",
"devices",
")",
";",
"}"
] | Push a simple alert to one or more devices.
@param message the alert message to push.
@param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path)
@param password the keystore's password.
@param production true to use Apple's production servers, false to use the sandbox servers.
@param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device}
@return a list of pushed notifications, each with details on transmission results and error (if any)
@throws KeystoreException thrown if an error occurs when loading the keystore
@throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers | [
"Push",
"a",
"simple",
"alert",
"to",
"one",
"or",
"more",
"devices",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/Push.java#L46-L48 |
2,083 | fernandospr/javapns-jdk16 | src/main/java/javapns/Push.java | Push.sound | public static PushedNotifications sound(String sound, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException {
return sendPayload(PushNotificationPayload.sound(sound), keystore, password, production, devices);
} | java | public static PushedNotifications sound(String sound, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException {
return sendPayload(PushNotificationPayload.sound(sound), keystore, password, production, devices);
} | [
"public",
"static",
"PushedNotifications",
"sound",
"(",
"String",
"sound",
",",
"Object",
"keystore",
",",
"String",
"password",
",",
"boolean",
"production",
",",
"Object",
"devices",
")",
"throws",
"CommunicationException",
",",
"KeystoreException",
"{",
"return",
"sendPayload",
"(",
"PushNotificationPayload",
".",
"sound",
"(",
"sound",
")",
",",
"keystore",
",",
"password",
",",
"production",
",",
"devices",
")",
";",
"}"
] | Push a simple sound name to one or more devices.
@param sound the sound name (stored in the client app) to push.
@param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path)
@param password the keystore's password.
@param production true to use Apple's production servers, false to use the sandbox servers.
@param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device}
@return a list of pushed notifications, each with details on transmission results and error (if any)
@throws KeystoreException thrown if an error occurs when loading the keystore
@throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers | [
"Push",
"a",
"simple",
"sound",
"name",
"to",
"one",
"or",
"more",
"devices",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/Push.java#L80-L82 |
2,084 | fernandospr/javapns-jdk16 | src/main/java/javapns/Push.java | Push.combined | public static PushedNotifications combined(String message, int badge, String sound, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException {
return sendPayload(PushNotificationPayload.combined(message, badge, sound), keystore, password, production, devices);
} | java | public static PushedNotifications combined(String message, int badge, String sound, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException {
return sendPayload(PushNotificationPayload.combined(message, badge, sound), keystore, password, production, devices);
} | [
"public",
"static",
"PushedNotifications",
"combined",
"(",
"String",
"message",
",",
"int",
"badge",
",",
"String",
"sound",
",",
"Object",
"keystore",
",",
"String",
"password",
",",
"boolean",
"production",
",",
"Object",
"devices",
")",
"throws",
"CommunicationException",
",",
"KeystoreException",
"{",
"return",
"sendPayload",
"(",
"PushNotificationPayload",
".",
"combined",
"(",
"message",
",",
"badge",
",",
"sound",
")",
",",
"keystore",
",",
"password",
",",
"production",
",",
"devices",
")",
";",
"}"
] | Push a notification combining an alert, a badge and a sound.
@param message the alert message to push (set to null to skip).
@param badge the badge number to push (set to -1 to skip).
@param sound the sound name to push (set to null to skip).
@param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path)
@param password the keystore's password.
@param production true to use Apple's production servers, false to use the sandbox servers.
@param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device}
@return a list of pushed notifications, each with details on transmission results and error (if any)
@throws KeystoreException thrown if an error occurs when loading the keystore
@throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers | [
"Push",
"a",
"notification",
"combining",
"an",
"alert",
"a",
"badge",
"and",
"a",
"sound",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/Push.java#L99-L101 |
2,085 | fernandospr/javapns-jdk16 | src/main/java/javapns/Push.java | Push.contentAvailable | public static PushedNotifications contentAvailable(Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException {
return sendPayload(NewsstandNotificationPayload.contentAvailable(), keystore, password, production, devices);
} | java | public static PushedNotifications contentAvailable(Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException {
return sendPayload(NewsstandNotificationPayload.contentAvailable(), keystore, password, production, devices);
} | [
"public",
"static",
"PushedNotifications",
"contentAvailable",
"(",
"Object",
"keystore",
",",
"String",
"password",
",",
"boolean",
"production",
",",
"Object",
"devices",
")",
"throws",
"CommunicationException",
",",
"KeystoreException",
"{",
"return",
"sendPayload",
"(",
"NewsstandNotificationPayload",
".",
"contentAvailable",
"(",
")",
",",
"keystore",
",",
"password",
",",
"production",
",",
"devices",
")",
";",
"}"
] | Push a content-available notification for Newsstand.
@param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path)
@param password the keystore's password.
@param production true to use Apple's production servers, false to use the sandbox servers.
@param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device}
@return a list of pushed notifications, each with details on transmission results and error (if any)
@throws KeystoreException thrown if an error occurs when loading the keystore
@throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers | [
"Push",
"a",
"content",
"-",
"available",
"notification",
"for",
"Newsstand",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/Push.java#L115-L117 |
2,086 | fernandospr/javapns-jdk16 | src/main/java/javapns/notification/NewsstandNotificationPayload.java | NewsstandNotificationPayload.contentAvailable | public static NewsstandNotificationPayload contentAvailable() {
NewsstandNotificationPayload payload = complex();
try {
payload.addContentAvailable();
} catch (JSONException e) {
}
return payload;
} | java | public static NewsstandNotificationPayload contentAvailable() {
NewsstandNotificationPayload payload = complex();
try {
payload.addContentAvailable();
} catch (JSONException e) {
}
return payload;
} | [
"public",
"static",
"NewsstandNotificationPayload",
"contentAvailable",
"(",
")",
"{",
"NewsstandNotificationPayload",
"payload",
"=",
"complex",
"(",
")",
";",
"try",
"{",
"payload",
".",
"addContentAvailable",
"(",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"}",
"return",
"payload",
";",
"}"
] | Create a pre-defined payload with a content-available property set to 1.
@return a ready-to-send newsstand payload | [
"Create",
"a",
"pre",
"-",
"defined",
"payload",
"with",
"a",
"content",
"-",
"available",
"property",
"set",
"to",
"1",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/notification/NewsstandNotificationPayload.java#L17-L24 |
2,087 | fernandospr/javapns-jdk16 | src/main/java/javapns/communication/ConnectionToAppleServer.java | ConnectionToAppleServer.createSSLSocketFactoryWithTrustManagers | protected SSLSocketFactory createSSLSocketFactoryWithTrustManagers(TrustManager[] trustManagers) throws KeystoreException {
logger.debug("Creating SSLSocketFactory");
// Get a KeyManager and initialize it
try {
KeyStore keystore = getKeystore();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(ALGORITHM);
try {
char[] password = KeystoreManager.getKeystorePasswordForSSL(server);
kmf.init(keystore, password);
} catch (Exception e) {
e = KeystoreManager.wrapKeystoreException(e);
throw e;
}
// Get the SSLContext to help create SSLSocketFactory
SSLContext sslc = SSLContext.getInstance(PROTOCOL);
sslc.init(kmf.getKeyManagers(), trustManagers, null);
return sslc.getSocketFactory();
} catch (Exception e) {
throw new KeystoreException("Keystore exception: " + e.getMessage(), e);
}
} | java | protected SSLSocketFactory createSSLSocketFactoryWithTrustManagers(TrustManager[] trustManagers) throws KeystoreException {
logger.debug("Creating SSLSocketFactory");
// Get a KeyManager and initialize it
try {
KeyStore keystore = getKeystore();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(ALGORITHM);
try {
char[] password = KeystoreManager.getKeystorePasswordForSSL(server);
kmf.init(keystore, password);
} catch (Exception e) {
e = KeystoreManager.wrapKeystoreException(e);
throw e;
}
// Get the SSLContext to help create SSLSocketFactory
SSLContext sslc = SSLContext.getInstance(PROTOCOL);
sslc.init(kmf.getKeyManagers(), trustManagers, null);
return sslc.getSocketFactory();
} catch (Exception e) {
throw new KeystoreException("Keystore exception: " + e.getMessage(), e);
}
} | [
"protected",
"SSLSocketFactory",
"createSSLSocketFactoryWithTrustManagers",
"(",
"TrustManager",
"[",
"]",
"trustManagers",
")",
"throws",
"KeystoreException",
"{",
"logger",
".",
"debug",
"(",
"\"Creating SSLSocketFactory\"",
")",
";",
"// Get a KeyManager and initialize it ",
"try",
"{",
"KeyStore",
"keystore",
"=",
"getKeystore",
"(",
")",
";",
"KeyManagerFactory",
"kmf",
"=",
"KeyManagerFactory",
".",
"getInstance",
"(",
"ALGORITHM",
")",
";",
"try",
"{",
"char",
"[",
"]",
"password",
"=",
"KeystoreManager",
".",
"getKeystorePasswordForSSL",
"(",
"server",
")",
";",
"kmf",
".",
"init",
"(",
"keystore",
",",
"password",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
"=",
"KeystoreManager",
".",
"wrapKeystoreException",
"(",
"e",
")",
";",
"throw",
"e",
";",
"}",
"// Get the SSLContext to help create SSLSocketFactory\t\t\t",
"SSLContext",
"sslc",
"=",
"SSLContext",
".",
"getInstance",
"(",
"PROTOCOL",
")",
";",
"sslc",
".",
"init",
"(",
"kmf",
".",
"getKeyManagers",
"(",
")",
",",
"trustManagers",
",",
"null",
")",
";",
"return",
"sslc",
".",
"getSocketFactory",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"KeystoreException",
"(",
"\"Keystore exception: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] | Generic SSLSocketFactory builder
@param trustManagers
@return SSLSocketFactory
@throws KeystoreException | [
"Generic",
"SSLSocketFactory",
"builder"
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/ConnectionToAppleServer.java#L90-L113 |
2,088 | fernandospr/javapns-jdk16 | src/main/java/javapns/communication/ConnectionToAppleServer.java | ConnectionToAppleServer.getSSLSocket | public SSLSocket getSSLSocket() throws KeystoreException, CommunicationException {
SSLSocketFactory socketFactory = getSSLSocketFactory();
logger.debug("Creating SSLSocket to " + getServerHost() + ":" + getServerPort());
try {
if (ProxyManager.isUsingProxy(server)) {
return tunnelThroughProxy(socketFactory);
} else {
return (SSLSocket) socketFactory.createSocket(getServerHost(), getServerPort());
}
} catch (Exception e) {
throw new CommunicationException("Communication exception: " + e, e);
}
} | java | public SSLSocket getSSLSocket() throws KeystoreException, CommunicationException {
SSLSocketFactory socketFactory = getSSLSocketFactory();
logger.debug("Creating SSLSocket to " + getServerHost() + ":" + getServerPort());
try {
if (ProxyManager.isUsingProxy(server)) {
return tunnelThroughProxy(socketFactory);
} else {
return (SSLSocket) socketFactory.createSocket(getServerHost(), getServerPort());
}
} catch (Exception e) {
throw new CommunicationException("Communication exception: " + e, e);
}
} | [
"public",
"SSLSocket",
"getSSLSocket",
"(",
")",
"throws",
"KeystoreException",
",",
"CommunicationException",
"{",
"SSLSocketFactory",
"socketFactory",
"=",
"getSSLSocketFactory",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"\"Creating SSLSocket to \"",
"+",
"getServerHost",
"(",
")",
"+",
"\":\"",
"+",
"getServerPort",
"(",
")",
")",
";",
"try",
"{",
"if",
"(",
"ProxyManager",
".",
"isUsingProxy",
"(",
"server",
")",
")",
"{",
"return",
"tunnelThroughProxy",
"(",
"socketFactory",
")",
";",
"}",
"else",
"{",
"return",
"(",
"SSLSocket",
")",
"socketFactory",
".",
"createSocket",
"(",
"getServerHost",
"(",
")",
",",
"getServerPort",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"CommunicationException",
"(",
"\"Communication exception: \"",
"+",
"e",
",",
"e",
")",
";",
"}",
"}"
] | Create a SSLSocket which will be used to send data to Apple
@return the SSLSocket
@throws KeystoreException
@throws CommunicationException | [
"Create",
"a",
"SSLSocket",
"which",
"will",
"be",
"used",
"to",
"send",
"data",
"to",
"Apple"
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/ConnectionToAppleServer.java#L145-L158 |
2,089 | fernandospr/javapns-jdk16 | src/main/java/javapns/communication/ProxyManager.java | ProxyManager.setProxy | public static void setProxy(String host, String port) {
System.setProperty(LOCAL_PROXY_HOST_PROPERTY, host);
System.setProperty(LOCAL_PROXY_PORT_PROPERTY, port);
} | java | public static void setProxy(String host, String port) {
System.setProperty(LOCAL_PROXY_HOST_PROPERTY, host);
System.setProperty(LOCAL_PROXY_PORT_PROPERTY, port);
} | [
"public",
"static",
"void",
"setProxy",
"(",
"String",
"host",
",",
"String",
"port",
")",
"{",
"System",
".",
"setProperty",
"(",
"LOCAL_PROXY_HOST_PROPERTY",
",",
"host",
")",
";",
"System",
".",
"setProperty",
"(",
"LOCAL_PROXY_PORT_PROPERTY",
",",
"port",
")",
";",
"}"
] | Configure a proxy to use for HTTPS connections created by JavaPNS.
@param host the proxyHost
@param port the proxyPort | [
"Configure",
"a",
"proxy",
"to",
"use",
"for",
"HTTPS",
"connections",
"created",
"by",
"JavaPNS",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/ProxyManager.java#L27-L30 |
2,090 | fernandospr/javapns-jdk16 | src/main/java/javapns/communication/ProxyManager.java | ProxyManager.getProxyHost | public static String getProxyHost(AppleServer server) {
String host = server != null ? server.getProxyHost() : null;
if (host != null && host.length() > 0) {
return host;
} else {
host = System.getProperty(LOCAL_PROXY_HOST_PROPERTY);
if (host != null && host.length() > 0) {
return host;
} else {
host = System.getProperty(JVM_PROXY_HOST_PROPERTY);
if (host != null && host.length() > 0) {
return host;
} else {
return null;
}
}
}
} | java | public static String getProxyHost(AppleServer server) {
String host = server != null ? server.getProxyHost() : null;
if (host != null && host.length() > 0) {
return host;
} else {
host = System.getProperty(LOCAL_PROXY_HOST_PROPERTY);
if (host != null && host.length() > 0) {
return host;
} else {
host = System.getProperty(JVM_PROXY_HOST_PROPERTY);
if (host != null && host.length() > 0) {
return host;
} else {
return null;
}
}
}
} | [
"public",
"static",
"String",
"getProxyHost",
"(",
"AppleServer",
"server",
")",
"{",
"String",
"host",
"=",
"server",
"!=",
"null",
"?",
"server",
".",
"getProxyHost",
"(",
")",
":",
"null",
";",
"if",
"(",
"host",
"!=",
"null",
"&&",
"host",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return",
"host",
";",
"}",
"else",
"{",
"host",
"=",
"System",
".",
"getProperty",
"(",
"LOCAL_PROXY_HOST_PROPERTY",
")",
";",
"if",
"(",
"host",
"!=",
"null",
"&&",
"host",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return",
"host",
";",
"}",
"else",
"{",
"host",
"=",
"System",
".",
"getProperty",
"(",
"JVM_PROXY_HOST_PROPERTY",
")",
";",
"if",
"(",
"host",
"!=",
"null",
"&&",
"host",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return",
"host",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"}",
"}"
] | Get the proxy host address currently configured.
This method checks if a server-specific proxy has been configured,
then checks if a proxy has been configured for the entire library,
and finally checks if a JVM-wide proxy setting is available for HTTPS.
@param server a specific server to check for proxy settings (may be null)
@return a proxy host, or null if none is configured | [
"Get",
"the",
"proxy",
"host",
"address",
"currently",
"configured",
".",
"This",
"method",
"checks",
"if",
"a",
"server",
"-",
"specific",
"proxy",
"has",
"been",
"configured",
"then",
"checks",
"if",
"a",
"proxy",
"has",
"been",
"configured",
"for",
"the",
"entire",
"library",
"and",
"finally",
"checks",
"if",
"a",
"JVM",
"-",
"wide",
"proxy",
"setting",
"is",
"available",
"for",
"HTTPS",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/ProxyManager.java#L53-L70 |
2,091 | fernandospr/javapns-jdk16 | src/main/java/javapns/communication/ProxyManager.java | ProxyManager.getProxyPort | public static int getProxyPort(AppleServer server) {
String host = server != null ? server.getProxyHost() : null;
if (host != null && host.length() > 0) {
return server.getProxyPort();
} else {
host = System.getProperty(LOCAL_PROXY_HOST_PROPERTY);
if (host != null && host.length() > 0) {
return Integer.parseInt(System.getProperty(LOCAL_PROXY_PORT_PROPERTY));
} else {
host = System.getProperty(JVM_PROXY_HOST_PROPERTY);
if (host != null && host.length() > 0) {
return Integer.parseInt(System.getProperty(JVM_PROXY_PORT_PROPERTY));
} else {
return 0;
}
}
}
} | java | public static int getProxyPort(AppleServer server) {
String host = server != null ? server.getProxyHost() : null;
if (host != null && host.length() > 0) {
return server.getProxyPort();
} else {
host = System.getProperty(LOCAL_PROXY_HOST_PROPERTY);
if (host != null && host.length() > 0) {
return Integer.parseInt(System.getProperty(LOCAL_PROXY_PORT_PROPERTY));
} else {
host = System.getProperty(JVM_PROXY_HOST_PROPERTY);
if (host != null && host.length() > 0) {
return Integer.parseInt(System.getProperty(JVM_PROXY_PORT_PROPERTY));
} else {
return 0;
}
}
}
} | [
"public",
"static",
"int",
"getProxyPort",
"(",
"AppleServer",
"server",
")",
"{",
"String",
"host",
"=",
"server",
"!=",
"null",
"?",
"server",
".",
"getProxyHost",
"(",
")",
":",
"null",
";",
"if",
"(",
"host",
"!=",
"null",
"&&",
"host",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return",
"server",
".",
"getProxyPort",
"(",
")",
";",
"}",
"else",
"{",
"host",
"=",
"System",
".",
"getProperty",
"(",
"LOCAL_PROXY_HOST_PROPERTY",
")",
";",
"if",
"(",
"host",
"!=",
"null",
"&&",
"host",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"System",
".",
"getProperty",
"(",
"LOCAL_PROXY_PORT_PROPERTY",
")",
")",
";",
"}",
"else",
"{",
"host",
"=",
"System",
".",
"getProperty",
"(",
"JVM_PROXY_HOST_PROPERTY",
")",
";",
"if",
"(",
"host",
"!=",
"null",
"&&",
"host",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"System",
".",
"getProperty",
"(",
"JVM_PROXY_PORT_PROPERTY",
")",
")",
";",
"}",
"else",
"{",
"return",
"0",
";",
"}",
"}",
"}",
"}"
] | Get the proxy port currently configured.
This method first locates a proxy host setting, then returns the proxy port from the same location.
@param server a specific server to check for proxy settings (may be null)
@return a network port, or 0 if no proxy is configured | [
"Get",
"the",
"proxy",
"port",
"currently",
"configured",
".",
"This",
"method",
"first",
"locates",
"a",
"proxy",
"host",
"setting",
"then",
"returns",
"the",
"proxy",
"port",
"from",
"the",
"same",
"location",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/ProxyManager.java#L79-L96 |
2,092 | fernandospr/javapns-jdk16 | src/main/java/javapns/communication/ProxyManager.java | ProxyManager.isUsingProxy | public static boolean isUsingProxy(AppleServer server) {
String proxyHost = getProxyHost(server);
boolean proxyConfigured = proxyHost != null && proxyHost.length() > 0;
return proxyConfigured;
} | java | public static boolean isUsingProxy(AppleServer server) {
String proxyHost = getProxyHost(server);
boolean proxyConfigured = proxyHost != null && proxyHost.length() > 0;
return proxyConfigured;
} | [
"public",
"static",
"boolean",
"isUsingProxy",
"(",
"AppleServer",
"server",
")",
"{",
"String",
"proxyHost",
"=",
"getProxyHost",
"(",
"server",
")",
";",
"boolean",
"proxyConfigured",
"=",
"proxyHost",
"!=",
"null",
"&&",
"proxyHost",
".",
"length",
"(",
")",
">",
"0",
";",
"return",
"proxyConfigured",
";",
"}"
] | Determine if a proxy is currently configured.
@param server a specific server to check for proxy settings (may be null)
@return true if a proxy is set, false otherwise | [
"Determine",
"if",
"a",
"proxy",
"is",
"currently",
"configured",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/ProxyManager.java#L104-L108 |
2,093 | fernandospr/javapns-jdk16 | src/main/java/org/json/XMLTokener.java | XMLTokener.nextCDATA | public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (c == 0) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
} | java | public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (c == 0) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
} | [
"public",
"String",
"nextCDATA",
"(",
")",
"throws",
"JSONException",
"{",
"char",
"c",
";",
"int",
"i",
";",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"for",
"(",
";",
";",
")",
"{",
"c",
"=",
"next",
"(",
")",
";",
"if",
"(",
"c",
"==",
"0",
")",
"{",
"throw",
"syntaxError",
"(",
"\"Unclosed CDATA\"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"c",
")",
";",
"i",
"=",
"sb",
".",
"length",
"(",
")",
"-",
"3",
";",
"if",
"(",
"i",
">=",
"0",
"&&",
"sb",
".",
"charAt",
"(",
"i",
")",
"==",
"'",
"'",
"&&",
"sb",
".",
"charAt",
"(",
"i",
"+",
"1",
")",
"==",
"'",
"'",
"&&",
"sb",
".",
"charAt",
"(",
"i",
"+",
"2",
")",
"==",
"'",
"'",
")",
"{",
"sb",
".",
"setLength",
"(",
"i",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"}",
"}"
] | Get the text in the CDATA block.
@return The string up to the <code>]]></code>.
@throws JSONException If the <code>]]></code> is not found. | [
"Get",
"the",
"text",
"in",
"the",
"CDATA",
"block",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/org/json/XMLTokener.java#L64-L81 |
2,094 | fernandospr/javapns-jdk16 | src/main/java/javapns/notification/PushedNotifications.java | PushedNotifications.getSuccessfulNotifications | public PushedNotifications getSuccessfulNotifications() {
PushedNotifications filteredList = new PushedNotifications(this);
for (PushedNotification notification : this) {
if (notification.isSuccessful()) filteredList.add(notification);
}
return filteredList;
} | java | public PushedNotifications getSuccessfulNotifications() {
PushedNotifications filteredList = new PushedNotifications(this);
for (PushedNotification notification : this) {
if (notification.isSuccessful()) filteredList.add(notification);
}
return filteredList;
} | [
"public",
"PushedNotifications",
"getSuccessfulNotifications",
"(",
")",
"{",
"PushedNotifications",
"filteredList",
"=",
"new",
"PushedNotifications",
"(",
"this",
")",
";",
"for",
"(",
"PushedNotification",
"notification",
":",
"this",
")",
"{",
"if",
"(",
"notification",
".",
"isSuccessful",
"(",
")",
")",
"filteredList",
".",
"add",
"(",
"notification",
")",
";",
"}",
"return",
"filteredList",
";",
"}"
] | Filter a list of pushed notifications and return only the ones that were successful.
@return a filtered list containing only notifications that were succcessful | [
"Filter",
"a",
"list",
"of",
"pushed",
"notifications",
"and",
"return",
"only",
"the",
"ones",
"that",
"were",
"successful",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/notification/PushedNotifications.java#L53-L59 |
2,095 | fernandospr/javapns-jdk16 | src/main/java/javapns/notification/PushedNotifications.java | PushedNotifications.getFailedNotifications | public PushedNotifications getFailedNotifications() {
PushedNotifications filteredList = new PushedNotifications(this);
for (PushedNotification notification : this) {
if (!notification.isSuccessful()) {
filteredList.add(notification);
}
}
return filteredList;
} | java | public PushedNotifications getFailedNotifications() {
PushedNotifications filteredList = new PushedNotifications(this);
for (PushedNotification notification : this) {
if (!notification.isSuccessful()) {
filteredList.add(notification);
}
}
return filteredList;
} | [
"public",
"PushedNotifications",
"getFailedNotifications",
"(",
")",
"{",
"PushedNotifications",
"filteredList",
"=",
"new",
"PushedNotifications",
"(",
"this",
")",
";",
"for",
"(",
"PushedNotification",
"notification",
":",
"this",
")",
"{",
"if",
"(",
"!",
"notification",
".",
"isSuccessful",
"(",
")",
")",
"{",
"filteredList",
".",
"add",
"(",
"notification",
")",
";",
"}",
"}",
"return",
"filteredList",
";",
"}"
] | Filter a list of pushed notifications and return only the ones that failed.
@return a filtered list containing only notifications that were <b>not</b> successful | [
"Filter",
"a",
"list",
"of",
"pushed",
"notifications",
"and",
"return",
"only",
"the",
"ones",
"that",
"failed",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/notification/PushedNotifications.java#L67-L75 |
2,096 | fernandospr/javapns-jdk16 | src/main/java/javapns/devices/implementations/basic/BasicDeviceFactory.java | BasicDeviceFactory.addDevice | public Device addDevice(String id, String token) throws DuplicateDeviceException, NullIdException, NullDeviceTokenException, Exception {
if ((id == null) || (id.trim().equals(""))) {
throw new NullIdException();
} else if ((token == null) || (token.trim().equals(""))) {
throw new NullDeviceTokenException();
} else {
if (!this.devices.containsKey(id)) {
token = token.trim().replace(" ", "");
BasicDevice device = new BasicDevice(id, token, new Timestamp(Calendar.getInstance().getTime().getTime()));
this.devices.put(id, device);
return device;
} else {
throw new DuplicateDeviceException();
}
}
} | java | public Device addDevice(String id, String token) throws DuplicateDeviceException, NullIdException, NullDeviceTokenException, Exception {
if ((id == null) || (id.trim().equals(""))) {
throw new NullIdException();
} else if ((token == null) || (token.trim().equals(""))) {
throw new NullDeviceTokenException();
} else {
if (!this.devices.containsKey(id)) {
token = token.trim().replace(" ", "");
BasicDevice device = new BasicDevice(id, token, new Timestamp(Calendar.getInstance().getTime().getTime()));
this.devices.put(id, device);
return device;
} else {
throw new DuplicateDeviceException();
}
}
} | [
"public",
"Device",
"addDevice",
"(",
"String",
"id",
",",
"String",
"token",
")",
"throws",
"DuplicateDeviceException",
",",
"NullIdException",
",",
"NullDeviceTokenException",
",",
"Exception",
"{",
"if",
"(",
"(",
"id",
"==",
"null",
")",
"||",
"(",
"id",
".",
"trim",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
")",
"{",
"throw",
"new",
"NullIdException",
"(",
")",
";",
"}",
"else",
"if",
"(",
"(",
"token",
"==",
"null",
")",
"||",
"(",
"token",
".",
"trim",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
")",
"{",
"throw",
"new",
"NullDeviceTokenException",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"this",
".",
"devices",
".",
"containsKey",
"(",
"id",
")",
")",
"{",
"token",
"=",
"token",
".",
"trim",
"(",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
";",
"BasicDevice",
"device",
"=",
"new",
"BasicDevice",
"(",
"id",
",",
"token",
",",
"new",
"Timestamp",
"(",
"Calendar",
".",
"getInstance",
"(",
")",
".",
"getTime",
"(",
")",
".",
"getTime",
"(",
")",
")",
")",
";",
"this",
".",
"devices",
".",
"put",
"(",
"id",
",",
"device",
")",
";",
"return",
"device",
";",
"}",
"else",
"{",
"throw",
"new",
"DuplicateDeviceException",
"(",
")",
";",
"}",
"}",
"}"
] | Add a device to the map
@param id The device id
@param token The device token
@throws DuplicateDeviceException
@throws NullIdException
@throws NullDeviceTokenException | [
"Add",
"a",
"device",
"to",
"the",
"map"
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/devices/implementations/basic/BasicDeviceFactory.java#L47-L62 |
2,097 | fernandospr/javapns-jdk16 | src/main/java/javapns/devices/implementations/basic/BasicDeviceFactory.java | BasicDeviceFactory.getDevice | public Device getDevice(String id) throws UnknownDeviceException, NullIdException {
if ((id == null) || (id.trim().equals(""))) {
throw new NullIdException();
} else {
if (this.devices.containsKey(id)) {
return this.devices.get(id);
} else {
throw new UnknownDeviceException();
}
}
} | java | public Device getDevice(String id) throws UnknownDeviceException, NullIdException {
if ((id == null) || (id.trim().equals(""))) {
throw new NullIdException();
} else {
if (this.devices.containsKey(id)) {
return this.devices.get(id);
} else {
throw new UnknownDeviceException();
}
}
} | [
"public",
"Device",
"getDevice",
"(",
"String",
"id",
")",
"throws",
"UnknownDeviceException",
",",
"NullIdException",
"{",
"if",
"(",
"(",
"id",
"==",
"null",
")",
"||",
"(",
"id",
".",
"trim",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
")",
"{",
"throw",
"new",
"NullIdException",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"devices",
".",
"containsKey",
"(",
"id",
")",
")",
"{",
"return",
"this",
".",
"devices",
".",
"get",
"(",
"id",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"UnknownDeviceException",
"(",
")",
";",
"}",
"}",
"}"
] | Get a device according to his id
@param id The device id
@return The device
@throws UnknownDeviceException
@throws NullIdException | [
"Get",
"a",
"device",
"according",
"to",
"his",
"id"
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/devices/implementations/basic/BasicDeviceFactory.java#L72-L82 |
2,098 | fernandospr/javapns-jdk16 | src/main/java/javapns/devices/implementations/basic/BasicDeviceFactory.java | BasicDeviceFactory.removeDevice | public void removeDevice(String id) throws UnknownDeviceException, NullIdException {
if ((id == null) || (id.trim().equals(""))) {
throw new NullIdException();
}
if (this.devices.containsKey(id)) {
this.devices.remove(id);
} else {
throw new UnknownDeviceException();
}
} | java | public void removeDevice(String id) throws UnknownDeviceException, NullIdException {
if ((id == null) || (id.trim().equals(""))) {
throw new NullIdException();
}
if (this.devices.containsKey(id)) {
this.devices.remove(id);
} else {
throw new UnknownDeviceException();
}
} | [
"public",
"void",
"removeDevice",
"(",
"String",
"id",
")",
"throws",
"UnknownDeviceException",
",",
"NullIdException",
"{",
"if",
"(",
"(",
"id",
"==",
"null",
")",
"||",
"(",
"id",
".",
"trim",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
")",
"{",
"throw",
"new",
"NullIdException",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"devices",
".",
"containsKey",
"(",
"id",
")",
")",
"{",
"this",
".",
"devices",
".",
"remove",
"(",
"id",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"UnknownDeviceException",
"(",
")",
";",
"}",
"}"
] | Remove a device
@param id The device id
@throws UnknownDeviceException
@throws NullIdException | [
"Remove",
"a",
"device"
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/devices/implementations/basic/BasicDeviceFactory.java#L91-L100 |
2,099 | fernandospr/javapns-jdk16 | src/main/java/javapns/communication/KeystoreManager.java | KeystoreManager.ensureReusableKeystore | static Object ensureReusableKeystore(AppleServer server, Object keystore) throws KeystoreException {
if (keystore instanceof InputStream) keystore = loadKeystore(server, keystore, false);
return keystore;
} | java | static Object ensureReusableKeystore(AppleServer server, Object keystore) throws KeystoreException {
if (keystore instanceof InputStream) keystore = loadKeystore(server, keystore, false);
return keystore;
} | [
"static",
"Object",
"ensureReusableKeystore",
"(",
"AppleServer",
"server",
",",
"Object",
"keystore",
")",
"throws",
"KeystoreException",
"{",
"if",
"(",
"keystore",
"instanceof",
"InputStream",
")",
"keystore",
"=",
"loadKeystore",
"(",
"server",
",",
"keystore",
",",
"false",
")",
";",
"return",
"keystore",
";",
"}"
] | Make sure that the provided keystore will be reusable.
@param server the server the keystore is intended for
@param keystore a keystore containing your private key and the certificate signed by Apple (File, InputStream, byte[], KeyStore or String for a file path)
@return a reusable keystore
@throws KeystoreException | [
"Make",
"sure",
"that",
"the",
"provided",
"keystore",
"will",
"be",
"reusable",
"."
] | 84de6d9328ab01af92f77cc60c4554de02420909 | https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/KeystoreManager.java#L86-L89 |
Subsets and Splits