Search in sources :

Example 31 with XPathEvalException

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

the class VTDUtils method getValue.

/**
	 * <p>
	 * 根据 XPath 取值(XPath 支持相对定位)。<br/>
	 * 使用此方法时,可以结合 {@link #pilot(String)} 或 {@link #pilot(AutoPilot, String)} 方法采用相对定位,可以大大提高导航效率
	 * </p>
	 * <b>注意</b>在XPath基础上,添加关键字“[name]”、“puretext()”的支持: <li>[name]:用于取得指定属性名称,例如,/a/@*[name] 取得 a 节点下所有属性的名字</li> <li>
	 * puretext():用于取得指定节点的纯文本内容(排除子节点),例如,/a/puretext() 取得 a 节点的纯文本内容</li>
	 * @param ap
	 *            AutoPilot 实例
	 * @param xpath
	 *            XPath 表达式
	 * @param defaultValue
	 *            默认值
	 * @return XPath 得到的值;
	 */
public String getValue(AutoPilot ap, String xpath, String defaultValue) {
    if (ap == null) {
        ap = new AutoPilot(vn);
    }
    String value = null;
    try {
        vn.push();
        if (xpath.endsWith("/puretext()")) {
            xpath = xpath.substring(0, xpath.length() - "/puretext()".length());
            ap.selectXPath(xpath);
            if (ap.evalXPath() != -1) {
                value = getElementPureText();
            }
        } else if (xpath.endsWith("/text()")) {
            xpath = xpath.substring(0, xpath.length() - "/text()".length());
            ap.selectXPath(xpath);
            if (ap.evalXPath() != -1) {
                value = getElementContent();
            }
        } else {
            // 是否是取属性名字
            boolean isAttrName = false;
            if (xpath.endsWith("[name]")) {
                xpath = xpath.substring(0, xpath.length() - "[name]".length());
                isAttrName = true;
            }
            ap.selectXPath(xpath);
            if (ap.evalXPath() != -1) {
                int type = vn.getTokenType(vn.getCurrentIndex());
                if (type == VTDNav.TOKEN_STARTING_TAG) {
                    long l = vn.getElementFragment();
                    value = vn.toString((int) l, (int) (l >> 32));
                } else if (type == VTDNav.TOKEN_ATTR_NAME || type == VTDNav.TOKEN_ATTR_NS) {
                    if (isAttrName) {
                        value = vn.toString(vn.getCurrentIndex());
                    } else {
                        value = vn.toString(vn.getCurrentIndex() + 1);
                    }
                } else {
                    value = vn.toString(vn.getCurrentIndex());
                }
            }
        }
    } catch (XPathParseException e) {
        LOGGER.error("", e);
    } catch (XPathEvalException e) {
        LOGGER.error("", e);
    } catch (NavException e) {
        LOGGER.error("", e);
    } finally {
        vn.pop();
    }
    return value == null ? defaultValue : value;
}
Also used : XPathParseException(com.ximpleware.XPathParseException) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException)

Example 32 with XPathEvalException

use of com.ximpleware.XPathEvalException 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 33 with XPathEvalException

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

the class VTDUtils method getValues.

/**
	 * 根据 XPath 取一个集合的值。<br/>
	 * <b>注意</b>在XPath基础上,添加关键字“[name]”、“puretext()”的支持: <li>[name]:用于取得指定属性名称,例如,/a/@*[name] 取得 a 节点下所有属性的名字</li> <li>
	 * puretext():用于取得指定节点的纯文本内容(排除子节点),例如,/a/puretext() 取得 a 节点的纯文本内容</li>
	 * @param ap
	 *            AutoPilot 对象
	 * @param xpath
	 *            XPath 表达式
	 * @param isAllowRepeat
	 *            是否允许取值重复。
	 * @return XPath 得到的值,无匹配的值则为 null;
	 */
public List<String> getValues(AutoPilot ap, String xpath, boolean isAllowRepeat) {
    if (ap == null) {
        ap = new AutoPilot(vn);
    }
    List<String> values = new Vector<String>();
    try {
        vn.push();
        if (xpath.endsWith("/puretext()")) {
            xpath = xpath.substring(0, xpath.length() - "/puretext()".length());
            ap.selectXPath(xpath);
            if (ap.evalXPath() != -1) {
                String strTmpValue = getElementPureText();
                if (isAllowRepeat) {
                    values.add(strTmpValue);
                } else {
                    if (!values.contains(strTmpValue)) {
                        values.add(strTmpValue);
                    }
                }
            }
        } else if (xpath.endsWith("/text()")) {
            xpath = xpath.substring(0, xpath.length() - "/text()".length());
            ap.selectXPath(xpath);
            while (ap.evalXPath() != -1) {
                String strTmpValue = getElementContent();
                if (isAllowRepeat) {
                    values.add(strTmpValue);
                } else {
                    if (!values.contains(strTmpValue)) {
                        values.add(strTmpValue);
                    }
                }
            }
        } else {
            boolean isAttrName = false;
            if (xpath.endsWith("[name]")) {
                xpath = xpath.substring(0, xpath.length() - "[name]".length());
                isAttrName = true;
            }
            ap.selectXPath(xpath);
            while (ap.evalXPath() != -1) {
                int type = vn.getTokenType(vn.getCurrentIndex());
                if (type == VTDNav.TOKEN_STARTING_TAG) {
                    long l = vn.getElementFragment();
                    String strTmpValue = vn.toString((int) l, (int) (l >> 32));
                    if (isAllowRepeat) {
                        values.add(strTmpValue);
                    } else {
                        if (!values.contains(strTmpValue)) {
                            values.add(strTmpValue);
                        }
                    }
                } else if (type == VTDNav.TOKEN_ATTR_NAME || type == VTDNav.TOKEN_ATTR_NS) {
                    String strTmpValue;
                    if (isAttrName) {
                        strTmpValue = vn.toString(vn.getCurrentIndex());
                    } else {
                        strTmpValue = vn.toString(vn.getCurrentIndex() + 1);
                    }
                    if (isAllowRepeat) {
                        values.add(strTmpValue);
                    } else {
                        if (!values.contains(strTmpValue)) {
                            values.add(strTmpValue);
                        }
                    }
                } else {
                    String strTmpValue = vn.toString(vn.getCurrentIndex());
                    if (isAllowRepeat) {
                        values.add(strTmpValue);
                    } else {
                        if (!values.contains(strTmpValue)) {
                            values.add(strTmpValue);
                        }
                    }
                }
            }
        }
    } catch (XPathParseException e) {
        LOGGER.error("", e);
    } catch (XPathEvalException e) {
        LOGGER.error("", e);
    } catch (NavException e) {
        LOGGER.error("", e);
    } finally {
        vn.pop();
    }
    if (values.size() == 0) {
        values = null;
    }
    return values;
}
Also used : XPathParseException(com.ximpleware.XPathParseException) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) Vector(java.util.Vector)

Example 34 with XPathEvalException

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

the class DocUtils method isTMX.

/**
	 * 判断是否是正确的 TMX 文件
	 * @param fileName
	 * @return ;
	 * @throws FileNotFoundException
	 * @throws ParseException
	 * @throws EntityException
	 * @throws EOFException
	 * @throws EncodingException
	 */
public static VTDUtils isTMX(String fileName) throws FileNotFoundException, EncodingException, ParseException {
    VTDGen vg = new VTDGen();
    FileInputStream fis = null;
    File f = null;
    try {
        f = new File(fileName);
        fis = new FileInputStream(f);
        byte[] b = new byte[(int) f.length()];
        int offset = 0;
        int numRead = 0;
        // I choose this value randomally,
        int numOfBytes = 1048576;
        // any other (not too big) value also can be here.
        if (b.length - offset < numOfBytes) {
            numOfBytes = b.length - offset;
        }
        while (offset < b.length && (numRead = fis.read(b, offset, numOfBytes)) >= 0) {
            offset += numRead;
            if (b.length - offset < numOfBytes) {
                numOfBytes = b.length - offset;
            }
        }
        vg.setDoc(b);
        vg.parse(true);
    } catch (IOException e) {
        LOGGER.error(Messages.getString("document.DocUtils.logger1"), e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
    }
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    String rootPath = "/tmx";
    VTDUtils vu = new VTDUtils();
    try {
        vu.bind(vn);
        ap.selectXPath(rootPath);
        if (ap.evalXPath() == -1) {
            return null;
        }
    } catch (NavException e) {
        LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
        return null;
    } catch (XPathEvalException e) {
        LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
        return null;
    } catch (XPathParseException e) {
        LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
        return null;
    } finally {
        vg.clear();
    }
    return vu;
}
Also used : NavException(com.ximpleware.NavException) XPathEvalException(com.ximpleware.XPathEvalException) VTDGen(com.ximpleware.VTDGen) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) EOFException(com.ximpleware.EOFException) XPathParseException(com.ximpleware.XPathParseException) NavException(com.ximpleware.NavException) IOException(java.io.IOException) EncodingException(com.ximpleware.EncodingException) FileNotFoundException(java.io.FileNotFoundException) ParseException(com.ximpleware.ParseException) XPathEvalException(com.ximpleware.XPathEvalException) EntityException(com.ximpleware.EntityException) XPathParseException(com.ximpleware.XPathParseException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) File(java.io.File) VTDNav(com.ximpleware.VTDNav)

Example 35 with XPathEvalException

use of com.ximpleware.XPathEvalException 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)

Aggregations

NavException (com.ximpleware.NavException)65 XPathEvalException (com.ximpleware.XPathEvalException)65 XPathParseException (com.ximpleware.XPathParseException)65 AutoPilot (com.ximpleware.AutoPilot)59 VTDNav (com.ximpleware.VTDNav)44 VTDUtils (net.heartsome.xml.vtdimpl.VTDUtils)36 ModifyException (com.ximpleware.ModifyException)17 ArrayList (java.util.ArrayList)17 XMLModifier (com.ximpleware.XMLModifier)15 IOException (java.io.IOException)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 VTDGen (com.ximpleware.VTDGen)11 HashMap (java.util.HashMap)9 ParseException (com.ximpleware.ParseException)8 TranscodeException (com.ximpleware.TranscodeException)7 FileNotFoundException (java.io.FileNotFoundException)7 FileOutputStream (java.io.FileOutputStream)6 EOFException (com.ximpleware.EOFException)5 EncodingException (com.ximpleware.EncodingException)5 EntityException (com.ximpleware.EntityException)5