2 * copyright(c) 2005 kuwata-lab all rights reserved.
7 import java.util.HashMap;
8 import java.util.IdentityHashMap;
10 import java.util.Iterator;
13 * yaml parser which can keep line number of path.
15 public class YamlParser extends PlainYamlParser {
16 private Map linenumsTable = new IdentityHashMap(); // object => sequence or mapping
17 private int firstLinenum = -1;
18 private Object document = null;
20 YamlParser(String yamlStr) {
24 public Object parse() throws SyntaxException {
25 document = super.parse();
29 protected String getLine() {
30 String line = super.getLine();
31 if (firstLinenum < 0) {
32 firstLinenum = currentLineNumber();
38 private int getPathLineNumber(String ypath) throws InvalidPathException {
39 if (document == null) {
42 if (ypath.length() == 0 || "/".equals(ypath)) {
45 String[] elems = ypath.split("/");
46 String lastElem = elems.length > 0 ? elems[elems.length - 1] : null;
47 int i = ypath.charAt(0) == '/' ? 1 : 0;
48 int len = elems.length - 1;
49 Object documentCollection = this.document; // collection
50 for ( ; i < len ; i++) {
51 if (documentCollection == null) {
52 throw new InvalidPathException(ypath);
53 } else if (documentCollection instanceof Map) {
54 documentCollection = ((Map)documentCollection).get(elems[i]);
55 } else if (documentCollection instanceof List) {
56 int index = Integer.parseInt(elems[i]);
57 if (index < 0 || ((List)documentCollection).size() < index) {
58 throw new InvalidPathException(ypath);
60 documentCollection = ((List)documentCollection).get(index);
62 throw new InvalidPathException(ypath);
66 if (documentCollection == null) {
67 throw new InvalidPathException(ypath);
69 Object linenums = linenumsTable.get(documentCollection); // Map or List
71 if (documentCollection instanceof Map) {
72 assert linenums instanceof Map;
73 Object d = ((Map)linenums).get(lastElem);
74 linenum = (Integer) d;
75 } else if (documentCollection instanceof List) {
76 assert linenums instanceof List;
77 int index = Integer.parseInt(lastElem);
78 if (index < 0 || ((List)linenums).size() <= index) {
79 throw new InvalidPathException(ypath);
81 Object d = ((List)linenums).get(index);
82 linenum = (Integer) d;
84 throw new InvalidPathException(ypath);
89 public void setErrorsLineNumber(List errors) throws InvalidPathException {
90 for (Iterator it = errors.iterator(); it.hasNext(); ) {
91 ValidationException ex = (ValidationException)it.next();
92 ex.setLineNumber(getPathLineNumber(ex.getPath()));
96 protected Map createMapping() {
97 Map map = super.createMapping();
98 linenumsTable.put(map, new HashMap());