Bug 2363, Bug 2205. Beta version of LeafRefContext tree computation
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / leafref / LeafRefPathErrorListener.java
1 /**
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl.leafref;
9
10 import java.util.ArrayList;
11 import java.util.List;
12 import org.antlr.v4.runtime.BaseErrorListener;
13 import org.antlr.v4.runtime.RecognitionException;
14 import org.antlr.v4.runtime.Recognizer;
15 import org.opendaylight.yangtools.yang.model.api.Module;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 class LeafRefPathErrorListener extends BaseErrorListener {
20     private static final Logger LOG = LoggerFactory
21             .getLogger(LeafRefPathErrorListener.class);
22     private final List<LeafRefPathSyntaxErrorException> exceptions = new ArrayList<>();
23     private final Module module;
24
25     public LeafRefPathErrorListener(final Module module) {
26         this.module = module;
27     }
28
29     @Override
30     public void syntaxError(final Recognizer<?, ?> recognizer,
31             final Object offendingSymbol, final int line,
32             final int charPositionInLine, final String msg,
33             final RecognitionException e) {
34         LOG.debug("Syntax error in module {} at {}:{}: {}", module.getName(), line, charPositionInLine, msg, e);
35
36         exceptions.add(new LeafRefPathSyntaxErrorException(module.getName(), line,
37                 charPositionInLine, msg, e));
38     }
39
40     public void validate() throws LeafRefPathSyntaxErrorException {
41         if (exceptions.isEmpty()) {
42             return;
43         }
44
45         // Single exception: just throw it
46         if (exceptions.size() == 1) {
47             throw exceptions.get(0);
48         }
49
50         final StringBuilder sb = new StringBuilder();
51         String module = null;
52         boolean first = true;
53         for (final LeafRefPathSyntaxErrorException e : exceptions) {
54             if (module == null) {
55                 module = e.getModule();
56             }
57             if (first) {
58                 first = false;
59             } else {
60                 sb.append('\n');
61             }
62
63             sb.append(e.getFormattedMessage());
64         }
65
66         throw new LeafRefPathSyntaxErrorException(module, 0, 0, sb.toString());
67     }
68
69 }