use of com.ximpleware.XMLModifier in project revapi by revapi.
the class ConvertToXmlConfigMojo method updateAllConfigurations.
private static void updateAllConfigurations(File pomXml, Map<String, ModelNode> extensionSchemas, int indentationSize) throws Exception {
VTDGen gen = new VTDGen();
gen.enableIgnoredWhiteSpace(true);
gen.parseFile(pomXml.getAbsolutePath(), true);
VTDNav nav = gen.getNav();
XMLModifier mod = new XMLModifier(nav);
Callable<Void> update = () -> {
int textPos = nav.getText();
String jsonConfig = nav.toRawString(textPos);
PlexusConfiguration xml = convertToXml(extensionSchemas, jsonConfig);
if (xml == null) {
return null;
}
StringWriter pretty = new StringWriter();
XmlUtil.toIndentedString(xml, indentationSize, nav.getTokenDepth(textPos), pretty);
// remove the first indentation, because text is already indented
String prettyXml = pretty.toString().substring(indentationSize * nav.getTokenDepth(textPos));
mod.insertAfterElement(prettyXml);
mod.remove();
return null;
};
AutoPilot ap = new AutoPilot(nav);
ap.selectXPath("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']/configuration/analysisConfiguration");
while (ap.evalXPath() != -1) {
update.call();
}
ap.resetXPath();
ap.selectXPath("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']/executions/execution/configuration/analysisConfiguration");
while (ap.evalXPath() != -1) {
update.call();
}
try (OutputStream out = new FileOutputStream(pomXml)) {
mod.output(out);
}
}
use of com.ximpleware.XMLModifier in project revapi by revapi.
the class ConvertToXmlConfigMojo method updateAllConfigurationFiles.
private void updateAllConfigurationFiles(MavenProject project, Map<String, ModelNode> extensionSchemas, int indentationSize) throws Exception {
VTDGen gen = new VTDGen();
gen.enableIgnoredWhiteSpace(true);
gen.parseFile(project.getFile().getAbsolutePath(), true);
VTDNav nav = gen.getNav();
XMLModifier mod = new XMLModifier(nav);
AutoPilot ap = new AutoPilot(nav);
ThrowingConsumer<String> update = xpath -> {
ap.resetXPath();
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
int textPos = nav.getText();
String configFile = nav.toString(textPos);
File newFile = updateConfigurationFile(new File(configFile), extensionSchemas, indentationSize);
if (newFile == null) {
continue;
}
mod.updateToken(textPos, newFile.getPath());
}
};
update.accept("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']" + "/configuration/analysisConfigurationFiles/*[not(self::configurationFile)]");
update.accept("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']" + "/configuration/analysisConfigurationFiles/configurationFile[not(roots)]/path");
update.accept("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']" + "/executions/execution/configuration/analysisConfigurationFiles/*[not(self::configurationFile)]");
update.accept("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']" + "/executions/execution/configuration/analysisConfigurationFiles/configurationFile[not(roots)]/path");
try (OutputStream out = new FileOutputStream(project.getFile())) {
mod.output(out);
}
}
use of com.ximpleware.XMLModifier in project translationstudio8 by heartsome.
the class VTDUtils method handleXML.
/**
* 处理 XPath 表达式所定位到的 XML 内容
* @param ap
* AutoPilot 实例
* @param xm
* XMLModifier 实例
* @param xpath
* xpath表达式
* @param newValue
* 要修改的新值
* @param condition
* 本次操作的限定条件
* @return XMLModifier 实例;
*/
private XMLModifier handleXML(AutoPilot ap, XMLModifier xm, String xpath, String newValue, int condition, boolean remove) {
try {
vn.push();
if (ap == null) {
ap = new AutoPilot(vn);
}
if (xm == null) {
xm = new XMLModifier(vn);
}
boolean pilotToEnd = (condition & PILOT_TO_END) != 0;
boolean isContent = false;
if (xpath.endsWith("/text()")) {
// 操作的是内容节点。
xpath = xpath.substring(0, xpath.length() - "/text()".length());
isContent = true;
}
ap.selectXPath(xpath);
boolean exist = false;
while (ap.evalXPath() != -1) {
exist = true;
long contentFragment = vn.getContentFragment();
int currentIndex = vn.getCurrentIndex();
int type = vn.getTokenType(currentIndex);
if (remove || newValue == null) {
// newValue 为 null,执行移除操作
if (isContent) {
if (contentFragment != -1) {
// 执行删除
// 删除内容
xm.remove(contentFragment);
}
} else {
// 属性节点不执行删除,除非调用 delete 方法(判断是否调用 delete 方法的依据是,newValue 是否为 null)
if ((type != VTDNav.TOKEN_ATTR_NAME && type != VTDNav.TOKEN_ATTR_NS) || newValue == null) {
// 删除节点
xm.remove();
}
}
}
if (newValue != null) {
// 执行修改
if (isContent) {
xm.insertBeforeTail(newValue.getBytes(getCharsetByEncoding()));
} else {
if (type == VTDNav.TOKEN_STARTING_TAG) {
xm.insertAfterElement(newValue);
} else if (type == VTDNav.TOKEN_ATTR_NAME || type == VTDNav.TOKEN_ATTR_NS) {
xm.updateToken(currentIndex + 1, newValue);
} else {
xm.updateToken(currentIndex, newValue.getBytes());
}
}
}
if (!pilotToEnd) {
// 不需要导航到 XML 末尾,停止循环
break;
}
}
boolean createIfNotExist = (condition & CREATE_IF_NOT_EXIST) != 0;
if (!exist && createIfNotExist) {
// 如果不存在并且需要创建
int lastSeperator = xpath.lastIndexOf("/");
String nodeName = xpath.substring(lastSeperator + 1);
// 截掉最后一部分
xpath = xpath.substring(0, lastSeperator);
if (nodeName.startsWith("@")) {
nodeName = nodeName.substring(1);
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
// 插入属性
insertAttribute(xm, nodeName, newValue);
if (!pilotToEnd) {
// 不需要导航到 XML 末尾,停止循环
break;
}
}
} else {
if (isContent) {
// 如果改动的是节点内容
newValue = getNodeXML(nodeName, newValue, null);
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
xm.insertAfterHead(newValue);
if (!pilotToEnd) {
// 不需要导航到 XML 末尾,停止循环
break;
}
}
}
}
}
} catch (XPathParseException e) {
LOGGER.error("", e);
} catch (XPathEvalException e) {
LOGGER.error("", e);
} catch (NavException e) {
LOGGER.error("", e);
} catch (ModifyException e) {
LOGGER.error("", e);
} catch (UnsupportedEncodingException e) {
LOGGER.error("", e);
} finally {
vn.pop();
}
return xm;
}
use of com.ximpleware.XMLModifier in project translationstudio8 by heartsome.
the class Docx2Xliff method idealizeGTag.
/**
* 简化 xliff 文件的标记,主要功能是将一个源文中的 g 标记进行抽取到骨架的操作。针对一个源文中只有一个 g 标记,并且该 g 标记包褒全文本段
* 生成一个 名为 interTag.xml 的文件,存放于骨架文件的第一级子目录,与 word 文件夹同目录
* 其结构大致为<br>
* <docxTags><br>
* <tag tuId="0" >this is a tag</tag><br>
* </docxTags><br>
* <div style="color:red">备注:interTag.xml 介绍: 此文件并非 docx 的内部文件,而是保存转换 docx 文件时的部份 g标记(源文中只有一对 g 标记,并且是它包褒一整个文本段)</div>
*/
private static void idealizeGTag(String xliffPath, String interTagPath) throws Exception {
final String constantGHeader = "<g";
final String constantGEnd = "</g>";
VTDGen vg = new VTDGen();
if (!vg.parseFile(xliffPath, true)) {
throw new Exception();
}
VTDNav vn = vg.getNav();
String xpath = "/xliff/file/body/descendant::trans-unit[source/text()!='' or source/*]";
AutoPilot ap = new AutoPilot(vn);
AutoPilot childAP = new AutoPilot(vn);
VTDUtils vu = new VTDUtils(vn);
XMLModifier xm = new XMLModifier(vn);
ap.selectXPath(xpath);
int index = -1;
String id = null;
StringBuffer tagContentSB = new StringBuffer();
while (ap.evalXPath() != -1) {
id = null;
index = vn.getAttrVal("id");
if (index != -1) {
id = vn.toString(index);
}
if (id == null) {
vn.pop();
continue;
}
vn.push();
childAP.selectXPath("./source");
if (childAP.evalXPath() == -1) {
vn.pop();
continue;
}
String srcText = vu.getElementContent();
childAP.selectXPath("count(./g)");
// 如果 g 标签个数为 1 ,并且包褒整个文本段,那么便可进行清理
if (childAP.evalXPathToNumber() == 1) {
if (srcText.indexOf(constantGHeader) == 0 && srcText.indexOf(constantGEnd) == (srcText.length() - 4)) {
childAP.selectXPath("./g");
if (childAP.evalXPath() != -1) {
String header = vu.getElementHead();
String content = vu.getElementContent();
// 删除 g 标记
xm.remove();
xm.insertAfterElement(content);
// 将删除的 g 标记保存至 interTag.xml 文件中
tagContentSB.append("\t<tag tuId=\"" + id + "\">" + header + "</g>" + "</tag>\n");
}
}
}
vn.pop();
}
xm.output(xliffPath);
if (tagContentSB.length() > 0) {
// 开始创建 interTag.xml 文件
File file = new File(interTagPath);
if (!file.exists()) {
FileOutputStream output;
output = new FileOutputStream(interTagPath);
output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes("UTF-8"));
output.write("<docxTags>\n".getBytes("UTF-8"));
output.write(tagContentSB.toString().getBytes("UTF-8"));
output.write("</docxTags>".getBytes("UTF-8"));
output.close();
}
}
}
use of com.ximpleware.XMLModifier in project translationstudio8 by heartsome.
the class XLFHandler method splitSegment.
/**
* 分割文本段
* @param rowId
* 要分割的行的RowId
* @param spltOffset
* 分割的位置;
* @return ;
*/
public String splitSegment(String rowId, int spltOffset) {
String fileName = RowIdUtil.getFileNameByRowId(rowId);
VTDNav vn = vnMap.get(fileName);
AutoPilot ap = new AutoPilot(vn);
ap.declareXPathNameSpace(hsNSPrefix, hsR7NSUrl);
String xpath = RowIdUtil.parseRowIdToXPath(rowId);
try {
VTDUtils vu = new VTDUtils(vn);
ap.selectXPath(xpath);
if (ap.evalXPath() == -1) {
return "";
}
String tuid = vu.getCurrentElementAttribut("id", "");
String xmlSpace = vu.getCurrentElementAttribut("xml:space", "preserve");
String approved = vu.getCurrentElementAttribut("approved", null);
String sendToTM = vu.getCurrentElementAttribut("hs:send-to-tm", null);
String needReview = vu.getCurrentElementAttribut("hs:needs-review", null);
String tuHead = vu.getElementHead();
// 删除 approved 属性
if (approved != null) {
tuHead = tuHead.replace(" approved=\"" + approved + "\"", "");
tuHead = tuHead.replace(" approved='" + approved + "'", "");
}
// tuHead2 删除 hs:send-to-tm, hs:needs-review 属性
String tuHead2 = tuHead;
if (sendToTM != null) {
tuHead2 = tuHead2.replace(" hs:send-to-tm=\"" + sendToTM + "\"", "");
tuHead2 = tuHead2.replace(" hs:send-to-tm='" + sendToTM + "'", "");
}
if (needReview != null) {
tuHead2 = tuHead2.replace(" hs:needs-review=\"" + needReview + "\"", "");
tuHead2 = tuHead2.replace(" hs:needs-review='" + needReview + "'", "");
}
StringBuffer tu1;
StringBuffer tu2;
if (tuHead.contains("id=\"" + tuid + "\"")) {
tu1 = new StringBuffer(tuHead.replace("id=\"" + tuid + "\"", "id=\"" + tuid + "-1\""));
tu2 = new StringBuffer(tuHead2.replace("id=\"" + tuid + "\"", "id=\"" + tuid + "-2\""));
} else if (tuHead.contains("id='" + tuid + "'")) {
tu1 = new StringBuffer(tuHead.replace("id='" + tuid + "'", "id=\"" + tuid + "-1\""));
tu2 = new StringBuffer(tuHead2.replace("id='" + tuid + "'", "id=\"" + tuid + "-2\""));
} else {
// 不存在 id 属性
return "";
}
String sourceFragment1 = null;
String sourceFragment2 = null;
String targetFragment1 = null;
String targetFragment2 = null;
ap.selectXPath(xpath + "/source");
if (ap.evalXPath() != -1) {
String sourceHead = vu.getElementHead();
if (sourceHead != null) {
// source节点的内容
String sourceContent = vu.getElementContent();
// 处理光标在 g 标记内的情况 --robert 2012-11-15
List<Map<String, String>> tagLocationList = getTagLocation(vn, sourceContent);
String srcAddStr1 = "";
String srcAddStr2 = "";
for (Map<String, String> map : tagLocationList) {
String tagHeader = map.get("tagHeader");
String tagTail = map.get("tagTail");
int headerIdx = Integer.parseInt(map.get("headerIdx"));
int tailIdx = Integer.parseInt(map.get("tailIdx"));
if (headerIdx < spltOffset && spltOffset <= tailIdx) {
srcAddStr1 = tagTail + srcAddStr1;
srcAddStr2 += tagHeader;
}
}
sourceFragment1 = sourceHead + sourceContent.substring(0, spltOffset) + srcAddStr1 + "</source>";
sourceFragment2 = sourceHead + srcAddStr2 + sourceContent.substring(spltOffset) + "</source>";
}
}
ap.selectXPath(xpath + "/target");
if (ap.evalXPath() != -1) {
String state = vu.getCurrentElementAttribut("state", null);
String targetHead = vu.getElementHead();
if (targetHead != null) {
if (state != null && !state.equalsIgnoreCase("new")) {
targetHead = targetHead.replace(" state=\"" + state + "\"", " state=\"new\"");
targetHead = targetHead.replace(" state='" + state + "'", " state=\"new\"");
targetFragment1 = targetHead + vu.getElementContent() + "</target>";
} else {
// target节点的段落
targetFragment1 = vu.getElementFragment();
}
// targetFragment2 = targetHead + "</target>";
// modify by peason---- Bug #1048
targetFragment2 = "<target></target>";
}
}
if (sourceFragment1 != null) {
tu1.append(sourceFragment1);
}
if (targetFragment1 != null) {
tu1.append(targetFragment1);
}
if (sourceFragment2 != null) {
tu2.append(sourceFragment2);
}
if (targetFragment2 != null) {
tu2.append(targetFragment2);
}
// 批注信息添加到分割后的第一个文本段中
ap.selectXPath(xpath + "/note");
while (ap.evalXPath() != -1) {
tu1.append(vu.getElementFragment());
}
tu1.append("</trans-unit>");
tu2.append("</trans-unit>");
StringBuffer group = new StringBuffer("<group ");
group.append("id=\"" + tuid + "\" ");
group.append("ts=\"hs-split\" ");
group.append("splitMergeIndex=\"" + System.nanoTime() + "\" ");
group.append("xml:space=\"" + xmlSpace + "\">");
group.append(tu1).append(tu2);
group.append("</group>");
String tuFragment = "";
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
XMLModifier xm = new XMLModifier(vn);
xm.insertBeforeElement(group.toString());
// 保存修改前的内容
tuFragment = vu.getElementFragment();
xm.remove();
// 保存并更新VTDNav对象
saveAndReparse(xm, fileName);
int index = rowIds.indexOf(rowId);
// 移除分割前的RowId
rowIds.remove(index);
// 添加分割后的RowId
rowIds.add(index, rowId + "-2");
rowIds.add(index, rowId + "-1");
int tuSize = tuSizeMap.get(fileName);
// 翻译单元总数加1
tuSizeMap.put(fileName, tuSize + 1);
}
return tuFragment;
} catch (XPathParseException e) {
LOGGER.error("", e);
e.printStackTrace();
} catch (XPathEvalException e) {
LOGGER.error("", e);
e.printStackTrace();
} catch (NavException e) {
LOGGER.error("", e);
e.printStackTrace();
} catch (ModifyException e) {
LOGGER.error("", e);
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
LOGGER.error("", e);
e.printStackTrace();
}
return "";
}
Aggregations