Search in sources :

Example 26 with ModifyException

use of com.ximpleware.ModifyException 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;
}
Also used : XPathParseException(com.ximpleware.XPathParseException) XMLModifier(com.ximpleware.XMLModifier) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) ModifyException(com.ximpleware.ModifyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 27 with ModifyException

use of com.ximpleware.ModifyException in project translationstudio8 by heartsome.

the class VTDUtils method insertAttribute.

/**
	 * 插入新属性(到最后的位置)。
	 * @param xm
	 * @param attrName
	 * @param attrValue
	 * @throws ModifyException
	 *             ;
	 */
private void insertAttribute(XMLModifier xm, String attrName, String attrValue) throws ModifyException {
    int startTagIndex = vn.getCurrentIndex();
    int type = vn.getTokenType(startTagIndex);
    if (type != VTDNav.TOKEN_STARTING_TAG)
        throw new ModifyException("Token type is not a starting tag");
    String attrFragment = new StringBuffer(" ").append(attrName).append("=\"").append(attrValue).append("\"").toString();
    // 得到开始标记的结束位置
    long i = vn.getOffsetAfterHead();
    if (vn.getEncoding() < VTDNav.FORMAT_UTF_16BE) {
        xm.insertBytesAt((int) i - 1, attrFragment.getBytes());
    } else {
        xm.insertBytesAt(((int) i - 1) << 1, attrFragment.getBytes());
    }
}
Also used : ModifyException(com.ximpleware.ModifyException)

Example 28 with ModifyException

use of com.ximpleware.ModifyException in project translationstudio8 by heartsome.

the class XLFHandler method updateAltTrans.

private void updateAltTrans(VTDUtils vu, XMLModifier xm, String rowId, List<AltTransBean> newAltTrans, List<String> oldAltTransToolId) {
    String tuXPath = RowIdUtil.parseRowIdToXPath(rowId);
    AutoPilot ap = new AutoPilot(vu.getVTDNav());
    ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
    ap.declareXPathNameSpace(hsNSPrefix, hsR7NSUrl);
    try {
        ap.selectXPath(tuXPath);
        if (ap.evalXPath() != -1) {
            StringBuffer bf = new StringBuffer();
            for (String toolId : oldAltTransToolId) {
                bf.append("@tool-id='").append(toolId).append("' | ");
            }
            if (bf.length() > 0) {
                String toolId = bf.substring(0, bf.lastIndexOf("|"));
                String deleteXpath = "./alt-trans[" + toolId + "]";
                AutoPilot _ap = new AutoPilot(vu.getVTDNav());
                _ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
                _ap.declareXPathNameSpace(hsNSPrefix, hsR7NSUrl);
                vu.delete(_ap, xm, deleteXpath, VTDUtils.PILOT_TO_END);
            }
            StringBuffer xmlBf = new StringBuffer();
            for (AltTransBean altTran : newAltTrans) {
                xmlBf.append(altTran.toXMLString());
            }
            if (xmlBf.length() > 0) {
                xm.insertBeforeTail(xmlBf.toString());
            }
        }
    } catch (XPathParseException e) {
        LOGGER.error("", e);
    } catch (XPathEvalException e) {
        LOGGER.error("", e);
    } catch (ModifyException e) {
        LOGGER.error("", e);
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("", e);
    } catch (NavException e) {
        LOGGER.error("", e);
    }
}
Also used : XPathParseException(com.ximpleware.XPathParseException) AltTransBean(net.heartsome.cat.ts.core.bean.AltTransBean) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) ModifyException(com.ximpleware.ModifyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 29 with ModifyException

use of com.ximpleware.ModifyException 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 "";
}
Also used : XMLModifier(com.ximpleware.XMLModifier) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) XPathParseException(com.ximpleware.XPathParseException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) ModifyException(com.ximpleware.ModifyException) VTDNav(com.ximpleware.VTDNav) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 30 with ModifyException

use of com.ximpleware.ModifyException in project translationstudio8 by heartsome.

the class XLFHandler method resetSplitSegment.

/**
	 * 恢复分割的文本段
	 * @param rowId
	 *            唯一标识
	 * @param tuFragment
	 *            翻译单元的原始XML文本;
	 */
public void resetSplitSegment(String rowId, String tuFragment) {
    String groupXPath = RowIdUtil.parseRowIdToGroupXPath(rowId);
    String fileName = RowIdUtil.getFileNameByRowId(rowId);
    VTDNav vn = vnMap.get(fileName);
    AutoPilot ap = new AutoPilot(vn);
    try {
        ap.selectXPath(groupXPath);
        if (ap.evalXPath() != -1) {
            XMLModifier xm = new XMLModifier(vn);
            // 添加 trans-unit 节点
            xm.insertBeforeElement(tuFragment);
            // 删除 group 节点
            xm.remove(vn.getElementFragment());
            saveAndReparse(xm, fileName);
            int index = rowIds.indexOf(rowId + "-1");
            // 添加分割前的RowId
            rowIds.add(index, rowId);
            rowIds.remove(rowId + "-1");
            // 移除分割后的RowId
            rowIds.remove(rowId + "-2");
        }
    } 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();
    }
}
Also used : XPathParseException(com.ximpleware.XPathParseException) XMLModifier(com.ximpleware.XMLModifier) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) ModifyException(com.ximpleware.ModifyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) VTDNav(com.ximpleware.VTDNav)

Aggregations

ModifyException (com.ximpleware.ModifyException)35 NavException (com.ximpleware.NavException)27 XMLModifier (com.ximpleware.XMLModifier)25 AutoPilot (com.ximpleware.AutoPilot)20 XPathParseException (com.ximpleware.XPathParseException)20 XPathEvalException (com.ximpleware.XPathEvalException)18 VTDUtils (net.heartsome.xml.vtdimpl.VTDUtils)18 TranscodeException (com.ximpleware.TranscodeException)17 IOException (java.io.IOException)17 VTDNav (com.ximpleware.VTDNav)16 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 FileOutputStream (java.io.FileOutputStream)12 BufferedOutputStream (java.io.BufferedOutputStream)10 ArrayList (java.util.ArrayList)7 ParseException (com.ximpleware.ParseException)6 VTDGen (com.ximpleware.VTDGen)6 List (java.util.List)6 LinkedList (java.util.LinkedList)5 FileNotFoundException (java.io.FileNotFoundException)4 HashMap (java.util.HashMap)4