repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
dita-ot/dita-ot | src/main/java/org/dita/dost/reader/MapMetaReader.java | MapMetaReader.read | @Override
public void read(final File filename) {
filePath = filename;
//clear the history on global metadata table
globalMeta.clear();
super.read(filename);
} | java | @Override
public void read(final File filename) {
filePath = filename;
//clear the history on global metadata table
globalMeta.clear();
super.read(filename);
} | [
"@",
"Override",
"public",
"void",
"read",
"(",
"final",
"File",
"filename",
")",
"{",
"filePath",
"=",
"filename",
";",
"//clear the history on global metadata table",
"globalMeta",
".",
"clear",
"(",
")",
";",
"super",
".",
"read",
"(",
"filename",
")",
";",... | read map files.
@param filename filename | [
"read",
"map",
"files",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/reader/MapMetaReader.java#L124-L131 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/reader/MapMetaReader.java | MapMetaReader.removeIndexTermRecursive | private void removeIndexTermRecursive(final Element parent) {
if (parent == null) {
return;
}
final NodeList children = parent.getChildNodes();
Element child;
for (int i = children.getLength() - 1; i >= 0; i--) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
child = (Element) children.item(i);
final boolean isIndexTerm = TOPIC_INDEXTERM.matches(child);
final boolean hasStart = !child.getAttribute(ATTRIBUTE_NAME_START).isEmpty();
final boolean hasEnd = !child.getAttribute(ATTRIBUTE_NAME_END).isEmpty();
if (isIndexTerm && (hasStart || hasEnd)) {
parent.removeChild(child);
} else {
removeIndexTermRecursive(child);
}
}
}
} | java | private void removeIndexTermRecursive(final Element parent) {
if (parent == null) {
return;
}
final NodeList children = parent.getChildNodes();
Element child;
for (int i = children.getLength() - 1; i >= 0; i--) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
child = (Element) children.item(i);
final boolean isIndexTerm = TOPIC_INDEXTERM.matches(child);
final boolean hasStart = !child.getAttribute(ATTRIBUTE_NAME_START).isEmpty();
final boolean hasEnd = !child.getAttribute(ATTRIBUTE_NAME_END).isEmpty();
if (isIndexTerm && (hasStart || hasEnd)) {
parent.removeChild(child);
} else {
removeIndexTermRecursive(child);
}
}
}
} | [
"private",
"void",
"removeIndexTermRecursive",
"(",
"final",
"Element",
"parent",
")",
"{",
"if",
"(",
"parent",
"==",
"null",
")",
"{",
"return",
";",
"}",
"final",
"NodeList",
"children",
"=",
"parent",
".",
"getChildNodes",
"(",
")",
";",
"Element",
"ch... | traverse the node tree and remove all indexterm elements with either start or
end attribute.
@param parent root element | [
"traverse",
"the",
"node",
"tree",
"and",
"remove",
"all",
"indexterm",
"elements",
"with",
"either",
"start",
"or",
"end",
"attribute",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/reader/MapMetaReader.java#L171-L190 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/reader/MapMetaReader.java | MapMetaReader.cloneElementMap | private Map<String, Element> cloneElementMap(final Map<String, Element> current) {
final Map<String, Element> topicMetaTable = new HashMap<>(16);
for (final Entry<String, Element> topicMetaItem: current.entrySet()) {
topicMetaTable.put(topicMetaItem.getKey(), (Element) resultDoc.importNode(topicMetaItem.getValue(), true));
}
return topicMetaTable;
} | java | private Map<String, Element> cloneElementMap(final Map<String, Element> current) {
final Map<String, Element> topicMetaTable = new HashMap<>(16);
for (final Entry<String, Element> topicMetaItem: current.entrySet()) {
topicMetaTable.put(topicMetaItem.getKey(), (Element) resultDoc.importNode(topicMetaItem.getValue(), true));
}
return topicMetaTable;
} | [
"private",
"Map",
"<",
"String",
",",
"Element",
">",
"cloneElementMap",
"(",
"final",
"Map",
"<",
"String",
",",
"Element",
">",
"current",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Element",
">",
"topicMetaTable",
"=",
"new",
"HashMap",
"<>",
"(",... | Clone metadata map.
@param current metadata map to clone
@return a clone of the original map | [
"Clone",
"metadata",
"map",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/reader/MapMetaReader.java#L276-L282 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/Processor.java | Processor.setProperty | public Processor setProperty(final String name, final String value) {
args.put(name, value);
return this;
} | java | public Processor setProperty(final String name, final String value) {
args.put(name, value);
return this;
} | [
"public",
"Processor",
"setProperty",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"value",
")",
"{",
"args",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Set property. Existing property mapping will be overridden.
@param name property name
@param value property value
@return this Process object | [
"Set",
"property",
".",
"Existing",
"property",
"mapping",
"will",
"be",
"overridden",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/Processor.java#L113-L116 | train |
dita-ot/dita-ot | src/main/plugins/org.dita.htmlhelp/src/main/java/org/dita/dost/writer/CHMIndexWriter.java | CHMIndexWriter.findTargets | private void findTargets(final IndexTerm term) {
final List<IndexTerm> subTerms = term.getSubTerms();
List<IndexTermTarget> subTargets = null;
if (subTerms != null && ! subTerms.isEmpty()){
for (final IndexTerm subTerm : subTerms) {
subTargets = subTerm.getTargetList();
if (subTargets != null && !subTargets.isEmpty()) {
//findTargets(subTerm);
//add targets(child term)
term.addTargets(subTerm.getTargetList());
} else {
//term.addTargets(subTerm.getTargetList());
//recursive search child's child term
findTargets(subTerm);
}
//add target to parent indexterm
term.addTargets(subTerm.getTargetList());
}
}
} | java | private void findTargets(final IndexTerm term) {
final List<IndexTerm> subTerms = term.getSubTerms();
List<IndexTermTarget> subTargets = null;
if (subTerms != null && ! subTerms.isEmpty()){
for (final IndexTerm subTerm : subTerms) {
subTargets = subTerm.getTargetList();
if (subTargets != null && !subTargets.isEmpty()) {
//findTargets(subTerm);
//add targets(child term)
term.addTargets(subTerm.getTargetList());
} else {
//term.addTargets(subTerm.getTargetList());
//recursive search child's child term
findTargets(subTerm);
}
//add target to parent indexterm
term.addTargets(subTerm.getTargetList());
}
}
} | [
"private",
"void",
"findTargets",
"(",
"final",
"IndexTerm",
"term",
")",
"{",
"final",
"List",
"<",
"IndexTerm",
">",
"subTerms",
"=",
"term",
".",
"getSubTerms",
"(",
")",
";",
"List",
"<",
"IndexTermTarget",
">",
"subTargets",
"=",
"null",
";",
"if",
... | find the targets in its subterms when the current term doesn't have any target
@param term The current IndexTerm instance | [
"find",
"the",
"targets",
"in",
"its",
"subterms",
"when",
"the",
"current",
"term",
"doesn",
"t",
"have",
"any",
"target"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/plugins/org.dita.htmlhelp/src/main/java/org/dita/dost/writer/CHMIndexWriter.java#L134-L154 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/ProcessorFactory.java | ProcessorFactory.setBaseTempDir | public void setBaseTempDir(final File tmp) {
if (!tmp.isAbsolute()) {
throw new IllegalArgumentException("Temporary directory must be absolute");
}
args.put("base.temp.dir", tmp.getAbsolutePath());
} | java | public void setBaseTempDir(final File tmp) {
if (!tmp.isAbsolute()) {
throw new IllegalArgumentException("Temporary directory must be absolute");
}
args.put("base.temp.dir", tmp.getAbsolutePath());
} | [
"public",
"void",
"setBaseTempDir",
"(",
"final",
"File",
"tmp",
")",
"{",
"if",
"(",
"!",
"tmp",
".",
"isAbsolute",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Temporary directory must be absolute\"",
")",
";",
"}",
"args",
".",
... | Set base directory for temporary directories.
@param tmp absolute directory for temporary directories | [
"Set",
"base",
"directory",
"for",
"temporary",
"directories",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/ProcessorFactory.java#L40-L45 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/ProcessorFactory.java | ProcessorFactory.newProcessor | public Processor newProcessor(final String transtype) {
if (ditaDir == null) {
throw new IllegalStateException();
}
if (!Configuration.transtypes.contains(transtype)) {
throw new IllegalArgumentException("Transtype " + transtype + " not supported");
}
return new Processor(ditaDir, transtype, Collections.unmodifiableMap(args));
} | java | public Processor newProcessor(final String transtype) {
if (ditaDir == null) {
throw new IllegalStateException();
}
if (!Configuration.transtypes.contains(transtype)) {
throw new IllegalArgumentException("Transtype " + transtype + " not supported");
}
return new Processor(ditaDir, transtype, Collections.unmodifiableMap(args));
} | [
"public",
"Processor",
"newProcessor",
"(",
"final",
"String",
"transtype",
")",
"{",
"if",
"(",
"ditaDir",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
")",
";",
"}",
"if",
"(",
"!",
"Configuration",
".",
"transtypes",
".",
"conta... | Create new Processor to run DITA-OT
@param transtype transtype for the processor
@return new Processor instance | [
"Create",
"new",
"Processor",
"to",
"run",
"DITA",
"-",
"OT"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/ProcessorFactory.java#L53-L61 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/platform/Plugins.java | Plugins.getInstalledPlugins | public static List<String> getInstalledPlugins() {
final List<Element> plugins = toList(getPluginConfiguration().getElementsByTagName("plugin"));
return plugins.stream()
.map((Element elem) -> elem.getAttributeNode("id"))
.filter(Objects::nonNull)
.map(Attr::getValue)
.sorted()
.collect(Collectors.toList());
} | java | public static List<String> getInstalledPlugins() {
final List<Element> plugins = toList(getPluginConfiguration().getElementsByTagName("plugin"));
return plugins.stream()
.map((Element elem) -> elem.getAttributeNode("id"))
.filter(Objects::nonNull)
.map(Attr::getValue)
.sorted()
.collect(Collectors.toList());
} | [
"public",
"static",
"List",
"<",
"String",
">",
"getInstalledPlugins",
"(",
")",
"{",
"final",
"List",
"<",
"Element",
">",
"plugins",
"=",
"toList",
"(",
"getPluginConfiguration",
"(",
")",
".",
"getElementsByTagName",
"(",
"\"plugin\"",
")",
")",
";",
"ret... | Read the list of installed plugins | [
"Read",
"the",
"list",
"of",
"installed",
"plugins"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/platform/Plugins.java#L32-L40 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/platform/Plugins.java | Plugins.getPluginConfiguration | public static Document getPluginConfiguration() {
try (final InputStream in = Plugins.class.getClassLoader().getResourceAsStream(PLUGIN_CONF)) {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
} catch (final ParserConfigurationException | SAXException | IOException e) {
throw new RuntimeException("Failed to read plugin configuration: " + e.getMessage(), e);
}
} | java | public static Document getPluginConfiguration() {
try (final InputStream in = Plugins.class.getClassLoader().getResourceAsStream(PLUGIN_CONF)) {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
} catch (final ParserConfigurationException | SAXException | IOException e) {
throw new RuntimeException("Failed to read plugin configuration: " + e.getMessage(), e);
}
} | [
"public",
"static",
"Document",
"getPluginConfiguration",
"(",
")",
"{",
"try",
"(",
"final",
"InputStream",
"in",
"=",
"Plugins",
".",
"class",
".",
"getClassLoader",
"(",
")",
".",
"getResourceAsStream",
"(",
"PLUGIN_CONF",
")",
")",
"{",
"return",
"Document... | Read plugin configuration | [
"Read",
"plugin",
"configuration"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/platform/Plugins.java#L45-L51 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/platform/Features.java | Features.addFeature | public final void addFeature(final String id, final Element elem) {
boolean isFile;
String value = elem.getAttribute("file");
if (!value.isEmpty()) {
isFile = true;
} else {
value = elem.getAttribute("value");
isFile = "file".equals(elem.getAttribute("type"));
}
final StringTokenizer valueTokenizer = new StringTokenizer(value, Integrator.FEAT_VALUE_SEPARATOR);
final List<String> valueBuffer = new ArrayList<>();
if (featureTable.containsKey(id)) {
valueBuffer.addAll(featureTable.get(id));
}
while (valueTokenizer.hasMoreElements()) {
final String valueElement = valueTokenizer.nextToken();
if (valueElement != null && valueElement.trim().length() != 0) {
if (isFile && !FileUtils.isAbsolutePath(valueElement)) {
if (id.equals("ant.import")) {
valueBuffer.add("${dita.plugin." + this.id + ".dir}" + File.separator + valueElement.trim());
} else {
valueBuffer.add(pluginDir + File.separator + valueElement.trim());
}
} else {
valueBuffer.add(valueElement.trim());
}
}
}
featureTable.put(id, valueBuffer);
} | java | public final void addFeature(final String id, final Element elem) {
boolean isFile;
String value = elem.getAttribute("file");
if (!value.isEmpty()) {
isFile = true;
} else {
value = elem.getAttribute("value");
isFile = "file".equals(elem.getAttribute("type"));
}
final StringTokenizer valueTokenizer = new StringTokenizer(value, Integrator.FEAT_VALUE_SEPARATOR);
final List<String> valueBuffer = new ArrayList<>();
if (featureTable.containsKey(id)) {
valueBuffer.addAll(featureTable.get(id));
}
while (valueTokenizer.hasMoreElements()) {
final String valueElement = valueTokenizer.nextToken();
if (valueElement != null && valueElement.trim().length() != 0) {
if (isFile && !FileUtils.isAbsolutePath(valueElement)) {
if (id.equals("ant.import")) {
valueBuffer.add("${dita.plugin." + this.id + ".dir}" + File.separator + valueElement.trim());
} else {
valueBuffer.add(pluginDir + File.separator + valueElement.trim());
}
} else {
valueBuffer.add(valueElement.trim());
}
}
}
featureTable.put(id, valueBuffer);
} | [
"public",
"final",
"void",
"addFeature",
"(",
"final",
"String",
"id",
",",
"final",
"Element",
"elem",
")",
"{",
"boolean",
"isFile",
";",
"String",
"value",
"=",
"elem",
".",
"getAttribute",
"(",
"\"file\"",
")",
";",
"if",
"(",
"!",
"value",
".",
"i... | Add feature to the feature table.
@param id feature id
@param elem configuration element | [
"Add",
"feature",
"to",
"the",
"feature",
"table",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/platform/Features.java#L109-L138 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/XMLSerializer.java | XMLSerializer.close | public void close() throws IOException {
if (outStream == null && outWriter == null) {
throw new IllegalStateException();
}
if (outStream != null) {
outStream.close();
}
if (outWriter != null) {
outWriter.close();
}
} | java | public void close() throws IOException {
if (outStream == null && outWriter == null) {
throw new IllegalStateException();
}
if (outStream != null) {
outStream.close();
}
if (outWriter != null) {
outWriter.close();
}
} | [
"public",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"outStream",
"==",
"null",
"&&",
"outWriter",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
")",
";",
"}",
"if",
"(",
"outStream",
"!=",
"null",
")",
... | Close output.
@throws IOException if closing result output failed | [
"Close",
"output",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLSerializer.java#L120-L130 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/XMLSerializer.java | XMLSerializer.writeStartElement | public void writeStartElement(final String uri, final String qName) throws SAXException {
processStartElement();
final QName res = new QName(uri, qName);
addNamespace(res.uri, res.prefix, res);
elementStack.addFirst(res); // push
openStartElement = true;
} | java | public void writeStartElement(final String uri, final String qName) throws SAXException {
processStartElement();
final QName res = new QName(uri, qName);
addNamespace(res.uri, res.prefix, res);
elementStack.addFirst(res); // push
openStartElement = true;
} | [
"public",
"void",
"writeStartElement",
"(",
"final",
"String",
"uri",
",",
"final",
"String",
"qName",
")",
"throws",
"SAXException",
"{",
"processStartElement",
"(",
")",
";",
"final",
"QName",
"res",
"=",
"new",
"QName",
"(",
"uri",
",",
"qName",
")",
";... | Write start element without attributes.
@param qName element QName
@throws SAXException if processing the event failed | [
"Write",
"start",
"element",
"without",
"attributes",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLSerializer.java#L169-L175 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/XMLSerializer.java | XMLSerializer.writeNamespace | public void writeNamespace(final String prefix, final String uri) {
if (!openStartElement) {
throw new IllegalStateException("Current state does not allow Namespace writing");
}
final QName qName = elementStack.getFirst(); // peek
for (final NamespaceMapping p: qName.mappings) {
if (p.prefix.equals(prefix) && p.uri.equals(uri)) {
return;
} else if (p.prefix.equals(prefix)) {
throw new IllegalArgumentException("Prefix " + prefix + " already bound to " + uri);
}
}
qName.mappings.add(new NamespaceMapping(prefix, uri, true));
} | java | public void writeNamespace(final String prefix, final String uri) {
if (!openStartElement) {
throw new IllegalStateException("Current state does not allow Namespace writing");
}
final QName qName = elementStack.getFirst(); // peek
for (final NamespaceMapping p: qName.mappings) {
if (p.prefix.equals(prefix) && p.uri.equals(uri)) {
return;
} else if (p.prefix.equals(prefix)) {
throw new IllegalArgumentException("Prefix " + prefix + " already bound to " + uri);
}
}
qName.mappings.add(new NamespaceMapping(prefix, uri, true));
} | [
"public",
"void",
"writeNamespace",
"(",
"final",
"String",
"prefix",
",",
"final",
"String",
"uri",
")",
"{",
"if",
"(",
"!",
"openStartElement",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Current state does not allow Namespace writing\"",
")",
";",... | Write namepace prefix.
@param prefix namespace prefix
@param uri namespace URI
@throws IllegalStateException if start element is not open
@throws IllegalArgumentException if prefix is already bound | [
"Write",
"namepace",
"prefix",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLSerializer.java#L185-L198 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/XMLSerializer.java | XMLSerializer.writeEndElement | public void writeEndElement() throws SAXException {
processStartElement();
final QName qName = elementStack.remove(); // pop
transformer.endElement(qName.uri, qName.localName, qName.qName);
for (final NamespaceMapping p: qName.mappings) {
if (p.newMapping) {
transformer.endPrefixMapping(p.prefix);
}
}
} | java | public void writeEndElement() throws SAXException {
processStartElement();
final QName qName = elementStack.remove(); // pop
transformer.endElement(qName.uri, qName.localName, qName.qName);
for (final NamespaceMapping p: qName.mappings) {
if (p.newMapping) {
transformer.endPrefixMapping(p.prefix);
}
}
} | [
"public",
"void",
"writeEndElement",
"(",
")",
"throws",
"SAXException",
"{",
"processStartElement",
"(",
")",
";",
"final",
"QName",
"qName",
"=",
"elementStack",
".",
"remove",
"(",
")",
";",
"// pop",
"transformer",
".",
"endElement",
"(",
"qName",
".",
"... | Write end element.
@throws SAXException if processing the event failed | [
"Write",
"end",
"element",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLSerializer.java#L236-L245 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/XMLSerializer.java | XMLSerializer.writeProcessingInstruction | public void writeProcessingInstruction(final String target, final String data) throws SAXException {
processStartElement();
transformer.processingInstruction(target, data != null ? data : "");
} | java | public void writeProcessingInstruction(final String target, final String data) throws SAXException {
processStartElement();
transformer.processingInstruction(target, data != null ? data : "");
} | [
"public",
"void",
"writeProcessingInstruction",
"(",
"final",
"String",
"target",
",",
"final",
"String",
"data",
")",
"throws",
"SAXException",
"{",
"processStartElement",
"(",
")",
";",
"transformer",
".",
"processingInstruction",
"(",
"target",
",",
"data",
"!=... | Write processing instruction.
@param target processing instruction name
@param data processing instruction data, {@code null} if no data
@throws SAXException if processing the event failed | [
"Write",
"processing",
"instruction",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLSerializer.java#L286-L289 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/XMLSerializer.java | XMLSerializer.writeComment | public void writeComment(final String data) throws SAXException {
processStartElement();
final char[] ch = data.toCharArray();
transformer.comment(ch, 0, ch.length);
} | java | public void writeComment(final String data) throws SAXException {
processStartElement();
final char[] ch = data.toCharArray();
transformer.comment(ch, 0, ch.length);
} | [
"public",
"void",
"writeComment",
"(",
"final",
"String",
"data",
")",
"throws",
"SAXException",
"{",
"processStartElement",
"(",
")",
";",
"final",
"char",
"[",
"]",
"ch",
"=",
"data",
".",
"toCharArray",
"(",
")",
";",
"transformer",
".",
"comment",
"(",... | Write comment.
@param data comment data
@throws SAXException if processing the event failed | [
"Write",
"comment",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLSerializer.java#L297-L301 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.isHTMLFile | @Deprecated
public static boolean isHTMLFile(final String lcasefn) {
for (final String ext: supportedHTMLExtensions) {
if (lcasefn.endsWith(ext)) {
return true;
}
}
return false;
} | java | @Deprecated
public static boolean isHTMLFile(final String lcasefn) {
for (final String ext: supportedHTMLExtensions) {
if (lcasefn.endsWith(ext)) {
return true;
}
}
return false;
} | [
"@",
"Deprecated",
"public",
"static",
"boolean",
"isHTMLFile",
"(",
"final",
"String",
"lcasefn",
")",
"{",
"for",
"(",
"final",
"String",
"ext",
":",
"supportedHTMLExtensions",
")",
"{",
"if",
"(",
"lcasefn",
".",
"endsWith",
"(",
"ext",
")",
")",
"{",
... | Return if the file is a html file by extension.
@param lcasefn file name
@return true if is html file and false otherwise | [
"Return",
"if",
"the",
"file",
"is",
"a",
"html",
"file",
"by",
"extension",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L96-L104 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.isResourceFile | @Deprecated
public static boolean isResourceFile(final String lcasefn) {
for (final String ext: supportedResourceExtensions) {
if (lcasefn.endsWith(ext)) {
return true;
}
}
return false;
} | java | @Deprecated
public static boolean isResourceFile(final String lcasefn) {
for (final String ext: supportedResourceExtensions) {
if (lcasefn.endsWith(ext)) {
return true;
}
}
return false;
} | [
"@",
"Deprecated",
"public",
"static",
"boolean",
"isResourceFile",
"(",
"final",
"String",
"lcasefn",
")",
"{",
"for",
"(",
"final",
"String",
"ext",
":",
"supportedResourceExtensions",
")",
"{",
"if",
"(",
"lcasefn",
".",
"endsWith",
"(",
"ext",
")",
")",
... | Return if the file is a resource file by its extension.
@param lcasefn file name in lower case.
@return {@code true} if file is a resource file, otherwise {@code false} | [
"Return",
"if",
"the",
"file",
"is",
"a",
"resource",
"file",
"by",
"its",
"extension",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L136-L144 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.isSupportedImageFile | @Deprecated
public static boolean isSupportedImageFile(final String lcasefn) {
for (final String ext: supportedImageExtensions) {
if (lcasefn.endsWith(ext)) {
return true;
}
}
return false;
} | java | @Deprecated
public static boolean isSupportedImageFile(final String lcasefn) {
for (final String ext: supportedImageExtensions) {
if (lcasefn.endsWith(ext)) {
return true;
}
}
return false;
} | [
"@",
"Deprecated",
"public",
"static",
"boolean",
"isSupportedImageFile",
"(",
"final",
"String",
"lcasefn",
")",
"{",
"for",
"(",
"final",
"String",
"ext",
":",
"supportedImageExtensions",
")",
"{",
"if",
"(",
"lcasefn",
".",
"endsWith",
"(",
"ext",
")",
")... | Return if the file is a supported image file by extension.
@param lcasefn filename
@return true if is supported image and false otherwise | [
"Return",
"if",
"the",
"file",
"is",
"a",
"supported",
"image",
"file",
"by",
"extension",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L151-L159 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.normalizePath | private static String normalizePath(final String path, final String separator) {
final String p = path.replace(WINDOWS_SEPARATOR, separator).replace(UNIX_SEPARATOR, separator);
// remove "." from the directory.
final List<String> dirs = new LinkedList<>();
final StringTokenizer tokenizer = new StringTokenizer(p, separator);
while (tokenizer.hasMoreTokens()) {
final String token = tokenizer.nextToken();
if (!(".".equals(token))) {
dirs.add(token);
}
}
// remove ".." and the dir name before it.
int dirNum = dirs.size();
int i = 0;
while (i < dirNum) {
if (i > 0) {
final String lastDir = dirs.get(i - 1);
final String dir = dirs.get(i);
if ("..".equals(dir) && !("..".equals(lastDir))) {
dirs.remove(i);
dirs.remove(i - 1);
dirNum = dirs.size();
i = i - 1;
continue;
}
}
i++;
}
// restore the directory.
final StringBuilder buff = new StringBuilder(p.length());
if (p.startsWith(separator + separator)) {
buff.append(separator).append(separator);
} else if (p.startsWith(separator)) {
buff.append(separator);
}
final Iterator<String> iter = dirs.iterator();
while (iter.hasNext()) {
buff.append(iter.next());
if (iter.hasNext()) {
buff.append(separator);
}
}
if (p.endsWith(separator)) {
buff.append(separator);
}
return buff.toString();
} | java | private static String normalizePath(final String path, final String separator) {
final String p = path.replace(WINDOWS_SEPARATOR, separator).replace(UNIX_SEPARATOR, separator);
// remove "." from the directory.
final List<String> dirs = new LinkedList<>();
final StringTokenizer tokenizer = new StringTokenizer(p, separator);
while (tokenizer.hasMoreTokens()) {
final String token = tokenizer.nextToken();
if (!(".".equals(token))) {
dirs.add(token);
}
}
// remove ".." and the dir name before it.
int dirNum = dirs.size();
int i = 0;
while (i < dirNum) {
if (i > 0) {
final String lastDir = dirs.get(i - 1);
final String dir = dirs.get(i);
if ("..".equals(dir) && !("..".equals(lastDir))) {
dirs.remove(i);
dirs.remove(i - 1);
dirNum = dirs.size();
i = i - 1;
continue;
}
}
i++;
}
// restore the directory.
final StringBuilder buff = new StringBuilder(p.length());
if (p.startsWith(separator + separator)) {
buff.append(separator).append(separator);
} else if (p.startsWith(separator)) {
buff.append(separator);
}
final Iterator<String> iter = dirs.iterator();
while (iter.hasNext()) {
buff.append(iter.next());
if (iter.hasNext()) {
buff.append(separator);
}
}
if (p.endsWith(separator)) {
buff.append(separator);
}
return buff.toString();
} | [
"private",
"static",
"String",
"normalizePath",
"(",
"final",
"String",
"path",
",",
"final",
"String",
"separator",
")",
"{",
"final",
"String",
"p",
"=",
"path",
".",
"replace",
"(",
"WINDOWS_SEPARATOR",
",",
"separator",
")",
".",
"replace",
"(",
"UNIX_SE... | Remove redundant names ".." and "." from the given path and replace directory separators.
@param path input path
@param separator directory separator
@return processed path | [
"Remove",
"redundant",
"names",
"..",
"and",
".",
"from",
"the",
"given",
"path",
"and",
"replace",
"directory",
"separators",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L363-L413 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.isAbsolutePath | public static boolean isAbsolutePath (final String path) {
if (path == null || path.trim().length() == 0) {
return false;
}
if (File.separator.equals(UNIX_SEPARATOR)) {
return path.startsWith(UNIX_SEPARATOR);
} else
if (File.separator.equals(WINDOWS_SEPARATOR) && path.length() > 2) {
return path.matches("([a-zA-Z]:|\\\\)\\\\.*");
}
return false;
} | java | public static boolean isAbsolutePath (final String path) {
if (path == null || path.trim().length() == 0) {
return false;
}
if (File.separator.equals(UNIX_SEPARATOR)) {
return path.startsWith(UNIX_SEPARATOR);
} else
if (File.separator.equals(WINDOWS_SEPARATOR) && path.length() > 2) {
return path.matches("([a-zA-Z]:|\\\\)\\\\.*");
}
return false;
} | [
"public",
"static",
"boolean",
"isAbsolutePath",
"(",
"final",
"String",
"path",
")",
"{",
"if",
"(",
"path",
"==",
"null",
"||",
"path",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
... | Return if the path is absolute.
@param path test path
@return true if path is absolute and false otherwise. | [
"Return",
"if",
"the",
"path",
"is",
"absolute",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L421-L435 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.getExtension | public static String getExtension(final String file) {
final int index = file.indexOf(SHARP);
if (file.startsWith(SHARP)) {
return null;
} else if (index != -1) {
final String fileName = file.substring(0, index);
final int fileExtIndex = fileName.lastIndexOf(DOT);
return fileExtIndex != -1 ? fileName.substring(fileExtIndex + 1) : null;
} else {
final int fileExtIndex = file.lastIndexOf(DOT);
return fileExtIndex != -1 ? file.substring(fileExtIndex + 1) : null;
}
} | java | public static String getExtension(final String file) {
final int index = file.indexOf(SHARP);
if (file.startsWith(SHARP)) {
return null;
} else if (index != -1) {
final String fileName = file.substring(0, index);
final int fileExtIndex = fileName.lastIndexOf(DOT);
return fileExtIndex != -1 ? fileName.substring(fileExtIndex + 1) : null;
} else {
final int fileExtIndex = file.lastIndexOf(DOT);
return fileExtIndex != -1 ? file.substring(fileExtIndex + 1) : null;
}
} | [
"public",
"static",
"String",
"getExtension",
"(",
"final",
"String",
"file",
")",
"{",
"final",
"int",
"index",
"=",
"file",
".",
"indexOf",
"(",
"SHARP",
")",
";",
"if",
"(",
"file",
".",
"startsWith",
"(",
"SHARP",
")",
")",
"{",
"return",
"null",
... | Get file extension
@param file filename, may contain a URL fragment
@return file extensions, {@code null} if no extension was found | [
"Get",
"file",
"extension"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L472-L485 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.getName | public static String getName(final String aURLString) {
int pathnameEndIndex;
if (isWindows()) {
if (aURLString.contains(SHARP)) {
pathnameEndIndex = aURLString.lastIndexOf(SHARP);
} else {
pathnameEndIndex = aURLString.lastIndexOf(WINDOWS_SEPARATOR);
if (pathnameEndIndex == -1) {
pathnameEndIndex = aURLString.lastIndexOf(UNIX_SEPARATOR);
}
}
} else {
if (aURLString.contains(SHARP)) {
pathnameEndIndex = aURLString.lastIndexOf(SHARP);
}
pathnameEndIndex = aURLString.lastIndexOf(UNIX_SEPARATOR);
}
String schemaLocation;
if (aURLString.contains(SHARP)) {
schemaLocation = aURLString.substring(0, pathnameEndIndex);
} else {
schemaLocation = aURLString.substring(pathnameEndIndex + 1);
}
return schemaLocation;
} | java | public static String getName(final String aURLString) {
int pathnameEndIndex;
if (isWindows()) {
if (aURLString.contains(SHARP)) {
pathnameEndIndex = aURLString.lastIndexOf(SHARP);
} else {
pathnameEndIndex = aURLString.lastIndexOf(WINDOWS_SEPARATOR);
if (pathnameEndIndex == -1) {
pathnameEndIndex = aURLString.lastIndexOf(UNIX_SEPARATOR);
}
}
} else {
if (aURLString.contains(SHARP)) {
pathnameEndIndex = aURLString.lastIndexOf(SHARP);
}
pathnameEndIndex = aURLString.lastIndexOf(UNIX_SEPARATOR);
}
String schemaLocation;
if (aURLString.contains(SHARP)) {
schemaLocation = aURLString.substring(0, pathnameEndIndex);
} else {
schemaLocation = aURLString.substring(pathnameEndIndex + 1);
}
return schemaLocation;
} | [
"public",
"static",
"String",
"getName",
"(",
"final",
"String",
"aURLString",
")",
"{",
"int",
"pathnameEndIndex",
";",
"if",
"(",
"isWindows",
"(",
")",
")",
"{",
"if",
"(",
"aURLString",
".",
"contains",
"(",
"SHARP",
")",
")",
"{",
"pathnameEndIndex",
... | Get filename from a path.
@param aURLString Windows, UNIX, or URI path, may contain hash fragment
@return filename without path or hash fragment | [
"Get",
"filename",
"from",
"a",
"path",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L493-L519 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.getFullPathNoEndSeparator | public static String getFullPathNoEndSeparator(final String aURLString) {
final int pathnameStartIndex = aURLString.indexOf(UNIX_SEPARATOR);
final int pathnameEndIndex = aURLString.lastIndexOf(UNIX_SEPARATOR);
String aPath = aURLString.substring(0, pathnameEndIndex);
return aPath;
} | java | public static String getFullPathNoEndSeparator(final String aURLString) {
final int pathnameStartIndex = aURLString.indexOf(UNIX_SEPARATOR);
final int pathnameEndIndex = aURLString.lastIndexOf(UNIX_SEPARATOR);
String aPath = aURLString.substring(0, pathnameEndIndex);
return aPath;
} | [
"public",
"static",
"String",
"getFullPathNoEndSeparator",
"(",
"final",
"String",
"aURLString",
")",
"{",
"final",
"int",
"pathnameStartIndex",
"=",
"aURLString",
".",
"indexOf",
"(",
"UNIX_SEPARATOR",
")",
";",
"final",
"int",
"pathnameEndIndex",
"=",
"aURLString"... | Get base path from a path.
@param aURLString UNIX or URI path
@return base path | [
"Get",
"base",
"path",
"from",
"a",
"path",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L538-L543 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.stripFragment | @Deprecated
public static String stripFragment(final String path) {
final int i = path.indexOf(SHARP);
if (i != -1) {
return path.substring(0, i);
} else {
return path;
}
} | java | @Deprecated
public static String stripFragment(final String path) {
final int i = path.indexOf(SHARP);
if (i != -1) {
return path.substring(0, i);
} else {
return path;
}
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"stripFragment",
"(",
"final",
"String",
"path",
")",
"{",
"final",
"int",
"i",
"=",
"path",
".",
"indexOf",
"(",
"SHARP",
")",
";",
"if",
"(",
"i",
"!=",
"-",
"1",
")",
"{",
"return",
"path",
".",
"... | Strip fragment part from path.
@param path path
@return path without path | [
"Strip",
"fragment",
"part",
"from",
"path",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L551-L559 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/FileUtils.java | FileUtils.getFragment | @Deprecated
public static String getFragment(final String path, final String defaultValue) {
final int i = path.indexOf(SHARP);
if (i != -1) {
return path.substring(i + 1);
} else {
return defaultValue;
}
} | java | @Deprecated
public static String getFragment(final String path, final String defaultValue) {
final int i = path.indexOf(SHARP);
if (i != -1) {
return path.substring(i + 1);
} else {
return defaultValue;
}
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"getFragment",
"(",
"final",
"String",
"path",
",",
"final",
"String",
"defaultValue",
")",
"{",
"final",
"int",
"i",
"=",
"path",
".",
"indexOf",
"(",
"SHARP",
")",
";",
"if",
"(",
"i",
"!=",
"-",
"1",
... | Get fragment part from path or return default fragment.
@param path path
@param defaultValue default fragment value
@return fragment without {@link Constants#SHARP}, default value if no fragment exists | [
"Get",
"fragment",
"part",
"from",
"path",
"or",
"return",
"default",
"fragment",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L592-L600 | train |
dita-ot/dita-ot | src/main/java/org/ditang/relaxng/defaults/OxygenRelaxNGSchemaReader.java | OxygenRelaxNGSchemaReader.wrapPattern2 | private static SchemaWrapper wrapPattern2(Pattern start, SchemaPatternBuilder spb, PropertyMap properties)
throws SAXException, IncorrectSchemaException {
if (properties.contains(RngProperty.FEASIBLE)) {
//Use a feasible transform
start = FeasibleTransform.transform(spb, start);
}
//Get properties for supported IDs
properties = AbstractSchema.filterProperties(properties, supportedPropertyIds);
Schema schema = new PatternSchema(spb, start, properties);
IdTypeMap idTypeMap = null;
if (spb.hasIdTypes() && properties.contains(RngProperty.CHECK_ID_IDREF)) {
//Check ID/IDREF
ErrorHandler eh = properties.get(ValidateProperty.ERROR_HANDLER);
idTypeMap = new IdTypeMapBuilder(eh, start).getIdTypeMap();
if (idTypeMap == null) {
throw new IncorrectSchemaException();
}
Schema idSchema;
if (properties.contains(RngProperty.FEASIBLE)) {
idSchema = new FeasibleIdTypeMapSchema(idTypeMap, properties);
} else {
idSchema = new IdTypeMapSchema(idTypeMap, properties);
}
schema = new CombineSchema(schema, idSchema, properties);
}
//Wrap the schema
SchemaWrapper sw = new SchemaWrapper(schema);
sw.setStart(start);
sw.setIdTypeMap(idTypeMap);
return sw;
} | java | private static SchemaWrapper wrapPattern2(Pattern start, SchemaPatternBuilder spb, PropertyMap properties)
throws SAXException, IncorrectSchemaException {
if (properties.contains(RngProperty.FEASIBLE)) {
//Use a feasible transform
start = FeasibleTransform.transform(spb, start);
}
//Get properties for supported IDs
properties = AbstractSchema.filterProperties(properties, supportedPropertyIds);
Schema schema = new PatternSchema(spb, start, properties);
IdTypeMap idTypeMap = null;
if (spb.hasIdTypes() && properties.contains(RngProperty.CHECK_ID_IDREF)) {
//Check ID/IDREF
ErrorHandler eh = properties.get(ValidateProperty.ERROR_HANDLER);
idTypeMap = new IdTypeMapBuilder(eh, start).getIdTypeMap();
if (idTypeMap == null) {
throw new IncorrectSchemaException();
}
Schema idSchema;
if (properties.contains(RngProperty.FEASIBLE)) {
idSchema = new FeasibleIdTypeMapSchema(idTypeMap, properties);
} else {
idSchema = new IdTypeMapSchema(idTypeMap, properties);
}
schema = new CombineSchema(schema, idSchema, properties);
}
//Wrap the schema
SchemaWrapper sw = new SchemaWrapper(schema);
sw.setStart(start);
sw.setIdTypeMap(idTypeMap);
return sw;
} | [
"private",
"static",
"SchemaWrapper",
"wrapPattern2",
"(",
"Pattern",
"start",
",",
"SchemaPatternBuilder",
"spb",
",",
"PropertyMap",
"properties",
")",
"throws",
"SAXException",
",",
"IncorrectSchemaException",
"{",
"if",
"(",
"properties",
".",
"contains",
"(",
"... | Make a schema wrapper.
@param start Start pattern.
@param spb The schema pattern builder.
@param properties The properties map.
@return The schema wrapper. | [
"Make",
"a",
"schema",
"wrapper",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/ditang/relaxng/defaults/OxygenRelaxNGSchemaReader.java#L174-L205 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/XmlFilterModule.java | XmlFilterModule.execute | @Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input)
throws DITAOTException {
final Collection<FileInfo> fis = job.getFileInfo(fileInfoFilter);
for (final FileInfo f: fis) {
final URI file = job.tempDirURI.resolve(f.uri);
logger.info("Processing " + file);
try {
xmlUtils.transform(file, getProcessingPipe(f));
} catch (final DITAOTException e) {
logger.error("Failed to process XML filter: " + e.getMessage(), e);
}
}
return null;
} | java | @Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input)
throws DITAOTException {
final Collection<FileInfo> fis = job.getFileInfo(fileInfoFilter);
for (final FileInfo f: fis) {
final URI file = job.tempDirURI.resolve(f.uri);
logger.info("Processing " + file);
try {
xmlUtils.transform(file, getProcessingPipe(f));
} catch (final DITAOTException e) {
logger.error("Failed to process XML filter: " + e.getMessage(), e);
}
}
return null;
} | [
"@",
"Override",
"public",
"AbstractPipelineOutput",
"execute",
"(",
"final",
"AbstractPipelineInput",
"input",
")",
"throws",
"DITAOTException",
"{",
"final",
"Collection",
"<",
"FileInfo",
">",
"fis",
"=",
"job",
".",
"getFileInfo",
"(",
"fileInfoFilter",
")",
"... | Filter files through XML filters.
@param input Input parameters and resources.
@return always returns {@code null} | [
"Filter",
"files",
"through",
"XML",
"filters",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/XmlFilterModule.java#L45-L59 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/reader/SubjectSchemeReader.java | SubjectSchemeReader.writeMapToXML | public static void writeMapToXML(final Map<URI, Set<URI>> m, final File outputFile) throws IOException {
if (m == null) {
return;
}
final Properties prop = new Properties();
for (final Map.Entry<URI, Set<URI>> entry: m.entrySet()) {
final URI key = entry.getKey();
final String value = StringUtils.join(entry.getValue(), COMMA);
prop.setProperty(key.getPath(), value);
}
try (OutputStream os = new FileOutputStream(outputFile)) {
prop.storeToXML(os, null);
} catch (final IOException e) {
throw new IOException("Failed to write subject scheme graph: " + e.getMessage(), e);
}
} | java | public static void writeMapToXML(final Map<URI, Set<URI>> m, final File outputFile) throws IOException {
if (m == null) {
return;
}
final Properties prop = new Properties();
for (final Map.Entry<URI, Set<URI>> entry: m.entrySet()) {
final URI key = entry.getKey();
final String value = StringUtils.join(entry.getValue(), COMMA);
prop.setProperty(key.getPath(), value);
}
try (OutputStream os = new FileOutputStream(outputFile)) {
prop.storeToXML(os, null);
} catch (final IOException e) {
throw new IOException("Failed to write subject scheme graph: " + e.getMessage(), e);
}
} | [
"public",
"static",
"void",
"writeMapToXML",
"(",
"final",
"Map",
"<",
"URI",
",",
"Set",
"<",
"URI",
">",
">",
"m",
",",
"final",
"File",
"outputFile",
")",
"throws",
"IOException",
"{",
"if",
"(",
"m",
"==",
"null",
")",
"{",
"return",
";",
"}",
... | Write map of sets to a file.
<p>The serialization format is XML properties format where values are comma
separated lists.</p>
@param m map to serialize
@param outputFile output filename, relative to temporary directory | [
"Write",
"map",
"of",
"sets",
"to",
"a",
"file",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/reader/SubjectSchemeReader.java#L142-L157 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/reader/SubjectSchemeReader.java | SubjectSchemeReader.loadSubjectScheme | public void loadSubjectScheme(final File scheme) {
assert scheme.isAbsolute();
if (!scheme.exists()) {
throw new IllegalStateException();
}
logger.debug("Load subject scheme " + scheme);
try {
final DocumentBuilder builder = XMLUtils.getDocumentBuilder();
final Document doc = builder.parse(scheme);
final Element schemeRoot = doc.getDocumentElement();
if (schemeRoot == null) {
return;
}
loadSubjectScheme(schemeRoot);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
}
} | java | public void loadSubjectScheme(final File scheme) {
assert scheme.isAbsolute();
if (!scheme.exists()) {
throw new IllegalStateException();
}
logger.debug("Load subject scheme " + scheme);
try {
final DocumentBuilder builder = XMLUtils.getDocumentBuilder();
final Document doc = builder.parse(scheme);
final Element schemeRoot = doc.getDocumentElement();
if (schemeRoot == null) {
return;
}
loadSubjectScheme(schemeRoot);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
}
} | [
"public",
"void",
"loadSubjectScheme",
"(",
"final",
"File",
"scheme",
")",
"{",
"assert",
"scheme",
".",
"isAbsolute",
"(",
")",
";",
"if",
"(",
"!",
"scheme",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
")",
";",
... | Load schema file.
@param scheme absolute path for subject scheme | [
"Load",
"schema",
"file",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/reader/SubjectSchemeReader.java#L164-L184 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/reader/SubjectSchemeReader.java | SubjectSchemeReader.putValuePairsIntoMap | private void putValuePairsIntoMap(final Element subtree, final String elementName, final QName attName, final String category) {
if (subtree == null || attName == null) {
return;
}
Map<String, Set<String>> valueMap = validValuesMap.get(attName);
if (valueMap == null) {
valueMap = new HashMap<>();
}
Set<String> valueSet = valueMap.get(elementName);
if (valueSet == null) {
valueSet = new HashSet<>();
}
final LinkedList<Element> queue = new LinkedList<>();
queue.offer(subtree);
while (!queue.isEmpty()) {
final Element node = queue.poll();
final NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)children.item(i));
}
}
if (SUBJECTSCHEME_SUBJECTDEF.matches(node)) {
final String key = node.getAttribute(ATTRIBUTE_NAME_KEYS);
if (!(key == null || key.trim().isEmpty() || key.equals(category))) {
valueSet.add(key);
}
}
}
valueMap.put(elementName, valueSet);
validValuesMap.put(attName, valueMap);
} | java | private void putValuePairsIntoMap(final Element subtree, final String elementName, final QName attName, final String category) {
if (subtree == null || attName == null) {
return;
}
Map<String, Set<String>> valueMap = validValuesMap.get(attName);
if (valueMap == null) {
valueMap = new HashMap<>();
}
Set<String> valueSet = valueMap.get(elementName);
if (valueSet == null) {
valueSet = new HashSet<>();
}
final LinkedList<Element> queue = new LinkedList<>();
queue.offer(subtree);
while (!queue.isEmpty()) {
final Element node = queue.poll();
final NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)children.item(i));
}
}
if (SUBJECTSCHEME_SUBJECTDEF.matches(node)) {
final String key = node.getAttribute(ATTRIBUTE_NAME_KEYS);
if (!(key == null || key.trim().isEmpty() || key.equals(category))) {
valueSet.add(key);
}
}
}
valueMap.put(elementName, valueSet);
validValuesMap.put(attName, valueMap);
} | [
"private",
"void",
"putValuePairsIntoMap",
"(",
"final",
"Element",
"subtree",
",",
"final",
"String",
"elementName",
",",
"final",
"QName",
"attName",
",",
"final",
"String",
"category",
")",
"{",
"if",
"(",
"subtree",
"==",
"null",
"||",
"attName",
"==",
"... | Populate valid values map
@param subtree subject scheme definition element
@param elementName element name
@param attName attribute name
@param category enumeration category name | [
"Populate",
"valid",
"values",
"map"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/reader/SubjectSchemeReader.java#L285-L320 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/CopyToModule.java | CopyToModule.processMap | private void processMap() throws DITAOTException {
final URI in = job.tempDirURI.resolve(job.getFileInfo(fi -> fi.isInput).iterator().next().uri);
final List<XMLFilter> pipe = getProcessingPipe(in);
xmlUtils.transform(in, pipe);
} | java | private void processMap() throws DITAOTException {
final URI in = job.tempDirURI.resolve(job.getFileInfo(fi -> fi.isInput).iterator().next().uri);
final List<XMLFilter> pipe = getProcessingPipe(in);
xmlUtils.transform(in, pipe);
} | [
"private",
"void",
"processMap",
"(",
")",
"throws",
"DITAOTException",
"{",
"final",
"URI",
"in",
"=",
"job",
".",
"tempDirURI",
".",
"resolve",
"(",
"job",
".",
"getFileInfo",
"(",
"fi",
"->",
"fi",
".",
"isInput",
")",
".",
"iterator",
"(",
")",
"."... | Process start map to read copy-to map and write unique topic references. | [
"Process",
"start",
"map",
"to",
"read",
"copy",
"-",
"to",
"map",
"and",
"write",
"unique",
"topic",
"references",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/CopyToModule.java#L94-L100 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/CopyToModule.java | CopyToModule.getProcessingPipe | private List<XMLFilter> getProcessingPipe(final URI fileToParse) {
final List<XMLFilter> pipe = new ArrayList<>();
if (forceUnique) {
forceUniqueFilter = new ForceUniqueFilter();
forceUniqueFilter.setLogger(logger);
forceUniqueFilter.setJob(job);
forceUniqueFilter.setCurrentFile(fileToParse);
forceUniqueFilter.setTempFileNameScheme(tempFileNameScheme);
pipe.add(forceUniqueFilter);
}
reader.setJob(job);
reader.setLogger(logger);
reader.setCurrentFile(fileToParse);
pipe.add(reader);
return pipe;
} | java | private List<XMLFilter> getProcessingPipe(final URI fileToParse) {
final List<XMLFilter> pipe = new ArrayList<>();
if (forceUnique) {
forceUniqueFilter = new ForceUniqueFilter();
forceUniqueFilter.setLogger(logger);
forceUniqueFilter.setJob(job);
forceUniqueFilter.setCurrentFile(fileToParse);
forceUniqueFilter.setTempFileNameScheme(tempFileNameScheme);
pipe.add(forceUniqueFilter);
}
reader.setJob(job);
reader.setLogger(logger);
reader.setCurrentFile(fileToParse);
pipe.add(reader);
return pipe;
} | [
"private",
"List",
"<",
"XMLFilter",
">",
"getProcessingPipe",
"(",
"final",
"URI",
"fileToParse",
")",
"{",
"final",
"List",
"<",
"XMLFilter",
">",
"pipe",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"forceUnique",
")",
"{",
"forceUniqueFilte... | Get processign filters | [
"Get",
"processign",
"filters"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/CopyToModule.java#L105-L123 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/CopyToModule.java | CopyToModule.getCopyToMap | private Map<FileInfo, FileInfo> getCopyToMap() {
final Map<FileInfo, FileInfo> copyToMap = new HashMap<>();
if (forceUnique) {
forceUniqueFilter.copyToMap.forEach((dstFi, srcFi) -> {
job.add(dstFi);
copyToMap.put(dstFi, srcFi);
});
}
for (final Map.Entry<URI, URI> e : reader.getCopyToMap().entrySet()) {
final URI target = job.tempDirURI.relativize(e.getKey());
final FileInfo targetFi = job.getFileInfo(target);
final URI source = job.tempDirURI.relativize(e.getValue());
final FileInfo sourceFi = job.getFileInfo(source);
// Filter when copy-to was ignored (so target is not in job),
// or where target is used directly
if (targetFi == null ||
(targetFi != null && targetFi.src != null)) {
continue;
}
copyToMap.put(targetFi, sourceFi);
}
return copyToMap;
} | java | private Map<FileInfo, FileInfo> getCopyToMap() {
final Map<FileInfo, FileInfo> copyToMap = new HashMap<>();
if (forceUnique) {
forceUniqueFilter.copyToMap.forEach((dstFi, srcFi) -> {
job.add(dstFi);
copyToMap.put(dstFi, srcFi);
});
}
for (final Map.Entry<URI, URI> e : reader.getCopyToMap().entrySet()) {
final URI target = job.tempDirURI.relativize(e.getKey());
final FileInfo targetFi = job.getFileInfo(target);
final URI source = job.tempDirURI.relativize(e.getValue());
final FileInfo sourceFi = job.getFileInfo(source);
// Filter when copy-to was ignored (so target is not in job),
// or where target is used directly
if (targetFi == null ||
(targetFi != null && targetFi.src != null)) {
continue;
}
copyToMap.put(targetFi, sourceFi);
}
return copyToMap;
} | [
"private",
"Map",
"<",
"FileInfo",
",",
"FileInfo",
">",
"getCopyToMap",
"(",
")",
"{",
"final",
"Map",
"<",
"FileInfo",
",",
"FileInfo",
">",
"copyToMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"if",
"(",
"forceUnique",
")",
"{",
"forceUniqueFilter... | Get copy-to map based on map processing.
@return target to source map of URIs relative to temporary directory | [
"Get",
"copy",
"-",
"to",
"map",
"based",
"on",
"map",
"processing",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/CopyToModule.java#L130-L155 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/CopyToModule.java | CopyToModule.performCopytoTask | private void performCopytoTask(final Map<FileInfo, FileInfo> copyToMap) {
for (final Map.Entry<FileInfo, FileInfo> entry : copyToMap.entrySet()) {
final URI copytoTarget = entry.getKey().uri;
final URI copytoSource = entry.getValue().uri;
final URI srcFile = job.tempDirURI.resolve(copytoSource);
final URI targetFile = job.tempDirURI.resolve(copytoTarget);
if (new File(targetFile).exists()) {
logger.warn(MessageUtils.getMessage("DOTX064W", copytoTarget.getPath()).toString());
} else {
final FileInfo input = job.getFileInfo(fi -> fi.isInput).iterator().next();
final URI inputMapInTemp = job.tempDirURI.resolve(input.uri);
copyFileWithPIReplaced(srcFile, targetFile, copytoTarget, inputMapInTemp);
// add new file info into job
final FileInfo src = job.getFileInfo(copytoSource);
assert src != null;
final FileInfo dst = job.getFileInfo(copytoTarget);
assert dst != null;
final URI dstTemp = tempFileNameScheme.generateTempFileName(dst.result);
final FileInfo res = new FileInfo.Builder(src)
.result(dst.result)
.uri(dstTemp)
.build();
job.add(res);
}
}
} | java | private void performCopytoTask(final Map<FileInfo, FileInfo> copyToMap) {
for (final Map.Entry<FileInfo, FileInfo> entry : copyToMap.entrySet()) {
final URI copytoTarget = entry.getKey().uri;
final URI copytoSource = entry.getValue().uri;
final URI srcFile = job.tempDirURI.resolve(copytoSource);
final URI targetFile = job.tempDirURI.resolve(copytoTarget);
if (new File(targetFile).exists()) {
logger.warn(MessageUtils.getMessage("DOTX064W", copytoTarget.getPath()).toString());
} else {
final FileInfo input = job.getFileInfo(fi -> fi.isInput).iterator().next();
final URI inputMapInTemp = job.tempDirURI.resolve(input.uri);
copyFileWithPIReplaced(srcFile, targetFile, copytoTarget, inputMapInTemp);
// add new file info into job
final FileInfo src = job.getFileInfo(copytoSource);
assert src != null;
final FileInfo dst = job.getFileInfo(copytoTarget);
assert dst != null;
final URI dstTemp = tempFileNameScheme.generateTempFileName(dst.result);
final FileInfo res = new FileInfo.Builder(src)
.result(dst.result)
.uri(dstTemp)
.build();
job.add(res);
}
}
} | [
"private",
"void",
"performCopytoTask",
"(",
"final",
"Map",
"<",
"FileInfo",
",",
"FileInfo",
">",
"copyToMap",
")",
"{",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"FileInfo",
",",
"FileInfo",
">",
"entry",
":",
"copyToMap",
".",
"entrySet",
"(",
"... | Execute copy-to task, generate copy-to targets base on sources.
@param copyToMap target to source map of URIs relative to temporary directory | [
"Execute",
"copy",
"-",
"to",
"task",
"generate",
"copy",
"-",
"to",
"targets",
"base",
"on",
"sources",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/CopyToModule.java#L162-L188 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/CopyToModule.java | CopyToModule.copyFileWithPIReplaced | private void copyFileWithPIReplaced(final URI src, final URI target, final URI copytoTargetFilename, final URI inputMapInTemp) {
assert src.isAbsolute();
assert target.isAbsolute();
assert !copytoTargetFilename.isAbsolute();
assert inputMapInTemp.isAbsolute();
final File workdir = new File(target).getParentFile();
if (!workdir.exists() && !workdir.mkdirs()) {
logger.error("Failed to create copy-to target directory " + workdir.toURI());
return;
}
final File path2project = getPathtoProject(copytoTargetFilename, target, inputMapInTemp, job);
final File path2rootmap = getPathtoRootmap(target, inputMapInTemp);
XMLFilter filter = new CopyToFilter(workdir, path2project, path2rootmap, src, target);
logger.info("Processing " + src + " to " + target);
try {
xmlUtils.transform(src, target, Collections.singletonList(filter));
} catch (final DITAOTException e) {
logger.error("Failed to write copy-to file: " + e.getMessage(), e);
}
} | java | private void copyFileWithPIReplaced(final URI src, final URI target, final URI copytoTargetFilename, final URI inputMapInTemp) {
assert src.isAbsolute();
assert target.isAbsolute();
assert !copytoTargetFilename.isAbsolute();
assert inputMapInTemp.isAbsolute();
final File workdir = new File(target).getParentFile();
if (!workdir.exists() && !workdir.mkdirs()) {
logger.error("Failed to create copy-to target directory " + workdir.toURI());
return;
}
final File path2project = getPathtoProject(copytoTargetFilename, target, inputMapInTemp, job);
final File path2rootmap = getPathtoRootmap(target, inputMapInTemp);
XMLFilter filter = new CopyToFilter(workdir, path2project, path2rootmap, src, target);
logger.info("Processing " + src + " to " + target);
try {
xmlUtils.transform(src, target, Collections.singletonList(filter));
} catch (final DITAOTException e) {
logger.error("Failed to write copy-to file: " + e.getMessage(), e);
}
} | [
"private",
"void",
"copyFileWithPIReplaced",
"(",
"final",
"URI",
"src",
",",
"final",
"URI",
"target",
",",
"final",
"URI",
"copytoTargetFilename",
",",
"final",
"URI",
"inputMapInTemp",
")",
"{",
"assert",
"src",
".",
"isAbsolute",
"(",
")",
";",
"assert",
... | Copy files and replace workdir PI contents.
@param src source URI in temporary directory
@param target target URI in temporary directory
@param copytoTargetFilename target URI relative to temporary directory
@param inputMapInTemp input map URI in temporary directory | [
"Copy",
"files",
"and",
"replace",
"workdir",
"PI",
"contents",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/CopyToModule.java#L198-L218 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/CopyToModule.java | CopyToModule.getPathtoRootmap | public static File getPathtoRootmap(final URI traceFilename, final URI inputMap) {
assert traceFilename.isAbsolute();
assert inputMap.isAbsolute();
return toFile(getRelativePath(traceFilename, inputMap)).getParentFile();
} | java | public static File getPathtoRootmap(final URI traceFilename, final URI inputMap) {
assert traceFilename.isAbsolute();
assert inputMap.isAbsolute();
return toFile(getRelativePath(traceFilename, inputMap)).getParentFile();
} | [
"public",
"static",
"File",
"getPathtoRootmap",
"(",
"final",
"URI",
"traceFilename",
",",
"final",
"URI",
"inputMap",
")",
"{",
"assert",
"traceFilename",
".",
"isAbsolute",
"(",
")",
";",
"assert",
"inputMap",
".",
"isAbsolute",
"(",
")",
";",
"return",
"t... | Get path to root map
@param traceFilename absolute input file
@param inputMap absolute path to start file
@return path to base directory, {@code null} if not available | [
"Get",
"path",
"to",
"root",
"map"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/CopyToModule.java#L351-L355 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/reader/MergeMapParser.java | MergeMapParser.read | public void read(final File filename, final File tmpDir) {
tempdir = tmpDir != null ? tmpDir : filename.getParentFile();
try {
final TransformerHandler s = stf.newTransformerHandler();
s.getTransformer().setOutputProperty(OMIT_XML_DECLARATION, "yes");
s.setResult(new StreamResult(output));
setContentHandler(s);
dirPath = filename.getParentFile();
reader.setErrorHandler(new DITAOTXMLErrorHandler(filename.getAbsolutePath(), logger));
topicParser.getContentHandler().startDocument();
logger.info("Processing " + filename.getAbsolutePath());
reader.parse(filename.toURI().toString());
topicParser.getContentHandler().endDocument();
output.write(topicBuffer.toByteArray());
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
}
} | java | public void read(final File filename, final File tmpDir) {
tempdir = tmpDir != null ? tmpDir : filename.getParentFile();
try {
final TransformerHandler s = stf.newTransformerHandler();
s.getTransformer().setOutputProperty(OMIT_XML_DECLARATION, "yes");
s.setResult(new StreamResult(output));
setContentHandler(s);
dirPath = filename.getParentFile();
reader.setErrorHandler(new DITAOTXMLErrorHandler(filename.getAbsolutePath(), logger));
topicParser.getContentHandler().startDocument();
logger.info("Processing " + filename.getAbsolutePath());
reader.parse(filename.toURI().toString());
topicParser.getContentHandler().endDocument();
output.write(topicBuffer.toByteArray());
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
}
} | [
"public",
"void",
"read",
"(",
"final",
"File",
"filename",
",",
"final",
"File",
"tmpDir",
")",
"{",
"tempdir",
"=",
"tmpDir",
"!=",
"null",
"?",
"tmpDir",
":",
"filename",
".",
"getParentFile",
"(",
")",
";",
"try",
"{",
"final",
"TransformerHandler",
... | Read map.
@param filename map file path
@param tmpDir temporary directory path, may be {@code null} | [
"Read",
"map",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/reader/MergeMapParser.java#L130-L149 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java | AbstractReaderModule.initXMLReader | void initXMLReader(final File ditaDir, final boolean validate) throws SAXException {
reader = XMLUtils.getXMLReader();
reader.setFeature(FEATURE_NAMESPACE, true);
reader.setFeature(FEATURE_NAMESPACE_PREFIX, true);
if (validate) {
reader.setFeature(FEATURE_VALIDATION, true);
try {
reader.setFeature(FEATURE_VALIDATION_SCHEMA, true);
} catch (final SAXNotRecognizedException e) {
// Not Xerces, ignore exception
}
} else {
logger.warn(MessageUtils.getMessage("DOTJ037W").toString());
}
if (gramcache) {
final XMLGrammarPool grammarPool = GrammarPoolManager.getGrammarPool();
try {
reader.setProperty("http://apache.org/xml/properties/internal/grammar-pool", grammarPool);
logger.info("Using Xerces grammar pool for DTD and schema caching.");
} catch (final NoClassDefFoundError e) {
logger.debug("Xerces not available, not using grammar caching");
} catch (final SAXNotRecognizedException | SAXNotSupportedException e) {
logger.warn("Failed to set Xerces grammar pool for parser: " + e.getMessage());
}
}
CatalogUtils.setDitaDir(ditaDir);
reader.setEntityResolver(CatalogUtils.getCatalogResolver());
} | java | void initXMLReader(final File ditaDir, final boolean validate) throws SAXException {
reader = XMLUtils.getXMLReader();
reader.setFeature(FEATURE_NAMESPACE, true);
reader.setFeature(FEATURE_NAMESPACE_PREFIX, true);
if (validate) {
reader.setFeature(FEATURE_VALIDATION, true);
try {
reader.setFeature(FEATURE_VALIDATION_SCHEMA, true);
} catch (final SAXNotRecognizedException e) {
// Not Xerces, ignore exception
}
} else {
logger.warn(MessageUtils.getMessage("DOTJ037W").toString());
}
if (gramcache) {
final XMLGrammarPool grammarPool = GrammarPoolManager.getGrammarPool();
try {
reader.setProperty("http://apache.org/xml/properties/internal/grammar-pool", grammarPool);
logger.info("Using Xerces grammar pool for DTD and schema caching.");
} catch (final NoClassDefFoundError e) {
logger.debug("Xerces not available, not using grammar caching");
} catch (final SAXNotRecognizedException | SAXNotSupportedException e) {
logger.warn("Failed to set Xerces grammar pool for parser: " + e.getMessage());
}
}
CatalogUtils.setDitaDir(ditaDir);
reader.setEntityResolver(CatalogUtils.getCatalogResolver());
} | [
"void",
"initXMLReader",
"(",
"final",
"File",
"ditaDir",
",",
"final",
"boolean",
"validate",
")",
"throws",
"SAXException",
"{",
"reader",
"=",
"XMLUtils",
".",
"getXMLReader",
"(",
")",
";",
"reader",
".",
"setFeature",
"(",
"FEATURE_NAMESPACE",
",",
"true"... | Init xml reader used for pipeline parsing.
@param ditaDir absolute path to DITA-OT directory
@param validate whether validate input file
@throws SAXException parsing exception | [
"Init",
"xml",
"reader",
"used",
"for",
"pipeline",
"parsing",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java#L186-L213 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java | AbstractReaderModule.processParseResult | void processParseResult(final URI currentFile) {
// Category non-copyto result
for (final Reference file: listFilter.getNonCopytoResult()) {
categorizeReferenceFile(file);
}
for (final Map.Entry<URI, URI> e : listFilter.getCopytoMap().entrySet()) {
final URI source = e.getValue();
final URI target = e.getKey();
copyTo.put(target, source);
}
schemeSet.addAll(listFilter.getSchemeRefSet());
hrefTargetSet.addAll(listFilter.getHrefTargets());
conrefTargetSet.addAll(listFilter.getConrefTargets());
nonConrefCopytoTargetSet.addAll(listFilter.getNonConrefCopytoTargets());
coderefTargetSet.addAll(listFilter.getCoderefTargets());
outDitaFilesSet.addAll(listFilter.getOutFilesSet());
// Generate topic-scheme dictionary
final Set<URI> schemeSet = listFilter.getSchemeSet();
if (schemeSet != null && !schemeSet.isEmpty()) {
Set<URI> children = schemeDictionary.get(currentFile);
if (children == null) {
children = new HashSet<>();
}
children.addAll(schemeSet);
schemeDictionary.put(currentFile, children);
final Set<URI> hrfSet = listFilter.getHrefTargets();
for (final URI filename: hrfSet) {
children = schemeDictionary.get(filename);
if (children == null) {
children = new HashSet<>();
}
children.addAll(schemeSet);
schemeDictionary.put(filename, children);
}
}
} | java | void processParseResult(final URI currentFile) {
// Category non-copyto result
for (final Reference file: listFilter.getNonCopytoResult()) {
categorizeReferenceFile(file);
}
for (final Map.Entry<URI, URI> e : listFilter.getCopytoMap().entrySet()) {
final URI source = e.getValue();
final URI target = e.getKey();
copyTo.put(target, source);
}
schemeSet.addAll(listFilter.getSchemeRefSet());
hrefTargetSet.addAll(listFilter.getHrefTargets());
conrefTargetSet.addAll(listFilter.getConrefTargets());
nonConrefCopytoTargetSet.addAll(listFilter.getNonConrefCopytoTargets());
coderefTargetSet.addAll(listFilter.getCoderefTargets());
outDitaFilesSet.addAll(listFilter.getOutFilesSet());
// Generate topic-scheme dictionary
final Set<URI> schemeSet = listFilter.getSchemeSet();
if (schemeSet != null && !schemeSet.isEmpty()) {
Set<URI> children = schemeDictionary.get(currentFile);
if (children == null) {
children = new HashSet<>();
}
children.addAll(schemeSet);
schemeDictionary.put(currentFile, children);
final Set<URI> hrfSet = listFilter.getHrefTargets();
for (final URI filename: hrfSet) {
children = schemeDictionary.get(filename);
if (children == null) {
children = new HashSet<>();
}
children.addAll(schemeSet);
schemeDictionary.put(filename, children);
}
}
} | [
"void",
"processParseResult",
"(",
"final",
"URI",
"currentFile",
")",
"{",
"// Category non-copyto result",
"for",
"(",
"final",
"Reference",
"file",
":",
"listFilter",
".",
"getNonCopytoResult",
"(",
")",
")",
"{",
"categorizeReferenceFile",
"(",
"file",
")",
";... | Process results from parsing a single topic
@param currentFile absolute URI processes files | [
"Process",
"results",
"from",
"parsing",
"a",
"single",
"topic"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java#L445-L482 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java | AbstractReaderModule.addToWaitList | void addToWaitList(final Reference ref) {
final URI file = ref.filename;
assert file.isAbsolute() && file.getFragment() == null;
if (doneList.contains(file) || waitList.contains(ref) || file.equals(currentFile)) {
return;
}
waitList.add(ref);
} | java | void addToWaitList(final Reference ref) {
final URI file = ref.filename;
assert file.isAbsolute() && file.getFragment() == null;
if (doneList.contains(file) || waitList.contains(ref) || file.equals(currentFile)) {
return;
}
waitList.add(ref);
} | [
"void",
"addToWaitList",
"(",
"final",
"Reference",
"ref",
")",
"{",
"final",
"URI",
"file",
"=",
"ref",
".",
"filename",
";",
"assert",
"file",
".",
"isAbsolute",
"(",
")",
"&&",
"file",
".",
"getFragment",
"(",
")",
"==",
"null",
";",
"if",
"(",
"d... | Add the given file the wait list if it has not been parsed.
@param ref reference to absolute system path | [
"Add",
"the",
"given",
"file",
"the",
"wait",
"list",
"if",
"it",
"has",
"not",
"been",
"parsed",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java#L542-L550 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java | AbstractReaderModule.parseFilterFile | private FilterUtils parseFilterFile() {
final FilterUtils filterUtils;
if (ditavalFile != null) {
final DitaValReader ditaValReader = new DitaValReader();
ditaValReader.setLogger(logger);
ditaValReader.setJob(job);
ditaValReader.read(ditavalFile.toURI());
flagImageSet.addAll(ditaValReader.getImageList());
relFlagImagesSet.addAll(ditaValReader.getRelFlagImageList());
filterUtils = new FilterUtils(printTranstype.contains(transtype), ditaValReader.getFilterMap(),
ditaValReader.getForegroundConflictColor(), ditaValReader.getBackgroundConflictColor());
} else {
filterUtils = new FilterUtils(printTranstype.contains(transtype));
}
filterUtils.setLogger(logger);
return filterUtils;
} | java | private FilterUtils parseFilterFile() {
final FilterUtils filterUtils;
if (ditavalFile != null) {
final DitaValReader ditaValReader = new DitaValReader();
ditaValReader.setLogger(logger);
ditaValReader.setJob(job);
ditaValReader.read(ditavalFile.toURI());
flagImageSet.addAll(ditaValReader.getImageList());
relFlagImagesSet.addAll(ditaValReader.getRelFlagImageList());
filterUtils = new FilterUtils(printTranstype.contains(transtype), ditaValReader.getFilterMap(),
ditaValReader.getForegroundConflictColor(), ditaValReader.getBackgroundConflictColor());
} else {
filterUtils = new FilterUtils(printTranstype.contains(transtype));
}
filterUtils.setLogger(logger);
return filterUtils;
} | [
"private",
"FilterUtils",
"parseFilterFile",
"(",
")",
"{",
"final",
"FilterUtils",
"filterUtils",
";",
"if",
"(",
"ditavalFile",
"!=",
"null",
")",
"{",
"final",
"DitaValReader",
"ditaValReader",
"=",
"new",
"DitaValReader",
"(",
")",
";",
"ditaValReader",
".",... | Parse filter file
@return configured filter utility | [
"Parse",
"filter",
"file"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/reader/AbstractReaderModule.java#L557-L573 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/writer/DitaWriterFilter.java | DitaWriterFilter.getAttributeValue | private String getAttributeValue(final String elemQName, final QName attQName, final String value) {
if (StringUtils.isEmptyString(value) && !defaultValueMap.isEmpty()) {
final Map<String, String> defaultMap = defaultValueMap.get(attQName);
if (defaultMap != null) {
final String defaultValue = defaultMap.get(elemQName);
if (defaultValue != null) {
return defaultValue;
}
}
}
return value;
} | java | private String getAttributeValue(final String elemQName, final QName attQName, final String value) {
if (StringUtils.isEmptyString(value) && !defaultValueMap.isEmpty()) {
final Map<String, String> defaultMap = defaultValueMap.get(attQName);
if (defaultMap != null) {
final String defaultValue = defaultMap.get(elemQName);
if (defaultValue != null) {
return defaultValue;
}
}
}
return value;
} | [
"private",
"String",
"getAttributeValue",
"(",
"final",
"String",
"elemQName",
",",
"final",
"QName",
"attQName",
",",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmptyString",
"(",
"value",
")",
"&&",
"!",
"defaultValueMap",
".",
... | Get attribute value or default if attribute is not defined
@param elemQName element QName
@param attQName attribute QName
@param value attribute value
@return attribute value or default | [
"Get",
"attribute",
"value",
"or",
"default",
"if",
"attribute",
"is",
"not",
"defined"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/writer/DitaWriterFilter.java#L180-L191 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/writer/DitaWriterFilter.java | DitaWriterFilter.replaceHREF | private URI replaceHREF(final QName attName, final Attributes atts) {
URI attValue = toURI(atts.getValue(attName.getNamespaceURI(), attName.getLocalPart()));
if (attValue != null) {
final String fragment = attValue.getFragment();
if (fragment != null) {
attValue = stripFragment(attValue);
}
if (attValue.toString().length() != 0) {
final URI current = currentFile.resolve(attValue);
final FileInfo f = job.getFileInfo(current);
if (f != null) {
final FileInfo cfi = job.getFileInfo(currentFile);
final URI currrentFileTemp = job.tempDirURI.resolve(cfi.uri);
final URI targetTemp = job.tempDirURI.resolve(f.uri);
attValue = getRelativePath(currrentFileTemp, targetTemp);
} else if (tempFileNameScheme != null) {
final URI currrentFileTemp = job.tempDirURI.resolve(tempFileNameScheme.generateTempFileName(currentFile));
final URI targetTemp = job.tempDirURI.resolve(tempFileNameScheme.generateTempFileName(current));
final URI relativePath = getRelativePath(currrentFileTemp, targetTemp);
attValue = relativePath;
} else {
attValue = getRelativePath(currentFile, current);
}
}
if (fragment != null) {
attValue = setFragment(attValue, fragment);
}
} else {
return null;
}
return attValue;
} | java | private URI replaceHREF(final QName attName, final Attributes atts) {
URI attValue = toURI(atts.getValue(attName.getNamespaceURI(), attName.getLocalPart()));
if (attValue != null) {
final String fragment = attValue.getFragment();
if (fragment != null) {
attValue = stripFragment(attValue);
}
if (attValue.toString().length() != 0) {
final URI current = currentFile.resolve(attValue);
final FileInfo f = job.getFileInfo(current);
if (f != null) {
final FileInfo cfi = job.getFileInfo(currentFile);
final URI currrentFileTemp = job.tempDirURI.resolve(cfi.uri);
final URI targetTemp = job.tempDirURI.resolve(f.uri);
attValue = getRelativePath(currrentFileTemp, targetTemp);
} else if (tempFileNameScheme != null) {
final URI currrentFileTemp = job.tempDirURI.resolve(tempFileNameScheme.generateTempFileName(currentFile));
final URI targetTemp = job.tempDirURI.resolve(tempFileNameScheme.generateTempFileName(current));
final URI relativePath = getRelativePath(currrentFileTemp, targetTemp);
attValue = relativePath;
} else {
attValue = getRelativePath(currentFile, current);
}
}
if (fragment != null) {
attValue = setFragment(attValue, fragment);
}
} else {
return null;
}
return attValue;
} | [
"private",
"URI",
"replaceHREF",
"(",
"final",
"QName",
"attName",
",",
"final",
"Attributes",
"atts",
")",
"{",
"URI",
"attValue",
"=",
"toURI",
"(",
"atts",
".",
"getValue",
"(",
"attName",
".",
"getNamespaceURI",
"(",
")",
",",
"attName",
".",
"getLocal... | Relativize absolute references if possible.
@param attName attribute name
@param atts attributes
@return attribute value, may be {@code null} | [
"Relativize",
"absolute",
"references",
"if",
"possible",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/writer/DitaWriterFilter.java#L200-L231 | train |
dita-ot/dita-ot | src/main/plugins/org.dita.pdf2/src/com/idiominc/ws/opentopic/fo/i18n/Configuration.java | Configuration.getAlphabetForChar | public Alphabet getAlphabetForChar(final char theChar) {
Alphabet result = null;
for (final Alphabet alphabet : this.alphabets) {
if (alphabet.isContain(theChar)) {
result = alphabet;
break;
}
}
return result;
} | java | public Alphabet getAlphabetForChar(final char theChar) {
Alphabet result = null;
for (final Alphabet alphabet : this.alphabets) {
if (alphabet.isContain(theChar)) {
result = alphabet;
break;
}
}
return result;
} | [
"public",
"Alphabet",
"getAlphabetForChar",
"(",
"final",
"char",
"theChar",
")",
"{",
"Alphabet",
"result",
"=",
"null",
";",
"for",
"(",
"final",
"Alphabet",
"alphabet",
":",
"this",
".",
"alphabets",
")",
"{",
"if",
"(",
"alphabet",
".",
"isContain",
"(... | Searches alphabets for a char
@return first founded alphabet that contains given char
or <code>null</code> if no alphabets contains given char. | [
"Searches",
"alphabets",
"for",
"a",
"char"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/plugins/org.dita.pdf2/src/com/idiominc/ws/opentopic/fo/i18n/Configuration.java#L64-L73 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.correct | public static URL correct(final File file) throws MalformedURLException {
if (file == null) {
throw new MalformedURLException("The url is null");
}
return new URL(correct(file.toURI().toString(), true));
} | java | public static URL correct(final File file) throws MalformedURLException {
if (file == null) {
throw new MalformedURLException("The url is null");
}
return new URL(correct(file.toURI().toString(), true));
} | [
"public",
"static",
"URL",
"correct",
"(",
"final",
"File",
"file",
")",
"throws",
"MalformedURLException",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"throw",
"new",
"MalformedURLException",
"(",
"\"The url is null\"",
")",
";",
"}",
"return",
"new",
"... | Corrects the file to URL.
@param file
The file to be corrected. If null will throw
MalformedURLException.
@return a corrected URL. Never null.
@exception MalformedURLException
when the argument is null. | [
"Corrects",
"the",
"file",
"to",
"URL",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L45-L50 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.correct | public static URL correct(final URL url) throws MalformedURLException {
if (url == null) {
throw new MalformedURLException("The url is null");
}
return new URL(correct(url.toString(), false));
} | java | public static URL correct(final URL url) throws MalformedURLException {
if (url == null) {
throw new MalformedURLException("The url is null");
}
return new URL(correct(url.toString(), false));
} | [
"public",
"static",
"URL",
"correct",
"(",
"final",
"URL",
"url",
")",
"throws",
"MalformedURLException",
"{",
"if",
"(",
"url",
"==",
"null",
")",
"{",
"throw",
"new",
"MalformedURLException",
"(",
"\"The url is null\"",
")",
";",
"}",
"return",
"new",
"URL... | Corrects an URL.
@param url
The URL to be corrected. If null will throw
MalformedURLException.
@return a corrected URL. Never null.
@exception MalformedURLException
when the argument is null. | [
"Corrects",
"an",
"URL",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L62-L67 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.getCanonicalFileFromFileUrl | public static File getCanonicalFileFromFileUrl(final URL url) {
File file = null;
if (url == null) {
throw new NullPointerException("The URL cannot be null.");
}
if ("file".equals(url.getProtocol())) {
final String fileName = url.getFile();
final String path = URLUtils.uncorrect(fileName);
file = new File(path);
try {
file = file.getCanonicalFile();
} catch (final IOException e) {
// Does not exist.
file = file.getAbsoluteFile();
}
}
return file;
} | java | public static File getCanonicalFileFromFileUrl(final URL url) {
File file = null;
if (url == null) {
throw new NullPointerException("The URL cannot be null.");
}
if ("file".equals(url.getProtocol())) {
final String fileName = url.getFile();
final String path = URLUtils.uncorrect(fileName);
file = new File(path);
try {
file = file.getCanonicalFile();
} catch (final IOException e) {
// Does not exist.
file = file.getAbsoluteFile();
}
}
return file;
} | [
"public",
"static",
"File",
"getCanonicalFileFromFileUrl",
"(",
"final",
"URL",
"url",
")",
"{",
"File",
"file",
"=",
"null",
";",
"if",
"(",
"url",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"The URL cannot be null.\"",
")",
";",
... | On Windows names of files from network neighborhood must be corrected
before open.
@param url
The file URL.
@return The canonical or absolute file, or null if the protocol is not
file. | [
"On",
"Windows",
"names",
"of",
"files",
"from",
"network",
"neighborhood",
"must",
"be",
"corrected",
"before",
"open",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L179-L198 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.correct | private static String correct(String url, final boolean forceCorrection) {
if (url == null) {
return null;
}
final String initialUrl = url;
// If there is a % that means the URL was already corrected.
if (!forceCorrection && url.contains("%")) {
return initialUrl;
}
// Extract the reference (anchor) part from the URL. The '#' char identifying the anchor
// must not be corrected.
String reference = null;
if (!forceCorrection) {
final int refIndex = url.lastIndexOf('#');
if (refIndex != -1) {
reference = FilePathToURI.filepath2URI(url.substring(refIndex + 1));
url = url.substring(0, refIndex);
}
}
// Buffer where eventual query string will be processed.
StringBuilder queryBuffer = null;
if (!forceCorrection) {
final int queryIndex = url.indexOf('?');
if (queryIndex != -1) {
// We have a query
final String query = url.substring(queryIndex + 1);
url = url.substring(0, queryIndex);
queryBuffer = new StringBuilder(query.length());
// Tokenize by &
final StringTokenizer st = new StringTokenizer(query, "&");
while (st.hasMoreElements()) {
String token = st.nextToken();
token = FilePathToURI.filepath2URI(token);
// Correct token
queryBuffer.append(token);
if (st.hasMoreElements()) {
queryBuffer.append("&");
}
}
}
}
String toReturn = FilePathToURI.filepath2URI(url);
if (queryBuffer != null) {
// Append to the end the corrected query.
toReturn += "?" + queryBuffer.toString();
}
if (reference != null) {
// Append the reference to the end the corrected query.
toReturn += "#" + reference;
}
return toReturn;
} | java | private static String correct(String url, final boolean forceCorrection) {
if (url == null) {
return null;
}
final String initialUrl = url;
// If there is a % that means the URL was already corrected.
if (!forceCorrection && url.contains("%")) {
return initialUrl;
}
// Extract the reference (anchor) part from the URL. The '#' char identifying the anchor
// must not be corrected.
String reference = null;
if (!forceCorrection) {
final int refIndex = url.lastIndexOf('#');
if (refIndex != -1) {
reference = FilePathToURI.filepath2URI(url.substring(refIndex + 1));
url = url.substring(0, refIndex);
}
}
// Buffer where eventual query string will be processed.
StringBuilder queryBuffer = null;
if (!forceCorrection) {
final int queryIndex = url.indexOf('?');
if (queryIndex != -1) {
// We have a query
final String query = url.substring(queryIndex + 1);
url = url.substring(0, queryIndex);
queryBuffer = new StringBuilder(query.length());
// Tokenize by &
final StringTokenizer st = new StringTokenizer(query, "&");
while (st.hasMoreElements()) {
String token = st.nextToken();
token = FilePathToURI.filepath2URI(token);
// Correct token
queryBuffer.append(token);
if (st.hasMoreElements()) {
queryBuffer.append("&");
}
}
}
}
String toReturn = FilePathToURI.filepath2URI(url);
if (queryBuffer != null) {
// Append to the end the corrected query.
toReturn += "?" + queryBuffer.toString();
}
if (reference != null) {
// Append the reference to the end the corrected query.
toReturn += "#" + reference;
}
return toReturn;
} | [
"private",
"static",
"String",
"correct",
"(",
"String",
"url",
",",
"final",
"boolean",
"forceCorrection",
")",
"{",
"if",
"(",
"url",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"String",
"initialUrl",
"=",
"url",
";",
"// If there is a ... | Method introduced to correct the URLs in the default machine encoding.
@param url
The URL to be corrected. If it contains a % char, it means it
already was corrected, so it will be returned. Take care at
composing URLs from a corrected part and an uncorrected part.
Correcting the result will not work. Try to correct first the
relative part.
@param forceCorrection
True if the correction must be executed any way (for files
containing % for example - the % will be also corrected). Also
if <code>true</code> '#' and '?' will be corrected otherwise
will consider that is an URL that contains an anchor or a
query.
@return The corrected URL. | [
"Method",
"introduced",
"to",
"correct",
"the",
"URLs",
"in",
"the",
"default",
"machine",
"encoding",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L216-L273 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.getURL | public static String getURL(final String fileName) {
if (fileName.startsWith("file:/")) {
return fileName;
} else {
final File file = new File(fileName);
return file.toURI().toString();
}
} | java | public static String getURL(final String fileName) {
if (fileName.startsWith("file:/")) {
return fileName;
} else {
final File file = new File(fileName);
return file.toURI().toString();
}
} | [
"public",
"static",
"String",
"getURL",
"(",
"final",
"String",
"fileName",
")",
"{",
"if",
"(",
"fileName",
".",
"startsWith",
"(",
"\"file:/\"",
")",
")",
"{",
"return",
"fileName",
";",
"}",
"else",
"{",
"final",
"File",
"file",
"=",
"new",
"File",
... | Convert a file name to url.
@param fileName -
The file name string.
@return string -
URL | [
"Convert",
"a",
"file",
"name",
"to",
"url",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L282-L291 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.isAbsolute | public static boolean isAbsolute(final URI uri) {
final String p = uri.getPath();
return p != null && p.startsWith(URI_SEPARATOR);
} | java | public static boolean isAbsolute(final URI uri) {
final String p = uri.getPath();
return p != null && p.startsWith(URI_SEPARATOR);
} | [
"public",
"static",
"boolean",
"isAbsolute",
"(",
"final",
"URI",
"uri",
")",
"{",
"final",
"String",
"p",
"=",
"uri",
".",
"getPath",
"(",
")",
";",
"return",
"p",
"!=",
"null",
"&&",
"p",
".",
"startsWith",
"(",
"URI_SEPARATOR",
")",
";",
"}"
] | Test if URI path is absolute. | [
"Test",
"if",
"URI",
"path",
"is",
"absolute",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L427-L430 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.toFile | public static File toFile(final URI filename) {
if (filename == null) {
return null;
}
final URI f = stripFragment(filename);
if ("file".equals(f.getScheme()) && f.getPath() != null && f.isAbsolute()) {
return new File(f);
} else {
return toFile(f.toString());
}
} | java | public static File toFile(final URI filename) {
if (filename == null) {
return null;
}
final URI f = stripFragment(filename);
if ("file".equals(f.getScheme()) && f.getPath() != null && f.isAbsolute()) {
return new File(f);
} else {
return toFile(f.toString());
}
} | [
"public",
"static",
"File",
"toFile",
"(",
"final",
"URI",
"filename",
")",
"{",
"if",
"(",
"filename",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"URI",
"f",
"=",
"stripFragment",
"(",
"filename",
")",
";",
"if",
"(",
"\"file\"",
"... | Convert URI reference to system file path.
@param filename URI to convert to system file path, may be relative or absolute
@return file path, {@code null} if input was {@code null} | [
"Convert",
"URI",
"reference",
"to",
"system",
"file",
"path",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L438-L448 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.toFile | public static File toFile(final String filename) {
if (filename == null) {
return null;
}
String f;
try {
f = URLDecoder.decode(filename, UTF8);
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
f = f.replace(WINDOWS_SEPARATOR, File.separator).replace(UNIX_SEPARATOR, File.separator);
return new File(f);
} | java | public static File toFile(final String filename) {
if (filename == null) {
return null;
}
String f;
try {
f = URLDecoder.decode(filename, UTF8);
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
f = f.replace(WINDOWS_SEPARATOR, File.separator).replace(UNIX_SEPARATOR, File.separator);
return new File(f);
} | [
"public",
"static",
"File",
"toFile",
"(",
"final",
"String",
"filename",
")",
"{",
"if",
"(",
"filename",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"String",
"f",
";",
"try",
"{",
"f",
"=",
"URLDecoder",
".",
"decode",
"(",
"filename",
","... | Convert URI or chimera references to file paths.
@param filename file reference
@return file path, {@code null} if input was {@code null} | [
"Convert",
"URI",
"or",
"chimera",
"references",
"to",
"file",
"paths",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L456-L468 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.toURI | public static URI toURI(final String file) {
if (file == null) {
return null;
}
if (File.separatorChar == '\\' && file.indexOf('\\') != -1) {
return toURI(new File(file));
}
try {
return new URI(file);
} catch (final URISyntaxException e) {
try {
return new URI(clean(file.replace(WINDOWS_SEPARATOR, URI_SEPARATOR).trim(), false));
} catch (final URISyntaxException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
} | java | public static URI toURI(final String file) {
if (file == null) {
return null;
}
if (File.separatorChar == '\\' && file.indexOf('\\') != -1) {
return toURI(new File(file));
}
try {
return new URI(file);
} catch (final URISyntaxException e) {
try {
return new URI(clean(file.replace(WINDOWS_SEPARATOR, URI_SEPARATOR).trim(), false));
} catch (final URISyntaxException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
} | [
"public",
"static",
"URI",
"toURI",
"(",
"final",
"String",
"file",
")",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"File",
".",
"separatorChar",
"==",
"'",
"'",
"&&",
"file",
".",
"indexOf",
"(",
"'",
... | Covert file reference to URI. Fixes directory separators and escapes characters.
@param file The string to be parsed into a URI, may be {@code null}
@return URI from parsing the given string, {@code null} if input was {@code null} | [
"Covert",
"file",
"reference",
"to",
"URI",
".",
"Fixes",
"directory",
"separators",
"and",
"escapes",
"characters",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L499-L515 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.setFragment | public static URI setFragment(final URI path, final String fragment) {
try {
if (path.getPath() != null) {
return new URI(path.getScheme(), path.getUserInfo(), path.getHost(), path.getPort(), path.getPath(), path.getQuery(), fragment);
} else {
return new URI(path.getScheme(), path.getSchemeSpecificPart(), fragment);
}
} catch (final URISyntaxException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | java | public static URI setFragment(final URI path, final String fragment) {
try {
if (path.getPath() != null) {
return new URI(path.getScheme(), path.getUserInfo(), path.getHost(), path.getPort(), path.getPath(), path.getQuery(), fragment);
} else {
return new URI(path.getScheme(), path.getSchemeSpecificPart(), fragment);
}
} catch (final URISyntaxException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | [
"public",
"static",
"URI",
"setFragment",
"(",
"final",
"URI",
"path",
",",
"final",
"String",
"fragment",
")",
"{",
"try",
"{",
"if",
"(",
"path",
".",
"getPath",
"(",
")",
"!=",
"null",
")",
"{",
"return",
"new",
"URI",
"(",
"path",
".",
"getScheme... | Create new URI with a given fragment.
@param path URI to set fragment on
@param fragment new fragment, {@code null} for no fragment
@return new URI instance with given fragment | [
"Create",
"new",
"URI",
"with",
"a",
"given",
"fragment",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L551-L561 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.setPath | public static URI setPath(final URI orig, final String path) {
try {
return new URI(orig.getScheme(), orig.getUserInfo(), orig.getHost(), orig.getPort(), path, orig.getQuery(), orig.getFragment());
} catch (final URISyntaxException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | java | public static URI setPath(final URI orig, final String path) {
try {
return new URI(orig.getScheme(), orig.getUserInfo(), orig.getHost(), orig.getPort(), path, orig.getQuery(), orig.getFragment());
} catch (final URISyntaxException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | [
"public",
"static",
"URI",
"setPath",
"(",
"final",
"URI",
"orig",
",",
"final",
"String",
"path",
")",
"{",
"try",
"{",
"return",
"new",
"URI",
"(",
"orig",
".",
"getScheme",
"(",
")",
",",
"orig",
".",
"getUserInfo",
"(",
")",
",",
"orig",
".",
"... | Create new URI with a given path.
@param orig URI to set path on
@param path new path, {@code null} for no path
@return new URI instance with given path | [
"Create",
"new",
"URI",
"with",
"a",
"given",
"path",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L570-L576 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.setScheme | public static URI setScheme(final URI orig, final String scheme) {
try {
return new URI(scheme, orig.getUserInfo(), orig.getHost(), orig.getPort(), orig.getPath(), orig.getQuery(), orig.getFragment());
} catch (final URISyntaxException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | java | public static URI setScheme(final URI orig, final String scheme) {
try {
return new URI(scheme, orig.getUserInfo(), orig.getHost(), orig.getPort(), orig.getPath(), orig.getQuery(), orig.getFragment());
} catch (final URISyntaxException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | [
"public",
"static",
"URI",
"setScheme",
"(",
"final",
"URI",
"orig",
",",
"final",
"String",
"scheme",
")",
"{",
"try",
"{",
"return",
"new",
"URI",
"(",
"scheme",
",",
"orig",
".",
"getUserInfo",
"(",
")",
",",
"orig",
".",
"getHost",
"(",
")",
",",... | Create new URI with a given scheme.
@param orig URI to set scheme on
@param scheme new scheme, {@code null} for no scheme
@return new URI instance with given path | [
"Create",
"new",
"URI",
"with",
"a",
"given",
"scheme",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L585-L591 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.getRelativePath | public static URI getRelativePath(final URI base, final URI ref) {
final String baseScheme = base.getScheme();
final String refScheme = ref.getScheme();
final String baseAuth = base.getAuthority();
final String refAuth = ref.getAuthority();
if (!(((baseScheme == null && refScheme == null) || (baseScheme != null && refScheme != null && baseScheme.equals(refScheme))) &&
((baseAuth == null && refAuth == null) || (baseAuth != null && refAuth != null && baseAuth.equals(refAuth))))) {
return ref;
}
URI rel;
if (base.getPath().equals(ref.getPath()) && ref.getFragment() != null) {
rel = toURI("");
} else {
final StringBuilder upPathBuffer = new StringBuilder(128);
final StringBuilder downPathBuffer = new StringBuilder(128);
String basePath = base.normalize().getPath();
if (basePath.endsWith("/")) {
basePath = basePath + "dummy";
}
String refPath = ref.normalize().getPath();
final StringTokenizer baseTokenizer = new StringTokenizer(basePath, URI_SEPARATOR);
final StringTokenizer refTokenizer = new StringTokenizer(refPath, URI_SEPARATOR);
while (baseTokenizer.countTokens() > 1 && refTokenizer.countTokens() > 1) {
final String baseToken = baseTokenizer.nextToken();
final String refToken = refTokenizer.nextToken();
//if OS is Windows, we need to ignore case when comparing path names.
final boolean equals = OS_NAME.toLowerCase().contains(OS_NAME_WINDOWS)
? baseToken.equalsIgnoreCase(refToken)
: baseToken.equals(refToken);
if (!equals) {
if (baseToken.endsWith(COLON) || refToken.endsWith(COLON)) {
//the two files are in different disks under Windows
return ref;
}
upPathBuffer.append("..");
upPathBuffer.append(URI_SEPARATOR);
downPathBuffer.append(refToken);
downPathBuffer.append(URI_SEPARATOR);
break;
}
}
while (baseTokenizer.countTokens() > 1) {
baseTokenizer.nextToken();
upPathBuffer.append("..");
upPathBuffer.append(URI_SEPARATOR);
}
while (refTokenizer.hasMoreTokens()) {
downPathBuffer.append(refTokenizer.nextToken());
if (refTokenizer.hasMoreTokens()) {
downPathBuffer.append(URI_SEPARATOR);
}
}
upPathBuffer.append(downPathBuffer);
try {
rel = new URI(null, null, upPathBuffer.toString(), null, null);
} catch (final URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
return setFragment(rel, ref.getFragment());
} | java | public static URI getRelativePath(final URI base, final URI ref) {
final String baseScheme = base.getScheme();
final String refScheme = ref.getScheme();
final String baseAuth = base.getAuthority();
final String refAuth = ref.getAuthority();
if (!(((baseScheme == null && refScheme == null) || (baseScheme != null && refScheme != null && baseScheme.equals(refScheme))) &&
((baseAuth == null && refAuth == null) || (baseAuth != null && refAuth != null && baseAuth.equals(refAuth))))) {
return ref;
}
URI rel;
if (base.getPath().equals(ref.getPath()) && ref.getFragment() != null) {
rel = toURI("");
} else {
final StringBuilder upPathBuffer = new StringBuilder(128);
final StringBuilder downPathBuffer = new StringBuilder(128);
String basePath = base.normalize().getPath();
if (basePath.endsWith("/")) {
basePath = basePath + "dummy";
}
String refPath = ref.normalize().getPath();
final StringTokenizer baseTokenizer = new StringTokenizer(basePath, URI_SEPARATOR);
final StringTokenizer refTokenizer = new StringTokenizer(refPath, URI_SEPARATOR);
while (baseTokenizer.countTokens() > 1 && refTokenizer.countTokens() > 1) {
final String baseToken = baseTokenizer.nextToken();
final String refToken = refTokenizer.nextToken();
//if OS is Windows, we need to ignore case when comparing path names.
final boolean equals = OS_NAME.toLowerCase().contains(OS_NAME_WINDOWS)
? baseToken.equalsIgnoreCase(refToken)
: baseToken.equals(refToken);
if (!equals) {
if (baseToken.endsWith(COLON) || refToken.endsWith(COLON)) {
//the two files are in different disks under Windows
return ref;
}
upPathBuffer.append("..");
upPathBuffer.append(URI_SEPARATOR);
downPathBuffer.append(refToken);
downPathBuffer.append(URI_SEPARATOR);
break;
}
}
while (baseTokenizer.countTokens() > 1) {
baseTokenizer.nextToken();
upPathBuffer.append("..");
upPathBuffer.append(URI_SEPARATOR);
}
while (refTokenizer.hasMoreTokens()) {
downPathBuffer.append(refTokenizer.nextToken());
if (refTokenizer.hasMoreTokens()) {
downPathBuffer.append(URI_SEPARATOR);
}
}
upPathBuffer.append(downPathBuffer);
try {
rel = new URI(null, null, upPathBuffer.toString(), null, null);
} catch (final URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
return setFragment(rel, ref.getFragment());
} | [
"public",
"static",
"URI",
"getRelativePath",
"(",
"final",
"URI",
"base",
",",
"final",
"URI",
"ref",
")",
"{",
"final",
"String",
"baseScheme",
"=",
"base",
".",
"getScheme",
"(",
")",
";",
"final",
"String",
"refScheme",
"=",
"ref",
".",
"getScheme",
... | Resolves absolute URI against another absolute URI.
@param base absolute base file URI
@param ref absolute reference file URI
@return relative URI if possible, otherwise original reference file URI argument | [
"Resolves",
"absolute",
"URI",
"against",
"another",
"absolute",
"URI",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L600-L666 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.setElementID | public static URI setElementID(final URI relativePath, final String id) {
String topic = getTopicID(relativePath);
if (topic != null) {
return setFragment(relativePath, topic + (id != null ? SLASH + id : ""));
} else if (id == null) {
return stripFragment(relativePath);
} else {
throw new IllegalArgumentException(relativePath.toString());
}
} | java | public static URI setElementID(final URI relativePath, final String id) {
String topic = getTopicID(relativePath);
if (topic != null) {
return setFragment(relativePath, topic + (id != null ? SLASH + id : ""));
} else if (id == null) {
return stripFragment(relativePath);
} else {
throw new IllegalArgumentException(relativePath.toString());
}
} | [
"public",
"static",
"URI",
"setElementID",
"(",
"final",
"URI",
"relativePath",
",",
"final",
"String",
"id",
")",
"{",
"String",
"topic",
"=",
"getTopicID",
"(",
"relativePath",
")",
";",
"if",
"(",
"topic",
"!=",
"null",
")",
"{",
"return",
"setFragment"... | Set the element ID from the path
@param relativePath path
@param id element ID
@return element ID, may be {@code null} | [
"Set",
"the",
"element",
"ID",
"from",
"the",
"path"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L722-L731 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.getElementID | public static String getElementID(final String relativePath) {
final String fragment = FileUtils.getFragment(relativePath);
if (fragment != null) {
if (fragment.lastIndexOf(SLASH) != -1) {
final String id = fragment.substring(fragment.lastIndexOf(SLASH) + 1);
return id.isEmpty() ? null : id;
}
}
return null;
} | java | public static String getElementID(final String relativePath) {
final String fragment = FileUtils.getFragment(relativePath);
if (fragment != null) {
if (fragment.lastIndexOf(SLASH) != -1) {
final String id = fragment.substring(fragment.lastIndexOf(SLASH) + 1);
return id.isEmpty() ? null : id;
}
}
return null;
} | [
"public",
"static",
"String",
"getElementID",
"(",
"final",
"String",
"relativePath",
")",
"{",
"final",
"String",
"fragment",
"=",
"FileUtils",
".",
"getFragment",
"(",
"relativePath",
")",
";",
"if",
"(",
"fragment",
"!=",
"null",
")",
"{",
"if",
"(",
"f... | Retrieve the element ID from the path
@param relativePath path
@return element ID, may be {@code null} | [
"Retrieve",
"the",
"element",
"ID",
"from",
"the",
"path"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L739-L748 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/URLUtils.java | URLUtils.getTopicID | public static String getTopicID(final URI relativePath) {
final String fragment = relativePath.getFragment();
if (fragment != null) {
final String id = fragment.lastIndexOf(SLASH) != -1
? fragment.substring(0, fragment.lastIndexOf(SLASH))
: fragment;
return id.isEmpty() ? null : id;
}
return null;
} | java | public static String getTopicID(final URI relativePath) {
final String fragment = relativePath.getFragment();
if (fragment != null) {
final String id = fragment.lastIndexOf(SLASH) != -1
? fragment.substring(0, fragment.lastIndexOf(SLASH))
: fragment;
return id.isEmpty() ? null : id;
}
return null;
} | [
"public",
"static",
"String",
"getTopicID",
"(",
"final",
"URI",
"relativePath",
")",
"{",
"final",
"String",
"fragment",
"=",
"relativePath",
".",
"getFragment",
"(",
")",
";",
"if",
"(",
"fragment",
"!=",
"null",
")",
"{",
"final",
"String",
"id",
"=",
... | Retrieve the topic ID from the path
@param relativePath path
@return topic ID, may be {@code null} | [
"Retrieve",
"the",
"topic",
"ID",
"from",
"the",
"path"
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L756-L765 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/StringUtils.java | StringUtils.join | @SuppressWarnings("rawtypes")
public static String join(final Collection coll, final String delim) {
final StringBuilder buff = new StringBuilder(256);
Iterator iter;
if ((coll == null) || coll.isEmpty()) {
return "";
}
iter = coll.iterator();
while (iter.hasNext()) {
buff.append(iter.next().toString());
if (iter.hasNext()) {
buff.append(delim);
}
}
return buff.toString();
} | java | @SuppressWarnings("rawtypes")
public static String join(final Collection coll, final String delim) {
final StringBuilder buff = new StringBuilder(256);
Iterator iter;
if ((coll == null) || coll.isEmpty()) {
return "";
}
iter = coll.iterator();
while (iter.hasNext()) {
buff.append(iter.next().toString());
if (iter.hasNext()) {
buff.append(delim);
}
}
return buff.toString();
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"static",
"String",
"join",
"(",
"final",
"Collection",
"coll",
",",
"final",
"String",
"delim",
")",
"{",
"final",
"StringBuilder",
"buff",
"=",
"new",
"StringBuilder",
"(",
"256",
")",
";",
"Iter... | Assemble all elements in collection to a string.
@param coll -
java.util.List
@param delim -
Description of the Parameter
@return java.lang.String | [
"Assemble",
"all",
"elements",
"in",
"collection",
"to",
"a",
"string",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L42-L61 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/StringUtils.java | StringUtils.join | @SuppressWarnings({ "rawtypes", "unchecked" })
public static String join(final Map value, final String delim) {
if (value == null || value.isEmpty()) {
return "";
}
final StringBuilder buf = new StringBuilder();
for (final Iterator<Map.Entry<String, String>> i = value.entrySet().iterator(); i.hasNext();) {
final Map.Entry<String, String> e = i.next();
buf.append(e.getKey()).append(EQUAL).append(e.getValue());
if (i.hasNext()) {
buf.append(delim);
}
}
return buf.toString();
} | java | @SuppressWarnings({ "rawtypes", "unchecked" })
public static String join(final Map value, final String delim) {
if (value == null || value.isEmpty()) {
return "";
}
final StringBuilder buf = new StringBuilder();
for (final Iterator<Map.Entry<String, String>> i = value.entrySet().iterator(); i.hasNext();) {
final Map.Entry<String, String> e = i.next();
buf.append(e.getKey()).append(EQUAL).append(e.getValue());
if (i.hasNext()) {
buf.append(delim);
}
}
return buf.toString();
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"public",
"static",
"String",
"join",
"(",
"final",
"Map",
"value",
",",
"final",
"String",
"delim",
")",
"{",
"if",
"(",
"value",
"==",
"null",
"||",
"value",
".",
"isEmp... | Assemble all elements in map to a string.
@param value map to serializer
@param delim entry delimiter
@return concatenated map | [
"Assemble",
"all",
"elements",
"in",
"map",
"to",
"a",
"string",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L70-L84 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/StringUtils.java | StringUtils.replaceAll | public static String replaceAll(final String input,
final String pattern, final String replacement) {
final StringBuilder result = new StringBuilder();
int startIndex = 0;
int newIndex;
while ((newIndex = input.indexOf(pattern, startIndex)) >= 0) {
result.append(input, startIndex, newIndex);
result.append(replacement);
startIndex = newIndex + pattern.length();
}
result.append(input.substring(startIndex));
return result.toString();
} | java | public static String replaceAll(final String input,
final String pattern, final String replacement) {
final StringBuilder result = new StringBuilder();
int startIndex = 0;
int newIndex;
while ((newIndex = input.indexOf(pattern, startIndex)) >= 0) {
result.append(input, startIndex, newIndex);
result.append(replacement);
startIndex = newIndex + pattern.length();
}
result.append(input.substring(startIndex));
return result.toString();
} | [
"public",
"static",
"String",
"replaceAll",
"(",
"final",
"String",
"input",
",",
"final",
"String",
"pattern",
",",
"final",
"String",
"replacement",
")",
"{",
"final",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
"startIndex"... | Replaces each substring of this string that matches the given string
with the given replacement. Differ from the JDK String.replaceAll function,
this method does not support regular expression based replacement on purpose.
@param input input string
@param pattern This pattern is recognized as it is. It will not solve
as an regular expression.
@param replacement string used to replace with
@return replaced string | [
"Replaces",
"each",
"substring",
"of",
"this",
"string",
"that",
"matches",
"the",
"given",
"string",
"with",
"the",
"given",
"replacement",
".",
"Differ",
"from",
"the",
"JDK",
"String",
".",
"replaceAll",
"function",
"this",
"method",
"does",
"not",
"support... | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L98-L113 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/StringUtils.java | StringUtils.setOrAppend | public static String setOrAppend(final String target, final String value, final boolean withSpace) {
if (target == null) {
return value;
}if(value == null) {
return target;
} else {
if (withSpace && !target.endsWith(STRING_BLANK)) {
return target + STRING_BLANK + value;
} else {
return target + value;
}
}
} | java | public static String setOrAppend(final String target, final String value, final boolean withSpace) {
if (target == null) {
return value;
}if(value == null) {
return target;
} else {
if (withSpace && !target.endsWith(STRING_BLANK)) {
return target + STRING_BLANK + value;
} else {
return target + value;
}
}
} | [
"public",
"static",
"String",
"setOrAppend",
"(",
"final",
"String",
"target",
",",
"final",
"String",
"value",
",",
"final",
"boolean",
"withSpace",
")",
"{",
"if",
"(",
"target",
"==",
"null",
")",
"{",
"return",
"value",
";",
"}",
"if",
"(",
"value",
... | If target is null, return the value; else append value to target.
If withSpace is true, insert a blank between them.
@param target target to be appended
@param value value to append
@param withSpace whether insert a blank
@return processed string | [
"If",
"target",
"is",
"null",
"return",
"the",
"value",
";",
"else",
"append",
"value",
"to",
"target",
".",
"If",
"withSpace",
"is",
"true",
"insert",
"a",
"blank",
"between",
"them",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L179-L191 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/StringUtils.java | StringUtils.getLocale | public static Locale getLocale(final String anEncoding) {
Locale aLocale = null;
String country = null;
String language = null;
String variant;
//Tokenize the string using "-" as the token string as per IETF RFC4646 (superceeds RFC3066).
final StringTokenizer tokenizer = new StringTokenizer(anEncoding, "-");
//We need to know how many tokens we have so we can create a Locale object with the proper constructor.
final int numberOfTokens = tokenizer.countTokens();
if (numberOfTokens == 1) {
final String tempString = tokenizer.nextToken().toLowerCase();
//Note: Newer XML parsers should throw an error if the xml:lang value contains
//underscore. But this is not guaranteed.
//Check to see if some one used "en_US" instead of "en-US".
//If so, the first token will contain "en_US" or "xxx_YYYYYYYY". In this case,
//we will only grab the value for xxx.
final int underscoreIndex = tempString.indexOf("_");
if (underscoreIndex == -1) {
language = tempString;
} else if (underscoreIndex == 2 || underscoreIndex == 3) {
//check is first subtag is two or three characters in length.
language = tempString.substring(0, underscoreIndex);
}
aLocale = new Locale(language);
} else if (numberOfTokens == 2) {
language = tokenizer.nextToken().toLowerCase();
final String subtag2 = tokenizer.nextToken();
//All country tags should be three characters or less.
//If the subtag is longer than three characters, it assumes that
//is a dialect or variant.
if (subtag2.length() <= 3) {
country = subtag2.toUpperCase();
aLocale = new Locale(language, country);
} else if (subtag2.length() > 3 && subtag2.length() <= 8) {
variant = subtag2;
aLocale = new Locale(language, "", variant);
} else if (subtag2.length() > 8) {
//return an error!
}
} else if (numberOfTokens >= 3) {
language = tokenizer.nextToken().toLowerCase();
final String subtag2 = tokenizer.nextToken();
if (subtag2.length() <= 3) {
country = subtag2.toUpperCase();
} else if (subtag2.length() > 3 && subtag2.length() <= 8) {
} else if (subtag2.length() > 8) {
//return an error!
}
variant = tokenizer.nextToken();
aLocale = new Locale(language, country, variant);
} else {
//return an warning or do nothing.
//The xml:lang attribute is empty.
aLocale = new Locale(LANGUAGE_EN,
COUNTRY_US);
}
return aLocale;
} | java | public static Locale getLocale(final String anEncoding) {
Locale aLocale = null;
String country = null;
String language = null;
String variant;
//Tokenize the string using "-" as the token string as per IETF RFC4646 (superceeds RFC3066).
final StringTokenizer tokenizer = new StringTokenizer(anEncoding, "-");
//We need to know how many tokens we have so we can create a Locale object with the proper constructor.
final int numberOfTokens = tokenizer.countTokens();
if (numberOfTokens == 1) {
final String tempString = tokenizer.nextToken().toLowerCase();
//Note: Newer XML parsers should throw an error if the xml:lang value contains
//underscore. But this is not guaranteed.
//Check to see if some one used "en_US" instead of "en-US".
//If so, the first token will contain "en_US" or "xxx_YYYYYYYY". In this case,
//we will only grab the value for xxx.
final int underscoreIndex = tempString.indexOf("_");
if (underscoreIndex == -1) {
language = tempString;
} else if (underscoreIndex == 2 || underscoreIndex == 3) {
//check is first subtag is two or three characters in length.
language = tempString.substring(0, underscoreIndex);
}
aLocale = new Locale(language);
} else if (numberOfTokens == 2) {
language = tokenizer.nextToken().toLowerCase();
final String subtag2 = tokenizer.nextToken();
//All country tags should be three characters or less.
//If the subtag is longer than three characters, it assumes that
//is a dialect or variant.
if (subtag2.length() <= 3) {
country = subtag2.toUpperCase();
aLocale = new Locale(language, country);
} else if (subtag2.length() > 3 && subtag2.length() <= 8) {
variant = subtag2;
aLocale = new Locale(language, "", variant);
} else if (subtag2.length() > 8) {
//return an error!
}
} else if (numberOfTokens >= 3) {
language = tokenizer.nextToken().toLowerCase();
final String subtag2 = tokenizer.nextToken();
if (subtag2.length() <= 3) {
country = subtag2.toUpperCase();
} else if (subtag2.length() > 3 && subtag2.length() <= 8) {
} else if (subtag2.length() > 8) {
//return an error!
}
variant = tokenizer.nextToken();
aLocale = new Locale(language, country, variant);
} else {
//return an warning or do nothing.
//The xml:lang attribute is empty.
aLocale = new Locale(LANGUAGE_EN,
COUNTRY_US);
}
return aLocale;
} | [
"public",
"static",
"Locale",
"getLocale",
"(",
"final",
"String",
"anEncoding",
")",
"{",
"Locale",
"aLocale",
"=",
"null",
";",
"String",
"country",
"=",
"null",
";",
"String",
"language",
"=",
"null",
";",
"String",
"variant",
";",
"//Tokenize the string us... | Return a Java Locale object.
@param anEncoding encoding
@return locale
@throws NullPointerException when anEncoding parameter is {@code null} | [
"Return",
"a",
"Java",
"Locale",
"object",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L200-L275 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/StringUtils.java | StringUtils.escapeRegExp | public static String escapeRegExp(final String value) {
final StringBuilder buff = new StringBuilder();
if (value == null || value.length() == 0) {
return "";
}
int index = 0;
// $( )+.[^{\
while (index < value.length()) {
final char current = value.charAt(index);
switch (current) {
case '.':
buff.append("\\.");
break;
// case '/':
// case '|':
case '\\':
buff.append("[\\\\|/]");
break;
case '(':
buff.append("\\(");
break;
case ')':
buff.append("\\)");
break;
case '[':
buff.append("\\[");
break;
case ']':
buff.append("\\]");
break;
case '{':
buff.append("\\{");
break;
case '}':
buff.append("\\}");
break;
case '^':
buff.append("\\^");
break;
case '+':
buff.append("\\+");
break;
case '$':
buff.append("\\$");
break;
default:
buff.append(current);
}
index++;
}
return buff.toString();
} | java | public static String escapeRegExp(final String value) {
final StringBuilder buff = new StringBuilder();
if (value == null || value.length() == 0) {
return "";
}
int index = 0;
// $( )+.[^{\
while (index < value.length()) {
final char current = value.charAt(index);
switch (current) {
case '.':
buff.append("\\.");
break;
// case '/':
// case '|':
case '\\':
buff.append("[\\\\|/]");
break;
case '(':
buff.append("\\(");
break;
case ')':
buff.append("\\)");
break;
case '[':
buff.append("\\[");
break;
case ']':
buff.append("\\]");
break;
case '{':
buff.append("\\{");
break;
case '}':
buff.append("\\}");
break;
case '^':
buff.append("\\^");
break;
case '+':
buff.append("\\+");
break;
case '$':
buff.append("\\$");
break;
default:
buff.append(current);
}
index++;
}
return buff.toString();
} | [
"public",
"static",
"String",
"escapeRegExp",
"(",
"final",
"String",
"value",
")",
"{",
"final",
"StringBuilder",
"buff",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"value",
"==",
"null",
"||",
"value",
".",
"length",
"(",
")",
"==",
"0",
... | Escape regular expression special characters.
@param value input
@return input with regular expression special characters escaped | [
"Escape",
"regular",
"expression",
"special",
"characters",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L283-L334 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/StringUtils.java | StringUtils.normalizeAndCollapseWhitespace | public static void normalizeAndCollapseWhitespace(final StringBuilder strBuffer) {
WhiteSpaceState currentState = WhiteSpaceState.WORD;
for (int i = strBuffer.length() - 1; i >= 0; i--) {
final char currentChar = strBuffer.charAt(i);
if (Character.isWhitespace(currentChar)) {
if (currentState == WhiteSpaceState.SPACE) {
strBuffer.delete(i, i + 1);
} else if (currentChar != ' ') {
strBuffer.replace(i, i + 1, " ");
}
currentState = WhiteSpaceState.SPACE;
} else {
currentState = WhiteSpaceState.WORD;
}
}
} | java | public static void normalizeAndCollapseWhitespace(final StringBuilder strBuffer) {
WhiteSpaceState currentState = WhiteSpaceState.WORD;
for (int i = strBuffer.length() - 1; i >= 0; i--) {
final char currentChar = strBuffer.charAt(i);
if (Character.isWhitespace(currentChar)) {
if (currentState == WhiteSpaceState.SPACE) {
strBuffer.delete(i, i + 1);
} else if (currentChar != ' ') {
strBuffer.replace(i, i + 1, " ");
}
currentState = WhiteSpaceState.SPACE;
} else {
currentState = WhiteSpaceState.WORD;
}
}
} | [
"public",
"static",
"void",
"normalizeAndCollapseWhitespace",
"(",
"final",
"StringBuilder",
"strBuffer",
")",
"{",
"WhiteSpaceState",
"currentState",
"=",
"WhiteSpaceState",
".",
"WORD",
";",
"for",
"(",
"int",
"i",
"=",
"strBuffer",
".",
"length",
"(",
")",
"-... | Normalize and collapse whitespaces from string buffer.
@param strBuffer The string buffer. | [
"Normalize",
"and",
"collapse",
"whitespaces",
"from",
"string",
"buffer",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L344-L359 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/StringUtils.java | StringUtils.split | public static Collection<String> split(final String value) {
if (value == null) {
return Collections.emptyList();
}
final String[] tokens = value.trim().split("\\s+");
return asList(tokens);
} | java | public static Collection<String> split(final String value) {
if (value == null) {
return Collections.emptyList();
}
final String[] tokens = value.trim().split("\\s+");
return asList(tokens);
} | [
"public",
"static",
"Collection",
"<",
"String",
">",
"split",
"(",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}",
"final",
"String",
"[",
"]",
"tokens",
... | Split string by whitespace.
@param value string to split
@return list of tokens | [
"Split",
"string",
"by",
"whitespace",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L367-L373 | train |
dita-ot/dita-ot | src/main/java/org/dita/dost/module/ImageMetadataModule.java | ImageMetadataModule.execute | @Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input)
throws DITAOTException {
if (logger == null) {
throw new IllegalStateException("Logger not set");
}
final Collection<FileInfo> images = job.getFileInfo(f -> ATTR_FORMAT_VALUE_IMAGE.equals(f.format) || ATTR_FORMAT_VALUE_HTML.equals(f.format));
if (!images.isEmpty()) {
final File outputDir = new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR));
final ImageMetadataFilter writer = new ImageMetadataFilter(outputDir, job);
writer.setLogger(logger);
writer.setJob(job);
final Predicate<FileInfo> filter = fileInfoFilter != null
? fileInfoFilter
: f -> !f.isResourceOnly && ATTR_FORMAT_VALUE_DITA.equals(f.format);
for (final FileInfo f : job.getFileInfo(filter)) {
writer.write(new File(job.tempDir, f.file.getPath()).getAbsoluteFile());
}
storeImageFormat(writer.getImages(), outputDir);
try {
job.write();
} catch (IOException e) {
throw new DITAOTException("Failed to serialize job configuration: " + e.getMessage(), e);
}
}
return null;
} | java | @Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input)
throws DITAOTException {
if (logger == null) {
throw new IllegalStateException("Logger not set");
}
final Collection<FileInfo> images = job.getFileInfo(f -> ATTR_FORMAT_VALUE_IMAGE.equals(f.format) || ATTR_FORMAT_VALUE_HTML.equals(f.format));
if (!images.isEmpty()) {
final File outputDir = new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR));
final ImageMetadataFilter writer = new ImageMetadataFilter(outputDir, job);
writer.setLogger(logger);
writer.setJob(job);
final Predicate<FileInfo> filter = fileInfoFilter != null
? fileInfoFilter
: f -> !f.isResourceOnly && ATTR_FORMAT_VALUE_DITA.equals(f.format);
for (final FileInfo f : job.getFileInfo(filter)) {
writer.write(new File(job.tempDir, f.file.getPath()).getAbsoluteFile());
}
storeImageFormat(writer.getImages(), outputDir);
try {
job.write();
} catch (IOException e) {
throw new DITAOTException("Failed to serialize job configuration: " + e.getMessage(), e);
}
}
return null;
} | [
"@",
"Override",
"public",
"AbstractPipelineOutput",
"execute",
"(",
"final",
"AbstractPipelineInput",
"input",
")",
"throws",
"DITAOTException",
"{",
"if",
"(",
"logger",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Logger not set\"",
")... | Entry point of image metadata ModuleElem.
@param input Input parameters and resources.
@return null
@throws DITAOTException exception | [
"Entry",
"point",
"of",
"image",
"metadata",
"ModuleElem",
"."
] | ea776b3c60c03d9f033b6f7ea072349e49dbcdd2 | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/module/ImageMetadataModule.java#L43-L72 | train |
apiman/apiman | manager/api/beans/src/main/java/io/apiman/manager/api/beans/BeanUtils.java | BeanUtils.idFromName | public static final String idFromName(String name) {
Transliterator tr = Transliterator.getInstance("Any-Latin; Latin-ASCII"); //$NON-NLS-1$
return removeNonWord(tr.transliterate(name));
} | java | public static final String idFromName(String name) {
Transliterator tr = Transliterator.getInstance("Any-Latin; Latin-ASCII"); //$NON-NLS-1$
return removeNonWord(tr.transliterate(name));
} | [
"public",
"static",
"final",
"String",
"idFromName",
"(",
"String",
"name",
")",
"{",
"Transliterator",
"tr",
"=",
"Transliterator",
".",
"getInstance",
"(",
"\"Any-Latin; Latin-ASCII\"",
")",
";",
"//$NON-NLS-1$",
"return",
"removeNonWord",
"(",
"tr",
".",
"trans... | Creates a bean id from the given bean name.
@param name the name
@return the id | [
"Creates",
"a",
"bean",
"id",
"from",
"the",
"given",
"bean",
"name",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/beans/src/main/java/io/apiman/manager/api/beans/BeanUtils.java#L35-L38 | train |
apiman/apiman | gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/connectors/ok/HttpURLConnectionImpl.java | HttpURLConnectionImpl.getResponse | private HttpEngine getResponse() throws IOException {
initHttpEngine();
if (httpEngine.hasResponse()) {
return httpEngine;
}
while (true) {
if (!execute(true)) {
continue;
}
Response response = httpEngine.getResponse();
Request followUp = httpEngine.followUpRequest();
if (followUp == null) {
httpEngine.releaseConnection();
return httpEngine;
}
if (++followUpCount > HttpEngine.MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
// The first request was insufficient. Prepare for another...
url = followUp.url();
requestHeaders = followUp.headers().newBuilder();
// Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM redirect
// should keep the same method, Chrome, Firefox and the RI all issue GETs
// when following any redirect.
Sink requestBody = httpEngine.getRequestBody();
if (!followUp.method().equals(method)) {
requestBody = null;
}
if (requestBody != null && !(requestBody instanceof RetryableSink)) {
throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
}
if (!httpEngine.sameConnection(followUp.url())) {
httpEngine.releaseConnection();
}
Connection connection = httpEngine.close();
httpEngine = newHttpEngine(followUp.method(), connection, (RetryableSink) requestBody,
response);
}
} | java | private HttpEngine getResponse() throws IOException {
initHttpEngine();
if (httpEngine.hasResponse()) {
return httpEngine;
}
while (true) {
if (!execute(true)) {
continue;
}
Response response = httpEngine.getResponse();
Request followUp = httpEngine.followUpRequest();
if (followUp == null) {
httpEngine.releaseConnection();
return httpEngine;
}
if (++followUpCount > HttpEngine.MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
// The first request was insufficient. Prepare for another...
url = followUp.url();
requestHeaders = followUp.headers().newBuilder();
// Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM redirect
// should keep the same method, Chrome, Firefox and the RI all issue GETs
// when following any redirect.
Sink requestBody = httpEngine.getRequestBody();
if (!followUp.method().equals(method)) {
requestBody = null;
}
if (requestBody != null && !(requestBody instanceof RetryableSink)) {
throw new HttpRetryException("Cannot retry streamed HTTP body", responseCode);
}
if (!httpEngine.sameConnection(followUp.url())) {
httpEngine.releaseConnection();
}
Connection connection = httpEngine.close();
httpEngine = newHttpEngine(followUp.method(), connection, (RetryableSink) requestBody,
response);
}
} | [
"private",
"HttpEngine",
"getResponse",
"(",
")",
"throws",
"IOException",
"{",
"initHttpEngine",
"(",
")",
";",
"if",
"(",
"httpEngine",
".",
"hasResponse",
"(",
")",
")",
"{",
"return",
"httpEngine",
";",
"}",
"while",
"(",
"true",
")",
"{",
"if",
"(",... | Aggressively tries to get the final HTTP response, potentially making
many HTTP requests in the process in order to cope with redirects and
authentication. | [
"Aggressively",
"tries",
"to",
"get",
"the",
"final",
"HTTP",
"response",
"potentially",
"making",
"many",
"HTTP",
"requests",
"in",
"the",
"process",
"in",
"order",
"to",
"cope",
"with",
"redirects",
"and",
"authentication",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/connectors/ok/HttpURLConnectionImpl.java#L378-L426 | train |
apiman/apiman | gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/connectors/ok/HttpURLConnectionImpl.java | HttpURLConnectionImpl.execute | private boolean execute(boolean readResponse) throws IOException {
try {
httpEngine.sendRequest();
route = httpEngine.getRoute();
handshake = httpEngine.getConnection() != null
? httpEngine.getConnection().getHandshake()
: null;
if (readResponse) {
httpEngine.readResponse();
}
return true;
} catch (RequestException e) {
// An attempt to interpret a request failed.
IOException toThrow = e.getCause();
httpEngineFailure = toThrow;
throw toThrow;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
HttpEngine retryEngine = httpEngine.recover(e);
if (retryEngine != null) {
httpEngine = retryEngine;
return false;
}
// Give up; recovery is not possible.
IOException toThrow = e.getLastConnectException();
httpEngineFailure = toThrow;
throw toThrow;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
HttpEngine retryEngine = httpEngine.recover(e);
if (retryEngine != null) {
httpEngine = retryEngine;
return false;
}
// Give up; recovery is not possible.
httpEngineFailure = e;
throw e;
}
} | java | private boolean execute(boolean readResponse) throws IOException {
try {
httpEngine.sendRequest();
route = httpEngine.getRoute();
handshake = httpEngine.getConnection() != null
? httpEngine.getConnection().getHandshake()
: null;
if (readResponse) {
httpEngine.readResponse();
}
return true;
} catch (RequestException e) {
// An attempt to interpret a request failed.
IOException toThrow = e.getCause();
httpEngineFailure = toThrow;
throw toThrow;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
HttpEngine retryEngine = httpEngine.recover(e);
if (retryEngine != null) {
httpEngine = retryEngine;
return false;
}
// Give up; recovery is not possible.
IOException toThrow = e.getLastConnectException();
httpEngineFailure = toThrow;
throw toThrow;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
HttpEngine retryEngine = httpEngine.recover(e);
if (retryEngine != null) {
httpEngine = retryEngine;
return false;
}
// Give up; recovery is not possible.
httpEngineFailure = e;
throw e;
}
} | [
"private",
"boolean",
"execute",
"(",
"boolean",
"readResponse",
")",
"throws",
"IOException",
"{",
"try",
"{",
"httpEngine",
".",
"sendRequest",
"(",
")",
";",
"route",
"=",
"httpEngine",
".",
"getRoute",
"(",
")",
";",
"handshake",
"=",
"httpEngine",
".",
... | Sends a request and optionally reads a response. Returns true if the
request was successfully executed, and false if the request can be
retried. Throws an exception if the request failed permanently. | [
"Sends",
"a",
"request",
"and",
"optionally",
"reads",
"a",
"response",
".",
"Returns",
"true",
"if",
"the",
"request",
"was",
"successfully",
"executed",
"and",
"false",
"if",
"the",
"request",
"can",
"be",
"retried",
".",
"Throws",
"an",
"exception",
"if",... | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/connectors/ok/HttpURLConnectionImpl.java#L433-L474 | train |
apiman/apiman | gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/components/ldap/LdapClientConnectionImpl.java | LdapClientConnectionImpl.close | @Override
public void close(IAsyncResultHandler<Void> result) {
vertx.executeBlocking(blocking -> {
super.close(result);
}, res -> {
if (res.failed())
result.handle(AsyncResultImpl.create(res.cause()));
});
} | java | @Override
public void close(IAsyncResultHandler<Void> result) {
vertx.executeBlocking(blocking -> {
super.close(result);
}, res -> {
if (res.failed())
result.handle(AsyncResultImpl.create(res.cause()));
});
} | [
"@",
"Override",
"public",
"void",
"close",
"(",
"IAsyncResultHandler",
"<",
"Void",
">",
"result",
")",
"{",
"vertx",
".",
"executeBlocking",
"(",
"blocking",
"->",
"{",
"super",
".",
"close",
"(",
"result",
")",
";",
"}",
",",
"res",
"->",
"{",
"if",... | Indicates whether connection was successfully closed.
@param result the result | [
"Indicates",
"whether",
"connection",
"was",
"successfully",
"closed",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/components/ldap/LdapClientConnectionImpl.java#L51-L59 | train |
apiman/apiman | gateway/engine/vertx-polling/src/main/java/io/apiman/gateway/engine/vertx/polling/URILoadingRegistry.java | URILoadingRegistry.reloadData | public static void reloadData(IAsyncHandler<Void> doneHandler) {
synchronized(URILoadingRegistry.class) {
if (instance == null) {
doneHandler.handle((Void) null);
return;
}
Map<URILoadingRegistry, IAsyncResultHandler<Void>> regs = instance.handlers;
Vertx vertx = instance.vertx;
URI uri = instance.uri;
Map<String, String> config = instance.config;
AtomicInteger ctr = new AtomicInteger(regs.size());
OneShotURILoader newLoader = new OneShotURILoader(vertx, uri, config);
regs.entrySet().stream().forEach(pair -> {
// Clear the registrys' internal maps to prepare for reload.
// NB: If we add production hot reloading, we'll need to work around this (e.g. clone?).
pair.getKey().getMap().clear();
// Re-subscribe the registry.
newLoader.subscribe(pair.getKey(), result -> {
checkAndFlip(ctr.decrementAndGet(), newLoader, doneHandler);
});
});
checkAndFlip(ctr.get(), newLoader, doneHandler);
}
} | java | public static void reloadData(IAsyncHandler<Void> doneHandler) {
synchronized(URILoadingRegistry.class) {
if (instance == null) {
doneHandler.handle((Void) null);
return;
}
Map<URILoadingRegistry, IAsyncResultHandler<Void>> regs = instance.handlers;
Vertx vertx = instance.vertx;
URI uri = instance.uri;
Map<String, String> config = instance.config;
AtomicInteger ctr = new AtomicInteger(regs.size());
OneShotURILoader newLoader = new OneShotURILoader(vertx, uri, config);
regs.entrySet().stream().forEach(pair -> {
// Clear the registrys' internal maps to prepare for reload.
// NB: If we add production hot reloading, we'll need to work around this (e.g. clone?).
pair.getKey().getMap().clear();
// Re-subscribe the registry.
newLoader.subscribe(pair.getKey(), result -> {
checkAndFlip(ctr.decrementAndGet(), newLoader, doneHandler);
});
});
checkAndFlip(ctr.get(), newLoader, doneHandler);
}
} | [
"public",
"static",
"void",
"reloadData",
"(",
"IAsyncHandler",
"<",
"Void",
">",
"doneHandler",
")",
"{",
"synchronized",
"(",
"URILoadingRegistry",
".",
"class",
")",
"{",
"if",
"(",
"instance",
"==",
"null",
")",
"{",
"doneHandler",
".",
"handle",
"(",
... | For testing only. Reloads rather than full restart. | [
"For",
"testing",
"only",
".",
"Reloads",
"rather",
"than",
"full",
"restart",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/vertx-polling/src/main/java/io/apiman/gateway/engine/vertx/polling/URILoadingRegistry.java#L103-L127 | train |
apiman/apiman | gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/TransferQuotaPolicy.java | TransferQuotaPolicy.doQuotaExceededFailure | protected void doQuotaExceededFailure(final IPolicyContext context, final TransferQuotaConfig config,
final IPolicyChain<?> chain, RateLimitResponse rtr) {
Map<String, String> responseHeaders = RateLimitingPolicy.responseHeaders(config, rtr,
defaultLimitHeader(), defaultRemainingHeader(), defaultResetHeader());
IPolicyFailureFactoryComponent failureFactory = context.getComponent(IPolicyFailureFactoryComponent.class);
PolicyFailure failure = limitExceededFailure(failureFactory);
failure.getHeaders().putAll(responseHeaders);
chain.doFailure(failure);
} | java | protected void doQuotaExceededFailure(final IPolicyContext context, final TransferQuotaConfig config,
final IPolicyChain<?> chain, RateLimitResponse rtr) {
Map<String, String> responseHeaders = RateLimitingPolicy.responseHeaders(config, rtr,
defaultLimitHeader(), defaultRemainingHeader(), defaultResetHeader());
IPolicyFailureFactoryComponent failureFactory = context.getComponent(IPolicyFailureFactoryComponent.class);
PolicyFailure failure = limitExceededFailure(failureFactory);
failure.getHeaders().putAll(responseHeaders);
chain.doFailure(failure);
} | [
"protected",
"void",
"doQuotaExceededFailure",
"(",
"final",
"IPolicyContext",
"context",
",",
"final",
"TransferQuotaConfig",
"config",
",",
"final",
"IPolicyChain",
"<",
"?",
">",
"chain",
",",
"RateLimitResponse",
"rtr",
")",
"{",
"Map",
"<",
"String",
",",
"... | Called to send a 'quota exceeded' failure.
@param context
@param config
@param chain
@param rtr | [
"Called",
"to",
"send",
"a",
"quota",
"exceeded",
"failure",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/TransferQuotaPolicy.java#L268-L277 | train |
apiman/apiman | manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaUtil.java | JpaUtil.isConstraintViolation | public static boolean isConstraintViolation(Exception e) {
Throwable cause = e;
while (cause != cause.getCause() && cause.getCause() != null) {
if (cause.getClass().getSimpleName().equals("ConstraintViolationException")) //$NON-NLS-1$
return true;
cause = cause.getCause();
}
return false;
} | java | public static boolean isConstraintViolation(Exception e) {
Throwable cause = e;
while (cause != cause.getCause() && cause.getCause() != null) {
if (cause.getClass().getSimpleName().equals("ConstraintViolationException")) //$NON-NLS-1$
return true;
cause = cause.getCause();
}
return false;
} | [
"public",
"static",
"boolean",
"isConstraintViolation",
"(",
"Exception",
"e",
")",
"{",
"Throwable",
"cause",
"=",
"e",
";",
"while",
"(",
"cause",
"!=",
"cause",
".",
"getCause",
"(",
")",
"&&",
"cause",
".",
"getCause",
"(",
")",
"!=",
"null",
")",
... | Returns true if the given exception is a unique constraint violation. This
is useful to detect whether someone is trying to persist an entity that
already exists. It allows us to simply assume that persisting a new entity
will work, without first querying the DB for the existence of that entity.
Note that my understanding is that JPA is supposed to throw an {@link EntityExistsException}
when the row already exists. However, this is not always the case, based on
experience. Or perhaps it only throws the exception if the entity is already
loaded from the DB and exists in the {@link EntityManager}.
@param e the exception
@return whether a constraint violation occurred | [
"Returns",
"true",
"if",
"the",
"given",
"exception",
"is",
"a",
"unique",
"constraint",
"violation",
".",
"This",
"is",
"useful",
"to",
"detect",
"whether",
"someone",
"is",
"trying",
"to",
"persist",
"an",
"entity",
"that",
"already",
"exists",
".",
"It",
... | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaUtil.java#L49-L57 | train |
apiman/apiman | manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaUtil.java | JpaUtil.rollbackQuietly | public static void rollbackQuietly(EntityManager entityManager) {
if (entityManager.getTransaction().isActive()/* && entityManager.getTransaction().getRollbackOnly()*/) {
try {
entityManager.getTransaction().rollback();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
} | java | public static void rollbackQuietly(EntityManager entityManager) {
if (entityManager.getTransaction().isActive()/* && entityManager.getTransaction().getRollbackOnly()*/) {
try {
entityManager.getTransaction().rollback();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
} | [
"public",
"static",
"void",
"rollbackQuietly",
"(",
"EntityManager",
"entityManager",
")",
"{",
"if",
"(",
"entityManager",
".",
"getTransaction",
"(",
")",
".",
"isActive",
"(",
")",
"/* && entityManager.getTransaction().getRollbackOnly()*/",
")",
"{",
"try",
"{",
... | Rolls back a transaction. Tries to be smart and quiet about it.
@param entityManager the entity manager | [
"Rolls",
"back",
"a",
"transaction",
".",
"Tries",
"to",
"be",
"smart",
"and",
"quiet",
"about",
"it",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaUtil.java#L63-L71 | train |
apiman/apiman | gateway/platforms/war/src/main/java/io/apiman/gateway/platforms/war/WarEngineConfig.java | WarEngineConfig.getConfigProperty | public String getConfigProperty(String propertyName, String defaultValue) {
return getConfig().getString(propertyName, defaultValue);
} | java | public String getConfigProperty(String propertyName, String defaultValue) {
return getConfig().getString(propertyName, defaultValue);
} | [
"public",
"String",
"getConfigProperty",
"(",
"String",
"propertyName",
",",
"String",
"defaultValue",
")",
"{",
"return",
"getConfig",
"(",
")",
".",
"getString",
"(",
"propertyName",
",",
"defaultValue",
")",
";",
"}"
] | Returns the given configuration property name or the provided default
value if not found.
@param propertyName the property name
@param defaultValue the default value
@return the config property | [
"Returns",
"the",
"given",
"configuration",
"property",
"name",
"or",
"the",
"provided",
"default",
"value",
"if",
"not",
"found",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/src/main/java/io/apiman/gateway/platforms/war/WarEngineConfig.java#L86-L88 | train |
apiman/apiman | manager/api/security/src/main/java/io/apiman/manager/api/security/impl/AbstractSecurityContext.java | AbstractSecurityContext.loadPermissions | private IndexedPermissions loadPermissions() {
String userId = getCurrentUser();
try {
return new IndexedPermissions(getQuery().getPermissions(userId));
} catch (StorageException e) {
logger.error(Messages.getString("AbstractSecurityContext.ErrorLoadingPermissions") + userId, e); //$NON-NLS-1$
return new IndexedPermissions(new HashSet<>());
}
} | java | private IndexedPermissions loadPermissions() {
String userId = getCurrentUser();
try {
return new IndexedPermissions(getQuery().getPermissions(userId));
} catch (StorageException e) {
logger.error(Messages.getString("AbstractSecurityContext.ErrorLoadingPermissions") + userId, e); //$NON-NLS-1$
return new IndexedPermissions(new HashSet<>());
}
} | [
"private",
"IndexedPermissions",
"loadPermissions",
"(",
")",
"{",
"String",
"userId",
"=",
"getCurrentUser",
"(",
")",
";",
"try",
"{",
"return",
"new",
"IndexedPermissions",
"(",
"getQuery",
"(",
")",
".",
"getPermissions",
"(",
"userId",
")",
")",
";",
"}... | Loads the current user's permissions into a thread local variable. | [
"Loads",
"the",
"current",
"user",
"s",
"permissions",
"into",
"a",
"thread",
"local",
"variable",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/security/src/main/java/io/apiman/manager/api/security/impl/AbstractSecurityContext.java#L97-L105 | train |
apiman/apiman | gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultJdbcComponent.java | DefaultJdbcComponent.datasourceFromConfig | @SuppressWarnings("nls")
protected DataSource datasourceFromConfig(JdbcOptionsBean config) {
Properties props = new Properties();
props.putAll(config.getDsProperties());
setConfigProperty(props, "jdbcUrl", config.getJdbcUrl());
setConfigProperty(props, "username", config.getUsername());
setConfigProperty(props, "password", config.getPassword());
setConfigProperty(props, "connectionTimeout", config.getConnectionTimeout());
setConfigProperty(props, "idleTimeout", config.getIdleTimeout());
setConfigProperty(props, "maxPoolSize", config.getMaximumPoolSize());
setConfigProperty(props, "maxLifetime", config.getMaxLifetime());
setConfigProperty(props, "minIdle", config.getMinimumIdle());
setConfigProperty(props, "poolName", config.getPoolName());
setConfigProperty(props, "autoCommit", config.isAutoCommit());
HikariConfig hikariConfig = new HikariConfig(props);
return new HikariDataSource(hikariConfig);
} | java | @SuppressWarnings("nls")
protected DataSource datasourceFromConfig(JdbcOptionsBean config) {
Properties props = new Properties();
props.putAll(config.getDsProperties());
setConfigProperty(props, "jdbcUrl", config.getJdbcUrl());
setConfigProperty(props, "username", config.getUsername());
setConfigProperty(props, "password", config.getPassword());
setConfigProperty(props, "connectionTimeout", config.getConnectionTimeout());
setConfigProperty(props, "idleTimeout", config.getIdleTimeout());
setConfigProperty(props, "maxPoolSize", config.getMaximumPoolSize());
setConfigProperty(props, "maxLifetime", config.getMaxLifetime());
setConfigProperty(props, "minIdle", config.getMinimumIdle());
setConfigProperty(props, "poolName", config.getPoolName());
setConfigProperty(props, "autoCommit", config.isAutoCommit());
HikariConfig hikariConfig = new HikariConfig(props);
return new HikariDataSource(hikariConfig);
} | [
"@",
"SuppressWarnings",
"(",
"\"nls\"",
")",
"protected",
"DataSource",
"datasourceFromConfig",
"(",
"JdbcOptionsBean",
"config",
")",
"{",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"props",
".",
"putAll",
"(",
"config",
".",
"getDsPropert... | Creates a datasource from the given jdbc config info. | [
"Creates",
"a",
"datasource",
"from",
"the",
"given",
"jdbc",
"config",
"info",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultJdbcComponent.java#L84-L102 | train |
apiman/apiman | gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultJdbcComponent.java | DefaultJdbcComponent.setConfigProperty | private void setConfigProperty(Properties props, String propName, Object value) {
if (value != null) {
props.setProperty(propName, String.valueOf(value));
}
} | java | private void setConfigProperty(Properties props, String propName, Object value) {
if (value != null) {
props.setProperty(propName, String.valueOf(value));
}
} | [
"private",
"void",
"setConfigProperty",
"(",
"Properties",
"props",
",",
"String",
"propName",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"props",
".",
"setProperty",
"(",
"propName",
",",
"String",
".",
"valueOf",
"(",
... | Sets a configuration property, but only if it's not null. | [
"Sets",
"a",
"configuration",
"property",
"but",
"only",
"if",
"it",
"s",
"not",
"null",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultJdbcComponent.java#L107-L111 | train |
apiman/apiman | common/util/src/main/java/io/apiman/common/util/AbstractMessages.java | AbstractMessages.getBundle | private ResourceBundle getBundle() {
String bundleKey = getBundleKey();
if (bundles.containsKey(bundleKey)) {
return bundles.get(bundleKey);
} else {
ResourceBundle bundle = loadBundle();
bundles.put(bundleKey, bundle);
return bundle;
}
} | java | private ResourceBundle getBundle() {
String bundleKey = getBundleKey();
if (bundles.containsKey(bundleKey)) {
return bundles.get(bundleKey);
} else {
ResourceBundle bundle = loadBundle();
bundles.put(bundleKey, bundle);
return bundle;
}
} | [
"private",
"ResourceBundle",
"getBundle",
"(",
")",
"{",
"String",
"bundleKey",
"=",
"getBundleKey",
"(",
")",
";",
"if",
"(",
"bundles",
".",
"containsKey",
"(",
"bundleKey",
")",
")",
"{",
"return",
"bundles",
".",
"get",
"(",
"bundleKey",
")",
";",
"}... | Gets a bundle. First tries to find one in the cache, then loads it if
it can't find one. | [
"Gets",
"a",
"bundle",
".",
"First",
"tries",
"to",
"find",
"one",
"in",
"the",
"cache",
"then",
"loads",
"it",
"if",
"it",
"can",
"t",
"find",
"one",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/util/src/main/java/io/apiman/common/util/AbstractMessages.java#L61-L70 | train |
apiman/apiman | common/util/src/main/java/io/apiman/common/util/AbstractMessages.java | AbstractMessages.loadBundle | private ResourceBundle loadBundle() {
String pkg = clazz.getPackage().getName();
Locale locale = getLocale();
return PropertyResourceBundle.getBundle(pkg + ".messages", locale, clazz.getClassLoader(), new ResourceBundle.Control() { //$NON-NLS-1$
@Override
public List<String> getFormats(String baseName) {
return FORMATS;
}
});
} | java | private ResourceBundle loadBundle() {
String pkg = clazz.getPackage().getName();
Locale locale = getLocale();
return PropertyResourceBundle.getBundle(pkg + ".messages", locale, clazz.getClassLoader(), new ResourceBundle.Control() { //$NON-NLS-1$
@Override
public List<String> getFormats(String baseName) {
return FORMATS;
}
});
} | [
"private",
"ResourceBundle",
"loadBundle",
"(",
")",
"{",
"String",
"pkg",
"=",
"clazz",
".",
"getPackage",
"(",
")",
".",
"getName",
"(",
")",
";",
"Locale",
"locale",
"=",
"getLocale",
"(",
")",
";",
"return",
"PropertyResourceBundle",
".",
"getBundle",
... | Loads the resource bundle.
@param c | [
"Loads",
"the",
"resource",
"bundle",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/util/src/main/java/io/apiman/common/util/AbstractMessages.java#L85-L94 | train |
apiman/apiman | common/util/src/main/java/io/apiman/common/util/AbstractMessages.java | AbstractMessages.format | public String format(String key, Object ... params) {
ResourceBundle bundle = getBundle();
if (bundle.containsKey(key)) {
String msg = bundle.getString(key);
return MessageFormat.format(msg, params);
} else {
return MessageFormat.format("!!{0}!!", key); //$NON-NLS-1$
}
} | java | public String format(String key, Object ... params) {
ResourceBundle bundle = getBundle();
if (bundle.containsKey(key)) {
String msg = bundle.getString(key);
return MessageFormat.format(msg, params);
} else {
return MessageFormat.format("!!{0}!!", key); //$NON-NLS-1$
}
} | [
"public",
"String",
"format",
"(",
"String",
"key",
",",
"Object",
"...",
"params",
")",
"{",
"ResourceBundle",
"bundle",
"=",
"getBundle",
"(",
")",
";",
"if",
"(",
"bundle",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"String",
"msg",
"=",
"bundle... | Look up a message in the i18n resource message bundle by key, then format the
message with the given params and return the result.
@param key the key
@param params the parameters
@return formatted string | [
"Look",
"up",
"a",
"message",
"in",
"the",
"i18n",
"resource",
"message",
"bundle",
"by",
"key",
"then",
"format",
"the",
"message",
"with",
"the",
"given",
"params",
"and",
"return",
"the",
"result",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/util/src/main/java/io/apiman/common/util/AbstractMessages.java#L116-L124 | train |
apiman/apiman | gateway/engine/influxdb/src/main/java/io/apiman/gateway/engine/influxdb/InfluxDb09Driver.java | InfluxDb09Driver.listDatabases | @SuppressWarnings("nls")
public void listDatabases(final IAsyncResultHandler<List<String>> handler) {
IHttpClientRequest request = httpClient.request(queryUrl.toString(), HttpMethod.GET,
result -> {
try {
if (result.isError() || result.getResult().getResponseCode() != 200) {
handleError(result, handler);
return;
}
List<String> results = new ArrayList<>();
// {"results":
JsonNode arrNode = objectMapper.readTree(result.getResult().getBody())
.path("results").elements().next() // results: [ first-elem
.path("series").elements().next(); // series: [ first-elem
// values: [[db1], [db2], [...]] => db1, db2
flattenArrays(arrNode.get("values"), results);
// send results
handler.handle(AsyncResultImpl.create(results));
} catch (IOException e) {
AsyncResultImpl.create(new RuntimeException(
"Unable to parse Influx JSON response", e));
}
});
request.end();
} | java | @SuppressWarnings("nls")
public void listDatabases(final IAsyncResultHandler<List<String>> handler) {
IHttpClientRequest request = httpClient.request(queryUrl.toString(), HttpMethod.GET,
result -> {
try {
if (result.isError() || result.getResult().getResponseCode() != 200) {
handleError(result, handler);
return;
}
List<String> results = new ArrayList<>();
// {"results":
JsonNode arrNode = objectMapper.readTree(result.getResult().getBody())
.path("results").elements().next() // results: [ first-elem
.path("series").elements().next(); // series: [ first-elem
// values: [[db1], [db2], [...]] => db1, db2
flattenArrays(arrNode.get("values"), results);
// send results
handler.handle(AsyncResultImpl.create(results));
} catch (IOException e) {
AsyncResultImpl.create(new RuntimeException(
"Unable to parse Influx JSON response", e));
}
});
request.end();
} | [
"@",
"SuppressWarnings",
"(",
"\"nls\"",
")",
"public",
"void",
"listDatabases",
"(",
"final",
"IAsyncResultHandler",
"<",
"List",
"<",
"String",
">",
">",
"handler",
")",
"{",
"IHttpClientRequest",
"request",
"=",
"httpClient",
".",
"request",
"(",
"queryUrl",
... | List all databases
@param handler the result handler | [
"List",
"all",
"databases"
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/influxdb/src/main/java/io/apiman/gateway/engine/influxdb/InfluxDb09Driver.java#L111-L141 | train |
apiman/apiman | manager/api/war/src/main/java/io/apiman/manager/api/war/WarCdiFactory.java | WarCdiFactory.createCustomComponent | @SuppressWarnings("unchecked")
private static <T> T createCustomComponent(Class<T> componentType, Class<?> componentClass,
Map<String, String> configProperties) throws Exception {
if (componentClass == null) {
throw new IllegalArgumentException("Invalid component spec (class not found)."); //$NON-NLS-1$
}
try {
Constructor<?> constructor = componentClass.getConstructor(Map.class);
return (T) constructor.newInstance(configProperties);
} catch (Exception e) {
}
return (T) componentClass.getConstructor().newInstance();
} | java | @SuppressWarnings("unchecked")
private static <T> T createCustomComponent(Class<T> componentType, Class<?> componentClass,
Map<String, String> configProperties) throws Exception {
if (componentClass == null) {
throw new IllegalArgumentException("Invalid component spec (class not found)."); //$NON-NLS-1$
}
try {
Constructor<?> constructor = componentClass.getConstructor(Map.class);
return (T) constructor.newInstance(configProperties);
} catch (Exception e) {
}
return (T) componentClass.getConstructor().newInstance();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"<",
"T",
">",
"T",
"createCustomComponent",
"(",
"Class",
"<",
"T",
">",
"componentType",
",",
"Class",
"<",
"?",
">",
"componentClass",
",",
"Map",
"<",
"String",
",",
"String",
">"... | Creates a custom component from a loaded class.
@param componentType
@param componentClass
@param configProperties | [
"Creates",
"a",
"custom",
"component",
"from",
"a",
"loaded",
"class",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/war/src/main/java/io/apiman/manager/api/war/WarCdiFactory.java#L370-L382 | train |
apiman/apiman | manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaStorageInitializer.java | JpaStorageInitializer.lookupDS | private static DataSource lookupDS(String dsJndiLocation) {
DataSource ds;
try {
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup(dsJndiLocation);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (ds == null) {
throw new RuntimeException("Datasource not found: " + dsJndiLocation); //$NON-NLS-1$
}
return ds;
} | java | private static DataSource lookupDS(String dsJndiLocation) {
DataSource ds;
try {
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup(dsJndiLocation);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (ds == null) {
throw new RuntimeException("Datasource not found: " + dsJndiLocation); //$NON-NLS-1$
}
return ds;
} | [
"private",
"static",
"DataSource",
"lookupDS",
"(",
"String",
"dsJndiLocation",
")",
"{",
"DataSource",
"ds",
";",
"try",
"{",
"InitialContext",
"ctx",
"=",
"new",
"InitialContext",
"(",
")",
";",
"ds",
"=",
"(",
"DataSource",
")",
"ctx",
".",
"lookup",
"(... | Lookup the datasource in JNDI.
@param dsJndiLocation | [
"Lookup",
"the",
"datasource",
"in",
"JNDI",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaStorageInitializer.java#L102-L115 | train |
apiman/apiman | common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java | PluginClassLoader.createWorkDir | protected File createWorkDir(File pluginArtifactFile) throws IOException {
File tempDir = File.createTempFile(pluginArtifactFile.getName(), "");
tempDir.delete();
tempDir.mkdirs();
return tempDir;
} | java | protected File createWorkDir(File pluginArtifactFile) throws IOException {
File tempDir = File.createTempFile(pluginArtifactFile.getName(), "");
tempDir.delete();
tempDir.mkdirs();
return tempDir;
} | [
"protected",
"File",
"createWorkDir",
"(",
"File",
"pluginArtifactFile",
")",
"throws",
"IOException",
"{",
"File",
"tempDir",
"=",
"File",
".",
"createTempFile",
"(",
"pluginArtifactFile",
".",
"getName",
"(",
")",
",",
"\"\"",
")",
";",
"tempDir",
".",
"dele... | Creates a work directory into which various resources discovered in the plugin
artifact can be extracted.
@param pluginArtifactFile plugin artifact
@throws IOException if an I/O error has occurred | [
"Creates",
"a",
"work",
"directory",
"into",
"which",
"various",
"resources",
"discovered",
"in",
"the",
"plugin",
"artifact",
"can",
"be",
"extracted",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java#L81-L86 | train |
apiman/apiman | common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java | PluginClassLoader.indexPluginArtifact | private void indexPluginArtifact() throws IOException {
dependencyZips = new ArrayList<>();
Enumeration<? extends ZipEntry> entries = this.pluginArtifactZip.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = entries.nextElement();
if (zipEntry.getName().startsWith("WEB-INF/lib/") && zipEntry.getName().toLowerCase().endsWith(".jar")) {
ZipFile dependencyZipFile = extractDependency(zipEntry);
if (dependencyZipFile != null) {
dependencyZips.add(dependencyZipFile);
}
}
}
} | java | private void indexPluginArtifact() throws IOException {
dependencyZips = new ArrayList<>();
Enumeration<? extends ZipEntry> entries = this.pluginArtifactZip.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = entries.nextElement();
if (zipEntry.getName().startsWith("WEB-INF/lib/") && zipEntry.getName().toLowerCase().endsWith(".jar")) {
ZipFile dependencyZipFile = extractDependency(zipEntry);
if (dependencyZipFile != null) {
dependencyZips.add(dependencyZipFile);
}
}
}
} | [
"private",
"void",
"indexPluginArtifact",
"(",
")",
"throws",
"IOException",
"{",
"dependencyZips",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Enumeration",
"<",
"?",
"extends",
"ZipEntry",
">",
"entries",
"=",
"this",
".",
"pluginArtifactZip",
".",
"entri... | Indexes the content of the plugin artifact. This includes discovering all of the
dependency JARs as well as any configuration resources such as plugin definitions.
@throws IOException if an I/O error has occurred | [
"Indexes",
"the",
"content",
"of",
"the",
"plugin",
"artifact",
".",
"This",
"includes",
"discovering",
"all",
"of",
"the",
"dependency",
"JARs",
"as",
"well",
"as",
"any",
"configuration",
"resources",
"such",
"as",
"plugin",
"definitions",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java#L93-L105 | train |
apiman/apiman | common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java | PluginClassLoader.findClassContent | protected InputStream findClassContent(String className) throws IOException {
String primaryArtifactEntryName = "WEB-INF/classes/" + className.replace('.', '/') + ".class";
String dependencyEntryName = className.replace('.', '/') + ".class";
ZipEntry entry = this.pluginArtifactZip.getEntry(primaryArtifactEntryName);
if (entry != null) {
return this.pluginArtifactZip.getInputStream(entry);
}
for (ZipFile zipFile : this.dependencyZips) {
entry = zipFile.getEntry(dependencyEntryName);
if (entry != null) {
return zipFile.getInputStream(entry);
}
}
return null;
} | java | protected InputStream findClassContent(String className) throws IOException {
String primaryArtifactEntryName = "WEB-INF/classes/" + className.replace('.', '/') + ".class";
String dependencyEntryName = className.replace('.', '/') + ".class";
ZipEntry entry = this.pluginArtifactZip.getEntry(primaryArtifactEntryName);
if (entry != null) {
return this.pluginArtifactZip.getInputStream(entry);
}
for (ZipFile zipFile : this.dependencyZips) {
entry = zipFile.getEntry(dependencyEntryName);
if (entry != null) {
return zipFile.getInputStream(entry);
}
}
return null;
} | [
"protected",
"InputStream",
"findClassContent",
"(",
"String",
"className",
")",
"throws",
"IOException",
"{",
"String",
"primaryArtifactEntryName",
"=",
"\"WEB-INF/classes/\"",
"+",
"className",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
"+",
"\".class\""... | Searches the plugin artifact ZIP and all dependency ZIPs for a zip entry for
the given fully qualified class name.
@param className name of class
@throws IOException if an I/O error has occurred | [
"Searches",
"the",
"plugin",
"artifact",
"ZIP",
"and",
"all",
"dependency",
"ZIPs",
"for",
"a",
"zip",
"entry",
"for",
"the",
"given",
"fully",
"qualified",
"class",
"name",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java#L206-L220 | train |
apiman/apiman | common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java | PluginClassLoader.close | public void close() throws IOException {
if (closed) { return; }
this.pluginArtifactZip.close();
for (ZipFile zipFile : this.dependencyZips) {
zipFile.close();
}
closed = true;
} | java | public void close() throws IOException {
if (closed) { return; }
this.pluginArtifactZip.close();
for (ZipFile zipFile : this.dependencyZips) {
zipFile.close();
}
closed = true;
} | [
"public",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"closed",
")",
"{",
"return",
";",
"}",
"this",
".",
"pluginArtifactZip",
".",
"close",
"(",
")",
";",
"for",
"(",
"ZipFile",
"zipFile",
":",
"this",
".",
"dependencyZips",
"... | Closes any resources the plugin classloader is holding open.
@throws IOException if an I/O error has occurred | [
"Closes",
"any",
"resources",
"the",
"plugin",
"classloader",
"is",
"holding",
"open",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/plugin/src/main/java/io/apiman/common/plugin/PluginClassLoader.java#L322-L329 | train |
apiman/apiman | manager/api/core/src/main/java/io/apiman/manager/api/core/plugin/AbstractPluginRegistry.java | AbstractPluginRegistry.createPluginClassLoader | protected PluginClassLoader createPluginClassLoader(final File pluginFile) throws IOException {
return new PluginClassLoader(pluginFile, Thread.currentThread().getContextClassLoader()) {
@Override
protected File createWorkDir(File pluginArtifactFile) throws IOException {
File workDir = new File(pluginFile.getParentFile(), ".work"); //$NON-NLS-1$
workDir.mkdirs();
return workDir;
}
};
} | java | protected PluginClassLoader createPluginClassLoader(final File pluginFile) throws IOException {
return new PluginClassLoader(pluginFile, Thread.currentThread().getContextClassLoader()) {
@Override
protected File createWorkDir(File pluginArtifactFile) throws IOException {
File workDir = new File(pluginFile.getParentFile(), ".work"); //$NON-NLS-1$
workDir.mkdirs();
return workDir;
}
};
} | [
"protected",
"PluginClassLoader",
"createPluginClassLoader",
"(",
"final",
"File",
"pluginFile",
")",
"throws",
"IOException",
"{",
"return",
"new",
"PluginClassLoader",
"(",
"pluginFile",
",",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(... | Creates a plugin classloader for the given plugin file. | [
"Creates",
"a",
"plugin",
"classloader",
"for",
"the",
"given",
"plugin",
"file",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/core/src/main/java/io/apiman/manager/api/core/plugin/AbstractPluginRegistry.java#L133-L142 | train |
apiman/apiman | gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/InMemoryRegistry.java | InMemoryRegistry.getClientInternal | protected Client getClientInternal(String idx) {
Client client;
synchronized (mutex) {
client = (Client) getMap().get(idx);
}
return client;
} | java | protected Client getClientInternal(String idx) {
Client client;
synchronized (mutex) {
client = (Client) getMap().get(idx);
}
return client;
} | [
"protected",
"Client",
"getClientInternal",
"(",
"String",
"idx",
")",
"{",
"Client",
"client",
";",
"synchronized",
"(",
"mutex",
")",
"{",
"client",
"=",
"(",
"Client",
")",
"getMap",
"(",
")",
".",
"get",
"(",
"idx",
")",
";",
"}",
"return",
"client... | Gets the client and returns it.
@param apiKey | [
"Gets",
"the",
"client",
"and",
"returns",
"it",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/InMemoryRegistry.java#L169-L175 | train |
apiman/apiman | gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/InMemoryRegistry.java | InMemoryRegistry.getClientIndex | private String getClientIndex(Client client) {
return getClientIndex(client.getOrganizationId(), client.getClientId(), client.getVersion());
} | java | private String getClientIndex(Client client) {
return getClientIndex(client.getOrganizationId(), client.getClientId(), client.getVersion());
} | [
"private",
"String",
"getClientIndex",
"(",
"Client",
"client",
")",
"{",
"return",
"getClientIndex",
"(",
"client",
".",
"getOrganizationId",
"(",
")",
",",
"client",
".",
"getClientId",
"(",
")",
",",
"client",
".",
"getVersion",
"(",
")",
")",
";",
"}"
... | Generates an in-memory key for an client, used to index the client for later quick
retrieval.
@param client an client
@return a client key | [
"Generates",
"an",
"in",
"-",
"memory",
"key",
"for",
"an",
"client",
"used",
"to",
"index",
"the",
"client",
"for",
"later",
"quick",
"retrieval",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/InMemoryRegistry.java#L349-L351 | train |
apiman/apiman | manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaStorage.java | JpaStorage.getClientContractsInternal | protected List<ContractSummaryBean> getClientContractsInternal(String organizationId, String clientId,
String version) throws StorageException {
List<ContractSummaryBean> rval = new ArrayList<>();
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT c from ContractBean c " +
" JOIN c.client clientv " +
" JOIN clientv.client client " +
" JOIN client.organization aorg" +
" WHERE client.id = :clientId " +
" AND aorg.id = :orgId " +
" AND clientv.version = :version " +
" ORDER BY aorg.id, client.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId); //$NON-NLS-1$
query.setParameter("clientId", clientId); //$NON-NLS-1$
query.setParameter("version", version); //$NON-NLS-1$
List<ContractBean> contracts = query.getResultList();
for (ContractBean contractBean : contracts) {
ClientBean client = contractBean.getClient().getClient();
ApiBean api = contractBean.getApi().getApi();
PlanBean plan = contractBean.getPlan().getPlan();
OrganizationBean clientOrg = entityManager.find(OrganizationBean.class, client.getOrganization().getId());
OrganizationBean apiOrg = entityManager.find(OrganizationBean.class, api.getOrganization().getId());
ContractSummaryBean csb = new ContractSummaryBean();
csb.setClientId(client.getId());
csb.setClientOrganizationId(client.getOrganization().getId());
csb.setClientOrganizationName(clientOrg.getName());
csb.setClientName(client.getName());
csb.setClientVersion(contractBean.getClient().getVersion());
csb.setContractId(contractBean.getId());
csb.setCreatedOn(contractBean.getCreatedOn());
csb.setPlanId(plan.getId());
csb.setPlanName(plan.getName());
csb.setPlanVersion(contractBean.getPlan().getVersion());
csb.setApiDescription(api.getDescription());
csb.setApiId(api.getId());
csb.setApiName(api.getName());
csb.setApiOrganizationId(apiOrg.getId());
csb.setApiOrganizationName(apiOrg.getName());
csb.setApiVersion(contractBean.getApi().getVersion());
rval.add(csb);
}
return rval;
} | java | protected List<ContractSummaryBean> getClientContractsInternal(String organizationId, String clientId,
String version) throws StorageException {
List<ContractSummaryBean> rval = new ArrayList<>();
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT c from ContractBean c " +
" JOIN c.client clientv " +
" JOIN clientv.client client " +
" JOIN client.organization aorg" +
" WHERE client.id = :clientId " +
" AND aorg.id = :orgId " +
" AND clientv.version = :version " +
" ORDER BY aorg.id, client.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId); //$NON-NLS-1$
query.setParameter("clientId", clientId); //$NON-NLS-1$
query.setParameter("version", version); //$NON-NLS-1$
List<ContractBean> contracts = query.getResultList();
for (ContractBean contractBean : contracts) {
ClientBean client = contractBean.getClient().getClient();
ApiBean api = contractBean.getApi().getApi();
PlanBean plan = contractBean.getPlan().getPlan();
OrganizationBean clientOrg = entityManager.find(OrganizationBean.class, client.getOrganization().getId());
OrganizationBean apiOrg = entityManager.find(OrganizationBean.class, api.getOrganization().getId());
ContractSummaryBean csb = new ContractSummaryBean();
csb.setClientId(client.getId());
csb.setClientOrganizationId(client.getOrganization().getId());
csb.setClientOrganizationName(clientOrg.getName());
csb.setClientName(client.getName());
csb.setClientVersion(contractBean.getClient().getVersion());
csb.setContractId(contractBean.getId());
csb.setCreatedOn(contractBean.getCreatedOn());
csb.setPlanId(plan.getId());
csb.setPlanName(plan.getName());
csb.setPlanVersion(contractBean.getPlan().getVersion());
csb.setApiDescription(api.getDescription());
csb.setApiId(api.getId());
csb.setApiName(api.getName());
csb.setApiOrganizationId(apiOrg.getId());
csb.setApiOrganizationName(apiOrg.getName());
csb.setApiVersion(contractBean.getApi().getVersion());
rval.add(csb);
}
return rval;
} | [
"protected",
"List",
"<",
"ContractSummaryBean",
">",
"getClientContractsInternal",
"(",
"String",
"organizationId",
",",
"String",
"clientId",
",",
"String",
"version",
")",
"throws",
"StorageException",
"{",
"List",
"<",
"ContractSummaryBean",
">",
"rval",
"=",
"n... | Returns a list of all contracts for the given client.
@param organizationId
@param clientId
@param version
@throws StorageException | [
"Returns",
"a",
"list",
"of",
"all",
"contracts",
"for",
"the",
"given",
"client",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaStorage.java#L1382-L1429 | train |
apiman/apiman | manager/api/migrator/src/main/java/io/apiman/manager/api/migrator/DataMigrator.java | DataMigrator.main | public static void main(String[] args) {
File from;
File to;
if (args.length < 2) {
System.out.println("Usage: DataMigrator <pathToSourceFile> <pathToDestFile>"); //$NON-NLS-1$
return;
}
String frompath = args[0];
String topath = args[1];
from = new File(frompath);
to = new File(topath);
System.out.println("Starting data migration."); //$NON-NLS-1$
System.out.println(" From: " + from); //$NON-NLS-1$
System.out.println(" To: " + to); //$NON-NLS-1$
DataMigrator migrator = new DataMigrator();
migrator.setLogger(new SystemOutLogger());
Version version = new Version();
version.postConstruct();
migrator.setVersion(version);
migrator.migrate(from, to);
} | java | public static void main(String[] args) {
File from;
File to;
if (args.length < 2) {
System.out.println("Usage: DataMigrator <pathToSourceFile> <pathToDestFile>"); //$NON-NLS-1$
return;
}
String frompath = args[0];
String topath = args[1];
from = new File(frompath);
to = new File(topath);
System.out.println("Starting data migration."); //$NON-NLS-1$
System.out.println(" From: " + from); //$NON-NLS-1$
System.out.println(" To: " + to); //$NON-NLS-1$
DataMigrator migrator = new DataMigrator();
migrator.setLogger(new SystemOutLogger());
Version version = new Version();
version.postConstruct();
migrator.setVersion(version);
migrator.migrate(from, to);
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"File",
"from",
";",
"File",
"to",
";",
"if",
"(",
"args",
".",
"length",
"<",
"2",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"Usage: DataMigrator <pathToSourc... | Main method - used when running the data migrator in standalone
mode.
@param args | [
"Main",
"method",
"-",
"used",
"when",
"running",
"the",
"data",
"migrator",
"in",
"standalone",
"mode",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/migrator/src/main/java/io/apiman/manager/api/migrator/DataMigrator.java#L102-L126 | train |
apiman/apiman | gateway/engine/storage-common/src/main/java/io/apiman/gateway/engine/storage/util/BackingStoreUtil.java | BackingStoreUtil.readPrimitive | public static Object readPrimitive(Class<?> clazz, String value) throws Exception {
if (clazz == String.class) {
return value;
} else if (clazz == Long.class) {
return Long.parseLong(value);
} else if (clazz == Integer.class) {
return Integer.parseInt(value);
} else if (clazz == Double.class) {
return Double.parseDouble(value);
} else if (clazz == Boolean.class) {
return Boolean.parseBoolean(value);
} else if (clazz == Byte.class) {
return Byte.parseByte(value);
} else if (clazz == Short.class) {
return Short.parseShort(value);
} else if (clazz == Float.class) {
return Float.parseFloat(value);
} else {
throw new Exception("Unsupported primitive: " + clazz); //$NON-NLS-1$
}
} | java | public static Object readPrimitive(Class<?> clazz, String value) throws Exception {
if (clazz == String.class) {
return value;
} else if (clazz == Long.class) {
return Long.parseLong(value);
} else if (clazz == Integer.class) {
return Integer.parseInt(value);
} else if (clazz == Double.class) {
return Double.parseDouble(value);
} else if (clazz == Boolean.class) {
return Boolean.parseBoolean(value);
} else if (clazz == Byte.class) {
return Byte.parseByte(value);
} else if (clazz == Short.class) {
return Short.parseShort(value);
} else if (clazz == Float.class) {
return Float.parseFloat(value);
} else {
throw new Exception("Unsupported primitive: " + clazz); //$NON-NLS-1$
}
} | [
"public",
"static",
"Object",
"readPrimitive",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"value",
")",
"throws",
"Exception",
"{",
"if",
"(",
"clazz",
"==",
"String",
".",
"class",
")",
"{",
"return",
"value",
";",
"}",
"else",
"if",
"(",
... | Parses the String value as a primitive or a String, depending on its type.
@param clazz the destination type
@param value the value to parse
@return the parsed value
@throws Exception | [
"Parses",
"the",
"String",
"value",
"as",
"a",
"primitive",
"or",
"a",
"String",
"depending",
"on",
"its",
"type",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/storage-common/src/main/java/io/apiman/gateway/engine/storage/util/BackingStoreUtil.java#L41-L61 | train |
apiman/apiman | gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/ESSharedStateComponent.java | ESSharedStateComponent.readPrimitive | protected Object readPrimitive(JestResult result) throws Exception {
PrimitiveBean pb = result.getSourceAsObject(PrimitiveBean.class);
String value = pb.getValue();
Class<?> c = Class.forName(pb.getType());
return BackingStoreUtil.readPrimitive(c, value);
} | java | protected Object readPrimitive(JestResult result) throws Exception {
PrimitiveBean pb = result.getSourceAsObject(PrimitiveBean.class);
String value = pb.getValue();
Class<?> c = Class.forName(pb.getType());
return BackingStoreUtil.readPrimitive(c, value);
} | [
"protected",
"Object",
"readPrimitive",
"(",
"JestResult",
"result",
")",
"throws",
"Exception",
"{",
"PrimitiveBean",
"pb",
"=",
"result",
".",
"getSourceAsObject",
"(",
"PrimitiveBean",
".",
"class",
")",
";",
"String",
"value",
"=",
"pb",
".",
"getValue",
"... | Reads a stored primitive.
@param result | [
"Reads",
"a",
"stored",
"primitive",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/ESSharedStateComponent.java#L150-L155 | train |
apiman/apiman | gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/components/HttpClientRequestImpl.java | HttpClientRequestImpl.connect | private void connect() {
try {
URL url = new URL(this.endpoint);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(this.readTimeoutMs);
connection.setConnectTimeout(this.connectTimeoutMs);
connection.setRequestMethod(this.method.name());
if (method == HttpMethod.POST || method == HttpMethod.PUT) {
connection.setDoOutput(true);
} else {
connection.setDoOutput(false);
}
connection.setDoInput(true);
connection.setUseCaches(false);
for (String headerName : headers.keySet()) {
String headerValue = headers.get(headerName);
connection.setRequestProperty(headerName, headerValue);
}
connection.connect();
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | private void connect() {
try {
URL url = new URL(this.endpoint);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(this.readTimeoutMs);
connection.setConnectTimeout(this.connectTimeoutMs);
connection.setRequestMethod(this.method.name());
if (method == HttpMethod.POST || method == HttpMethod.PUT) {
connection.setDoOutput(true);
} else {
connection.setDoOutput(false);
}
connection.setDoInput(true);
connection.setUseCaches(false);
for (String headerName : headers.keySet()) {
String headerValue = headers.get(headerName);
connection.setRequestProperty(headerName, headerValue);
}
connection.connect();
} catch (Exception e) {
throw new RuntimeException(e);
}
} | [
"private",
"void",
"connect",
"(",
")",
"{",
"try",
"{",
"URL",
"url",
"=",
"new",
"URL",
"(",
"this",
".",
"endpoint",
")",
";",
"connection",
"=",
"(",
"HttpURLConnection",
")",
"url",
".",
"openConnection",
"(",
")",
";",
"connection",
".",
"setRead... | Connect to the remote server. | [
"Connect",
"to",
"the",
"remote",
"server",
"."
] | 8c049c2a2f2e4a69bbb6125686a15edd26f29c21 | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/components/HttpClientRequestImpl.java#L151-L173 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.