Merge branch 'master' of ../controller
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / repo / YangErrorListener.java
1 /*
2  * Copyright (c) 2013 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.parser.rfc7950.repo;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import org.antlr.v4.runtime.BaseErrorListener;
15 import org.antlr.v4.runtime.RecognitionException;
16 import org.antlr.v4.runtime.Recognizer;
17 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
18 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 public final class YangErrorListener extends BaseErrorListener {
23     private static final Logger LOG = LoggerFactory.getLogger(YangErrorListener.class);
24
25     private final List<YangSyntaxErrorException> exceptions = new ArrayList<>();
26     private final SourceIdentifier source;
27
28     public YangErrorListener(final SourceIdentifier source) {
29         this.source = requireNonNull(source);
30     }
31
32     @Override
33     @SuppressWarnings("checkstyle:parameterName")
34     public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line,
35             final int charPositionInLine, final String msg, final RecognitionException e) {
36         LOG.debug("Syntax error in {} at {}:{}: {}", source, line, charPositionInLine, msg, e);
37         exceptions.add(new YangSyntaxErrorException(source, line, charPositionInLine, msg, e));
38     }
39
40     public void validate() throws YangSyntaxErrorException {
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         boolean first = true;
52         for (YangSyntaxErrorException e : exceptions) {
53             if (first) {
54                 first = false;
55             } else {
56                 sb.append('\n');
57             }
58
59             sb.append(e.getFormattedMessage());
60         }
61
62         throw new YangSyntaxErrorException(source, 0, 0, sb.toString());
63     }
64 }