[ONOS-4350] Inter Jar dependency implementation and code restructuring.
Change-Id: Iacac75e4187aed93ce1754c170a9c19707e5b8c3
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/YangLinker.java b/plugin/src/main/java/org/onosproject/yangutils/linker/YangLinker.java
new file mode 100644
index 0000000..bbb673a
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/YangLinker.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.onosproject.yangutils.linker;
+
+import java.util.Set;
+import org.onosproject.yangutils.plugin.manager.YangFileInfo;
+
+/**
+ * Abstraction of entity which provides linking service of YANG files.
+ */
+public interface YangLinker {
+
+ /**
+ * Resolve the import and include dependencies for a given resolution
+ * information.
+ *
+ * @param yangFileInfoSet set of all dependent YANG files
+ */
+ void resolveDependencies(Set<YangFileInfo> yangFileInfoSet);
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/YangLinkingPhase.java b/plugin/src/main/java/org/onosproject/yangutils/linker/YangLinkingPhase.java
new file mode 100644
index 0000000..23020df
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/YangLinkingPhase.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.linker;
+
+/**
+ * Represents the phase of YANG file reference linking.
+ */
+public enum YangLinkingPhase {
+
+ /**
+ * Linking the reference within the files.
+ */
+ INTRA_FILE,
+
+ /**
+ * Linking the reference across the files.
+ */
+ INTER_FILE
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/exceptions/LinkerException.java b/plugin/src/main/java/org/onosproject/yangutils/linker/exceptions/LinkerException.java
new file mode 100644
index 0000000..755b5b4
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/exceptions/LinkerException.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.linker.exceptions;
+
+/**
+ * Represents base class for exceptions in linker operations.
+ */
+public class LinkerException extends RuntimeException {
+
+ private static final long serialVersionUID = 20160211L;
+ private int lineNumber;
+ private int charPositionInLine;
+ private String fileName;
+
+ /**
+ * Creates a new linker exception.
+ */
+ public LinkerException() {
+ super();
+ }
+
+ /**
+ * Creates a new linker exception with given message.
+ *
+ * @param message the detail of exception in string
+ */
+ public LinkerException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new linker exception from given message and cause.
+ *
+ * @param message the detail of exception in string
+ * @param cause underlying cause of the error
+ */
+ public LinkerException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new linker exception from cause.
+ *
+ * @param cause underlying cause of the error
+ */
+ public LinkerException(final Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Returns line number of the exception.
+ *
+ * @return line number of the exception
+ */
+ public int getLineNumber() {
+ return this.lineNumber;
+ }
+
+ /**
+ * Returns YANG file name of the exception.
+ *
+ * @return YANG file name of the exception
+ */
+ public String getFileName() {
+ return this.fileName;
+ }
+
+ /**
+ * Returns position of the exception.
+ *
+ * @return position of the exception
+ */
+ public int getCharPositionInLine() {
+ return this.charPositionInLine;
+ }
+
+ /**
+ * Sets line number of YANG file.
+ *
+ * @param line line number of YANG file
+ */
+ public void setLine(int line) {
+ this.lineNumber = line;
+ }
+
+ /**
+ * Sets position of exception.
+ *
+ * @param charPosition position of exception
+ */
+ public void setCharPosition(int charPosition) {
+ this.charPositionInLine = charPosition;
+ }
+
+ /**
+ * Sets file name in parser exception.
+ *
+ * @param fileName YANG file name
+ */
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/exceptions/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/linker/exceptions/package-info.java
new file mode 100644
index 0000000..42cf3a2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/exceptions/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+/**
+ * Custom linker exceptions.
+ */
+package org.onosproject.yangutils.linker.exceptions;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangEntityToResolveInfoImpl.java b/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangEntityToResolveInfoImpl.java
new file mode 100644
index 0000000..6b6be58
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangEntityToResolveInfoImpl.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.linker.impl;
+
+import java.io.Serializable;
+
+import org.onosproject.yangutils.datamodel.YangEntityToResolveInfo;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangUses;
+import org.onosproject.yangutils.linker.exceptions.LinkerException;
+
+/**
+ * Represents implementation of information about entity being resolved.
+ *
+ * @param <T> type of entity being resolved, uses / grouping
+ */
+public class YangEntityToResolveInfoImpl<T> implements YangEntityToResolveInfo<T>, Serializable {
+
+ private static final long serialVersionUID = 806201659L;
+
+ // Parsable node for which resolution is to be performed.
+ private T entityToResolve;
+
+ // Holder of the YANG construct for which resolution has to be carried out.
+ private YangNode holderOfEntityToResolve;
+
+ @Override
+ public T getEntityToResolve() {
+ return entityToResolve;
+ }
+
+ @Override
+ public void setEntityToResolve(T entityToResolve) {
+ this.entityToResolve = entityToResolve;
+ }
+
+ @Override
+ public YangNode getHolderOfEntityToResolve() {
+ return holderOfEntityToResolve;
+ }
+
+ @Override
+ public void setHolderOfEntityToResolve(YangNode holderOfEntityToResolve) {
+ this.holderOfEntityToResolve = holderOfEntityToResolve;
+ }
+
+ /**
+ * Retrieves the prefix of the entity.
+ *
+ * @return entities prefix
+ * @throws LinkerException linker error
+ */
+ public String getEntityPrefix()
+ throws LinkerException {
+ if (getEntityToResolve() == null) {
+ return null;
+ }
+
+ String prefix;
+ T entityToBeResolved = getEntityToResolve();
+ if (entityToBeResolved instanceof YangType) {
+ prefix = ((YangType<?>) entityToBeResolved).getPrefix();
+ } else if (entityToBeResolved instanceof YangUses) {
+ prefix = ((YangUses) entityToBeResolved).getPrefix();
+ } else {
+ throw new LinkerException("Linker Exception: Entity to resolved is other than type/uses");
+ }
+ return prefix;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangLinkerManager.java b/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangLinkerManager.java
new file mode 100644
index 0000000..4e8a60a
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangLinkerManager.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.onosproject.yangutils.linker.impl;
+
+import java.util.HashSet;
+import java.util.Set;
+import org.onosproject.yangutils.datamodel.ResolvableType;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangReferenceResolver;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.linker.YangLinker;
+import org.onosproject.yangutils.linker.exceptions.LinkerException;
+import org.onosproject.yangutils.plugin.manager.YangFileInfo;
+
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+
+/**
+ * Representation of entity which provides linking service of YANG files.
+ */
+public class YangLinkerManager
+ implements YangLinker {
+
+ /*
+ * Set of all the YANG nodes, corresponding to the YANG files parsed by
+ * parser.
+ */
+ Set<YangNode> yangNodeSet = new HashSet<>();
+
+ /**
+ * Returns set of YANG node.
+ *
+ * @return set of YANG node
+ */
+ public Set<YangNode> getYangNodeSet() {
+ return yangNodeSet;
+ }
+
+ /**
+ * Creates YANG nodes set.
+ *
+ * @param yangFileInfoSet YANG file information set
+ */
+ public void createYangNodeSet(Set<YangFileInfo> yangFileInfoSet) {
+ for (YangFileInfo yangFileInfo : yangFileInfoSet) {
+ getYangNodeSet().add(yangFileInfo.getRootNode());
+ }
+ }
+
+ @Override
+ public void resolveDependencies(Set<YangFileInfo> yangFileInfoSet) {
+
+ // Create YANG node set.
+ createYangNodeSet(yangFileInfoSet);
+
+ // Carry out linking of sub module with module.
+ linkSubModulesToParentModule(yangFileInfoSet);
+
+ // Add references to import list.
+ addRefToYangFilesImportList(yangFileInfoSet);
+
+ // Add reference to include list.
+ addRefToYangFilesIncludeList(yangFileInfoSet);
+
+ // TODO check for circular import/include.
+
+ // Carry out inter-file linking.
+ processInterFileLinking(yangFileInfoSet);
+ }
+
+ /**
+ * Resolves sub-module linking by linking sub module with parent module.
+ *
+ * @param yangFileInfoSet set of YANG files info
+ * @throws LinkerException fails to link sub-module to parent module
+ */
+ public void linkSubModulesToParentModule(Set<YangFileInfo> yangFileInfoSet)
+ throws LinkerException {
+ for (YangFileInfo yangFileInfo : yangFileInfoSet) {
+ YangNode yangNode = yangFileInfo.getRootNode();
+ if (yangNode instanceof YangSubModule) {
+ try {
+ ((YangSubModule) yangNode).linkWithModule(getYangNodeSet());
+ } catch (DataModelException e) {
+ String errorInfo = "YANG file error: " + yangFileInfo.getYangFileName() + " at line: "
+ + e.getLineNumber() + " at position: " + e.getCharPositionInLine() + NEW_LINE
+ + e.getMessage();
+ throw new LinkerException(errorInfo);
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds imported node information to the import list.
+ *
+ * @param yangFileInfoSet set of YANG files info
+ * @throws LinkerException fails to find imported module
+ */
+ public void addRefToYangFilesImportList(Set<YangFileInfo> yangFileInfoSet) throws LinkerException {
+ for (YangFileInfo yangFileInfo : yangFileInfoSet) {
+ YangNode yangNode = yangFileInfo.getRootNode();
+ if (yangNode instanceof YangReferenceResolver) {
+ try {
+ ((YangReferenceResolver) yangNode).addReferencesToImportList(getYangNodeSet());
+ } catch (DataModelException e) {
+ String errorInfo = "Error in file: " + yangFileInfo.getYangFileName() + " at line: "
+ + e.getLineNumber() + " at position: " + e.getCharPositionInLine() + NEW_LINE
+ + e.getMessage();
+ throw new LinkerException(errorInfo);
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds included node information to the include list.
+ *
+ * @param yangFileInfoSet set of YANG files info
+ * @throws LinkerException fails to find included sub-module
+ */
+ public void addRefToYangFilesIncludeList(Set<YangFileInfo> yangFileInfoSet) throws LinkerException {
+ for (YangFileInfo yangFileInfo : yangFileInfoSet) {
+ YangNode yangNode = yangFileInfo.getRootNode();
+ if (yangNode instanceof YangReferenceResolver) {
+ try {
+ ((YangReferenceResolver) yangNode).addReferencesToIncludeList(getYangNodeSet());
+ } catch (DataModelException e) {
+ String errorInfo = "Error in file: " + yangFileInfo.getYangFileName() + " at line: "
+ + e.getLineNumber() + " at position: " + e.getCharPositionInLine() + NEW_LINE
+ + e.getMessage();
+ throw new LinkerException(errorInfo);
+ }
+ }
+ }
+ }
+
+ /**
+ * Processes inter file linking for type and uses.
+ *
+ * @param yangFileInfoSet set of YANG files info
+ * @throws LinkerException a violation in linker execution
+ */
+ public void processInterFileLinking(Set<YangFileInfo> yangFileInfoSet)
+ throws LinkerException {
+ for (YangFileInfo yangFileInfo : yangFileInfoSet) {
+ try {
+ ((YangReferenceResolver) yangFileInfo.getRootNode()).resolveInterFileLinking(ResolvableType.YANG_USES);
+ ((YangReferenceResolver) yangFileInfo.getRootNode())
+ .resolveInterFileLinking(ResolvableType.YANG_DERIVED_DATA_TYPE);
+ } catch (DataModelException e) {
+ String errorInfo = "Error in file: " + yangFileInfo.getYangFileName() + " at line: "
+ + e.getLineNumber() + " at position: " + e.getCharPositionInLine() + NEW_LINE + e.getMessage();
+ throw new LinkerException(errorInfo);
+ }
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangResolutionInfoImpl.java b/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangResolutionInfoImpl.java
new file mode 100644
index 0000000..2a710dc
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/impl/YangResolutionInfoImpl.java
@@ -0,0 +1,863 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.linker.impl;
+
+import java.io.Serializable;
+import java.util.Stack;
+
+import org.onosproject.yangutils.datamodel.Resolvable;
+import org.onosproject.yangutils.datamodel.YangDataTypes;
+import org.onosproject.yangutils.datamodel.YangDerivedInfo;
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangImport;
+import org.onosproject.yangutils.datamodel.YangInclude;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangReferenceResolver;
+import org.onosproject.yangutils.datamodel.YangResolutionInfo;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.YangUses;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.ResolvableStatus;
+import org.onosproject.yangutils.linker.YangLinkingPhase;
+
+import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.INTER_FILE_LINKED;
+import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.INTRA_FILE_RESOLVED;
+import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.LINKED;
+import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.RESOLVED;
+import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.UNRESOLVED;
+import static org.onosproject.yangutils.linker.YangLinkingPhase.INTER_FILE;
+import static org.onosproject.yangutils.linker.YangLinkingPhase.INTRA_FILE;
+import static org.onosproject.yangutils.utils.UtilConstants.GROUPING_LINKER_ERROR;
+import static org.onosproject.yangutils.utils.UtilConstants.TYPEDEF_LINKER_ERROR;
+
+/**
+ * Represents implementation of resolution object which will be resolved by
+ * linker.
+ *
+ * @param <T> type of resolution entity uses / type
+ */
+public class YangResolutionInfoImpl<T>
+ implements YangResolutionInfo<T>, Serializable {
+
+ private static final long serialVersionUID = 806201658L;
+
+ /**
+ * Information about the entity that needs to be resolved.
+ */
+ private YangEntityToResolveInfoImpl<T> entityToResolveInfo;
+
+ /**
+ * Error line number.
+ */
+ private transient int lineNumber;
+
+ /**
+ * Error character position in number.
+ */
+ private transient int charPosition;
+
+ /**
+ * Current module/sub-module reference, will be used in inter-file/
+ * inter-jar scenario to get the import/include list.
+ */
+ private transient YangReferenceResolver curReferenceResolver;
+
+ /**
+ * Stack for type/uses is maintained for hierarchical references, this is
+ * used during resolution.
+ */
+ private Stack<YangEntityToResolveInfoImpl<T>> partialResolvedStack;
+
+ /**
+ * It is private to ensure the overloaded method be invoked to create an
+ * object.
+ */
+ @SuppressWarnings("unused")
+ private YangResolutionInfoImpl() {
+
+ }
+
+ /**
+ * Creates a resolution information object with all the inputs.
+ *
+ * @param dataNode current parsable data node
+ * @param holderNode parent YANG node
+ * @param lineNumber error line number
+ * @param charPositionInLine error character position in line
+ */
+ public YangResolutionInfoImpl(T dataNode, YangNode holderNode, int lineNumber, int charPositionInLine) {
+ setEntityToResolveInfo(new YangEntityToResolveInfoImpl<>());
+ getEntityToResolveInfo().setEntityToResolve(dataNode);
+ getEntityToResolveInfo().setHolderOfEntityToResolve(holderNode);
+ this.setLineNumber(lineNumber);
+ this.setCharPosition(charPositionInLine);
+ setPartialResolvedStack(new Stack<>());
+ }
+
+ @Override
+ public void resolveLinkingForResolutionInfo(YangReferenceResolver dataModelRootNode)
+ throws DataModelException {
+
+ setCurReferenceResolver(dataModelRootNode);
+
+ // Current node to resolve, it can be a YANG type or YANG uses.
+ T entityToResolve = getEntityToResolveInfo().getEntityToResolve();
+
+ // Check if linking is already done
+ if (entityToResolve instanceof Resolvable) {
+ Resolvable resolvable = (Resolvable) entityToResolve;
+ if (resolvable.getResolvableStatus() == RESOLVED) {
+ /**
+ * entity is already resolved, so nothing to do
+ */
+ return;
+ }
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+
+ // Push the initial entity to resolve in stack.
+ addInPartialResolvedStack(getEntityToResolveInfo());
+
+ linkAndResolvePartialResolvedStack();
+ }
+
+ /**
+ * Resolves linking with ancestors.
+ *
+ * @throws DataModelException a violation of data model rules
+ */
+ private void linkAndResolvePartialResolvedStack()
+ throws DataModelException {
+
+ while (getPartialResolvedStack().size() != 0) {
+
+ // Current node to resolve, it can be a YANG type or YANG uses.
+ T entityToResolve = getCurrentEntityToResolveFromStack();
+ // Check if linking is already done
+ if (entityToResolve instanceof Resolvable) {
+
+ Resolvable resolvable = (Resolvable) entityToResolve;
+ switch (resolvable.getResolvableStatus()) {
+ case RESOLVED: {
+ /*
+ * If the entity is already resolved in the stack, then pop
+ * it and continue with the remaining stack elements to
+ * resolve
+ */
+ getPartialResolvedStack().pop();
+ break;
+ }
+
+ case LINKED: {
+ /*
+ * If the top of the stack is already linked then resolve
+ * the references and pop the entity and continue with
+ * remaining stack elements to resolve.
+ */
+ resolveTopOfStack(INTRA_FILE);
+ getPartialResolvedStack().pop();
+ break;
+ }
+
+ case INTRA_FILE_RESOLVED: {
+ /*
+ * Pop the top of the stack.
+ */
+ getPartialResolvedStack().pop();
+ break;
+ }
+
+ case UNRESOLVED: {
+ linkTopOfStackReferenceUpdateStack();
+
+ if (resolvable.getResolvableStatus() == UNRESOLVED) {
+ // If current entity is still not resolved, then
+ // linking/resolution has failed.
+ String errorInfo;
+ if (resolvable instanceof YangType) {
+ errorInfo = TYPEDEF_LINKER_ERROR;
+ } else {
+ errorInfo = GROUPING_LINKER_ERROR;
+ }
+ DataModelException dataModelException = new DataModelException(errorInfo);
+ dataModelException.setLine(getLineNumber());
+ dataModelException.setCharPosition(getCharPosition());
+ throw dataModelException;
+ }
+ break;
+ }
+ default: {
+ throw new DataModelException("Data Model Exception: Unsupported, linker state");
+ }
+
+ }
+
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+
+ }
+
+ }
+
+ /**
+ * Resolves the current entity in the stack.
+ */
+ private void resolveTopOfStack(YangLinkingPhase linkingPhase)
+ throws DataModelException {
+ ((Resolvable) getCurrentEntityToResolveFromStack()).resolve();
+ if (((Resolvable) getCurrentEntityToResolveFromStack()).getResolvableStatus() != INTRA_FILE_RESOLVED) {
+ // Sets the resolution status in inside the type/uses.
+ ((Resolvable) getCurrentEntityToResolveFromStack()).setResolvableStatus(RESOLVED);
+ }
+ }
+
+ /**
+ * Resolves linking for a node child and siblings.
+ *
+ * @throws DataModelException data model error
+ */
+ private void linkTopOfStackReferenceUpdateStack()
+ throws DataModelException {
+
+ /*
+ * Check if self file reference is there, this will not check for the
+ * scenario when prefix is not present and type/uses is present in
+ * sub-module from include list.
+ */
+ if (!isCandidateForSelfFileReference()) {
+ ((Resolvable) getCurrentEntityToResolveFromStack()).setResolvableStatus(INTRA_FILE_RESOLVED);
+ return;
+ }
+
+ /**
+ * Try to resolve the top of the stack and update partial resolved stack
+ * if there is recursive references
+ */
+ YangNode potentialAncestorWithReferredNode = getPartialResolvedStack().peek()
+ .getHolderOfEntityToResolve();
+
+ /**
+ * Traverse up in the ancestor tree to check if the referred node is
+ * defined
+ */
+ while (potentialAncestorWithReferredNode != null) {
+
+ /**
+ * Check for the referred node defined in a ancestor scope
+ */
+ YangNode potentialReferredNode = potentialAncestorWithReferredNode.getChild();
+ if (isReferredNodeInSiblingListProcessed(potentialReferredNode)) {
+ return;
+ }
+
+ potentialAncestorWithReferredNode = potentialAncestorWithReferredNode.getParent();
+ }
+
+ /*
+ * In case prefix is not present it's a candidate for inter-file
+ * resolution via include list.
+ */
+ if (getRefPrefix() == null) {
+ ((Resolvable) getCurrentEntityToResolveFromStack()).setResolvableStatus(INTRA_FILE_RESOLVED);
+ }
+ }
+
+ /**
+ * Checks if the reference in self file or in external file.
+ *
+ * @return true if self file reference, false otherwise
+ * @throws DataModelException a violation of data model rules
+ */
+ private boolean isCandidateForSelfFileReference()
+ throws DataModelException {
+ String prefix = getRefPrefix();
+ return prefix == null || prefix.contentEquals(getCurReferenceResolver().getPrefix());
+ }
+
+ /**
+ * Checks for the referred node defined in a ancestor scope.
+ *
+ * @param potentialReferredNode potential referred node
+ * @return status of resolution and updating the partial resolved stack with
+ * the any recursive references
+ * @throws DataModelException data model errors
+ */
+ private boolean isReferredNodeInSiblingListProcessed(YangNode potentialReferredNode)
+ throws DataModelException {
+ while (potentialReferredNode != null) {
+
+ // Check if the potential referred node is the actual referred node
+ if (isReferredNode(potentialReferredNode)) {
+
+ // Adds reference link of entity to the node under resolution.
+ addReferredEntityLink(potentialReferredNode, LINKED);
+
+ /**
+ * resolve the reference and update the partial resolution stack
+ * with any further recursive references
+ */
+ addUnresolvedRecursiveReferenceToStack(potentialReferredNode);
+
+ /*
+ * return true, since the reference is linked and any recursive
+ * unresolved references is added to the stack
+ */
+ return true;
+ }
+
+ potentialReferredNode = potentialReferredNode.getNextSibling();
+ }
+ return false;
+ }
+
+ /**
+ * Checks if the potential referred node is the actual referred node.
+ *
+ * @param potentialReferredNode typedef/grouping node
+ * @return true if node is of resolve type otherwise false
+ * @throws DataModelException a violation of data model rules
+ */
+ private boolean isReferredNode(YangNode potentialReferredNode)
+ throws DataModelException {
+ if (getCurrentEntityToResolveFromStack() instanceof YangType) {
+ if (potentialReferredNode instanceof YangTypeDef) {
+ /*
+ * Check if name of node name matches with the entity being
+ * resolved
+ */
+ return isNodeNameSameAsResolutionInfoName(potentialReferredNode);
+ }
+ } else if (getCurrentEntityToResolveFromStack() instanceof YangUses) {
+ if (potentialReferredNode instanceof YangGrouping) {
+ /*
+ * Check if name of node name matches with the entity being
+ * resolved
+ */
+ return isNodeNameSameAsResolutionInfoName(potentialReferredNode);
+ }
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+ return false;
+ }
+
+ /**
+ * Checks if node name is same as name in resolution info, i.e. name of
+ * typedef/grouping is same as name of type/uses.
+ *
+ * @param node typedef/grouping node
+ * @return true if node name is same as name in resolution info, otherwise
+ * false
+ * @throws DataModelException a violation of data model rules
+ */
+
+ private boolean isNodeNameSameAsResolutionInfoName(YangNode node)
+ throws DataModelException {
+ if (getCurrentEntityToResolveFromStack() instanceof YangType) {
+ if (node.getName().contentEquals(
+ ((YangType<?>) getCurrentEntityToResolveFromStack())
+ .getDataTypeName())) {
+ return true;
+ }
+ } else if (getCurrentEntityToResolveFromStack() instanceof YangUses) {
+ if (node.getName().contentEquals(
+ ((YangUses) getCurrentEntityToResolveFromStack()).getName())) {
+ return true;
+ }
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+ return false;
+ }
+
+ /**
+ * Adds reference of grouping/typedef in uses/type.
+ *
+ * @param referredNode grouping/typedef node being referred
+ * @param linkedStatus linked status if success.
+ * @throws DataModelException a violation of data model rules
+ */
+ private void addReferredEntityLink(YangNode referredNode, ResolvableStatus linkedStatus)
+ throws DataModelException {
+ if (getCurrentEntityToResolveFromStack() instanceof YangType) {
+ YangDerivedInfo<?> derivedInfo = (YangDerivedInfo<?>) ((YangType<?>) getCurrentEntityToResolveFromStack())
+ .getDataTypeExtendedInfo();
+ derivedInfo.setReferredTypeDef((YangTypeDef) referredNode);
+ } else if (getCurrentEntityToResolveFromStack() instanceof YangUses) {
+ ((YangUses) getCurrentEntityToResolveFromStack())
+ .setRefGroup((YangGrouping) referredNode);
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+
+ // Sets the resolution status in inside the type/uses.
+ ((Resolvable) getCurrentEntityToResolveFromStack()).setResolvableStatus(linkedStatus);
+ }
+
+ /**
+ * Checks if type/grouping has further reference to typedef/ unresolved
+ * uses. Add it to the partial resolve stack and return the status of
+ * addition to stack.
+ *
+ * @param referredNode grouping/typedef node
+ * @throws DataModelException a violation of data model rules
+ */
+ private void addUnresolvedRecursiveReferenceToStack(YangNode referredNode)
+ throws DataModelException {
+ if (getCurrentEntityToResolveFromStack() instanceof YangType) {
+ /*
+ * Checks if typedef type is derived
+ */
+ if (((YangTypeDef) referredNode).getTypeDefBaseType().getDataType() == YangDataTypes.DERIVED) {
+
+ YangEntityToResolveInfoImpl<YangType<?>> unResolvedEntityInfo = new YangEntityToResolveInfoImpl<>();
+ unResolvedEntityInfo.setEntityToResolve(((YangTypeDef) referredNode)
+ .getTypeDefBaseType());
+ unResolvedEntityInfo.setHolderOfEntityToResolve(referredNode);
+ addInPartialResolvedStack((YangEntityToResolveInfoImpl<T>) unResolvedEntityInfo);
+ }
+
+ } else if (getCurrentEntityToResolveFromStack() instanceof YangUses) {
+ /*
+ * Search if the grouping has any un resolved uses child, if so
+ * return true, else return false.
+ */
+ addUnResolvedUsesToStack(referredNode);
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+ }
+
+ /**
+ * Returns if there is any unresolved uses in grouping.
+ *
+ * @param node grouping/typedef node
+ */
+ private void addUnResolvedUsesToStack(YangNode node) {
+
+ /**
+ * Search the grouping node's children for presence of uses node.
+ */
+ YangNode curNode = node.getChild();
+ while (curNode != null) {
+ if (curNode instanceof YangUses) {
+ YangEntityToResolveInfoImpl<YangUses> unResolvedEntityInfo = new YangEntityToResolveInfoImpl<>();
+ unResolvedEntityInfo.setEntityToResolve((YangUses) curNode);
+ unResolvedEntityInfo.setHolderOfEntityToResolve(node);
+ addInPartialResolvedStack((YangEntityToResolveInfoImpl<T>) unResolvedEntityInfo);
+
+ }
+ curNode = curNode.getNextSibling();
+ }
+ }
+
+ /**
+ * Returns stack of YANG type with partially resolved YANG construct
+ * hierarchy.
+ *
+ * @return partial resolved YANG construct stack
+ */
+ private Stack<YangEntityToResolveInfoImpl<T>> getPartialResolvedStack() {
+ return partialResolvedStack;
+ }
+
+ /**
+ * Sets stack of YANG type with partially resolved YANG construct hierarchy.
+ *
+ * @param partialResolvedStack partial resolved YANG construct stack
+ */
+ private void setPartialResolvedStack(Stack<YangEntityToResolveInfoImpl<T>> partialResolvedStack) {
+ this.partialResolvedStack = partialResolvedStack;
+ }
+
+ /**
+ * Sets stack of YANG type with partially resolved YANG construct hierarchy.
+ *
+ * @param partialResolvedInfo partial resolved YANG construct stack
+ */
+ private void addInPartialResolvedStack(YangEntityToResolveInfoImpl<T> partialResolvedInfo) {
+ getPartialResolvedStack().push(partialResolvedInfo);
+ }
+
+ /**
+ * Retrieves the next entity in the stack that needs to be resolved. It is
+ * assumed that the caller ensures that the stack is not empty.
+ *
+ * @return next entity in the stack that needs to be resolved
+ */
+ private T getCurrentEntityToResolveFromStack() {
+ return getPartialResolvedStack().peek().getEntityToResolve();
+ }
+
+ @Override
+ public YangEntityToResolveInfoImpl<T> getEntityToResolveInfo() {
+ return entityToResolveInfo;
+ }
+
+ /**
+ * Sets information about the entity that needs to be resolved.
+ *
+ * @param entityToResolveInfo information about the entity that needs to be
+ * resolved
+ */
+ private void setEntityToResolveInfo(YangEntityToResolveInfoImpl<T> entityToResolveInfo) {
+ this.entityToResolveInfo = entityToResolveInfo;
+ }
+
+ @Override
+ public int getLineNumber() {
+ return lineNumber;
+ }
+
+ @Override
+ public int getCharPosition() {
+ return charPosition;
+ }
+
+ @Override
+ public void setLineNumber(int lineNumber) {
+ this.lineNumber = lineNumber;
+ }
+
+ @Override
+ public void setCharPosition(int charPositionInLine) {
+ this.charPosition = charPositionInLine;
+ }
+
+ /**
+ * Returns current module/sub-module reference, will be used in inter-file/
+ * inter-jar scenario to get the import/include list.
+ *
+ * @return current module/sub-module reference
+ */
+ private YangReferenceResolver getCurReferenceResolver() {
+ return curReferenceResolver;
+ }
+
+ /**
+ * Sets current module/sub-module reference, will be used in inter-file/
+ * inter-jar scenario to get the import/include list.
+ *
+ * @param curReferenceResolver current module/sub-module reference
+ */
+ private void setCurReferenceResolver(YangReferenceResolver curReferenceResolver) {
+ this.curReferenceResolver = curReferenceResolver;
+ }
+
+ @Override
+ public void linkInterFile(YangReferenceResolver dataModelRootNode)
+ throws DataModelException {
+
+ setCurReferenceResolver(dataModelRootNode);
+
+ // Current node to resolve, it can be a YANG type or YANG uses.
+ T entityToResolve = getEntityToResolveInfo().getEntityToResolve();
+
+ // Check if linking is already done
+ if (entityToResolve instanceof Resolvable) {
+ Resolvable resolvable = (Resolvable) entityToResolve;
+ if (resolvable.getResolvableStatus() == RESOLVED) {
+ return;
+ }
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is not Resolvable");
+ }
+
+ // Push the initial entity to resolve in stack.
+ addInPartialResolvedStack(getEntityToResolveInfo());
+
+ // Inter file linking and resolution.
+ linkInterFileAndResolve();
+ }
+
+ /**
+ * Returns the referenced prefix of entity under resolution.
+ *
+ * @return referenced prefix of entity under resolution
+ * @throws DataModelException a violation in data model rule
+ */
+ private String getRefPrefix()
+ throws DataModelException {
+ String refPrefix;
+ if (getCurrentEntityToResolveFromStack() instanceof YangType) {
+ refPrefix = ((YangType<?>) getCurrentEntityToResolveFromStack()).getPrefix();
+ } else if (getCurrentEntityToResolveFromStack() instanceof YangUses) {
+ refPrefix = ((YangUses) getCurrentEntityToResolveFromStack()).getPrefix();
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+ return refPrefix;
+ }
+
+ /**
+ * Performs inter file linking and resolution.
+ *
+ * @throws DataModelException a violation in data model rule
+ */
+ private void linkInterFileAndResolve()
+ throws DataModelException {
+
+ while (getPartialResolvedStack().size() != 0) {
+
+ // Current node to resolve, it can be a YANG type or YANG uses.
+ T entityToResolve = getCurrentEntityToResolveFromStack();
+ // Check if linking is already done
+ if (entityToResolve instanceof Resolvable) {
+
+ Resolvable resolvable = (Resolvable) entityToResolve;
+ switch (resolvable.getResolvableStatus()) {
+ case RESOLVED: {
+ /*
+ * If the entity is already resolved in the stack, then pop
+ * it and continue with the remaining stack elements to
+ * resolve
+ */
+ getPartialResolvedStack().pop();
+ break;
+ }
+
+ case INTER_FILE_LINKED: {
+ /*
+ * If the top of the stack is already linked then resolve
+ * the references and pop the entity and continue with
+ * remaining stack elements to resolve
+ */
+ resolveTopOfStack(INTER_FILE);
+ getPartialResolvedStack().pop();
+ break;
+ }
+
+ case INTRA_FILE_RESOLVED: {
+ /*
+ * If the top of the stack is intra file resolved then check
+ * if top of stack is linked, if not link it using
+ * import/include list and push the linked referred entity
+ * to the stack, otherwise only push it to the stack.
+ */
+ linkInterFileTopOfStackRefUpdateStack();
+ break;
+ }
+
+ default: {
+ throw new DataModelException("Data Model Exception: Unsupported, linker state");
+ }
+
+ }
+
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+
+ }
+
+ }
+
+ /**
+ * Links the top of the stack if it's inter-file and update stack.
+ *
+ * @throws DataModelException data model error
+ */
+ private void linkInterFileTopOfStackRefUpdateStack()
+ throws DataModelException {
+
+ /*
+ * Obtain the referred node of top of stack entity under resolution
+ */
+ T referredNode = getRefNode();
+
+ /*
+ * Check for null for scenario when it's not linked and inter-file
+ * linking is required.
+ */
+ if (referredNode == null) {
+
+ /*
+ * Check if prefix is null or not, to identify whether to search in
+ * import list or include list.
+ */
+ if (getRefPrefix() != null && !getRefPrefix().contentEquals(getCurReferenceResolver().getPrefix())) {
+ if (resolveWithImport()) {
+ return;
+ }
+ } else {
+ if (resolveWithInclude()) {
+ return;
+ }
+ }
+ // Exception when referred typedef/grouping is not found.
+ DataModelException dataModelException = new DataModelException("YANG file error: Referred " +
+ "typedef/grouping for a given type/uses can't be found.");
+ dataModelException.setLine(getLineNumber());
+ dataModelException.setCharPosition(getCharPosition());
+ throw dataModelException;
+ } else {
+ /*
+ * If referred node is already linked, then just change the status
+ * and push to the stack.
+ */
+ ((Resolvable) getCurrentEntityToResolveFromStack()).setResolvableStatus(INTER_FILE_LINKED);
+ addUnresolvedRecursiveReferenceToStack((YangNode) referredNode);
+ }
+ }
+
+ /**
+ * Finds and resolves with include list.
+ *
+ * @return true if resolved, false otherwise
+ * @throws DataModelException a violation in data model rule
+ */
+ private boolean resolveWithInclude()
+ throws DataModelException {
+ /*
+ * Run through all the nodes in include list and search for referred
+ * typedef/grouping at the root level.
+ */
+ for (YangInclude yangInclude : getCurReferenceResolver().getIncludeList()) {
+ YangNode linkedNode = null;
+ if (getCurrentEntityToResolveFromStack() instanceof YangType) {
+ linkedNode = findRefTypedef(yangInclude.getIncludedNode());
+ } else if (getCurrentEntityToResolveFromStack() instanceof YangUses) {
+ linkedNode = findRefGrouping(yangInclude.getIncludedNode());
+ }
+ if (linkedNode != null) {
+ // Add the link to external entity.
+ addReferredEntityLink(linkedNode, INTER_FILE_LINKED);
+ /*
+ * Update the current reference resolver to external
+ * module/sub-module containing the referred typedef/grouping.
+ */
+ setCurReferenceResolver((YangReferenceResolver) yangInclude.getIncludedNode());
+ // Add the type/uses of referred typedef/grouping to the stack.
+ addUnresolvedRecursiveReferenceToStack(linkedNode);
+ return true;
+ }
+ }
+ // If referred node can't be found return false.
+ return false;
+ }
+
+ /**
+ * Finds and resolves with import list.
+ *
+ * @return true if resolved, false otherwise
+ * @throws DataModelException a violation in data model rule
+ */
+ private boolean resolveWithImport()
+ throws DataModelException {
+ /*
+ * Run through import list to find the referred typedef/grouping.
+ */
+ for (YangImport yangImport : getCurReferenceResolver().getImportList()) {
+ /*
+ * Match the prefix attached to entity under resolution with the
+ * imported/included module/sub-module's prefix. If found, search
+ * for the referred typedef/grouping at the root level.
+ */
+ if (yangImport.getPrefixId().contentEquals(getRefPrefix())) {
+ YangNode linkedNode = null;
+ if (getCurrentEntityToResolveFromStack() instanceof YangType) {
+ linkedNode = findRefTypedef(yangImport.getImportedNode());
+ } else if (getCurrentEntityToResolveFromStack() instanceof YangUses) {
+ linkedNode = findRefGrouping(yangImport.getImportedNode());
+ }
+ if (linkedNode != null) {
+ // Add the link to external entity.
+ addReferredEntityLink(linkedNode, INTER_FILE_LINKED);
+ /*
+ * Update the current reference resolver to external
+ * module/sub-module containing the referred
+ * typedef/grouping.
+ */
+ setCurReferenceResolver((YangReferenceResolver) yangImport.getImportedNode());
+ // Add the type/uses of referred typedef/grouping to the
+ // stack.
+ addUnresolvedRecursiveReferenceToStack(linkedNode);
+ return true;
+ }
+ /*
+ * If referred node can't be found at root level break for loop,
+ * and return false.
+ */
+ break;
+ }
+ }
+ // If referred node can't be found return false.
+ return false;
+ }
+
+ /**
+ * Returns referred typedef/grouping node.
+ *
+ * @return referred typedef/grouping node
+ * @throws DataModelException a violation in data model rule
+ */
+ private T getRefNode()
+ throws DataModelException {
+ if (getCurrentEntityToResolveFromStack() instanceof YangType) {
+ YangDerivedInfo<?> derivedInfo = (YangDerivedInfo<?>) ((YangType<?>) getCurrentEntityToResolveFromStack())
+ .getDataTypeExtendedInfo();
+ return (T) derivedInfo.getReferredTypeDef();
+ } else if (getCurrentEntityToResolveFromStack() instanceof YangUses) {
+ return (T) ((YangUses) getCurrentEntityToResolveFromStack()).getRefGroup();
+ } else {
+ throw new DataModelException("Data Model Exception: Entity to resolved is other than type/uses");
+ }
+ }
+
+ /**
+ * Finds the referred grouping node at the root level of imported/included node.
+ *
+ * @param refNode module/sub-module node
+ * @return referred grouping
+ */
+ private YangNode findRefGrouping(YangNode refNode) {
+ YangNode tmpNode = refNode.getChild();
+ while (tmpNode != null) {
+ if (tmpNode instanceof YangGrouping) {
+ if (tmpNode.getName()
+ .equals(((YangUses) getCurrentEntityToResolveFromStack()).getName())) {
+ return tmpNode;
+ }
+ }
+ tmpNode = tmpNode.getNextSibling();
+ }
+ return null;
+ }
+
+ /**
+ * Finds the referred typedef node at the root level of imported/included node.
+ *
+ * @param refNode module/sub-module node
+ * @return referred typedef
+ */
+ private YangNode findRefTypedef(YangNode refNode) {
+ YangNode tmpNode = refNode.getChild();
+ while (tmpNode != null) {
+ if (tmpNode instanceof YangTypeDef) {
+ if (tmpNode.getName()
+ .equals(((YangType) getCurrentEntityToResolveFromStack()).getDataTypeName())) {
+ return tmpNode;
+ }
+ }
+ tmpNode = tmpNode.getNextSibling();
+ }
+ return null;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/impl/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/linker/impl/package-info.java
new file mode 100644
index 0000000..1d38e5a
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Provide intra/inter file and inter jar linking implementation.
+ */
+package org.onosproject.yangutils.linker.impl;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/linker/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/linker/package-info.java
new file mode 100644
index 0000000..04ce9d6
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/linker/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Provide inter jar and inter file linking abstract interface.
+ */
+package org.onosproject.yangutils.linker;
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/YangUtilsParser.java b/plugin/src/main/java/org/onosproject/yangutils/parser/YangUtilsParser.java
new file mode 100644
index 0000000..ba119f6
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/YangUtilsParser.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+
+/**
+ * Abstraction of entity which provides parser service of YANG files for yangutils-maven-plugin.
+ */
+public interface YangUtilsParser {
+
+ /**
+ * Returns the data model node. It is an entry function to initiate the YANG file parsing.
+ *
+ * @param file input YANG file
+ * @return YangNode root node of the data model tree
+ * @throws ParserException when fails to get the data model
+ * @throws IOException when there is an exception in IO operation
+ */
+ YangNode getDataModel(String file) throws IOException, ParserException;
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/antlrgencode/GeneratedYangListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/antlrgencode/GeneratedYangListener.java
new file mode 100644
index 0000000..c4c52f0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/antlrgencode/GeneratedYangListener.java
@@ -0,0 +1,1968 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Generated from GeneratedYang.g4 by ANTLR 4.5
+
+
+package org.onosproject.yangutils.parser.antlrgencode;
+
+import org.antlr.v4.runtime.tree.ParseTreeListener;
+
+/**
+ * Represents ANTLR interfaces to be implemented by listener to traverse the parse tree.
+ */
+public interface GeneratedYangListener extends ParseTreeListener {
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * yangfile.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterYangfile(GeneratedYangParser.YangfileContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * yangfile.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitYangfile(GeneratedYangParser.YangfileContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * moduleStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterModuleStatement(GeneratedYangParser.ModuleStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * moduleStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitModuleStatement(GeneratedYangParser.ModuleStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * moduleBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterModuleBody(GeneratedYangParser.ModuleBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * moduleBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitModuleBody(GeneratedYangParser.ModuleBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * moduleHeaderStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterModuleHeaderStatement(GeneratedYangParser.ModuleHeaderStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * moduleHeaderStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitModuleHeaderStatement(GeneratedYangParser.ModuleHeaderStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * linkageStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterLinkageStatements(GeneratedYangParser.LinkageStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * linkageStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitLinkageStatements(GeneratedYangParser.LinkageStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * metaStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterMetaStatements(GeneratedYangParser.MetaStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * metaStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitMetaStatements(GeneratedYangParser.MetaStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * revisionStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRevisionStatements(GeneratedYangParser.RevisionStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * revisionStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRevisionStatements(GeneratedYangParser.RevisionStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * bodyStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterBodyStatements(GeneratedYangParser.BodyStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * bodyStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitBodyStatements(GeneratedYangParser.BodyStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * yangVersionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterYangVersionStatement(GeneratedYangParser.YangVersionStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * yangVersionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitYangVersionStatement(GeneratedYangParser.YangVersionStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * namespaceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterNamespaceStatement(GeneratedYangParser.NamespaceStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * namespaceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitNamespaceStatement(GeneratedYangParser.NamespaceStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * prefixStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterPrefixStatement(GeneratedYangParser.PrefixStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * prefixStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitPrefixStatement(GeneratedYangParser.PrefixStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * importStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterImportStatement(GeneratedYangParser.ImportStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * importStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitImportStatement(GeneratedYangParser.ImportStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * importStatementBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterImportStatementBody(GeneratedYangParser.ImportStatementBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * importStatementBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitImportStatementBody(GeneratedYangParser.ImportStatementBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * revisionDateStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRevisionDateStatement(GeneratedYangParser.RevisionDateStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * revisionDateStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRevisionDateStatement(GeneratedYangParser.RevisionDateStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * includeStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterIncludeStatement(GeneratedYangParser.IncludeStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * includeStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitIncludeStatement(GeneratedYangParser.IncludeStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * organizationStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterOrganizationStatement(GeneratedYangParser.OrganizationStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * organizationStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitOrganizationStatement(GeneratedYangParser.OrganizationStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * contactStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterContactStatement(GeneratedYangParser.ContactStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * contactStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitContactStatement(GeneratedYangParser.ContactStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * descriptionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDescriptionStatement(GeneratedYangParser.DescriptionStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * descriptionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDescriptionStatement(GeneratedYangParser.DescriptionStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * referenceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterReferenceStatement(GeneratedYangParser.ReferenceStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * referenceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitReferenceStatement(GeneratedYangParser.ReferenceStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * revisionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRevisionStatement(GeneratedYangParser.RevisionStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * revisionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRevisionStatement(GeneratedYangParser.RevisionStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * revisionStatementBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRevisionStatementBody(GeneratedYangParser.RevisionStatementBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * revisionStatementBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRevisionStatementBody(GeneratedYangParser.RevisionStatementBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * subModuleStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterSubModuleStatement(GeneratedYangParser.SubModuleStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * subModuleStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitSubModuleStatement(GeneratedYangParser.SubModuleStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * submoduleBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterSubmoduleBody(GeneratedYangParser.SubmoduleBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * submoduleBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitSubmoduleBody(GeneratedYangParser.SubmoduleBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * submoduleHeaderStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterSubmoduleHeaderStatement(GeneratedYangParser.SubmoduleHeaderStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * submoduleHeaderStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitSubmoduleHeaderStatement(GeneratedYangParser.SubmoduleHeaderStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * belongstoStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterBelongstoStatement(GeneratedYangParser.BelongstoStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * belongstoStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitBelongstoStatement(GeneratedYangParser.BelongstoStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * belongstoStatementBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterBelongstoStatementBody(GeneratedYangParser.BelongstoStatementBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * belongstoStatementBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitBelongstoStatementBody(GeneratedYangParser.BelongstoStatementBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * extensionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterExtensionStatement(GeneratedYangParser.ExtensionStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * extensionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitExtensionStatement(GeneratedYangParser.ExtensionStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * extensionBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterExtensionBody(GeneratedYangParser.ExtensionBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * extensionBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitExtensionBody(GeneratedYangParser.ExtensionBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * argumentStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterArgumentStatement(GeneratedYangParser.ArgumentStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * argumentStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitArgumentStatement(GeneratedYangParser.ArgumentStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * argumentBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterArgumentBody(GeneratedYangParser.ArgumentBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * argumentBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitArgumentBody(GeneratedYangParser.ArgumentBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * yinElementStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterYinElementStatement(GeneratedYangParser.YinElementStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * yinElementStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitYinElementStatement(GeneratedYangParser.YinElementStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * identityStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterIdentityStatement(GeneratedYangParser.IdentityStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * identityStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitIdentityStatement(GeneratedYangParser.IdentityStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * identityBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterIdentityBody(GeneratedYangParser.IdentityBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * identityBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitIdentityBody(GeneratedYangParser.IdentityBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * baseStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterBaseStatement(GeneratedYangParser.BaseStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * baseStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitBaseStatement(GeneratedYangParser.BaseStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * featureStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterFeatureStatement(GeneratedYangParser.FeatureStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * featureStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitFeatureStatement(GeneratedYangParser.FeatureStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * featureBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterFeatureBody(GeneratedYangParser.FeatureBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * featureBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitFeatureBody(GeneratedYangParser.FeatureBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * dataDefStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDataDefStatement(GeneratedYangParser.DataDefStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * dataDefStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDataDefStatement(GeneratedYangParser.DataDefStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * ifFeatureStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterIfFeatureStatement(GeneratedYangParser.IfFeatureStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * ifFeatureStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitIfFeatureStatement(GeneratedYangParser.IfFeatureStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * unitsStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterUnitsStatement(GeneratedYangParser.UnitsStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * unitsStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitUnitsStatement(GeneratedYangParser.UnitsStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * typedefStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterTypedefStatement(GeneratedYangParser.TypedefStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * typedefStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitTypedefStatement(GeneratedYangParser.TypedefStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * typeStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterTypeStatement(GeneratedYangParser.TypeStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * typeStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitTypeStatement(GeneratedYangParser.TypeStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * typeBodyStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterTypeBodyStatements(GeneratedYangParser.TypeBodyStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * typeBodyStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitTypeBodyStatements(GeneratedYangParser.TypeBodyStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * numericalRestrictions.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDecimal64Specification(GeneratedYangParser.Decimal64SpecificationContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * numericalRestrictions.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDecimal64Specification(GeneratedYangParser.Decimal64SpecificationContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * numericalRestrictions.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterNumericalRestrictions(GeneratedYangParser.NumericalRestrictionsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * numericalRestrictions.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitNumericalRestrictions(GeneratedYangParser.NumericalRestrictionsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * rangeStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRangeStatement(GeneratedYangParser.RangeStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * rangeStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRangeStatement(GeneratedYangParser.RangeStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * commonStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterCommonStatements(GeneratedYangParser.CommonStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * commonStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitCommonStatements(GeneratedYangParser.CommonStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * stringRestrictions.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterStringRestrictions(GeneratedYangParser.StringRestrictionsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * stringRestrictions.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitStringRestrictions(GeneratedYangParser.StringRestrictionsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * lengthStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterLengthStatement(GeneratedYangParser.LengthStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * lengthStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitLengthStatement(GeneratedYangParser.LengthStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * patternStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterPatternStatement(GeneratedYangParser.PatternStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * patternStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitPatternStatement(GeneratedYangParser.PatternStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * defaultStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDefaultStatement(GeneratedYangParser.DefaultStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * defaultStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDefaultStatement(GeneratedYangParser.DefaultStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * enumSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterEnumSpecification(GeneratedYangParser.EnumSpecificationContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * enumSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitEnumSpecification(GeneratedYangParser.EnumSpecificationContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * enumStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterEnumStatement(GeneratedYangParser.EnumStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * enumStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitEnumStatement(GeneratedYangParser.EnumStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * enumStatementBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterEnumStatementBody(GeneratedYangParser.EnumStatementBodyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * enumStatementBody.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitEnumStatementBody(GeneratedYangParser.EnumStatementBodyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * leafrefSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterLeafrefSpecification(GeneratedYangParser.LeafrefSpecificationContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * leafrefSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitLeafrefSpecification(GeneratedYangParser.LeafrefSpecificationContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * pathStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterPathStatement(GeneratedYangParser.PathStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * pathStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitPathStatement(GeneratedYangParser.PathStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * requireInstanceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRequireInstanceStatement(GeneratedYangParser.RequireInstanceStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * requireInstanceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRequireInstanceStatement(GeneratedYangParser.RequireInstanceStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * instanceIdentifierSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterInstanceIdentifierSpecification(
+ GeneratedYangParser.InstanceIdentifierSpecificationContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * instanceIdentifierSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitInstanceIdentifierSpecification(GeneratedYangParser.InstanceIdentifierSpecificationContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * identityrefSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterIdentityrefSpecification(GeneratedYangParser.IdentityrefSpecificationContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * identityrefSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitIdentityrefSpecification(GeneratedYangParser.IdentityrefSpecificationContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * unionSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterUnionSpecification(GeneratedYangParser.UnionSpecificationContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * unionSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitUnionSpecification(GeneratedYangParser.UnionSpecificationContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * bitsSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterBitsSpecification(GeneratedYangParser.BitsSpecificationContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * bitsSpecification.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitBitsSpecification(GeneratedYangParser.BitsSpecificationContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * bitStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterBitStatement(GeneratedYangParser.BitStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * bitStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitBitStatement(GeneratedYangParser.BitStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * bitBodyStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterBitBodyStatement(GeneratedYangParser.BitBodyStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * bitBodyStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitBitBodyStatement(GeneratedYangParser.BitBodyStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * positionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterPositionStatement(GeneratedYangParser.PositionStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * positionStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitPositionStatement(GeneratedYangParser.PositionStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * statusStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterStatusStatement(GeneratedYangParser.StatusStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * statusStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitStatusStatement(GeneratedYangParser.StatusStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * configStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterConfigStatement(GeneratedYangParser.ConfigStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * configStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitConfigStatement(GeneratedYangParser.ConfigStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * mandatoryStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterMandatoryStatement(GeneratedYangParser.MandatoryStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * mandatoryStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitMandatoryStatement(GeneratedYangParser.MandatoryStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * presenceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterPresenceStatement(GeneratedYangParser.PresenceStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * presenceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitPresenceStatement(GeneratedYangParser.PresenceStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * orderedByStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterOrderedByStatement(GeneratedYangParser.OrderedByStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * orderedByStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitOrderedByStatement(GeneratedYangParser.OrderedByStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * mustStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterMustStatement(GeneratedYangParser.MustStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * mustStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitMustStatement(GeneratedYangParser.MustStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * errorMessageStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterErrorMessageStatement(GeneratedYangParser.ErrorMessageStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * errorMessageStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitErrorMessageStatement(GeneratedYangParser.ErrorMessageStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * errorAppTagStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterErrorAppTagStatement(GeneratedYangParser.ErrorAppTagStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * errorAppTagStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitErrorAppTagStatement(GeneratedYangParser.ErrorAppTagStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * minElementsStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterMinElementsStatement(GeneratedYangParser.MinElementsStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * minElementsStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitMinElementsStatement(GeneratedYangParser.MinElementsStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * maxElementsStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterMaxElementsStatement(GeneratedYangParser.MaxElementsStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * maxElementsStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitMaxElementsStatement(GeneratedYangParser.MaxElementsStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * valueStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterValueStatement(GeneratedYangParser.ValueStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * valueStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitValueStatement(GeneratedYangParser.ValueStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * groupingStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterGroupingStatement(GeneratedYangParser.GroupingStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * groupingStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitGroupingStatement(GeneratedYangParser.GroupingStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * containerStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterContainerStatement(GeneratedYangParser.ContainerStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * containerStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitContainerStatement(GeneratedYangParser.ContainerStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * leafStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterLeafStatement(GeneratedYangParser.LeafStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * leafStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitLeafStatement(GeneratedYangParser.LeafStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * leafListStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterLeafListStatement(GeneratedYangParser.LeafListStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * leafListStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitLeafListStatement(GeneratedYangParser.LeafListStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * listStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterListStatement(GeneratedYangParser.ListStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * listStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitListStatement(GeneratedYangParser.ListStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * keyStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterKeyStatement(GeneratedYangParser.KeyStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule
+ * keyStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitKeyStatement(GeneratedYangParser.KeyStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule
+ * uniqueStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterUniqueStatement(GeneratedYangParser.UniqueStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule uniqueStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitUniqueStatement(GeneratedYangParser.UniqueStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule choiceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterChoiceStatement(GeneratedYangParser.ChoiceStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule choiceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitChoiceStatement(GeneratedYangParser.ChoiceStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule shortCaseStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterShortCaseStatement(GeneratedYangParser.ShortCaseStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule shortCaseStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitShortCaseStatement(GeneratedYangParser.ShortCaseStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule caseStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterCaseStatement(GeneratedYangParser.CaseStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule caseStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitCaseStatement(GeneratedYangParser.CaseStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule anyxmlStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterAnyxmlStatement(GeneratedYangParser.AnyxmlStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule anyxmlStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitAnyxmlStatement(GeneratedYangParser.AnyxmlStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule usesStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterUsesStatement(GeneratedYangParser.UsesStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule usesStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitUsesStatement(GeneratedYangParser.UsesStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refineStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefineStatement(GeneratedYangParser.RefineStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refineStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefineStatement(GeneratedYangParser.RefineStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refineContainerStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefineContainerStatements(GeneratedYangParser.RefineContainerStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refineContainerStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefineContainerStatements(GeneratedYangParser.RefineContainerStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refineLeafStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefineLeafStatements(GeneratedYangParser.RefineLeafStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refineLeafStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefineLeafStatements(GeneratedYangParser.RefineLeafStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refineLeafListStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefineLeafListStatements(GeneratedYangParser.RefineLeafListStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refineLeafListStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefineLeafListStatements(GeneratedYangParser.RefineLeafListStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refineListStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefineListStatements(GeneratedYangParser.RefineListStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refineListStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefineListStatements(GeneratedYangParser.RefineListStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refineChoiceStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefineChoiceStatements(GeneratedYangParser.RefineChoiceStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refineChoiceStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefineChoiceStatements(GeneratedYangParser.RefineChoiceStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refineCaseStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefineCaseStatements(GeneratedYangParser.RefineCaseStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refineCaseStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefineCaseStatements(GeneratedYangParser.RefineCaseStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refineAnyxmlStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefineAnyxmlStatements(GeneratedYangParser.RefineAnyxmlStatementsContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refineAnyxmlStatements.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefineAnyxmlStatements(GeneratedYangParser.RefineAnyxmlStatementsContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule augmentStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterAugmentStatement(GeneratedYangParser.AugmentStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule augmentStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitAugmentStatement(GeneratedYangParser.AugmentStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule whenStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterWhenStatement(GeneratedYangParser.WhenStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule whenStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitWhenStatement(GeneratedYangParser.WhenStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule rpcStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRpcStatement(GeneratedYangParser.RpcStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule rpcStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRpcStatement(GeneratedYangParser.RpcStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule inputStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterInputStatement(GeneratedYangParser.InputStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule inputStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitInputStatement(GeneratedYangParser.InputStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule outputStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterOutputStatement(GeneratedYangParser.OutputStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule outputStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitOutputStatement(GeneratedYangParser.OutputStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule notificationStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterNotificationStatement(GeneratedYangParser.NotificationStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule notificationStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitNotificationStatement(GeneratedYangParser.NotificationStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule deviationStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDeviationStatement(GeneratedYangParser.DeviationStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule deviationStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDeviationStatement(GeneratedYangParser.DeviationStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule deviateNotSupportedStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDeviateNotSupportedStatement(GeneratedYangParser.DeviateNotSupportedStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule deviateNotSupportedStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDeviateNotSupportedStatement(GeneratedYangParser.DeviateNotSupportedStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule deviateAddStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDeviateAddStatement(GeneratedYangParser.DeviateAddStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule deviateAddStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDeviateAddStatement(GeneratedYangParser.DeviateAddStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule deviateDeleteStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDeviateDeleteStatement(GeneratedYangParser.DeviateDeleteStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule deviateDeleteStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDeviateDeleteStatement(GeneratedYangParser.DeviateDeleteStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule deviateReplaceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDeviateReplaceStatement(GeneratedYangParser.DeviateReplaceStatementContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule deviateReplaceStatement.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDeviateReplaceStatement(GeneratedYangParser.DeviateReplaceStatementContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule string.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterString(GeneratedYangParser.StringContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule string.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitString(GeneratedYangParser.StringContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule identifier.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterIdentifier(GeneratedYangParser.IdentifierContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule identifier.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitIdentifier(GeneratedYangParser.IdentifierContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule version.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterVersion(GeneratedYangParser.VersionContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule version.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitVersion(GeneratedYangParser.VersionContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule range.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRange(GeneratedYangParser.RangeContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule range.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRange(GeneratedYangParser.RangeContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule dateArgumentString.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDateArgumentString(GeneratedYangParser.DateArgumentStringContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule dateArgumentString.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDateArgumentString(GeneratedYangParser.DateArgumentStringContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule length.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterLength(GeneratedYangParser.LengthContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule length.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitLength(GeneratedYangParser.LengthContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule path.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterPath(GeneratedYangParser.PathContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule path.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitPath(GeneratedYangParser.PathContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule position.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterPosition(GeneratedYangParser.PositionContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule position.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitPosition(GeneratedYangParser.PositionContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule status.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterStatus(GeneratedYangParser.StatusContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule status.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitStatus(GeneratedYangParser.StatusContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule config.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterConfig(GeneratedYangParser.ConfigContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule config.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitConfig(GeneratedYangParser.ConfigContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule mandatory.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterMandatory(GeneratedYangParser.MandatoryContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule mandatory.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitMandatory(GeneratedYangParser.MandatoryContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule ordered-by.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterOrderedBy(GeneratedYangParser.OrderedByContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule ordered-by.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitOrderedBy(GeneratedYangParser.OrderedByContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule min elements value.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterMinValue(GeneratedYangParser.MinValueContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule min elements value.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitMinValue(GeneratedYangParser.MinValueContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule max elements value.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterMaxValue(GeneratedYangParser.MaxValueContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule max elements value.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitMaxValue(GeneratedYangParser.MaxValueContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule key.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterKey(GeneratedYangParser.KeyContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule key.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitKey(GeneratedYangParser.KeyContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule unique.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterUnique(GeneratedYangParser.UniqueContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule unique.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitUnique(GeneratedYangParser.UniqueContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule refine.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterRefine(GeneratedYangParser.RefineContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule refine.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitRefine(GeneratedYangParser.RefineContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule augment.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterAugment(GeneratedYangParser.AugmentContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule augment.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitAugment(GeneratedYangParser.AugmentContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule augment.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterFraction(GeneratedYangParser.FractionContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule augment.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitFraction(GeneratedYangParser.FractionContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule deviation.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterDeviation(GeneratedYangParser.DeviationContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule deviation.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitDeviation(GeneratedYangParser.DeviationContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule deviation.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterValue(GeneratedYangParser.ValueContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule deviation.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitValue(GeneratedYangParser.ValueContext currentContext);
+
+ /**
+ * Enters a parse tree produced by GeneratedYangParser for grammar rule yang construct.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void enterYangConstruct(GeneratedYangParser.YangConstructContext currentContext);
+
+ /**
+ * Exits a parse tree produced by GeneratedYangParser for grammar rule yang construct.
+ *
+ * @param currentContext current context in the parsed tree
+ */
+ void exitYangConstruct(GeneratedYangParser.YangConstructContext currentContext);
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/antlrgencode/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/parser/antlrgencode/package-info.java
new file mode 100644
index 0000000..747974e
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/antlrgencode/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+/**
+ * ANTLR interfaces to be implemented by listener.
+ */
+package org.onosproject.yangutils.parser.antlrgencode;
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/exceptions/ParserException.java b/plugin/src/main/java/org/onosproject/yangutils/parser/exceptions/ParserException.java
new file mode 100644
index 0000000..6a18b54
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/exceptions/ParserException.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.exceptions;
+
+/**
+ * Represents base class for exceptions in parser operations.
+ */
+public class ParserException extends RuntimeException {
+
+ private static final long serialVersionUID = 20160211L;
+ private int lineNumber;
+ private int charPositionInLine;
+ private String fileName;
+
+ /**
+ * Creates a new parser exception.
+ */
+ public ParserException() {
+ super();
+ }
+
+ /**
+ * Creates a new parser exception with given message.
+ *
+ * @param message the detail of exception in string
+ */
+ public ParserException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new parser exception from given message and cause.
+ *
+ * @param message the detail of exception in string
+ * @param cause underlying cause of the error
+ */
+ public ParserException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new parser exception from cause.
+ *
+ * @param cause underlying cause of the error
+ */
+ public ParserException(final Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Returns line number of the exception.
+ *
+ * @return line number of the exception
+ */
+ public int getLineNumber() {
+ return this.lineNumber;
+ }
+
+ /**
+ * Returns YANG file name of the exception.
+ *
+ * @return YANG file name of the exception
+ */
+ public String getFileName() {
+ return this.fileName;
+ }
+
+ /**
+ * Returns position of the exception.
+ *
+ * @return position of the exception
+ */
+ public int getCharPositionInLine() {
+ return this.charPositionInLine;
+ }
+
+ /**
+ * Sets line number of YANG file.
+ *
+ * @param line line number of YANG file
+ */
+ public void setLine(int line) {
+ this.lineNumber = line;
+ }
+
+ /**
+ * Sets position of exception.
+ *
+ * @param charPosition position of exception
+ */
+ public void setCharPosition(int charPosition) {
+ this.charPositionInLine = charPosition;
+ }
+
+ /**
+ * Sets file name in parser exception.
+ *
+ * @param fileName YANG file name
+ */
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/exceptions/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/parser/exceptions/package-info.java
new file mode 100644
index 0000000..ec36b0d
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/exceptions/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+/**
+ * Custom parser exceptions.
+ */
+package org.onosproject.yangutils.parser.exceptions;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/TreeWalkListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/TreeWalkListener.java
new file mode 100644
index 0000000..194d32f
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/TreeWalkListener.java
@@ -0,0 +1,1423 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl;
+
+import java.util.Stack;
+
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.antlr.v4.runtime.tree.ErrorNode;
+import org.antlr.v4.runtime.tree.TerminalNode;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangListener;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.impl.listeners.AugmentListener;
+import org.onosproject.yangutils.parser.impl.listeners.BaseFileListener;
+import org.onosproject.yangutils.parser.impl.listeners.BelongsToListener;
+import org.onosproject.yangutils.parser.impl.listeners.BitListener;
+import org.onosproject.yangutils.parser.impl.listeners.BitsListener;
+import org.onosproject.yangutils.parser.impl.listeners.CaseListener;
+import org.onosproject.yangutils.parser.impl.listeners.ChoiceListener;
+import org.onosproject.yangutils.parser.impl.listeners.ConfigListener;
+import org.onosproject.yangutils.parser.impl.listeners.ContactListener;
+import org.onosproject.yangutils.parser.impl.listeners.ContainerListener;
+import org.onosproject.yangutils.parser.impl.listeners.DefaultListener;
+import org.onosproject.yangutils.parser.impl.listeners.DescriptionListener;
+import org.onosproject.yangutils.parser.impl.listeners.EnumListener;
+import org.onosproject.yangutils.parser.impl.listeners.EnumerationListener;
+import org.onosproject.yangutils.parser.impl.listeners.GroupingListener;
+import org.onosproject.yangutils.parser.impl.listeners.ImportListener;
+import org.onosproject.yangutils.parser.impl.listeners.IncludeListener;
+import org.onosproject.yangutils.parser.impl.listeners.InputListener;
+import org.onosproject.yangutils.parser.impl.listeners.KeyListener;
+import org.onosproject.yangutils.parser.impl.listeners.LeafListListener;
+import org.onosproject.yangutils.parser.impl.listeners.LeafListener;
+import org.onosproject.yangutils.parser.impl.listeners.LengthRestrictionListener;
+import org.onosproject.yangutils.parser.impl.listeners.ListListener;
+import org.onosproject.yangutils.parser.impl.listeners.MandatoryListener;
+import org.onosproject.yangutils.parser.impl.listeners.MaxElementsListener;
+import org.onosproject.yangutils.parser.impl.listeners.MinElementsListener;
+import org.onosproject.yangutils.parser.impl.listeners.ModuleListener;
+import org.onosproject.yangutils.parser.impl.listeners.NotificationListener;
+import org.onosproject.yangutils.parser.impl.listeners.NamespaceListener;
+import org.onosproject.yangutils.parser.impl.listeners.OrganizationListener;
+import org.onosproject.yangutils.parser.impl.listeners.OutputListener;
+import org.onosproject.yangutils.parser.impl.listeners.PatternRestrictionListener;
+import org.onosproject.yangutils.parser.impl.listeners.PositionListener;
+import org.onosproject.yangutils.parser.impl.listeners.PrefixListener;
+import org.onosproject.yangutils.parser.impl.listeners.PresenceListener;
+import org.onosproject.yangutils.parser.impl.listeners.RangeRestrictionListener;
+import org.onosproject.yangutils.parser.impl.listeners.ReferenceListener;
+import org.onosproject.yangutils.parser.impl.listeners.RevisionDateListener;
+import org.onosproject.yangutils.parser.impl.listeners.RevisionListener;
+import org.onosproject.yangutils.parser.impl.listeners.RpcListener;
+import org.onosproject.yangutils.parser.impl.listeners.ShortCaseListener;
+import org.onosproject.yangutils.parser.impl.listeners.StatusListener;
+import org.onosproject.yangutils.parser.impl.listeners.SubModuleListener;
+import org.onosproject.yangutils.parser.impl.listeners.TypeDefListener;
+import org.onosproject.yangutils.parser.impl.listeners.TypeListener;
+import org.onosproject.yangutils.parser.impl.listeners.UnionListener;
+import org.onosproject.yangutils.parser.impl.listeners.UnitsListener;
+import org.onosproject.yangutils.parser.impl.listeners.UsesListener;
+import org.onosproject.yangutils.parser.impl.listeners.ValueListener;
+import org.onosproject.yangutils.parser.impl.listeners.VersionListener;
+
+import static org.onosproject.yangutils.utils.UtilConstants.UNSUPPORTED_YANG_CONSTRUCT;
+import static org.onosproject.yangutils.utils.UtilConstants.CURRENTLY_UNSUPPORTED;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.handleUnsupportedYangConstruct;
+
+/**
+ * Represents ANTLR generates parse-tree. ANTLR generates a parse-tree listener interface that responds to events
+ * triggered by the built-in tree walker. The methods in listener are just
+ * callbacks. This class implements listener interface and generates the
+ * corresponding data model tree.
+ */
+public class TreeWalkListener implements GeneratedYangListener {
+
+ // List of parsable node entries maintained in stack
+ private Stack<Parsable> parsedDataStack = new Stack<>();
+
+ // Parse tree root node
+ private YangNode rootNode;
+
+ /**
+ * Returns stack of parsable data.
+ *
+ * @return stack of parsable data
+ */
+ public Stack<Parsable> getParsedDataStack() {
+ return parsedDataStack;
+ }
+
+ /**
+ * Returns root node.
+ *
+ * @return rootNode of data model tree
+ */
+ public YangNode getRootNode() {
+ return rootNode;
+ }
+
+ /**
+ * Set parsed data stack.
+ *
+ * @param parsedDataStack stack of parsable data objects
+ */
+ public void setParsedDataStack(Stack<Parsable> parsedDataStack) {
+ this.parsedDataStack = parsedDataStack;
+ }
+
+ /**
+ * Set root node.
+ *
+ * @param rootNode root node of data model tree
+ */
+ public void setRootNode(YangNode rootNode) {
+ this.rootNode = rootNode;
+ }
+
+ @Override
+ public void enterYangfile(GeneratedYangParser.YangfileContext ctx) {
+ BaseFileListener.processYangFileEntry(this, ctx);
+ }
+
+ @Override
+ public void exitYangfile(GeneratedYangParser.YangfileContext ctx) {
+ BaseFileListener.processYangFileExit(this, ctx);
+ }
+
+ @Override
+ public void enterModuleStatement(GeneratedYangParser.ModuleStatementContext ctx) {
+ ModuleListener.processModuleEntry(this, ctx);
+ }
+
+ @Override
+ public void exitModuleStatement(GeneratedYangParser.ModuleStatementContext ctx) {
+ ModuleListener.processModuleExit(this, ctx);
+ }
+
+ @Override
+ public void enterModuleBody(GeneratedYangParser.ModuleBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitModuleBody(GeneratedYangParser.ModuleBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterModuleHeaderStatement(GeneratedYangParser.ModuleHeaderStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitModuleHeaderStatement(GeneratedYangParser.ModuleHeaderStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterLinkageStatements(GeneratedYangParser.LinkageStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitLinkageStatements(GeneratedYangParser.LinkageStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterMetaStatements(GeneratedYangParser.MetaStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitMetaStatements(GeneratedYangParser.MetaStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRevisionStatements(GeneratedYangParser.RevisionStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRevisionStatements(GeneratedYangParser.RevisionStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterBodyStatements(GeneratedYangParser.BodyStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitBodyStatements(GeneratedYangParser.BodyStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterYangVersionStatement(GeneratedYangParser.YangVersionStatementContext ctx) {
+ VersionListener.processVersionEntry(this, ctx);
+ }
+
+ @Override
+ public void exitYangVersionStatement(GeneratedYangParser.YangVersionStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterNamespaceStatement(GeneratedYangParser.NamespaceStatementContext ctx) {
+ NamespaceListener.processNamespaceEntry(this, ctx);
+ }
+
+ @Override
+ public void exitNamespaceStatement(GeneratedYangParser.NamespaceStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterPrefixStatement(GeneratedYangParser.PrefixStatementContext ctx) {
+ PrefixListener.processPrefixEntry(this, ctx);
+ }
+
+ @Override
+ public void exitPrefixStatement(GeneratedYangParser.PrefixStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterImportStatement(GeneratedYangParser.ImportStatementContext ctx) {
+ ImportListener.processImportEntry(this, ctx);
+ }
+
+ @Override
+ public void exitImportStatement(GeneratedYangParser.ImportStatementContext ctx) {
+ ImportListener.processImportExit(this, ctx);
+ }
+
+ @Override
+ public void enterImportStatementBody(GeneratedYangParser.ImportStatementBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitImportStatementBody(GeneratedYangParser.ImportStatementBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRevisionDateStatement(GeneratedYangParser.RevisionDateStatementContext ctx) {
+ RevisionDateListener.processRevisionDateEntry(this, ctx);
+ }
+
+ @Override
+ public void exitRevisionDateStatement(GeneratedYangParser.RevisionDateStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterIncludeStatement(GeneratedYangParser.IncludeStatementContext ctx) {
+ IncludeListener.processIncludeEntry(this, ctx);
+ }
+
+ @Override
+ public void exitIncludeStatement(GeneratedYangParser.IncludeStatementContext ctx) {
+ IncludeListener.processIncludeExit(this, ctx);
+ }
+
+ @Override
+ public void enterOrganizationStatement(GeneratedYangParser.OrganizationStatementContext ctx) {
+ OrganizationListener.processOrganizationEntry(this, ctx);
+ }
+
+ @Override
+ public void exitOrganizationStatement(GeneratedYangParser.OrganizationStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterContactStatement(GeneratedYangParser.ContactStatementContext ctx) {
+ ContactListener.processContactEntry(this, ctx);
+ }
+
+ @Override
+ public void exitContactStatement(GeneratedYangParser.ContactStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterDescriptionStatement(GeneratedYangParser.DescriptionStatementContext ctx) {
+ DescriptionListener.processDescriptionEntry(this, ctx);
+ }
+
+ @Override
+ public void exitDescriptionStatement(GeneratedYangParser.DescriptionStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterReferenceStatement(GeneratedYangParser.ReferenceStatementContext ctx) {
+ ReferenceListener.processReferenceEntry(this, ctx);
+ }
+
+ @Override
+ public void exitReferenceStatement(GeneratedYangParser.ReferenceStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRevisionStatement(GeneratedYangParser.RevisionStatementContext ctx) {
+ RevisionListener.processRevisionEntry(this, ctx);
+ }
+
+ @Override
+ public void exitRevisionStatement(GeneratedYangParser.RevisionStatementContext ctx) {
+ RevisionListener.processRevisionExit(this, ctx);
+ }
+
+ @Override
+ public void enterRevisionStatementBody(GeneratedYangParser.RevisionStatementBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRevisionStatementBody(GeneratedYangParser.RevisionStatementBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterSubModuleStatement(GeneratedYangParser.SubModuleStatementContext ctx) {
+ SubModuleListener.processSubModuleEntry(this, ctx);
+ }
+
+ @Override
+ public void exitSubModuleStatement(GeneratedYangParser.SubModuleStatementContext ctx) {
+ SubModuleListener.processSubModuleExit(this, ctx);
+ }
+
+ @Override
+ public void enterSubmoduleBody(GeneratedYangParser.SubmoduleBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitSubmoduleBody(GeneratedYangParser.SubmoduleBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterSubmoduleHeaderStatement(GeneratedYangParser.SubmoduleHeaderStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitSubmoduleHeaderStatement(GeneratedYangParser.SubmoduleHeaderStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterBelongstoStatement(GeneratedYangParser.BelongstoStatementContext ctx) {
+ BelongsToListener.processBelongsToEntry(this, ctx);
+ }
+
+ @Override
+ public void exitBelongstoStatement(GeneratedYangParser.BelongstoStatementContext ctx) {
+ BelongsToListener.processBelongsToExit(this, ctx);
+ }
+
+ @Override
+ public void enterBelongstoStatementBody(GeneratedYangParser.BelongstoStatementBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitBelongstoStatementBody(GeneratedYangParser.BelongstoStatementBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterExtensionStatement(GeneratedYangParser.ExtensionStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.EXTENSION_DATA, ctx, UNSUPPORTED_YANG_CONSTRUCT);
+ }
+
+ @Override
+ public void exitExtensionStatement(GeneratedYangParser.ExtensionStatementContext ctx) {
+ // do nothing
+ }
+
+ @Override
+ public void enterExtensionBody(GeneratedYangParser.ExtensionBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitExtensionBody(GeneratedYangParser.ExtensionBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterArgumentStatement(GeneratedYangParser.ArgumentStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitArgumentStatement(GeneratedYangParser.ArgumentStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterArgumentBody(GeneratedYangParser.ArgumentBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitArgumentBody(GeneratedYangParser.ArgumentBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterYinElementStatement(GeneratedYangParser.YinElementStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitYinElementStatement(GeneratedYangParser.YinElementStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterIdentityStatement(GeneratedYangParser.IdentityStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.IDENTITY_DATA, ctx, CURRENTLY_UNSUPPORTED);
+ }
+
+ @Override
+ public void exitIdentityStatement(GeneratedYangParser.IdentityStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterIdentityBody(GeneratedYangParser.IdentityBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitIdentityBody(GeneratedYangParser.IdentityBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterBaseStatement(GeneratedYangParser.BaseStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.BASE_DATA, ctx, CURRENTLY_UNSUPPORTED);
+ }
+
+ @Override
+ public void exitBaseStatement(GeneratedYangParser.BaseStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterFeatureStatement(GeneratedYangParser.FeatureStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.FEATURE_DATA, ctx, CURRENTLY_UNSUPPORTED);
+ }
+
+ @Override
+ public void exitFeatureStatement(GeneratedYangParser.FeatureStatementContext ctx) {
+ //TODO: to be implemented
+ }
+
+ @Override
+ public void enterFeatureBody(GeneratedYangParser.FeatureBodyContext ctx) {
+ //TODO : to be implemented
+ }
+
+ @Override
+ public void exitFeatureBody(GeneratedYangParser.FeatureBodyContext ctx) {
+ //TODO : to be implemented
+ }
+
+ @Override
+ public void enterDataDefStatement(GeneratedYangParser.DataDefStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitDataDefStatement(GeneratedYangParser.DataDefStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterIfFeatureStatement(GeneratedYangParser.IfFeatureStatementContext ctx) {
+ // TODO: to be implemented
+ }
+
+ @Override
+ public void exitIfFeatureStatement(GeneratedYangParser.IfFeatureStatementContext ctx) {
+ // TODO: to be implemented
+ }
+
+ @Override
+ public void enterUnitsStatement(GeneratedYangParser.UnitsStatementContext ctx) {
+ UnitsListener.processUnitsEntry(this, ctx);
+ }
+
+ @Override
+ public void exitUnitsStatement(GeneratedYangParser.UnitsStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterTypedefStatement(GeneratedYangParser.TypedefStatementContext ctx) {
+ TypeDefListener.processTypeDefEntry(this, ctx);
+ }
+
+ @Override
+ public void exitTypedefStatement(GeneratedYangParser.TypedefStatementContext ctx) {
+ TypeDefListener.processTypeDefExit(this, ctx);
+ }
+
+ @Override
+ public void enterTypeStatement(GeneratedYangParser.TypeStatementContext ctx) {
+ TypeListener.processTypeEntry(this, ctx);
+ }
+
+ @Override
+ public void exitTypeStatement(GeneratedYangParser.TypeStatementContext ctx) {
+ TypeListener.processTypeExit(this, ctx);
+ }
+
+ @Override
+ public void enterTypeBodyStatements(GeneratedYangParser.TypeBodyStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitTypeBodyStatements(GeneratedYangParser.TypeBodyStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterDecimal64Specification(GeneratedYangParser.Decimal64SpecificationContext ctx) {
+ // TODO: implement the method.
+ }
+
+ @Override
+ public void exitDecimal64Specification(GeneratedYangParser.Decimal64SpecificationContext ctx) {
+ // TODO: implement the method.
+ }
+
+ @Override
+ public void enterNumericalRestrictions(GeneratedYangParser.NumericalRestrictionsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitNumericalRestrictions(GeneratedYangParser.NumericalRestrictionsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRangeStatement(GeneratedYangParser.RangeStatementContext ctx) {
+ RangeRestrictionListener.processRangeRestrictionEntry(this, ctx);
+ }
+
+ @Override
+ public void exitRangeStatement(GeneratedYangParser.RangeStatementContext ctx) {
+ RangeRestrictionListener.processRangeRestrictionExit(this, ctx);
+ }
+
+ @Override
+ public void enterCommonStatements(GeneratedYangParser.CommonStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitCommonStatements(GeneratedYangParser.CommonStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterStringRestrictions(GeneratedYangParser.StringRestrictionsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitStringRestrictions(GeneratedYangParser.StringRestrictionsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterLengthStatement(GeneratedYangParser.LengthStatementContext ctx) {
+ LengthRestrictionListener.processLengthRestrictionEntry(this, ctx);
+ }
+
+ @Override
+ public void exitLengthStatement(GeneratedYangParser.LengthStatementContext ctx) {
+ LengthRestrictionListener.processLengthRestrictionExit(this, ctx);
+ }
+
+ @Override
+ public void enterPatternStatement(GeneratedYangParser.PatternStatementContext ctx) {
+ PatternRestrictionListener.processPatternRestrictionEntry(this, ctx);
+ }
+
+ @Override
+ public void exitPatternStatement(GeneratedYangParser.PatternStatementContext ctx) {
+ PatternRestrictionListener.processPatternRestrictionExit(this, ctx);
+ }
+
+ @Override
+ public void enterDefaultStatement(GeneratedYangParser.DefaultStatementContext ctx) {
+ DefaultListener.processDefaultEntry(this, ctx);
+ }
+
+ @Override
+ public void exitDefaultStatement(GeneratedYangParser.DefaultStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterEnumSpecification(GeneratedYangParser.EnumSpecificationContext ctx) {
+ EnumerationListener.processEnumerationEntry(this, ctx);
+ }
+
+ @Override
+ public void exitEnumSpecification(GeneratedYangParser.EnumSpecificationContext ctx) {
+ EnumerationListener.processEnumerationExit(this, ctx);
+ }
+
+ @Override
+ public void enterEnumStatement(GeneratedYangParser.EnumStatementContext ctx) {
+ EnumListener.processEnumEntry(this, ctx);
+ }
+
+ @Override
+ public void exitEnumStatement(GeneratedYangParser.EnumStatementContext ctx) {
+ EnumListener.processEnumExit(this, ctx);
+ }
+
+ @Override
+ public void enterEnumStatementBody(GeneratedYangParser.EnumStatementBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitEnumStatementBody(GeneratedYangParser.EnumStatementBodyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterLeafrefSpecification(GeneratedYangParser.LeafrefSpecificationContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitLeafrefSpecification(GeneratedYangParser.LeafrefSpecificationContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterPathStatement(GeneratedYangParser.PathStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.PATH_DATA, ctx, CURRENTLY_UNSUPPORTED);
+ }
+
+ @Override
+ public void exitPathStatement(GeneratedYangParser.PathStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRequireInstanceStatement(GeneratedYangParser.RequireInstanceStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.REQUIRE_INSTANCE_DATA, ctx, UNSUPPORTED_YANG_CONSTRUCT);
+ }
+
+ @Override
+ public void exitRequireInstanceStatement(GeneratedYangParser.RequireInstanceStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterInstanceIdentifierSpecification(GeneratedYangParser.InstanceIdentifierSpecificationContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitInstanceIdentifierSpecification(GeneratedYangParser.InstanceIdentifierSpecificationContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterIdentityrefSpecification(GeneratedYangParser.IdentityrefSpecificationContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitIdentityrefSpecification(GeneratedYangParser.IdentityrefSpecificationContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterUnionSpecification(GeneratedYangParser.UnionSpecificationContext ctx) {
+ UnionListener.processUnionEntry(this, ctx);
+ }
+
+ @Override
+ public void exitUnionSpecification(GeneratedYangParser.UnionSpecificationContext ctx) {
+ UnionListener.processUnionExit(this, ctx);
+ }
+
+ @Override
+ public void enterBitsSpecification(GeneratedYangParser.BitsSpecificationContext ctx) {
+ BitsListener.processBitsEntry(this, ctx);
+ }
+
+ @Override
+ public void exitBitsSpecification(GeneratedYangParser.BitsSpecificationContext ctx) {
+ BitsListener.processBitsExit(this, ctx);
+ }
+
+ @Override
+ public void enterBitStatement(GeneratedYangParser.BitStatementContext ctx) {
+ BitListener.processBitEntry(this, ctx);
+ }
+
+ @Override
+ public void exitBitStatement(GeneratedYangParser.BitStatementContext ctx) {
+ BitListener.processBitExit(this, ctx);
+ }
+
+ @Override
+ public void enterBitBodyStatement(GeneratedYangParser.BitBodyStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitBitBodyStatement(GeneratedYangParser.BitBodyStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterPositionStatement(GeneratedYangParser.PositionStatementContext ctx) {
+ PositionListener.processPositionEntry(this, ctx);
+ }
+
+ @Override
+ public void exitPositionStatement(GeneratedYangParser.PositionStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterStatusStatement(GeneratedYangParser.StatusStatementContext ctx) {
+ StatusListener.processStatusEntry(this, ctx);
+ }
+
+ @Override
+ public void exitStatusStatement(GeneratedYangParser.StatusStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterConfigStatement(GeneratedYangParser.ConfigStatementContext ctx) {
+ ConfigListener.processConfigEntry(this, ctx);
+ }
+
+ @Override
+ public void exitConfigStatement(GeneratedYangParser.ConfigStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterMandatoryStatement(GeneratedYangParser.MandatoryStatementContext ctx) {
+ MandatoryListener.processMandatoryEntry(this, ctx);
+ }
+
+ @Override
+ public void exitMandatoryStatement(GeneratedYangParser.MandatoryStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterPresenceStatement(GeneratedYangParser.PresenceStatementContext ctx) {
+ PresenceListener.processPresenceEntry(this, ctx);
+ }
+
+ @Override
+ public void exitPresenceStatement(GeneratedYangParser.PresenceStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterOrderedByStatement(GeneratedYangParser.OrderedByStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.ORDERED_BY_DATA, ctx, CURRENTLY_UNSUPPORTED);
+ }
+
+ @Override
+ public void exitOrderedByStatement(GeneratedYangParser.OrderedByStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterMustStatement(GeneratedYangParser.MustStatementContext ctx) {
+ // TODO: to be implemented
+ }
+
+ @Override
+ public void exitMustStatement(GeneratedYangParser.MustStatementContext ctx) {
+ // TODO: to be implemented
+ }
+
+ @Override
+ public void enterErrorMessageStatement(GeneratedYangParser.ErrorMessageStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.ERROR_MESSAGE_DATA, ctx, CURRENTLY_UNSUPPORTED);
+ }
+
+ @Override
+ public void exitErrorMessageStatement(GeneratedYangParser.ErrorMessageStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterErrorAppTagStatement(GeneratedYangParser.ErrorAppTagStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.ERROR_APP_TAG_DATA, ctx, CURRENTLY_UNSUPPORTED);
+ }
+
+ @Override
+ public void exitErrorAppTagStatement(GeneratedYangParser.ErrorAppTagStatementContext ctx) {
+ //do nothing
+ }
+
+ @Override
+ public void enterMinElementsStatement(GeneratedYangParser.MinElementsStatementContext ctx) {
+ MinElementsListener.processMinElementsEntry(this, ctx);
+ }
+
+ @Override
+ public void exitMinElementsStatement(GeneratedYangParser.MinElementsStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterMaxElementsStatement(GeneratedYangParser.MaxElementsStatementContext ctx) {
+ MaxElementsListener.processMaxElementsEntry(this, ctx);
+ }
+
+ @Override
+ public void exitMaxElementsStatement(GeneratedYangParser.MaxElementsStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterValueStatement(GeneratedYangParser.ValueStatementContext ctx) {
+ ValueListener.processValueEntry(this, ctx);
+ }
+
+ @Override
+ public void exitValueStatement(GeneratedYangParser.ValueStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterGroupingStatement(GeneratedYangParser.GroupingStatementContext ctx) {
+ GroupingListener.processGroupingEntry(this, ctx);
+ }
+
+ @Override
+ public void exitGroupingStatement(GeneratedYangParser.GroupingStatementContext ctx) {
+ GroupingListener.processGroupingExit(this, ctx);
+ }
+
+ @Override
+ public void enterContainerStatement(GeneratedYangParser.ContainerStatementContext ctx) {
+ ContainerListener.processContainerEntry(this, ctx);
+ }
+
+ @Override
+ public void exitContainerStatement(GeneratedYangParser.ContainerStatementContext ctx) {
+ ContainerListener.processContainerExit(this, ctx);
+ }
+
+ @Override
+ public void enterLeafStatement(GeneratedYangParser.LeafStatementContext ctx) {
+ LeafListener.processLeafEntry(this, ctx);
+ }
+
+ @Override
+ public void exitLeafStatement(GeneratedYangParser.LeafStatementContext ctx) {
+ LeafListener.processLeafExit(this, ctx);
+ }
+
+ @Override
+ public void enterLeafListStatement(GeneratedYangParser.LeafListStatementContext ctx) {
+ LeafListListener.processLeafListEntry(this, ctx);
+ }
+
+ @Override
+ public void exitLeafListStatement(GeneratedYangParser.LeafListStatementContext ctx) {
+ LeafListListener.processLeafListExit(this, ctx);
+ }
+
+ @Override
+ public void enterListStatement(GeneratedYangParser.ListStatementContext ctx) {
+ ListListener.processListEntry(this, ctx);
+ }
+
+ @Override
+ public void exitListStatement(GeneratedYangParser.ListStatementContext ctx) {
+ ListListener.processListExit(this, ctx);
+ }
+
+ @Override
+ public void enterKeyStatement(GeneratedYangParser.KeyStatementContext ctx) {
+ KeyListener.processKeyEntry(this, ctx);
+ }
+
+ @Override
+ public void exitKeyStatement(GeneratedYangParser.KeyStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterUniqueStatement(GeneratedYangParser.UniqueStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.UNIQUE_DATA, ctx, CURRENTLY_UNSUPPORTED);
+ }
+
+ @Override
+ public void exitUniqueStatement(GeneratedYangParser.UniqueStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterChoiceStatement(GeneratedYangParser.ChoiceStatementContext ctx) {
+ ChoiceListener.processChoiceEntry(this, ctx);
+ }
+
+ @Override
+ public void exitChoiceStatement(GeneratedYangParser.ChoiceStatementContext ctx) {
+ ChoiceListener.processChoiceExit(this, ctx);
+ }
+
+ @Override
+ public void enterShortCaseStatement(GeneratedYangParser.ShortCaseStatementContext ctx) {
+ ShortCaseListener.processShortCaseEntry(this, ctx);
+ }
+
+ @Override
+ public void exitShortCaseStatement(GeneratedYangParser.ShortCaseStatementContext ctx) {
+ ShortCaseListener.processShortCaseExit(this, ctx);
+ }
+
+ @Override
+ public void enterCaseStatement(GeneratedYangParser.CaseStatementContext ctx) {
+ CaseListener.processCaseEntry(this, ctx);
+ }
+
+ @Override
+ public void exitCaseStatement(GeneratedYangParser.CaseStatementContext ctx) {
+ CaseListener.processCaseExit(this, ctx);
+ }
+
+ @Override
+ public void enterAnyxmlStatement(GeneratedYangParser.AnyxmlStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.ANYXML_DATA, ctx, UNSUPPORTED_YANG_CONSTRUCT);
+ }
+
+ @Override
+ public void exitAnyxmlStatement(GeneratedYangParser.AnyxmlStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterUsesStatement(GeneratedYangParser.UsesStatementContext ctx) {
+ UsesListener.processUsesEntry(this, ctx);
+ }
+
+ @Override
+ public void exitUsesStatement(GeneratedYangParser.UsesStatementContext ctx) {
+ UsesListener.processUsesExit(this, ctx);
+ }
+
+ @Override
+ public void enterRefineStatement(GeneratedYangParser.RefineStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.REFINE_DATA, ctx, UNSUPPORTED_YANG_CONSTRUCT);
+ }
+
+ @Override
+ public void exitRefineStatement(GeneratedYangParser.RefineStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRefineContainerStatements(GeneratedYangParser.RefineContainerStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRefineContainerStatements(GeneratedYangParser.RefineContainerStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRefineLeafStatements(GeneratedYangParser.RefineLeafStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRefineLeafStatements(GeneratedYangParser.RefineLeafStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRefineLeafListStatements(GeneratedYangParser.RefineLeafListStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRefineLeafListStatements(GeneratedYangParser.RefineLeafListStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRefineListStatements(GeneratedYangParser.RefineListStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRefineListStatements(GeneratedYangParser.RefineListStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRefineChoiceStatements(GeneratedYangParser.RefineChoiceStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRefineChoiceStatements(GeneratedYangParser.RefineChoiceStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRefineCaseStatements(GeneratedYangParser.RefineCaseStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRefineCaseStatements(GeneratedYangParser.RefineCaseStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRefineAnyxmlStatements(GeneratedYangParser.RefineAnyxmlStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRefineAnyxmlStatements(GeneratedYangParser.RefineAnyxmlStatementsContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterAugmentStatement(GeneratedYangParser.AugmentStatementContext ctx) {
+ AugmentListener.processAugmentEntry(this, ctx);
+ }
+
+ @Override
+ public void exitAugmentStatement(GeneratedYangParser.AugmentStatementContext ctx) {
+ AugmentListener.processAugmentExit(this, ctx);
+ }
+
+ @Override
+ public void enterWhenStatement(GeneratedYangParser.WhenStatementContext ctx) {
+ // TODO: to be implemented
+ }
+
+ @Override
+ public void exitWhenStatement(GeneratedYangParser.WhenStatementContext ctx) {
+ // TODO: to be implemented
+ }
+
+ @Override
+ public void enterRpcStatement(GeneratedYangParser.RpcStatementContext ctx) {
+ RpcListener.processRpcEntry(this, ctx);
+ }
+
+ @Override
+ public void exitRpcStatement(GeneratedYangParser.RpcStatementContext ctx) {
+ RpcListener.processRpcExit(this, ctx);
+ }
+
+ @Override
+ public void enterInputStatement(GeneratedYangParser.InputStatementContext ctx) {
+ InputListener.processInputEntry(this, ctx);
+ }
+
+ @Override
+ public void exitInputStatement(GeneratedYangParser.InputStatementContext ctx) {
+ InputListener.processInputExit(this, ctx);
+ }
+
+ @Override
+ public void enterOutputStatement(GeneratedYangParser.OutputStatementContext ctx) {
+ OutputListener.processOutputEntry(this, ctx);
+ }
+
+ @Override
+ public void exitOutputStatement(GeneratedYangParser.OutputStatementContext ctx) {
+ OutputListener.processOutputExit(this, ctx);
+ }
+
+ @Override
+ public void enterNotificationStatement(GeneratedYangParser.NotificationStatementContext ctx) {
+ NotificationListener.processNotificationEntry(this, ctx);
+ }
+
+ @Override
+ public void exitNotificationStatement(GeneratedYangParser.NotificationStatementContext ctx) {
+ NotificationListener.processNotificationExit(this, ctx);
+ }
+
+ @Override
+ public void enterDeviationStatement(GeneratedYangParser.DeviationStatementContext ctx) {
+ handleUnsupportedYangConstruct(YangConstructType.DEVIATION_DATA, ctx, UNSUPPORTED_YANG_CONSTRUCT);
+ }
+
+ @Override
+ public void exitDeviationStatement(GeneratedYangParser.DeviationStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterDeviateNotSupportedStatement(GeneratedYangParser.DeviateNotSupportedStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitDeviateNotSupportedStatement(GeneratedYangParser.DeviateNotSupportedStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterDeviateAddStatement(GeneratedYangParser.DeviateAddStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitDeviateAddStatement(GeneratedYangParser.DeviateAddStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterDeviateDeleteStatement(GeneratedYangParser.DeviateDeleteStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitDeviateDeleteStatement(GeneratedYangParser.DeviateDeleteStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterDeviateReplaceStatement(GeneratedYangParser.DeviateReplaceStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitDeviateReplaceStatement(GeneratedYangParser.DeviateReplaceStatementContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterString(GeneratedYangParser.StringContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitString(GeneratedYangParser.StringContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterIdentifier(GeneratedYangParser.IdentifierContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitIdentifier(GeneratedYangParser.IdentifierContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterDateArgumentString(GeneratedYangParser.DateArgumentStringContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitDateArgumentString(GeneratedYangParser.DateArgumentStringContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRange(GeneratedYangParser.RangeContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRange(GeneratedYangParser.RangeContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterLength(GeneratedYangParser.LengthContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitLength(GeneratedYangParser.LengthContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterPath(GeneratedYangParser.PathContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitPath(GeneratedYangParser.PathContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterPosition(GeneratedYangParser.PositionContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitPosition(GeneratedYangParser.PositionContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterStatus(GeneratedYangParser.StatusContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitStatus(GeneratedYangParser.StatusContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterConfig(GeneratedYangParser.ConfigContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitConfig(GeneratedYangParser.ConfigContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterMandatory(GeneratedYangParser.MandatoryContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitMandatory(GeneratedYangParser.MandatoryContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterOrderedBy(GeneratedYangParser.OrderedByContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitOrderedBy(GeneratedYangParser.OrderedByContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterMinValue(GeneratedYangParser.MinValueContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitMinValue(GeneratedYangParser.MinValueContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterMaxValue(GeneratedYangParser.MaxValueContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitMaxValue(GeneratedYangParser.MaxValueContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterKey(GeneratedYangParser.KeyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitKey(GeneratedYangParser.KeyContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterUnique(GeneratedYangParser.UniqueContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitUnique(GeneratedYangParser.UniqueContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterRefine(GeneratedYangParser.RefineContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitRefine(GeneratedYangParser.RefineContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterAugment(GeneratedYangParser.AugmentContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitAugment(GeneratedYangParser.AugmentContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterDeviation(GeneratedYangParser.DeviationContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitDeviation(GeneratedYangParser.DeviationContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterYangConstruct(GeneratedYangParser.YangConstructContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitYangConstruct(GeneratedYangParser.YangConstructContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterVersion(GeneratedYangParser.VersionContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitVersion(GeneratedYangParser.VersionContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterValue(GeneratedYangParser.ValueContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitValue(GeneratedYangParser.ValueContext ctx) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterFraction(GeneratedYangParser.FractionContext ctx) {
+ // TODO: implement the method.
+ }
+
+ @Override
+ public void exitFraction(GeneratedYangParser.FractionContext ctx) {
+ // TODO: implement the method.
+ }
+
+ @Override
+ public void visitTerminal(TerminalNode terminalNode) {
+ // do nothing.
+ }
+
+ @Override
+ public void visitErrorNode(ErrorNode errorNode) {
+ // do nothing.
+ }
+
+ @Override
+ public void enterEveryRule(ParserRuleContext parserRuleContext) {
+ // do nothing.
+ }
+
+ @Override
+ public void exitEveryRule(ParserRuleContext parserRuleContext) {
+ // do nothing.
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/YangUtilsParserManager.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/YangUtilsParserManager.java
new file mode 100644
index 0000000..6a5b1d2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/YangUtilsParserManager.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl;
+
+import java.io.IOException;
+
+import org.antlr.v4.runtime.ANTLRFileStream;
+import org.antlr.v4.runtime.ANTLRInputStream;
+import org.antlr.v4.runtime.CommonTokenStream;
+import org.antlr.v4.runtime.tree.ParseTree;
+import org.antlr.v4.runtime.tree.ParseTreeWalker;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.parser.YangUtilsParser;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangLexer;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.parserutils.ParseTreeErrorListener;
+
+/**
+ * Represents file parsing, parse tree creation and data model tree creation
+ * corresponding to an input YANG file.
+ */
+public class YangUtilsParserManager implements YangUtilsParser {
+
+ @Override
+ public YangNode getDataModel(String yangFile) throws IOException, ParserException {
+
+ /**
+ * Create a char stream that reads from YANG file. Throws an exception
+ * in case input YANG file is either null or non existent.
+ */
+ ANTLRInputStream input;
+ try {
+ input = new ANTLRFileStream(yangFile);
+ } catch (IOException e) {
+ throw new ParserException("YANG file error : YANG file does not exist.");
+ }
+
+ // Create a lexer that feeds off of input char stream.
+ GeneratedYangLexer lexer = new GeneratedYangLexer(input);
+
+ // Create a buffer of tokens pulled from the lexer.
+ CommonTokenStream tokens = new CommonTokenStream(lexer);
+
+ // Create a parser that feeds off the tokens buffer.
+ GeneratedYangParser parser = new GeneratedYangParser(tokens);
+
+ // Remove console error listener.
+ parser.removeErrorListeners();
+
+ // Create instance of customized error listener.
+ ParseTreeErrorListener parseTreeErrorListener = new ParseTreeErrorListener();
+
+ // Add customized error listener to catch errors during parsing.
+ parser.addErrorListener(parseTreeErrorListener);
+
+ ParseTree tree;
+
+ try {
+ // Begin parsing YANG file and generate parse tree.
+ tree = parser.yangfile();
+ } catch (ParserException parserException) {
+ parserException.setFileName(yangFile);
+ throw parserException;
+ }
+
+ // Create a walker to walk the parse tree.
+ ParseTreeWalker walker = new ParseTreeWalker();
+
+ // Create a listener implementation class object.
+ TreeWalkListener treeWalker = new TreeWalkListener();
+
+ /**
+ * Walk parse tree, provide call backs to methods in listener and build
+ * data model tree.
+ */
+ try {
+ walker.walk(treeWalker, tree);
+ } catch (ParserException listenerException) {
+ // TODO free incomplete data model tree.
+ listenerException.setFileName(yangFile);
+ throw listenerException;
+ } finally {
+ // TODO free parsable stack
+ }
+
+ // Returns the Root Node of the constructed data model tree.
+ return treeWalker.getRootNode();
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/AugmentListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/AugmentListener.java
new file mode 100644
index 0000000..b6172ed
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/AugmentListener.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangAugment;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNodeIdentifier;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.YangUses;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.AUGMENT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CASE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DATA_DEF_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.WHEN_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.AugmentListenerUtil.generateNameForAugmentNode;
+import static org.onosproject.yangutils.parser.impl.parserutils.AugmentListenerUtil.getParentsPrefix;
+import static org.onosproject.yangutils.parser.impl.parserutils.AugmentListenerUtil.parserException;
+import static org.onosproject.yangutils.parser.impl.parserutils.AugmentListenerUtil.validateNodeInTargetPath;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidAbsoluteSchemaNodeId;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateMutuallyExclusiveChilds;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangAugmentNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * augment-stmt = augment-keyword sep augment-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * 1*((data-def-stmt stmtsep) /
+ * (case-stmt stmtsep))
+ * "}"
+ *
+ * ANTLR grammar rule
+ * augmentStatement : AUGMENT_KEYWORD augment LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | statusStatement
+ * | descriptionStatement | referenceStatement | dataDefStatement | caseStatement)* RIGHT_CURLY_BRACE;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "augment"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class AugmentListener {
+
+ /**
+ * Creates a new augment listener.
+ */
+ private AugmentListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (augment), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processAugmentEntry(TreeWalkListener listener,
+ GeneratedYangParser.AugmentStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, AUGMENT_DATA, ctx.augment().getText(), ENTRY);
+
+ // Validate augment argument string
+ List<YangNodeIdentifier> targetNodes = getValidAbsoluteSchemaNodeId(ctx.augment().getText(),
+ AUGMENT_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, "", AUGMENT_DATA);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+ if (curData instanceof YangModule || curData instanceof YangSubModule || curData instanceof YangUses) {
+ YangNode curNode = (YangNode) curData;
+ YangAugment yangAugment = getYangAugmentNode(JAVA_GENERATION);
+
+ //validateTargetNodePath(targetNodes, curNode, ctx);
+ // TODO: handle in linker.
+
+ yangAugment.setTargetNode(targetNodes);
+ yangAugment.setName(generateNameForAugmentNode(curData, targetNodes, listener));
+
+ try {
+ curNode.addChild(yangAugment);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ AUGMENT_DATA, ctx.augment().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(yangAugment);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, AUGMENT_DATA,
+ ctx.augment().getText(), ENTRY));
+ }
+
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (augment), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processAugmentExit(TreeWalkListener listener,
+ GeneratedYangParser.AugmentStatementContext ctx) {
+
+ //Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, AUGMENT_DATA, ctx.augment().getText(), EXIT);
+
+ if (!(listener.getParsedDataStack().peek() instanceof YangAugment)) {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, AUGMENT_DATA,
+ ctx.augment().getText(), EXIT));
+ }
+ listener.getParsedDataStack().pop();
+ }
+
+ /**
+ * Validates the cardinality of augment sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.AugmentStatementContext ctx) {
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, AUGMENT_DATA, ctx.augment().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, AUGMENT_DATA, ctx.augment().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, AUGMENT_DATA, ctx.augment().getText());
+ validateCardinalityMaxOne(ctx.whenStatement(), WHEN_DATA, AUGMENT_DATA, ctx.augment().getText());
+ validateMutuallyExclusiveChilds(ctx.dataDefStatement(), DATA_DEF_DATA, ctx.caseStatement(),
+ CASE_DATA, AUGMENT_DATA, ctx.augment().getText());
+ }
+
+ /**
+ * Validates whether the current target node path is correct or not.
+ *
+ * @param targetNodes list of target nodes
+ * @param curNode current Node
+ * @param ctx augment context
+ * @param curNode current YANG node
+ */
+ private static void validateTargetNodePath(List<YangNodeIdentifier> targetNodes, YangNode curNode,
+ GeneratedYangParser.AugmentStatementContext ctx) {
+
+ YangNodeIdentifier moduleId = targetNodes.get(0);
+ if (moduleId.getPrefix() == null) {
+ if (!moduleId.getName().equals(curNode.getName())) {
+ throw parserException(ctx);
+ } else {
+ //validateNodeInTargetPath(curNode, targetNodes, ctx);
+ // TODO: handle in linker.
+ }
+ } else {
+ String parentPrefix = getParentsPrefix(curNode);
+ if (parentPrefix != null) {
+ if (!parentPrefix.equals(moduleId.getPrefix())) {
+ // TODO: handle in linker.
+ } else {
+ validateNodeInTargetPath(curNode, targetNodes, ctx);
+ }
+ } else {
+ // TODO: handle in linker.
+ }
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BaseFileListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BaseFileListener.java
new file mode 100644
index 0000000..8ba4d02
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BaseFileListener.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.YANGBASE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_CHILD;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ANTLR grammar rule
+ * yangfile : module_stmt
+ * | submodule_stmt;
+ */
+
+/**
+ * Representation of call back function corresponding to the "base rule" defined in
+ * ANTLR grammar file.
+ */
+public final class BaseFileListener {
+
+ /**
+ * Creates a new base listener.
+ */
+ private BaseFileListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (yangfile), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processYangFileEntry(TreeWalkListener listener, GeneratedYangParser.YangfileContext ctx) {
+
+ // Check if stack is empty.
+ checkStackIsEmpty(listener, INVALID_HOLDER, YANGBASE_DATA, "", ENTRY);
+
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (yangfile), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processYangFileExit(TreeWalkListener listener, GeneratedYangParser.YangfileContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, YANGBASE_DATA, "", EXIT);
+
+ // Data Model tree root node is set.
+ if (listener.getParsedDataStack().peek() instanceof YangModule
+ || listener.getParsedDataStack().peek() instanceof YangSubModule) {
+ listener.setRootNode((YangNode) listener.getParsedDataStack().pop());
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_CHILD, YANGBASE_DATA, "", EXIT));
+ }
+
+ // Check if stack is empty.
+ checkStackIsEmpty(listener, INVALID_HOLDER, YANGBASE_DATA, "", EXIT);
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BelongsToListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BelongsToListener.java
new file mode 100644
index 0000000..ab12d46
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BelongsToListener.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangBelongsTo;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.BELONGS_TO_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * submodule-header-stmts =
+ * ;; these stmts can appear in any order
+ * [yang-version-stmt stmtsep]
+ * belongs-to-stmt stmtsep
+ *
+ * belongs-to-stmt = belongs-to-keyword sep identifier-arg-str
+ * optsep
+ * "{" stmtsep
+ * prefix-stmt stmtsep
+ * "}"
+ *
+ * ANTLR grammar rule
+ * submodule_header_statement : yang_version_stmt? belongs_to_stmt
+ * | belongs_to_stmt yang_version_stmt?
+ * ;
+ * belongs_to_stmt : BELONGS_TO_KEYWORD identifier LEFT_CURLY_BRACE belongs_to_stmt_body RIGHT_CURLY_BRACE;
+ * belongs_to_stmt_body : prefix_stmt;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "belongs to" rule defined in ANTLR grammar file for corresponding ABNF rule
+ * in RFC 6020.
+ */
+public final class BelongsToListener {
+
+ /**
+ * Creates a new belongto listener.
+ */
+ private BelongsToListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (belongsto), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processBelongsToEntry(TreeWalkListener listener,
+ GeneratedYangParser.BelongstoStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BELONGS_TO_DATA, ctx.identifier().getText(),
+ ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), BELONGS_TO_DATA, ctx);
+
+ YangBelongsTo belongstoNode = new YangBelongsTo();
+ belongstoNode.setBelongsToModuleName(identifier);
+
+ // Set the line number and character position in line for the belongs to.
+ int errorLine = ctx.getStart().getLine();
+ int errorPosition = ctx.getStart().getCharPositionInLine();
+ belongstoNode.setLineNumber(errorLine);
+ belongstoNode.setCharPosition(errorPosition);
+
+ // Push belongsto into the stack.
+ listener.getParsedDataStack().push(belongstoNode);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (belongsto), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processBelongsToExit(TreeWalkListener listener,
+ GeneratedYangParser.BelongstoStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BELONGS_TO_DATA, ctx.identifier().getText(),
+ EXIT);
+
+ Parsable tmpBelongstoNode = listener.getParsedDataStack().peek();
+ if (tmpBelongstoNode instanceof YangBelongsTo) {
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BELONGS_TO_DATA,
+ ctx.identifier().getText(), EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case SUB_MODULE_DATA: {
+ YangSubModule subModule = (YangSubModule) tmpNode;
+ subModule.setBelongsTo((YangBelongsTo) tmpBelongstoNode);
+ subModule.setPrefix(subModule.getBelongsTo().getPrefix());
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, BELONGS_TO_DATA,
+ ctx.identifier().getText(),
+ EXIT));
+ }
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, BELONGS_TO_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BitListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BitListener.java
new file mode 100644
index 0000000..39084e0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BitListener.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * bit-stmt = bit-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [position-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ * "}")
+ *
+ * ANTLR grammar rule
+ * bitStatement : BIT_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE bitBodyStatement RIGHT_CURLY_BRACE);
+ *
+ * bitBodyStatement : positionStatement? statusStatement? descriptionStatement? referenceStatement?
+ * | positionStatement? statusStatement? referenceStatement? descriptionStatement?
+ * | positionStatement? descriptionStatement? statusStatement? referenceStatement?
+ * | positionStatement? descriptionStatement? referenceStatement? statusStatement?
+ * | positionStatement? referenceStatement? statusStatement? descriptionStatement?
+ * | positionStatement? referenceStatement? descriptionStatement? statusStatement?
+ * | statusStatement? positionStatement? descriptionStatement? referenceStatement?
+ * | statusStatement? positionStatement? referenceStatement? descriptionStatement?
+ * | statusStatement? descriptionStatement? descriptionStatement? positionStatement?
+ * | statusStatement? descriptionStatement? positionStatement? descriptionStatement?
+ * | statusStatement? referenceStatement? positionStatement? descriptionStatement?
+ * | statusStatement? referenceStatement? descriptionStatement? positionStatement?
+ * | descriptionStatement? positionStatement? statusStatement? referenceStatement?
+ * | descriptionStatement? positionStatement? referenceStatement? statusStatement?
+ * | descriptionStatement? statusStatement? positionStatement? referenceStatement?
+ * | descriptionStatement? statusStatement? referenceStatement? positionStatement?
+ * | descriptionStatement? referenceStatement? positionStatement? statusStatement?
+ * | descriptionStatement? referenceStatement? statusStatement? positionStatement?
+ * | referenceStatement? positionStatement? descriptionStatement? statusStatement?
+ * | referenceStatement? positionStatement? statusStatement? descriptionStatement?
+ * | referenceStatement? statusStatement? descriptionStatement? positionStatement?
+ * | referenceStatement? statusStatement? positionStatement? descriptionStatement?
+ * | referenceStatement? descriptionStatement? positionStatement? statusStatement?
+ * | referenceStatement? descriptionStatement? statusStatement? positionStatement?
+ * ;
+ */
+
+import org.onosproject.yangutils.datamodel.YangBit;
+import org.onosproject.yangutils.datamodel.YangBits;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.BIT_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_CONTENT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/**
+ * Represents listener based call back function corresponding to the "bit"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class BitListener {
+
+ /**
+ * Creates a new bit listener.
+ */
+ private BitListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (bit), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processBitEntry(TreeWalkListener listener,
+ GeneratedYangParser.BitStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BIT_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), BIT_DATA, ctx);
+
+ YangBit bitNode = new YangBit();
+ bitNode.setBitName(identifier);
+ listener.getParsedDataStack().push(bitNode);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (bit), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processBitExit(TreeWalkListener listener,
+ GeneratedYangParser.BitStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BIT_DATA, ctx.identifier().getText(), EXIT);
+
+ Parsable tmpBitNode = listener.getParsedDataStack().peek();
+ if (tmpBitNode instanceof YangBit) {
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BIT_DATA, ctx.identifier().getText(), EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case BITS_DATA: {
+ YangBits yangBits = (YangBits) tmpNode;
+ if (ctx.bitBodyStatement() == null || ctx.bitBodyStatement().positionStatement() == null) {
+ int maxPosition = 0;
+ boolean isPositionPresent = false;
+
+ for (YangBit curBit : yangBits.getBitSet()) {
+ if (maxPosition <= curBit.getPosition()) {
+ maxPosition = curBit.getPosition();
+ isPositionPresent = true;
+ }
+ }
+ if (isPositionPresent) {
+ maxPosition++;
+ }
+ ((YangBit) tmpBitNode).setPosition(maxPosition);
+ }
+ try {
+ yangBits.addBitInfo((YangBit) tmpBitNode);
+ } catch (DataModelException e) {
+ ParserException parserException = new ParserException(constructExtendedListenerErrorMessage(
+ INVALID_CONTENT, BIT_DATA, ctx.identifier().getText(), EXIT, e.getMessage()));
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ break;
+ }
+ default:
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, BIT_DATA, ctx.identifier().getText(), EXIT));
+ }
+ } else {
+ throw new ParserException(
+ constructListenerErrorMessage(MISSING_CURRENT_HOLDER, BIT_DATA, ctx.identifier().getText(), EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BitsListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BitsListener.java
new file mode 100644
index 0000000..c53a516
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/BitsListener.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * type-body-stmts = numerical-restrictions /
+ * decimal64-specification /
+ * string-restrictions /
+ * enum-specification /
+ * leafref-specification /
+ * identityref-specification /
+ * instance-identifier-specification /
+ * bits-specification /
+ * union-specification
+ *
+ * bits-specification = 1*(bit-stmt stmtsep)
+ *
+ * ANTLR grammar rule
+ *
+ * typeBodyStatements : numericalRestrictions | stringRestrictions | enumSpecification
+ * | leafrefSpecification | identityrefSpecification | instanceIdentifierSpecification
+ * | bitsSpecification | unionSpecification;
+ *
+ * bitsSpecification : bitStatement+;
+ */
+
+import org.onosproject.yangutils.datamodel.YangBits;
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.YangUnion;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.BITS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/**
+ * Represents listener based call back function corresponding to the "bits" rule
+ * defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class BitsListener {
+
+ /**
+ * Creates a new bits listener.
+ */
+ private BitsListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (bits), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processBitsEntry(TreeWalkListener listener,
+ GeneratedYangParser.BitsSpecificationContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BITS_DATA, "", ENTRY);
+
+ if (listener.getParsedDataStack().peek() instanceof YangType) {
+ YangBits bitsNode = new YangBits();
+ Parsable typeData = listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BITS_DATA, "", ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+
+ switch (tmpData.getYangConstructType()) {
+ case LEAF_DATA:
+ bitsNode.setBitsName(((YangLeaf) tmpData).getName());
+ break;
+ case LEAF_LIST_DATA:
+ bitsNode.setBitsName(((YangLeafList) tmpData).getName());
+ break;
+ case TYPEDEF_DATA:
+ bitsNode.setBitsName(((YangTypeDef) tmpData).getName());
+ break;
+ case UNION_DATA:
+ bitsNode.setBitsName(((YangUnion) tmpData).getName());
+ break;
+ // TODO typedef, union, deviate.
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, TYPE_DATA,
+ ((YangType<?>) typeData).getDataTypeName(), ENTRY));
+ }
+ listener.getParsedDataStack().push(typeData);
+ listener.getParsedDataStack().push(bitsNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, BITS_DATA, "", ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (bits), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processBitsExit(TreeWalkListener listener,
+ GeneratedYangParser.BitsSpecificationContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BITS_DATA, "", EXIT);
+
+ Parsable tmpBitsNode = listener.getParsedDataStack().peek();
+ if (tmpBitsNode instanceof YangBits) {
+ YangBits bitsNode = (YangBits) tmpBitsNode;
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, BITS_DATA, "", EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case TYPE_DATA: {
+ YangType<YangBits> typeNode = (YangType<YangBits>) tmpNode;
+ typeNode.setDataTypeExtendedInfo(bitsNode);
+ break;
+ }
+ default:
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, BITS_DATA, "", EXIT));
+ }
+ } else {
+ throw new ParserException(
+ constructListenerErrorMessage(MISSING_CURRENT_HOLDER, BITS_DATA, "", EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/CaseListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/CaseListener.java
new file mode 100644
index 0000000..5aa1dcd
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/CaseListener.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangChoice;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CASE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.WHEN_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangCaseNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * case-stmt = case-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *(data-def-stmt stmtsep)
+ * "}")
+ *
+ * ANTLR grammar rule
+ * caseStatement : CASE_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement
+ * | statusStatement | descriptionStatement | referenceStatement | dataDefStatement)* RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "case" rule
+ * defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class CaseListener {
+
+ /**
+ * Create a new case listener.
+ */
+ private CaseListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (case), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processCaseEntry(TreeWalkListener listener,
+ GeneratedYangParser.CaseStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, CASE_DATA, ctx.identifier().getText(), ENTRY);
+
+ // Check validity of identifier and remove double quotes.
+ String identifier = getValidIdentifier(ctx.identifier().getText(), CASE_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, CASE_DATA);
+
+ if (curData instanceof YangChoice) {
+ YangCase caseNode = getYangCaseNode(JAVA_GENERATION);
+ caseNode.setName(identifier);
+ YangNode curNode = (YangNode) curData;
+ try {
+ curNode.addChild(caseNode);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ CASE_DATA, ctx.identifier().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(caseNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, CASE_DATA,
+ ctx.identifier().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (case), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processCaseExit(TreeWalkListener listener,
+ GeneratedYangParser.CaseStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, CASE_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangCase) {
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, CASE_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of case sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.CaseStatementContext ctx) {
+
+ validateCardinalityMaxOne(ctx.whenStatement(), WHEN_DATA, CASE_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, CASE_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, CASE_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, CASE_DATA, ctx.identifier().getText());
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ChoiceListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ChoiceListener.java
new file mode 100644
index 0000000..61c2df1
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ChoiceListener.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangAugment;
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangChoice;
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CASE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CHOICE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONFIG_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DEFAULT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MANDATORY_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.SHORT_CASE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.WHEN_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateMutuallyExclusiveChilds;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangChoiceNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * choice-stmt = choice-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * [default-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((short-case-stmt / case-stmt) stmtsep)
+ * "}")
+ *
+ * ANTLR grammar rule
+ * choiceStatement : CHOICE_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement
+ * | defaultStatement | configStatement | mandatoryStatement | statusStatement | descriptionStatement
+ * | referenceStatement | shortCaseStatement | caseStatement)* RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "choice"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ChoiceListener {
+
+ /**
+ * Create a new choice listener.
+ */
+ private ChoiceListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (choice), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processChoiceEntry(TreeWalkListener listener,
+ GeneratedYangParser.ChoiceStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, CHOICE_DATA, ctx.identifier().getText(), ENTRY);
+
+ // Check validity of identifier and remove double quotes.
+ String identifier = getValidIdentifier(ctx.identifier().getText(), CHOICE_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, CHOICE_DATA);
+
+ if (curData instanceof YangModule || curData instanceof YangSubModule || curData instanceof YangContainer
+ || curData instanceof YangList || curData instanceof YangCase || curData instanceof YangGrouping
+ || curData instanceof YangAugment || curData instanceof YangInput || curData instanceof YangOutput
+ || curData instanceof YangNotification) {
+
+ YangChoice choiceNode = getYangChoiceNode(JAVA_GENERATION);
+ choiceNode.setName(identifier);
+
+ YangNode curNode = (YangNode) curData;
+ try {
+ curNode.addChild(choiceNode);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ CHOICE_DATA, ctx.identifier().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(choiceNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER,
+ CHOICE_DATA, ctx.identifier().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (choice), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processChoiceExit(TreeWalkListener listener,
+ GeneratedYangParser.ChoiceStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, CHOICE_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangChoice) {
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, CHOICE_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of choice sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule.
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.ChoiceStatementContext ctx) {
+
+ validateCardinalityMaxOne(ctx.whenStatement(), WHEN_DATA, CHOICE_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.defaultStatement(), DEFAULT_DATA, CHOICE_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.configStatement(), CONFIG_DATA, CHOICE_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.mandatoryStatement(), MANDATORY_DATA, CHOICE_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, CHOICE_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, CHOICE_DATA,
+ ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, CHOICE_DATA, ctx.identifier().getText());
+ validateMutuallyExclusiveChilds(ctx.shortCaseStatement(), SHORT_CASE_DATA, ctx.caseStatement(), CASE_DATA,
+ CHOICE_DATA, ctx.identifier().getText());
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ConfigListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ConfigListener.java
new file mode 100644
index 0000000..d595cb0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ConfigListener.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONFIG_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidBooleanValue;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * config-stmt = config-keyword sep
+ * config-arg-str stmtend
+ * config-arg-str = < a string that matches the rule
+ * config-arg >
+ * config-arg = true-keyword / false-keyword
+ *
+ * ANTLR grammar rule
+ * configStatement : CONFIG_KEYWORD config STMTEND;
+ * config : string;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "config"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ConfigListener {
+
+ /**
+ * Creates a new config listener.
+ */
+ private ConfigListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (config), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processConfigEntry(TreeWalkListener listener,
+ GeneratedYangParser.ConfigStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, CONFIG_DATA, "", ENTRY);
+
+ boolean isConfig = getValidBooleanValue(ctx.config().getText(), CONFIG_DATA, ctx);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ switch (tmpData.getYangConstructType()) {
+ case LEAF_DATA:
+ YangLeaf leaf = (YangLeaf) tmpData;
+ leaf.setConfig(isConfig);
+ break;
+ case CONTAINER_DATA:
+ YangContainer container = (YangContainer) tmpData;
+ container.setConfig(isConfig);
+ break;
+ case LEAF_LIST_DATA:
+ YangLeafList leafList = (YangLeafList) tmpData;
+ leafList.setConfig(isConfig);
+ break;
+ case LIST_DATA:
+ YangList yangList = (YangList) tmpData;
+ yangList.setConfig(isConfig);
+ break;
+ case CHOICE_DATA: // TODO
+ break;
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, CONFIG_DATA, "", ENTRY));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ContactListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ContactListener.java
new file mode 100644
index 0000000..4cab95d
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ContactListener.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONTACT_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * meta-stmts = ;; these stmts can appear in any order
+ * [organization-stmt stmtsep]
+ * [contact-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * contact-stmt = contact-keyword sep string optsep stmtend
+ *
+ * ANTLR grammar rule
+ * meta_stmts : organization_stmt? contact_stmt? description_stmt? reference_stmt?
+ * | organization_stmt? contact_stmt? reference_stmt? description_stmt?
+ * | organization_stmt? description_stmt? contact_stmt? reference_stmt?
+ * | organization_stmt? description_stmt? reference_stmt? contact_stmt?
+ * | organization_stmt? reference_stmt? contact_stmt? description_stmt?
+ * | organization_stmt? reference_stmt? description_stmt? contact_stmt?
+ * | contact_stmt? organization_stmt? description_stmt? reference_stmt?
+ * | contact_stmt? organization_stmt? reference_stmt? description_stmt?
+ * | contact_stmt? reference_stmt? organization_stmt? description_stmt?
+ * | contact_stmt? reference_stmt? description_stmt? organization_stmt?
+ * | contact_stmt? description_stmt? reference_stmt? organization_stmt?
+ * | contact_stmt? description_stmt? organization_stmt? reference_stmt?
+ * | reference_stmt? contact_stmt? organization_stmt? description_stmt?
+ * | reference_stmt? contact_stmt? description_stmt? organization_stmt?
+ * | reference_stmt? organization_stmt? contact_stmt? description_stmt?
+ * | reference_stmt? organization_stmt? description_stmt? contact_stmt?
+ * | reference_stmt? description_stmt? organization_stmt? contact_stmt?
+ * | reference_stmt? description_stmt? contact_stmt? organization_stmt?
+ * | description_stmt? reference_stmt? contact_stmt? organization_stmt?
+ * | description_stmt? reference_stmt? organization_stmt? contact_stmt?
+ * | description_stmt? contact_stmt? reference_stmt? organization_stmt?
+ * | description_stmt? contact_stmt? organization_stmt? reference_stmt?
+ * | description_stmt? organization_stmt? contact_stmt? reference_stmt?
+ * | description_stmt? organization_stmt? reference_stmt? contact_stmt?
+ * ;
+ * contact_stmt : CONTACT_KEYWORD string STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "contact"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ContactListener {
+
+ /**
+ * Creates a new contact listener.
+ */
+ private ContactListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (contact), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processContactEntry(TreeWalkListener listener, GeneratedYangParser.ContactStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, CONTACT_DATA, ctx.string().getText(), ENTRY);
+
+ // Obtain the node of the stack.
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case MODULE_DATA: {
+ YangModule module = (YangModule) tmpNode;
+ module.setContact(ctx.string().getText());
+ break;
+ }
+ case SUB_MODULE_DATA: {
+ YangSubModule subModule = (YangSubModule) tmpNode;
+ subModule.setContact(ctx.string().getText());
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, CONTACT_DATA,
+ ctx.string().getText(), ENTRY));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ContainerListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ContainerListener.java
new file mode 100644
index 0000000..9ed3e76
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ContainerListener.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangAugment;
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+import org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONFIG_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONTAINER_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.PRESENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangContainerNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * container-stmt = container-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * *(must-stmt stmtsep)
+ * [presence-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * *(data-def-stmt stmtsep)
+ * "}")
+ *
+ * ANTLR grammar rule
+ * containerStatement : CONTAINER_KEYWORD identifier
+ * (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | mustStatement |
+ * presenceStatement | configStatement | statusStatement | descriptionStatement |
+ * referenceStatement | typedefStatement | groupingStatement
+ * | dataDefStatement)* RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "container"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ContainerListener {
+
+ /**
+ * Creates a new container listener.
+ */
+ private ContainerListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (container), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processContainerEntry(TreeWalkListener listener,
+ GeneratedYangParser.ContainerStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, CONTAINER_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), CONTAINER_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, CONTAINER_DATA);
+
+ YangContainer container = getYangContainerNode(JAVA_GENERATION);
+ container.setName(identifier);
+
+ /*
+ * If "config" is not specified, the default is the same as the parent
+ * schema node's "config" value.
+ */
+ if (ctx.configStatement().isEmpty()) {
+ boolean parentConfig = ListenerValidation.getParentNodeConfig(listener);
+ container.setConfig(parentConfig);
+ }
+
+ Parsable curData = listener.getParsedDataStack().peek();
+ if (curData instanceof YangModule || curData instanceof YangSubModule
+ || curData instanceof YangContainer || curData instanceof YangList
+ || curData instanceof YangCase || curData instanceof YangNotification
+ || curData instanceof YangInput || curData instanceof YangOutput
+ || curData instanceof YangAugment || curData instanceof YangGrouping) {
+ YangNode curNode = (YangNode) curData;
+ try {
+ curNode.addChild(container);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ CONTAINER_DATA, ctx.identifier().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(container);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, CONTAINER_DATA,
+ ctx.identifier().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (container), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processContainerExit(TreeWalkListener listener,
+ GeneratedYangParser.ContainerStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, CONTAINER_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangContainer) {
+ YangContainer yangContainer = (YangContainer) listener.getParsedDataStack().peek();
+ try {
+ yangContainer.validateDataOnExit();
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ CONTAINER_DATA, ctx.identifier().getText(), EXIT, e.getMessage()));
+ }
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, CONTAINER_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of container sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.ContainerStatementContext ctx) {
+
+ validateCardinalityMaxOne(ctx.presenceStatement(), PRESENCE_DATA, CONTAINER_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.configStatement(), CONFIG_DATA, CONTAINER_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, CONTAINER_DATA,
+ ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, CONTAINER_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, CONTAINER_DATA, ctx.identifier().getText());
+ // TODO validate 'when' cardinality
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/DefaultListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/DefaultListener.java
new file mode 100644
index 0000000..e07895f
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/DefaultListener.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * typedef-stmt = typedef-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * type-stmt stmtsep
+ * [units-stmt stmtsep]
+ * [default-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ * default-stmt = default-keyword sep string stmtend
+
+ *
+ * ANTLR grammar rule
+ * typedefStatement : TYPEDEF_KEYWORD IDENTIFIER LEFT_CURLY_BRACE
+ * (typeStatement | unitsStatement | defaultStatement | statusStatement
+ * | descriptionStatement | referenceStatement)* RIGHT_CURLY_BRACE;
+ * defaultStatement : DEFAULT_KEYWORD string STMTEND;
+ */
+
+import org.onosproject.yangutils.datamodel.YangChoice;
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DEFAULT_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/**
+ * Represents listener for default YANG statement.
+ */
+public final class DefaultListener {
+
+ /**
+ * Creates a new default listener.
+ */
+ private DefaultListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (default), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processDefaultEntry(TreeWalkListener listener,
+ GeneratedYangParser.DefaultStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, DEFAULT_DATA, ctx.string().getText(), ENTRY);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case TYPEDEF_DATA: {
+ YangTypeDef typeDef = (YangTypeDef) tmpNode;
+ typeDef.setDefaultValueInString(ctx.string().getText());
+ break;
+ }
+ case LEAF_DATA: {
+ YangLeaf leaf = (YangLeaf) tmpNode;
+ leaf.setDefaultValueInString(ctx.string().getText());
+ break;
+ }
+ case CHOICE_DATA: {
+ YangChoice choice = (YangChoice) tmpNode;
+ choice.setDefaultValueInString(ctx.string().getText());
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER,
+ DEFAULT_DATA, ctx.string().getText(), ENTRY));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/DescriptionListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/DescriptionListener.java
new file mode 100644
index 0000000..c7988a8
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/DescriptionListener.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangDesc;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * description-stmt = description-keyword sep string optsep stmtend
+ *
+ * ANTLR grammar rule
+ * descriptionStatement : DESCRIPTION_KEYWORD string STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "description" rule defined in ANTLR grammar file for corresponding ABNF rule
+ * in RFC 6020.
+ */
+public final class DescriptionListener {
+
+ /**
+ * Creates a new description listener.
+ */
+ private DescriptionListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (description), perform validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processDescriptionEntry(TreeWalkListener listener,
+ GeneratedYangParser.DescriptionStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, DESCRIPTION_DATA, ctx.string().getText(), ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData instanceof YangDesc) {
+ YangDesc description = (YangDesc) tmpData;
+ description.setDescription(ctx.string().getText());
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, DESCRIPTION_DATA,
+ ctx.string().getText(), ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/EnumListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/EnumListener.java
new file mode 100644
index 0000000..9cfc5aa
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/EnumListener.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * enum-stmt = enum-keyword sep string optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [value-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ *
+ * ANTLR grammar rule
+ * enumStatement : ENUM_KEYWORD string (STMTEND | LEFT_CURLY_BRACE enumStatementBody RIGHT_CURLY_BRACE);
+ *
+ * enumStatementBody : valueStatement? statusStatement? descriptionStatement? referenceStatement?
+ * | valueStatement? statusStatement? referenceStatement? descriptionStatement?
+ * | valueStatement? descriptionStatement? statusStatement? referenceStatement?
+ * | valueStatement? descriptionStatement? referenceStatement? statusStatement?
+ * | valueStatement? referenceStatement? statusStatement? descriptionStatement?
+ * | valueStatement? referenceStatement? descriptionStatement? statusStatement?
+ * | statusStatement? valueStatement? descriptionStatement? referenceStatement?
+ * | statusStatement? valueStatement? referenceStatement? descriptionStatement?
+ * | statusStatement? descriptionStatement? descriptionStatement? valueStatement?
+ * | statusStatement? descriptionStatement? valueStatement? descriptionStatement?
+ * | statusStatement? referenceStatement? valueStatement? descriptionStatement?
+ * | statusStatement? referenceStatement? descriptionStatement? valueStatement?
+ * | descriptionStatement? valueStatement? statusStatement? referenceStatement?
+ * | descriptionStatement? valueStatement? referenceStatement? statusStatement?
+ * | descriptionStatement? statusStatement? valueStatement? referenceStatement?
+ * | descriptionStatement? statusStatement? referenceStatement? valueStatement?
+ * | descriptionStatement? referenceStatement? valueStatement? statusStatement?
+ * | descriptionStatement? referenceStatement? statusStatement? valueStatement?
+ * | referenceStatement? valueStatement? descriptionStatement? statusStatement?
+ * | referenceStatement? valueStatement? statusStatement? descriptionStatement?
+ * | referenceStatement? statusStatement? descriptionStatement? valueStatement?
+ * | referenceStatement? statusStatement? valueStatement? descriptionStatement?
+ * | referenceStatement? descriptionStatement? valueStatement? statusStatement?
+ * | referenceStatement? descriptionStatement? statusStatement? valueStatement?
+ * ;
+ */
+
+import org.onosproject.yangutils.datamodel.YangEnum;
+import org.onosproject.yangutils.datamodel.YangEnumeration;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.ENUM_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.DUPLICATE_ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.utils.UtilConstants.QUOTES;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+
+/**
+ * Represents listener based call back function corresponding to the "enum" rule
+ * defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class EnumListener {
+
+ /**
+ * Creates a new enum listener.
+ */
+ private EnumListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (enum), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processEnumEntry(TreeWalkListener listener, GeneratedYangParser.EnumStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, ENUM_DATA, ctx.string().getText(), ENTRY);
+
+ YangEnum enumNode = new YangEnum();
+ enumNode.setNamedValue(getValidNamedValue(ctx.string().getText()));
+ listener.getParsedDataStack().push(enumNode);
+ }
+
+ /*Removes quotes from the enum name if present.*/
+ private static String getValidNamedValue(String name) {
+ if (name.contains(QUOTES)) {
+ name = name.replace(QUOTES, EMPTY_STRING);
+ }
+ return name;
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (enum), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processEnumExit(TreeWalkListener listener, GeneratedYangParser.EnumStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, ENUM_DATA, ctx.string().getText(), EXIT);
+
+ Parsable tmpEnumNode = listener.getParsedDataStack().peek();
+ if (tmpEnumNode instanceof YangEnum) {
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, ENUM_DATA, ctx.string().getText(), EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case ENUMERATION_DATA: {
+ YangEnumeration yangEnumeration = (YangEnumeration) tmpNode;
+ if (ctx.enumStatementBody() == null || ctx.enumStatementBody().valueStatement() == null) {
+ int maxValue = 0;
+ boolean isValuePresent = false;
+
+ for (YangEnum curEnum : yangEnumeration.getEnumSet()) {
+ if (curEnum.getValue() == Integer.MAX_VALUE) {
+ ParserException parserException = new ParserException("YANG file error : "
+ + "An enum value MUST be specified for enum substatements following the one"
+ + "with the current highest value");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ } else if (maxValue <= curEnum.getValue()) {
+ maxValue = curEnum.getValue();
+ isValuePresent = true;
+ }
+ }
+ if (isValuePresent) {
+ maxValue++;
+ }
+ ((YangEnum) tmpEnumNode).setValue(maxValue);
+ }
+ try {
+ yangEnumeration.addEnumInfo((YangEnum) tmpEnumNode);
+ } catch (DataModelException e) {
+ ParserException parserException = new ParserException(constructExtendedListenerErrorMessage(
+ DUPLICATE_ENTRY, ENUM_DATA, ctx.string().getText(), EXIT, e.getMessage()));
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ break;
+ }
+ default:
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, ENUM_DATA, ctx.string().getText(), EXIT));
+ }
+ } else {
+ throw new ParserException(
+ constructListenerErrorMessage(MISSING_CURRENT_HOLDER, ENUM_DATA, ctx.string().getText(), EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/EnumerationListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/EnumerationListener.java
new file mode 100644
index 0000000..2db40f3
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/EnumerationListener.java
@@ -0,0 +1,225 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * type-body-stmts = numerical-restrictions /
+ * decimal64-specification /
+ * string-restrictions /
+ * enum-specification /
+ * leafref-specification /
+ * identityref-specification /
+ * instance-identifier-specification /
+ * bits-specification /
+ * union-specification
+ *
+ * enum-specification = 1*(enum-stmt stmtsep)
+ *
+ * ANTLR grammar rule
+ *
+ * typeBodyStatements : numericalRestrictions | stringRestrictions | enumSpecification
+ * | leafrefSpecification | identityrefSpecification | instanceIdentifierSpecification
+ * | bitsSpecification | unionSpecification;
+ *
+ * enumSpecification : enumStatement+;
+ */
+
+import org.onosproject.yangutils.datamodel.YangEnumeration;
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.YangUnion;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.ENUMERATION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangEnumerationNode;
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "enumeration" rule defined in ANTLR grammar file for corresponding ABNF rule
+ * in RFC 6020.
+ */
+public final class EnumerationListener {
+
+ /**
+ * Suffix to be used while creating enumeration class.
+ */
+ private static final String ENUMERATION_CLASS_SUFFIX = "_enum";
+
+ /**
+ * Creates a new enumeration listener.
+ */
+ private EnumerationListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (enumeration), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processEnumerationEntry(TreeWalkListener listener,
+ GeneratedYangParser.EnumSpecificationContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, ENUMERATION_DATA, "", ENTRY);
+
+ if (listener.getParsedDataStack().peek() instanceof YangType) {
+ YangEnumeration enumerationNode = getYangEnumerationNode(JAVA_GENERATION);
+ Parsable typeData = listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, ENUMERATION_DATA, "", ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+
+ switch (tmpData.getYangConstructType()) {
+ case LEAF_DATA:
+ // Set the name of enumeration same as leaf.
+ enumerationNode.setName(((YangLeaf) tmpData).getName() + ENUMERATION_CLASS_SUFFIX);
+ // Pop the stack entry to obtain the parent YANG node.
+ Parsable leaf = listener.getParsedDataStack().pop();
+ // Add the enumeration node to the parent holder of leaf.
+ addChildToParentNode(listener, enumerationNode);
+ // Push the popped entry back to the stack.
+ listener.getParsedDataStack().push(leaf);
+ break;
+ case LEAF_LIST_DATA:
+ // Set the name of enumeration same as leaf list.
+ enumerationNode.setName(((YangLeafList) tmpData).getName() + ENUMERATION_CLASS_SUFFIX);
+ // Pop the stack entry to obtain the parent YANG node.
+ Parsable leafList = listener.getParsedDataStack().pop();
+ // Add the enumeration node to the parent holder of leaf.
+ addChildToParentNode(listener, enumerationNode);
+ // Push the popped entry back to the stack.
+ listener.getParsedDataStack().push(leafList);
+ break;
+ case UNION_DATA:
+ YangUnion yangUnion = (YangUnion) tmpData;
+ /*
+ * In case parent of enumeration is a union, name of the
+ * enumeration is parent union name suffixed with running
+ * integer number, this is done because under union there
+ * could be multiple child union types.
+ */
+ enumerationNode.setName(yangUnion.getName() + ENUMERATION_CLASS_SUFFIX
+ + yangUnion.getChildUnionNumber());
+ // Increment the running number.
+ yangUnion.setChildUnionNumber(yangUnion.getChildUnionNumber() + 1);
+ // Add union as a child to parent union.
+ addChildToParentNode(listener, enumerationNode);
+ break;
+ case TYPEDEF_DATA:
+ YangTypeDef typeDef = (YangTypeDef) tmpData;
+ // Set the name of enumeration same as typedef name.
+ enumerationNode.setName(typeDef.getName() + ENUMERATION_CLASS_SUFFIX);
+ // Add enumeration as a child to parent type def.
+ addChildToParentNode(listener, enumerationNode);
+ break;
+ // TODO deviate.
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, TYPE_DATA,
+ ((YangType<?>) typeData).getDataTypeName(), ENTRY));
+ }
+ listener.getParsedDataStack().push(typeData);
+ listener.getParsedDataStack().push(enumerationNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, ENUMERATION_DATA, "", ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (enumeration), it
+ * perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processEnumerationExit(TreeWalkListener listener,
+ GeneratedYangParser.EnumSpecificationContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, ENUMERATION_DATA, "", EXIT);
+
+ Parsable tmpEnumerationNode = listener.getParsedDataStack().peek();
+ if (tmpEnumerationNode instanceof YangEnumeration) {
+ YangEnumeration enumerationNode = (YangEnumeration) tmpEnumerationNode;
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, ENUMERATION_DATA, "", EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case TYPE_DATA: {
+ YangType<YangEnumeration> typeNode = (YangType<YangEnumeration>) tmpNode;
+ typeNode.setDataTypeExtendedInfo(enumerationNode);
+ break;
+ }
+ default:
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, ENUMERATION_DATA, "", EXIT));
+ }
+ } else {
+ throw new ParserException(
+ constructListenerErrorMessage(MISSING_CURRENT_HOLDER, ENUMERATION_DATA, "", EXIT));
+ }
+ }
+
+ /**
+ * Adds the enumeration node to the parent holder.
+ *
+ * @param listener listener's object
+ * @param enumerationNode enumeration node which needs to be added to parent
+ */
+ private static void addChildToParentNode(TreeWalkListener listener, YangEnumeration enumerationNode) {
+ if (!(listener.getParsedDataStack().peek() instanceof YangNode)) {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, ENUMERATION_DATA,
+ "", ENTRY));
+ } else {
+ YangNode curNode = (YangNode) listener.getParsedDataStack().peek();
+ try {
+ curNode.addChild(enumerationNode);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ YangConstructType.ENUMERATION_DATA, "", ENTRY, e.getMessage()));
+ }
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/GroupingListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/GroupingListener.java
new file mode 100644
index 0000000..5171e2f
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/GroupingListener.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangRpc;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.GROUPING_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPEDEF_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateMutuallyExclusiveChilds;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangGroupingNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * grouping-stmt = grouping-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * *(data-def-stmt stmtsep)
+ * "}")
+ *
+ * ANTLR grammar rule
+ * groupingStatement : GROUPING_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE
+ * (statusStatement | descriptionStatement | referenceStatement | typedefStatement | groupingStatement
+ * | dataDefStatement)* RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "grouping"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class GroupingListener {
+
+ /**
+ * Creates a new grouping listener.
+ */
+ private GroupingListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (grouping), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processGroupingEntry(TreeWalkListener listener,
+ GeneratedYangParser.GroupingStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, GROUPING_DATA, ctx.identifier().getText(), ENTRY);
+
+ // Check validity of identifier and remove double quotes.
+ String identifier = getValidIdentifier(ctx.identifier().getText(), GROUPING_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, GROUPING_DATA);
+
+ if (curData instanceof YangModule || curData instanceof YangSubModule
+ || curData instanceof YangContainer || curData instanceof YangNotification
+ || curData instanceof YangList || curData instanceof YangGrouping
+ || curData instanceof YangRpc || curData instanceof YangInput
+ || curData instanceof YangOutput) {
+
+ YangGrouping groupingNode = getYangGroupingNode(JAVA_GENERATION);
+ groupingNode.setName(identifier);
+
+ YangNode curNode = (YangNode) curData;
+ try {
+ curNode.addChild(groupingNode);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ GROUPING_DATA, ctx.identifier().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(groupingNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER,
+ GROUPING_DATA, ctx.identifier().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (grouping), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processGroupingExit(TreeWalkListener listener,
+ GeneratedYangParser.GroupingStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, GROUPING_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangGrouping) {
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, GROUPING_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of case sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.GroupingStatementContext ctx) {
+
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, GROUPING_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, GROUPING_DATA,
+ ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, GROUPING_DATA, ctx.identifier().getText());
+ validateMutuallyExclusiveChilds(ctx.typedefStatement(), TYPEDEF_DATA, ctx.groupingStatement(), GROUPING_DATA,
+ GROUPING_DATA, ctx.identifier().getText());
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ImportListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ImportListener.java
new file mode 100644
index 0000000..76a2e30
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ImportListener.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangImport;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.IMPORT_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * linkage-stmts = ;; these stmts can appear in any order
+ * *(import-stmt stmtsep)
+ * *(include-stmt stmtsep)
+ *
+ * import-stmt = import-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * prefix-stmt stmtsep
+ * [revision-date-stmt stmtsep]
+ * "}"
+ *
+ * ANTLR grammar rule
+ * linkage_stmts : (import_stmt
+ * | include_stmt)*;
+ * import_stmt : IMPORT_KEYWORD identifier LEFT_CURLY_BRACE import_stmt_body
+ * RIGHT_CURLY_BRACE;
+ * import_stmt_body : prefix_stmt revision_date_stmt?;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "import"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ImportListener {
+
+ /**
+ * Creates a new import listener.
+ */
+ private ImportListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (import), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processImportEntry(TreeWalkListener listener, GeneratedYangParser.ImportStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, IMPORT_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), IMPORT_DATA, ctx);
+
+ YangImport importNode = new YangImport();
+ importNode.setModuleName(identifier);
+
+ // Set the line number and character position in line for the belongs to.
+ int errorLine = ctx.getStart().getLine();
+ int errorPosition = ctx.getStart().getCharPositionInLine();
+ importNode.setLineNumber(errorLine);
+ importNode.setCharPosition(errorPosition);
+
+ // Push import node to the stack.
+ listener.getParsedDataStack().push(importNode);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (import), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processImportExit(TreeWalkListener listener, GeneratedYangParser.ImportStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, IMPORT_DATA, ctx.identifier().getText(), EXIT);
+
+ Parsable tmpImportNode = listener.getParsedDataStack().peek();
+ if (tmpImportNode instanceof YangImport) {
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, IMPORT_DATA, ctx.identifier().getText(),
+ EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case MODULE_DATA: {
+ YangModule module = (YangModule) tmpNode;
+ module.addToImportList((YangImport) tmpImportNode);
+ break;
+ }
+ case SUB_MODULE_DATA: {
+ YangSubModule subModule = (YangSubModule) tmpNode;
+ subModule.addToImportList((YangImport) tmpImportNode);
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, IMPORT_DATA,
+ ctx.identifier().getText(),
+ EXIT));
+ }
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, IMPORT_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/IncludeListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/IncludeListener.java
new file mode 100644
index 0000000..847712f
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/IncludeListener.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangInclude;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.INCLUDE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * linkage-stmts = ;; these stmts can appear in any order
+ * *(import-stmt stmtsep)
+ * *(include-stmt stmtsep)
+ *
+ * include-stmt = include-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * [revision-date-stmt stmtsep]
+ * "}")
+ *
+ * ANTLR grammar rule
+ * linkage_stmts : (import_stmt
+ * | include_stmt)*;
+ * include_stmt : INCLUDE_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE
+ * revision_date_stmt? RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "include"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class IncludeListener {
+
+ /**
+ * Creates a new include listener.
+ */
+ private IncludeListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (include), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processIncludeEntry(TreeWalkListener listener, GeneratedYangParser.IncludeStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, INCLUDE_DATA, ctx.identifier().getText(),
+ ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), INCLUDE_DATA, ctx);
+
+ YangInclude includeNode = new YangInclude();
+ includeNode.setSubModuleName(identifier);
+
+ // Set the line number and character position in line for the belongs to.
+ int errorLine = ctx.getStart().getLine();
+ int errorPosition = ctx.getStart().getCharPositionInLine();
+ includeNode.setLineNumber(errorLine);
+ includeNode.setCharPosition(errorPosition);
+
+ listener.getParsedDataStack().push(includeNode);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (include), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processIncludeExit(TreeWalkListener listener, GeneratedYangParser.IncludeStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, INCLUDE_DATA, ctx.identifier().getText(), EXIT);
+
+ Parsable tmpIncludeNode = listener.getParsedDataStack().peek();
+ if (tmpIncludeNode instanceof YangInclude) {
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, INCLUDE_DATA, ctx.identifier().getText(),
+ EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case MODULE_DATA: {
+ YangModule module = (YangModule) tmpNode;
+ module.addToIncludeList((YangInclude) tmpIncludeNode);
+ break;
+ }
+ case SUB_MODULE_DATA: {
+ YangSubModule subModule = (YangSubModule) tmpNode;
+ subModule.addToIncludeList((YangInclude) tmpIncludeNode);
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, INCLUDE_DATA,
+ ctx.identifier().getText(),
+ EXIT));
+ }
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, INCLUDE_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/InputListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/InputListener.java
new file mode 100644
index 0000000..92e61f8
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/InputListener.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangRpc;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.INPUT_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangInputNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ *
+ * input-stmt = input-keyword optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * 1*(data-def-stmt stmtsep)
+ * "}"
+ *
+ * inputStatement : INPUT_KEYWORD LEFT_CURLY_BRACE inputStatementBody RIGHT_CURLY_BRACE;
+
+ * inputStatementBody : typedefStatement* dataDefStatement+
+ * | dataDefStatement+ typedefStatement*
+ * | groupingStatement* dataDefStatement+
+ * | dataDefStatement+ groupingStatement*;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "input"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class InputListener {
+
+ private static final String INPUT_KEYWORD = "_input";
+
+ /**
+ * Creates a new input listener.
+ */
+ private InputListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (input), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processInputEntry(TreeWalkListener listener,
+ GeneratedYangParser.InputStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, INPUT_DATA, "", ENTRY);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+ if (curData instanceof YangRpc) {
+
+ YangInput yangInput = getYangInputNode(JAVA_GENERATION);
+ yangInput.setName(((YangRpc) curData).getName() + INPUT_KEYWORD);
+ YangNode curNode = (YangNode) curData;
+ try {
+ curNode.addChild(yangInput);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ INPUT_DATA, "", ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(yangInput);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, INPUT_DATA,
+ "", ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (input), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processInputExit(TreeWalkListener listener,
+ GeneratedYangParser.InputStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, INPUT_DATA, "", EXIT);
+
+ if (!(listener.getParsedDataStack().peek() instanceof YangInput)) {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, INPUT_DATA,
+ "", EXIT));
+ }
+ listener.getParsedDataStack().pop();
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/KeyListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/KeyListener.java
new file mode 100644
index 0000000..889de0a
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/KeyListener.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.KEY_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.removeQuotesAndHandleConcat;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * key-stmt = key-keyword sep key-arg-str stmtend
+ *
+ * ANTLR grammar rule
+ * keyStatement : KEY_KEYWORD key STMTEND;
+ * key : string;
+ */
+
+/**
+ * Represesnts listener based call back function corresponding to the "key" rule
+ * defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class KeyListener {
+
+ /**
+ * Creates a new key listener.
+ */
+ private KeyListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (key), perform validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processKeyEntry(TreeWalkListener listener,
+ GeneratedYangParser.KeyStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, KEY_DATA, ctx.key().getText(), ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (listener.getParsedDataStack().peek() instanceof YangList) {
+ YangList yangList = (YangList) tmpData;
+ String tmpKeyValue = removeQuotesAndHandleConcat(ctx.key().getText());
+ if (tmpKeyValue.contains(" ")) {
+ String[] keyValues = tmpKeyValue.split(" ");
+ for (String keyValue : keyValues) {
+ try {
+ yangList.addKey(keyValue);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA, KEY_DATA,
+ ctx.key().getText(), ENTRY, e.getMessage()));
+ }
+ }
+ } else {
+ try {
+ yangList.addKey(tmpKeyValue);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA, KEY_DATA,
+ ctx.key().getText(), ENTRY, e.getMessage()));
+ }
+ }
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, KEY_DATA, ctx.key().getText(),
+ ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafListListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafListListener.java
new file mode 100644
index 0000000..6d3a97e
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafListListener.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangLeavesHolder;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONFIG_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.LEAF_LIST_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MAX_ELEMENT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MIN_ELEMENT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.UNITS_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityEqualsOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangLeafList;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * leaf-list-stmt = leaf-list-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * type-stmt stmtsep
+ * [units-stmt stmtsep]
+ * *(must-stmt stmtsep)
+ * [config-stmt stmtsep]
+ * [min-elements-stmt stmtsep]
+ * [max-elements-stmt stmtsep]
+ * [ordered-by-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ *
+ * ANTLR grammar rule
+ * leafListStatement : LEAF_LIST_KEYWORD identifier LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement |
+ * typeStatement | unitsStatement | mustStatement | configStatement | minElementsStatement | maxElementsStatement |
+ * orderedByStatement | statusStatement | descriptionStatement | referenceStatement)* RIGHT_CURLY_BRACE;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "leaf-list"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class LeafListListener {
+
+ /**
+ * Creates a new leaf list listener.
+ */
+ private LeafListListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (leaf-list), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processLeafListEntry(TreeWalkListener listener,
+ GeneratedYangParser.LeafListStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, LEAF_LIST_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), LEAF_LIST_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, LEAF_LIST_DATA);
+
+ YangLeafList leafList = getYangLeafList(JAVA_GENERATION);
+ leafList.setLeafName(identifier);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ YangLeavesHolder leavesHolder;
+
+ if (tmpData instanceof YangLeavesHolder) {
+ leavesHolder = (YangLeavesHolder) tmpData;
+ leavesHolder.addLeafList(leafList);
+ leafList.setContainedIn(leavesHolder);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LEAF_LIST_DATA,
+ ctx.identifier().getText(), ENTRY));
+ }
+ listener.getParsedDataStack().push(leafList);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (leaf-list), it performs
+ * validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processLeafListExit(TreeWalkListener listener,
+ GeneratedYangParser.LeafListStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, LEAF_LIST_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangLeafList) {
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, LEAF_LIST_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of leaf-list sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.LeafListStatementContext ctx) {
+
+ validateCardinalityEqualsOne(ctx.typeStatement(), TYPE_DATA, LEAF_LIST_DATA, ctx.identifier().getText(), ctx);
+ validateCardinalityMaxOne(ctx.unitsStatement(), UNITS_DATA, LEAF_LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.configStatement(), CONFIG_DATA, LEAF_LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.maxElementsStatement(), MAX_ELEMENT_DATA, LEAF_LIST_DATA,
+ ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.minElementsStatement(), MIN_ELEMENT_DATA, LEAF_LIST_DATA,
+ ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, LEAF_LIST_DATA,
+ ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, LEAF_LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, LEAF_LIST_DATA, ctx.identifier().getText());
+ //TODO ordered by
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafListener.java
new file mode 100644
index 0000000..7b5ac34
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafListener.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Implements listener based call back function corresponding to the "leaf"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeavesHolder;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONFIG_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.LEAF_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MANDATORY_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.UNITS_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityEqualsOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangLeaf;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * leaf-stmt = leaf-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * type-stmt stmtsep
+ * [units-stmt stmtsep]
+ * *(must-stmt stmtsep)
+ * [default-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ *
+ * ANTLR grammar rule
+ * leafStatement : LEAF_KEYWORD identifier LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | typeStatement |
+ * unitsStatement | mustStatement | defaultStatement | configStatement | mandatoryStatement | statusStatement |
+ * descriptionStatement | referenceStatement)* RIGHT_CURLY_BRACE;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "leaf" rule
+ * defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class LeafListener {
+
+ /**
+ * Creates a new leaf listener.
+ */
+ private LeafListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (leaf), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processLeafEntry(TreeWalkListener listener,
+ GeneratedYangParser.LeafStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, LEAF_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), LEAF_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, LEAF_DATA);
+
+ YangLeaf leaf = getYangLeaf(JAVA_GENERATION);
+ leaf.setLeafName(identifier);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ YangLeavesHolder leavesHolder;
+
+ if (tmpData instanceof YangLeavesHolder) {
+ leavesHolder = (YangLeavesHolder) tmpData;
+ leavesHolder.addLeaf(leaf);
+ leaf.setContainedIn(leavesHolder);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LEAF_DATA,
+ ctx.identifier().getText(), ENTRY));
+ }
+
+ listener.getParsedDataStack().push(leaf);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (leaf), performs
+ * validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processLeafExit(TreeWalkListener listener,
+ GeneratedYangParser.LeafStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, LEAF_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangLeaf) {
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, LEAF_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of leaf sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.LeafStatementContext ctx) {
+
+ validateCardinalityEqualsOne(ctx.typeStatement(), TYPE_DATA, LEAF_DATA, ctx.identifier().getText(), ctx);
+ validateCardinalityMaxOne(ctx.unitsStatement(), UNITS_DATA, LEAF_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.configStatement(), CONFIG_DATA, LEAF_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.mandatoryStatement(), MANDATORY_DATA, LEAF_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, LEAF_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, LEAF_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, LEAF_DATA, ctx.identifier().getText());
+ //TODO when.
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LengthRestrictionListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LengthRestrictionListener.java
new file mode 100644
index 0000000..bf8c6b0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LengthRestrictionListener.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangDerivedInfo;
+import org.onosproject.yangutils.datamodel.YangRangeRestriction;
+import org.onosproject.yangutils.datamodel.YangStringRestriction;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.YangDataTypes.BINARY;
+import static org.onosproject.yangutils.datamodel.YangDataTypes.DERIVED;
+import static org.onosproject.yangutils.datamodel.YangDataTypes.STRING;
+import static org.onosproject.yangutils.datamodel.utils.RestrictionResolver.processLengthRestriction;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.LENGTH_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * length-stmt = length-keyword sep length-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [error-message-stmt stmtsep]
+ * [error-app-tag-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ *
+ *
+ * ANTLR grammar rule
+ * lengthStatement : LENGTH_KEYWORD length
+ * (STMTEND | LEFT_CURLY_BRACE commonStatements RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "length"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class LengthRestrictionListener {
+
+ /**
+ * Creates a new length restriction listener.
+ */
+ private LengthRestrictionListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (length), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processLengthRestrictionEntry(TreeWalkListener listener,
+ GeneratedYangParser.LengthStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, LENGTH_DATA, ctx.length().getText(), ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData.getYangConstructType() == TYPE_DATA) {
+ YangType type = (YangType) tmpData;
+ setLengthRestriction(listener, type, ctx);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LENGTH_DATA,
+ ctx.length().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * Sets the length restriction to type.
+ *
+ * @param listener listener's object
+ * @param type Yang type for which length restriction to be set
+ * @param ctx context object of the grammar rule
+ */
+ private static void setLengthRestriction(TreeWalkListener listener, YangType type,
+ GeneratedYangParser.LengthStatementContext ctx) {
+
+ if (type.getDataType() == DERIVED) {
+ ((YangDerivedInfo<YangRangeRestriction>) type.getDataTypeExtendedInfo())
+ .setLengthRestrictionString(ctx.length().getText());
+ ((YangDerivedInfo<YangRangeRestriction>) type.getDataTypeExtendedInfo())
+ .setLineNumber(ctx.getStart().getLine());
+ ((YangDerivedInfo<YangRangeRestriction>) type.getDataTypeExtendedInfo())
+ .setCharPosition(ctx.getStart().getCharPositionInLine());
+ return;
+ }
+
+ if (type.getDataType() != STRING && type.getDataType() != BINARY) {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(LENGTH_DATA) + " name " + ctx.length().getText() +
+ " can be used to restrict the built-in type string/binary or types derived from string/binary.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ YangRangeRestriction lengthRestriction = null;
+ try {
+ lengthRestriction = processLengthRestriction(null, ctx.getStart().getLine(),
+ ctx.getStart().getCharPositionInLine(), false, ctx.length().getText());
+ } catch (DataModelException e) {
+ ParserException parserException = new ParserException(e.getMessage());
+ parserException.setCharPosition(e.getCharPositionInLine());
+ parserException.setLine(e.getLineNumber());
+ throw parserException;
+ }
+
+ if (type.getDataType() == STRING) {
+ YangStringRestriction stringRestriction = (YangStringRestriction) type.getDataTypeExtendedInfo();
+ if (stringRestriction == null) {
+ stringRestriction = new YangStringRestriction();
+ type.setDataTypeExtendedInfo(stringRestriction);
+ }
+
+ stringRestriction.setLengthRestriction(lengthRestriction);
+ } else {
+ type.setDataTypeExtendedInfo(lengthRestriction);
+ }
+
+ listener.getParsedDataStack().push(lengthRestriction);
+ }
+
+ /**
+ * Performs validation and updates the data model tree.
+ * It is called when parser exits from grammar rule (length).
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processLengthRestrictionExit(TreeWalkListener listener,
+ GeneratedYangParser.LengthStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, LENGTH_DATA, ctx.length().getText(), EXIT);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData instanceof YangRangeRestriction) {
+ listener.getParsedDataStack().pop();
+ } else if (tmpData instanceof YangType
+ && ((YangType) tmpData).getDataType() == DERIVED) {
+ // TODO : need to handle in linker
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, LENGTH_DATA,
+ ctx.length().getText(), EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ListListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ListListener.java
new file mode 100644
index 0000000..d0e7300
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ListListener.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangAugment;
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+import org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONFIG_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DATA_DEF_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.KEY_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.LIST_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MAX_ELEMENT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MIN_ELEMENT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityNonZero;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangListNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * list-stmt = list-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * *(must-stmt stmtsep)
+ * [key-stmt stmtsep]
+ * *(unique-stmt stmtsep)
+ * [config-stmt stmtsep]
+ * [min-elements-stmt stmtsep]
+ * [max-elements-stmt stmtsep]
+ * [ordered-by-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * 1*(data-def-stmt stmtsep)
+ * "}"
+ *
+ * ANTLR grammar rule
+ * listStatement : LIST_KEYWORD identifier LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | mustStatement |
+ * keyStatement | uniqueStatement | configStatement | minElementsStatement | maxElementsStatement |
+ * orderedByStatement | statusStatement | descriptionStatement | referenceStatement | typedefStatement |
+ * groupingStatement| dataDefStatement)* RIGHT_CURLY_BRACE;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "list" rule
+ * defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ListListener {
+
+ /**
+ * Creates a new list listener.
+ */
+ private ListListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (list), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processListEntry(TreeWalkListener listener,
+ GeneratedYangParser.ListStatementContext ctx) {
+
+ YangNode curNode;
+
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, LIST_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), LIST_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, LIST_DATA);
+
+ YangList yangList = getYangListNode(JAVA_GENERATION);
+ yangList.setName(identifier);
+
+ /*
+ * If "config" is not specified, the default is the same as the parent
+ * schema node's "config" value.
+ */
+ if (ctx.configStatement().isEmpty()) {
+ boolean parentConfig = ListenerValidation.getParentNodeConfig(listener);
+ yangList.setConfig(parentConfig);
+ }
+
+ Parsable curData = listener.getParsedDataStack().peek();
+ if (curData instanceof YangModule || curData instanceof YangContainer
+ || curData instanceof YangList || curData instanceof YangCase
+ || curData instanceof YangNotification || curData instanceof YangInput
+ || curData instanceof YangOutput || curData instanceof YangAugment
+ || curData instanceof YangGrouping || curData instanceof YangSubModule) {
+ curNode = (YangNode) curData;
+ try {
+ curNode.addChild(yangList);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ LIST_DATA, ctx.identifier().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(yangList);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LIST_DATA,
+ ctx.identifier().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (list), it performs
+ * validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processListExit(TreeWalkListener listener,
+ GeneratedYangParser.ListStatementContext ctx) {
+
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, LIST_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangList) {
+ YangList yangList = (YangList) listener.getParsedDataStack().peek();
+ try {
+ yangList.validateDataOnExit();
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ LIST_DATA, ctx.identifier().getText(), EXIT, e.getMessage()));
+ }
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, LIST_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of list sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.ListStatementContext ctx) {
+
+ validateCardinalityMaxOne(ctx.keyStatement(), KEY_DATA, LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.configStatement(), CONFIG_DATA, LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.maxElementsStatement(), MAX_ELEMENT_DATA, LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.minElementsStatement(), MIN_ELEMENT_DATA, LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, LIST_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, LIST_DATA, ctx.identifier().getText());
+ validateCardinalityNonZero(ctx.dataDefStatement(), DATA_DEF_DATA, LIST_DATA, ctx.identifier().getText(), ctx);
+ //TODO when, typedef, grouping, unique
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MandatoryListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MandatoryListener.java
new file mode 100644
index 0000000..b945f81
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MandatoryListener.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MANDATORY_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidBooleanValue;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * mandatory-stmt = mandatory-keyword sep
+ * mandatory-arg-str stmtend
+ *
+ * mandatory-arg-str = < a string that matches the rule
+ * mandatory-arg >
+ *
+ * mandatory-arg = true-keyword / false-keyword
+ *
+ * ANTLR grammar rule
+ * mandatoryStatement : MANDATORY_KEYWORD mandatory STMTEND;
+ * mandatory : string;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "mandatory"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class MandatoryListener {
+
+ /**
+ * Creates a new mandatory listener.
+ */
+ private MandatoryListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (mandatory), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processMandatoryEntry(TreeWalkListener listener,
+ GeneratedYangParser.MandatoryStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, MANDATORY_DATA, "", ENTRY);
+
+ boolean isMandatory = getValidBooleanValue(ctx.mandatory().getText(), MANDATORY_DATA, ctx);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case LEAF_DATA:
+ YangLeaf leaf = (YangLeaf) tmpNode;
+ leaf.setMandatory(isMandatory);
+ break;
+ case CHOICE_DATA: // TODO
+ break;
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, MANDATORY_DATA, "", ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MaxElementsListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MaxElementsListener.java
new file mode 100644
index 0000000..afb6dc3
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MaxElementsListener.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MAX_ELEMENT_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.removeQuotesAndHandleConcat;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * max-elements-stmt = max-elements-keyword sep
+ * max-value-arg-str stmtend
+ * max-value-arg-str = < a string that matches the rule
+ * max-value-arg >
+ *
+ * ANTLR grammar rule
+ * maxElementsStatement : MAX_ELEMENTS_KEYWORD maxValue STMTEND;
+ * maxValue : string;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "max-elements" rule defined in ANTLR grammar file for corresponding ABNF rule
+ * in RFC 6020.
+ */
+public final class MaxElementsListener {
+
+ private static final String POSITIVE_INTEGER_PATTERN = "[1-9][0-9]*";
+ private static final String UNBOUNDED_KEYWORD = "unbounded";
+
+ /**
+ * Creates a new max-elements listener.
+ */
+ private MaxElementsListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (max-elements), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processMaxElementsEntry(TreeWalkListener listener,
+ GeneratedYangParser.MaxElementsStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, MAX_ELEMENT_DATA, "", ENTRY);
+
+ int maxElementsValue = getValidMaxElementValue(ctx);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ switch (tmpData.getYangConstructType()) {
+ case LEAF_LIST_DATA:
+ YangLeafList leafList = (YangLeafList) tmpData;
+ leafList.setMaxElelements(maxElementsValue);
+ break;
+ case LIST_DATA:
+ YangList yangList = (YangList) tmpData;
+ yangList.setMaxElements(maxElementsValue);
+ break;
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, MAX_ELEMENT_DATA, "", ENTRY));
+ }
+ }
+
+ /**
+ * Validates max element value and returns the value from context.
+ *
+ * @param ctx context object of the grammar rule
+ * @return max element's value
+ */
+ private static int getValidMaxElementValue(GeneratedYangParser.MaxElementsStatementContext ctx) {
+
+ int maxElementsValue;
+
+ String value = removeQuotesAndHandleConcat(ctx.maxValue().getText());
+ if (value.equals(UNBOUNDED_KEYWORD)) {
+ maxElementsValue = Integer.MAX_VALUE;
+ } else if (value.matches(POSITIVE_INTEGER_PATTERN)) {
+ try {
+ maxElementsValue = Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(MAX_ELEMENT_DATA) + " value " + value + " is not " +
+ "valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ } else {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(MAX_ELEMENT_DATA) + " value " + value + " is not " +
+ "valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ return maxElementsValue;
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MinElementsListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MinElementsListener.java
new file mode 100644
index 0000000..7553aa2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/MinElementsListener.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MIN_ELEMENT_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidNonNegativeIntegerValue;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * min-elements-stmt = min-elements-keyword sep
+ * min-value-arg-str stmtend
+ * min-value-arg-str = < a string that matches the rule
+ * min-value-arg >
+ * min-value-arg = non-negative-integer-value
+ *
+ * ANTLR grammar rule
+ * minElementsStatement : MIN_ELEMENTS_KEYWORD minValue STMTEND;
+ * minValue : string;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "min-elements"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class MinElementsListener {
+
+ /**
+ * Creates a new min-elements listener.
+ */
+ private MinElementsListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (min-elements), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processMinElementsEntry(TreeWalkListener listener,
+ GeneratedYangParser.MinElementsStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, MIN_ELEMENT_DATA, ctx.minValue().getText(), ENTRY);
+
+ int minElementValue = getValidNonNegativeIntegerValue(ctx.minValue().getText(), MIN_ELEMENT_DATA, ctx);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ switch (tmpData.getYangConstructType()) {
+ case LEAF_LIST_DATA:
+ YangLeafList leafList = (YangLeafList) tmpData;
+ leafList.setMinElements(minElementValue);
+ break;
+ case LIST_DATA:
+ YangList yangList = (YangList) tmpData;
+ yangList.setMinElements(minElementValue);
+ break;
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, MIN_ELEMENT_DATA,
+ ctx.minValue().getText(), ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ModuleListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ModuleListener.java
new file mode 100644
index 0000000..ef1af2d
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ModuleListener.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.ResolvableType;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangReferenceResolver;
+import org.onosproject.yangutils.datamodel.YangRevision;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.linker.exceptions.LinkerException;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.MODULE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.setCurrentDateForRevision;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangModuleNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * module-stmt = optsep module-keyword sep identifier-arg-str
+ * optsep
+ * "{" stmtsep
+ * module-header-stmts
+ * linkage-stmts
+ * meta-stmts
+ * revision-stmts
+ * body-stmts
+ * "}" optsep
+ *
+ * ANTLR grammar rule
+ * module_stmt : MODULE_KEYWORD identifier LEFT_CURLY_BRACE module_body* RIGHT_CURLY_BRACE;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "module"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ModuleListener {
+
+ /**
+ * Creates a new module listener.
+ */
+ private ModuleListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (module), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processModuleEntry(TreeWalkListener listener, GeneratedYangParser.ModuleStatementContext ctx) {
+
+ // Check if stack is empty.
+ checkStackIsEmpty(listener, INVALID_HOLDER, MODULE_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), MODULE_DATA, ctx);
+
+ YangModule yangModule = getYangModuleNode(JAVA_GENERATION);
+ yangModule.setName(identifier);
+
+ if (ctx.moduleBody().moduleHeaderStatement().yangVersionStatement() == null) {
+ yangModule.setVersion((byte) 1);
+ }
+
+ if (ctx.moduleBody().revisionStatements().revisionStatement().isEmpty()) {
+ String currentDate = setCurrentDateForRevision();
+ YangRevision currentRevision = new YangRevision();
+ currentRevision.setRevDate(currentDate);
+ yangModule.setRevision(currentRevision);
+ }
+
+ listener.getParsedDataStack().push(yangModule);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (module), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processModuleExit(TreeWalkListener listener, GeneratedYangParser.ModuleStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, MODULE_DATA, ctx.identifier().getText(), EXIT);
+
+ if (!(listener.getParsedDataStack().peek() instanceof YangModule)) {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, MODULE_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ try {
+ ((YangReferenceResolver) listener.getParsedDataStack()
+ .peek()).resolveSelfFileLinking(ResolvableType.YANG_USES);
+ ((YangReferenceResolver) listener.getParsedDataStack()
+ .peek()).resolveSelfFileLinking(ResolvableType.YANG_DERIVED_DATA_TYPE);
+ } catch (DataModelException e) {
+ LinkerException linkerException = new LinkerException(e.getMessage());
+ linkerException.setLine(e.getLineNumber());
+ linkerException.setCharPosition(e.getCharPositionInLine());
+ throw linkerException;
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/NamespaceListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/NamespaceListener.java
new file mode 100644
index 0000000..f32a4ed
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/NamespaceListener.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import java.net.URI;
+
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNameSpace;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.NAMESPACE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * module-header-stmts = ;; these stmts can appear in any order
+ * [yang-version-stmt stmtsep]
+ * namespace-stmt stmtsep
+ * prefix-stmt stmtsep
+ *
+ * namespace-stmt = namespace-keyword sep uri-str optsep stmtend
+ *
+ * ANTLR grammar rule
+ * module_header_statement : yang_version_stmt? namespace_stmt prefix_stmt
+ * | yang_version_stmt? prefix_stmt namespace_stmt
+ * | namespace_stmt yang_version_stmt? prefix_stmt
+ * | namespace_stmt prefix_stmt yang_version_stmt?
+ * | prefix_stmt namespace_stmt yang_version_stmt?
+ * | prefix_stmt yang_version_stmt? namespace_stmt
+ * ;
+ * namespace_stmt : NAMESPACE_KEYWORD string STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "namespace"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class NamespaceListener {
+
+ /**
+ * Creates a new namespace listener.
+ */
+ private NamespaceListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (namespace), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processNamespaceEntry(TreeWalkListener listener,
+ GeneratedYangParser.NamespaceStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, NAMESPACE_DATA, ctx.string().getText(), ENTRY);
+
+ if (!validateUriValue(ctx.string().getText())) {
+ ParserException parserException = new ParserException("YANG file error: Invalid namespace URI");
+ parserException.setLine(ctx.string().STRING(0).getSymbol().getLine());
+ parserException.setCharPosition(ctx.string().STRING(0).getSymbol().getCharPositionInLine());
+ throw parserException;
+ }
+
+ // Obtain the node of the stack.
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case MODULE_DATA: {
+ YangModule module = (YangModule) tmpNode;
+ YangNameSpace uri = new YangNameSpace();
+ uri.setUri(ctx.string().getText());
+ module.setNameSpace(uri);
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, NAMESPACE_DATA,
+ ctx.string().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * Validate input URI.
+ *
+ * @param uri input namespace URI
+ * @return validation result
+ */
+ private static boolean validateUriValue(String uri) {
+ uri = uri.replace("\"", "");
+ try {
+ URI.create(uri);
+ } catch (Exception e1) {
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/NotificationListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/NotificationListener.java
new file mode 100644
index 0000000..6088ab4
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/NotificationListener.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.GROUPING_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.NOTIFICATION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPEDEF_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateMutuallyExclusiveChilds;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangNotificationNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * notification-stmt = notification-keyword sep
+ * identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * *(data-def-stmt stmtsep)
+ * "}")
+ *
+ * ANTLR grammar rule
+ * notificationStatement : NOTIFICATION_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (ifFeatureStatement
+ * | statusStatement | descriptionStatement | referenceStatement | typedefStatement
+ * | groupingStatement | dataDefStatement)* RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "notification"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class NotificationListener {
+
+ /**
+ * Creates a new notification listener.
+ */
+ private NotificationListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (notification), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processNotificationEntry(TreeWalkListener listener,
+ GeneratedYangParser.NotificationStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, NOTIFICATION_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), NOTIFICATION_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, NOTIFICATION_DATA);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+ if (curData instanceof YangModule || curData instanceof YangSubModule) {
+
+ YangNotification notification = getYangNotificationNode(JAVA_GENERATION);
+ notification.setName(identifier);
+ YangNode curNode = (YangNode) curData;
+ try {
+ curNode.addChild(notification);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ NOTIFICATION_DATA, ctx.identifier().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(notification);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, NOTIFICATION_DATA,
+ ctx.identifier().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (notification), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processNotificationExit(TreeWalkListener listener,
+ GeneratedYangParser.NotificationStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, NOTIFICATION_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangNotification) {
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, NOTIFICATION_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of notification sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.NotificationStatementContext ctx) {
+
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, NOTIFICATION_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, NOTIFICATION_DATA,
+ ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, NOTIFICATION_DATA,
+ ctx.identifier().getText());
+ validateMutuallyExclusiveChilds(ctx.typedefStatement(), TYPEDEF_DATA, ctx.groupingStatement(), GROUPING_DATA,
+ NOTIFICATION_DATA, ctx.identifier().getText());
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/OrganizationListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/OrganizationListener.java
new file mode 100644
index 0000000..20a42c1
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/OrganizationListener.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.ORGANIZATION_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * meta-stmts = ;; these stmts can appear in any order
+ * [organization-stmt stmtsep]
+ * [contact-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * organization-stmt = organization-keyword sep string
+ * optsep stmtend
+ *
+ * ANTLR grammar rule
+ * meta_stmts : organization_stmt? contact_stmt? description_stmt? reference_stmt?
+ * | organization_stmt? contact_stmt? reference_stmt? description_stmt?
+ * | organization_stmt? description_stmt? contact_stmt? reference_stmt?
+ * | organization_stmt? description_stmt? reference_stmt? contact_stmt?
+ * | organization_stmt? reference_stmt? contact_stmt? description_stmt?
+ * | organization_stmt? reference_stmt? description_stmt? contact_stmt?
+ * | contact_stmt? organization_stmt? description_stmt? reference_stmt?
+ * | contact_stmt? organization_stmt? reference_stmt? description_stmt?
+ * | contact_stmt? reference_stmt? organization_stmt? description_stmt?
+ * | contact_stmt? reference_stmt? description_stmt? organization_stmt?
+ * | contact_stmt? description_stmt? reference_stmt? organization_stmt?
+ * | contact_stmt? description_stmt? organization_stmt? reference_stmt?
+ * | reference_stmt? contact_stmt? organization_stmt? description_stmt?
+ * | reference_stmt? contact_stmt? description_stmt? organization_stmt?
+ * | reference_stmt? organization_stmt? contact_stmt? description_stmt?
+ * | reference_stmt? organization_stmt? description_stmt? contact_stmt?
+ * | reference_stmt? description_stmt? organization_stmt? contact_stmt?
+ * | reference_stmt? description_stmt? contact_stmt? organization_stmt?
+ * | description_stmt? reference_stmt? contact_stmt? organization_stmt?
+ * | description_stmt? reference_stmt? organization_stmt? contact_stmt?
+ * | description_stmt? contact_stmt? reference_stmt? organization_stmt?
+ * | description_stmt? contact_stmt? organization_stmt? reference_stmt?
+ * | description_stmt? organization_stmt? contact_stmt? reference_stmt?
+ * | description_stmt? organization_stmt? reference_stmt? contact_stmt?
+ * ;
+ * organization_stmt : ORGANIZATION_KEYWORD string STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "organization" rule defined in ANTLR grammar file for corresponding ABNF rule
+ * in RFC 6020.
+ */
+public final class OrganizationListener {
+
+ /**
+ * Creates a new organization listener.
+ */
+ private OrganizationListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (organization), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processOrganizationEntry(TreeWalkListener listener,
+ GeneratedYangParser.OrganizationStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, ORGANIZATION_DATA, ctx.string().getText(),
+ ENTRY);
+
+ // Obtain the node of the stack.
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case MODULE_DATA: {
+ YangModule module = (YangModule) tmpNode;
+ module.setOrganization(ctx.string().getText());
+ break;
+ }
+ case SUB_MODULE_DATA: {
+ YangSubModule subModule = (YangSubModule) tmpNode;
+ subModule.setOrganization(ctx.string().getText());
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, ORGANIZATION_DATA,
+ ctx.string().getText(), ENTRY));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/OutputListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/OutputListener.java
new file mode 100644
index 0000000..d0ef568
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/OutputListener.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangRpc;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.OUTPUT_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction
+ .constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangOutputNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ *
+ * output-stmt = output-keyword optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * 1*(data-def-stmt stmtsep)
+ * "}"
+ *
+ * outputStatement : OUTPUT_KEYWORD LEFT_CURLY_BRACE outputStatementBody RIGHT_CURLY_BRACE;
+
+ * outputStatementBody : typedefStatement* dataDefStatement+
+ * | dataDefStatement+ typedefStatement*
+ * | groupingStatement* dataDefStatement+
+ * | dataDefStatement+ groupingStatement*;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "output"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class OutputListener {
+
+ private static final String OUTPUT_KEYWORD = "_output";
+
+ /**
+ * Creates a new output listener.
+ */
+ private OutputListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (output), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processOutputEntry(TreeWalkListener listener,
+ GeneratedYangParser.OutputStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, OUTPUT_DATA, "", ENTRY);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+ if (curData instanceof YangRpc) {
+
+ YangOutput yangOutput = getYangOutputNode(JAVA_GENERATION);
+ yangOutput.setName(((YangRpc) curData).getName() + OUTPUT_KEYWORD);
+ YangNode curNode = (YangNode) curData;
+ try {
+ curNode.addChild(yangOutput);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ OUTPUT_DATA, "", ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(yangOutput);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, OUTPUT_DATA,
+ "", ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (output), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processOutputExit(TreeWalkListener listener,
+ GeneratedYangParser.OutputStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, OUTPUT_DATA, "", EXIT);
+
+ if (!(listener.getParsedDataStack().peek() instanceof YangOutput)) {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, OUTPUT_DATA,
+ "", EXIT));
+ }
+ listener.getParsedDataStack().pop();
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PatternRestrictionListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PatternRestrictionListener.java
new file mode 100644
index 0000000..26ff6d1
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PatternRestrictionListener.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+import org.onosproject.yangutils.datamodel.YangDataTypes;
+import org.onosproject.yangutils.datamodel.YangDerivedInfo;
+import org.onosproject.yangutils.datamodel.YangPatternRestriction;
+import org.onosproject.yangutils.datamodel.YangStringRestriction;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.YangDataTypes.DERIVED;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.PATTERN_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * pattern-stmt = pattern-keyword sep string optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [error-message-stmt stmtsep]
+ * [error-app-tag-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ *
+ * ANTLR grammar rule
+ * patternStatement : PATTERN_KEYWORD string (STMTEND | LEFT_CURLY_BRACE commonStatements RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "pattern"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class PatternRestrictionListener {
+
+ private static final String EMPTY_STRING = "";
+
+ /**
+ * Creates a new pattern restriction listener.
+ */
+ private PatternRestrictionListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (pattern), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processPatternRestrictionEntry(TreeWalkListener listener,
+ GeneratedYangParser.PatternStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, PATTERN_DATA, ctx.string().getText(), ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData.getYangConstructType() == TYPE_DATA) {
+ YangType type = (YangType) tmpData;
+ setPatternRestriction(listener, type, ctx);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, PATTERN_DATA,
+ ctx.string().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * Sets the pattern restriction to type.
+ *
+ * @param listener listener's object
+ * @param type Yang type for which pattern restriction to be set
+ * @param ctx context object of the grammar rule
+ */
+ private static void setPatternRestriction(TreeWalkListener listener, YangType type,
+ GeneratedYangParser.PatternStatementContext ctx) {
+
+ if (type.getDataType() != YangDataTypes.STRING && type.getDataType() != YangDataTypes.DERIVED) {
+
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(PATTERN_DATA) + " name " + ctx.string().getText() +
+ " can be used to restrict the built-in type string or types derived from string.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ // Validate and get valid pattern restriction string.
+ String patternArgument = getValidPattern(ctx);
+
+ if (type.getDataType() == YangDataTypes.STRING) {
+ YangStringRestriction stringRestriction = (YangStringRestriction) type.getDataTypeExtendedInfo();
+ if (stringRestriction == null) {
+ stringRestriction = new YangStringRestriction();
+ type.setDataTypeExtendedInfo(stringRestriction);
+ stringRestriction.addPattern(patternArgument);
+ } else {
+ stringRestriction.addPattern(patternArgument);
+ }
+ listener.getParsedDataStack().push(stringRestriction);
+ } else {
+ YangPatternRestriction patternRestriction = (YangPatternRestriction) ((YangDerivedInfo<?>) type
+ .getDataTypeExtendedInfo()).getPatternRestriction();
+ if (patternRestriction == null) {
+ patternRestriction = new YangPatternRestriction();
+ ((YangDerivedInfo<?>) type.getDataTypeExtendedInfo()).setPatternRestriction(patternRestriction);
+ patternRestriction.addPattern(patternArgument);
+ } else {
+ ((YangDerivedInfo<?>) type.getDataTypeExtendedInfo()).setPatternRestriction(patternRestriction);
+ patternRestriction.addPattern(patternArgument);
+ }
+ }
+ }
+
+ /**
+ * Performs validation and updates the data model tree.
+ * It is called when parser exits from grammar rule (pattern).
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processPatternRestrictionExit(TreeWalkListener listener,
+ GeneratedYangParser.PatternStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, PATTERN_DATA, ctx.string().getText(), EXIT);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData instanceof YangStringRestriction) {
+ listener.getParsedDataStack().pop();
+ } else if (tmpData instanceof YangType
+ && ((YangType) tmpData).getDataType() == DERIVED) {
+ // TODO : need to handle in linker
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, PATTERN_DATA,
+ ctx.string().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates and return the valid pattern.
+ *
+ * @param ctx context object of the grammar rule
+ * @return validated string
+ */
+ private static String getValidPattern(GeneratedYangParser.PatternStatementContext ctx) {
+ String userInputPattern = ctx.string().getText().replace("\"", EMPTY_STRING);
+ try {
+ Pattern.compile(userInputPattern);
+ } catch (PatternSyntaxException exception) {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(PATTERN_DATA) + " name " + ctx.string().getText() +
+ " is not a valid regular expression");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ return userInputPattern;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PositionListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PositionListener.java
new file mode 100644
index 0000000..4ae66bb
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PositionListener.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * position-stmt = position-keyword sep
+ * position-value-arg-str stmtend
+ * position-value-arg-str = < a string that matches the rule
+ * position-value-arg >
+ * position-value-arg = non-negative-integer-value
+ * non-negative-integer-value = "0" / positive-integer-value
+ * positive-integer-value = (non-zero-digit *DIGIT)
+ * zero-integer-value = 1*DIGIT
+ *
+ * ANTLR grammar rule
+ * positionStatement : POSITION_KEYWORD position STMTEND;
+ * position : string;
+ */
+
+import org.onosproject.yangutils.datamodel.YangBit;
+import org.onosproject.yangutils.datamodel.YangBits;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.POSITION_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidNonNegativeIntegerValue;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/**
+ * Represents listener based call back function corresponding to the "position"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class PositionListener {
+
+ /**
+ * Creates a new position listener.
+ */
+ private PositionListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (position), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processPositionEntry(TreeWalkListener listener,
+ GeneratedYangParser.PositionStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, POSITION_DATA, ctx.position().getText(), ENTRY);
+
+ // Obtain the node of the stack.
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case BIT_DATA: {
+ YangBit bitNode = (YangBit) tmpNode;
+ int positionValue = getValidBitPosition(listener, ctx);
+ bitNode.setPosition(positionValue);
+ break;
+ }
+ default:
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, POSITION_DATA, ctx.position().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * Validates BITS position value correctness and uniqueness.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ * @return position value
+ */
+ private static int getValidBitPosition(TreeWalkListener listener,
+ GeneratedYangParser.PositionStatementContext ctx) {
+ Parsable bitNode = listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, POSITION_DATA, ctx.position().getText(), ENTRY);
+
+ int positionValue = getValidNonNegativeIntegerValue(ctx.position().getText(), POSITION_DATA, ctx);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case BITS_DATA: {
+ YangBits yangBits = (YangBits) tmpNode;
+ for (YangBit curBit : yangBits.getBitSet()) {
+ if (positionValue == curBit.getPosition()) {
+ listener.getParsedDataStack().push(bitNode);
+ ParserException parserException = new ParserException("YANG file error: Duplicate value of " +
+ "position is invalid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ }
+ listener.getParsedDataStack().push(bitNode);
+ return positionValue;
+ }
+ default:
+ listener.getParsedDataStack().push(bitNode);
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, POSITION_DATA, ctx.position().getText(), ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PrefixListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PrefixListener.java
new file mode 100644
index 0000000..b75f77c
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PrefixListener.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangBelongsTo;
+import org.onosproject.yangutils.datamodel.YangImport;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.PREFIX_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * module-header-stmts = ;; these stmts can appear in any order
+ * [yang-version-stmt stmtsep]
+ * namespace-stmt stmtsep
+ * prefix-stmt stmtsep
+ *
+ * prefix-stmt = prefix-keyword sep prefix-arg-str
+ * optsep stmtend
+ *
+ * ANTLR grammar rule
+ * module_header_statement : yang_version_stmt? namespace_stmt prefix_stmt
+ * | yang_version_stmt? prefix_stmt namespace_stmt
+ * | namespace_stmt yang_version_stmt? prefix_stmt
+ * | namespace_stmt prefix_stmt yang_version_stmt?
+ * | prefix_stmt namespace_stmt yang_version_stmt?
+ * | prefix_stmt yang_version_stmt? namespace_stmt
+ * ;
+ * prefix_stmt : PREFIX_KEYWORD identifier STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "prefix"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class PrefixListener {
+
+ /**
+ * Creates a new prefix listener.
+ */
+ private PrefixListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (prefix),perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processPrefixEntry(TreeWalkListener listener, GeneratedYangParser.PrefixStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, PREFIX_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), PREFIX_DATA, ctx);
+
+ // Obtain the node of the stack.
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case MODULE_DATA: {
+ YangModule module = (YangModule) tmpNode;
+ module.setPrefix(identifier);
+ break;
+ }
+ case IMPORT_DATA: {
+ YangImport importNode = (YangImport) tmpNode;
+ importNode.setPrefixId(identifier);
+ break;
+ }
+ case BELONGS_TO_DATA: {
+ YangBelongsTo belongstoNode = (YangBelongsTo) tmpNode;
+ belongstoNode.setPrefix(identifier);
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, PREFIX_DATA,
+ ctx.identifier().getText(), ENTRY));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PresenceListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PresenceListener.java
new file mode 100644
index 0000000..ef744d5
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PresenceListener.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CONTAINER_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.PRESENCE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * presence-stmt = presence-keyword sep string stmtend
+ *
+ * ANTLR grammar rule
+ * presenceStatement : PRESENCE_KEYWORD string STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "presence"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class PresenceListener {
+
+ /**
+ * Creates a new presence listener.
+ */
+ private PresenceListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (presence), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processPresenceEntry(TreeWalkListener listener,
+ GeneratedYangParser.PresenceStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, PRESENCE_DATA, ctx.string().getText(), ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData.getYangConstructType() == CONTAINER_DATA) {
+ YangContainer container = (YangContainer) tmpData;
+ container.setPresence(ctx.string().getText());
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, PRESENCE_DATA,
+ ctx.string().getText(), ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RangeRestrictionListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RangeRestrictionListener.java
new file mode 100644
index 0000000..d7094ed
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RangeRestrictionListener.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangDerivedInfo;
+import org.onosproject.yangutils.datamodel.YangRangeRestriction;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.YangDataTypes.DERIVED;
+import static org.onosproject.yangutils.datamodel.utils.RestrictionResolver.isOfRangeRestrictedType;
+import static org.onosproject.yangutils.datamodel.utils.RestrictionResolver.processRangeRestriction;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.RANGE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * range-stmt = range-keyword sep range-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [error-message-stmt stmtsep]
+ * [error-app-tag-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ *
+ * ANTLR grammar rule
+ * rangeStatement : RANGE_KEYWORD range (STMTEND | LEFT_CURLY_BRACE commonStatements RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "range"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class RangeRestrictionListener {
+
+ /**
+ * Creates a new range restriction listener.
+ */
+ private RangeRestrictionListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (range), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processRangeRestrictionEntry(TreeWalkListener listener,
+ GeneratedYangParser.RangeStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, RANGE_DATA, ctx.range().getText(), ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData.getYangConstructType() == TYPE_DATA) {
+ YangType type = (YangType) tmpData;
+ setRangeRestriction(listener, type, ctx);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, RANGE_DATA,
+ ctx.range().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * Sets the range restriction to type.
+ *
+ * @param listener listener's object
+ * @param type YANG type for which range restriction to be added
+ * @param ctx context object of the grammar rule
+ */
+ private static void setRangeRestriction(TreeWalkListener listener, YangType type,
+ GeneratedYangParser.RangeStatementContext ctx) {
+
+ if (type.getDataType() == DERIVED) {
+ ((YangDerivedInfo<YangRangeRestriction>) type.getDataTypeExtendedInfo())
+ .setRangeRestrictionString(ctx.range().getText());
+ ((YangDerivedInfo<YangRangeRestriction>) type.getDataTypeExtendedInfo())
+ .setLineNumber(ctx.getStart().getLine());
+ ((YangDerivedInfo<YangRangeRestriction>) type.getDataTypeExtendedInfo())
+ .setCharPosition(ctx.getStart().getCharPositionInLine());
+ return;
+ }
+
+ if (!(isOfRangeRestrictedType(type.getDataType()))) {
+ ParserException parserException = new ParserException("YANG file error: Range restriction can't be " +
+ "applied to a given type");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ YangRangeRestriction rangeRestriction = null;
+ try {
+ rangeRestriction = processRangeRestriction(null, ctx.getStart().getLine(),
+ ctx.getStart().getCharPositionInLine(), false, ctx.range().getText(), type.getDataType());
+ } catch (DataModelException e) {
+ ParserException parserException = new ParserException(e.getMessage());
+ parserException.setCharPosition(e.getCharPositionInLine());
+ parserException.setLine(e.getLineNumber());
+ throw parserException;
+ }
+
+ if (rangeRestriction != null) {
+ type.setDataTypeExtendedInfo(rangeRestriction);
+ }
+ listener.getParsedDataStack().push(rangeRestriction);
+ }
+
+ /**
+ * Performs validation and updates the data model tree.
+ * It is called when parser exits from grammar rule (range).
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processRangeRestrictionExit(TreeWalkListener listener,
+ GeneratedYangParser.RangeStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, RANGE_DATA, ctx.range().getText(), EXIT);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData instanceof YangRangeRestriction) {
+ listener.getParsedDataStack().pop();
+ } else if (tmpData instanceof YangType
+ && ((YangType) tmpData).getDataType() == DERIVED) {
+ // TODO : need to handle in linker
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, RANGE_DATA,
+ ctx.range().getText(), EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ReferenceListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ReferenceListener.java
new file mode 100644
index 0000000..02cdf62
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ReferenceListener.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangReference;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * reference-stmt = reference-keyword sep string optsep stmtend
+ *
+ * ANTLR grammar rule
+ * referenceStatement : REFERENCE_KEYWORD string STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "reference"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ReferenceListener {
+
+ /**
+ * Creates a new reference listener.
+ */
+ private ReferenceListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (reference), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processReferenceEntry(TreeWalkListener listener,
+ GeneratedYangParser.ReferenceStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, REFERENCE_DATA, ctx.string().getText(), ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData instanceof YangReference) {
+ YangReference reference = (YangReference) tmpData;
+ reference.setReference(ctx.string().getText());
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, REFERENCE_DATA,
+ ctx.string().getText(), ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RevisionDateListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RevisionDateListener.java
new file mode 100644
index 0000000..bb701a6
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RevisionDateListener.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangImport;
+import org.onosproject.yangutils.datamodel.YangInclude;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REVISION_DATE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.isDateValid;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.removeQuotesAndHandleConcat;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * import-stmt = import-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * prefix-stmt stmtsep
+ * [revision-date-stmt stmtsep]
+ * "}"
+ * include-stmt = include-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * [revision-date-stmt stmtsep]
+ * "}")
+ * revision-date-stmt = revision-date-keyword sep revision-date stmtend
+ *
+ * ANTLR grammar rule
+ * import_stmt : IMPORT_KEYWORD IDENTIFIER LEFT_CURLY_BRACE import_stmt_body
+ * RIGHT_CURLY_BRACE;
+ * import_stmt_body : prefix_stmt revision_date_stmt?;
+ *
+ * include_stmt : INCLUDE_KEYWORD IDENTIFIER (STMTEND | LEFT_CURLY_BRACE
+ * revision_date_stmt_body? RIGHT_CURLY_BRACE);
+ *
+ * revision_date_stmt : REVISION_DATE_KEYWORD DATE_ARG STMTEND;
+ *
+ */
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "revision date" rule defined in ANTLR grammar file for corresponding ABNF
+ * rule in RFC 6020.
+ */
+public final class RevisionDateListener {
+
+ /**
+ * Creates a new revision date listener.
+ */
+ private RevisionDateListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (revision date),perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processRevisionDateEntry(TreeWalkListener listener,
+ GeneratedYangParser.RevisionDateStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, REVISION_DATE_DATA, ctx.dateArgumentString().getText(),
+ ENTRY);
+
+ String date = removeQuotesAndHandleConcat(ctx.dateArgumentString().getText());
+ if (!isDateValid(date)) {
+ ParserException parserException = new ParserException("YANG file error: Input date is not correct");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ // Obtain the node of the stack.
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case IMPORT_DATA: {
+ YangImport importNode = (YangImport) tmpNode;
+ importNode.setRevision(date);
+ break;
+ }
+ case INCLUDE_DATA: {
+ YangInclude includeNode = (YangInclude) tmpNode;
+ includeNode.setRevision(date);
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, REVISION_DATE_DATA,
+ ctx.dateArgumentString().getText(), ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RevisionListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RevisionListener.java
new file mode 100644
index 0000000..36d028a
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RevisionListener.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangRevision;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REVISION_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.isDateValid;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.removeQuotesAndHandleConcat;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * module-stmt = optsep module-keyword sep identifier-arg-str
+ * optsep
+ * "{" stmtsep
+ * module-header-stmts
+ * linkage-stmts
+ * meta-stmts
+ * revision-stmts
+ * body-stmts
+ * "}" optsep
+ *
+ * revision-stmt = revision-keyword sep revision-date optsep
+ * (";" /
+ * "{" stmtsep
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ *
+ * ANTLR grammar rule
+ * module_stmt : MODULE_KEYWORD IDENTIFIER LEFT_CURLY_BRACE module_body* RIGHT_CURLY_BRACE;
+ *
+ * revision_stmt : REVISION_KEYWORD DATE_ARG (STMTEND | LEFT_CURLY_BRACE revision_stmt_body RIGHT_CURLY_BRACE);
+ * revision_stmt_body : description_stmt? reference_stmt?;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "revision"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class RevisionListener {
+
+ /**
+ * Creates a new revision listener.
+ */
+ private RevisionListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (revision),perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processRevisionEntry(TreeWalkListener listener,
+ GeneratedYangParser.RevisionStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, REVISION_DATA, ctx.dateArgumentString().getText(), ENTRY);
+
+ // Validate for reverse chronological order of revision & for revision
+ // value.
+ if (!validateRevision(listener, ctx)) {
+ return;
+ // TODO to be implemented.
+ }
+
+ String date = removeQuotesAndHandleConcat(ctx.dateArgumentString().getText());
+ if (!isDateValid(date)) {
+ ParserException parserException = new ParserException("YANG file error: Input date is not correct");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ YangRevision revisionNode = new YangRevision();
+ revisionNode.setRevDate(date);
+
+ listener.getParsedDataStack().push(revisionNode);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (revision), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processRevisionExit(TreeWalkListener listener, GeneratedYangParser.RevisionStatementContext
+ ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, REVISION_DATA, ctx.dateArgumentString().getText(), EXIT);
+
+ Parsable tmpRevisionNode = listener.getParsedDataStack().peek();
+ if (tmpRevisionNode instanceof YangRevision) {
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, REVISION_DATA, ctx.dateArgumentString().getText(),
+ EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case MODULE_DATA: {
+ YangModule module = (YangModule) tmpNode;
+ module.setRevision((YangRevision) tmpRevisionNode);
+ break;
+ }
+ case SUB_MODULE_DATA: {
+ YangSubModule subModule = (YangSubModule) tmpNode;
+ subModule.setRevision((YangRevision) tmpRevisionNode);
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, REVISION_DATA,
+ ctx.dateArgumentString().getText(),
+ EXIT));
+ }
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, REVISION_DATA,
+ ctx.dateArgumentString().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validate revision.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ * @return validation result
+ */
+ private static boolean validateRevision(TreeWalkListener listener,
+ GeneratedYangParser.RevisionStatementContext ctx) {
+ // TODO to be implemented
+ return true;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RpcListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RpcListener.java
new file mode 100644
index 0000000..afb78a3
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RpcListener.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangRpc;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.GROUPING_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.INPUT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.OUTPUT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.RPC_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPEDEF_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.*;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateMutuallyExclusiveChilds;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangRpcNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * rpc-stmt = rpc-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * [input-stmt stmtsep]
+ * [output-stmt stmtsep]
+ * "}")
+ *
+ * ANTLR grammar rule
+ * rpcStatement : RPC_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (ifFeatureStatement | statusStatement
+ * | descriptionStatement | referenceStatement | typedefStatement | groupingStatement | inputStatement
+ * | outputStatement)* RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "rpc"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class RpcListener {
+
+ /**
+ * Creates a new rpc listener.
+ */
+ private RpcListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (rpc), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processRpcEntry(TreeWalkListener listener,
+ GeneratedYangParser.RpcStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, RPC_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), RPC_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, RPC_DATA);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+ if (curData instanceof YangModule || curData instanceof YangSubModule) {
+
+ YangNode curNode = (YangNode) curData;
+ YangRpc yangRpc = getYangRpcNode(JAVA_GENERATION);
+ yangRpc.setName(identifier);
+ try {
+ curNode.addChild(yangRpc);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ RPC_DATA, ctx.identifier().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(yangRpc);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, RPC_DATA,
+ ctx.identifier().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (rpc), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processRpcExit(TreeWalkListener listener,
+ GeneratedYangParser.RpcStatementContext ctx) {
+
+ //Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, RPC_DATA, ctx.identifier().getText(), EXIT);
+
+ if (!(listener.getParsedDataStack().peek() instanceof YangRpc)) {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, RPC_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ listener.getParsedDataStack().pop();
+ }
+
+ /**
+ * Validates the cardinality of rpc sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.RpcStatementContext ctx) {
+
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, RPC_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, RPC_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, RPC_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.inputStatement(), INPUT_DATA, RPC_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.outputStatement(), OUTPUT_DATA, RPC_DATA, ctx.identifier().getText());
+ validateMutuallyExclusiveChilds(ctx.typedefStatement(), TYPEDEF_DATA, ctx.groupingStatement(), GROUPING_DATA,
+ RPC_DATA, ctx.identifier().getText());
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ShortCaseListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ShortCaseListener.java
new file mode 100644
index 0000000..612fe3b
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ShortCaseListener.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.antlr.v4.runtime.tree.ParseTree;
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangChoice;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.CASE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.SHORT_CASE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_CHILD;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangCaseNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * short-case-stmt = container-stmt /
+ * leaf-stmt /
+ * leaf-list-stmt /
+ * list-stmt /
+ * anyxml-stmt
+ *
+ * ANTLR grammar rule
+ * shortCaseStatement : containerStatement | leafStatement | leafListStatement | listStatement;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "short
+ * case" rule defined in ANTLR grammar file for corresponding ABNF rule in RFC
+ * 6020.
+ */
+public final class ShortCaseListener {
+
+ /**
+ * Create a new short case listener.
+ */
+ private ShortCaseListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (short case), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processShortCaseEntry(TreeWalkListener listener,
+ GeneratedYangParser.ShortCaseStatementContext ctx) {
+
+ ParseTree errorConstructContext;
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, SHORT_CASE_DATA, "", ENTRY);
+
+ YangCase caseNode = getYangCaseNode(JAVA_GENERATION);
+
+ if (ctx.containerStatement() != null) {
+ caseNode.setName(getValidIdentifier(ctx.containerStatement().identifier().getText(), CASE_DATA, ctx));
+ errorConstructContext = ctx.containerStatement();
+ } else if (ctx.listStatement() != null) {
+ caseNode.setName(getValidIdentifier(ctx.listStatement().identifier().getText(), CASE_DATA, ctx));
+ errorConstructContext = ctx.listStatement();
+ } else if (ctx.leafListStatement() != null) {
+ caseNode.setName(getValidIdentifier(ctx.leafListStatement().identifier().getText(), CASE_DATA, ctx));
+ errorConstructContext = ctx.leafListStatement();
+ } else if (ctx.leafStatement() != null) {
+ caseNode.setName(getValidIdentifier(ctx.leafStatement().identifier().getText(), CASE_DATA, ctx));
+ errorConstructContext = ctx.leafStatement();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_CHILD, SHORT_CASE_DATA, "", ENTRY));
+ }
+ // TODO implement for augment.
+
+ int line = ((ParserRuleContext) errorConstructContext).getStart().getLine();
+ int charPositionInLine = ((ParserRuleContext) errorConstructContext).getStart().getCharPositionInLine();
+
+ // Check for identifier collision
+ detectCollidingChildUtil(listener, line, charPositionInLine, caseNode.getName(), CASE_DATA);
+
+ if ((listener.getParsedDataStack().peek()) instanceof YangChoice) {
+ try {
+ ((YangChoice) listener.getParsedDataStack().peek()).addChild(caseNode);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ SHORT_CASE_DATA, caseNode.getName(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(caseNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, SHORT_CASE_DATA,
+ caseNode.getName(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (short case), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processShortCaseExit(TreeWalkListener listener,
+ GeneratedYangParser.ShortCaseStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, SHORT_CASE_DATA, "", EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangCase) {
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, SHORT_CASE_DATA,
+ "", EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/StatusListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/StatusListener.java
new file mode 100644
index 0000000..81d6b61
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/StatusListener.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangStatus;
+import org.onosproject.yangutils.datamodel.YangStatusType;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.removeQuotesAndHandleConcat;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * status-stmt = status-keyword sep status-arg-str stmtend
+ * status-arg-str = < a string that matches the rule
+ * status-arg >
+ * status-arg = current-keyword /
+ * obsolete-keyword /
+ * deprecated-keyword
+ *
+ * ANTLR grammar rule
+ * statusStatement : STATUS_KEYWORD status STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "status"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class StatusListener {
+
+ private static final String CURRENT_KEYWORD = "current";
+ private static final String DEPRECATED_KEYWORD = "deprecated";
+ private static final String OBSOLETE_KEYWORD = "obsolete";
+
+ /**
+ * Creates a new status listener.
+ */
+ private StatusListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (status), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processStatusEntry(TreeWalkListener listener,
+ GeneratedYangParser.StatusStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, STATUS_DATA, "", ENTRY);
+
+ YangStatusType status = getValidStatus(ctx);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ if (tmpData instanceof YangStatus) {
+ YangStatus yangStatus = (YangStatus) tmpData;
+ yangStatus.setStatus(status);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, STATUS_DATA, "", ENTRY));
+ }
+ }
+
+ /**
+ * Validates status value and returns the value from context.
+ *
+ * @param ctx context object of the grammar rule
+ * @return status current/deprecated/obsolete
+ */
+ private static YangStatusType getValidStatus(GeneratedYangParser.StatusStatementContext ctx) {
+
+ YangStatusType status;
+
+ String value = removeQuotesAndHandleConcat(ctx.status().getText());
+ switch (value) {
+ case CURRENT_KEYWORD: {
+ status = YangStatusType.CURRENT;
+ break;
+ }
+ case DEPRECATED_KEYWORD: {
+ status = YangStatusType.DEPRECATED;
+ break;
+ }
+ case OBSOLETE_KEYWORD: {
+ status = YangStatusType.OBSOLETE;
+ break;
+ }
+ default: {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(STATUS_DATA) + " " + ctx.status().getText() +
+ " is not valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ }
+
+ return status;
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/SubModuleListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/SubModuleListener.java
new file mode 100644
index 0000000..639906a
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/SubModuleListener.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.ResolvableType;
+import org.onosproject.yangutils.datamodel.YangReferenceResolver;
+import org.onosproject.yangutils.datamodel.YangRevision;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.linker.exceptions.LinkerException;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.SUB_MODULE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.setCurrentDateForRevision;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangSubModuleNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * submodule-stmt = optsep submodule-keyword sep identifier-arg-str
+ * optsep
+ * "{" stmtsep
+ * submodule-header-stmts
+ * linkage-stmts
+ * meta-stmts
+ * revision-stmts
+ * body-stmts
+ * "}" optsep
+ *
+ * ANTLR grammar rule
+ * submodule_stmt : SUBMODULE_KEYWORD identifier LEFT_CURLY_BRACE submodule_body* RIGHT_CURLY_BRACE;
+ * submodule_body : submodule_header_statement linkage_stmts meta_stmts revision_stmts body_stmts;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "submodule"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class SubModuleListener {
+
+ /**
+ * Creates a new sub module listener.
+ */
+ private SubModuleListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule (sub
+ * module), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processSubModuleEntry(TreeWalkListener listener,
+ GeneratedYangParser.SubModuleStatementContext ctx) {
+
+ // Check if stack is empty.
+ checkStackIsEmpty(listener, INVALID_HOLDER, SUB_MODULE_DATA, ctx.identifier().getText(),
+ ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), SUB_MODULE_DATA, ctx);
+
+ YangSubModule yangSubModule = getYangSubModuleNode(JAVA_GENERATION);
+ yangSubModule.setName(identifier);
+
+ if (ctx.submoduleBody().submoduleHeaderStatement().yangVersionStatement() == null) {
+ yangSubModule.setVersion((byte) 1);
+ }
+
+ if (ctx.submoduleBody().revisionStatements().revisionStatement().isEmpty()) {
+ String currentDate = setCurrentDateForRevision();
+ YangRevision currentRevision = new YangRevision();
+ currentRevision.setRevDate(currentDate);
+ yangSubModule.setRevision(currentRevision);
+ }
+
+ listener.getParsedDataStack().push(yangSubModule);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (submodule), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processSubModuleExit(TreeWalkListener listener,
+ GeneratedYangParser.SubModuleStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, SUB_MODULE_DATA, ctx.identifier().getText(),
+ EXIT);
+
+ if (!(listener.getParsedDataStack().peek() instanceof YangSubModule)) {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, SUB_MODULE_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ try {
+ ((YangReferenceResolver) listener.getParsedDataStack().peek())
+ .resolveSelfFileLinking(ResolvableType.YANG_USES);
+ ((YangReferenceResolver) listener.getParsedDataStack().peek())
+ .resolveSelfFileLinking(ResolvableType.YANG_DERIVED_DATA_TYPE);
+ } catch (DataModelException e) {
+ LinkerException linkerException = new LinkerException(e.getMessage());
+ linkerException.setLine(e.getLineNumber());
+ linkerException.setCharPosition(e.getCharPositionInLine());
+ throw linkerException;
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeDefListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeDefListener.java
new file mode 100644
index 0000000..4a629ba
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeDefListener.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangRpc;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DEFAULT_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPEDEF_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.UNITS_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_CONTENT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityEqualsOne;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangTypeDefNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * body-stmts = *((extension-stmt /
+ * feature-stmt /
+ * identity-stmt /
+ * typedef-stmt /
+ * grouping-stmt /
+ * data-def-stmt /
+ * augment-stmt /
+ * rpc-stmt /
+ * notification-stmt /
+ * deviation-stmt) stmtsep)
+ *
+ * typedef-stmt = typedef-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * type-stmt stmtsep
+ * [units-stmt stmtsep]
+ * [default-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ *
+ * ANTLR grammar rule
+ * typedefStatement : TYPEDEF_KEYWORD identifier LEFT_CURLY_BRACE
+ * (typeStatement | unitsStatement | defaultStatement | statusStatement
+ * | descriptionStatement | referenceStatement)* RIGHT_CURLY_BRACE;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "typedef"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class TypeDefListener {
+
+ /**
+ * Creates a new typedef listener.
+ */
+ private TypeDefListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (typedef), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processTypeDefEntry(TreeWalkListener listener,
+ GeneratedYangParser.TypedefStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, TYPEDEF_DATA, ctx.identifier().getText(), ENTRY);
+
+ String identifier = getValidIdentifier(ctx.identifier().getText(), TYPEDEF_DATA, ctx);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ detectCollidingChildUtil(listener, line, charPositionInLine, identifier, TYPEDEF_DATA);
+
+ /*
+ * Create a derived type information, the base type must be set in type
+ * listener.
+ */
+ YangTypeDef typeDefNode = getYangTypeDefNode(JAVA_GENERATION);
+ typeDefNode.setName(identifier);
+
+ Parsable curData = listener.getParsedDataStack().peek();
+
+ if (curData instanceof YangModule || curData instanceof YangSubModule || curData instanceof YangContainer
+ || curData instanceof YangList || curData instanceof YangNotification || curData instanceof YangRpc
+ || curData instanceof YangInput || curData instanceof YangOutput || curData instanceof YangGrouping) {
+
+ YangNode curNode = (YangNode) curData;
+ try {
+ curNode.addChild(typeDefNode);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ TYPEDEF_DATA, ctx.identifier().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(typeDefNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER,
+ TYPEDEF_DATA, ctx.identifier().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (typedef), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processTypeDefExit(TreeWalkListener listener,
+ GeneratedYangParser.TypedefStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, TYPEDEF_DATA, ctx.identifier().getText(), EXIT);
+
+ if (listener.getParsedDataStack().peek() instanceof YangTypeDef) {
+ YangTypeDef typeDefNode = (YangTypeDef) listener.getParsedDataStack().peek();
+ try {
+ typeDefNode.validateDataOnExit();
+ } catch (DataModelException e) {
+ throw new ParserException(constructListenerErrorMessage(INVALID_CONTENT, TYPEDEF_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+
+ listener.getParsedDataStack().pop();
+ } else {
+ throw new ParserException(constructListenerErrorMessage(MISSING_CURRENT_HOLDER, TYPEDEF_DATA,
+ ctx.identifier().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Validates the cardinality of typedef sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.TypedefStatementContext ctx) {
+
+ validateCardinalityMaxOne(ctx.unitsStatement(), UNITS_DATA, TYPEDEF_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.defaultStatement(), DEFAULT_DATA, TYPEDEF_DATA, ctx.identifier().getText());
+ validateCardinalityEqualsOne(ctx.typeStatement(), TYPE_DATA, TYPEDEF_DATA, ctx.identifier().getText(), ctx);
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, TYPEDEF_DATA,
+ ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, TYPEDEF_DATA, ctx.identifier().getText());
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, TYPEDEF_DATA, ctx.identifier().getText());
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeListener.java
new file mode 100644
index 0000000..ea14df2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeListener.java
@@ -0,0 +1,268 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangDataTypes;
+import org.onosproject.yangutils.datamodel.YangDerivedInfo;
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNodeIdentifier;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.YangUnion;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.linker.impl.YangResolutionInfoImpl;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.addResolutionInfo;
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.UNRESOLVED;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidNodeIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangType;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * type-stmt = type-keyword sep identifier-ref-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * type-body-stmts
+ * "}")
+ *
+ * ANTLR grammar rule
+ * typeStatement : TYPE_KEYWORD string (STMTEND | LEFT_CURLY_BRACE typeBodyStatements RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "type" rule
+ * defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class TypeListener {
+
+ /**
+ * Creates a new type listener.
+ */
+ private TypeListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (type), performs validation and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processTypeEntry(TreeWalkListener listener,
+ GeneratedYangParser.TypeStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, TYPE_DATA, ctx.string().getText(), ENTRY);
+
+ // Validate node identifier.
+ YangNodeIdentifier nodeIdentifier = getValidNodeIdentifier(ctx.string().getText(), TYPE_DATA,
+ ctx);
+
+ // Obtain the YANG data type.
+ YangDataTypes yangDataTypes = YangDataTypes.getType(ctx.string().getText());
+
+ // Create YANG type object and fill the values.
+ YangType<?> type = getYangType(JAVA_GENERATION);
+ type.setNodeIdentifier(nodeIdentifier);
+ type.setDataType(yangDataTypes);
+
+ int errorLine = ctx.getStart().getLine();
+ int errorPosition = ctx.getStart().getCharPositionInLine();
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ switch (tmpData.getYangConstructType()) {
+ case LEAF_DATA:
+ YangLeaf leaf = (YangLeaf) tmpData;
+ leaf.setDataType(type);
+
+ /*
+ * If data type is derived, resolution information to be added
+ * in resolution list.
+ */
+ if (yangDataTypes == YangDataTypes.DERIVED) {
+ // Parent YANG node of leaf to be added in resolution information.
+ Parsable leafData = listener.getParsedDataStack().pop();
+ Parsable parentNodeOfLeaf = listener.getParsedDataStack().peek();
+ listener.getParsedDataStack().push(leafData);
+
+ // Verify parent node of leaf
+ if (!(parentNodeOfLeaf instanceof YangNode)) {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, TYPE_DATA,
+ ctx.string().getText(), EXIT));
+ }
+
+ // Create empty derived info and attach it to type extended info.
+ YangDerivedInfo<?> yangDerivedInfo = new YangDerivedInfo<>();
+ ((YangType<YangDerivedInfo>) type).setDataTypeExtendedInfo(yangDerivedInfo);
+
+ type.setResolvableStatus(UNRESOLVED);
+
+ // Add resolution information to the list
+ YangResolutionInfoImpl resolutionInfo = new YangResolutionInfoImpl<YangType>(type,
+ (YangNode) parentNodeOfLeaf, errorLine, errorPosition);
+ addToResolutionList(resolutionInfo, ctx);
+ }
+ break;
+ case LEAF_LIST_DATA:
+ YangLeafList leafList = (YangLeafList) tmpData;
+ leafList.setDataType(type);
+
+ /*
+ * If data type is derived, resolution information to be added
+ * in resolution list.
+ */
+ if (yangDataTypes == YangDataTypes.DERIVED) {
+ // Parent YANG node of leaf list to be added in resolution information.
+ Parsable leafListData = listener.getParsedDataStack().pop();
+ Parsable parentNodeOfLeafList = listener.getParsedDataStack().peek();
+ listener.getParsedDataStack().push(leafListData);
+
+ // Verify parent node of leaf
+ if (!(parentNodeOfLeafList instanceof YangNode)) {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, TYPE_DATA,
+ ctx.string().getText(), EXIT));
+ }
+
+ // Create empty derived info and attach it to type extended info.
+ YangDerivedInfo<?> yangDerivedInfo = new YangDerivedInfo<>();
+ ((YangType<YangDerivedInfo>) type).setDataTypeExtendedInfo(yangDerivedInfo);
+
+ // Add resolution information to the list
+ YangResolutionInfoImpl resolutionInfo =
+ new YangResolutionInfoImpl<YangType>(type, (YangNode) parentNodeOfLeafList, errorLine,
+ errorPosition);
+ addToResolutionList(resolutionInfo, ctx);
+ }
+ break;
+ case UNION_DATA:
+ YangUnion unionNode = (YangUnion) tmpData;
+ try {
+ unionNode.addType(type);
+ } catch (DataModelException e) {
+ ParserException parserException = new ParserException(e.getMessage());
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ /*
+ * If data type is derived, resolution information to be added
+ * in resolution list.
+ */
+ if (yangDataTypes == YangDataTypes.DERIVED) {
+
+ // Create empty derived info and attach it to type extended info.
+ YangDerivedInfo<?> yangDerivedInfo = new YangDerivedInfo<>();
+ ((YangType<YangDerivedInfo>) type).setDataTypeExtendedInfo(yangDerivedInfo);
+
+ type.setResolvableStatus(UNRESOLVED);
+
+ // Add resolution information to the list
+ YangResolutionInfoImpl resolutionInfo =
+ new YangResolutionInfoImpl<YangType>(type, unionNode, errorLine, errorPosition);
+ addToResolutionList(resolutionInfo, ctx);
+ }
+
+ break;
+ case TYPEDEF_DATA:
+ /* Prepare the base type info and set in derived type */
+ YangTypeDef typeDef = (YangTypeDef) tmpData;
+ typeDef.setDataType(type);
+
+ /*
+ * If data type is derived, resolution information to be added
+ * in resolution list.
+ */
+ if (yangDataTypes == YangDataTypes.DERIVED) {
+ // Create empty derived info and attach it to type extended info.
+ YangDerivedInfo<?> yangDerivedInfo = new YangDerivedInfo<>();
+ ((YangType<YangDerivedInfo>) type).setDataTypeExtendedInfo(yangDerivedInfo);
+
+ type.setResolvableStatus(UNRESOLVED);
+
+ // Add resolution information to the list
+ YangResolutionInfoImpl resolutionInfo =
+ new YangResolutionInfoImpl<YangType>(type, typeDef, errorLine, errorPosition);
+ addToResolutionList(resolutionInfo, ctx);
+ }
+ break;
+ //TODO: deviate replacement statement.
+
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, TYPE_DATA,
+ ctx.string().getText(), EXIT));
+ }
+
+ // Push the type to the stack.
+ listener.getParsedDataStack().push(type);
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (type), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processTypeExit(TreeWalkListener listener,
+ GeneratedYangParser.TypeStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_CURRENT_HOLDER, TYPE_DATA, ctx.string().getText(), EXIT);
+
+ Parsable parsableType = listener.getParsedDataStack().pop();
+ if (!(parsableType instanceof YangType)) {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, TYPE_DATA,
+ ctx.string().getText(), EXIT));
+ }
+ }
+
+ /**
+ * Adds to resolution list.
+ *
+ * @param resolutionInfo resolution information
+ * @param ctx context object of the grammar rule
+ */
+ private static void addToResolutionList(YangResolutionInfoImpl<YangType> resolutionInfo,
+ GeneratedYangParser.TypeStatementContext ctx) {
+ try {
+ addResolutionInfo(resolutionInfo);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ TYPE_DATA, ctx.string().getText(), ENTRY, e.getMessage()));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UnionListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UnionListener.java
new file mode 100644
index 0000000..32eb4d9
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UnionListener.java
@@ -0,0 +1,220 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * type-body-stmts = numerical-restrictions /
+ * decimal64-specification /
+ * string-restrictions /
+ * enum-specification /
+ * leafref-specification /
+ * identityref-specification /
+ * instance-identifier-specification /
+ * bits-specification /
+ * union-specification
+ *
+ * union-specification = 1*(type-stmt stmtsep)
+ *
+ * ANTLR grammar rule
+ * typeBodyStatements : numericalRestrictions | stringRestrictions | enumSpecification
+ * | leafrefSpecification | identityrefSpecification | instanceIdentifierSpecification
+ * | bitsSpecification | unionSpecification;
+ *
+ * unionSpecification : typeStatement+;
+ */
+
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.YangUnion;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.TYPE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.UNION_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangUnionNode;
+
+/**
+ * Represents listener based call back function corresponding to the "union" rule
+ * defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class UnionListener {
+
+ /**
+ * Suffix to be used while creating union class.
+ */
+ private static final String UNION_CLASS_SUFFIX = "_union";
+
+ /**
+ * Creates a new union listener.
+ */
+ private UnionListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (union), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processUnionEntry(TreeWalkListener listener,
+ GeneratedYangParser.UnionSpecificationContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, UNION_DATA, "", ENTRY);
+
+ if (listener.getParsedDataStack().peek() instanceof YangType) {
+ YangUnion unionNode = getYangUnionNode(JAVA_GENERATION);
+ Parsable typeData = listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, UNION_DATA, "", ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+
+ switch (tmpData.getYangConstructType()) {
+ case LEAF_DATA:
+ // Set the name of union same as leaf.
+ unionNode.setName(((YangLeaf) tmpData).getName() + UNION_CLASS_SUFFIX);
+ // Pop the stack entry to obtain the parent YANG node.
+ Parsable leaf = listener.getParsedDataStack().pop();
+ // Add the union node to the parent holder of leaf.
+ addChildToParentNode(listener, unionNode);
+ // Push the popped entry back to the stack.
+ listener.getParsedDataStack().push(leaf);
+ break;
+ case LEAF_LIST_DATA:
+ // Set the name of union same as leaf list.
+ unionNode.setName(((YangLeafList) tmpData).getName() + UNION_CLASS_SUFFIX);
+ // Pop the stack entry to obtain the parent YANG node.
+ Parsable leafList = listener.getParsedDataStack().pop();
+ // Add the union node to the parent holder of leaf.
+ addChildToParentNode(listener, unionNode);
+ // Push the popped entry back to the stack.
+ listener.getParsedDataStack().push(leafList);
+ break;
+ case UNION_DATA:
+ YangUnion parentUnion = (YangUnion) tmpData;
+ /*
+ * In case parent of union is again a union, name of the
+ * child union is parent union name suffixed with running
+ * integer number, this is done because under union there
+ * could be multiple child union types.
+ */
+ unionNode.setName(parentUnion.getName() + UNION_CLASS_SUFFIX + parentUnion.getChildUnionNumber());
+ // Increment the running number.
+ parentUnion.setChildUnionNumber(parentUnion.getChildUnionNumber() + 1);
+ // Add union as a child to parent union.
+ addChildToParentNode(listener, unionNode);
+ break;
+ case TYPEDEF_DATA:
+ YangTypeDef typeDef = (YangTypeDef) tmpData;
+ // Set the name of union same as typedef name.
+ unionNode.setName(typeDef.getName() + UNION_CLASS_SUFFIX);
+ // Add union as a child to parent type def.
+ addChildToParentNode(listener, unionNode);
+ break;
+ // TODO deviate.
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, TYPE_DATA,
+ ((YangType<?>) typeData).getDataTypeName(), ENTRY));
+ }
+ listener.getParsedDataStack().push(typeData);
+ listener.getParsedDataStack().push(unionNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, UNION_DATA, "", ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (union), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processUnionExit(TreeWalkListener listener,
+ GeneratedYangParser.UnionSpecificationContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, UNION_DATA, "", EXIT);
+
+ Parsable tmpUnionNode = listener.getParsedDataStack().peek();
+ if (tmpUnionNode instanceof YangUnion) {
+ YangUnion unionNode = (YangUnion) tmpUnionNode;
+ listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, UNION_DATA, "", EXIT);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case TYPE_DATA: {
+ YangType<YangUnion> typeNode = (YangType<YangUnion>) tmpNode;
+ typeNode.setDataTypeExtendedInfo(unionNode);
+ break;
+ }
+ default:
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, UNION_DATA, "", EXIT));
+ }
+ } else {
+ throw new ParserException(
+ constructListenerErrorMessage(MISSING_CURRENT_HOLDER, UNION_DATA, "", EXIT));
+ }
+ }
+
+ /**
+ * Adds the union node to the parent holder.
+ *
+ * @param listener listener's object
+ * @param unionNode union node which needs to be added to parent
+ */
+ private static void addChildToParentNode(TreeWalkListener listener, YangUnion unionNode) {
+ if (!(listener.getParsedDataStack().peek() instanceof YangNode)) {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, UNION_DATA,
+ "", ENTRY));
+ } else {
+ YangNode curNode = (YangNode) listener.getParsedDataStack().peek();
+ try {
+ curNode.addChild(unionNode);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ UNION_DATA, "", ENTRY, e.getMessage()));
+ }
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UnitsListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UnitsListener.java
new file mode 100644
index 0000000..e7acccf
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UnitsListener.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.UNITS_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * units-stmt = units-keyword sep string optsep stmtend
+ *
+ * ANTLR grammar rule
+ * unitsStatement : UNITS_KEYWORD string STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "units"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class UnitsListener {
+
+ /**
+ * Creates a new units listener.
+ */
+ private UnitsListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar
+ * rule (units), performs validation and updates the data model
+ * tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processUnitsEntry(TreeWalkListener listener,
+ GeneratedYangParser.UnitsStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, UNITS_DATA, ctx.string().getText(), ENTRY);
+
+ Parsable tmpData = listener.getParsedDataStack().peek();
+ switch (tmpData.getYangConstructType()) {
+ case LEAF_DATA:
+ YangLeaf leaf = (YangLeaf) tmpData;
+ leaf.setUnits(ctx.string().getText());
+ break;
+ case LEAF_LIST_DATA:
+ YangLeafList leafList = (YangLeafList) tmpData;
+ leafList.setUnits(ctx.string().getText());
+ break;
+ case TYPEDEF_DATA:
+ // TODO
+ break;
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, UNITS_DATA,
+ ctx.string().getText(), ENTRY));
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UsesListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UsesListener.java
new file mode 100644
index 0000000..2240c16
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/UsesListener.java
@@ -0,0 +1,223 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangAugment;
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNodeIdentifier;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.YangUses;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.linker.impl.YangResolutionInfoImpl;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.addResolutionInfo;
+import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.DESCRIPTION_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REFERENCE_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.STATUS_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.USES_DATA;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.WHEN_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerCollisionDetector.detectCollidingChildUtil;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidNodeIdentifier;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
+import static org.onosproject.yangutils.translator.tojava.YangDataModelFactory.getYangUsesNode;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * data-def-stmt = container-stmt /
+ * leaf-stmt /
+ * leaf-list-stmt /
+ * list-stmt /
+ * choice-stmt /
+ * anyxml-stmt /
+ * uses-stmt
+ *
+ * uses-stmt = uses-keyword sep identifier-ref-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *(refine-stmt stmtsep)
+ * *(uses-augment-stmt stmtsep)
+ * "}")
+ *
+ * ANTLR grammar rule
+ * dataDefStatement : containerStatement
+ * | leafStatement
+ * | leafListStatement
+ * | listStatement
+ * | choiceStatement
+ * | usesStatement;
+ *
+ * usesStatement : USES_KEYWORD string (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement
+ * | statusStatement | descriptionStatement | referenceStatement | refineStatement
+ * | usesAugmentStatement)* RIGHT_CURLY_BRACE);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "uses"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class UsesListener {
+
+ /**
+ * Creates a new uses listener.
+ */
+ private UsesListener() {
+ }
+
+ /**
+ * It is called when parser enters grammar rule (uses), it perform
+ * validations and updates the data model tree.
+ *
+ * @param listener listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processUsesEntry(TreeWalkListener listener, GeneratedYangParser.UsesStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, USES_DATA, ctx.string().getText(), ENTRY);
+
+ // Validate sub statement cardinality.
+ validateSubStatementsCardinality(ctx);
+
+ // Check for identifier collision
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+
+ detectCollidingChildUtil(listener, line, charPositionInLine, ctx.string().getText(), USES_DATA);
+ Parsable curData = listener.getParsedDataStack().peek();
+
+ if (curData instanceof YangModule || curData instanceof YangSubModule
+ || curData instanceof YangContainer || curData instanceof YangList
+ || curData instanceof YangUses || curData instanceof YangAugment
+ || curData instanceof YangCase || curData instanceof YangGrouping
+ || curData instanceof YangInput || curData instanceof YangOutput
+ || curData instanceof YangNotification) {
+
+ YangUses usesNode = getYangUsesNode(JAVA_GENERATION);
+ YangNodeIdentifier nodeIdentifier = getValidNodeIdentifier(ctx.string().getText(), USES_DATA, ctx);
+ usesNode.setNodeIdentifier(nodeIdentifier);
+ YangNode curNode = (YangNode) curData;
+
+ try {
+ curNode.addChild(usesNode);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ USES_DATA, ctx.string().getText(), ENTRY, e.getMessage()));
+ }
+ listener.getParsedDataStack().push(usesNode);
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER,
+ USES_DATA, ctx.string().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * It is called when parser exits from grammar rule (uses), it perform
+ * validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processUsesExit(TreeWalkListener listener,
+ GeneratedYangParser.UsesStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, USES_DATA, ctx.string().getText(), EXIT);
+
+ Parsable parsableUses = listener.getParsedDataStack().pop();
+ if (!(parsableUses instanceof YangUses)) {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, USES_DATA,
+ ctx.string().getText(), EXIT));
+ }
+ YangUses uses = (YangUses) parsableUses;
+ int errorLine = ctx.getStart().getLine();
+ int errorPosition = ctx.getStart().getCharPositionInLine();
+
+ // Parent YANG node of uses to be added in resolution information.
+ Parsable parentNode = listener.getParsedDataStack().peek();
+
+ // Verify parent node of leaf
+ if (!(parentNode instanceof YangNode)) {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, USES_DATA,
+ ctx.string().getText(), EXIT));
+ }
+
+ // Add resolution information to the list
+ YangResolutionInfoImpl resolutionInfo = new YangResolutionInfoImpl<YangUses>(uses,
+ (YangNode) parentNode, errorLine,
+ errorPosition);
+ addToResolutionList(resolutionInfo, ctx);
+ }
+
+ // TODO linker to handle collision scenarios like leaf obtained by uses, conflicts with some existing leaf.
+
+ /**
+ * Validates the cardinality of case sub-statements as per grammar.
+ *
+ * @param ctx context object of the grammar rule
+ */
+ private static void validateSubStatementsCardinality(GeneratedYangParser.UsesStatementContext ctx) {
+ validateCardinalityMaxOne(ctx.whenStatement(), WHEN_DATA, USES_DATA, ctx.string().getText());
+ validateCardinalityMaxOne(ctx.statusStatement(), STATUS_DATA, USES_DATA, ctx.string().getText());
+ validateCardinalityMaxOne(ctx.descriptionStatement(), DESCRIPTION_DATA, USES_DATA, ctx.string().getText());
+ validateCardinalityMaxOne(ctx.referenceStatement(), REFERENCE_DATA, USES_DATA, ctx.string().getText());
+ }
+
+ /**
+ * Add to resolution list.
+ *
+ * @param resolutionInfo resolution information.
+ * @param ctx context object of the grammar rule
+ */
+ private static void addToResolutionList(YangResolutionInfoImpl<YangUses> resolutionInfo,
+ GeneratedYangParser.UsesStatementContext ctx) {
+
+ try {
+ addResolutionInfo(resolutionInfo);
+ } catch (DataModelException e) {
+ throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+ USES_DATA, ctx.string().getText(), EXIT, e.getMessage()));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ValueListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ValueListener.java
new file mode 100644
index 0000000..39efa6b
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ValueListener.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * value-stmt = value-keyword sep integer-value stmtend
+ *
+ * ANTLR grammar rule
+ * valueStatement : VALUE_KEYWORD ((MINUS INTEGER) | INTEGER) STMTEND;
+ */
+
+import org.onosproject.yangutils.datamodel.YangEnum;
+import org.onosproject.yangutils.datamodel.YangEnumeration;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.VALUE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIntegerValue;
+
+/**
+ * Represents listener based call back function corresponding to the "value"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class ValueListener {
+
+ /**
+ * Creates a new value listener.
+ */
+ private ValueListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (value), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processValueEntry(TreeWalkListener listener, GeneratedYangParser.ValueStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, VALUE_DATA, ctx.value().getText(), ENTRY);
+
+ // Validate value
+ int value = getValidIntegerValue(ctx.value().getText(), VALUE_DATA, ctx);
+
+ // Obtain the node of the stack.
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case ENUM_DATA: {
+ YangEnum enumNode = (YangEnum) tmpNode;
+ if (!isEnumValueValid(listener, ctx, value)) {
+ ParserException parserException = new ParserException("Duplicate Value Entry");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ enumNode.setValue(value);
+ break;
+ }
+ default:
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, VALUE_DATA, ctx.value().getText(), ENTRY));
+ }
+ }
+
+ /**
+ * Validates ENUM value uniqueness.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ * @param value enum value
+ * @return validation result
+ */
+ private static boolean isEnumValueValid(TreeWalkListener listener, GeneratedYangParser.ValueStatementContext ctx,
+ int value) {
+ Parsable enumNode = listener.getParsedDataStack().pop();
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, VALUE_DATA, ctx.value().getText(), ENTRY);
+
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case ENUMERATION_DATA: {
+ YangEnumeration yangEnumeration = (YangEnumeration) tmpNode;
+ for (YangEnum curEnum : yangEnumeration.getEnumSet()) {
+ if (value == curEnum.getValue()) {
+ listener.getParsedDataStack().push(enumNode);
+ return false;
+ }
+ }
+ listener.getParsedDataStack().push(enumNode);
+ return true;
+ }
+ default:
+ listener.getParsedDataStack().push(enumNode);
+ throw new ParserException(
+ constructListenerErrorMessage(INVALID_HOLDER, VALUE_DATA, ctx.value().getText(), ENTRY));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/VersionListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/VersionListener.java
new file mode 100644
index 0000000..80caaa2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/VersionListener.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidVersion;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.VERSION_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * module-header-stmts = ;; these stmts can appear in any order
+ * [yang-version-stmt stmtsep]
+ * namespace-stmt stmtsep
+ * prefix-stmt stmtsep
+ *
+ * submodule-header-stmts =
+ * ;; these stmts can appear in any order
+ * [yang-version-stmt stmtsep]
+ * belongs-to-stmt stmtsep
+ *
+ * yang-version-stmt = yang-version-keyword sep yang-version-arg-str
+ * optsep stmtend
+ *
+ *
+ * ANTLR grammar rule
+ * module_header_statement : yang_version_stmt? namespace_stmt prefix_stmt
+ * | yang_version_stmt? prefix_stmt namespace_stmt
+ * | namespace_stmt yang_version_stmt? prefix_stmt
+ * | namespace_stmt prefix_stmt yang_version_stmt?
+ * | prefix_stmt namespace_stmt yang_version_stmt?
+ * | prefix_stmt yang_version_stmt? namespace_stmt?
+ * ;
+ * submodule_header_statement : yang_version_stmt? belongs_to_stmt
+ * | belongs_to_stmt yang_version_stmt?
+ * ;
+ * yang_version_stmt : YANG_VERSION_KEYWORD version STMTEND;
+ * version : string;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the "version"
+ * rule defined in ANTLR grammar file for corresponding ABNF rule in RFC 6020.
+ */
+public final class VersionListener {
+
+ /**
+ * Creates a new version listener.
+ */
+ private VersionListener() {
+ }
+
+ /**
+ * It is called when parser receives an input matching the grammar rule
+ * (version), perform validations and update the data model tree.
+ *
+ * @param listener Listener's object
+ * @param ctx context object of the grammar rule
+ */
+ public static void processVersionEntry(TreeWalkListener listener,
+ GeneratedYangParser.YangVersionStatementContext ctx) {
+
+ // Check for stack to be non empty.
+ checkStackIsNotEmpty(listener, MISSING_HOLDER, VERSION_DATA, ctx.version().getText(), ENTRY);
+
+ byte version = getValidVersion(ctx);
+
+ // Obtain the node of the stack.
+ Parsable tmpNode = listener.getParsedDataStack().peek();
+ switch (tmpNode.getYangConstructType()) {
+ case MODULE_DATA: {
+ YangModule module = (YangModule) tmpNode;
+ module.setVersion(version);
+ break;
+ }
+ case SUB_MODULE_DATA: {
+ YangSubModule subModule = (YangSubModule) tmpNode;
+ subModule.setVersion(version);
+ break;
+ }
+ default:
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, VERSION_DATA,
+ ctx.version().getText(), ENTRY));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/package-info.java
new file mode 100644
index 0000000..240cd55
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Provide call back functions for listeners based tree walk.
+ */
+package org.onosproject.yangutils.parser.impl.listeners;
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/package-info.java
new file mode 100644
index 0000000..d935f7b
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+/**
+ * Parse the YANG information from ANTLR generated parse tree.
+ */
+package org.onosproject.yangutils.parser.impl;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/AugmentListenerUtil.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/AugmentListenerUtil.java
new file mode 100644
index 0000000..1b2009e
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/AugmentListenerUtil.java
@@ -0,0 +1,309 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.parserutils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.CollisionDetector;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNodeIdentifier;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.AUGMENT_DATA;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+
+/**
+ * Represents a utility which provides listener utilities augment node.
+ */
+public final class AugmentListenerUtil {
+
+ /**
+ * Prefix to be added to generated java file for augment node.
+ */
+ private static final String AUGMENTED = "Augmented";
+
+ /**
+ * The number of time augment has updated the same target node in same module/submodule.
+ */
+ private static int occurrenceCount = 1;
+
+ /**
+ * List of names for augment's generated java file.
+ */
+ private static List<String> augmentJavaFileNameList = new ArrayList<>();
+
+ private static final int ONE = 1;
+ private static final int TWO = 2;
+ private static final int ZERO = 0;
+
+ /**
+ * Creates an instance of augment java file name generator utility.
+ */
+ private AugmentListenerUtil() {
+ }
+
+ /**
+ * Sets the augment java file name list.
+ *
+ * @param nameList name list
+ */
+ private static void setAugmentJavaFileNameList(List<String> nameList) {
+ augmentJavaFileNameList = nameList;
+ }
+
+ /**
+ * Returns augment java file name list.
+ *
+ * @return augment java file name list
+ */
+ public static List<String> getAugmentJavaFileNameList() {
+ return augmentJavaFileNameList;
+ }
+
+ /**
+ * Sets occurrence count.
+ *
+ * @param occurrence occurrence count
+ */
+ private static void setOccurrenceCount(int occurrence) {
+ occurrenceCount = occurrence;
+ }
+
+ /**
+ * Returns occurrence count.
+ *
+ * @return occurrence count
+ */
+ private static int getOccurrenceCount() {
+ return occurrenceCount;
+ }
+
+ /**
+ * Generates name for augment node also detects collision for java file generation of augment node when
+ * augment is updating the same target node in same parent multiple times.
+ *
+ * @param curData parsable data
+ * @param targetNodes list of target nodes
+ * @param listener tree walk listener
+ * @return name for augment node
+ */
+ public static String generateNameForAugmentNode(Parsable curData, List<YangNodeIdentifier> targetNodes,
+ TreeWalkListener listener) {
+
+ String curPrefix = getParentsPrefix((YangNode) curData);
+ YangNodeIdentifier nodeId = targetNodes.get(targetNodes.size() - 1);
+ boolean isPrefix = isPrefixPresent(nodeId, curPrefix);
+ String generateName = createValidNameForAugment(nodeId, isPrefix);
+
+ if (listener.getParsedDataStack().peek() instanceof CollisionDetector) {
+ try {
+ ((CollisionDetector) listener.getParsedDataStack().peek()).detectCollidingChild(generateName,
+ AUGMENT_DATA);
+ } catch (DataModelException e) {
+ return updateNameWhenHasMultipleOuccrrence(nodeId, isPrefix);
+ }
+ }
+
+ clearOccurrenceCount();
+ return generateName;
+ }
+
+ /**
+ * Creates a name identifier for augment.
+ *
+ * @param nodeId node identifier
+ * @param isPrefix if prefix is present or it is not equals to parent's prefix
+ * @return valid name for augment
+ */
+ public static String createValidNameForAugment(YangNodeIdentifier nodeId, boolean isPrefix) {
+ getAugmentJavaFileNameList().add(createName(nodeId, isPrefix));
+ setAugmentJavaFileNameList(getAugmentJavaFileNameList());
+ return getAugmentJavaFileNameList().get(getAugmentJavaFileNameList().size() - 1);
+ }
+
+ /**
+ * Creates name for the current augment file.
+ *
+ * @param nodeId node identifier
+ * @param isPrefix if prefix is present or it is not equals to parent's prefix
+ */
+ private static String createName(YangNodeIdentifier nodeId, boolean isPrefix) {
+ if (isPrefix) {
+ return AUGMENTED + getCapitalCase(nodeId.getPrefix()) + getCapitalCase(nodeId.getName());
+ } else {
+ return AUGMENTED + getCapitalCase(nodeId.getName());
+ }
+ }
+
+ /**
+ * Updates occurrence count of augment.
+ */
+ private static void updateOccurenceCount() {
+ int count = getOccurrenceCount();
+ count++;
+ setOccurrenceCount(count);
+ }
+
+ /**
+ * Updates the list of name when augment has occurred multiple times to update the same target node
+ * and returns a valid name for augment node's generated java file.
+ *
+ * @param nodeId YANG node identifier
+ * @param isPrefix true if a prefix is present and it is not equals to parents prefix
+ * @return valid name for augment node
+ */
+ public static String updateNameWhenHasMultipleOuccrrence(YangNodeIdentifier nodeId, boolean isPrefix) {
+ String name = "";
+ updateOccurenceCount();
+
+ if (getOccurrenceCount() == TWO) {
+ String previousAugmentsName = getAugmentJavaFileNameList().get(getAugmentJavaFileNameList().size() - ONE);
+ getAugmentJavaFileNameList().remove(ZERO);
+ getAugmentJavaFileNameList().add(previousAugmentsName + ONE);
+ //TODO: update when already contains the name.
+ name = createName(nodeId, isPrefix) + TWO;
+ } else {
+ name = createName(nodeId, isPrefix) + getOccurrenceCount();
+ }
+ getAugmentJavaFileNameList().add(name);
+ return name;
+ }
+
+ /**
+ * Resets occurrence count to one.
+ */
+ public static void clearOccurrenceCount() {
+ setOccurrenceCount(ONE);
+ }
+
+ /**
+ * Returns true if a prefix is present and it is not equals to parents prefix.
+ *
+ * @param nodeId YANG node identifier
+ * @param parentsPrefix parent's prefix
+ * @return true if a prefix is present and it is not equals to parents prefix
+ */
+ private static boolean isPrefixPresent(YangNodeIdentifier nodeId, String parentsPrefix) {
+ return nodeId.getPrefix() != null && nodeId.getPrefix() != parentsPrefix;
+ }
+
+ /**
+ * Validates whether current node in target path is valid or not.
+ *
+ * @param curNode current YANG node
+ * @param targetNodes list of target nodes
+ * @param ctx augment statement context
+ */
+ public static void validateNodeInTargetPath(YangNode curNode, List<YangNodeIdentifier> targetNodes,
+ GeneratedYangParser.AugmentStatementContext ctx) {
+
+ curNode = curNode.getChild();
+ YangNode tempNode = validateCurrentTargetNode(targetNodes, curNode);
+ if (tempNode != null) {
+ switch (tempNode.getNodeType()) {
+ case CONTAINER_NODE:
+ break;
+ case LIST_NODE:
+ break;
+ case CHOICE_NODE:
+ break;
+ case CASE_NODE:
+ break;
+ case INPUT_NODE:
+ break;
+ case OUTPUT_NODE:
+ break;
+ case NOTIFICATION_NODE:
+ break;
+ default:
+ throw parserException(ctx);
+ }
+ } else {
+ throw parserException(ctx);
+ }
+ }
+
+ /**
+ * Validates whether nodes in target node list are valid or not.
+ *
+ * @param targetNodes target node
+ * @param curNode YANG node
+ * @return true or false
+ */
+ private static YangNode validateCurrentTargetNode(List<YangNodeIdentifier> targetNodes, YangNode curNode) {
+ YangNode tempNode = null;
+ while (curNode != null) {
+ tempNode = curNode;
+ for (int i = 1; i < targetNodes.size(); i++) {
+ if (curNode.getName().equals(targetNodes.get(i).getName())) {
+ if (curNode.getChild() != null && targetNodes.size() - 1 != i) {
+ curNode = curNode.getChild();
+ } else if (curNode.getChild() != null && targetNodes.size() - 1 == i) {
+ return curNode;
+ } else if (curNode.getChild() == null && targetNodes.size() - 1 == i) {
+ return curNode;
+ } else {
+ break;
+ }
+ } else {
+ curNode = tempNode;
+ break;
+ }
+ }
+ curNode = curNode.getNextSibling();
+ }
+ return null;
+ }
+
+ /**
+ * Builds parser exception.
+ *
+ * @param ctx augment statement context
+ * @return parser exception
+ */
+ public static ParserException parserException(GeneratedYangParser.AugmentStatementContext ctx) {
+ int line = ctx.getStart().getLine();
+ int charPositionInLine = ctx.getStart().getCharPositionInLine();
+ ParserException exception = new ParserException("invalid target node path.");
+ exception.setLine(line);
+ exception.setCharPosition(charPositionInLine);
+ return exception;
+ }
+
+ /**
+ * Returns parent nodes prefix.
+ *
+ * @param curNode current YANG node
+ * @return parent nodes prefix
+ */
+ public static String getParentsPrefix(YangNode curNode) {
+ String curPrefix = null;
+ if (curNode instanceof YangModule) {
+ curPrefix = ((YangModule) curNode).getPrefix();
+ } else if (curNode instanceof YangSubModule) {
+ curPrefix = ((YangSubModule) curNode).getPrefix();
+ }
+ return curPrefix;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerCollisionDetector.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerCollisionDetector.java
new file mode 100644
index 0000000..632f50d
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerCollisionDetector.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.parserutils;
+
+import org.onosproject.yangutils.datamodel.CollisionDetector;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+
+/**
+ * Represents the detector of YANG construct collision in a YANG file.
+ */
+public final class ListenerCollisionDetector {
+
+ /**
+ * Creates a new listener collision.
+ */
+ private ListenerCollisionDetector() {
+ }
+
+ /**
+ * Detects that the identifiers of all these child nodes must be unique
+ * within all cases in a choice.
+ *
+ * @param listener listener's object
+ * @param line line of identifier in YANG file, required for error
+ * reporting
+ * @param charPosition character position of identifier in YANG file,
+ * required for error reporting
+ * @param identifierName name for which uniqueness is to be detected
+ * @param constructType type of YANG construct for which collision check is
+ * to be performed
+ * @throws ParserException if identifier is not unique
+ */
+ public static void detectCollidingChildUtil(TreeWalkListener listener, int line, int charPosition,
+ String identifierName, YangConstructType constructType)
+ throws ParserException {
+
+ if (listener.getParsedDataStack().peek() instanceof CollisionDetector) {
+ try {
+ ((CollisionDetector) listener.getParsedDataStack().peek()).detectCollidingChild(
+ identifierName, constructType);
+ } catch (DataModelException e) {
+ ParserException parserException = new ParserException(e.getMessage());
+ parserException.setLine(line);
+ parserException.setCharPosition(charPosition);
+ throw parserException;
+ }
+ } else {
+ throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, constructType, identifierName,
+ EXIT));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorLocation.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorLocation.java
new file mode 100644
index 0000000..c1c2888
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorLocation.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.parserutils;
+
+/**
+ * Represents listener error location.
+ */
+public enum ListenerErrorLocation {
+ /**
+ * Represents that the error location is before processing.
+ */
+ ENTRY(),
+
+ /**
+ * Represents that the error location is before processing.
+ */
+ EXIT();
+
+ /**
+ * Returns the message corresponding to listener error location.
+ *
+ * @param errorLocation enum value for type of error
+ * @return message corresponding to listener error location
+ */
+ public static String getErrorLocationMessage(ListenerErrorLocation errorLocation) {
+
+ switch (errorLocation) {
+ case ENTRY:
+ return "before";
+ case EXIT:
+ return "after";
+ default:
+ return "during";
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorMessageConstruction.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorMessageConstruction.java
new file mode 100644
index 0000000..15b2170
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorMessageConstruction.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.parserutils;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.getYangConstructType;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.getErrorLocationMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.getErrorType;
+
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+
+/**
+ * Represents a utility to help construct detailed error message.
+ */
+public final class ListenerErrorMessageConstruction {
+
+ /**
+ * Creates a object of listen error message.
+ */
+ private ListenerErrorMessageConstruction() {
+ }
+
+ /**
+ * Constructs message for error with extended information and returns the
+ * same.
+ *
+ * @param errorType error type needs to be set in error message
+ * @param yangConstructType type of parsable data in which error occurred
+ * @param parsableDataTypeName identifier/string of parsable data type in
+ * which error occurred
+ * @param errorLocation location where error occurred
+ * @param extendedErrorInformation extended error information
+ * @return constructed error message
+ */
+ public static String constructExtendedListenerErrorMessage(ListenerErrorType errorType,
+ YangConstructType yangConstructType,
+ String parsableDataTypeName,
+ ListenerErrorLocation errorLocation,
+ String extendedErrorInformation) {
+ String newErrorMessage;
+ newErrorMessage = constructListenerErrorMessage(errorType, yangConstructType, parsableDataTypeName,
+ errorLocation)
+ + "\n"
+ + "Error Information: "
+ + extendedErrorInformation;
+ return newErrorMessage;
+ }
+
+ /**
+ * Constructs message for error during listener based tree walk and returns
+ * the same.
+ *
+ * @param errorType error type needs to be set in error message
+ * @param yangConstructType type of parsable data in which error occurred
+ * @param parsableDataTypeName identifier/string of parsable data type in
+ * which error occurred
+ * @param errorLocation location where error occurred
+ * @return constructed error message
+ */
+ public static String constructListenerErrorMessage(ListenerErrorType errorType,
+ YangConstructType yangConstructType,
+ String parsableDataTypeName,
+ ListenerErrorLocation errorLocation) {
+
+ String errorMessage;
+
+ errorMessage = "Internal parser error detected: " + getErrorType(errorType) + " "
+ + getYangConstructType(yangConstructType);
+
+ if (!parsableDataTypeName.isEmpty()) {
+ errorMessage = errorMessage + " \"" + parsableDataTypeName + "\" ";
+ } else {
+ errorMessage = errorMessage + " ";
+
+ }
+ errorMessage = errorMessage + getErrorLocationMessage(errorLocation) + " processing.";
+ return errorMessage;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorType.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorType.java
new file mode 100644
index 0000000..f1cb284
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerErrorType.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.parserutils;
+
+/**
+ * Represents listener error type.
+ */
+public enum ListenerErrorType {
+ /**
+ * Represents the parent holder in parsable stack for given YANG construct
+ * is invalid.
+ */
+ INVALID_HOLDER(),
+
+ /**
+ * Represents the parent holder in parsable stack for given YANG construct
+ * is missing.
+ */
+ MISSING_HOLDER(),
+
+ /**
+ * Represents the current holder in parsable stack for given YANG construct
+ * is missing.
+ */
+ MISSING_CURRENT_HOLDER(),
+
+ /**
+ * Represents that the child in parsable stack for given YANG construct is
+ * invalid.
+ */
+ INVALID_CHILD(),
+
+ /**
+ * Represents that the cardinality for given YANG construct is invalid.
+ */
+ INVALID_CARDINALITY(),
+
+ /**
+ * Represents that the entry is duplicate.
+ */
+ DUPLICATE_ENTRY(),
+
+ /**
+ * Represents that the content is invalid.
+ */
+ INVALID_CONTENT(),
+
+ /**
+ * Represents that the identifier collision is detected.
+ */
+ IDENTIFIER_COLLISION(),
+
+ /**
+ * Represents that some of earlier parsed data is not handled correctly.
+ */
+ UNHANDLED_PARSED_DATA();
+
+ /**
+ * Returns the message corresponding to listener error type.
+ *
+ * @param errorType enum value for type of error
+ * @return message corresponding to listener error type
+ */
+ public static String getErrorType(ListenerErrorType errorType) {
+
+ switch (errorType) {
+ case INVALID_HOLDER:
+ return "Invalid holder for";
+ case MISSING_HOLDER:
+ return "Missing holder at";
+ case MISSING_CURRENT_HOLDER:
+ return "Missing";
+ case INVALID_CHILD:
+ return "Invalid child in";
+ case INVALID_CARDINALITY:
+ return "Invalid cardinality in";
+ case DUPLICATE_ENTRY:
+ return "Duplicate";
+ case INVALID_CONTENT:
+ return "Invalid content in";
+ case IDENTIFIER_COLLISION:
+ return "Identifier collision detected for";
+ case UNHANDLED_PARSED_DATA:
+ return "Unhandled parsed data at";
+ default:
+ return "Problem in";
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerUtil.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerUtil.java
new file mode 100644
index 0000000..d05c8d0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerUtil.java
@@ -0,0 +1,376 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.parserutils;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.onosproject.yangutils.datamodel.YangNodeIdentifier;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+
+import static org.onosproject.yangutils.utils.UtilConstants.ADD;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.UtilConstants.COLON;
+import static org.onosproject.yangutils.utils.UtilConstants.CARET;
+import static org.onosproject.yangutils.utils.UtilConstants.CURRENTLY_UNSUPPORTED;
+import static org.onosproject.yangutils.utils.UtilConstants.QUOTES;
+import static org.onosproject.yangutils.utils.UtilConstants.HYPHEN;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.TRUE;
+import static org.onosproject.yangutils.utils.UtilConstants.FALSE;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_FILE_ERROR;
+import static org.onosproject.yangutils.utils.UtilConstants.IDENTITYREF;
+import static org.onosproject.yangutils.utils.UtilConstants.LEAFREF;
+import static org.onosproject.yangutils.utils.UtilConstants.INSTANCE_IDENTIFIER;
+
+/**
+ * Represents an utility for listener.
+ */
+public final class ListenerUtil {
+
+ private static final Pattern IDENTIFIER_PATTERN = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_.-]*");
+ private static final String DATE_PATTERN = "[0-9]{4}-([0-9]{2}|[0-9])-([0-9]{2}|[0-9])";
+ private static final String NON_NEGATIVE_INTEGER_PATTERN = "[0-9]+";
+ private static final Pattern INTEGER_PATTERN = Pattern.compile("[-][0-9]+|[0-9]+");
+ private static final String XML = "xml";
+ private static final String ONE = "1";
+ private static final int IDENTIFIER_LENGTH = 64;
+ private static final String DATE_FORMAT = "yyyy-MM-dd";
+
+ /**
+ * Creates a new listener util.
+ */
+ private ListenerUtil() {
+ }
+
+ /**
+ * Removes doubles quotes and concatenates if string has plus symbol.
+ *
+ * @param yangStringData string from yang file
+ * @return concatenated string after removing double quotes
+ */
+ public static String removeQuotesAndHandleConcat(String yangStringData) {
+
+ yangStringData = yangStringData.replace("\"", EMPTY_STRING);
+ String[] tmpData = yangStringData.split(Pattern.quote(ADD));
+ StringBuilder builder = new StringBuilder();
+ for (String yangString : tmpData) {
+ builder.append(yangString);
+ }
+ return builder.toString();
+ }
+
+ /**
+ * Validates identifier and returns concatenated string if string contains plus symbol.
+ *
+ * @param identifier string from yang file
+ * @param yangConstruct yang construct for creating error message
+ * @param ctx yang construct's context to get the line number and character position
+ * @return concatenated string after removing double quotes
+ */
+ public static String getValidIdentifier(String identifier, YangConstructType yangConstruct, ParserRuleContext ctx) {
+
+ String identifierString = removeQuotesAndHandleConcat(identifier);
+ ParserException parserException;
+
+ if (identifierString.length() > IDENTIFIER_LENGTH) {
+ parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " name " + identifierString + " is " +
+ "greater than 64 characters.");
+ } else if (!IDENTIFIER_PATTERN.matcher(identifierString).matches()) {
+ parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " name " + identifierString + " is not " +
+ "valid.");
+ } else if (identifierString.toLowerCase().startsWith(XML)) {
+ parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " identifier " + identifierString +
+ " must not start with (('X'|'x') ('M'|'m') ('L'|'l')).");
+ } else {
+ return identifierString;
+ }
+
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ /**
+ * Validates the revision date.
+ *
+ * @param dateToValidate input revision date
+ * @return validation result, true for success, false for failure
+ */
+ public static boolean isDateValid(String dateToValidate) {
+ if (dateToValidate == null || !dateToValidate.matches(DATE_PATTERN)) {
+ return false;
+ }
+
+ SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
+ sdf.setLenient(false);
+
+ try {
+ //if not valid, it will throw ParseException
+ sdf.parse(dateToValidate);
+ } catch (ParseException e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Validates YANG version.
+ *
+ * @param ctx version context object of the grammar rule
+ * @return valid version
+ */
+ public static byte getValidVersion(GeneratedYangParser.YangVersionStatementContext ctx) {
+
+ String value = removeQuotesAndHandleConcat(ctx.version().getText());
+ if (!value.equals(ONE)) {
+ ParserException parserException = new ParserException("YANG file error: Input version not supported");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ return Byte.valueOf(value);
+ }
+
+ /**
+ * Validates non negative integer value.
+ *
+ * @param integerValue integer to be validated
+ * @param yangConstruct yang construct for creating error message
+ * @param ctx context object of the grammar rule
+ * @return valid non negative integer value
+ */
+ public static int getValidNonNegativeIntegerValue(String integerValue, YangConstructType yangConstruct,
+ ParserRuleContext ctx) {
+
+ String value = removeQuotesAndHandleConcat(integerValue);
+ if (!value.matches(NON_NEGATIVE_INTEGER_PATTERN)) {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " value " + value + " is not " +
+ "valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ int valueInInteger;
+ try {
+ valueInInteger = Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " value " + value + " is not " +
+ "valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ return valueInInteger;
+ }
+
+ /**
+ * Validates integer value.
+ *
+ * @param integerValue integer to be validated
+ * @param yangConstruct yang construct for creating error message
+ * @param ctx context object of the grammar rule
+ * @return valid integer value
+ */
+ public static int getValidIntegerValue(String integerValue, YangConstructType yangConstruct,
+ ParserRuleContext ctx) {
+
+ String value = removeQuotesAndHandleConcat(integerValue);
+ if (!INTEGER_PATTERN.matcher(value).matches()) {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " value " + value + " is not " +
+ "valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+
+ int valueInInteger;
+ try {
+ valueInInteger = Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " value " + value + " is not " +
+ "valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ return valueInInteger;
+ }
+
+ /**
+ * Validates boolean value.
+ *
+ * @param booleanValue value to be validated
+ * @param yangConstruct yang construct for creating error message
+ * @param ctx context object of the grammar rule
+ * @return boolean value either true or false
+ */
+ public static boolean getValidBooleanValue(String booleanValue, YangConstructType yangConstruct,
+ ParserRuleContext ctx) {
+
+ String value = removeQuotesAndHandleConcat(booleanValue);
+ if (value.equals(TRUE)) {
+ return true;
+ } else if (value.equals(FALSE)) {
+ return false;
+ } else {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " value " + value + " is not " +
+ "valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ }
+
+ /**
+ * Sets current date and makes it in usable format for revision.
+ *
+ * @return usable current date format for revision
+ */
+ public static String setCurrentDateForRevision() {
+
+ Calendar date = Calendar.getInstance();
+ SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
+ String dateForRevision = dateFormat.format(date.getTime()).replaceAll(SLASH, HYPHEN).replaceAll(SPACE,
+ EMPTY_STRING);
+ return dateForRevision;
+ }
+
+ /**
+ * Checks and return valid node identifier.
+ *
+ * @param nodeIdentifierString string from yang file
+ * @param yangConstruct yang construct for creating error message
+ * @param ctx yang construct's context to get the line number and character position
+ * @return valid node identifier
+ */
+ public static YangNodeIdentifier getValidNodeIdentifier(String nodeIdentifierString,
+ YangConstructType yangConstruct, ParserRuleContext ctx) {
+ String tmpIdentifierString = removeQuotesAndHandleConcat(nodeIdentifierString);
+ String[] tmpData = tmpIdentifierString.split(Pattern.quote(COLON));
+ if (tmpData.length == 1) {
+ YangNodeIdentifier nodeIdentifier = new YangNodeIdentifier();
+ checkForUnsupportedTypes(tmpData[0], yangConstruct, ctx);
+ nodeIdentifier.setName(getValidIdentifier(tmpData[0], yangConstruct, ctx));
+ return nodeIdentifier;
+ } else if (tmpData.length == 2) {
+ YangNodeIdentifier nodeIdentifier = new YangNodeIdentifier();
+ nodeIdentifier.setPrefix(getValidIdentifier(tmpData[0], yangConstruct, ctx));
+ nodeIdentifier.setName(getValidIdentifier(tmpData[1], yangConstruct, ctx));
+ return nodeIdentifier;
+ } else {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstruct) + " name " + nodeIdentifierString +
+ " is not valid.");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ }
+
+ /**
+ * Checks whether the type is an unsupported type.
+ *
+ * @param typeName name of the type
+ * @param yangConstruct yang construct to check if it is type
+ * @param ctx yang construct's context to get the line number and character position
+ */
+ private static void checkForUnsupportedTypes(String typeName,
+ YangConstructType yangConstruct, ParserRuleContext ctx) {
+
+ if (yangConstruct == YangConstructType.TYPE_DATA) {
+ if (typeName.equalsIgnoreCase(LEAFREF)) {
+ handleUnsupportedYangConstruct(YangConstructType.LEAFREF_DATA,
+ ctx, CURRENTLY_UNSUPPORTED);
+ } else if (typeName.equalsIgnoreCase(IDENTITYREF)) {
+ handleUnsupportedYangConstruct(YangConstructType.IDENTITYREF_DATA,
+ ctx, CURRENTLY_UNSUPPORTED);
+ } else if (typeName.equalsIgnoreCase(INSTANCE_IDENTIFIER)) {
+ handleUnsupportedYangConstruct(YangConstructType.INSTANCE_IDENTIFIER_DATA,
+ ctx, CURRENTLY_UNSUPPORTED);
+ }
+ }
+ }
+
+ /**
+ * Checks and return valid absolute schema node id.
+ *
+ * @param argumentString string from yang file
+ * @param yangConstructType yang construct for creating error message
+ * @param ctx yang construct's context to get the line number and character position
+ * @return target nodes list of absolute schema node id
+ */
+ public static List<YangNodeIdentifier> getValidAbsoluteSchemaNodeId(String argumentString,
+ YangConstructType yangConstructType, ParserRuleContext ctx) {
+
+ List<YangNodeIdentifier> targetNodes = new LinkedList<>();
+ YangNodeIdentifier yangNodeIdentifier;
+ String tmpSchemaNodeId = removeQuotesAndHandleConcat(argumentString);
+
+ // absolute-schema-nodeid = 1*("/" node-identifier)
+ if (!tmpSchemaNodeId.startsWith(SLASH)) {
+ ParserException parserException = new ParserException("YANG file error : " +
+ YangConstructType.getYangConstructType(yangConstructType) + " name " + argumentString +
+ "is not valid");
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ String[] tmpData = tmpSchemaNodeId.replaceFirst(CARET + SLASH, EMPTY_STRING).split(SLASH);
+ for (String nodeIdentifiers : tmpData) {
+ yangNodeIdentifier = getValidNodeIdentifier(nodeIdentifiers, yangConstructType, ctx);
+ targetNodes.add(yangNodeIdentifier);
+ }
+ return targetNodes;
+ }
+
+ /**
+ * Throws parser exception for unsupported YANG constructs.
+ *
+ * @param yangConstructType yang construct for creating error message
+ * @param ctx yang construct's context to get the line number and character position
+ * @param errorInfo error information
+ */
+ public static void handleUnsupportedYangConstruct(YangConstructType yangConstructType,
+ ParserRuleContext ctx, String errorInfo) {
+ ParserException parserException = new ParserException(YANG_FILE_ERROR
+ + QUOTES + YangConstructType.getYangConstructType(yangConstructType) + QUOTES
+ + errorInfo);
+ parserException.setLine(ctx.getStart().getLine());
+ parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerValidation.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerValidation.java
new file mode 100644
index 0000000..f5e98d0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerValidation.java
@@ -0,0 +1,237 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.parserutils;
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.datamodel.utils.YangConstructType;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.getYangConstructType;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+
+/**
+ * Represents a utility to carry out listener validation.
+ */
+public final class ListenerValidation {
+
+ /**
+ * Creates a new listener validation.
+ */
+ private ListenerValidation() {
+ }
+
+ /**
+ * Checks parsed data stack is not empty.
+ *
+ * @param listener Listener's object
+ * @param errorType error type needs to be set in error message
+ * @param yangConstructType type of parsable data in which error occurred
+ * @param parsableDataTypeName name of parsable data type in which error
+ * occurred
+ * @param errorLocation location where error occurred
+ */
+ public static void checkStackIsNotEmpty(TreeWalkListener listener, ListenerErrorType errorType,
+ YangConstructType yangConstructType, String parsableDataTypeName,
+ ListenerErrorLocation errorLocation) {
+
+ if (listener.getParsedDataStack().empty()) {
+ /*
+ * If stack is empty it indicates error condition, value of
+ * parsableDataTypeName will be null in case there is no name
+ * attached to parsable data type.
+ */
+ String message = constructListenerErrorMessage(errorType, yangConstructType, parsableDataTypeName,
+ errorLocation);
+ throw new ParserException(message);
+ }
+ }
+
+ /**
+ * Checks parsed data stack is empty.
+ *
+ * @param listener Listener's object
+ * @param errorType error type needs to be set in error message
+ * @param yangConstructType type of parsable data in which error occurred
+ * @param parsableDataTypeName name of parsable data type in which error
+ * occurred
+ * @param errorLocation location where error occurred
+ */
+ public static void checkStackIsEmpty(TreeWalkListener listener, ListenerErrorType errorType,
+ YangConstructType yangConstructType, String parsableDataTypeName,
+ ListenerErrorLocation errorLocation) {
+
+ if (!listener.getParsedDataStack().empty()) {
+ /*
+ * If stack is empty it indicates error condition, value of
+ * parsableDataTypeName will be null in case there is no name
+ * attached to parsable data type.
+ */
+ String message = constructListenerErrorMessage(errorType, yangConstructType, parsableDataTypeName,
+ errorLocation);
+ throw new ParserException(message);
+ }
+ }
+
+ /**
+ * Returns parent node config value, if top node does not specify a config
+ * statement then default value true is returned.
+ *
+ * @param listener listener's object
+ * @return true/false parent's config value
+ */
+ public static boolean getParentNodeConfig(TreeWalkListener listener) {
+
+ YangNode parentNode;
+ Parsable curData = listener.getParsedDataStack().peek();
+ if (curData instanceof YangNode) {
+ parentNode = ((YangNode) curData).getParent();
+ if (parentNode instanceof YangContainer) {
+ return ((YangContainer) parentNode).isConfig();
+ } else if (parentNode instanceof YangList) {
+ return ((YangList) parentNode).isConfig();
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Checks if a rule occurrences is as per the expected YANG grammar's
+ * cardinality.
+ *
+ * @param childContext child's context
+ * @param yangChildConstruct child construct for whom cardinality is to be
+ * validated
+ * @param yangParentConstruct parent construct
+ * @param parentName parent name
+ * @throws ParserException exception if cardinality check fails
+ */
+ public static void validateCardinalityMaxOne(List<?> childContext, YangConstructType yangChildConstruct,
+ YangConstructType yangParentConstruct, String parentName)
+ throws ParserException {
+
+ if (!childContext.isEmpty() && childContext.size() != 1) {
+ ParserException parserException = new ParserException("YANG file error: \""
+ + getYangConstructType(yangChildConstruct) + "\" is defined more than once in \""
+ + getYangConstructType(yangParentConstruct) + " " + parentName + "\".");
+
+ Iterator<?> context = childContext.iterator();
+ parserException.setLine(((ParserRuleContext) context.next()).getStart().getLine());
+ parserException.setCharPosition(((ParserRuleContext) context.next()).getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ }
+
+ /**
+ * Checks if a rule occurrences is exactly 1.
+ *
+ * @param childContext child's context
+ * @param yangChildConstruct child construct for whom cardinality is to be
+ * validated
+ * @param yangParentConstruct parent construct
+ * @param parentName parent name
+ * @param parentContext parents's context
+ * @throws ParserException exception if cardinality check fails
+ */
+ public static void validateCardinalityEqualsOne(List<?> childContext, YangConstructType yangChildConstruct,
+ YangConstructType yangParentConstruct, String parentName,
+ ParserRuleContext parentContext)
+ throws ParserException {
+
+ if (childContext.isEmpty()) {
+ ParserException parserException = new ParserException("YANG file error: Missing \""
+ + getYangConstructType(yangChildConstruct) + "\" in \"" + getYangConstructType(yangParentConstruct)
+ + " " + parentName + "\".");
+ parserException.setLine(parentContext.getStart().getLine());
+ parserException.setCharPosition(parentContext.getStart().getCharPositionInLine());
+ throw parserException;
+ } else if (!childContext.isEmpty() && childContext.size() != 1) {
+ Iterator<?> childcontext = childContext.iterator();
+ ParserException parserException = new ParserException("YANG file error: \""
+ + getYangConstructType(yangChildConstruct) + "\" is present more than once in \""
+ + getYangConstructType(yangParentConstruct) + " " + parentName + "\".");
+ parserException.setLine(((ParserRuleContext) childcontext.next()).getStart().getLine());
+ parserException.setCharPosition(((ParserRuleContext) childcontext.next()).getStart()
+ .getCharPositionInLine());
+ throw parserException;
+ }
+ }
+
+ /**
+ * Checks if a rule occurrences is minimum 1.
+ *
+ * @param childContext child's context
+ * @param yangChildConstruct child construct for whom cardinality is to be
+ * validated
+ * @param yangParentConstruct parent construct
+ * @param parentName parent name
+ * @param parentContext parents's context
+ * @throws ParserException exception if cardinality check fails
+ */
+ public static void validateCardinalityNonZero(List<?> childContext, YangConstructType yangChildConstruct,
+ YangConstructType yangParentConstruct, String parentName,
+ ParserRuleContext parentContext)
+ throws ParserException {
+
+ if (childContext.isEmpty()) {
+ ParserException parserException = new ParserException("YANG file error: Missing \""
+ + getYangConstructType(yangChildConstruct) + "\" in \"" + getYangConstructType(yangParentConstruct)
+ + " " + parentName + "\".");
+
+ parserException.setLine(parentContext.getStart().getLine());
+ parserException.setCharPosition(parentContext.getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ }
+
+ /**
+ * Checks if a either of one construct occurrence.
+ *
+ * @param child1Context first optional child's context
+ * @param yangChild1Construct first child construct for whom cardinality is
+ * to be validated
+ * @param child2Context second optional child's context
+ * @param yangChild2Construct second child construct for whom cardinality is
+ * to be validated
+ * @param yangParentConstruct parent construct
+ * @param parentName parent name
+ * @throws ParserException exception if cardinality check fails
+ */
+ public static void validateMutuallyExclusiveChilds(List<?> child1Context, YangConstructType yangChild1Construct,
+ List<?> child2Context, YangConstructType yangChild2Construct,
+ YangConstructType yangParentConstruct, String parentName)
+ throws ParserException {
+
+ if (!child1Context.isEmpty() && !child2Context.isEmpty()) {
+ ParserException parserException = new ParserException("YANG file error: \""
+ + getYangConstructType(yangChild1Construct) + "\" & \"" + getYangConstructType(yangChild2Construct)
+ + "\" should be mutually exclusive in \"" + getYangConstructType(yangParentConstruct) + " "
+ + parentName + "\".");
+
+ parserException.setLine(((ParserRuleContext) child2Context).getStart().getLine());
+ parserException.setCharPosition(((ParserRuleContext) child2Context).getStart().getCharPositionInLine());
+ throw parserException;
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ParseTreeErrorListener.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ParseTreeErrorListener.java
new file mode 100644
index 0000000..af81d6f
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ParseTreeErrorListener.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.parserutils;
+
+import org.antlr.v4.runtime.BaseErrorListener;
+import org.antlr.v4.runtime.RecognitionException;
+import org.antlr.v4.runtime.Recognizer;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+
+/**
+ * Represent the parse tree error listener.
+ * By default, ANTLR sends all errors to standard error, this is changed by
+ * providing this new implementation of interface ANTLRErrorListener. The
+ * interface has a syntaxError() method that applies to both lexer and parser.
+ */
+public class ParseTreeErrorListener extends BaseErrorListener {
+
+ @Override
+ public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
+ String msg, RecognitionException e) {
+
+ ParserException parserException = new ParserException(msg);
+ parserException.setLine(line);
+ parserException.setCharPosition(charPositionInLine);
+ throw parserException;
+ }
+}
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/package-info.java
new file mode 100644
index 0000000..9eafb00
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Provide common utils for parser implementation.
+ */
+package org.onosproject.yangutils.parser.impl.parserutils;
\ No newline at end of file
diff --git a/plugin/src/main/java/org/onosproject/yangutils/parser/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/parser/package-info.java
new file mode 100644
index 0000000..f039e68
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/parser/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+/**
+ * Interfaces to process YANG information from ANTLR generated listeners.
+ */
+package org.onosproject.yangutils.parser;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/YangFileInfo.java b/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/YangFileInfo.java
new file mode 100644
index 0000000..6c16aa2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/YangFileInfo.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.plugin.manager;
+
+import java.util.Objects;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.utils.ResolvableStatus;
+
+/**
+ * Represents YANG file information.
+ */
+public class YangFileInfo {
+
+ /**
+ * YANG file name.
+ */
+ private String yangFileName;
+
+ /**
+ * YANG file revision.
+ */
+ private String revision;
+
+ /**
+ * Data model node after parsing YANG file.
+ */
+ private YangNode rootNode;
+
+ /**
+ * Resolution status of YANG file.
+ */
+ private ResolvableStatus resolvableStatus;
+
+ /**
+ * Location for serialized files in case of inter-jar dependencies.
+ */
+ private String serializedFile;
+
+ /**
+ * Flag to know if the root node require to be translated.
+ */
+ private boolean isForTranslator = true;
+
+ /**
+ * Returns data model node for YANG file.
+ *
+ * @return data model node for YANG file
+ */
+ public YangNode getRootNode() {
+ return rootNode;
+ }
+
+ /**
+ * Sets data model node for YANG file.
+ *
+ * @param rootNode of the Yang file
+ */
+ public void setRootNode(YangNode rootNode) {
+ this.rootNode = rootNode;
+ }
+
+ /**
+ * Returns YANG file name.
+ *
+ * @return yangFileName YANG file name
+ */
+ public String getYangFileName() {
+ return yangFileName;
+ }
+
+ /**
+ * Sets YANG file name.
+ *
+ * @param yangFileName YANG file name
+ */
+ public void setYangFileName(String yangFileName) {
+ this.yangFileName = yangFileName;
+ }
+
+ /**
+ * Returns the revision of YANG file.
+ *
+ * @return revision of YANG file
+ */
+ public String getRevision() {
+ return revision;
+ }
+
+ /**
+ * Sets the revision of YANG file.
+ *
+ * @param revision revision of YANG file
+ */
+ public void setRevision(String revision) {
+ this.revision = revision;
+ }
+
+ /**
+ * Returns the resolution status of YANG file.
+ *
+ * @return resolution status of YANG file
+ */
+ public ResolvableStatus getResolvableStatus() {
+ return resolvableStatus;
+ }
+
+ /**
+ * Sets the resolution status of YANG file.
+ *
+ * @param resolvableStatus resolution status of YANG file
+ */
+ public void setResolvableStatus(ResolvableStatus resolvableStatus) {
+ this.resolvableStatus = resolvableStatus;
+ }
+
+ /**
+ * Returns serialized file of datamodel.
+ *
+ * @return the serialized file of datamodel
+ */
+ public String getSerializedFile() {
+ return serializedFile;
+ }
+
+ /**
+ * Sets serialized file of datamodel.
+ *
+ * @param serializedFile serialized file of datamodel
+ */
+ public void setSerializedFile(String serializedFile) {
+ this.serializedFile = serializedFile;
+ }
+
+ /**
+ * Returns true if node need to be translated.
+ *
+ * @return isForTranslator true if node need to be translated
+ */
+ public boolean isForTranslator() {
+ return isForTranslator;
+ }
+
+ /**
+ * Sets true if node need to be translated.
+ *
+ * @param isForTranslator true if node need to be translated
+ */
+ public void setForTranslator(boolean isForTranslator) {
+ this.isForTranslator = isForTranslator;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof YangFileInfo) {
+ final YangFileInfo other = (YangFileInfo) obj;
+ return Objects.equals(yangFileName, other.yangFileName);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(yangFileName);
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/YangUtilManager.java b/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/YangUtilManager.java
new file mode 100644
index 0000000..9339e4b
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/YangUtilManager.java
@@ -0,0 +1,374 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.plugin.manager;
+
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.maven.artifact.repository.ArtifactRepository;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugins.annotations.Component;
+import org.apache.maven.plugins.annotations.Mojo;
+import org.apache.maven.plugins.annotations.Parameter;
+import org.apache.maven.project.MavenProject;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.linker.YangLinker;
+import org.onosproject.yangutils.linker.exceptions.LinkerException;
+import org.onosproject.yangutils.linker.impl.YangLinkerManager;
+import org.onosproject.yangutils.parser.YangUtilsParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.YangUtilsParserManager;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+import org.onosproject.yangutils.translator.tojava.utils.YangToJavaNamingConflictUtil;
+import org.onosproject.yangutils.utils.io.impl.YangFileScanner;
+import org.sonatype.plexus.build.incremental.BuildContext;
+
+import static org.apache.maven.plugins.annotations.LifecyclePhase.GENERATE_SOURCES;
+import static org.apache.maven.plugins.annotations.ResolutionScope.COMPILE;
+import static org.onosproject.yangutils.translator.tojava.JavaCodeGeneratorUtil.generateJavaCode;
+import static org.onosproject.yangutils.translator.tojava.JavaCodeGeneratorUtil.translatorErrorHandler;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
+import static org.onosproject.yangutils.utils.UtilConstants.DEFAULT_BASE_PKG;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.addToCompilationRoot;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.copyYangFilesToTarget;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.deleteDirectory;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getDirectory;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.resolveInterJarDependencies;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.serializeDataModel;
+
+/**
+ * Represents ONOS YANG utility maven plugin.
+ * Goal of plugin is yang2java.
+ * Execution phase is generate-sources.
+ * requiresDependencyResolution at compile time.
+ */
+@Mojo(name = "yang2java", defaultPhase = GENERATE_SOURCES, requiresDependencyResolution = COMPILE,
+ requiresProject = true)
+public class YangUtilManager
+ extends AbstractMojo {
+
+ private YangNode rootNode;
+ // YANG file information set.
+ private Set<YangFileInfo> yangFileInfoSet = new HashSet<>();
+ private YangUtilsParser yangUtilsParser = new YangUtilsParserManager();
+ private YangLinker yangLinker = new YangLinkerManager();
+ private YangFileInfo curYangFileInfo = new YangFileInfo();
+
+ private static final String DEFAULT_PKG = SLASH + getPackageDirPathFromJavaJPackage(DEFAULT_BASE_PKG);
+
+ /**
+ * Source directory for YANG files.
+ */
+ @Parameter(property = "yangFilesDir", defaultValue = "src/main/yang")
+ private String yangFilesDir;
+
+ /**
+ * Source directory for generated files.
+ */
+ @Parameter(property = "genFilesDir", defaultValue = "src/main/java")
+ private String genFilesDir;
+
+ /**
+ * Base directory for project.
+ */
+ @Parameter(property = "basedir", defaultValue = "${basedir}")
+ private String baseDir;
+
+ /**
+ * Output directory.
+ */
+ @Parameter(property = "project.build.outputDirectory", required = true, defaultValue = "target/classes")
+ private String outputDirectory;
+
+ /**
+ * Current maven project.
+ */
+ @Parameter(property = "project", required = true, readonly = true, defaultValue = "${project}")
+ private MavenProject project;
+
+ /**
+ * Replacement required for period special character in the identifier.
+ */
+ @Parameter(property = "replacementForPeriod")
+ private String replacementForPeriod;
+
+ /**
+ * Replacement required for underscore special character in the identifier.
+ */
+ @Parameter(property = "replacementForUnderscore")
+ private String replacementForUnderscore;
+
+ /**
+ * Replacement required for hyphen special character in the identifier.
+ */
+ @Parameter(property = "replacementForHyphen")
+ private String replacementForHyphen;
+
+ /**
+ * Prefix which is required for adding with the identifier.
+ */
+ @Parameter(property = "prefixForIdentifier")
+ private String prefixForIdentifier;
+
+ /**
+ * Build context.
+ */
+ @Component
+ private BuildContext context;
+
+ @Parameter(readonly = true, defaultValue = "${localRepository}")
+ private ArtifactRepository localRepository;
+
+ @Parameter(readonly = true, defaultValue = "${project.remoteArtifactRepositories}")
+ private List<ArtifactRepository> remoteRepository;
+
+ @Override
+ public void execute()
+ throws MojoExecutionException, MojoFailureException {
+
+ try {
+
+ /*
+ * For deleting the generated code in previous build.
+ */
+ deleteDirectory(getDirectory(baseDir, genFilesDir) + DEFAULT_PKG);
+ deleteDirectory(getDirectory(baseDir, outputDirectory));
+
+ String searchDir = getDirectory(baseDir, yangFilesDir);
+ String codeGenDir = getDirectory(baseDir, genFilesDir) + SLASH;
+
+ // Creates conflict resolver and set values to it.
+ YangToJavaNamingConflictUtil conflictResolver = new YangToJavaNamingConflictUtil();
+ conflictResolver.setReplacementForPeriod(replacementForPeriod);
+ conflictResolver.setReplacementForHyphen(replacementForHyphen);
+ conflictResolver.setReplacementForUnderscore(replacementForUnderscore);
+ conflictResolver.setPrefixForIdentifier(prefixForIdentifier);
+ YangPluginConfig yangPlugin = new YangPluginConfig();
+ yangPlugin.setCodeGenDir(codeGenDir);
+ yangPlugin.setConflictResolver(conflictResolver);
+
+ /*
+ * Obtain the YANG files at a path mentioned in plugin and creates
+ * YANG file information set.
+ */
+ createYangFileInfoSet(YangFileScanner.getYangFiles(searchDir));
+
+ // Check if there are any file to translate, if not return.
+ if (getYangFileInfoSet() == null || getYangFileInfoSet().isEmpty()) {
+ // No files to translate
+ return;
+ }
+ // Resolve inter jar dependency.
+ resolveInterJardependency();
+
+ // Carry out the parsing for all the YANG files.
+ parseYangFileInfoSet();
+
+ // Resolve dependencies using linker.
+ resolveDependenciesUsingLinker();
+
+ // Perform translation to JAVA.
+ translateToJava(getYangFileInfoSet(), yangPlugin);
+
+ // Serialize data model.
+ serializeDataModel(getDirectory(baseDir, outputDirectory), getYangFileInfoSet(), project, true);
+
+ addToCompilationRoot(getDirectory(baseDir, genFilesDir), project, context);
+
+ copyYangFilesToTarget(getYangFileInfoSet(), getDirectory(baseDir, outputDirectory), project);
+ } catch (IOException | ParserException e) {
+ getLog().info(e);
+ String fileName = "";
+ if (getCurYangFileInfo() != null) {
+ fileName = getCurYangFileInfo().getYangFileName();
+ }
+ try {
+ translatorErrorHandler(getRootNode());
+ deleteDirectory(getDirectory(baseDir, genFilesDir) + DEFAULT_PKG);
+ } catch (IOException ex) {
+ throw new MojoExecutionException(
+ "Error handler failed to delete files for data model node.");
+ }
+ throw new MojoExecutionException(
+ "Exception occured due to " + e.getLocalizedMessage() + " in " + fileName
+ + " YANG file.");
+ }
+ }
+
+ /**
+ * Resolved inter-jar dependencies.
+ *
+ * @throws IOException when fails to do IO operations
+ */
+ public void resolveInterJardependency() throws IOException {
+ try {
+ List<YangNode> interJarResolvedNodes = resolveInterJarDependencies(project, localRepository,
+ remoteRepository, getDirectory(baseDir, outputDirectory));
+ for (YangNode node : interJarResolvedNodes) {
+ YangFileInfo dependentFileInfo = new YangFileInfo();
+ dependentFileInfo.setRootNode(node);
+ dependentFileInfo.setForTranslator(false);
+ dependentFileInfo.setYangFileName(node.getName());
+ getYangFileInfoSet().add(dependentFileInfo);
+ }
+ } catch (IOException e) {
+ throw new IOException("failed to resolve in interjar scenario.");
+ }
+ }
+
+ /**
+ * Links all the provided with the YANG file info set.
+ *
+ * @throws MojoExecutionException a violation in mojo excecution
+ */
+ public void resolveDependenciesUsingLinker()
+ throws MojoExecutionException {
+ for (YangFileInfo yangFileInfo : getYangFileInfoSet()) {
+ setCurYangFileInfo(yangFileInfo);
+ try {
+ yangLinker.resolveDependencies(getYangFileInfoSet());
+ } catch (LinkerException e) {
+ throw new MojoExecutionException(e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * Parses all the provided YANG files and generates YANG data model tree.
+ *
+ * @throws IOException a violation in IO
+ */
+ public void parseYangFileInfoSet()
+ throws IOException {
+ for (YangFileInfo yangFileInfo : getYangFileInfoSet()) {
+ setCurYangFileInfo(yangFileInfo);
+ if (yangFileInfo.isForTranslator()) {
+ try {
+ YangNode yangNode = yangUtilsParser.getDataModel(yangFileInfo.getYangFileName());
+ yangFileInfo.setRootNode(yangNode);
+ setRootNode(yangNode);
+ } catch (ParserException e) {
+ String logInfo = "Error in file: " + e.getFileName();
+ if (e.getLineNumber() != 0) {
+ logInfo = logInfo + " at line: " + e.getLineNumber() + " at position: "
+ + e.getCharPositionInLine();
+
+ }
+ if (e.getMessage() != null) {
+ logInfo = logInfo + NEW_LINE + e.getMessage();
+ }
+ getLog().info(logInfo);
+ throw e;
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns current root YANG node of data-model tree.
+ *
+ * @return current root YANG node of data-model tree
+ */
+ private YangNode getRootNode() {
+ return rootNode;
+ }
+
+ /**
+ * Sets current root YANG node of data-model tree.
+ *
+ * @param rootNode current root YANG node of data-model tree
+ */
+ private void setRootNode(YangNode rootNode) {
+ this.rootNode = rootNode;
+ }
+
+ /**
+ * Translates to java code corresponding to the YANG schema.
+ *
+ * @param yangFileInfoSet YANG file information
+ * @param yangPlugin YANG plugin config
+ * @throws IOException when fails to generate java code file the current
+ * node
+ */
+ public void translateToJava(Set<YangFileInfo> yangFileInfoSet, YangPluginConfig yangPlugin)
+ throws IOException {
+ Iterator<YangFileInfo> yangFileIterator = yangFileInfoSet.iterator();
+ while (yangFileIterator.hasNext()) {
+ YangFileInfo yangFileInfo = yangFileIterator.next();
+ setCurYangFileInfo(yangFileInfo);
+ if (yangFileInfo.isForTranslator()) {
+ generateJavaCode(yangFileInfo.getRootNode(), yangPlugin);
+ }
+ }
+ }
+
+ /**
+ * Creates a YANG file info set.
+ *
+ * @param yangFileList YANG files list
+ */
+ public void createYangFileInfoSet(List<String> yangFileList) {
+ for (String yangFile : yangFileList) {
+ YangFileInfo yangFileInfo = new YangFileInfo();
+ yangFileInfo.setYangFileName(yangFile);
+ getYangFileInfoSet().add(yangFileInfo);
+ }
+ }
+
+ /**
+ * Returns the YANG file info set.
+ *
+ * @return the YANG file info set
+ */
+ public Set<YangFileInfo> getYangFileInfoSet() {
+ return yangFileInfoSet;
+ }
+
+ /**
+ * Sets the YANG file info set.
+ *
+ * @param yangFileInfoSet the YANG file info set
+ */
+ public void setYangFileInfoSet(Set<YangFileInfo> yangFileInfoSet) {
+ this.yangFileInfoSet = yangFileInfoSet;
+ }
+
+ /**
+ * Returns current YANG file's info.
+ *
+ * @return the yangFileInfo
+ */
+ public YangFileInfo getCurYangFileInfo() {
+ return curYangFileInfo;
+ }
+
+ /**
+ * Sets current YANG file's info.
+ *
+ * @param yangFileInfo the yangFileInfo to set
+ */
+ public void setCurYangFileInfo(YangFileInfo yangFileInfo) {
+ curYangFileInfo = yangFileInfo;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/package-info.java
new file mode 100644
index 0000000..745e91c
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/plugin/manager/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * YANG utility maven plugin.
+ */
+package org.onosproject.yangutils.plugin.manager;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/exception/TranslatorException.java b/plugin/src/main/java/org/onosproject/yangutils/translator/exception/TranslatorException.java
new file mode 100644
index 0000000..cf2c07d
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/exception/TranslatorException.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.exception;
+
+/**
+ * Represents custom translator exception for translator's operations.
+ */
+public class TranslatorException extends RuntimeException {
+
+ private static final long serialVersionUID = 20160311L;
+ private String fileName;
+
+ /**
+ * Create a new translator exception.
+ */
+ public TranslatorException() {
+ super();
+ }
+
+ /**
+ * Creates a new translator exception with given message.
+ *
+ * @param message the detail of exception in string
+ */
+ public TranslatorException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new translator exception from given message and cause.
+ *
+ * @param message the detail of exception in string
+ * @param cause underlying cause of the error
+ */
+ public TranslatorException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Creates a new translator exception from cause.
+ *
+ * @param cause underlying cause of the error
+ */
+ public TranslatorException(final Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Returns generated file name for the exception.
+ *
+ * @return generated file name for the exception
+ */
+ public String getFileName() {
+ return this.fileName;
+ }
+
+ /**
+ * Sets file name in translator exception.
+ *
+ * @param fileName generated file name
+ */
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/exception/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/translator/exception/package-info.java
new file mode 100644
index 0000000..b88a8a3
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/exception/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Custom exception for translator.
+ */
+package org.onosproject.yangutils.translator.exception;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/translator/package-info.java
new file mode 100644
index 0000000..72ba2e4
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Translator to generate class definition corresponding to YANG definition.
+ */
+package org.onosproject.yangutils.translator;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/GeneratedJavaFileType.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/GeneratedJavaFileType.java
new file mode 100644
index 0000000..d4666c0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/GeneratedJavaFileType.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+/**
+ * Represents type of java files generated.
+ */
+public final class GeneratedJavaFileType {
+
+ /**
+ * Interface file.
+ */
+ public static final int INTERFACE_MASK = 1;
+
+ /**
+ * Builder interface file.
+ */
+ public static final int BUILDER_INTERFACE_MASK = 2;
+
+ /**
+ * Builder class file.
+ */
+ public static final int BUILDER_CLASS_MASK = 4;
+
+ /**
+ * Impl class file.
+ */
+ public static final int IMPL_CLASS_MASK = 8;
+
+ /**
+ * Interface and class file.
+ */
+ public static final int GENERATE_INTERFACE_WITH_BUILDER = INTERFACE_MASK
+ | BUILDER_INTERFACE_MASK | BUILDER_CLASS_MASK | IMPL_CLASS_MASK;
+
+ /**
+ * Java interface corresponding to rpc.
+ */
+ public static final int GENERATE_SERVICE_AND_MANAGER = 16;
+
+ /**
+ * Java class corresponding to YANG enumeration.
+ */
+ public static final int GENERATE_ENUM_CLASS = 32;
+
+ /**
+ * Java class corresponding to typedef.
+ */
+ public static final int GENERATE_TYPEDEF_CLASS = 64;
+
+ /**
+ * Java class corresponding to union.
+ */
+ public static final int GENERATE_UNION_CLASS = 128;
+
+ /**
+ * Java class corresponding to typedef.
+ */
+ public static final int GENERATE_TYPE_CLASS = GENERATE_TYPEDEF_CLASS
+ | GENERATE_UNION_CLASS;
+
+ /**
+ * Event class.
+ */
+ public static final int GENERATE_EVENT_CLASS = 256;
+
+ /**
+ * Event listener class.
+ */
+ public static final int GENERATE_EVENT_LISTENER_INTERFACE = 512;
+
+ /**
+ * Event listener class.
+ */
+ public static final int GENERATE_EVENT_SUBJECT_CLASS = 1024;
+
+ /**
+ * Creates an instance of generate java file type.
+ */
+ private GeneratedJavaFileType() {
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/GeneratedTempFileType.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/GeneratedTempFileType.java
new file mode 100644
index 0000000..2ffd282
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/GeneratedTempFileType.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+/**
+ * Represents type of temporary files generated.
+ */
+public final class GeneratedTempFileType {
+
+ /**
+ * Attributes definition temporary file.
+ */
+ public static final int ATTRIBUTES_MASK = 1;
+
+ /**
+ * Getter methods for interface.
+ */
+ public static final int GETTER_FOR_INTERFACE_MASK = 2;
+
+ /**
+ * Getter methods for class.
+ */
+ public static final int GETTER_FOR_CLASS_MASK = 4;
+
+ /**
+ * Setter methods for interface.
+ */
+ public static final int SETTER_FOR_INTERFACE_MASK = 8;
+
+ /**
+ * Setter methods for class.
+ */
+ public static final int SETTER_FOR_CLASS_MASK = 16;
+
+ /**
+ * Constructor method of class.
+ */
+ public static final int CONSTRUCTOR_IMPL_MASK = 32;
+
+ /**
+ * Hash code implementation of class.
+ */
+ public static final int HASH_CODE_IMPL_MASK = 64;
+
+ /**
+ * Equals implementation of class.
+ */
+ public static final int EQUALS_IMPL_MASK = 128;
+
+ /**
+ * To string implementation of class.
+ */
+ public static final int TO_STRING_IMPL_MASK = 256;
+
+ /**
+ * Of string implementation of class.
+ */
+ public static final int OF_STRING_IMPL_MASK = 512;
+
+ /**
+ * Constructor for type class like typedef, union.
+ */
+ public static final int CONSTRUCTOR_FOR_TYPE_MASK = 1024;
+
+ /**
+ * From string implementation of class.
+ */
+ public static final int FROM_STRING_IMPL_MASK = 2048;
+
+ /**
+ * Enum implementation of class.
+ */
+ public static final int ENUM_IMPL_MASK = 4096;
+
+ /**
+ * Rpc interface of module / sub module.
+ */
+ public static final int RPC_INTERFACE_MASK = 8192;
+
+ /**
+ * Rpc implementation of module / sub module.
+ */
+ public static final int RPC_IMPL_MASK = 16384;
+
+ /**
+ * Event enum implementation of class.
+ */
+ public static final int EVENT_ENUM_MASK = 32768;
+
+ /**
+ * Event method implementation of class.
+ */
+ public static final int EVENT_METHOD_MASK = 65536;
+
+ /**
+ * Event subject attribute implementation of class.
+ */
+ public static final int EVENT_SUBJECT_ATTRIBUTE_MASK = 131072;
+
+ /**
+ * Event subject getter implementation of class.
+ */
+ public static final int EVENT_SUBJECT_GETTER_MASK = 262144;
+
+ /**
+ * Event subject setter implementation of class.
+ */
+ public static final int EVENT_SUBJECT_SETTER_MASK = 524288;
+
+ /**
+ * Creates an instance of generated temp file type.
+ */
+ private GeneratedTempFileType() {
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaAttributeInfo.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaAttributeInfo.java
new file mode 100644
index 0000000..485878b
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaAttributeInfo.java
@@ -0,0 +1,200 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+
+/**
+ * Represents the attribute info corresponding to class/interface generated.
+ */
+public final class JavaAttributeInfo {
+
+ /**
+ * The data type info of attribute.
+ */
+ private YangType<?> attrType;
+
+ /**
+ * Name of the attribute.
+ */
+ private String name;
+
+ /**
+ * If the added attribute is a list of info.
+ */
+ private boolean isListAttr;
+
+ /**
+ * If the added attribute has to be accessed in a fully qualified manner.
+ */
+ private boolean isQualifiedName;
+
+ /**
+ * The class info will be used to set the attribute type and package info
+ * will be use for qualified name.
+ */
+ private JavaQualifiedTypeInfo importInfo;
+
+ /**
+ * Creates a java attribute info object.
+ */
+ private JavaAttributeInfo() {
+ }
+
+ /**
+ * Creates object of java attribute info.
+ *
+ * @param attrType YANG type
+ * @param name attribute name
+ * @param isListAttr is list attribute
+ * @param isQualifiedName is qualified name
+ */
+ public JavaAttributeInfo(YangType<?> attrType, String name, boolean isListAttr, boolean isQualifiedName) {
+ this.attrType = attrType;
+ this.name = name;
+ this.isListAttr = isListAttr;
+ this.isQualifiedName = isQualifiedName;
+ }
+
+ /**
+ * Returns the data type info of attribute.
+ *
+ * @return the data type info of attribute
+ */
+ public YangType<?> getAttributeType() {
+
+ if (attrType == null) {
+ throw new TranslatorException("Expected java attribute type is null");
+ }
+ return attrType;
+ }
+
+ /**
+ * Sets the data type info of attribute.
+ *
+ * @param type the data type info of attribute
+ */
+ public void setAttributeType(YangType<?> type) {
+ attrType = type;
+ }
+
+ /**
+ * Returns name of the attribute.
+ *
+ * @return name of the attribute
+ */
+ public String getAttributeName() {
+
+ if (name == null) {
+ throw new TranslatorException("Expected java attribute name is null");
+ }
+ return name;
+ }
+
+ /**
+ * Sets name of the attribute.
+ *
+ * @param attrName name of the attribute
+ */
+ public void setAttributeName(String attrName) {
+ name = attrName;
+ }
+
+ /**
+ * Returns if the added attribute is a list of info.
+ *
+ * @return the if the added attribute is a list of info
+ */
+ public boolean isListAttr() {
+ return isListAttr;
+ }
+
+ /**
+ * Sets if the added attribute is a list of info.
+ *
+ * @param isList if the added attribute is a list of info
+ */
+ public void setListAttr(boolean isList) {
+ isListAttr = isList;
+ }
+
+ /**
+ * Returns if the added attribute has to be accessed in a fully qualified
+ * manner.
+ *
+ * @return the if the added attribute has to be accessed in a fully
+ * qualified manner.
+ */
+ public boolean isQualifiedName() {
+ return isQualifiedName;
+ }
+
+ /**
+ * Sets if the added attribute has to be accessed in a fully qualified
+ * manner.
+ *
+ * @param isQualified if the added attribute has to be accessed in a fully
+ * qualified manner
+ */
+ public void setIsQualifiedAccess(boolean isQualified) {
+ isQualifiedName = isQualified;
+ }
+
+ /**
+ * Returns the import info for the attribute type. It will be null, if the type
+ * is basic built-in java type.
+ *
+ * @return import info
+ */
+ public JavaQualifiedTypeInfo getImportInfo() {
+ return importInfo;
+ }
+
+ /**
+ * Sets the import info for the attribute type.
+ *
+ * @param importInfo import info for the attribute type
+ */
+ public void setImportInfo(JavaQualifiedTypeInfo importInfo) {
+ this.importInfo = importInfo;
+ }
+
+ /**
+ * Returns java attribute info.
+ *
+ * @param importInfo java qualified type info
+ * @param attributeName attribute name
+ * @param attributeType attribute type
+ * @param isQualifiedAccess is the attribute a qualified access
+ * @param isListAttribute is list attribute
+ * @return java attribute info.
+ */
+ public static JavaAttributeInfo getAttributeInfoForTheData(JavaQualifiedTypeInfo importInfo, String attributeName,
+ YangType<?> attributeType, boolean isQualifiedAccess,
+ boolean isListAttribute) {
+
+ JavaAttributeInfo newAttr = new JavaAttributeInfo();
+ newAttr.setImportInfo(importInfo);
+ newAttr.setAttributeName(attributeName);
+ newAttr.setAttributeType(attributeType);
+ newAttr.setIsQualifiedAccess(isQualifiedAccess);
+ newAttr.setListAttr(isListAttribute);
+
+ return newAttr;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaCodeGenerator.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaCodeGenerator.java
new file mode 100644
index 0000000..277038c
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaCodeGenerator.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+/**
+ * Abstraction of an entity which provides Code generator functionalities.
+ */
+public interface JavaCodeGenerator {
+
+ /**
+ * Traverse the schema of application and generate corresponding code.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException when fails to translate the data model tree
+ */
+ void generateCodeEntry(YangPluginConfig yangPlugin)
+ throws TranslatorException;
+
+ /**
+ * Traverse the schema of application and generate corresponding code.
+ *
+ * @throws TranslatorException when fails to generate java code
+ */
+ void generateCodeExit()
+ throws TranslatorException;
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaCodeGeneratorUtil.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaCodeGeneratorUtil.java
new file mode 100644
index 0000000..a6eb9d7
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaCodeGeneratorUtil.java
@@ -0,0 +1,262 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.TraversalType.CHILD;
+import static org.onosproject.yangutils.translator.tojava.TraversalType.PARENT;
+import static org.onosproject.yangutils.translator.tojava.TraversalType.ROOT;
+import static org.onosproject.yangutils.translator.tojava.TraversalType.SIBILING;
+
+/**
+ * Representation of java code generator based on application schema.
+ */
+public final class JavaCodeGeneratorUtil {
+
+ /**
+ * Current YANG node.
+ */
+ private static YangNode curNode;
+
+ /**
+ * Creates a java code generator utility object.
+ */
+ private JavaCodeGeneratorUtil() {
+ }
+
+ /**
+ * Returns current YANG node.
+ *
+ * @return current YANG node
+ */
+ public static YangNode getCurNode() {
+ return curNode;
+ }
+
+ /**
+ * Sets current YANG node.
+ *
+ * @param node current YANG node
+ */
+ public static void setCurNode(YangNode node) {
+ curNode = node;
+ }
+
+ /**
+ * Generates Java code files corresponding to the YANG schema.
+ *
+ * @param rootNode root node of the data model tree
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException when fails to generate java code file the current
+ * node
+ */
+ public static void generateJavaCode(YangNode rootNode, YangPluginConfig yangPlugin)
+ throws TranslatorException {
+
+ YangNode codeGenNode = rootNode;
+ TraversalType curTraversal = ROOT;
+
+ while (codeGenNode != null) {
+ if (curTraversal != PARENT) {
+ if (!(codeGenNode instanceof JavaCodeGenerator)) {
+ throw new TranslatorException("Unsupported node to generate code");
+ }
+
+ setCurNode(codeGenNode);
+ try {
+ generateCodeEntry(codeGenNode, yangPlugin);
+ } catch (Exception e) {
+ throw new TranslatorException(e.getMessage());
+ }
+
+ }
+ if (curTraversal != PARENT && codeGenNode.getChild() != null) {
+ curTraversal = CHILD;
+ codeGenNode = codeGenNode.getChild();
+ } else if (codeGenNode.getNextSibling() != null) {
+ try {
+ generateCodeExit(codeGenNode);
+ } catch (Exception e) {
+ throw new TranslatorException(e.getMessage());
+ }
+ curTraversal = SIBILING;
+ codeGenNode = codeGenNode.getNextSibling();
+ } else {
+ try {
+ generateCodeExit(codeGenNode);
+ } catch (Exception e) {
+ throw new TranslatorException(e.getMessage());
+ }
+ curTraversal = PARENT;
+ codeGenNode = codeGenNode.getParent();
+ }
+ }
+ }
+
+ /**
+ * Generates the current nodes code snippet.
+ *
+ * @param codeGenNode current data model node for which the code needs to be
+ * generated
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException when fails to generate java code file the current
+ * node
+ */
+ private static void generateCodeEntry(YangNode codeGenNode, YangPluginConfig yangPlugin)
+ throws TranslatorException {
+
+ if (codeGenNode instanceof JavaCodeGenerator) {
+ ((JavaCodeGenerator) codeGenNode).generateCodeEntry(yangPlugin);
+ } else {
+ throw new TranslatorException(
+ "Generated data model node cannot be translated to target language code");
+ }
+ }
+
+ /**
+ * Generates the current nodes code target code from the snippet.
+ *
+ * @param codeGenNode current data model node for which the code needs to be
+ * generated
+ * @throws TranslatorException when fails to generate java code file the current
+ * node
+ */
+ private static void generateCodeExit(YangNode codeGenNode)
+ throws TranslatorException {
+
+ if (codeGenNode instanceof JavaCodeGenerator) {
+ ((JavaCodeGenerator) codeGenNode).generateCodeExit();
+ } else {
+ throw new TranslatorException(
+ "Generated data model node cannot be translated to target language code");
+ }
+ }
+
+ /**
+ * Free other YANG nodes of data-model tree when error occurs while file
+ * generation of current node.
+ */
+ private static void freeRestResources() {
+
+ YangNode freedNode = getCurNode();
+ if (getCurNode() != null) {
+ YangNode tempNode = freedNode;
+ TraversalType curTraversal = ROOT;
+
+ while (freedNode != tempNode.getParent()) {
+
+ if (curTraversal != PARENT && freedNode.getChild() != null) {
+ curTraversal = CHILD;
+ freedNode = freedNode.getChild();
+ } else if (freedNode.getNextSibling() != null) {
+ curTraversal = SIBILING;
+ if (freedNode != tempNode) {
+ free(freedNode);
+ }
+ freedNode = freedNode.getNextSibling();
+ } else {
+ curTraversal = PARENT;
+ if (freedNode != tempNode) {
+ free(freedNode);
+ }
+ freedNode = freedNode.getParent();
+ }
+ }
+ }
+ }
+
+ /**
+ * Free the current node.
+ *
+ * @param node YANG node
+ */
+ private static void free(YangNode node) {
+
+ YangNode parent = node.getParent();
+ parent.setChild(null);
+
+ if (node.getNextSibling() != null) {
+ parent.setChild(node.getNextSibling());
+ } else if (node.getPreviousSibling() != null) {
+ parent.setChild(node.getPreviousSibling());
+ }
+ node = null;
+ }
+
+ /**
+ * Delete Java code files corresponding to the YANG schema.
+ *
+ * @param rootNode root node of data-model tree
+ * @throws IOException when fails to delete java code file the current node
+ */
+ public static void translatorErrorHandler(YangNode rootNode)
+ throws IOException {
+
+ if (rootNode != null) {
+ /**
+ * Free other resources where translator has failed.
+ */
+ freeRestResources();
+
+ /**
+ * Start removing all open files.
+ */
+ YangNode tempNode = rootNode;
+ setCurNode(tempNode.getChild());
+ TraversalType curTraversal = ROOT;
+
+ while (tempNode != null) {
+
+ if (curTraversal != PARENT) {
+ close(tempNode);
+ }
+ if (curTraversal != PARENT && tempNode.getChild() != null) {
+ curTraversal = CHILD;
+ tempNode = tempNode.getChild();
+ } else if (tempNode.getNextSibling() != null) {
+ curTraversal = SIBILING;
+ tempNode = tempNode.getNextSibling();
+ } else {
+ curTraversal = PARENT;
+ tempNode = tempNode.getParent();
+ }
+ }
+
+ freeRestResources();
+ }
+ }
+
+ /**
+ * Closes all the current open file handles of node and delete all generated
+ * files.
+ *
+ * @param node current YANG node
+ * @throws IOException when fails to do IO operations
+ */
+ private static void close(YangNode node)
+ throws IOException {
+ if (node instanceof JavaCodeGenerator && ((TempJavaCodeFragmentFilesContainer) node)
+ .getTempJavaCodeFragmentFiles() != null) {
+ ((TempJavaCodeFragmentFilesContainer) node).getTempJavaCodeFragmentFiles().freeTemporaryResources(true);
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaFileInfo.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaFileInfo.java
new file mode 100644
index 0000000..28302ee
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaFileInfo.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.Serializable;
+
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+/**
+ * Represents cached java file handle, which supports the addition of member attributes and
+ * methods.
+ */
+public class JavaFileInfo implements Serializable {
+
+ private static final long serialVersionUID = 806102633L;
+
+ /**
+ * The type(s) of java source file(s) to be generated when the cached file
+ * handle is closed.
+ */
+ private transient int genFileTypes;
+
+ /**
+ * Name of the module.
+ */
+ private String javaName;
+
+ /**
+ * Java Package of the mapped java class.
+ */
+ private String pkg;
+
+ /**
+ * File generation directory path.
+ */
+ private String relativeFilePath;
+
+ /**
+ * File generation base directory path.
+ */
+ private String codeGenDirFilePath;
+
+ /**
+ * Plugin configuration for naming convention.
+ */
+ private transient YangPluginConfig pluginConfig;
+
+ /**
+ * Returns the types of files being generated corresponding to the YANG
+ * definition.
+ *
+ * @return the types of files being generated corresponding to the YANG
+ * definition
+ */
+ public int getGeneratedFileTypes() {
+ return genFileTypes;
+ }
+
+ /**
+ * Sets the types of files being generated corresponding to the YANG
+ * definition.
+ *
+ * @param fileTypes the types of files being generated corresponding to the
+ * YANG definition
+ */
+ public void setGeneratedFileTypes(int fileTypes) {
+ genFileTypes = fileTypes;
+ }
+
+ /**
+ * Adds the types of files being generated corresponding to the YANG
+ * definition.
+ *
+ * @param fileTypes the types of files being generated corresponding to the
+ * YANG definition
+ */
+ public void addGeneratedFileTypes(int fileTypes) {
+ genFileTypes |= fileTypes;
+ }
+
+ /**
+ * Returns the java name of the node.
+ *
+ * @return the java name of node
+ */
+ public String getJavaName() {
+ return javaName;
+ }
+
+ /**
+ * Sets the java name of the node.
+ *
+ * @param name the java name of node
+ */
+ public void setJavaName(String name) {
+ javaName = name;
+ }
+
+ /**
+ * Returns the mapped java package.
+ *
+ * @return the java package
+ */
+ public String getPackage() {
+ return pkg;
+ }
+
+ /**
+ * Sets the node's package.
+ *
+ * @param nodePackage node's package
+ */
+ public void setPackage(String nodePackage) {
+ pkg = nodePackage;
+ }
+
+ /**
+ * Sets directory package path for code generation.
+ *
+ * @param path directory package path for code generation
+ */
+ public void setPackageFilePath(String path) {
+ relativeFilePath = path;
+ }
+
+ /**
+ * Returns directory package path for code generation.
+ *
+ * @return directory package path for code generation
+ */
+ public String getPackageFilePath() {
+ return relativeFilePath;
+ }
+
+ /**
+ * Returns base directory package path for code generation.
+ *
+ * @return directory package path for code generation
+ */
+ public String getBaseCodeGenPath() {
+ return codeGenDirFilePath;
+ }
+
+ /**
+ * Sets base directory package path for code generation.
+ *
+ * @param path base directory path
+ */
+ public void setBaseCodeGenPath(String path) {
+ codeGenDirFilePath = path;
+ }
+
+ /**
+ * Returns plugin configurations.
+ *
+ * @return the pluginConfig
+ */
+ public YangPluginConfig getPluginConfig() {
+ return pluginConfig;
+ }
+
+ /**
+ * Sets plugin configurations.
+ *
+ * @param pluginConfig the pluginConfig to set
+ */
+ public void setPluginConfig(YangPluginConfig pluginConfig) {
+ this.pluginConfig = pluginConfig;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaFileInfoContainer.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaFileInfoContainer.java
new file mode 100644
index 0000000..485df77
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaFileInfoContainer.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava;
+
+/**
+ * Represents data model nodes which are required to generate java classes, need to support
+ * java file info.
+ */
+public interface JavaFileInfoContainer {
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ JavaFileInfo getJavaFileInfo();
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ void setJavaFileInfo(JavaFileInfo javaInfo);
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaImportData.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaImportData.java
new file mode 100644
index 0000000..b1c36ec
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaImportData.java
@@ -0,0 +1,284 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import static org.onosproject.yangutils.utils.UtilConstants.ABSTRACT_EVENT;
+import static org.onosproject.yangutils.utils.UtilConstants.ARRAY_LIST;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTATION_HOLDER_CLASS_IMPORT_CLASS;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTED_INFO_CLASS_IMPORT_CLASS;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTED_INFO_CLASS_IMPORT_PKG;
+import static org.onosproject.yangutils.utils.UtilConstants.COLLECTION_IMPORTS;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_LISTENER;
+import static org.onosproject.yangutils.utils.UtilConstants.GOOGLE_MORE_OBJECT_IMPORT_CLASS;
+import static org.onosproject.yangutils.utils.UtilConstants.GOOGLE_MORE_OBJECT_IMPORT_PKG;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_LANG;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_UTIL_OBJECTS_IMPORT_CLASS;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_UTIL_OBJECTS_IMPORT_PKG;
+import static org.onosproject.yangutils.utils.UtilConstants.LIST;
+import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_REG;
+import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_SERVICE;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.ONOS_EVENT_PKG;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.PROVIDED_AUGMENTATION_CLASS_IMPORT_PKG;
+import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
+
+import static java.util.Collections.sort;
+
+/**
+ * Represents that generated Java file can contain imports.
+ */
+public class JavaImportData {
+
+ /**
+ * Flag to denote if any list in imported.
+ */
+ private boolean isListToImport;
+
+ /**
+ * Sorted set of import info, to be used to maintain the set of classes to
+ * be imported in the generated class.
+ */
+ private SortedSet<JavaQualifiedTypeInfo> importSet;
+
+ /**
+ * Creates java import data object.
+ */
+ public JavaImportData() {
+ setImportSet(new TreeSet<JavaQualifiedTypeInfo>());
+ }
+
+ /**
+ * Returns if the list needs to be imported.
+ *
+ * @return true if any of the attribute needs to be maintained as a list
+ */
+ public boolean getIfListImported() {
+ return isListToImport;
+ }
+
+ /**
+ * Sets the status of importing list.
+ *
+ * @param isList status to mention list is bing imported
+ */
+ public void setIfListImported(boolean isList) {
+ isListToImport = isList;
+ }
+
+ /**
+ * Returns the set containing the imported class/interface info.
+ *
+ * @return the set containing the imported class/interface info
+ */
+ public SortedSet<JavaQualifiedTypeInfo> getImportSet() {
+ return importSet;
+ }
+
+ /**
+ * Assigns the set containing the imported class/interface info.
+ *
+ * @param importSet the set containing the imported class/interface info
+ */
+ private void setImportSet(SortedSet<JavaQualifiedTypeInfo> importSet) {
+ this.importSet = importSet;
+ }
+
+ /**
+ * Adds an imported class/interface info if it is not already part of the
+ * collection.
+ *
+ * If already part of the collection, check if the packages are same, if so
+ * then return true, to denote it is already in the import collection, and
+ * it can be accessed without qualified access. If the packages do not
+ * match, then do not add to the import collection, and return false to
+ * denote, it is not added to import collection and needs to be accessed in
+ * a qualified manner.
+ *
+ * @param newImportInfo class/interface info being imported
+ * @param className name of the call being generated
+ * @param classPkg generated class package
+ * @return qualified access status of the import node being added
+ */
+ public boolean addImportInfo(JavaQualifiedTypeInfo newImportInfo,
+ String className, String classPkg) {
+
+ if (newImportInfo.getClassInfo().contentEquals(className)) {
+ /*
+ * if the current class name is same as the attribute class name,
+ * then the attribute must be accessed in a qualified manner.
+ */
+ return true;
+ } else if (newImportInfo.getPkgInfo() == null) {
+ /*
+ * If the package info is null, then it is not a candidate for import / qualified access
+ */
+ return false;
+ }
+
+ /*
+ * If the attribute type is having the package info, it is contender
+ * for import list and also need to check if it needs to be a
+ * qualified access.
+ */
+ if (newImportInfo.getPkgInfo().contentEquals(classPkg)) {
+ /**
+ * Package of the referred attribute and the generated class is same, so no need import
+ * or qualified access.
+ */
+ return false;
+ }
+
+ for (JavaQualifiedTypeInfo curImportInfo : getImportSet()) {
+ if (curImportInfo.getClassInfo()
+ .contentEquals(newImportInfo.getClassInfo())) {
+ return !curImportInfo.getPkgInfo()
+ .contentEquals(newImportInfo.getPkgInfo());
+ }
+ }
+
+ /*
+ * import is added, so it is a member for non qualified access
+ */
+ getImportSet().add(newImportInfo);
+ return false;
+ }
+
+ /**
+ * Returns import for class.
+ *
+ * @return imports for class
+ */
+ public List<String> getImports() {
+
+ String importString;
+ List<String> imports = new ArrayList<>();
+
+ for (JavaQualifiedTypeInfo importInfo : getImportSet()) {
+ if (!importInfo.getPkgInfo().equals(EMPTY_STRING) && importInfo.getClassInfo() != null
+ && !importInfo.getPkgInfo().equals(JAVA_LANG)) {
+ importString = IMPORT + importInfo.getPkgInfo() + PERIOD + importInfo.getClassInfo() + SEMI_COLAN
+ + NEW_LINE;
+
+ imports.add(importString);
+ }
+ }
+
+ if (getIfListImported()) {
+ imports.add(getImportForList());
+ }
+
+ sort(imports);
+ return imports;
+ }
+
+ /**
+ * Returns import for hash and equals method.
+ *
+ * @return import for hash and equals method
+ */
+ public String getImportForHashAndEquals() {
+ return IMPORT + JAVA_UTIL_OBJECTS_IMPORT_PKG + PERIOD + JAVA_UTIL_OBJECTS_IMPORT_CLASS;
+ }
+
+ /**
+ * Returns import for to string method.
+ *
+ * @return import for to string method
+ */
+ public String getImportForToString() {
+ return IMPORT + GOOGLE_MORE_OBJECT_IMPORT_PKG + PERIOD + GOOGLE_MORE_OBJECT_IMPORT_CLASS;
+ }
+
+ /**
+ * Returns import for list attribute.
+ *
+ * @return import for list attribute
+ */
+ public String getImportForList() {
+ return IMPORT + COLLECTION_IMPORTS + PERIOD + LIST + SEMI_COLAN + NEW_LINE;
+ }
+
+ /**
+ * Returns import for array list attribute.
+ *
+ * @return import for array list attribute
+ */
+ public String getImportForArrayList() {
+ return IMPORT + COLLECTION_IMPORTS + PERIOD + ARRAY_LIST + SEMI_COLAN + NEW_LINE;
+ }
+
+ /**
+ * Returns import string for AugmentationHolder class.
+ *
+ * @return import string for AugmentationHolder class
+ */
+ public String getAugmentationHolderImport() {
+ return IMPORT + PROVIDED_AUGMENTATION_CLASS_IMPORT_PKG + PERIOD + AUGMENTATION_HOLDER_CLASS_IMPORT_CLASS;
+ }
+
+ /**
+ * Returns import string for AugmentedInfo class.
+ *
+ * @return import string for AugmentedInfo class
+ */
+ public String getAugmentedInfoImport() {
+ return IMPORT + AUGMENTED_INFO_CLASS_IMPORT_PKG + PERIOD + AUGMENTED_INFO_CLASS_IMPORT_CLASS;
+ }
+
+ /**
+ * Returns import string for ListenerService class.
+ *
+ * @return import string for ListenerService class
+ */
+ public String getListenerServiceImport() {
+ return IMPORT + ONOS_EVENT_PKG + PERIOD + LISTENER_SERVICE + SEMI_COLAN + NEW_LINE;
+ }
+
+ /**
+ * Returns import string for ListenerRegistry class.
+ *
+ * @return import string for ListenerRegistry class
+ */
+ public String getListenerRegistryImport() {
+ return IMPORT + ONOS_EVENT_PKG + PERIOD + LISTENER_REG + SEMI_COLAN + NEW_LINE;
+ }
+
+ /**
+ * Returns import string for AbstractEvent class.
+ *
+ * @return import string for AbstractEvent class
+ */
+ public String getAbstractEventsImport() {
+ return IMPORT + ONOS_EVENT_PKG + PERIOD + ABSTRACT_EVENT + SEMI_COLAN + NEW_LINE;
+ }
+
+ /**
+ * Returns import string for EventListener class.
+ *
+ * @return import string for EventListener class
+ */
+ public String getEventListenerImport() {
+ return IMPORT + ONOS_EVENT_PKG + PERIOD + EVENT_LISTENER + SEMI_COLAN + NEW_LINE;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaImportDataContainer.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaImportDataContainer.java
new file mode 100644
index 0000000..e86b468
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaImportDataContainer.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava;
+
+/**
+ * Represents the information of the java import data.
+ */
+public interface JavaImportDataContainer {
+
+ /**
+ * Returns the data of java imports to be included in generated file.
+ *
+ * @return data of java imports to be included in generated file
+ */
+ JavaImportData getJavaImportData();
+
+ /**
+ * Sets the data of java imports to be included in generated file.
+ *
+ * @param javaImportData data of java imports to be included in generated
+ * file
+ */
+ void setJavaImportData(JavaImportData javaImportData);
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaQualifiedTypeInfo.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaQualifiedTypeInfo.java
new file mode 100644
index 0000000..98e44f8
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaQualifiedTypeInfo.java
@@ -0,0 +1,235 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.javamodel.JavaLeafInfoContainer;
+import org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType;
+import org.onosproject.yangutils.translator.tojava.utils.YangToJavaNamingConflictUtil;
+
+import com.google.common.base.MoreObjects;
+
+import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getJavaImportClass;
+import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getJavaImportPackage;
+
+/**
+ * Represents the information about individual imports in the generated file.
+ */
+public class JavaQualifiedTypeInfo
+ implements Comparable<JavaQualifiedTypeInfo>, Serializable {
+
+ private static final long serialVersionUID = 806201634L;
+
+ /**
+ * Package location where the imported class/interface is defined.
+ */
+ private String pkgInfo;
+
+ /**
+ * Class/interface being referenced.
+ */
+ private String classInfo;
+
+ /**
+ * Creates a java qualified type info object.
+ */
+ public JavaQualifiedTypeInfo() {
+ }
+
+ /**
+ * Returns the imported package info.
+ *
+ * @return the imported package info
+ */
+ public String getPkgInfo() {
+ return pkgInfo;
+ }
+
+ /**
+ * Sets the imported package info.
+ *
+ * @param pkgInfo the imported package info
+ */
+ public void setPkgInfo(String pkgInfo) {
+ this.pkgInfo = pkgInfo;
+ }
+
+ /**
+ * Returns the imported class/interface info.
+ *
+ * @return the imported class/interface info
+ */
+ public String getClassInfo() {
+ return classInfo;
+ }
+
+ /**
+ * Sets the imported class/interface info.
+ *
+ * @param classInfo the imported class/interface info
+ */
+ public void setClassInfo(String classInfo) {
+ this.classInfo = classInfo;
+ }
+
+ /**
+ * Updates the leaf's java information.
+ *
+ * @param leaf leaf whose java information is being updated
+ */
+ public static void updateLeavesJavaQualifiedInfo(JavaLeafInfoContainer leaf) {
+
+ JavaQualifiedTypeInfo importInfo = leaf.getJavaQualifiedInfo();
+
+ if (leaf.getDataType() == null) {
+ throw new TranslatorException("missing data type of leaf " + leaf.getName());
+ }
+
+ /*
+ * Current leaves holder is adding a leaf info as a attribute to the
+ * current class.
+ */
+ String className = AttributesJavaDataType.getJavaImportClass(leaf.getDataType(), leaf.isLeafList(),
+ leaf.getConflictResolveConfig());
+ if (className != null) {
+ /*
+ * Corresponding to the attribute type a class needs to be imported,
+ * since it can be a derived type or a usage of wrapper classes.
+ */
+ importInfo.setClassInfo(className);
+ String classPkg = AttributesJavaDataType.getJavaImportPackage(leaf.getDataType(),
+ leaf.isLeafList(), leaf.getConflictResolveConfig());
+ if (classPkg == null) {
+ throw new TranslatorException("import package cannot be null when the class is used");
+ }
+ importInfo.setPkgInfo(classPkg);
+ } else {
+ /*
+ * The attribute does not need a class to be imported, for example
+ * built in java types.
+ */
+ String dataTypeName = AttributesJavaDataType.getJavaDataType(leaf.getDataType());
+ if (dataTypeName == null) {
+ throw new TranslatorException("not supported data type");
+ }
+ importInfo.setClassInfo(dataTypeName);
+ }
+ }
+
+ /**
+ * Returns the import info for an attribute, which needs to be used for code
+ * generation for import or for qualified access.
+ *
+ * @param curNode current data model node for which the java file is being
+ * generated
+ * @param attributeName name of the attribute being added, it will used in
+ * import info for child class
+ * @return return the import info for this attribute
+ */
+ public static JavaQualifiedTypeInfo getQualifiedTypeInfoOfCurNode(YangNode curNode,
+ String attributeName) {
+
+ JavaQualifiedTypeInfo importInfo = new JavaQualifiedTypeInfo();
+
+ if (!(curNode instanceof JavaFileInfoContainer)) {
+ throw new TranslatorException("missing java file information to get the package details "
+ + "of attribute corresponding to child node");
+ }
+
+ importInfo.setClassInfo(attributeName);
+ importInfo.setPkgInfo(((JavaFileInfoContainer) curNode)
+ .getJavaFileInfo().getPackage());
+
+ return importInfo;
+ }
+
+ /**
+ * Returns the java qualified type information for the wrapper classes.
+ *
+ * @param referredTypesAttrInfo attribute of referred type
+ * @param conflictResolver plugin configurations
+ * @return return the import info for this attribute
+ */
+ public static JavaQualifiedTypeInfo getQualifiedInfoOfFromString(JavaAttributeInfo referredTypesAttrInfo,
+ YangToJavaNamingConflictUtil conflictResolver) {
+
+ /*
+ * Get the java qualified type information for the wrapper classes and
+ * set it in new java attribute information.
+ */
+ JavaQualifiedTypeInfo qualifiedInfoOfFromString = new JavaQualifiedTypeInfo();
+
+ qualifiedInfoOfFromString.setClassInfo(
+ getJavaImportClass(referredTypesAttrInfo.getAttributeType(), true, conflictResolver));
+ qualifiedInfoOfFromString.setPkgInfo(
+ getJavaImportPackage(referredTypesAttrInfo.getAttributeType(), true, conflictResolver));
+ return qualifiedInfoOfFromString;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(pkgInfo, classInfo);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof JavaQualifiedTypeInfo) {
+ JavaQualifiedTypeInfo other = (JavaQualifiedTypeInfo) obj;
+ return Objects.equals(pkgInfo, other.pkgInfo) &&
+ Objects.equals(classInfo, other.classInfo);
+ }
+ return false;
+ }
+
+ /**
+ * Checks if the import info matches.
+ *
+ * @param importInfo matched import
+ * @return if equal or not
+ */
+ public boolean exactMatch(JavaQualifiedTypeInfo importInfo) {
+ return equals(importInfo)
+ && Objects.equals(pkgInfo, importInfo.getPkgInfo())
+ && Objects.equals(classInfo, importInfo.getClassInfo());
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(getClass())
+ .add("pkgInfo", pkgInfo)
+ .add("classInfo", classInfo).toString();
+ }
+
+ /**
+ * Checks that there is no 2 objects with the same class name.
+ *
+ * @param other compared import info.
+ */
+ @Override
+ public int compareTo(JavaQualifiedTypeInfo other) {
+ return getClassInfo().compareTo(other.getClassInfo());
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaQualifiedTypeInfoContainer.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaQualifiedTypeInfoContainer.java
new file mode 100644
index 0000000..c6570c6
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/JavaQualifiedTypeInfoContainer.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2016 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava;
+
+/**
+ * Maintain the java qualified access details for an attribute or a class.
+ */
+public interface JavaQualifiedTypeInfoContainer {
+
+ /**
+ * Obtain the java qualified details.
+ *
+ * @return java qualified type details
+ */
+ JavaQualifiedTypeInfo getJavaQualifiedInfo();
+
+ /**
+ * Assign the qualified type info.
+ *
+ * @param typeInfo qualified type information
+ */
+ void setJavaQualifiedInfo(JavaQualifiedTypeInfo typeInfo);
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaBeanFragmentFiles.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaBeanFragmentFiles.java
new file mode 100644
index 0000000..14f4cd2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaBeanFragmentFiles.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getConstructor;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.closeFile;
+
+/**
+ * Represents implementation of java bean code fragments temporary implementations.
+ * Maintains the temp files required specific for bean java snippet generation.
+ */
+public class TempJavaBeanFragmentFiles
+ extends TempJavaFragmentFiles {
+
+ /**
+ * File name for constructor.
+ */
+ private static final String CONSTRUCTOR_FILE_NAME = "Constructor";
+
+ /**
+ * Temporary file handle for constructor of class.
+ */
+ private File constructorImplTempFileHandle;
+
+ /**
+ * Creates an instance of temporary java code fragment.
+ *
+ * @param javaFileInfo generated java file info
+ * @throws IOException when fails to create new file handle
+ */
+ public TempJavaBeanFragmentFiles(JavaFileInfo javaFileInfo)
+ throws IOException {
+
+ super(javaFileInfo);
+
+ /*
+ * Initialize getterImpl, attributes, constructor, hash code, equals and
+ * to strings when generation file type matches to impl class mask.
+ */
+ addGeneratedTempFile(CONSTRUCTOR_IMPL_MASK);
+
+ setConstructorImplTempFileHandle(getTemporaryFileHandle(CONSTRUCTOR_FILE_NAME));
+ }
+
+ /**
+ * Returns constructor's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getConstructorImplTempFileHandle() {
+ return constructorImplTempFileHandle;
+ }
+
+ /**
+ * Sets to constructor's temporary file handle.
+ *
+ * @param constructor file handle for to constructor
+ */
+ private void setConstructorImplTempFileHandle(File constructor) {
+ constructorImplTempFileHandle = constructor;
+ }
+
+ /**
+ * Adds constructor for class.
+ *
+ * @param attr attribute info
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addConstructor(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
+ throws IOException {
+ appendToFile(getConstructorImplTempFileHandle(), getConstructor(getGeneratedJavaClassName(), attr,
+ getGeneratedJavaFiles(), pluginConfig));
+ }
+
+ /**
+ * Adds the new attribute info to the target generated temporary files.
+ *
+ * @param newAttrInfo the attribute info that needs to be added to temporary
+ * files
+ * @throws IOException IO operation fail
+ */
+ @Override
+ void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo, YangPluginConfig pluginConfig)
+ throws IOException {
+ super.addJavaSnippetInfoToApplicableTempFiles(newAttrInfo, pluginConfig);
+ addConstructor(newAttrInfo, pluginConfig);
+ }
+
+ /**
+ * Removes all temporary file handles.
+ *
+ * @param isErrorOccurred when translator fails to generate java files we
+ * need to close all open file handles include temporary files
+ * and java files.
+ * @throws IOException when failed to delete the temporary files
+ */
+ @Override
+ public void freeTemporaryResources(boolean isErrorOccurred)
+ throws IOException {
+
+ /*
+ * Close constructor temporary file handle and delete the file.
+ */
+ closeFile(getConstructorImplTempFileHandle(), true);
+
+ super.freeTemporaryResources(isErrorOccurred);
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaCodeFragmentFiles.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaCodeFragmentFiles.java
new file mode 100644
index 0000000..309ee66
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaCodeFragmentFiles.java
@@ -0,0 +1,317 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangTypeHolder;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_ENUM_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_TYPE_CLASS;
+
+/**
+ * Represents implementation of java code fragments temporary implementations.
+ * Contains fragment file object of different types of java file.
+ * Uses required object(s) to generate the target java file(s).
+ */
+public class TempJavaCodeFragmentFiles {
+
+ /**
+ * Has the temporary files required for bean generated classes.
+ */
+ private TempJavaBeanFragmentFiles beanTempFiles;
+
+ /**
+ * Has the temporary files required for bean generated classes.
+ */
+ private TempJavaTypeFragmentFiles typeTempFiles;
+
+ /**
+ * Has the temporary files required for service generated classes.
+ */
+ private TempJavaServiceFragmentFiles serviceTempFiles;
+
+ /**
+ * Has the temporary files required for enumeration generated classes.
+ */
+ private TempJavaEnumerationFragmentFiles enumerationTempFiles;
+
+ /**
+ * Creates an instance of temporary java code fragment.
+ *
+ * @param javaFileInfo generated java file info
+ * @throws IOException when fails to create new file handle
+ */
+ public TempJavaCodeFragmentFiles(JavaFileInfo javaFileInfo)
+ throws IOException {
+
+ if ((javaFileInfo.getGeneratedFileTypes() & GENERATE_INTERFACE_WITH_BUILDER) != 0) {
+ setBeanTempFiles(new TempJavaBeanFragmentFiles(javaFileInfo));
+ }
+
+ if ((javaFileInfo.getGeneratedFileTypes() & GENERATE_TYPE_CLASS) != 0) {
+ setTypeTempFiles(new TempJavaTypeFragmentFiles(javaFileInfo));
+ }
+
+ if ((javaFileInfo.getGeneratedFileTypes() & GENERATE_ENUM_CLASS) != 0) {
+ setEnumerationTempFiles(new TempJavaEnumerationFragmentFiles(javaFileInfo));
+ }
+
+ if ((javaFileInfo.getGeneratedFileTypes() & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ setServiceTempFiles(new TempJavaServiceFragmentFiles(javaFileInfo));
+ }
+
+ }
+
+ /**
+ * Retrieves the temp file handle for bean file generation.
+ *
+ * @return temp file handle for bean file generation
+ */
+ public TempJavaBeanFragmentFiles getBeanTempFiles() {
+ return beanTempFiles;
+ }
+
+ /**
+ * Sets temp file handle for bean file generation.
+ *
+ * @param beanTempFiles temp file handle for bean file generation
+ */
+ public void setBeanTempFiles(TempJavaBeanFragmentFiles beanTempFiles) {
+ this.beanTempFiles = beanTempFiles;
+ }
+
+ /**
+ * Retrieves the temp file handle for data type file generation.
+ *
+ * @return temp file handle for data type file generation
+ */
+ public TempJavaTypeFragmentFiles getTypeTempFiles() {
+ return typeTempFiles;
+ }
+
+ /**
+ * Sets temp file handle for data type file generation.
+ *
+ * @param typeTempFiles temp file handle for data type file generation
+ */
+ public void setTypeTempFiles(TempJavaTypeFragmentFiles typeTempFiles) {
+ this.typeTempFiles = typeTempFiles;
+ }
+
+ /**
+ * Retrieves the temp file handle for service file generation.
+ *
+ * @return temp file handle for service file generation
+ */
+ public TempJavaServiceFragmentFiles getServiceTempFiles() {
+ return serviceTempFiles;
+ }
+
+ /**
+ * Sets temp file handle for service file generation.
+ *
+ * @param serviceTempFiles temp file handle for service file generation
+ */
+ public void setServiceTempFiles(TempJavaServiceFragmentFiles serviceTempFiles) {
+ this.serviceTempFiles = serviceTempFiles;
+ }
+
+ /**
+ * Retrieves the temp file handle for enumeration file generation.
+ *
+ * @return temp file handle for enumeration file generation
+ */
+ public TempJavaEnumerationFragmentFiles getEnumerationTempFiles() {
+ return enumerationTempFiles;
+ }
+
+ /**
+ * Sets temp file handle for enumeration file generation.
+ *
+ * @param enumerationTempFiles temp file handle for enumeration file generation
+ */
+ public void setEnumerationTempFiles(
+ TempJavaEnumerationFragmentFiles enumerationTempFiles) {
+ this.enumerationTempFiles = enumerationTempFiles;
+ }
+
+ /**
+ * Constructs java code exit.
+ *
+ * @param fileType generated file type
+ * @param curNode current YANG node
+ * @throws IOException when fails to generate java files
+ */
+ public void generateJavaFile(int fileType, YangNode curNode)
+ throws IOException {
+
+ if ((fileType & GENERATE_INTERFACE_WITH_BUILDER) != 0) {
+ getBeanTempFiles().generateJavaFile(fileType, curNode);
+ }
+
+ /*
+ * Creates user defined data type class file.
+ */
+ if ((fileType & GENERATE_TYPE_CLASS) != 0) {
+ getTypeTempFiles().generateJavaFile(fileType, curNode);
+ }
+
+ /*
+ * Creates service and manager class file.
+ */
+ if (fileType == GENERATE_SERVICE_AND_MANAGER) {
+ getServiceTempFiles().generateJavaFile(GENERATE_SERVICE_AND_MANAGER, curNode);
+ }
+
+ /*
+ * Creats enumeration class file.
+ */
+ if (fileType == GENERATE_ENUM_CLASS) {
+ getEnumerationTempFiles().generateJavaFile(GENERATE_ENUM_CLASS, curNode);
+ }
+
+ freeTemporaryResources(false);
+ }
+
+ /**
+ * Adds the new attribute info to the target generated temporary files.
+ *
+ * @param newAttrInfo the attribute info that needs to be added to temporary
+ * files
+ * @param pluginConfig plugin configurations
+ * @throws IOException IO operation fail
+ */
+ public void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo,
+ YangPluginConfig pluginConfig)
+ throws IOException {
+
+ if (getBeanTempFiles() != null) {
+ getBeanTempFiles()
+ .addJavaSnippetInfoToApplicableTempFiles(newAttrInfo, pluginConfig);
+ }
+
+ /**
+ * Creates user defined data type class file.
+ */
+ if (getTypeTempFiles() != null) {
+ getTypeTempFiles()
+ .addJavaSnippetInfoToApplicableTempFiles(newAttrInfo, pluginConfig);
+ }
+ }
+
+ /**
+ * Add all the type in the current data model node as part of the
+ * generated temporary file.
+ *
+ * @param yangTypeHolder YANG java data model node which has type info, eg union / typedef
+ * @param pluginConfig plugin configurations for naming convention
+ * @throws IOException IO operation fail
+ */
+ public void addTypeInfoToTempFiles(YangTypeHolder yangTypeHolder, YangPluginConfig pluginConfig)
+ throws IOException {
+ getTypeTempFiles()
+ .addTypeInfoToTempFiles(yangTypeHolder, pluginConfig);
+ }
+
+ /**
+ * Adds build method for interface.
+ *
+ * @param pluginConfig plugin configurations
+ * @return build method for interface
+ * @throws IOException when fails to append to temporary file
+ */
+ public String addBuildMethodForInterface(YangPluginConfig pluginConfig)
+ throws IOException {
+ if (getBeanTempFiles() != null) {
+ return getBeanTempFiles().addBuildMethodForInterface(pluginConfig);
+ }
+ throw new TranslatorException("build method only supported for bean class");
+ }
+
+ /**
+ * Adds default constructor for class.
+ *
+ * @param modifier modifier for constructor.
+ * @param toAppend string which need to be appended with the class name
+ * @param pluginConfig plugin configurations
+ * @return default constructor for class
+ * @throws IOException when fails to append to file
+ */
+ public String addDefaultConstructor(String modifier, String toAppend, YangPluginConfig pluginConfig)
+ throws IOException {
+ if (getTypeTempFiles() != null) {
+ return getTypeTempFiles()
+ .addDefaultConstructor(modifier, toAppend, pluginConfig);
+ }
+
+ if (getBeanTempFiles() != null) {
+ return getBeanTempFiles().addDefaultConstructor(modifier, toAppend, pluginConfig);
+ }
+
+ throw new TranslatorException("default constructor should not be added");
+ }
+
+ /**
+ * Adds build method's implementation for class.
+ *
+ * @return build method implementation for class
+ * @throws IOException when fails to append to temporary file
+ */
+ public String addBuildMethodImpl()
+ throws IOException {
+ if (getBeanTempFiles() != null) {
+ return getBeanTempFiles().addBuildMethodImpl();
+ }
+
+ throw new TranslatorException("build should not be added");
+ }
+
+ /**
+ * Removes all temporary file handles.
+ *
+ * @param isErrorOccurred when translator fails to generate java files we need to close
+ * all open file handles include temporary files and java files.
+ * @throws IOException when failed to delete the temporary files
+ */
+ public void freeTemporaryResources(boolean isErrorOccurred)
+ throws IOException {
+
+ if (getBeanTempFiles() != null) {
+ getBeanTempFiles().freeTemporaryResources(isErrorOccurred);
+ }
+
+ if (getTypeTempFiles() != null) {
+ getTypeTempFiles().freeTemporaryResources(isErrorOccurred);
+ }
+
+ if (getEnumerationTempFiles() != null) {
+ getEnumerationTempFiles().freeTemporaryResources(isErrorOccurred);
+ }
+
+ if (getServiceTempFiles() != null) {
+ getServiceTempFiles().freeTemporaryResources(isErrorOccurred);
+ }
+
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaCodeFragmentFilesContainer.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaCodeFragmentFilesContainer.java
new file mode 100644
index 0000000..1bbf349
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaCodeFragmentFilesContainer.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava;
+
+/**
+ * Represents Has temporary file handle.
+ */
+public interface TempJavaCodeFragmentFilesContainer {
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles();
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle);
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaEnumerationFragmentFiles.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaEnumerationFragmentFiles.java
new file mode 100644
index 0000000..2ab6f9d
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaEnumerationFragmentFiles.java
@@ -0,0 +1,316 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.onosproject.yangutils.datamodel.YangDataTypes;
+import org.onosproject.yangutils.datamodel.YangEnum;
+import org.onosproject.yangutils.datamodel.YangEnumeration;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaType;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ENUM_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getAttributeInfoForTheData;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.generateEnumAttributeString;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEnumClassFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getEnumJavaAttribute;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPrefixForIdentifier;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.closeFile;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_FIRST_DIGIT;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_AUTO_PREFIX;
+import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.createPackage;
+
+/**
+ * Represents implementation of java code fragments temporary implementations.
+ * Maintains the temp files required specific for enumeration java snippet generation.
+ */
+public class TempJavaEnumerationFragmentFiles extends TempJavaFragmentFiles {
+
+ /**
+ * File name for temporary enum class.
+ */
+ private static final String ENUM_CLASS_TEMP_FILE_NAME = "EnumClass";
+
+ /**
+ * File name for enum class file name suffix.
+ */
+ private static final String ENUM_CLASS_FILE_NAME_SUFFIX = EMPTY_STRING;
+
+ /**
+ * Current enum's value.
+ */
+ private int enumValue;
+
+ /**
+ * Contains data of enumSet.
+ */
+ private Map<String, Integer> enumStringMap = new HashMap<>();
+
+ /**
+ * Contains data of enumSet.
+ */
+ private List<String> enumStringList;
+
+ /**
+ * Temporary file handle for enum class file.
+ */
+ private File enumClassTempFileHandle;
+
+ /**
+ * Java file handle for enum class.
+ */
+ private File enumClassJavaFileHandle;
+
+ /**
+ * Creates an instance of temporary java code fragment.
+ *
+ * @param javaFileInfo generated java file info
+ * @throws IOException when fails to create new file handle
+ */
+ public TempJavaEnumerationFragmentFiles(JavaFileInfo javaFileInfo)
+ throws IOException {
+
+ super(javaFileInfo);
+ setEnumSetJavaMap(new HashMap<>());
+ setEnumStringList(new ArrayList<>());
+ /*
+ * Initialize enum when generation file type matches to enum class mask.
+ */
+ addGeneratedTempFile(ENUM_IMPL_MASK);
+ setEnumClassTempFileHandle(getTemporaryFileHandle(ENUM_CLASS_TEMP_FILE_NAME));
+ }
+
+ /**
+ * Returns enum class java file handle.
+ *
+ * @return enum class java file handle
+ */
+ public File getEnumClassJavaFileHandle() {
+ return enumClassJavaFileHandle;
+ }
+
+ /**
+ * Sets enum class java file handle.
+ *
+ * @param enumClassJavaFileHandle enum class java file handle
+ */
+ private void setEnumClassJavaFileHandle(File enumClassJavaFileHandle) {
+ this.enumClassJavaFileHandle = enumClassJavaFileHandle;
+ }
+
+ /**
+ * Returns enum's value.
+ *
+ * @return enum's value
+ */
+ private int getEnumValue() {
+ return enumValue;
+ }
+
+ /**
+ * Sets enum's value.
+ *
+ * @param enumValue enum's value
+ */
+ private void setEnumValue(int enumValue) {
+ this.enumValue = enumValue;
+ }
+
+ /**
+ * Returns enum set java map.
+ *
+ * @return the enum set java map
+ */
+ public Map<String, Integer> getEnumSetJavaMap() {
+ return enumStringMap;
+ }
+
+ /**
+ * Sets enum set java map.
+ *
+ * @param map the enum set java map to set
+ */
+ private void setEnumSetJavaMap(Map<String, Integer> map) {
+ this.enumStringMap = map;
+ }
+
+ /**
+ * Returns temporary file handle for enum class file.
+ *
+ * @return temporary file handle for enum class file
+ */
+ public File getEnumClassTempFileHandle() {
+ return enumClassTempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle for enum class file.
+ *
+ * @param enumClassTempFileHandle temporary file handle for enum class file
+ */
+ private void setEnumClassTempFileHandle(File enumClassTempFileHandle) {
+ this.enumClassTempFileHandle = enumClassTempFileHandle;
+ }
+
+ /**
+ * Adds enum class attributes to temporary file.
+ *
+ * @param curEnumName current YANG enum
+ * @throws IOException when fails to do IO operations.
+ */
+ private void addAttributesForEnumClass(String curEnumName, YangPluginConfig pluginConfig) throws IOException {
+ appendToFile(getEnumClassTempFileHandle(),
+ generateEnumAttributeString(curEnumName, getEnumValue(), pluginConfig));
+ }
+
+ /**
+ * Adds enum attributes to temporary files.
+ *
+ * @param curNode current YANG node
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to do IO operations
+ */
+ public void addEnumAttributeToTempFiles(YangNode curNode, YangPluginConfig pluginConfig) throws IOException {
+
+ super.addJavaSnippetInfoToApplicableTempFiles(getJavaAttributeForEnum(pluginConfig), pluginConfig);
+ if (curNode instanceof YangEnumeration) {
+ YangEnumeration enumeration = (YangEnumeration) curNode;
+ for (YangEnum curEnum : enumeration.getEnumSet()) {
+ String enumName = curEnum.getNamedValue();
+ String prefixForIdentifier = null;
+ if (enumName.matches(REGEX_FOR_FIRST_DIGIT)) {
+ prefixForIdentifier = getPrefixForIdentifier(pluginConfig.getConflictResolver());
+ if (prefixForIdentifier != null) {
+ curEnum.setNamedValue(prefixForIdentifier + enumName);
+ } else {
+ curEnum.setNamedValue(YANG_AUTO_PREFIX + enumName);
+ }
+ }
+ setEnumValue(curEnum.getValue());
+ addToEnumStringList(curEnum.getNamedValue());
+ addToEnumSetJavaMap(curEnum.getNamedValue(), curEnum.getValue());
+ addJavaSnippetInfoToApplicableTempFiles(curEnum.getNamedValue(), pluginConfig);
+ }
+ } else {
+ throw new TranslatorException("current node should be of enumeration type.");
+ }
+ }
+
+ /**
+ * Returns java attribute for enum class.
+ *
+ * @param pluginConfig plugin configurations
+ * @return java attribute
+ */
+ public JavaAttributeInfo getJavaAttributeForEnum(YangPluginConfig pluginConfig) {
+ YangJavaType<?> javaType = new YangJavaType<>();
+ javaType.setDataType(YangDataTypes.INT32);
+ javaType.setDataTypeName("int");
+ javaType.updateJavaQualifiedInfo(pluginConfig.getConflictResolver());
+ return getAttributeInfoForTheData(
+ javaType.getJavaQualifiedInfo(),
+ javaType.getDataTypeName(), javaType,
+ getIsQualifiedAccessOrAddToImportList(javaType.getJavaQualifiedInfo()),
+ false);
+ }
+
+ /**
+ * Adds current enum name to java list.
+ *
+ * @param curEnumName current enum name
+ */
+ private void addToEnumSetJavaMap(String curEnumName, int value) {
+ getEnumSetJavaMap().put(getEnumJavaAttribute(curEnumName).toUpperCase(), value);
+ }
+
+ /**
+ * Adds the new attribute info to the target generated temporary files.
+ *
+ * @param curEnumName the attribute name that needs to be added to temporary
+ * files
+ * @throws IOException IO operation fail
+ */
+ void addJavaSnippetInfoToApplicableTempFiles(String curEnumName, YangPluginConfig pluginConfig)
+ throws IOException {
+ addAttributesForEnumClass(getEnumJavaAttribute(curEnumName), pluginConfig);
+ }
+
+ /**
+ * Constructs java code exit.
+ *
+ * @param fileType generated file type
+ * @param curNode current YANG node
+ * @throws IOException when fails to generate java files
+ */
+ @Override
+ public void generateJavaFile(int fileType, YangNode curNode) throws IOException {
+ createPackage(curNode);
+ setEnumClassJavaFileHandle(getJavaFileHandle(getJavaClassName(ENUM_CLASS_FILE_NAME_SUFFIX)));
+ setEnumClassJavaFileHandle(generateEnumClassFile(getEnumClassJavaFileHandle(), curNode));
+ freeTemporaryResources(false);
+ }
+
+ /**
+ * Removes all temporary file handles.
+ *
+ * @param isErrorOccurred when translator fails to generate java files we
+ * need to close all open file handles include temporary files
+ * and java files.
+ * @throws IOException when failed to delete the temporary files
+ */
+ @Override
+ public void freeTemporaryResources(boolean isErrorOccurred) throws IOException {
+ closeFile(getEnumClassJavaFileHandle(), isErrorOccurred);
+ closeFile(getEnumClassTempFileHandle(), true);
+ super.freeTemporaryResources(isErrorOccurred);
+ }
+
+ /**
+ * Adds to enum string list.
+ *
+ * @param curEnumValue current enum value
+ */
+ private void addToEnumStringList(String curEnumValue) {
+ getEnumStringList().add(getEnumJavaAttribute(curEnumValue).toUpperCase());
+ }
+
+ /**
+ * Returns enum string list.
+ *
+ * @return the enumStringList
+ */
+ public List<String> getEnumStringList() {
+ return enumStringList;
+ }
+
+ /**
+ * Sets enum string list.
+ *
+ * @param enumStringList the enumStringList to set
+ */
+ public void setEnumStringList(List<String> enumStringList) {
+ this.enumStringList = enumStringList;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaFragmentFiles.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaFragmentFiles.java
new file mode 100644
index 0000000..3c35a71
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaFragmentFiles.java
@@ -0,0 +1,1663 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.RpcNotificationContainer;
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangLeavesHolder;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.javamodel.JavaLeafInfoContainer;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaGrouping;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
+import org.onosproject.yangutils.translator.tojava.utils.JavaExtendsListHolder;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.getParentNodeInGenCode;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_ENUM_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_TYPE_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.IMPL_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ATTRIBUTES_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EQUALS_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.FROM_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.HASH_CODE_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.TO_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getAttributeInfoForTheData;
+import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getQualifiedInfoOfFromString;
+import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getQualifiedTypeInfoOfCurNode;
+import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.updateJavaFileInfo;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getJavaAttributeDefination;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getJavaClassDefClose;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateBuilderClassFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateBuilderInterfaceFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateImplClassFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateInterfaceFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGeneratorUtils.getFileObject;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getRootPackage;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getBuildString;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getDefaultConstructorString;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEqualsMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getFromStringMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getGetterForClass;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getGetterString;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getHashCodeMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getOfMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getOverRideString;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getSetterForClass;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getSetterString;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getToStringMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.parseBuilderInterfaceBuildMethodString;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.addArrayListImport;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.addAugmentationHoldersImport;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.addAugmentedInfoImport;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.closeFile;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.isAugmentationHolderExtended;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.isAugmentedInfoExtended;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.sortImports;
+import static org.onosproject.yangutils.utils.UtilConstants.ACTIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER;
+import static org.onosproject.yangutils.utils.UtilConstants.COMPONENT;
+import static org.onosproject.yangutils.utils.UtilConstants.DEACTIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPL;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.INTERFACE;
+import static org.onosproject.yangutils.utils.UtilConstants.MANAGER;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.REFERENCE;
+import static org.onosproject.yangutils.utils.UtilConstants.REFERENCE_CARDINALITY;
+import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.SERVICE;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.createPackage;
+import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.readAppendFile;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.GETTER_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.OF_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getAbsolutePackagePath;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.insertDataIntoJavaFile;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.mergeJavaFiles;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.validateLineLength;
+
+/**
+ * Represents implementation of java code fragments temporary implementations.
+ * Manages the common temp file required for Java file(s) generated.
+ */
+public class TempJavaFragmentFiles {
+
+ /**
+ * Information about the java files being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * Imported class info.
+ */
+ private JavaImportData javaImportData;
+
+ /**
+ * The variable which guides the types of temporary files generated using
+ * the temporary generated file types mask.
+ */
+ private int generatedTempFiles;
+
+ /**
+ * Absolute path where the target java file needs to be generated.
+ */
+ private String absoluteDirPath;
+
+ /**
+ * Contains all the interface(s)/class name which will be extended by generated files.
+ */
+ private JavaExtendsListHolder javaExtendsListHolder;
+
+ /**
+ * File type extension for java classes.
+ */
+ private static final String JAVA_FILE_EXTENSION = ".java";
+
+ /**
+ * File type extension for temporary classes.
+ */
+ private static final String TEMP_FILE_EXTENSION = ".tmp";
+
+ /**
+ * Folder suffix for temporary files folder.
+ */
+ private static final String TEMP_FOLDER_NAME_SUFIX = "-Temp";
+
+ /**
+ * File name for getter method.
+ */
+ private static final String GETTER_METHOD_FILE_NAME = "GetterMethod";
+
+ /**
+ * File name for setter method.
+ */
+ private static final String SETTER_METHOD_FILE_NAME = "SetterMethod";
+
+ /**
+ * File name for getter method implementation.
+ */
+ private static final String GETTER_METHOD_IMPL_FILE_NAME = "GetterMethodImpl";
+
+ /**
+ * File name for setter method implementation.
+ */
+ private static final String SETTER_METHOD_IMPL_FILE_NAME = "SetterMethodImpl";
+
+ /**
+ * File name for attributes.
+ */
+ private static final String ATTRIBUTE_FILE_NAME = "Attributes";
+
+ /**
+ * File name for to string method.
+ */
+ private static final String TO_STRING_METHOD_FILE_NAME = "ToString";
+
+ /**
+ * File name for hash code method.
+ */
+ private static final String HASH_CODE_METHOD_FILE_NAME = "HashCode";
+
+ /**
+ * File name for equals method.
+ */
+ private static final String EQUALS_METHOD_FILE_NAME = "Equals";
+
+ /**
+ * File name for from string method.
+ */
+ private static final String FROM_STRING_METHOD_FILE_NAME = "FromString";
+
+ /**
+ * File name for interface java file name suffix.
+ */
+ private static final String INTERFACE_FILE_NAME_SUFFIX = EMPTY_STRING;
+
+ /**
+ * File name for builder interface file name suffix.
+ */
+ private static final String BUILDER_INTERFACE_FILE_NAME_SUFFIX = BUILDER + INTERFACE;
+
+ /**
+ * File name for builder class file name suffix.
+ */
+ private static final String BUILDER_CLASS_FILE_NAME_SUFFIX = BUILDER;
+
+ /**
+ * File name for impl class file name suffix.
+ */
+ private static final String IMPL_CLASS_FILE_NAME_SUFFIX = IMPL;
+
+ /**
+ * Java file handle for interface file.
+ */
+ private File interfaceJavaFileHandle;
+
+ /**
+ * Java file handle for builder interface file.
+ */
+ private File builderInterfaceJavaFileHandle;
+
+ /**
+ * Java file handle for builder class file.
+ */
+ private File builderClassJavaFileHandle;
+
+ /**
+ * Java file handle for impl class file.
+ */
+ private File implClassJavaFileHandle;
+
+ /**
+ * Temporary file handle for attribute.
+ */
+ private File attributesTempFileHandle;
+
+ /**
+ * Temporary file handle for getter of interface.
+ */
+ private File getterInterfaceTempFileHandle;
+
+ /**
+ * Temporary file handle for setter of interface.
+ */
+ private File setterInterfaceTempFileHandle;
+
+ /**
+ * Temporary file handle for getter of class.
+ */
+ private File getterImplTempFileHandle;
+
+ /**
+ * Temporary file handle for setter of class.
+ */
+ private File setterImplTempFileHandle;
+
+ /**
+ * Temporary file handle for hash code method of class.
+ */
+ private File hashCodeImplTempFileHandle;
+
+ /**
+ * Temporary file handle for equals method of class.
+ */
+ private File equalsImplTempFileHandle;
+
+ /**
+ * Temporary file handle for to string method of class.
+ */
+ private File toStringImplTempFileHandle;
+
+ /**
+ * Temporary file handle for from string method of class.
+ */
+ private File fromStringImplTempFileHandle;
+
+ /**
+ * Import info for case.
+ */
+ private JavaQualifiedTypeInfo caseImportInfo;
+
+ /**
+ * Is attribute added.
+ */
+ private boolean isAttributePresent;
+
+ /**
+ * Retrieves the absolute path where the file needs to be generated.
+ *
+ * @return absolute path where the file needs to be generated
+ */
+ private String getAbsoluteDirPath() {
+ return absoluteDirPath;
+ }
+
+ /**
+ * Sets absolute path where the file needs to be generated.
+ *
+ * @param absoluteDirPath absolute path where the file needs to be
+ * generated.
+ */
+ void setAbsoluteDirPath(String absoluteDirPath) {
+ this.absoluteDirPath = absoluteDirPath;
+ }
+
+ /**
+ * Sets the generated java file information.
+ *
+ * @param javaFileInfo generated java file information
+ */
+ public void setJavaFileInfo(JavaFileInfo javaFileInfo) {
+ this.javaFileInfo = javaFileInfo;
+ }
+
+ /**
+ * Retrieves the generated java file information.
+ *
+ * @return generated java file information
+ */
+ public JavaFileInfo getJavaFileInfo() {
+ return javaFileInfo;
+ }
+
+ /**
+ * Retrieves the generated temp files.
+ *
+ * @return generated temp files
+ */
+ int getGeneratedTempFiles() {
+ return generatedTempFiles;
+ }
+
+ /**
+ * Clears the generated file mask.
+ */
+ void clearGeneratedTempFileMask() {
+ generatedTempFiles = 0;
+ }
+
+ /**
+ * Adds to generated temporary files.
+ *
+ * @param generatedTempFile generated file
+ */
+ void addGeneratedTempFile(int generatedTempFile) {
+ generatedTempFiles |= generatedTempFile;
+ setGeneratedTempFiles(generatedTempFiles);
+ }
+
+ /**
+ * Sets generated file files.
+ *
+ * @param fileType generated file type
+ */
+ void setGeneratedTempFiles(int fileType) {
+ generatedTempFiles = fileType;
+ }
+
+ /**
+ * Retrieves the generated Java files.
+ *
+ * @return generated Java files
+ */
+ int getGeneratedJavaFiles() {
+ return getJavaFileInfo().getGeneratedFileTypes();
+ }
+
+ /**
+ * Retrieves the mapped Java class name.
+ *
+ * @return mapped Java class name
+ */
+ String getGeneratedJavaClassName() {
+ return getCapitalCase(getJavaFileInfo().getJavaName());
+ }
+
+ /**
+ * Retrieves the import data for the generated Java file.
+ *
+ * @return import data for the generated Java file
+ */
+ public JavaImportData getJavaImportData() {
+ return javaImportData;
+ }
+
+ /**
+ * Sets import data for the generated Java file.
+ *
+ * @param javaImportData import data for the generated Java file
+ */
+ void setJavaImportData(JavaImportData javaImportData) {
+ this.javaImportData = javaImportData;
+ }
+
+ /**
+ * Retrieves the status of any attributes added.
+ *
+ * @return status of any attributes added
+ */
+ public boolean isAttributePresent() {
+ return isAttributePresent;
+ }
+
+ /**
+ * Sets status of any attributes added.
+ *
+ * @param attributePresent status of any attributes added
+ */
+ public void setAttributePresent(boolean attributePresent) {
+ isAttributePresent = attributePresent;
+ }
+
+ /**
+ * Returns getter methods's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getGetterInterfaceTempFileHandle() {
+ return getterInterfaceTempFileHandle;
+ }
+
+ /**
+ * Sets to getter method's temporary file handle.
+ *
+ * @param getterForInterface file handle for to getter method
+ */
+ private void setGetterInterfaceTempFileHandle(File getterForInterface) {
+ getterInterfaceTempFileHandle = getterForInterface;
+ }
+
+ /**
+ * Returns setter method's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getSetterInterfaceTempFileHandle() {
+ return setterInterfaceTempFileHandle;
+ }
+
+ /**
+ * Sets to setter method's temporary file handle.
+ *
+ * @param setterForInterface file handle for to setter method
+ */
+ private void setSetterInterfaceTempFileHandle(File setterForInterface) {
+ setterInterfaceTempFileHandle = setterForInterface;
+ }
+
+ /**
+ * Returns setter method's impl's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getSetterImplTempFileHandle() {
+ return setterImplTempFileHandle;
+ }
+
+ /**
+ * Sets to setter method's impl's temporary file handle.
+ *
+ * @param setterImpl file handle for to setter method's implementation class
+ */
+ private void setSetterImplTempFileHandle(File setterImpl) {
+ setterImplTempFileHandle = setterImpl;
+ }
+
+ /**
+ * Returns from string method's temporary file handle.
+ *
+ * @return from string method's temporary file handle
+ */
+ public File getFromStringImplTempFileHandle() {
+ return fromStringImplTempFileHandle;
+ }
+
+ /**
+ * Sets from string method's temporary file handle.
+ *
+ * @param fromStringImplTempFileHandle from string method's temporary file
+ * handle
+ */
+ private void setFromStringImplTempFileHandle(File fromStringImplTempFileHandle) {
+ this.fromStringImplTempFileHandle = fromStringImplTempFileHandle;
+ }
+
+ /**
+ * Creates an instance of temporary java code fragment.
+ *
+ * @param javaFileInfo generated java file information
+ * @throws IOException when fails to create new file handle
+ */
+ TempJavaFragmentFiles(JavaFileInfo javaFileInfo)
+ throws IOException {
+ setJavaExtendsListHolder(new JavaExtendsListHolder());
+ setJavaImportData(new JavaImportData());
+ setJavaFileInfo(javaFileInfo);
+ setAbsoluteDirPath(getAbsolutePackagePath(getJavaFileInfo().getBaseCodeGenPath(),
+ getJavaFileInfo().getPackageFilePath()));
+
+ /*
+ * Initialize getter when generation file type matches to interface
+ * mask.
+ */
+ if ((getGeneratedJavaFiles() & INTERFACE_MASK) != 0) {
+ addGeneratedTempFile(GETTER_FOR_INTERFACE_MASK);
+ }
+
+ /*
+ * Initialize getter and setter when generation file type matches to
+ * builder interface mask.
+ */
+ if ((getGeneratedJavaFiles() & BUILDER_INTERFACE_MASK) != 0) {
+ addGeneratedTempFile(GETTER_FOR_INTERFACE_MASK);
+ addGeneratedTempFile(SETTER_FOR_INTERFACE_MASK);
+ }
+
+ /*
+ * Initialize getterImpl, setterImpl and attributes when generation file
+ * type matches to builder class mask.
+ */
+ if ((getGeneratedJavaFiles() & BUILDER_CLASS_MASK) != 0) {
+ addGeneratedTempFile(ATTRIBUTES_MASK);
+ addGeneratedTempFile(GETTER_FOR_CLASS_MASK);
+ addGeneratedTempFile(SETTER_FOR_CLASS_MASK);
+ }
+
+ /*
+ * Initialize getterImpl, attributes, constructor, hash code, equals and
+ * to strings when generation file type matches to impl class mask.
+ */
+ if ((getGeneratedJavaFiles() & IMPL_CLASS_MASK) != 0) {
+ addGeneratedTempFile(ATTRIBUTES_MASK);
+ addGeneratedTempFile(GETTER_FOR_CLASS_MASK);
+ addGeneratedTempFile(HASH_CODE_IMPL_MASK);
+ addGeneratedTempFile(EQUALS_IMPL_MASK);
+ addGeneratedTempFile(TO_STRING_IMPL_MASK);
+ }
+
+ /*
+ * Initialize temp files to generate type class.
+ */
+ if ((getGeneratedJavaFiles() & GENERATE_TYPE_CLASS) != 0) {
+ addGeneratedTempFile(ATTRIBUTES_MASK);
+ addGeneratedTempFile(GETTER_FOR_CLASS_MASK);
+ addGeneratedTempFile(HASH_CODE_IMPL_MASK);
+ addGeneratedTempFile(EQUALS_IMPL_MASK);
+ addGeneratedTempFile(TO_STRING_IMPL_MASK);
+ addGeneratedTempFile(FROM_STRING_IMPL_MASK);
+ }
+
+ /*
+ * Initialize temp files to generate enum class.
+ */
+ if ((getGeneratedJavaFiles() & GENERATE_ENUM_CLASS) != 0) {
+ addGeneratedTempFile(FROM_STRING_IMPL_MASK);
+ }
+ /*
+ * Initialize getter and setter when generation file type matches to
+ * builder interface mask.
+ */
+ if ((getGeneratedJavaFiles() & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ addGeneratedTempFile(GETTER_FOR_INTERFACE_MASK);
+ addGeneratedTempFile(SETTER_FOR_INTERFACE_MASK);
+ addGeneratedTempFile(GETTER_FOR_CLASS_MASK);
+ addGeneratedTempFile(SETTER_FOR_CLASS_MASK);
+ }
+
+ /*
+ * Set temporary file handles.
+ */
+ if ((getGeneratedTempFiles() & ATTRIBUTES_MASK) != 0) {
+ setAttributesTempFileHandle(getTemporaryFileHandle(ATTRIBUTE_FILE_NAME));
+ }
+
+ if ((getGeneratedTempFiles() & GETTER_FOR_INTERFACE_MASK) != 0) {
+ setGetterInterfaceTempFileHandle(getTemporaryFileHandle(GETTER_METHOD_FILE_NAME));
+ }
+
+ if ((getGeneratedTempFiles() & SETTER_FOR_INTERFACE_MASK) != 0) {
+ setSetterInterfaceTempFileHandle(getTemporaryFileHandle(SETTER_METHOD_FILE_NAME));
+ }
+
+ if ((getGeneratedTempFiles() & GETTER_FOR_CLASS_MASK) != 0) {
+ setGetterImplTempFileHandle(getTemporaryFileHandle(GETTER_METHOD_IMPL_FILE_NAME));
+ }
+
+ if ((getGeneratedTempFiles() & SETTER_FOR_CLASS_MASK) != 0) {
+ setSetterImplTempFileHandle(getTemporaryFileHandle(SETTER_METHOD_IMPL_FILE_NAME));
+ }
+
+ if ((getGeneratedTempFiles() & HASH_CODE_IMPL_MASK) != 0) {
+ setHashCodeImplTempFileHandle(getTemporaryFileHandle(HASH_CODE_METHOD_FILE_NAME));
+ }
+ if ((getGeneratedTempFiles() & EQUALS_IMPL_MASK) != 0) {
+ setEqualsImplTempFileHandle(getTemporaryFileHandle(EQUALS_METHOD_FILE_NAME));
+ }
+ if ((getGeneratedTempFiles() & TO_STRING_IMPL_MASK) != 0) {
+ setToStringImplTempFileHandle(getTemporaryFileHandle(TO_STRING_METHOD_FILE_NAME));
+ }
+ if ((getGeneratedTempFiles() & FROM_STRING_IMPL_MASK) != 0) {
+ setFromStringImplTempFileHandle(getTemporaryFileHandle(FROM_STRING_METHOD_FILE_NAME));
+ }
+
+ }
+
+ /**
+ * Returns java file handle for interface file.
+ *
+ * @return java file handle for interface file
+ */
+ private File getInterfaceJavaFileHandle() {
+ return interfaceJavaFileHandle;
+ }
+
+ /**
+ * Sets the java file handle for interface file.
+ *
+ * @param interfaceJavaFileHandle java file handle
+ */
+ private void setInterfaceJavaFileHandle(File interfaceJavaFileHandle) {
+ this.interfaceJavaFileHandle = interfaceJavaFileHandle;
+ }
+
+ /**
+ * Returns java file handle for builder interface file.
+ *
+ * @return java file handle for builder interface file
+ */
+ private File getBuilderInterfaceJavaFileHandle() {
+ return builderInterfaceJavaFileHandle;
+ }
+
+ /**
+ * Sets the java file handle for builder interface file.
+ *
+ * @param builderInterfaceJavaFileHandle java file handle
+ */
+ private void setBuilderInterfaceJavaFileHandle(File builderInterfaceJavaFileHandle) {
+ this.builderInterfaceJavaFileHandle = builderInterfaceJavaFileHandle;
+ }
+
+ /**
+ * Returns java file handle for builder class file.
+ *
+ * @return java file handle for builder class file
+ */
+ private File getBuilderClassJavaFileHandle() {
+ return builderClassJavaFileHandle;
+ }
+
+ /**
+ * Sets the java file handle for builder class file.
+ *
+ * @param builderClassJavaFileHandle java file handle
+ */
+ private void setBuilderClassJavaFileHandle(File builderClassJavaFileHandle) {
+ this.builderClassJavaFileHandle = builderClassJavaFileHandle;
+ }
+
+ /**
+ * Returns java file handle for impl class file.
+ *
+ * @return java file handle for impl class file
+ */
+ private File getImplClassJavaFileHandle() {
+ return implClassJavaFileHandle;
+ }
+
+ /**
+ * Sets the java file handle for impl class file.
+ *
+ * @param implClassJavaFileHandle java file handle
+ */
+ private void setImplClassJavaFileHandle(File implClassJavaFileHandle) {
+ this.implClassJavaFileHandle = implClassJavaFileHandle;
+ }
+
+ /**
+ * Returns attribute's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getAttributesTempFileHandle() {
+ return attributesTempFileHandle;
+ }
+
+ /**
+ * Sets attribute's temporary file handle.
+ *
+ * @param attributeForClass file handle for attribute
+ */
+ void setAttributesTempFileHandle(File attributeForClass) {
+ attributesTempFileHandle = attributeForClass;
+ }
+
+ /**
+ * Returns getter method's impl's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getGetterImplTempFileHandle() {
+ return getterImplTempFileHandle;
+ }
+
+ /**
+ * Sets to getter method's impl's temporary file handle.
+ *
+ * @param getterImpl file handle for to getter method's impl
+ */
+ void setGetterImplTempFileHandle(File getterImpl) {
+ getterImplTempFileHandle = getterImpl;
+ }
+
+ /**
+ * Returns hash code method's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getHashCodeImplTempFileHandle() {
+ return hashCodeImplTempFileHandle;
+ }
+
+ /**
+ * Sets hash code method's temporary file handle.
+ *
+ * @param hashCodeMethod file handle for hash code method
+ */
+ void setHashCodeImplTempFileHandle(File hashCodeMethod) {
+ hashCodeImplTempFileHandle = hashCodeMethod;
+ }
+
+ /**
+ * Returns equals mehtod's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getEqualsImplTempFileHandle() {
+ return equalsImplTempFileHandle;
+ }
+
+ /**
+ * Sets equals method's temporary file handle.
+ *
+ * @param equalsMethod file handle for to equals method
+ */
+ void setEqualsImplTempFileHandle(File equalsMethod) {
+ equalsImplTempFileHandle = equalsMethod;
+ }
+
+ /**
+ * Returns to string method's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getToStringImplTempFileHandle() {
+ return toStringImplTempFileHandle;
+ }
+
+ /**
+ * Sets to string method's temporary file handle.
+ *
+ * @param toStringMethod file handle for to string method
+ */
+ void setToStringImplTempFileHandle(File toStringMethod) {
+ toStringImplTempFileHandle = toStringMethod;
+ }
+
+ /**
+ * Returns java extends list holder.
+ *
+ * @return java extends list holder
+ */
+ public JavaExtendsListHolder getJavaExtendsListHolder() {
+ return javaExtendsListHolder;
+ }
+
+ /**
+ * Sets java extends list holder.
+ *
+ * @param javaExtendsListHolder java extends list holder
+ */
+ public void setJavaExtendsListHolder(JavaExtendsListHolder javaExtendsListHolder) {
+ this.javaExtendsListHolder = javaExtendsListHolder;
+ }
+
+ /**
+ * Adds attribute for class.
+ *
+ * @param attr attribute info
+ * @param yangPluginConfig plugin configurations
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addAttribute(JavaAttributeInfo attr, YangPluginConfig yangPluginConfig)
+ throws IOException {
+ appendToFile(getAttributesTempFileHandle(), parseAttribute(attr, yangPluginConfig)
+ + FOUR_SPACE_INDENTATION);
+ }
+
+ /**
+ * Adds getter for interface.
+ *
+ * @param attr attribute info
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addGetterForInterface(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
+ throws IOException {
+ appendToFile(getGetterInterfaceTempFileHandle(),
+ getGetterString(attr, getGeneratedJavaFiles(), pluginConfig) + NEW_LINE);
+ }
+
+ /**
+ * Adds setter for interface.
+ *
+ * @param attr attribute info
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addSetterForInterface(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
+ throws IOException {
+ appendToFile(getSetterInterfaceTempFileHandle(),
+ getSetterString(attr, getGeneratedJavaClassName(), getGeneratedJavaFiles(), pluginConfig)
+ + NEW_LINE);
+ }
+
+ /**
+ * Adds setter's implementation for class.
+ *
+ * @param attr attribute info
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addSetterImpl(JavaAttributeInfo attr)
+ throws IOException {
+ appendToFile(getSetterImplTempFileHandle(),
+ getOverRideString() + getSetterForClass(attr, getGeneratedJavaClassName(), getGeneratedJavaFiles())
+ +
+ NEW_LINE);
+ }
+
+ /**
+ * Adds getter method's impl for class.
+ *
+ * @param attr attribute info
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addGetterImpl(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
+ throws IOException {
+ if ((getGeneratedJavaFiles() & BUILDER_CLASS_MASK) != 0
+ || (getGeneratedJavaFiles() & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ appendToFile(getGetterImplTempFileHandle(), getOverRideString() + getGetterForClass(attr,
+ getGeneratedJavaFiles()) + NEW_LINE);
+ } else {
+ appendToFile(getGetterImplTempFileHandle(),
+ getJavaDoc(GETTER_METHOD, getCapitalCase(attr.getAttributeName()), false, pluginConfig)
+ + getGetterForClass(attr, getGeneratedJavaFiles()) + NEW_LINE);
+ }
+ }
+
+ /**
+ * Adds build method for interface.
+ *
+ * @param pluginConfig plugin configurations
+ * @return build method for interface
+ * @throws IOException when fails to append to temporary file
+ */
+ String addBuildMethodForInterface(YangPluginConfig pluginConfig)
+ throws IOException {
+ return parseBuilderInterfaceBuildMethodString(getGeneratedJavaClassName(), pluginConfig);
+ }
+
+ /**
+ * Adds build method's implementation for class.
+ *
+ * @return build method implementation for class
+ * @throws IOException when fails to append to temporary file
+ */
+ String addBuildMethodImpl()
+ throws IOException {
+ return getBuildString(getGeneratedJavaClassName()) + NEW_LINE;
+ }
+
+ /**
+ * Adds default constructor for class.
+ *
+ * @param modifier modifier for constructor.
+ * @param toAppend string which need to be appended with the class name
+ * @param pluginConfig plugin configurations
+ * @return default constructor for class
+ * @throws IOException when fails to append to file
+ */
+ String addDefaultConstructor(String modifier, String toAppend, YangPluginConfig pluginConfig)
+ throws IOException {
+ return NEW_LINE
+ + getDefaultConstructorString(getGeneratedJavaClassName() + toAppend, modifier, pluginConfig);
+ }
+
+ /**
+ * Adds default constructor for class.
+ *
+ * @param pluginCnfig plugin configurations
+ * @return default constructor for class
+ * @throws IOException when fails to append to file
+ */
+ public String addOfMethod(YangPluginConfig pluginCnfig)
+ throws IOException {
+ return getJavaDoc(OF_METHOD, getGeneratedJavaClassName(), false, pluginCnfig)
+ + getOfMethod(getGeneratedJavaClassName(), null);
+ }
+
+ /**
+ * Adds hash code method for class.
+ *
+ * @param attr attribute info
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addHashCodeMethod(JavaAttributeInfo attr)
+ throws IOException {
+ appendToFile(getHashCodeImplTempFileHandle(), getHashCodeMethod(attr) + NEW_LINE);
+ }
+
+ /**
+ * Adds equals method for class.
+ *
+ * @param attr attribute info
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addEqualsMethod(JavaAttributeInfo attr)
+ throws IOException {
+ appendToFile(getEqualsImplTempFileHandle(), getEqualsMethod(attr) + NEW_LINE);
+ }
+
+ /**
+ * Adds ToString method for class.
+ *
+ * @param attr attribute info
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addToStringMethod(JavaAttributeInfo attr)
+ throws IOException {
+ appendToFile(getToStringImplTempFileHandle(), getToStringMethod(attr) + NEW_LINE);
+ }
+
+ /**
+ * Adds from string method for union class.
+ *
+ * @param javaAttributeInfo type attribute info
+ * @param fromStringAttributeInfo from string attribute info
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addFromStringMethod(JavaAttributeInfo javaAttributeInfo,
+ JavaAttributeInfo fromStringAttributeInfo)
+ throws IOException {
+ appendToFile(getFromStringImplTempFileHandle(), getFromStringMethod(javaAttributeInfo,
+ fromStringAttributeInfo) + NEW_LINE);
+ }
+
+ /**
+ * Returns a temporary file handle for the specific file type.
+ *
+ * @param fileName file name
+ * @return temporary file handle
+ * @throws IOException when fails to create new file handle
+ */
+ File getTemporaryFileHandle(String fileName)
+ throws IOException {
+ String path = getTempDirPath();
+ File dir = new File(path);
+ if (!dir.exists()) {
+ dir.mkdirs();
+ }
+ File file = new File(path + fileName + TEMP_FILE_EXTENSION);
+ if (!file.exists()) {
+ file.createNewFile();
+ } else {
+ throw new IOException(fileName + " is reused due to YANG naming");
+ }
+ return file;
+ }
+
+ /**
+ * Returns a temporary file handle for the specific file type.
+ *
+ * @param fileName file name
+ * @return temporary file handle
+ * @throws IOException when fails to create new file handle
+ */
+ File getJavaFileHandle(String fileName)
+ throws IOException {
+ return getFileObject(getDirPath(), fileName, JAVA_FILE_EXTENSION, getJavaFileInfo());
+ }
+
+ /**
+ * Returns data from the temporary files.
+ *
+ * @param file temporary file handle
+ * @return stored data from temporary files
+ * @throws IOException when failed to get data from the given file
+ */
+ public String getTemporaryDataFromFileHandle(File file)
+ throws IOException {
+
+ String path = getTempDirPath();
+ if (new File(path + file.getName()).exists()) {
+ return readAppendFile(path + file.getName(), EMPTY_STRING);
+ } else {
+ throw new IOException("Unable to get data from the given "
+ + file.getName() + " file for " + getGeneratedJavaClassName() + PERIOD);
+ }
+ }
+
+ /**
+ * Returns temporary directory path.
+ *
+ * @return directory path
+ */
+ String getTempDirPath() {
+ return getPackageDirPathFromJavaJPackage(getAbsoluteDirPath()) + SLASH + getGeneratedJavaClassName()
+ + TEMP_FOLDER_NAME_SUFIX + SLASH;
+ }
+
+ /**
+ * Parses attribute to get the attribute string.
+ *
+ * @param attr attribute info
+ * @param pluginConfig plugin configurations
+ * @return attribute string
+ */
+ public String parseAttribute(JavaAttributeInfo attr, YangPluginConfig pluginConfig) {
+ /*
+ * TODO: check if this utility needs to be called or move to the caller
+ */
+ String attributeName = getCamelCase(attr.getAttributeName(), pluginConfig.getConflictResolver());
+ if (attr.isQualifiedName()) {
+ return getJavaAttributeDefination(attr.getImportInfo().getPkgInfo(),
+ attr.getImportInfo().getClassInfo(),
+ attributeName, attr.isListAttr());
+ } else {
+ return getJavaAttributeDefination(null, attr.getImportInfo().getClassInfo(), attributeName,
+ attr.isListAttr());
+ }
+ }
+
+ /**
+ * Appends content to temporary file.
+ *
+ * @param file temporary file
+ * @param data data to be appended
+ * @throws IOException when fails to append to file
+ */
+ void appendToFile(File file, String data)
+ throws IOException {
+ try {
+ insertDataIntoJavaFile(file, data);
+ } catch (IOException ex) {
+ throw new IOException("failed to write in temp file.");
+ }
+ }
+
+ /**
+ * Adds current node info as and attribute to the parent generated file.
+ *
+ * @param curNode current node which needs to be added as an attribute in
+ * the parent generated code
+ * @param isList is list construct
+ * @param pluginConfig plugin configurations
+ * @throws IOException IO operation exception
+ */
+ public static void addCurNodeInfoInParentTempFile(YangNode curNode,
+ boolean isList, YangPluginConfig pluginConfig)
+ throws IOException {
+ YangNode parent = getParentNodeInGenCode(curNode);
+ if (!(parent instanceof JavaCodeGenerator)) {
+ throw new TranslatorException("missing parent node to contain current node info in generated file");
+ }
+
+ if (parent instanceof YangJavaGrouping) {
+ /*
+ * In case of grouping, there is no need to add the information, it
+ * will be taken care in uses
+ */
+ return;
+ }
+
+ JavaAttributeInfo javaAttributeInfo = getCurNodeAsAttributeInTarget(curNode,
+ parent, isList);
+ if (!(parent instanceof TempJavaCodeFragmentFilesContainer)) {
+ throw new TranslatorException("missing parent temp file handle");
+ }
+ getNodesInterfaceFragmentFiles(parent)
+ .addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, pluginConfig);
+ }
+
+ /**
+ * Adds current node info as and attribute to the parent generated file.
+ *
+ * @param curNode current node which needs to be added as an attribute in
+ * the parent generated code
+ * @param pluginConfig plugin configurations
+ * @param targetNode target node to add the attribute
+ * @throws IOException IO operation exception
+ */
+ public static void addCurNodeAsAttributeInTargetTempFile(YangNode curNode,
+ YangPluginConfig pluginConfig, YangNode targetNode)
+ throws IOException {
+
+ if (!(targetNode instanceof JavaCodeGenerator)) {
+ throw new TranslatorException("invalid target node to generated file");
+ }
+
+ if (targetNode instanceof YangJavaGrouping) {
+ /*
+ * In case of grouping, there is no need to add the information, it
+ * will be taken care in uses
+ */
+ return;
+ }
+
+ boolean isList = curNode instanceof YangList;
+
+ JavaAttributeInfo javaAttributeInfo = getCurNodeAsAttributeInTarget(curNode,
+ targetNode, isList);
+ if (!(targetNode instanceof TempJavaCodeFragmentFilesContainer)) {
+ throw new TranslatorException("missing target node's temp file handle");
+ }
+ getNodesInterfaceFragmentFiles(targetNode)
+ .addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, pluginConfig);
+ }
+
+ /**
+ * Creates an attribute info object corresponding to a data model node and
+ * return it.
+ *
+ * @param curNode current data model node for which the java code generation
+ * is being handled
+ * @param targetNode target node in which the current node is an attribute
+ * @param isListNode is the current added attribute needs to be a list
+ * @return AttributeInfo attribute details required to add in temporary
+ * files
+ */
+ public static JavaAttributeInfo getCurNodeAsAttributeInTarget(YangNode curNode,
+ YangNode targetNode, boolean isListNode) {
+ String curNodeName = ((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName();
+ if (curNodeName == null) {
+ updateJavaFileInfo(curNode, null);
+ curNodeName = ((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName();
+ }
+
+ /*
+ * Get the import info corresponding to the attribute for import in
+ * generated java files or qualified access
+ */
+ JavaQualifiedTypeInfo qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(curNode,
+ getCapitalCase(curNodeName));
+ if (!(targetNode instanceof TempJavaCodeFragmentFilesContainer)) {
+ throw new TranslatorException("Parent node does not have file info");
+ }
+ TempJavaFragmentFiles tempJavaFragmentFiles = getNodesInterfaceFragmentFiles(targetNode);
+ JavaImportData parentImportData = tempJavaFragmentFiles.getJavaImportData();
+ JavaFileInfo fileInfo = ((JavaFileInfoContainer) targetNode).getJavaFileInfo();
+
+ boolean isQualified;
+ if ((targetNode instanceof YangJavaModule || targetNode instanceof YangJavaSubModule)
+ && (qualifiedTypeInfo.getClassInfo().contentEquals(SERVICE)
+ || qualifiedTypeInfo.getClassInfo().contentEquals(COMPONENT)
+ || qualifiedTypeInfo.getClassInfo().contentEquals(getCapitalCase(ACTIVATE))
+ || qualifiedTypeInfo.getClassInfo().contentEquals(getCapitalCase(DEACTIVATE))
+ || qualifiedTypeInfo.getClassInfo().contentEquals(REFERENCE_CARDINALITY)
+ || qualifiedTypeInfo.getClassInfo().contentEquals(REFERENCE))
+ || qualifiedTypeInfo.getClassInfo().contentEquals(getCapitalCase(fileInfo.getJavaName() + SERVICE))
+ || qualifiedTypeInfo.getClassInfo().contentEquals(getCapitalCase(fileInfo.getJavaName() + MANAGER))) {
+
+ isQualified = true;
+ } else {
+ String className;
+ if (targetNode instanceof YangJavaModule || targetNode instanceof YangJavaSubModule) {
+ className = getCapitalCase(fileInfo.getJavaName()) + "Service";
+ } else {
+ className = getCapitalCase(fileInfo.getJavaName());
+ }
+
+ isQualified = parentImportData.addImportInfo(qualifiedTypeInfo,
+ className, fileInfo.getPackage());
+ }
+
+ if (isListNode) {
+ parentImportData.setIfListImported(true);
+ }
+
+ return getAttributeInfoForTheData(qualifiedTypeInfo, curNodeName, null, isQualified, isListNode);
+ }
+
+ /**
+ * Resolves groupings java qualified info.
+ *
+ * @param curNode grouping node
+ * @param pluginConfig plugin configurations
+ * @return groupings java qualified info
+ */
+ public static JavaQualifiedTypeInfo resolveGroupingsQuailifiedInfo(YangNode curNode,
+ YangPluginConfig pluginConfig) {
+
+ JavaFileInfo groupingFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+ JavaQualifiedTypeInfo qualifiedTypeInfo = new JavaQualifiedTypeInfo();
+ if (groupingFileInfo.getPackage() == null) {
+ List<String> parentNames = new ArrayList<>();
+
+ YangNode tempNode = curNode.getParent();
+ YangNode groupingSuperParent = null;
+ while (tempNode != null) {
+ parentNames.add(tempNode.getName());
+ groupingSuperParent = tempNode;
+ tempNode = tempNode.getParent();
+ }
+
+ String pkg = null;
+ JavaFileInfo parentInfo = ((JavaFileInfoContainer) groupingSuperParent).getJavaFileInfo();
+ if (parentInfo.getPackage() == null) {
+ if (groupingSuperParent instanceof YangJavaModule) {
+ YangJavaModule module = (YangJavaModule) groupingSuperParent;
+ String modulePkg = getRootPackage(module.getVersion(), module.getNameSpace().getUri(), module
+ .getRevision().getRevDate(), pluginConfig.getConflictResolver());
+ pkg = modulePkg;
+ } else if (groupingSuperParent instanceof YangJavaSubModule) {
+ YangJavaSubModule submodule = (YangJavaSubModule) groupingSuperParent;
+ String subModulePkg = getRootPackage(submodule.getVersion(),
+ submodule.getNameSpaceFromModule(submodule.getBelongsTo()),
+ submodule.getRevision().getRevDate(), pluginConfig.getConflictResolver());
+ pkg = subModulePkg;
+ }
+ } else {
+ pkg = parentInfo.getPackage();
+ }
+ for (String name : parentNames) {
+ pkg = pkg + PERIOD + getCamelCase(name, pluginConfig.getConflictResolver());
+ }
+
+ qualifiedTypeInfo.setPkgInfo(pkg.toLowerCase());
+ qualifiedTypeInfo.setClassInfo(
+ getCapitalCase(getCamelCase(curNode.getName(), pluginConfig.getConflictResolver())));
+ return qualifiedTypeInfo;
+
+ } else {
+ qualifiedTypeInfo.setPkgInfo(groupingFileInfo.getPackage().toLowerCase());
+ qualifiedTypeInfo.setClassInfo(getCapitalCase(groupingFileInfo.getJavaName()));
+ return qualifiedTypeInfo;
+ }
+ }
+
+ /**
+ * Returns interface fragment files for node.
+ *
+ * @param node YANG node
+ * @return interface fragment files for node
+ */
+ public static TempJavaFragmentFiles getNodesInterfaceFragmentFiles(YangNode node) {
+ TempJavaFragmentFiles tempJavaFragmentFiles;
+ if (node instanceof RpcNotificationContainer) {
+ tempJavaFragmentFiles = ((TempJavaCodeFragmentFilesContainer) node)
+ .getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles();
+ } else {
+ tempJavaFragmentFiles = ((TempJavaCodeFragmentFilesContainer) node)
+ .getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles();
+ }
+ return tempJavaFragmentFiles;
+ }
+
+ /**
+ * Adds parent's info to current node import list.
+ *
+ * @param curNode current node for which import list needs to be updated
+ * @param pluginConfig plugin configurations
+ */
+ public void addParentInfoInCurNodeTempFile(YangNode curNode, YangPluginConfig pluginConfig) {
+ caseImportInfo = new JavaQualifiedTypeInfo();
+ YangNode parent = getParentNodeInGenCode(curNode);
+ if (!(parent instanceof JavaCodeGenerator)) {
+ throw new TranslatorException("missing parent node to contain current node info in generated file");
+ }
+ if (!(curNode instanceof JavaFileInfoContainer)) {
+ throw new TranslatorException("missing java file information to get the package details "
+ + "of attribute corresponding to child node");
+ }
+ caseImportInfo.setClassInfo(getCapitalCase(getCamelCase(parent.getName(),
+ pluginConfig.getConflictResolver())));
+ caseImportInfo.setPkgInfo(((JavaFileInfoContainer) parent).getJavaFileInfo().getPackage());
+
+ JavaFileInfo fileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles().getJavaImportData().addImportInfo(caseImportInfo,
+ getCapitalCase(fileInfo.getJavaName()), fileInfo.getPackage());
+ }
+
+ /**
+ * Adds leaf attributes in generated files.
+ *
+ * @param listOfLeaves list of YANG leaf
+ * @param yangPluginConfig plugin config
+ * @throws IOException IO operation fail
+ */
+ public void addLeavesInfoToTempFiles(List<YangLeaf> listOfLeaves,
+ YangPluginConfig yangPluginConfig)
+ throws IOException {
+ if (listOfLeaves != null) {
+ for (YangLeaf leaf : listOfLeaves) {
+ if (!(leaf instanceof JavaLeafInfoContainer)) {
+ throw new TranslatorException("Leaf does not have java information");
+ }
+ JavaLeafInfoContainer javaLeaf = (JavaLeafInfoContainer) leaf;
+ javaLeaf.setConflictResolveConfig(yangPluginConfig.getConflictResolver());
+ javaLeaf.updateJavaQualifiedInfo();
+ JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(
+ javaLeaf.getJavaQualifiedInfo(),
+ javaLeaf.getJavaName(yangPluginConfig.getConflictResolver()),
+ javaLeaf.getDataType(),
+ getIsQualifiedAccessOrAddToImportList(javaLeaf.getJavaQualifiedInfo()),
+ false);
+ addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, yangPluginConfig);
+ }
+ }
+ }
+
+ /**
+ * Adds leaf list's attributes in generated files.
+ *
+ * @param listOfLeafList list of YANG leaves
+ * @param yangPluginConfig plugin config
+ * @throws IOException IO operation fail
+ */
+ public void addLeafListInfoToTempFiles(List<YangLeafList> listOfLeafList, YangPluginConfig yangPluginConfig)
+ throws IOException {
+ if (listOfLeafList != null) {
+ for (YangLeafList leafList : listOfLeafList) {
+ if (!(leafList instanceof JavaLeafInfoContainer)) {
+ throw new TranslatorException("Leaf-list does not have java information");
+ }
+ JavaLeafInfoContainer javaLeaf = (JavaLeafInfoContainer) leafList;
+ javaLeaf.setConflictResolveConfig(yangPluginConfig.getConflictResolver());
+ javaLeaf.updateJavaQualifiedInfo();
+ getJavaImportData().setIfListImported(true);
+ JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(
+ javaLeaf.getJavaQualifiedInfo(),
+ javaLeaf.getJavaName(yangPluginConfig.getConflictResolver()),
+ javaLeaf.getDataType(),
+ getIsQualifiedAccessOrAddToImportList(javaLeaf.getJavaQualifiedInfo()),
+ true);
+ addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, yangPluginConfig);
+ }
+ }
+ }
+
+ /**
+ * Adds all the leaves in the current data model node as part of the
+ * generated temporary file.
+ *
+ * @param curNode java file info of the generated file
+ * @param yangPluginConfig plugin config
+ * @throws IOException IO operation fail
+ */
+ public void addCurNodeLeavesInfoToTempFiles(YangNode curNode,
+ YangPluginConfig yangPluginConfig)
+ throws IOException {
+ if (!(curNode instanceof YangLeavesHolder)) {
+ throw new TranslatorException("Data model node does not have any leaves");
+ }
+ YangLeavesHolder leavesHolder = (YangLeavesHolder) curNode;
+ addLeavesInfoToTempFiles(leavesHolder.getListOfLeaf(), yangPluginConfig);
+ addLeafListInfoToTempFiles(leavesHolder.getListOfLeafList(), yangPluginConfig);
+ }
+
+ /**
+ * Adds the new attribute info to the target generated temporary files.
+ *
+ * @param newAttrInfo the attribute info that needs to be added to temporary
+ * files
+ * @param pluginConfig plugin configurations
+ * @throws IOException IO operation fail
+ */
+ void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo, YangPluginConfig pluginConfig)
+ throws IOException {
+ setAttributePresent(true);
+ if ((getGeneratedTempFiles() & ATTRIBUTES_MASK) != 0) {
+ addAttribute(newAttrInfo, pluginConfig);
+ }
+
+ if ((getGeneratedTempFiles() & GETTER_FOR_INTERFACE_MASK) != 0) {
+ addGetterForInterface(newAttrInfo, pluginConfig);
+ }
+
+ if ((getGeneratedTempFiles() & SETTER_FOR_INTERFACE_MASK) != 0) {
+ addSetterForInterface(newAttrInfo, pluginConfig);
+ }
+
+ if ((getGeneratedTempFiles() & SETTER_FOR_CLASS_MASK) != 0) {
+ addSetterImpl(newAttrInfo);
+ }
+
+ if ((getGeneratedTempFiles() & GETTER_FOR_CLASS_MASK) != 0) {
+ addGetterImpl(newAttrInfo, pluginConfig);
+ }
+ if ((getGeneratedTempFiles() & HASH_CODE_IMPL_MASK) != 0) {
+ addHashCodeMethod(newAttrInfo);
+ }
+ if ((getGeneratedTempFiles() & EQUALS_IMPL_MASK) != 0) {
+ addEqualsMethod(newAttrInfo);
+ }
+ if ((getGeneratedTempFiles() & TO_STRING_IMPL_MASK) != 0) {
+ addToStringMethod(newAttrInfo);
+ }
+
+ if ((getGeneratedTempFiles() & FROM_STRING_IMPL_MASK) != 0) {
+ JavaQualifiedTypeInfo qualifiedInfoOfFromString = getQualifiedInfoOfFromString(newAttrInfo,
+ pluginConfig.getConflictResolver());
+ /*
+ * Create a new java attribute info with qualified information of
+ * wrapper classes.
+ */
+ JavaAttributeInfo fromStringAttributeInfo = getAttributeInfoForTheData(qualifiedInfoOfFromString,
+ newAttrInfo.getAttributeName(),
+ newAttrInfo.getAttributeType(),
+ getIsQualifiedAccessOrAddToImportList(qualifiedInfoOfFromString), false);
+
+ addFromStringMethod(newAttrInfo, fromStringAttributeInfo);
+ }
+ }
+
+ /**
+ * Returns java class name.
+ *
+ * @param suffix for the class name based on the file type
+ * @return java class name
+ */
+ String getJavaClassName(String suffix) {
+ return getCapitalCase(getJavaFileInfo().getJavaName()) + suffix;
+ }
+
+ /**
+ * Returns the directory path.
+ *
+ * @return directory path
+ */
+ private String getDirPath() {
+ return getJavaFileInfo().getPackageFilePath();
+ }
+
+ /**
+ * Constructs java code exit.
+ *
+ * @param fileType generated file type
+ * @param curNode current YANG node
+ * @throws IOException when fails to generate java files
+ */
+ public void generateJavaFile(int fileType, YangNode curNode)
+ throws IOException {
+ List<String> imports = new ArrayList<>();
+ imports = getJavaImportData().getImports();
+
+ createPackage(curNode);
+
+ /*
+ * Generate java code.
+ */
+ if ((fileType & INTERFACE_MASK) != 0 || (fileType &
+ BUILDER_INTERFACE_MASK) != 0) {
+
+ /*
+ * Create interface file.
+ */
+ setInterfaceJavaFileHandle(getJavaFileHandle(getJavaClassName(INTERFACE_FILE_NAME_SUFFIX)));
+ setInterfaceJavaFileHandle(
+ generateInterfaceFile(getInterfaceJavaFileHandle(), imports, curNode, isAttributePresent()));
+ /*
+ * Create builder interface file.
+ */
+ if ((fileType & BUILDER_INTERFACE_MASK) != 0) {
+ setBuilderInterfaceJavaFileHandle(
+ getJavaFileHandle(getJavaClassName(BUILDER_INTERFACE_FILE_NAME_SUFFIX)));
+ setBuilderInterfaceJavaFileHandle(
+ generateBuilderInterfaceFile(getBuilderInterfaceJavaFileHandle(), curNode,
+ isAttributePresent()));
+ /*
+ * Append builder interface file to interface file and close it.
+ */
+ mergeJavaFiles(getBuilderInterfaceJavaFileHandle(), getInterfaceJavaFileHandle());
+ validateLineLength(getInterfaceJavaFileHandle());
+ }
+ insertDataIntoJavaFile(getInterfaceJavaFileHandle(), getJavaClassDefClose());
+ if (isAugmentationHolderExtended(getJavaExtendsListHolder().getExtendsList())) {
+ addAugmentationHoldersImport(curNode, imports, false);
+ }
+ if (isAugmentedInfoExtended(getJavaExtendsListHolder().getExtendsList())) {
+ addAugmentedInfoImport(curNode, imports, false);
+ }
+ if (curNode instanceof YangCase) {
+ removeCaseImport(imports);
+ }
+ }
+ if ((fileType & BUILDER_CLASS_MASK) != 0 || (fileType & IMPL_CLASS_MASK) != 0) {
+ if (isAttributePresent()) {
+ addImportsToStringAndHasCodeMethods(curNode, imports);
+ }
+ if (isAugmentationHolderExtended(getJavaExtendsListHolder().getExtendsList())) {
+ addAugmentedInfoImport(curNode, imports, true);
+ addArrayListImport(curNode, imports, true);
+ }
+ sortImports(imports);
+ /*
+ * Create builder class file.
+ */
+ setBuilderClassJavaFileHandle(getJavaFileHandle(getJavaClassName(BUILDER_CLASS_FILE_NAME_SUFFIX)));
+ setBuilderClassJavaFileHandle(
+ generateBuilderClassFile(getBuilderClassJavaFileHandle(), imports, curNode,
+ isAttributePresent()));
+ /*
+ * Create impl class file.
+ */
+ if ((fileType & IMPL_CLASS_MASK) != 0) {
+ setImplClassJavaFileHandle(getJavaFileHandle(getJavaClassName(IMPL_CLASS_FILE_NAME_SUFFIX)));
+ setImplClassJavaFileHandle(
+ generateImplClassFile(getImplClassJavaFileHandle(), curNode, isAttributePresent()));
+ /*
+ * Append impl class to builder class and close it.
+ */
+ mergeJavaFiles(getImplClassJavaFileHandle(), getBuilderClassJavaFileHandle());
+ validateLineLength(getBuilderClassJavaFileHandle());
+ }
+ insertDataIntoJavaFile(getBuilderClassJavaFileHandle(), getJavaClassDefClose());
+ if (isAugmentationHolderExtended(getJavaExtendsListHolder().getExtendsList())) {
+ addAugmentedInfoImport(curNode, imports, false);
+ addArrayListImport(curNode, imports, false);
+ }
+ }
+ /*
+ * Close all the file handles.
+ */
+ freeTemporaryResources(false);
+ }
+
+ /**
+ * Adds imports for ToString and HashCodeMethod.
+ *
+ * @param curNode current YANG node
+ * @param imports import list
+ * @return import list
+ */
+ public List<String> addImportsToStringAndHasCodeMethods(YangNode curNode, List<String> imports) {
+ imports.add(getJavaImportData().getImportForHashAndEquals());
+ imports.add(getJavaImportData().getImportForToString());
+ return imports;
+ }
+
+ /**
+ * Removes case import info from import list.
+ *
+ * @param imports list of imports
+ * @return import for class
+ */
+ private List<String> removeCaseImport(List<String> imports) {
+ if (imports != null && caseImportInfo != null) {
+ String caseImport = IMPORT + caseImportInfo.getPkgInfo() + PERIOD + caseImportInfo.getClassInfo() +
+ SEMI_COLAN + NEW_LINE;
+ imports.remove(caseImport);
+ }
+ return imports;
+ }
+
+ /**
+ * Removes all temporary file handles.
+ *
+ * @param isErrorOccurred when translator fails to generate java files we
+ * need to close all open file handles include temporary files
+ * and java files.
+ * @throws IOException when failed to delete the temporary files
+ */
+ public void freeTemporaryResources(boolean isErrorOccurred)
+ throws IOException {
+ boolean isError = isErrorOccurred;
+ /*
+ * Close all java file handles and when error occurs delete the files.
+ */
+ if ((getGeneratedJavaFiles() & INTERFACE_MASK) != 0) {
+ closeFile(getInterfaceJavaFileHandle(), isError);
+ }
+ if ((getGeneratedJavaFiles() & BUILDER_CLASS_MASK) != 0) {
+ closeFile(getBuilderClassJavaFileHandle(), isError);
+ }
+ if ((getGeneratedJavaFiles() & BUILDER_INTERFACE_MASK) != 0) {
+ closeFile(getBuilderInterfaceJavaFileHandle(), true);
+ }
+ if ((getGeneratedJavaFiles() & IMPL_CLASS_MASK) != 0) {
+ closeFile(getImplClassJavaFileHandle(), true);
+ }
+
+ /*
+ * Close all temporary file handles and delete the files.
+ */
+ if ((getGeneratedTempFiles() & GETTER_FOR_CLASS_MASK) != 0) {
+ closeFile(getGetterImplTempFileHandle(), true);
+ }
+ if ((getGeneratedTempFiles() & ATTRIBUTES_MASK) != 0) {
+ closeFile(getAttributesTempFileHandle(), true);
+ }
+ if ((getGeneratedTempFiles() & HASH_CODE_IMPL_MASK) != 0) {
+ closeFile(getHashCodeImplTempFileHandle(), true);
+ }
+ if ((getGeneratedTempFiles() & TO_STRING_IMPL_MASK) != 0) {
+ closeFile(getToStringImplTempFileHandle(), true);
+ }
+ if ((getGeneratedTempFiles() & EQUALS_IMPL_MASK) != 0) {
+ closeFile(getEqualsImplTempFileHandle(), true);
+ }
+ if ((getGeneratedTempFiles() & FROM_STRING_IMPL_MASK) != 0) {
+ closeFile(getFromStringImplTempFileHandle(), true);
+ }
+ }
+
+ /**
+ * Returns if the attribute needs to be accessed in a qualified manner or
+ * not, if it needs to be imported, then the same needs to be done.
+ *
+ * @param importInfo import info for the current attribute being added
+ * @return status of the qualified access to the attribute
+ */
+ public boolean getIsQualifiedAccessOrAddToImportList(
+ JavaQualifiedTypeInfo importInfo) {
+
+ return getJavaImportData().addImportInfo(importInfo, getGeneratedJavaClassName(),
+ getJavaFileInfo().getPackage());
+ }
+
+ /**
+ * Checks if the import info is same as the package of the current generated
+ * java file.
+ *
+ * @param importInfo import info for an attribute
+ * @return true if the import info is same as the current nodes package
+ * false otherwise
+ */
+ public boolean isImportPkgEqualCurNodePkg(JavaQualifiedTypeInfo importInfo) {
+ return getJavaFileInfo().getPackage()
+ .contentEquals(importInfo.getPkgInfo());
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaServiceFragmentFiles.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaServiceFragmentFiles.java
new file mode 100644
index 0000000..0d6215e
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaServiceFragmentFiles.java
@@ -0,0 +1,802 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_ENUM_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_METHOD_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_ATTRIBUTE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_GETTER_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_SETTER_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.RPC_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.RPC_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getAttributeInfoForTheData;
+import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getQualifiedTypeInfoOfCurNode;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getJavaClassDefClose;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEventFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEventListenerFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEventSubjectFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateManagerClassFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateServiceInterfaceFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGeneratorUtils.getFileObject;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getEnumJavaAttribute;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getSmallCase;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getGetterForClass;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getRpcManagerMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getRpcServiceMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getSetterForClass;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.addAnnotationsImports;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.addListnersImport;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.closeFile;
+import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_REG;
+import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_SERVICE;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.RPC_INPUT_VAR_NAME;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.UtilConstants.VOID;
+import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.createPackage;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.generateJavaDocForRpc;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.ENUM_ATTRIBUTE;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.GETTER_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.MANAGER_SETTER_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.insertDataIntoJavaFile;
+
+/**
+ * Represents implementation of java service code fragments temporary implementations.
+ * Maintains the temp files required specific for service and manager java snippet generation.
+ */
+public class TempJavaServiceFragmentFiles
+ extends TempJavaFragmentFiles {
+
+ /**
+ * File name for rpc method.
+ */
+ private static final String RPC_INTERFACE_FILE_NAME = "Rpc";
+
+ /**
+ * File name for rpc implementation method.
+ */
+ private static final String RPC_IMPL_FILE_NAME = "RpcImpl";
+
+ /**
+ * File name for event enum temp file.
+ */
+ private static final String EVENT_ENUM_FILE_NAME = "EventEnum";
+
+ /**
+ * File name for event method temp file.
+ */
+ private static final String EVENT_METHOD_FILE_NAME = "EventMethod";
+
+ /**
+ * File name for event subject attribute temp file.
+ */
+ private static final String EVENT_SUBJECT_ATTRIBUTE_FILE_NAME = "EventSubjectAttribute";
+
+ /**
+ * File name for event subject getter temp file.
+ */
+ private static final String EVENT_SUBJECT_GETTER_FILE_NAME = "EventSubjectGetter";
+
+ /**
+ * File name for event subject setter temp file.
+ */
+ private static final String EVENT_SUBJECT_SETTER_FILE_NAME = "EventSubjectSetter";
+
+ /**
+ * File name for generated class file for service
+ * suffix.
+ */
+ private static final String SERVICE_FILE_NAME_SUFFIX = "Service";
+
+ /**
+ * File name for generated class file for manager
+ * suffix.
+ */
+ private static final String MANAGER_FILE_NAME_SUFFIX = "Manager";
+
+ /**
+ * File name for generated class file for special type like union, typedef
+ * suffix.
+ */
+ private static final String EVENT_FILE_NAME_SUFFIX = "Event";
+
+ /**
+ * File name for generated class file for special type like union, typedef
+ * suffix.
+ */
+ private static final String EVENT_LISTENER_FILE_NAME_SUFFIX = "Listener";
+
+ /**
+ * File name for generated class file for special type like union, typedef
+ * suffix.
+ */
+ public static final String EVENT_SUBJECT_NAME_SUFFIX = "EventSubject";
+
+ private static final String JAVA_FILE_EXTENSION = ".java";
+
+ /**
+ * Java file handle for event subject file.
+ */
+ private File eventSubjectJavaFileHandle;
+
+ /**
+ * Java file handle for event listener file.
+ */
+ private File eventListenerJavaFileHandle;
+
+ /**
+ * Java file handle for event file.
+ */
+ private File eventJavaFileHandle;
+
+ /**
+ * Temporary file handle for rpc interface.
+ */
+ private File rpcInterfaceTempFileHandle;
+
+ /**
+ * Temporary file handle for rpc manager impl.
+ */
+ private File rpcImplTempFileHandle;
+
+ /**
+ * Java file handle for rpc interface file.
+ */
+ private File serviceInterfaceJavaFileHandle;
+
+ /**
+ * Java file handle for manager impl file.
+ */
+ private File managerJavaFileHandle;
+
+ /**
+ * Java file handle for event enum impl file.
+ */
+ private File eventEnumTempFileHandle;
+
+ /**
+ * Java file handle for event method impl file.
+ */
+ private File eventMethodTempFileHandle;
+
+ /**
+ * Java file handle for event subject attribute file.
+ */
+ private File eventSubjectAttributeTempFileHandle;
+
+ /**
+ * Java file handle for event subject getter impl file.
+ */
+ private File eventSubjectGetterTempFileHandle;
+
+ /**
+ * Java file handle for event subject setter impl file.
+ */
+ private File eventSubjectSetterTempFileHandle;
+
+ /**
+ * Returns rpc method's java file handle.
+ *
+ * @return java file handle
+ */
+ private File getServiceInterfaceJavaFileHandle() {
+ return serviceInterfaceJavaFileHandle;
+ }
+
+ /**
+ * Sets rpc method's java file handle.
+ *
+ * @param serviceInterfaceJavaFileHandle file handle for to rpc method
+ */
+ private void setServiceInterfaceJavaFileHandle(File serviceInterfaceJavaFileHandle) {
+ this.serviceInterfaceJavaFileHandle = serviceInterfaceJavaFileHandle;
+ }
+
+ /**
+ * Returns managers java file handle.
+ *
+ * @return java file handle
+ */
+ public File getManagerJavaFileHandle() {
+ return managerJavaFileHandle;
+ }
+
+ /**
+ * Sets manager java file handle.
+ *
+ * @param managerJavaFileHandle file handle for to manager
+ */
+ public void setManagerJavaFileHandle(File managerJavaFileHandle) {
+ this.managerJavaFileHandle = managerJavaFileHandle;
+ }
+
+ /**
+ * Returns rpc method's temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ public File getRpcInterfaceTempFileHandle() {
+ return rpcInterfaceTempFileHandle;
+ }
+
+ /**
+ * Sets rpc method's temporary file handle.
+ *
+ * @param rpcInterfaceTempFileHandle file handle for to rpc method
+ */
+ private void setRpcInterfaceTempFileHandle(File rpcInterfaceTempFileHandle) {
+ this.rpcInterfaceTempFileHandle = rpcInterfaceTempFileHandle;
+ }
+
+ /**
+ * Retrieves the manager impl temp file.
+ *
+ * @return the manager impl temp file
+ */
+ public File getRpcImplTempFileHandle() {
+ return rpcImplTempFileHandle;
+ }
+
+ /**
+ * Sets the manager impl temp file.
+ *
+ * @param rpcImplTempFileHandle the manager impl temp file
+ */
+ public void setRpcImplTempFileHandle(File rpcImplTempFileHandle) {
+ this.rpcImplTempFileHandle = rpcImplTempFileHandle;
+ }
+
+ /**
+ * Returns event's java file handle.
+ *
+ * @return java file handle
+ */
+ private File getEventJavaFileHandle() {
+ return eventJavaFileHandle;
+ }
+
+ /**
+ * Sets event's java file handle.
+ *
+ * @param eventJavaFileHandle file handle for event
+ */
+ private void setEventJavaFileHandle(File eventJavaFileHandle) {
+ this.eventJavaFileHandle = eventJavaFileHandle;
+ }
+
+ /**
+ * Returns event listeners's java file handle.
+ *
+ * @return java file handle
+ */
+ private File getEventListenerJavaFileHandle() {
+ return eventListenerJavaFileHandle;
+ }
+
+ /**
+ * Sets event's java file handle.
+ *
+ * @param eventListenerJavaFileHandle file handle for event
+ */
+ private void setEventListenerJavaFileHandle(File eventListenerJavaFileHandle) {
+ this.eventListenerJavaFileHandle = eventListenerJavaFileHandle;
+ }
+
+ /**
+ * Returns event subject's java file handle.
+ *
+ * @return java file handle
+ */
+ private File getEventSubjectJavaFileHandle() {
+ return eventSubjectJavaFileHandle;
+ }
+
+ /**
+ * Sets event's subject java file handle.
+ *
+ * @param eventSubjectJavaFileHandle file handle for event's subject
+ */
+ private void setEventSubjectJavaFileHandle(File eventSubjectJavaFileHandle) {
+ this.eventSubjectJavaFileHandle = eventSubjectJavaFileHandle;
+ }
+
+ /**
+ * Creates an instance of temporary java code fragment.
+ *
+ * @param javaFileInfo generated file information
+ * @throws IOException when fails to create new file handle
+ */
+ public TempJavaServiceFragmentFiles(JavaFileInfo javaFileInfo)
+ throws IOException {
+ super(javaFileInfo);
+
+ addGeneratedTempFile(RPC_INTERFACE_MASK);
+ addGeneratedTempFile(RPC_IMPL_MASK);
+
+ addGeneratedTempFile(EVENT_ENUM_MASK);
+ addGeneratedTempFile(EVENT_METHOD_MASK);
+ addGeneratedTempFile(EVENT_SUBJECT_ATTRIBUTE_MASK);
+ addGeneratedTempFile(EVENT_SUBJECT_GETTER_MASK);
+ addGeneratedTempFile(EVENT_SUBJECT_SETTER_MASK);
+
+ setRpcInterfaceTempFileHandle(getTemporaryFileHandle(RPC_INTERFACE_FILE_NAME));
+ setRpcImplTempFileHandle(getTemporaryFileHandle(RPC_IMPL_FILE_NAME));
+
+ setEventEnumTempFileHandle(getTemporaryFileHandle(EVENT_ENUM_FILE_NAME));
+ setEventMethodTempFileHandle(getTemporaryFileHandle(EVENT_METHOD_FILE_NAME));
+ setEventSubjectAttributeTempFileHandle(getTemporaryFileHandle(EVENT_SUBJECT_ATTRIBUTE_FILE_NAME));
+ setEventSubjectGetterTempFileHandle(getTemporaryFileHandle(EVENT_SUBJECT_GETTER_FILE_NAME));
+ setEventSubjectSetterTempFileHandle(getTemporaryFileHandle(EVENT_SUBJECT_SETTER_FILE_NAME));
+ }
+
+ /**
+ * Constructs java code exit.
+ *
+ * @param fileType generated file type
+ * @param curNode current YANG node
+ * @throws IOException when fails to generate java files
+ */
+ @Override
+ public void generateJavaFile(int fileType, YangNode curNode)
+ throws IOException {
+ List<String> imports = getJavaImportData().getImports();
+
+ createPackage(curNode);
+
+ boolean isNotification = false;
+ if (curNode instanceof YangJavaModule) {
+ if (!((YangJavaModule) curNode).getNotificationNodes().isEmpty()) {
+ isNotification = true;
+ }
+ } else if (curNode instanceof YangJavaSubModule) {
+ if (!((YangJavaSubModule) curNode).getNotificationNodes().isEmpty()) {
+ isNotification = true;
+ }
+ }
+
+ if (isNotification) {
+ addListnersImport(curNode, imports, true, LISTENER_SERVICE);
+ }
+ /**
+ * Creates rpc interface file.
+ */
+ setServiceInterfaceJavaFileHandle(getJavaFileHandle(getJavaClassName(SERVICE_FILE_NAME_SUFFIX)));
+ generateServiceInterfaceFile(getServiceInterfaceJavaFileHandle(), curNode, imports, isAttributePresent());
+
+ if (isNotification) {
+ addListnersImport(curNode, imports, false, LISTENER_SERVICE);
+ addListnersImport(curNode, imports, true, LISTENER_REG);
+ }
+ addAnnotationsImports(imports, true);
+ /**
+ * Create builder class file.
+ */
+ setManagerJavaFileHandle(getJavaFileHandle(getJavaClassName(MANAGER_FILE_NAME_SUFFIX)));
+ generateManagerClassFile(getManagerJavaFileHandle(), imports, curNode, isAttributePresent());
+
+ insertDataIntoJavaFile(getManagerJavaFileHandle(), getJavaClassDefClose());
+ if (isNotification) {
+ addListnersImport(curNode, imports, false, LISTENER_REG);
+ }
+ addAnnotationsImports(imports, false);
+
+ if (isNotification) {
+ generateEventJavaFile(GENERATE_EVENT_CLASS, curNode);
+ generateEventListenerJavaFile(GENERATE_EVENT_LISTENER_INTERFACE, curNode);
+ generateEventSubjectJavaFile(GENERATE_EVENT_SUBJECT_CLASS, curNode);
+ }
+
+ /**
+ * Close all the file handles.
+ */
+ freeTemporaryResources(false);
+ }
+
+ /**
+ * Adds rpc string information to applicable temp file.
+ *
+ * @param javaAttributeInfoOfInput rpc's input node attribute info
+ * @param javaAttributeInfoOfOutput rpc's output node attribute info
+ * @param rpcName name of the rpc function
+ * @param pluginConfig plugin configurations
+ * @throws IOException IO operation fail
+ */
+ private void addRpcString(JavaAttributeInfo javaAttributeInfoOfInput,
+ JavaAttributeInfo javaAttributeInfoOfOutput, YangPluginConfig pluginConfig,
+ String rpcName)
+ throws IOException {
+ String rpcInput = EMPTY_STRING;
+ String rpcOutput = VOID;
+ String rpcInputJavaDoc = EMPTY_STRING;
+ if (javaAttributeInfoOfInput != null) {
+ rpcInput = getCapitalCase(javaAttributeInfoOfInput.getAttributeName());
+ }
+ if (javaAttributeInfoOfOutput != null) {
+ rpcOutput = getCapitalCase(javaAttributeInfoOfOutput.getAttributeName());
+ }
+ if (!rpcInput.equals(EMPTY_STRING)) {
+ rpcInputJavaDoc = RPC_INPUT_VAR_NAME;
+ }
+ appendToFile(getRpcInterfaceTempFileHandle(),
+ generateJavaDocForRpc(rpcName, rpcInputJavaDoc, rpcOutput, pluginConfig)
+ + getRpcServiceMethod(rpcName, rpcInput, rpcOutput, pluginConfig) + NEW_LINE);
+ appendToFile(getRpcImplTempFileHandle(),
+ getRpcManagerMethod(rpcName, rpcInput, rpcOutput, pluginConfig) + NEW_LINE);
+ }
+
+ /**
+ * Adds the JAVA rpc snippet information.
+ *
+ * @param javaAttributeInfoOfInput rpc's input node attribute info
+ * @param javaAttributeInfoOfOutput rpc's output node attribute info
+ * @param pluginConfig plugin configurations
+ * @param rpcName name of the rpc function
+ * @throws IOException IO operation fail
+ */
+ public void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo javaAttributeInfoOfInput,
+ JavaAttributeInfo javaAttributeInfoOfOutput, YangPluginConfig pluginConfig,
+ String rpcName)
+ throws IOException {
+ addRpcString(javaAttributeInfoOfInput, javaAttributeInfoOfOutput, pluginConfig, rpcName);
+ }
+
+ /**
+ * Constructs java code exit.
+ *
+ * @param fileType generated file type
+ * @param curNode current YANG node
+ * @throws IOException when fails to generate java files
+ */
+ public void generateEventJavaFile(int fileType, YangNode curNode)
+ throws IOException {
+
+ List<String> imports = new ArrayList<>();
+
+ imports.add(getJavaImportData().getAbstractEventsImport());
+ String curNodeInfo = getCapitalCase(((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName());
+ String nodeName = curNodeInfo + EVENT_STRING;
+
+ addEnumMethod(nodeName, curNodeInfo + EVENT_SUBJECT_NAME_SUFFIX);
+
+ /**
+ * Creates event interface file.
+ */
+ setEventJavaFileHandle(getJavaFileHandle(curNode, curNodeInfo + EVENT_FILE_NAME_SUFFIX));
+ generateEventFile(getEventJavaFileHandle(), curNode, imports);
+
+ /**
+ * Close all the file handles.
+ */
+ freeTemporaryResources(false);
+ }
+
+ /**
+ * Constructs java code exit.
+ *
+ * @param fileType generated file type
+ * @param curNode current YANG node
+ * @throws IOException when fails to generate java files
+ */
+ public void generateEventListenerJavaFile(int fileType, YangNode curNode)
+ throws IOException {
+
+ List<String> imports = new ArrayList<>();
+
+ imports.add(getJavaImportData().getEventListenerImport());
+ String curNodeInfo = getCapitalCase(((JavaFileInfoContainer) curNode)
+ .getJavaFileInfo().getJavaName());
+ /**
+ * Creates event listener interface file.
+ */
+ setEventListenerJavaFileHandle(
+ getJavaFileHandle(curNode, curNodeInfo + EVENT_LISTENER_FILE_NAME_SUFFIX));
+ generateEventListenerFile(getEventListenerJavaFileHandle(), curNode, imports);
+
+ /**
+ * Close all the file handles.
+ */
+ freeTemporaryResources(false);
+ }
+
+ /**
+ * Constructs java code exit.
+ *
+ * @param fileType generated file type
+ * @param curNode current YANG node
+ * @throws IOException when fails to generate java files
+ */
+ public void generateEventSubjectJavaFile(int fileType, YangNode curNode)
+ throws IOException {
+
+ String curNodeInfo = getCapitalCase(((JavaFileInfoContainer) curNode)
+ .getJavaFileInfo().getJavaName());
+ /**
+ * Creates event interface file.
+ */
+ setEventSubjectJavaFileHandle(getJavaFileHandle(curNode, curNodeInfo +
+ EVENT_SUBJECT_NAME_SUFFIX));
+ generateEventSubjectFile(getEventSubjectJavaFileHandle(), curNode);
+
+ /**
+ * Close all the file handles.
+ */
+ freeTemporaryResources(false);
+ }
+
+ /**
+ * Removes all temporary file handles.
+ *
+ * @param isErrorOccurred when translator fails to generate java files we
+ * need to close all open file handles include temporary files
+ * and java files.
+ * @throws IOException when failed to delete the temporary files
+ */
+ @Override
+ public void freeTemporaryResources(boolean isErrorOccurred)
+ throws IOException {
+ boolean isError = isErrorOccurred;
+
+ closeFile(getServiceInterfaceJavaFileHandle(), isError);
+ closeFile(getManagerJavaFileHandle(), isError);
+
+ if (getEventJavaFileHandle() != null) {
+ closeFile(getEventJavaFileHandle(), isError);
+ }
+ if (getEventListenerJavaFileHandle() != null) {
+ closeFile(getEventListenerJavaFileHandle(), isError);
+ }
+ if (getEventSubjectJavaFileHandle() != null) {
+ closeFile(getEventSubjectJavaFileHandle(), isError);
+ }
+
+ closeFile(getRpcInterfaceTempFileHandle(), true);
+ closeFile(getRpcImplTempFileHandle(), true);
+ closeFile(getGetterInterfaceTempFileHandle(), true);
+ closeFile(getSetterInterfaceTempFileHandle(), true);
+ closeFile(getSetterImplTempFileHandle(), true);
+
+ super.freeTemporaryResources(isErrorOccurred);
+
+ }
+
+ /**
+ * Returns event enum temp file.
+ *
+ * @return event enum temp file
+ */
+ public File getEventEnumTempFileHandle() {
+ return eventEnumTempFileHandle;
+ }
+
+ /**
+ * Sets event enum temp file.
+ *
+ * @param eventEnumTempFileHandle event enum temp file
+ */
+ public void setEventEnumTempFileHandle(File eventEnumTempFileHandle) {
+ this.eventEnumTempFileHandle = eventEnumTempFileHandle;
+ }
+
+ /**
+ * Returns event method temp file.
+ *
+ * @return event method temp file
+ */
+ public File getEventMethodTempFileHandle() {
+ return eventMethodTempFileHandle;
+ }
+
+ /**
+ * Sets event method temp file.
+ *
+ * @param eventMethodTempFileHandle event method temp file
+ */
+ public void setEventMethodTempFileHandle(File eventMethodTempFileHandle) {
+ this.eventMethodTempFileHandle = eventMethodTempFileHandle;
+ }
+
+ /**
+ * Returns event subject attribute temp file.
+ *
+ * @return event subject attribute temp file
+ */
+ public File getEventSubjectAttributeTempFileHandle() {
+ return eventSubjectAttributeTempFileHandle;
+ }
+
+ /**
+ * Sets event subject attribute temp file.
+ *
+ * @param eventSubjectAttributeTempFileHandle event subject attribute temp file
+ */
+ public void setEventSubjectAttributeTempFileHandle(File eventSubjectAttributeTempFileHandle) {
+ this.eventSubjectAttributeTempFileHandle = eventSubjectAttributeTempFileHandle;
+ }
+
+ /**
+ * Returns event subject getter temp file.
+ *
+ * @return event subject getter temp file
+ */
+ public File getEventSubjectGetterTempFileHandle() {
+ return eventSubjectGetterTempFileHandle;
+ }
+
+ /**
+ * Sets event subject getter temp file.
+ *
+ * @param eventSubjectGetterTempFileHandle event subject getter temp file
+ */
+ public void setEventSubjectGetterTempFileHandle(File eventSubjectGetterTempFileHandle) {
+ this.eventSubjectGetterTempFileHandle = eventSubjectGetterTempFileHandle;
+ }
+
+ /**
+ * Returns event subject setter temp file.
+ *
+ * @return event subject setter temp file
+ */
+ public File getEventSubjectSetterTempFileHandle() {
+ return eventSubjectSetterTempFileHandle;
+ }
+
+ /**
+ * Sets event subject setter temp file.
+ *
+ * @param eventSubjectSetterTempFileHandle event subject setter temp file
+ */
+ public void setEventSubjectSetterTempFileHandle(File eventSubjectSetterTempFileHandle) {
+ this.eventSubjectSetterTempFileHandle = eventSubjectSetterTempFileHandle;
+ }
+
+ /**
+ * Adds java snippet for events to event subject file.
+ *
+ * @param curNode current node
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to do IO operations
+ */
+ public void addJavaSnippetOfEvent(YangNode curNode, YangPluginConfig pluginConfig)
+ throws IOException {
+
+ String currentInfo = getCapitalCase(getCamelCase(((YangNotification) curNode).getName(),
+ pluginConfig.getConflictResolver()));
+ String notificationName = ((YangNotification) curNode).getName();
+
+ JavaQualifiedTypeInfo qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(curNode,
+ getCapitalCase(currentInfo));
+
+ JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(qualifiedTypeInfo, getSmallCase(currentInfo),
+ null, false, false);
+
+ /*Adds java info for event in respective temp files.*/
+ addEventEnum(notificationName, pluginConfig);
+ addEventSubjectAttribute(javaAttributeInfo, pluginConfig);
+ addEventSubjectGetter(javaAttributeInfo, pluginConfig);
+ addEventSubjectSetter(javaAttributeInfo, pluginConfig, currentInfo);
+ }
+
+ /*Adds event to enum temp file.*/
+ private void addEventEnum(String notificationName, YangPluginConfig pluginConfig)
+ throws IOException {
+ appendToFile(getEventEnumTempFileHandle(),
+ getJavaDoc(ENUM_ATTRIBUTE, notificationName, false, pluginConfig) + FOUR_SPACE_INDENTATION
+ + getEnumJavaAttribute(notificationName).toUpperCase() + COMMA + NEW_LINE);
+ }
+
+ /*Adds event method in event class*/
+ private void addEnumMethod(String eventClassname, String className)
+ throws IOException {
+ appendToFile(getEventMethodTempFileHandle(), getEventFileContents(eventClassname, className));
+ }
+
+ /*Adds event method contents to event file.*/
+ private static String getEventFileContents(String eventClassname, String classname) {
+ return "\n" +
+ " /**\n" +
+ " * Creates " + classname + " event with type and subject.\n" +
+ " *\n" +
+ " * @param type event type\n" +
+ " * @param subject subject " + classname + "\n" +
+ " */\n" +
+ " public " + eventClassname + "(Type type, " + getCapitalCase(classname) + " subject) {\n" +
+ " super(type, subject);\n" +
+ " }\n" +
+ "\n" +
+ " /**\n" +
+ " * Creates " + classname + " event with type, subject and time.\n" +
+ " *\n" +
+ " * @param type event type\n" +
+ " * @param subject subject " + classname + "\n" +
+ " * @param time time of event\n" +
+ " */\n" +
+ " public " + eventClassname + "(Type type, " + getCapitalCase(classname)
+ + " subject, long time) {\n" +
+ " super(type, subject, time);\n" +
+ " }\n" +
+ "\n";
+ }
+
+ /*Adds events to event subject file.*/
+ private void addEventSubjectAttribute(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
+ throws IOException {
+ appendToFile(getEventSubjectAttributeTempFileHandle(),
+ FOUR_SPACE_INDENTATION + parseAttribute(attr, pluginConfig));
+ }
+
+ /*Adds getter method for event in event subject class.*/
+ private void addEventSubjectGetter(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
+ throws IOException {
+ appendToFile(getEventSubjectGetterTempFileHandle(),
+ getJavaDoc(GETTER_METHOD, getCapitalCase(attr.getAttributeName()), false, pluginConfig)
+ + getGetterForClass(attr, GENERATE_EVENT_SUBJECT_CLASS) + NEW_LINE);
+ }
+
+ /*Adds setter method for event in event subject class.*/
+ private void addEventSubjectSetter(JavaAttributeInfo attr, YangPluginConfig pluginConfig, String className)
+ throws IOException {
+ appendToFile(getEventSubjectSetterTempFileHandle(),
+ getJavaDoc(MANAGER_SETTER_METHOD, getCapitalCase(attr.getAttributeName()), false, pluginConfig)
+ + getSetterForClass(attr, className, GENERATE_EVENT_SUBJECT_CLASS) + NEW_LINE);
+ }
+
+ /**
+ * Returns a temporary file handle for the event's file type.
+ *
+ * @param fileName file name
+ * @return temporary file handle
+ * @throws IOException when fails to create new file handle
+ */
+ private File getJavaFileHandle(YangNode curNode, String name)
+ throws IOException {
+
+ JavaFileInfo parentInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+
+ return getFileObject(getDirPath(parentInfo), name, JAVA_FILE_EXTENSION,
+ parentInfo);
+ }
+
+ /**
+ * Returns the directory path.
+ *
+ * @return directory path
+ */
+ private String getDirPath(JavaFileInfo parentInfo) {
+ return (parentInfo.getPackageFilePath() + SLASH + parentInfo.getJavaName()).toLowerCase();
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaTypeFragmentFiles.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaTypeFragmentFiles.java
new file mode 100644
index 0000000..930b6b4
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TempJavaTypeFragmentFiles.java
@@ -0,0 +1,353 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangTypeHolder;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaType;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_TYPEDEF_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_UNION_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_FOR_TYPE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.FROM_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.OF_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getAttributeInfoForTheData;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateTypeDefClassFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateUnionClassFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getOfMethodStringAndJavaDoc;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getTypeConstructorStringAndJavaDoc;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.closeFile;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.createPackage;
+
+/**
+ * Represents implementation of java data type code fragments temporary implementations.
+ * Maintains the temp files required specific for user defined data type java snippet generation.
+ */
+public class TempJavaTypeFragmentFiles
+ extends TempJavaFragmentFiles {
+
+ /**
+ * File name for of string method.
+ */
+ private static final String OF_STRING_METHOD_FILE_NAME = "OfString";
+
+ /**
+ * File name for construction for special type like union, typedef.
+ */
+ private static final String CONSTRUCTOR_FOR_TYPE_FILE_NAME = "ConstructorForType";
+
+ /**
+ * File name for typedef class file name suffix.
+ */
+ private static final String TYPEDEF_CLASS_FILE_NAME_SUFFIX = EMPTY_STRING;
+
+ /**
+ * File name for generated class file for special type like union, typedef
+ * suffix.
+ */
+ private static final String UNION_TYPE_CLASS_FILE_NAME_SUFFIX = EMPTY_STRING;
+
+ /**
+ * Temporary file handle for of string method of class.
+ */
+ private File ofStringImplTempFileHandle;
+
+ /**
+ * Temporary file handle for constructor for type class.
+ */
+ private File constructorForTypeTempFileHandle;
+
+ /**
+ * Java file handle for typedef class file.
+ */
+ private File typedefClassJavaFileHandle;
+
+ /**
+ * Java file handle for type class like union, typedef file.
+ */
+ private File typeClassJavaFileHandle;
+
+ /**
+ * Creates an instance of temporary java code fragment.
+ *
+ * @param javaFileInfo generated java file info
+ * @throws IOException when fails to create new file handle
+ */
+ public TempJavaTypeFragmentFiles(JavaFileInfo javaFileInfo)
+ throws IOException {
+
+ super(javaFileInfo);
+
+ /*
+ * Initialize getterImpl, attributes, hash code, equals and to strings
+ * when generation file type matches to typeDef class mask.
+ */
+ addGeneratedTempFile(OF_STRING_IMPL_MASK);
+ addGeneratedTempFile(CONSTRUCTOR_FOR_TYPE_MASK);
+ addGeneratedTempFile(FROM_STRING_IMPL_MASK);
+
+ setOfStringImplTempFileHandle(getTemporaryFileHandle(OF_STRING_METHOD_FILE_NAME));
+ setConstructorForTypeTempFileHandle(getTemporaryFileHandle(CONSTRUCTOR_FOR_TYPE_FILE_NAME));
+
+ }
+
+ /**
+ * Returns type class constructor method's temporary file handle.
+ *
+ * @return type class constructor method's temporary file handle
+ */
+
+ public File getConstructorForTypeTempFileHandle() {
+ return constructorForTypeTempFileHandle;
+ }
+
+ /**
+ * Sets type class constructor method's temporary file handle.
+ *
+ * @param constructorForTypeTempFileHandle type class constructor method's
+ * temporary file handle
+ */
+ private void setConstructorForTypeTempFileHandle(File constructorForTypeTempFileHandle) {
+ this.constructorForTypeTempFileHandle = constructorForTypeTempFileHandle;
+ }
+
+ /**
+ * Returns java file handle for typedef class file.
+ *
+ * @return java file handle for typedef class file
+ */
+ File getTypedefClassJavaFileHandle() {
+ return typedefClassJavaFileHandle;
+ }
+
+ /**
+ * Sets the java file handle for typedef class file.
+ *
+ * @param typedefClassJavaFileHandle java file handle
+ */
+ private void setTypedefClassJavaFileHandle(File typedefClassJavaFileHandle) {
+ this.typedefClassJavaFileHandle = typedefClassJavaFileHandle;
+ }
+
+ /**
+ * Returns java file handle for type class file.
+ *
+ * @return java file handle for type class file
+ */
+ File getTypeClassJavaFileHandle() {
+ return typeClassJavaFileHandle;
+ }
+
+ /**
+ * Sets the java file handle for type class file.
+ *
+ * @param typeClassJavaFileHandle type file handle
+ */
+ private void setTypeClassJavaFileHandle(File typeClassJavaFileHandle) {
+ this.typeClassJavaFileHandle = typeClassJavaFileHandle;
+ }
+
+ /**
+ * Returns of string method's temporary file handle.
+ *
+ * @return of string method's temporary file handle
+ */
+
+ public File getOfStringImplTempFileHandle() {
+ return ofStringImplTempFileHandle;
+ }
+
+ /**
+ * Set of string method's temporary file handle.
+ *
+ * @param ofStringImplTempFileHandle of string method's temporary file
+ * handle
+ */
+ private void setOfStringImplTempFileHandle(File ofStringImplTempFileHandle) {
+ this.ofStringImplTempFileHandle = ofStringImplTempFileHandle;
+ }
+
+ /**
+ * Adds all the type in the current data model node as part of the generated
+ * temporary file.
+ *
+ * @param yangTypeHolder YANG java data model node which has type info, eg union /
+ * typedef
+ * @param pluginConfig plugin configurations for naming conventions
+ * @throws IOException IO operation fail
+ */
+ public void addTypeInfoToTempFiles(YangTypeHolder yangTypeHolder, YangPluginConfig pluginConfig)
+ throws IOException {
+
+ List<YangType<?>> typeList = yangTypeHolder.getTypeList();
+ if (typeList != null) {
+ for (YangType<?> yangType : typeList) {
+ if (!(yangType instanceof YangJavaType)) {
+ throw new TranslatorException("Type does not have Java info");
+ }
+ YangJavaType<?> javaType = (YangJavaType<?>) yangType;
+ javaType.updateJavaQualifiedInfo(pluginConfig.getConflictResolver());
+ String typeName = javaType.getDataTypeName();
+ typeName = getCamelCase(typeName, pluginConfig.getConflictResolver());
+ JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(
+ javaType.getJavaQualifiedInfo(),
+ typeName, javaType,
+ getIsQualifiedAccessOrAddToImportList(javaType.getJavaQualifiedInfo()),
+ false);
+ addJavaSnippetInfoToApplicableTempFiles((YangNode) yangTypeHolder, javaAttributeInfo,
+ pluginConfig);
+ }
+ }
+ }
+
+ /**
+ * Adds the new attribute info to the target generated temporary files for
+ * union class.
+ *
+ * @param hasType the node for which the type is being added as an attribute
+ * @param javaAttributeInfo the attribute info that needs to be added to
+ * temporary files
+ * @param pluginConfig plugin configurations
+ * @throws IOException IO operation fail
+ */
+ private void addJavaSnippetInfoToApplicableTempFiles(YangNode hasType, JavaAttributeInfo javaAttributeInfo,
+ YangPluginConfig pluginConfig)
+ throws IOException {
+
+ super.addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, pluginConfig);
+
+ if ((getGeneratedTempFiles() & OF_STRING_IMPL_MASK) != 0) {
+ addOfStringMethod(javaAttributeInfo, pluginConfig);
+ }
+ if ((getGeneratedTempFiles() & CONSTRUCTOR_FOR_TYPE_MASK) != 0) {
+ addTypeConstructor(javaAttributeInfo, pluginConfig);
+ }
+ }
+
+ /**
+ * Adds type constructor.
+ *
+ * @param attr attribute info
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addTypeConstructor(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
+ throws IOException {
+ appendToFile(getConstructorForTypeTempFileHandle(), getTypeConstructorStringAndJavaDoc(attr,
+ getGeneratedJavaClassName(), pluginConfig) + NEW_LINE);
+ }
+
+ /**
+ * Adds of string for type.
+ *
+ * @param attr attribute info
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to append to temporary file
+ */
+ private void addOfStringMethod(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
+ throws IOException {
+ appendToFile(getOfStringImplTempFileHandle(), getOfMethodStringAndJavaDoc(attr,
+ getGeneratedJavaClassName(), pluginConfig)
+ + NEW_LINE);
+ }
+
+ /**
+ * Removes all temporary file handles.
+ *
+ * @param isErrorOccurred when translator fails to generate java files we
+ * need to close all open file handles include temporary files
+ * and java files.
+ * @throws IOException when failed to delete the temporary files
+ */
+ @Override
+ public void freeTemporaryResources(boolean isErrorOccurred)
+ throws IOException {
+ boolean isError = isErrorOccurred;
+
+ if ((getGeneratedJavaFiles() & GENERATE_TYPEDEF_CLASS) != 0) {
+ closeFile(getTypedefClassJavaFileHandle(), isError);
+ }
+
+ if ((getGeneratedJavaFiles() & GENERATE_UNION_CLASS) != 0) {
+ closeFile(getTypeClassJavaFileHandle(), isError);
+ }
+
+ if ((getGeneratedTempFiles() & CONSTRUCTOR_FOR_TYPE_MASK) != 0) {
+ closeFile(getConstructorForTypeTempFileHandle(), true);
+ }
+ if ((getGeneratedTempFiles() & OF_STRING_IMPL_MASK) != 0) {
+ closeFile(getOfStringImplTempFileHandle(), true);
+ }
+ if ((getGeneratedTempFiles() & FROM_STRING_IMPL_MASK) != 0) {
+ closeFile(getFromStringImplTempFileHandle(), true);
+ }
+
+ super.freeTemporaryResources(isErrorOccurred);
+
+ }
+
+ /**
+ * Constructs java code exit.
+ *
+ * @param fileType generated file type
+ * @param curNode current YANG node
+ * @throws IOException when fails to generate java files
+ */
+ @Override
+ public void generateJavaFile(int fileType, YangNode curNode)
+ throws IOException {
+ List<String> imports = new ArrayList<>();
+ if (isAttributePresent()) {
+ imports = getJavaImportData().getImports();
+ }
+
+ createPackage(curNode);
+
+ /*
+ * Creates type def class file.
+ */
+ if ((fileType & GENERATE_TYPEDEF_CLASS) != 0) {
+ addImportsToStringAndHasCodeMethods(curNode, imports);
+ setTypedefClassJavaFileHandle(getJavaFileHandle(getJavaClassName(TYPEDEF_CLASS_FILE_NAME_SUFFIX)));
+ generateTypeDefClassFile(getTypedefClassJavaFileHandle(), curNode, imports);
+ }
+ /*
+ * Creates type class file.
+ */
+ if ((fileType & GENERATE_UNION_CLASS) != 0) {
+ addImportsToStringAndHasCodeMethods(curNode, imports);
+ setTypeClassJavaFileHandle(getJavaFileHandle(getJavaClassName(UNION_TYPE_CLASS_FILE_NAME_SUFFIX)));
+ generateUnionClassFile(getTypeClassJavaFileHandle(), curNode, imports);
+ }
+
+ /*
+ * Close all the file handles.
+ */
+ freeTemporaryResources(false);
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TraversalType.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TraversalType.java
new file mode 100644
index 0000000..dd7db35
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/TraversalType.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava;
+
+/**
+ * Represents data model tree traversal types.
+ */
+public enum TraversalType {
+
+ /**
+ * Start of traversal at the tree root.
+ */
+ ROOT,
+
+ /**
+ * Child node traversal.
+ */
+ CHILD,
+
+ /**
+ * Sibling node traversal.
+ */
+ SIBILING,
+
+ /**
+ * Parent node traversal.
+ */
+ PARENT
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/YangDataModelFactory.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/YangDataModelFactory.java
new file mode 100644
index 0000000..4d68fe2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/YangDataModelFactory.java
@@ -0,0 +1,409 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava;
+
+import org.onosproject.yangutils.datamodel.YangAugment;
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangChoice;
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangRpc;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.YangUnion;
+import org.onosproject.yangutils.datamodel.YangUses;
+import org.onosproject.yangutils.datamodel.utils.GeneratedLanguage;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaAugment;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaCase;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaChoice;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaContainer;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaEnumeration;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaGrouping;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaInput;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaLeaf;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaLeafList;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaList;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaNotification;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaOutput;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaRpc;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaType;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaTypeDef;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaUnion;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaUses;
+
+/**
+ * Represents factory to create data model objects based on the target file type.
+ */
+public final class YangDataModelFactory {
+
+ /**
+ * Creates a YANG data model factory object.
+ */
+ private YangDataModelFactory() {
+ }
+
+ /**
+ * Based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangModule getYangModuleNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaModule();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangAugment getYangAugmentNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaAugment();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangCase getYangCaseNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaCase();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangChoice getYangChoiceNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaChoice();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangContainer getYangContainerNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaContainer();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangGrouping getYangGroupingNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaGrouping();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangList getYangListNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaList();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangSubModule getYangSubModuleNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaSubModule();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangTypeDef getYangTypeDefNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaTypeDef();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangUnion getYangUnionNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaUnion();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangUses getYangUsesNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaUses();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangNotification getYangNotificationNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaNotification();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangLeaf getYangLeaf(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaLeaf();
+ }
+ default: {
+ throw new RuntimeException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangLeafList getYangLeafList(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaLeafList();
+ }
+ default: {
+ throw new RuntimeException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangRpc getYangRpcNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaRpc();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangInput getYangInputNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaInput();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangOutput getYangOutputNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaOutput();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangJavaEnumeration getYangEnumerationNode(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaEnumeration();
+ }
+ default: {
+ throw new TranslatorException("Only YANG to Java is supported.");
+ }
+ }
+ }
+ /**
+ * Returns based on the target language generate the inherited data model node.
+ *
+ * @param targetLanguage target language in which YANG mapping needs to be
+ * generated
+ * @return the corresponding inherited node based on the target language
+ */
+ public static YangType getYangType(GeneratedLanguage targetLanguage) {
+ switch (targetLanguage) {
+ case JAVA_GENERATION: {
+ return new YangJavaType();
+ }
+ default: {
+ throw new RuntimeException("Only YANG to Java is supported.");
+ }
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaCodeGeneratorInfo.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaCodeGeneratorInfo.java
new file mode 100644
index 0000000..8dc0db5
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaCodeGeneratorInfo.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
+
+/**
+ * Represents YANG java info containing interface for java code generator, java
+ * file information, java import data and temp java code fragment files. This
+ * interface serves as a generic interface and help to unify the generate code
+ * entry function.
+ */
+public interface JavaCodeGeneratorInfo
+ extends JavaFileInfoContainer, TempJavaCodeFragmentFilesContainer {
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaLeafInfoContainer.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaLeafInfoContainer.java
new file mode 100644
index 0000000..3722ad3
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaLeafInfoContainer.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfoContainer;
+import org.onosproject.yangutils.translator.tojava.utils.YangToJavaNamingConflictUtil;
+
+/**
+ * Represent java based identification of the YANG leaves.
+ */
+public interface JavaLeafInfoContainer
+ extends JavaQualifiedTypeInfoContainer {
+ /**
+ * Retreives the data type of the leaf.
+ *
+ * @return data type of the leaf
+ */
+ YangType<?> getDataType();
+
+ /**
+ * Retreives the name of the leaf.
+ *
+ * @return name of the leaf
+ */
+ String getName();
+
+ /**
+ * Retreives the java name of the leaf.
+ *
+ * @param conflictResolveConfig user config to resolve conflicts
+ * @return name of the leaf
+ */
+ String getJavaName(YangToJavaNamingConflictUtil conflictResolveConfig);
+
+ /**
+ * Identifies if object is a leaf-list.
+ *
+ * @return true if leaf-list false otherwise
+ */
+ boolean isLeafList();
+
+ /**
+ * updates the qualified info.
+ */
+ void updateJavaQualifiedInfo();
+
+ /**
+ * Returns java naming conflict resolver.
+ *
+ * @return java naming conflict resolver
+ */
+ YangToJavaNamingConflictUtil getConflictResolveConfig();
+
+ /**
+ * Sets java naming conflict resolver.
+ *
+ * @param conflictResolveConfig java naming conflict resolver
+ */
+ void setConflictResolveConfig(YangToJavaNamingConflictUtil conflictResolveConfig);
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaQualifiedTypeResolver.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaQualifiedTypeResolver.java
new file mode 100644
index 0000000..5b1e7c5
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/JavaQualifiedTypeResolver.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfoContainer;
+import org.onosproject.yangutils.translator.tojava.utils.YangToJavaNamingConflictUtil;
+
+/**
+ * Represent java based identification of the YANG leaves.
+ */
+public interface JavaQualifiedTypeResolver
+ extends JavaQualifiedTypeInfoContainer {
+
+ /**
+ * updates the qualified access details of the type.
+ *
+ * @param confilictResolver plugin configurations
+ */
+ void updateJavaQualifiedInfo(YangToJavaNamingConflictUtil confilictResolver);
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaAugment.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaAugment.java
new file mode 100644
index 0000000..6ac0fb7
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaAugment.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangAugment;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfAugmentableNode;
+
+/**
+ * Represents augment information extended to support java code generation.
+ */
+public class YangJavaAugment
+ extends YangAugment
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201632L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates a YANG java augment object.
+ */
+ public YangJavaAugment() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * augment info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeOfAugmentableNode(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for augmentable node " + getName());
+ }
+ }
+
+ /**
+ * Create a java file using the YANG augment info.
+ *
+ * @throws TranslatorException when failed to do translator operations
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for augmentable node " + getName());
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaCase.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaCase.java
new file mode 100644
index 0000000..ba7bd01
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaCase.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfAugmentableNode;
+
+/**
+ * Represents case information extended to support java code generation.
+ */
+public class YangJavaCase
+ extends YangCase
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201631L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates YANG java case object.
+ */
+ public YangJavaCase() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * case info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeOfAugmentableNode(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for case node " + getName());
+ }
+ }
+
+ /**
+ * Creates a java file using the YANG case info.
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for case node " + getName());
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaChoice.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaChoice.java
new file mode 100644
index 0000000..4096972
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaChoice.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangChoice;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeAndUpdateInParent;
+
+/**
+ * Represents choice information extended to support java code generation.
+ */
+public class YangJavaChoice
+ extends YangChoice
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201631L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates YANG java choice object.
+ */
+ public YangJavaChoice() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(INTERFACE_MASK);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * choice info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeAndUpdateInParent(this, yangPlugin, false);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for choice node " + getName());
+ }
+ }
+
+ /**
+ * Creates a java file using the YANG choice info.
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(INTERFACE_MASK, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for choice node " + getName());
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaContainer.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaContainer.java
new file mode 100644
index 0000000..c056632
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaContainer.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangContainer;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeAndUpdateInParent;
+
+/**
+ * Represents container information extended to support java code generation.
+ */
+public class YangJavaContainer
+ extends YangContainer
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201630L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates YANG java container object.
+ */
+ public YangJavaContainer() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * container info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeAndUpdateInParent(this, yangPlugin, false);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for container node " + getName());
+ }
+ }
+
+ /**
+ * Create a java file using the YANG container info.
+ *
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for container node " + getName());
+ }
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaEnumeration.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaEnumeration.java
new file mode 100644
index 0000000..16cabc2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaEnumeration.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangEnumeration;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_ENUM_CLASS;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfNode;
+
+/**
+ * Represents YANG java enumeration information extended to support java code generation.
+ */
+public class YangJavaEnumeration
+ extends YangEnumeration
+ implements JavaCodeGenerator, JavaCodeGeneratorInfo {
+
+ private static final long serialVersionUID = 806201629L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates YANG java enumeration object.
+ */
+ public YangJavaEnumeration() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_ENUM_CLASS);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * enumeration info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operations fails
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeOfNode(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for enumeration node " + getName());
+ }
+ }
+
+ /**
+ * Creates a java file using the YANG enumeration info.
+ *
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_ENUM_CLASS, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for enumeration node " + getName());
+ }
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaGrouping.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaGrouping.java
new file mode 100644
index 0000000..8a90a44
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaGrouping.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.updatePackageInfo;
+
+/**
+ * Represents grouping information extended to support java code generation.
+ */
+public class YangJavaGrouping
+ extends YangGrouping
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201628L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates YANG Java grouping object.
+ */
+ public YangJavaGrouping() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin)
+ throws TranslatorException {
+ try {
+ updatePackageInfo(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException(e.getCause());
+ }
+ }
+
+ @Override
+ public void generateCodeExit()
+ throws TranslatorException {
+ /*
+ * Do nothing.
+ */
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaInput.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaInput.java
new file mode 100644
index 0000000..db59174
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaInput.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfAugmentableNode;
+
+/**
+ * Represents input information extended to support java code generation.
+ */
+public class YangJavaInput
+ extends YangInput
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201627L;
+
+ /**
+ * Contains information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates an instance of java input.
+ */
+ public YangJavaInput() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * input info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeOfAugmentableNode(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for input node " + getName());
+ }
+ }
+
+ /**
+ * Creates a java file using the YANG input info.
+ *
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for input node " + getName());
+ }
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaLeaf.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaLeaf.java
new file mode 100644
index 0000000..9f39dce
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaLeaf.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+import org.onosproject.yangutils.translator.tojava.utils.YangToJavaNamingConflictUtil;
+
+import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.updateLeavesJavaQualifiedInfo;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+
+/**
+ * Represents java information corresponding to the YANG leaf.
+ */
+public class YangJavaLeaf
+ extends YangLeaf
+ implements JavaLeafInfoContainer {
+
+ private static final long serialVersionUID = 806201636L;
+
+ private JavaQualifiedTypeInfo javaQualifiedAccess;
+ private transient YangToJavaNamingConflictUtil conflictResolveConfig;
+
+ /**
+ * Returns a new YANG leaf object with java qualified access details.
+ */
+ public YangJavaLeaf() {
+ super();
+ setJavaQualifiedInfo(new JavaQualifiedTypeInfo());
+ }
+
+ @Override
+ public JavaQualifiedTypeInfo getJavaQualifiedInfo() {
+ return javaQualifiedAccess;
+ }
+
+ @Override
+ public void setJavaQualifiedInfo(JavaQualifiedTypeInfo typeInfo) {
+ javaQualifiedAccess = typeInfo;
+
+ }
+
+ @Override
+ public String getJavaName(YangToJavaNamingConflictUtil conflictResolveConfig) {
+ return getCamelCase(getName(), conflictResolveConfig);
+ }
+
+ @Override
+ public boolean isLeafList() {
+ return false;
+ }
+
+ @Override
+ public void updateJavaQualifiedInfo() {
+ updateLeavesJavaQualifiedInfo(this);
+ }
+
+ /**
+ * Returns java naming conflict resolve configurations.
+ *
+ * @return java naming conflict resolve configurations
+ */
+ @Override
+ public YangToJavaNamingConflictUtil getConflictResolveConfig() {
+ return conflictResolveConfig;
+ }
+
+ /**
+ * Sets java naming conflict resolve configurations.
+ *
+ * @param conflictResolveConfig java naming conflict resolve configurations
+ */
+ @Override
+ public void setConflictResolveConfig(YangToJavaNamingConflictUtil conflictResolveConfig) {
+ this.conflictResolveConfig = conflictResolveConfig;
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaLeafList.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaLeafList.java
new file mode 100644
index 0000000..91c550f
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaLeafList.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+import org.onosproject.yangutils.translator.tojava.utils.YangToJavaNamingConflictUtil;
+
+import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.updateLeavesJavaQualifiedInfo;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+
+/**
+ * Represents java information corresponding to the YANG leaf-list.
+ */
+public class YangJavaLeafList
+ extends YangLeafList
+ implements JavaLeafInfoContainer {
+
+ private static final long serialVersionUID = 806201638L;
+
+ private JavaQualifiedTypeInfo javaQualifiedAccess;
+ private transient YangToJavaNamingConflictUtil conflictResolveConfig;
+
+ /**
+ * Returns a new YANG leaf object with java qualified access details.
+ */
+ public YangJavaLeafList() {
+ super();
+ setJavaQualifiedInfo(new JavaQualifiedTypeInfo());
+ }
+
+ @Override
+ public String getJavaName(YangToJavaNamingConflictUtil conflictResolveConfig) {
+ return getCamelCase(getName(), conflictResolveConfig);
+ }
+
+ @Override
+ public boolean isLeafList() {
+ return true;
+ }
+
+ @Override
+ public void updateJavaQualifiedInfo() {
+ updateLeavesJavaQualifiedInfo(this);
+ }
+
+ @Override
+ public JavaQualifiedTypeInfo getJavaQualifiedInfo() {
+ return javaQualifiedAccess;
+ }
+
+ @Override
+ public void setJavaQualifiedInfo(JavaQualifiedTypeInfo typeInfo) {
+ javaQualifiedAccess = typeInfo;
+ }
+
+ /**
+ * Returns java naming conflict resolve configurations.
+ *
+ * @return java naming conflict resolve configurations
+ */
+ @Override
+ public YangToJavaNamingConflictUtil getConflictResolveConfig() {
+ return conflictResolveConfig;
+ }
+
+ /**
+ * Sets java naming conflict resolve configurations.
+ *
+ * @param conflictResolveConfig java naming conflict resolve configurations
+ */
+ @Override
+ public void setConflictResolveConfig(YangToJavaNamingConflictUtil conflictResolveConfig) {
+ this.conflictResolveConfig = conflictResolveConfig;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaList.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaList.java
new file mode 100644
index 0000000..6f08b5d
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaList.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangList;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeAndUpdateInParent;
+
+/**
+ * Represents YANG list information extended to support java code generation.
+ */
+public class YangJavaList
+ extends YangList
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201626L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates YANG java list object.
+ */
+ public YangJavaList() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * list info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeAndUpdateInParent(this, yangPlugin, true);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for list node " + getName());
+ }
+ }
+
+ /**
+ * Creates a java file using the YANG list info.
+ *
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for list node " + getName());
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaModule.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaModule.java
new file mode 100644
index 0000000..1413f9c
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaModule.java
@@ -0,0 +1,212 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getRootPackage;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfRootNode;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.searchAndDeleteTempDir;
+
+/**
+ * Represents module information extended to support java code generation.
+ */
+public class YangJavaModule
+ extends YangModule
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201625L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * List of notifications nodes.
+ */
+ private List<YangNode> notificationNodes;
+
+ /**
+ * Creates a YANG node of module type.
+ */
+ public YangJavaModule() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ setNotificationNodes(new ArrayList<>());
+ int gentype = GENERATE_SERVICE_AND_MANAGER;
+ if (isNotificationChildNodePresent(this)) {
+ gentype = GENERATE_SERVICE_AND_MANAGER | GENERATE_EVENT_SUBJECT_CLASS | GENERATE_EVENT_CLASS
+ | GENERATE_EVENT_LISTENER_INTERFACE;
+ }
+ getJavaFileInfo().setGeneratedFileTypes(gentype);
+
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Generates java code for module.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException when fails to generate the source files
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ String modulePkg = getRootPackage(getVersion(), getNameSpace().getUri(), getRevision().getRevDate(),
+ yangPlugin.getConflictResolver());
+ try {
+ generateCodeOfRootNode(this, yangPlugin, modulePkg);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for module node " + getName());
+ }
+ }
+
+ /**
+ * Creates a java file using the YANG module info.
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ /**
+ * As part of the notification support the following files needs to be generated.
+ * 1) Subject of the notification(event), this is simple interface with builder class.
+ * 2) Event class extending "AbstractEvent" and defining event type enum.
+ * 3) Event listener interface extending "EventListener".
+ * 4) Event subject class.
+ *
+ * The manager class needs to extend the "ListenerRegistry".
+ */
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_SERVICE_AND_MANAGER, this);
+ searchAndDeleteTempDir(getJavaFileInfo().getBaseCodeGenPath() +
+ getJavaFileInfo().getPackageFilePath());
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for module node " + getName());
+ }
+ }
+
+ /**
+ * Returns notifications node list.
+ *
+ * @return notification nodes
+ */
+ public List<YangNode> getNotificationNodes() {
+ return notificationNodes;
+ }
+
+ /**
+ * Sets notifications list.
+ *
+ * @param notificationNodes notification list
+ */
+ private void setNotificationNodes(List<YangNode> notificationNodes) {
+ this.notificationNodes = notificationNodes;
+ }
+
+ /**
+ * Adds to notification node list.
+ *
+ * @param curNode notification node
+ */
+ private void addToNotificaitonList(YangNode curNode) {
+ getNotificationNodes().add(curNode);
+ }
+
+ /**
+ * Checks if there is any rpc defined in the module or sub-module.
+ *
+ * @param rootNode root node of the data model
+ * @return status of rpc's existence
+ */
+ public boolean isNotificationChildNodePresent(YangNode rootNode) {
+ YangNode childNode = rootNode.getChild();
+
+ while (childNode != null) {
+ if (childNode instanceof YangNotification) {
+ addToNotificaitonList(childNode);
+ }
+ childNode = childNode.getNextSibling();
+ }
+
+ if (!getNotificationNodes().isEmpty()) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaNotification.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaNotification.java
new file mode 100644
index 0000000..68f8164
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaNotification.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
+import org.onosproject.yangutils.translator.tojava.utils.JavaExtendsListHolder;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfAugmentableNode;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_LISTENER_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_STRING;
+
+/**
+ * Represents notification information extended to support java code generation.
+ */
+public class YangJavaNotification
+ extends YangNotification
+ implements JavaCodeGenerator, JavaCodeGeneratorInfo {
+
+ private static final long serialVersionUID = 806201624L;
+
+ /**
+ * Contains information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates an instance of java Notification.
+ */
+ public YangJavaNotification() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * notification info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+
+ /**
+ * As part of the notification support the following files needs to be generated.
+ * 1) Subject of the notification(event), this is simple interface with builder class.
+ * 2) Event class extending "AbstractEvent" and defining event type enum.
+ * 3) Event listener interface extending "EventListener".
+ *
+ * The manager class needs to extend the ListenerRegistry.
+ */
+
+ // Generate subject of the notification(event), this is simple interface
+ // with builder class.
+ try {
+ generateCodeOfAugmentableNode(this, yangPlugin);
+ addNotificationToExtendsList();
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for notification node " + getName());
+ }
+ }
+
+ /*Adds current notification info to the extends list so its parents service*/
+ private void addNotificationToExtendsList() {
+ YangNode parent = getParent();
+ JavaExtendsListHolder holder = ((TempJavaCodeFragmentFilesContainer) parent)
+ .getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles().getJavaExtendsListHolder();
+ JavaQualifiedTypeInfo event = new JavaQualifiedTypeInfo();
+
+ String parentInfo = getCapitalCase(((JavaFileInfoContainer) parent)
+ .getJavaFileInfo().getJavaName());
+ event.setClassInfo(parentInfo + EVENT_STRING);
+ event.setPkgInfo(getJavaFileInfo().getPackage());
+ holder.addToExtendsList(event, parent);
+
+ JavaQualifiedTypeInfo eventListener = new JavaQualifiedTypeInfo();
+
+ eventListener.setClassInfo(parentInfo + EVENT_LISTENER_STRING);
+ eventListener.setPkgInfo(getJavaFileInfo().getPackage());
+ holder.addToExtendsList(eventListener, parent);
+
+ }
+
+ /**
+ * Creates a java file using the YANG notification info.
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for notification node " + getName());
+ }
+
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaOutput.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaOutput.java
new file mode 100644
index 0000000..dda3fc9
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaOutput.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfAugmentableNode;
+
+/**
+ * Represents output information extended to support java code generation.
+ */
+public class YangJavaOutput
+ extends YangOutput
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201623L;
+
+ /**
+ * Contains information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates an instance of java output.
+ */
+ public YangJavaOutput() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * output info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeOfAugmentableNode(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for output node " + getName());
+ }
+
+ }
+
+ /**
+ * Creates a java file using the YANG output info.
+ *
+ * @throws TranslatorException translator operation fail
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code exit for output node " + getName());
+ }
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaRpc.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaRpc.java
new file mode 100644
index 0000000..f3730a2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaRpc.java
@@ -0,0 +1,254 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.RpcNotificationContainer;
+import org.onosproject.yangutils.datamodel.YangInput;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangOutput;
+import org.onosproject.yangutils.datamodel.YangRpc;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaAttributeInfo;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
+import org.onosproject.yangutils.translator.tojava.TempJavaFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.getParentNodeInGenCode;
+import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getAttributeInfoForTheData;
+import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getQualifiedTypeInfoOfCurNode;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.updatePackageInfo;
+import static org.onosproject.yangutils.utils.UtilConstants.ACTIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.COMPONENT;
+import static org.onosproject.yangutils.utils.UtilConstants.DEACTIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.MANAGER;
+import static org.onosproject.yangutils.utils.UtilConstants.REFERENCE;
+import static org.onosproject.yangutils.utils.UtilConstants.REFERENCE_CARDINALITY;
+import static org.onosproject.yangutils.utils.UtilConstants.SERVICE;
+
+/**
+ * Represents rpc information extended to support java code generation.
+ */
+public class YangJavaRpc
+ extends YangRpc
+ implements JavaCodeGenerator, JavaCodeGeneratorInfo {
+
+ private static final long serialVersionUID = 806201622L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * Temproary file for code generation.
+ */
+ private transient TempJavaCodeFragmentFiles tempJavaCodeFragmentFiles;
+
+ /**
+ * Creates an instance of YANG java rpc.
+ */
+ public YangJavaRpc() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+
+ if (javaFileInfo == null) {
+ throw new TranslatorException("missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempJavaCodeFragmentFiles;
+ }
+
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempJavaCodeFragmentFiles = fileHandle;
+ }
+
+ /**
+ * Prepares the information for java code generation corresponding to YANG
+ * RPC info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException translator operations fails
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin)
+ throws TranslatorException {
+
+ // Add package information for rpc and create corresponding folder.
+ try {
+ updatePackageInfo(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to prepare generate code entry for RPC node " + getName());
+ }
+ }
+
+ /**
+ * Creates a java file using the YANG RPC info.
+ *
+ * @throws TranslatorException translator operations fails
+ */
+ @Override
+ public void generateCodeExit()
+ throws TranslatorException {
+ // Get the parent module/sub-module.
+ YangNode parent = getParentNodeInGenCode(this);
+
+ // Parent should be holder of rpc or notification.
+ if (!(parent instanceof RpcNotificationContainer)) {
+ throw new TranslatorException("parent node of rpc can only be module or sub-module");
+ }
+
+ /*
+ * Create attribute info for input and output of rpc and add it to the
+ * parent import list.
+ */
+
+ JavaAttributeInfo javaAttributeInfoOfInput = null;
+ JavaAttributeInfo javaAttributeInfoOfOutput = null;
+
+ // Get the child input and output node and obtain create java attribute
+ // info.
+ YangNode yangNode = getChild();
+ while (yangNode != null) {
+ if (yangNode instanceof YangInput) {
+ javaAttributeInfoOfInput = getChildNodeAsAttributeInParentService(yangNode, this);
+
+ } else if (yangNode instanceof YangOutput) {
+ javaAttributeInfoOfOutput = getChildNodeAsAttributeInParentService(yangNode, this);
+ } else {
+ throw new TranslatorException("RPC should contain only input/output child nodes.");
+ }
+ yangNode = yangNode.getNextSibling();
+ }
+
+ if (!(parent instanceof TempJavaCodeFragmentFilesContainer)) {
+ throw new TranslatorException("missing parent temp file handle");
+ }
+
+ /*
+ * Add the rpc information to the parent's service temp file.
+ */
+ try {
+
+ ((TempJavaCodeFragmentFilesContainer) parent).getTempJavaCodeFragmentFiles().getServiceTempFiles()
+ .addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfoOfInput, javaAttributeInfoOfOutput,
+ ((JavaFileInfoContainer) parent).getJavaFileInfo().getPluginConfig(), getName());
+
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for RPC node " + getName());
+ }
+ // No file will be generated during RPC exit.
+ }
+
+ /**
+ * Creates an attribute info object corresponding to a data model node and
+ * return it.
+ *
+ * @param childNode child data model node(input / output) for which the java code generation
+ * is being handled
+ * @param currentNode parent node (module / sub-module) in which the child node is an attribute
+ * @return AttributeInfo attribute details required to add in temporary
+ * files
+ */
+ public JavaAttributeInfo getChildNodeAsAttributeInParentService(
+ YangNode childNode, YangNode currentNode) {
+
+ YangNode parentNode = getParentNodeInGenCode(currentNode);
+
+ String childNodeName = ((JavaFileInfoContainer) childNode).getJavaFileInfo().getJavaName();
+ /*
+ * Get the import info corresponding to the attribute for import in
+ * generated java files or qualified access
+ */
+ JavaQualifiedTypeInfo qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(childNode,
+ getCapitalCase(childNodeName));
+ if (!(parentNode instanceof TempJavaCodeFragmentFilesContainer)) {
+ throw new TranslatorException("Parent node does not have file info");
+ }
+
+ TempJavaFragmentFiles tempJavaFragmentFiles;
+ tempJavaFragmentFiles = ((TempJavaCodeFragmentFilesContainer) parentNode)
+ .getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles();
+
+ if (tempJavaFragmentFiles == null) {
+ throw new TranslatorException("Parent node does not have service file info");
+ }
+ boolean isQualified = addImportToService(qualifiedTypeInfo);
+ return getAttributeInfoForTheData(qualifiedTypeInfo, childNodeName, null, isQualified, false);
+ }
+
+ /**
+ * Adds to service class import list.
+ *
+ * @param importInfo import info
+ * @return true or false
+ */
+ private boolean addImportToService(JavaQualifiedTypeInfo importInfo) {
+ JavaFileInfo fileInfo = ((JavaFileInfoContainer) getParent()).getJavaFileInfo();
+
+ if (importInfo.getClassInfo().contentEquals(SERVICE)
+ || importInfo.getClassInfo().contentEquals(COMPONENT)
+ || importInfo.getClassInfo().contentEquals(getCapitalCase(ACTIVATE))
+ || importInfo.getClassInfo().contentEquals(getCapitalCase(DEACTIVATE))
+ || importInfo.getClassInfo().contentEquals(REFERENCE_CARDINALITY)
+ || importInfo.getClassInfo().contentEquals(REFERENCE)
+ || importInfo.getClassInfo().contentEquals(getCapitalCase(fileInfo.getJavaName() + SERVICE))
+ || importInfo.getClassInfo().contentEquals(getCapitalCase(fileInfo.getJavaName() + MANAGER))) {
+ return true;
+ }
+
+ String className;
+ className = getCapitalCase(fileInfo.getJavaName()) + "Service";
+
+ return ((TempJavaCodeFragmentFilesContainer) getParent()).getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles().getJavaImportData().addImportInfo(importInfo,
+ className, fileInfo.getPackage());
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaSubModule.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaSubModule.java
new file mode 100644
index 0000000..d838682
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaSubModule.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangBelongsTo;
+import org.onosproject.yangutils.datamodel.YangModule;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNotification;
+import org.onosproject.yangutils.datamodel.YangSubModule;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getRootPackage;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfRootNode;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.searchAndDeleteTempDir;
+
+/**
+ * Represents sub module information extended to support java code generation.
+ */
+public class YangJavaSubModule
+ extends YangSubModule
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201621L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * List of notifications nodes.
+ */
+ private List<YangNode> notificationNodes = new ArrayList<>();
+
+ /**
+ * Creates YANG java sub module object.
+ */
+ public YangJavaSubModule() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ int gentype = GENERATE_SERVICE_AND_MANAGER;
+ if (isNotificationChildNodePresent(this)) {
+ gentype = GENERATE_SERVICE_AND_MANAGER | GENERATE_EVENT_SUBJECT_CLASS | GENERATE_EVENT_CLASS
+ | GENERATE_EVENT_LISTENER_INTERFACE;
+ }
+ getJavaFileInfo().setGeneratedFileTypes(gentype);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Returns the name space of the module to which the sub module belongs to.
+ *
+ * @param belongsToInfo Information of the module to which the sub module
+ * belongs
+ * @return the name space string of the module.
+ */
+ public String getNameSpaceFromModule(YangBelongsTo belongsToInfo) {
+ return ((YangModule) belongsToInfo.getModuleNode()).getNameSpace().getUri();
+ }
+
+ /**
+ * Prepares the information for java code generation corresponding to YANG
+ * submodule info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException when fails to translate
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ String subModulePkg = getRootPackage(getVersion(), getNameSpaceFromModule(getBelongsTo()),
+ getRevision().getRevDate(), yangPlugin.getConflictResolver());
+ try {
+ generateCodeOfRootNode(this, yangPlugin, subModulePkg);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "failed to prepare generate code entry for submodule node " + getName());
+ }
+
+ }
+
+ /**
+ * Creates a java file using the YANG submodule info.
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ /**
+ * As part of the notification support the following files needs to be generated.
+ * 1) Subject of the notification(event), this is simple interface with builder class.
+ * 2) Event class extending "AbstractEvent" and defining event type enum.
+ * 3) Event listener interface extending "EventListener".
+ * 4) Event subject class.
+ *
+ * The manager class needs to extend the "ListenerRegistry".
+ */
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_SERVICE_AND_MANAGER, this);
+ searchAndDeleteTempDir(getJavaFileInfo().getBaseCodeGenPath() +
+ getJavaFileInfo().getPackageFilePath());
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for submodule node " + getName());
+ }
+ }
+
+ /**
+ * Returns notifications node list.
+ *
+ * @return notification nodes
+ */
+ public List<YangNode> getNotificationNodes() {
+ return notificationNodes;
+ }
+
+ /**
+ * Adds to notification node list.
+ *
+ * @param curNode notification node
+ */
+ private void addToNotificaitonList(YangNode curNode) {
+ getNotificationNodes().add(curNode);
+ }
+
+ /**
+ * Checks if there is any rpc defined in the module or sub-module.
+ *
+ * @param rootNode root node of the data model
+ * @return status of rpc's existence
+ */
+ public boolean isNotificationChildNodePresent(YangNode rootNode) {
+ YangNode childNode = rootNode.getChild();
+
+ while (childNode != null) {
+ if (childNode instanceof YangNotification) {
+ addToNotificaitonList(childNode);
+ }
+ childNode = childNode.getNextSibling();
+ }
+
+ if (!getNotificationNodes().isEmpty()) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaType.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaType.java
new file mode 100644
index 0000000..e537743
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaType.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+import org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType;
+import org.onosproject.yangutils.translator.tojava.utils.YangToJavaNamingConflictUtil;
+
+/**
+ * Represents java information corresponding to the YANG type.
+ *
+ * @param <T> generic parameter for YANG java type
+ */
+public class YangJavaType<T>
+ extends YangType<T>
+ implements JavaQualifiedTypeResolver {
+
+ private JavaQualifiedTypeInfo javaQualifiedAccess;
+
+ /**
+ * Create a YANG leaf object with java qualified access details.
+ */
+ public YangJavaType() {
+ super();
+ setJavaQualifiedInfo(new JavaQualifiedTypeInfo());
+ }
+
+ @Override
+ public void updateJavaQualifiedInfo(YangToJavaNamingConflictUtil conflictResolver) {
+ JavaQualifiedTypeInfo importInfo = getJavaQualifiedInfo();
+
+ /*
+ * Type is added as an attribute in the class.
+ */
+ String className = AttributesJavaDataType.getJavaImportClass(this, false, conflictResolver);
+ if (className != null) {
+ /*
+ * Corresponding to the attribute type a class needs to be imported,
+ * since it can be a derived type or a usage of wrapper classes.
+ */
+ importInfo.setClassInfo(className);
+ String classPkg = AttributesJavaDataType.getJavaImportPackage(this,
+ false, conflictResolver);
+ if (classPkg == null) {
+ throw new TranslatorException("import package cannot be null when the class is used");
+ }
+ importInfo.setPkgInfo(classPkg);
+ } else {
+ /*
+ * The attribute does not need a class to be imported, for example
+ * built in java types.
+ */
+ String dataTypeName = AttributesJavaDataType.getJavaDataType(this);
+ if (dataTypeName == null) {
+ throw new TranslatorException("not supported data type");
+ }
+ importInfo.setClassInfo(dataTypeName);
+ }
+ setJavaQualifiedInfo(importInfo);
+ }
+
+ @Override
+ public JavaQualifiedTypeInfo getJavaQualifiedInfo() {
+ return javaQualifiedAccess;
+ }
+
+ @Override
+ public void setJavaQualifiedInfo(JavaQualifiedTypeInfo typeInfo) {
+ javaQualifiedAccess = typeInfo;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaTypeDef.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaTypeDef.java
new file mode 100644
index 0000000..0124510
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaTypeDef.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_TYPEDEF_CLASS;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfNode;
+
+/**
+ * Represents type define information extended to support java code generation.
+ */
+public class YangJavaTypeDef
+ extends YangTypeDef
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201620L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates a YANG java typedef object.
+ */
+ public YangJavaTypeDef() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_TYPEDEF_CLASS);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * typedef info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException when fails to translate
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeOfNode(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for typedef node " + getName());
+ }
+
+ }
+
+ /**
+ * Create a java file using the YANG typedef info.
+ *
+ * @throws TranslatorException when fails to translate
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_TYPEDEF_CLASS, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for typedef node " + getName());
+ }
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaUnion.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaUnion.java
new file mode 100644
index 0000000..eac8e52
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaUnion.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.YangUnion;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_UNION_CLASS;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfNode;
+
+/**
+ * Represents union information extended to support java code generation.
+ */
+public class YangJavaUnion
+ extends YangUnion
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201619L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates an instance of YANG java union.
+ */
+ public YangJavaUnion() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ getJavaFileInfo().setGeneratedFileTypes(GENERATE_UNION_CLASS);
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new RuntimeException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ /**
+ * Prepare the information for java code generation corresponding to YANG
+ * union info.
+ *
+ * @param yangPlugin YANG plugin config
+ * @throws TranslatorException when fails to translate
+ */
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
+ try {
+ generateCodeOfNode(this, yangPlugin);
+ } catch (IOException e) {
+ throw new TranslatorException(
+ "Failed to prepare generate code entry for union node " + getName());
+ }
+
+ }
+
+ /**
+ * Creates a java file using the YANG union info.
+ *
+ * @throws TranslatorException when fails to translate
+ */
+ @Override
+ public void generateCodeExit() throws TranslatorException {
+ try {
+ getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_UNION_CLASS, this);
+ } catch (IOException e) {
+ throw new TranslatorException("Failed to generate code for union node " + getName());
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaUses.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaUses.java
new file mode 100644
index 0000000..f6166a5
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/YangJavaUses.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangGrouping;
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangUses;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.getParentNodeInGenCode;
+import static org.onosproject.yangutils.translator.tojava.TempJavaFragmentFiles.addCurNodeAsAttributeInTargetTempFile;
+import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.updatePackageInfo;
+
+/**
+ * Represents uses information extended to support java code generation.
+ */
+public class YangJavaUses
+ extends YangUses
+ implements JavaCodeGeneratorInfo, JavaCodeGenerator {
+
+ private static final long serialVersionUID = 806201618L;
+
+ /**
+ * Contains the information of the java file being generated.
+ */
+ private JavaFileInfo javaFileInfo;
+
+ /**
+ * File handle to maintain temporary java code fragments as per the code
+ * snippet types.
+ */
+ private transient TempJavaCodeFragmentFiles tempFileHandle;
+
+ /**
+ * Creates YANG java uses object.
+ */
+ public YangJavaUses() {
+ super();
+ setJavaFileInfo(new JavaFileInfo());
+ }
+
+ /**
+ * Returns the generated java file information.
+ *
+ * @return generated java file information
+ */
+ @Override
+ public JavaFileInfo getJavaFileInfo() {
+ if (javaFileInfo == null) {
+ throw new TranslatorException("Missing java info in java datamodel node");
+ }
+ return javaFileInfo;
+ }
+
+ /**
+ * Sets the java file info object.
+ *
+ * @param javaInfo java file info object
+ */
+ @Override
+ public void setJavaFileInfo(JavaFileInfo javaInfo) {
+ javaFileInfo = javaInfo;
+ }
+
+ /**
+ * Returns the temporary file handle.
+ *
+ * @return temporary file handle
+ */
+ @Override
+ public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
+ return tempFileHandle;
+ }
+
+ /**
+ * Sets temporary file handle.
+ *
+ * @param fileHandle temporary file handle
+ */
+ @Override
+ public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
+ tempFileHandle = fileHandle;
+ }
+
+ @Override
+ public void generateCodeEntry(YangPluginConfig yangPlugin)
+ throws TranslatorException {
+ try {
+ updatePackageInfo(this, yangPlugin);
+
+ if (!(getParentNodeInGenCode(this) instanceof JavaCodeGeneratorInfo)) {
+ throw new TranslatorException("invalid container of uses");
+ }
+ JavaCodeGeneratorInfo javaCodeGeneratorInfo = (JavaCodeGeneratorInfo) getParentNodeInGenCode(this);
+
+ if (javaCodeGeneratorInfo instanceof YangGrouping) {
+ /*
+ * Do nothing, since it will taken care in the groupings uses.
+ */
+ return;
+ }
+
+ for (List<YangLeaf> leavesList : getUsesResolvedLeavesList()) {
+ // add the resolved leaves to the parent as an attribute
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles().addLeavesInfoToTempFiles(leavesList, yangPlugin);
+ }
+
+ for (List<YangLeafList> listOfLeafLists : getUsesResolvedListOfLeafList()) {
+ // add the resolved leaf-list to the parent as an attribute
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles().addLeafListInfoToTempFiles(listOfLeafLists, yangPlugin);
+ }
+
+ for (YangNode usesResolvedNode : getUsesResolvedNodeList()) {
+ // add the resolved nodes to the parent as an attribute
+ addCurNodeAsAttributeInTargetTempFile(usesResolvedNode, yangPlugin,
+ getParentNodeInGenCode(this));
+ }
+
+ } catch (IOException e) {
+ throw new TranslatorException(e.getCause());
+ }
+ }
+
+ @Override
+ public void generateCodeExit()
+ throws TranslatorException {
+ /*
+ * Do nothing.
+ */
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/package-info.java
new file mode 100644
index 0000000..3257922
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/javamodel/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+/**
+ * Maintains application's schema mapped to java classes / interfaces.
+ */
+package org.onosproject.yangutils.translator.tojava.javamodel;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/package-info.java
new file mode 100644
index 0000000..1aac09e
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Generates java class definition from data model.
+ */
+package org.onosproject.yangutils.translator.tojava;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/AttributesJavaDataType.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/AttributesJavaDataType.java
new file mode 100644
index 0000000..19ed11d
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/AttributesJavaDataType.java
@@ -0,0 +1,506 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import java.util.Stack;
+
+import org.onosproject.yangutils.datamodel.YangDataTypes;
+import org.onosproject.yangutils.datamodel.YangDerivedInfo;
+import org.onosproject.yangutils.datamodel.YangEnumeration;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.YangTypeDef;
+import org.onosproject.yangutils.datamodel.YangUnion;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.javamodel.JavaCodeGeneratorInfo;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaEnumeration;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaTypeDef;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaUnion;
+
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCurNodePackage;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getRootPackage;
+import static org.onosproject.yangutils.utils.UtilConstants.BIG_INTEGER;
+import static org.onosproject.yangutils.utils.UtilConstants.BOOLEAN_DATA_TYPE;
+import static org.onosproject.yangutils.utils.UtilConstants.BOOLEAN_WRAPPER;
+import static org.onosproject.yangutils.utils.UtilConstants.BYTE;
+import static org.onosproject.yangutils.utils.UtilConstants.BYTE_WRAPPER;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.FROM_STRING_METHOD_NAME;
+import static org.onosproject.yangutils.utils.UtilConstants.INT;
+import static org.onosproject.yangutils.utils.UtilConstants.INTEGER_WRAPPER;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_LANG;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_MATH;
+import static org.onosproject.yangutils.utils.UtilConstants.LONG;
+import static org.onosproject.yangutils.utils.UtilConstants.LONG_WRAPPER;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW;
+import static org.onosproject.yangutils.utils.UtilConstants.PARSE_BOOLEAN;
+import static org.onosproject.yangutils.utils.UtilConstants.PARSE_BYTE;
+import static org.onosproject.yangutils.utils.UtilConstants.PARSE_INT;
+import static org.onosproject.yangutils.utils.UtilConstants.PARSE_LONG;
+import static org.onosproject.yangutils.utils.UtilConstants.PARSE_SHORT;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.SHORT;
+import static org.onosproject.yangutils.utils.UtilConstants.SHORT_WRAPPER;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.UtilConstants.STRING_DATA_TYPE;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_BINARY_CLASS;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_BITS_CLASS;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_DECIMAL64_CLASS;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_TYPES_PKG;
+
+/**
+ * Represents java data types info corresponding to YANG type.
+ */
+public final class AttributesJavaDataType {
+
+ /**
+ * Creates an instance of attribute java data type.
+ */
+ private AttributesJavaDataType() {
+ }
+
+ /**
+ * Returns java type.
+ *
+ * @param yangType YANG type
+ * @return java type
+ */
+ public static String getJavaDataType(YangType<?> yangType) {
+
+ YangDataTypes type = yangType.getDataType();
+
+ switch (type) {
+ case INT8:
+ return BYTE;
+ case INT16:
+ return SHORT;
+ case INT32:
+ return INT;
+ case INT64:
+ return LONG;
+ case UINT8:
+ return SHORT;
+ case UINT16:
+ return INT;
+ case UINT32:
+ return LONG;
+ case UINT64:
+ return BIG_INTEGER;
+ case BINARY:
+ return YANG_BINARY_CLASS;
+ case DECIMAL64:
+ return YANG_DECIMAL64_CLASS;
+ case STRING:
+ return STRING_DATA_TYPE;
+ case BOOLEAN:
+ return BOOLEAN_DATA_TYPE;
+ default:
+ throw new TranslatorException("given data type is not supported.");
+ }
+ }
+
+ /**
+ * Returns from string method parsed string.
+ *
+ * @param targetDataType target data type
+ * @param yangType YANG type
+ * @return parsed string
+ */
+ public static String getParseFromStringMethod(String targetDataType, YangType<?> yangType) {
+
+ YangDataTypes type = yangType.getDataType();
+
+ switch (type) {
+ case INT8:
+ return BYTE_WRAPPER + PERIOD + PARSE_BYTE;
+ case INT16:
+ return SHORT_WRAPPER + PERIOD + PARSE_SHORT;
+ case INT32:
+ return INTEGER_WRAPPER + PERIOD + PARSE_INT;
+ case INT64:
+ return LONG_WRAPPER + PERIOD + PARSE_LONG;
+ case UINT8:
+ return SHORT_WRAPPER + PERIOD + PARSE_SHORT;
+ case UINT16:
+ return INTEGER_WRAPPER + PERIOD + PARSE_INT;
+ case UINT32:
+ return LONG_WRAPPER + PERIOD + PARSE_LONG;
+ case UINT64:
+ return NEW + SPACE + BIG_INTEGER;
+ case STRING:
+ return EMPTY_STRING;
+ case EMPTY:
+ case BOOLEAN:
+ return BOOLEAN_WRAPPER + PERIOD + PARSE_BOOLEAN;
+ case DECIMAL64:
+ case BITS:
+ case BINARY:
+ case UNION:
+ case ENUMERATION:
+ case DERIVED:
+ return targetDataType + PERIOD + FROM_STRING_METHOD_NAME;
+ default:
+ throw new TranslatorException("given data type is not supported.");
+ }
+ }
+
+ /**
+ * Returns java import class.
+ *
+ * @param yangType YANG type
+ * @param isListAttr if the attribute need to be a list
+ * @param pluginConfig plugin configurations
+ * @return java import class
+ */
+ public static String getJavaImportClass(YangType<?> yangType, boolean isListAttr,
+ YangToJavaNamingConflictUtil pluginConfig) {
+
+ YangDataTypes type = yangType.getDataType();
+
+ if (isListAttr) {
+ switch (type) {
+ case INT8:
+ return BYTE_WRAPPER;
+ case INT16:
+ return SHORT_WRAPPER;
+ case INT32:
+ return INTEGER_WRAPPER;
+ case INT64:
+ return LONG_WRAPPER;
+ case UINT8:
+ return SHORT_WRAPPER;
+ case UINT16:
+ return INTEGER_WRAPPER;
+ case UINT32:
+ return LONG_WRAPPER;
+ case UINT64:
+ return BIG_INTEGER;
+ case DECIMAL64:
+ return YANG_DECIMAL64_CLASS;
+ case STRING:
+ return STRING_DATA_TYPE;
+ case BOOLEAN:
+ return BOOLEAN_WRAPPER;
+ case ENUMERATION:
+ return getCapitalCase(
+ getCamelCase(((YangJavaEnumeration) yangType.getDataTypeExtendedInfo()).getName(),
+ pluginConfig));
+ case BITS:
+ return YANG_BITS_CLASS;
+ case BINARY:
+ return YANG_BINARY_CLASS;
+ case LEAFREF:
+ //TODO:LEAFREF
+ break;
+ case IDENTITYREF:
+ //TODO:IDENTITYREF
+ break;
+ case EMPTY:
+ return BOOLEAN_WRAPPER;
+ case UNION:
+ return getCapitalCase(getCamelCase(((YangJavaUnion) yangType.getDataTypeExtendedInfo()).getName(),
+ pluginConfig));
+ case INSTANCE_IDENTIFIER:
+ //TODO:INSTANCE_IDENTIFIER
+ break;
+ case DERIVED:
+ return getCapitalCase(
+ getCamelCase(yangType.getDataTypeName(), pluginConfig));
+ default:
+ throw new TranslatorException("given data type is not supported.");
+ }
+ } else {
+ switch (type) {
+ case UINT64:
+ return BIG_INTEGER;
+ case DECIMAL64:
+ return YANG_DECIMAL64_CLASS;
+ case STRING:
+ return STRING_DATA_TYPE;
+ case ENUMERATION:
+ return getCapitalCase(
+ getCamelCase(((YangJavaEnumeration) yangType.getDataTypeExtendedInfo()).getName(),
+ pluginConfig));
+ case BITS:
+ return YANG_BITS_CLASS;
+ case BINARY:
+ return YANG_BINARY_CLASS;
+ case LEAFREF:
+ //TODO:LEAFREF
+ break;
+ case IDENTITYREF:
+ //TODO:IDENTITYREF
+ break;
+ case EMPTY:
+ return BOOLEAN_DATA_TYPE;
+ case UNION:
+ return getCapitalCase(getCamelCase(((YangJavaUnion) yangType.getDataTypeExtendedInfo()).getName(),
+ pluginConfig));
+ case INSTANCE_IDENTIFIER:
+ //TODO:INSTANCE_IDENTIFIER
+ break;
+ case DERIVED:
+ return getCapitalCase(
+ getCamelCase(yangType.getDataTypeName(), pluginConfig));
+ default:
+ return null;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns java import package.
+ *
+ * @param yangType YANG type
+ * @param isListAttr if the attribute is of list type
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return java import package
+ */
+ public static String getJavaImportPackage(YangType<?> yangType, boolean isListAttr,
+ YangToJavaNamingConflictUtil conflictResolver) {
+
+ YangDataTypes type = yangType.getDataType();
+
+ if (isListAttr) {
+ switch (type) {
+ case INT8:
+ case INT16:
+ case INT32:
+ case INT64:
+ case UINT8:
+ case UINT16:
+ case UINT32:
+ case STRING:
+ case BOOLEAN:
+ case EMPTY:
+ return JAVA_LANG;
+ case UINT64:
+ return JAVA_MATH;
+ case ENUMERATION:
+ return getEnumsPackage(yangType, conflictResolver);
+ case DECIMAL64:
+ case BITS:
+ case BINARY:
+ return YANG_TYPES_PKG;
+ case LEAFREF:
+ //TODO:LEAFREF
+ break;
+ case IDENTITYREF:
+ //TODO:IDENTITYREF
+ break;
+ case UNION:
+ return getUnionPackage(yangType, conflictResolver);
+ case INSTANCE_IDENTIFIER:
+ //TODO:INSTANCE_IDENTIFIER
+ break;
+ case DERIVED:
+ return getTypDefsPackage(yangType, conflictResolver);
+ default:
+ throw new TranslatorException("given data type is not supported.");
+ }
+ } else {
+ switch (type) {
+ case UINT64:
+ return JAVA_MATH;
+ case STRING:
+ return JAVA_LANG;
+ case ENUMERATION:
+ return getEnumsPackage(yangType, conflictResolver);
+ case DECIMAL64:
+ case BITS:
+ case BINARY:
+ return YANG_TYPES_PKG;
+ case LEAFREF:
+ //TODO:LEAFREF
+ break;
+ case IDENTITYREF:
+ //TODO:IDENTITYREF
+ break;
+ case EMPTY:
+ return JAVA_LANG;
+ case UNION:
+ return getUnionPackage(yangType, conflictResolver);
+ case INSTANCE_IDENTIFIER:
+ //TODO:INSTANCE_IDENTIFIER
+ break;
+ case DERIVED:
+ return getTypDefsPackage(yangType, conflictResolver);
+ default:
+ return null;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns java package for typedef node.
+ *
+ * @param type YANG type
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return java package for typedef node
+ */
+ private static String getTypDefsPackage(YangType<?> type, YangToJavaNamingConflictUtil conflictResolver) {
+ Object var = type.getDataTypeExtendedInfo();
+ if (!(var instanceof YangDerivedInfo)) {
+ throw new TranslatorException("type should have been derived.");
+ }
+
+ if (!(((YangDerivedInfo<?>) var).getReferredTypeDef() instanceof YangTypeDef)) {
+ throw new TranslatorException("derived info is not an instance of typedef.");
+ }
+
+ YangJavaTypeDef typedef = (YangJavaTypeDef) ((YangDerivedInfo<?>) var).getReferredTypeDef();
+ if (typedef.getJavaFileInfo().getPackage() == null) {
+ return getPackageFromParent(typedef.getParent(), conflictResolver);
+ }
+ return typedef.getJavaFileInfo().getPackage();
+ }
+
+ /**
+ * Returns java package for union node.
+ *
+ * @param type YANG type
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return java package for union node
+ */
+ private static String getUnionPackage(YangType<?> type, YangToJavaNamingConflictUtil conflictResolver) {
+
+ if (!(type.getDataTypeExtendedInfo() instanceof YangUnion)) {
+ throw new TranslatorException("type should have been union.");
+ }
+
+ YangJavaUnion union = (YangJavaUnion) type.getDataTypeExtendedInfo();
+ if (union.getJavaFileInfo().getPackage() == null) {
+ return getPackageFromParent(union.getParent(), conflictResolver);
+ }
+ return union.getJavaFileInfo().getPackage();
+ }
+
+ /**
+ * Returns YANG enumeration's java package.
+ *
+ * @param type YANG type
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return YANG enumeration's java package
+ */
+ private static String getEnumsPackage(YangType<?> type, YangToJavaNamingConflictUtil conflictResolver) {
+
+ if (!(type.getDataTypeExtendedInfo() instanceof YangEnumeration)) {
+ throw new TranslatorException("type should have been enumeration.");
+ }
+ YangJavaEnumeration enumeration = (YangJavaEnumeration) type.getDataTypeExtendedInfo();
+ if (enumeration.getJavaFileInfo().getPackage() == null) {
+ return getPackageFromParent(enumeration.getParent(), conflictResolver);
+ }
+ return enumeration.getJavaFileInfo().getPackage();
+ }
+
+ /**
+ * Returns package from parent node.
+ *
+ * @param parent parent YANG node
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return java package from parent node
+ */
+ private static String getPackageFromParent(YangNode parent,
+ YangToJavaNamingConflictUtil conflictResolver) {
+ if (!(parent instanceof JavaFileInfoContainer)) {
+ throw new TranslatorException("invalid child node is being processed.");
+ }
+ JavaFileInfo parentInfo = ((JavaFileInfoContainer) parent).getJavaFileInfo();
+ if (parentInfo.getPackage() == null) {
+ updateJavaFileInfo(parent, conflictResolver);
+ }
+ return parentInfo.getPackage() + PERIOD + parentInfo.getJavaName().toLowerCase();
+ }
+
+ /**
+ * Update the referred data model nodes java file info, this will be called,
+ * when the linked node is yet to translate. Then resolve until the parent hierarchy.
+ *
+ * @param yangNode node whose java info needs to be updated
+ * @param conflictResolver yang plugin config
+ */
+ public static void updateJavaFileInfo(YangNode yangNode,
+ YangToJavaNamingConflictUtil conflictResolver) {
+ Stack<YangNode> nodesToUpdatePackage = new Stack<YangNode>();
+
+ /*
+ * Add the nodes to be updated for package info in a stack.
+ */
+ while (yangNode != null
+ && ((JavaFileInfoContainer) yangNode)
+ .getJavaFileInfo().getPackage() == null) {
+ nodesToUpdatePackage.push(yangNode);
+ yangNode = yangNode.getParent();
+ }
+
+ /*
+ * If the package is not updated till root node, then root package needs to
+ * be updated.
+ */
+ if (yangNode == null) {
+ yangNode = nodesToUpdatePackage.pop();
+ String pkg;
+ if (yangNode instanceof YangJavaModule) {
+ YangJavaModule module = (YangJavaModule) yangNode;
+ pkg = getRootPackage(module.getVersion(), module.getNameSpace().getUri(), module
+ .getRevision().getRevDate(), conflictResolver);
+ } else if (yangNode instanceof YangJavaSubModule) {
+ YangJavaSubModule submodule = (YangJavaSubModule) yangNode;
+ pkg = getRootPackage(submodule.getVersion(),
+ submodule.getNameSpaceFromModule(submodule.getBelongsTo()),
+ submodule.getRevision().getRevDate(), conflictResolver);
+ } else {
+ throw new TranslatorException("Invalid root node of data model tree");
+ }
+
+ ((JavaCodeGeneratorInfo) yangNode).getJavaFileInfo()
+ .setJavaName(getCamelCase(yangNode.getName(), conflictResolver));
+ ((JavaCodeGeneratorInfo) yangNode).getJavaFileInfo()
+ .setPackage(pkg);
+ ((JavaCodeGeneratorInfo) yangNode).getJavaFileInfo()
+ .setPackageFilePath(getPackageDirPathFromJavaJPackage(
+ ((JavaCodeGeneratorInfo) yangNode).getJavaFileInfo()
+ .getPackage()));
+ }
+
+ /**
+ * Parent of the node in stack is updated with java info,
+ * all the nodes can be popped and updated
+ */
+ while (nodesToUpdatePackage.size() != 0) {
+ yangNode = nodesToUpdatePackage.pop();
+ ((JavaCodeGeneratorInfo) yangNode).getJavaFileInfo()
+ .setJavaName(getCamelCase(yangNode.getName(), conflictResolver));
+ ((JavaCodeGeneratorInfo) yangNode).getJavaFileInfo()
+ .setPackage(getCurNodePackage(yangNode));
+ ((JavaCodeGeneratorInfo) yangNode).getJavaFileInfo()
+ .setPackageFilePath(getPackageDirPathFromJavaJPackage(
+ ((JavaCodeGeneratorInfo) yangNode).getJavaFileInfo()
+ .getPackage()));
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/ClassDefinitionGenerator.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/ClassDefinitionGenerator.java
new file mode 100644
index 0000000..dde4b03
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/ClassDefinitionGenerator.java
@@ -0,0 +1,301 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaNotification;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_ENUM_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_TYPEDEF_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_UNION_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.IMPL_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.INTERFACE_MASK;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER;
+import static org.onosproject.yangutils.utils.UtilConstants.CLASS;
+import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
+import static org.onosproject.yangutils.utils.UtilConstants.DIAMOND_CLOSE_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.DIAMOND_OPEN_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.EIGHT_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.ENUM;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_LISTENER_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EXTEND;
+import static org.onosproject.yangutils.utils.UtilConstants.FINAL;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPL;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPLEMENTS;
+import static org.onosproject.yangutils.utils.UtilConstants.INTERFACE;
+import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_REG;
+import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_SERVICE;
+import static org.onosproject.yangutils.utils.UtilConstants.MANAGER;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_CURLY_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.PUBLIC;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE;
+import static org.onosproject.yangutils.utils.UtilConstants.SERVICE;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.UtilConstants.SUBJECT;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.trimAtLast;
+
+/**
+ * Represents generator for class definition of generated files.
+ */
+public final class ClassDefinitionGenerator {
+
+ /**
+ * Creates an instance of class definition generator.
+ */
+ private ClassDefinitionGenerator() {
+ }
+
+ /**
+ * Based on the file type and the YANG name of the file, generate the class
+ * / interface definition start.
+ *
+ * @param genFileTypes generated file type
+ * @param yangName class name
+ * @return class definition
+ */
+ public static String generateClassDefinition(int genFileTypes, String yangName) {
+
+ /**
+ * Based on the file type and the YANG name of the file, generate the
+ * class / interface definition start.
+ */
+ switch (genFileTypes) {
+ case BUILDER_CLASS_MASK:
+ return getBuilderClassDefinition(yangName);
+ case IMPL_CLASS_MASK:
+ return getImplClassDefinition(yangName);
+ case BUILDER_INTERFACE_MASK:
+ return getBuilderInterfaceDefinition(yangName);
+ case GENERATE_TYPEDEF_CLASS:
+ case GENERATE_UNION_CLASS:
+ return getTypeClassDefinition(yangName);
+ case GENERATE_ENUM_CLASS:
+ return getEnumClassDefinition(yangName);
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Based on the file type and the YANG name of the file, generate the class
+ * / interface definition start.
+ *
+ * @param genFileTypes generated file type
+ * @param yangName class name
+ * @param curNode current YANG node
+ * @return class definition
+ */
+ public static String generateClassDefinition(int genFileTypes, String yangName, YangNode curNode) {
+
+ /**
+ * Based on the file type and the YANG name of the file, generate the
+ * class / interface definition start.
+ */
+ switch (genFileTypes) {
+ case INTERFACE_MASK:
+ return getInterfaceDefinition(yangName, curNode);
+ case GENERATE_SERVICE_AND_MANAGER:
+ return getRpcInterfaceDefinition(yangName, curNode);
+ case GENERATE_EVENT_CLASS:
+ String eventName = yangName + SUBJECT;
+ return getEventDefinition(yangName, eventName);
+ case GENERATE_EVENT_LISTENER_INTERFACE:
+ return getEventListenerDefinition(yangName);
+ case GENERATE_EVENT_SUBJECT_CLASS:
+ return getClassDefinition(yangName);
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Returns enum file class definition.
+ *
+ * @param yangName class name
+ * @return enum file class definition
+ */
+ private static String getEnumClassDefinition(String yangName) {
+ return PUBLIC + SPACE + ENUM + SPACE + yangName + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns interface file class definition.
+ *
+ * @param yangName file name
+ * @return definition
+ */
+ private static String getInterfaceDefinition(String yangName, YangNode curNode) {
+ JavaExtendsListHolder holder = ((TempJavaCodeFragmentFilesContainer) curNode)
+ .getTempJavaCodeFragmentFiles().getBeanTempFiles().getJavaExtendsListHolder();
+
+ if (holder.getExtendsList() != null && !holder.getExtendsList().isEmpty()) {
+ String def = PUBLIC + SPACE + INTERFACE + SPACE + yangName + SPACE + EXTEND + SPACE;
+ for (JavaQualifiedTypeInfo info : holder.getExtendsList()) {
+ if (!holder.getExtendedClassStore().get(info)) {
+ def = def + info.getClassInfo() + COMMA + SPACE;
+ } else {
+ def = def + info.getPkgInfo() + PERIOD + info.getClassInfo() + COMMA + SPACE;
+ }
+ }
+
+ def = trimAtLast(def, COMMA);
+
+ return def + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+ return PUBLIC + SPACE + INTERFACE + SPACE + yangName + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns builder interface file class definition.
+ *
+ * @param yangName java class name, corresponding to which the builder class
+ * is being generated
+ * @return definition
+ */
+ private static String getBuilderInterfaceDefinition(String yangName) {
+ return INTERFACE + SPACE + yangName + BUILDER + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + NEW_LINE;
+ }
+
+ /**
+ * Returns builder file class definition.
+ *
+ * @param yangName file name
+ * @return definition
+ */
+ private static String getBuilderClassDefinition(String yangName) {
+ return PUBLIC + SPACE + CLASS + SPACE + yangName + BUILDER + SPACE + IMPLEMENTS + SPACE + yangName + PERIOD
+ + yangName + BUILDER + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns impl file class definition.
+ *
+ * @param yangName file name
+ * @return definition
+ */
+ private static String getImplClassDefinition(String yangName) {
+ return PUBLIC + SPACE + FINAL + SPACE + CLASS + SPACE + yangName + IMPL + SPACE + IMPLEMENTS + SPACE
+ + yangName + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns impl file class definition.
+ *
+ * @param yangName file name
+ * @return definition
+ */
+ private static String getClassDefinition(String yangName) {
+ return PUBLIC + SPACE + CLASS + SPACE + yangName + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns type file class definition.
+ *
+ * @param yangName file name
+ * @return definition
+ */
+ private static String getTypeClassDefinition(String yangName) {
+ return PUBLIC + SPACE + FINAL + SPACE + CLASS + SPACE + yangName + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns RPC file interface definition.
+ *
+ * @param yangName file name
+ * @param curNode current YANG node
+ * @return definition
+ */
+ private static String getRpcInterfaceDefinition(String yangName, YangNode curNode) {
+ JavaExtendsListHolder holder = ((TempJavaCodeFragmentFilesContainer) curNode)
+ .getTempJavaCodeFragmentFiles().getServiceTempFiles().getJavaExtendsListHolder();
+ if (holder.getExtendsList() != null && !holder.getExtendsList().isEmpty()) {
+ curNode = curNode.getChild();
+ while (curNode != null) {
+ if (curNode instanceof YangJavaNotification) {
+ return getRpcInterfaceDefinitionWhenItExtends(yangName, holder);
+ }
+ curNode = curNode.getNextSibling();
+ }
+ }
+ if (yangName.matches(REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE)) {
+ return PUBLIC + SPACE + INTERFACE + SPACE + yangName + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+ return PUBLIC + SPACE + CLASS + SPACE + yangName + SPACE + IMPLEMENTS + SPACE
+ + yangName.substring(0, yangName.length() - 7) + SERVICE + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /* Provides class definition when RPC interface needs to extends any event.*/
+ private static String getRpcInterfaceDefinitionWhenItExtends(String yangName,
+ JavaExtendsListHolder holder) {
+
+ if (yangName.matches(REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE)) {
+ String[] strArray = yangName.split(SERVICE);
+ return PUBLIC + SPACE + INTERFACE + SPACE + yangName + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + EXTEND + SPACE + LISTENER_SERVICE + DIAMOND_OPEN_BRACKET + strArray[0] + EVENT_STRING + COMMA
+ + SPACE + strArray[0] + EVENT_LISTENER_STRING + DIAMOND_CLOSE_BRACKET + SPACE
+ + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+ yangName = yangName.substring(0, yangName.length() - 7);
+ return PUBLIC + SPACE + CLASS + SPACE + yangName + MANAGER + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + EXTEND + SPACE + LISTENER_REG + DIAMOND_OPEN_BRACKET + yangName + EVENT_STRING + COMMA + SPACE
+ + yangName + EVENT_LISTENER_STRING + DIAMOND_CLOSE_BRACKET + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + IMPLEMENTS + SPACE + yangName + SERVICE + SPACE + OPEN_CURLY_BRACKET
+ + NEW_LINE;
+ }
+
+ /**
+ * Returns event class definition.
+ *
+ * @param javaName file name
+ * @return definition
+ */
+ private static String getEventDefinition(String javaName, String eventName) {
+ String classDef = PUBLIC + SPACE + CLASS + SPACE + javaName + SPACE + "extends AbstractEvent<"
+ + javaName + ".Type, " + eventName + ">" + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+
+ return classDef;
+ }
+
+ /**
+ * Returns event listener interface definition.
+ *
+ * @param javaName file name
+ * @return definition
+ */
+ private static String getEventListenerDefinition(String javaName) {
+ String intfDef = PUBLIC + SPACE + INTERFACE + SPACE + javaName + SPACE + "extends EventListener<"
+ + javaName;
+ if (intfDef.length() < 8) {
+ throw new RuntimeException("Event listener interface name is error");
+ }
+ intfDef = intfDef.substring(0, intfDef.length() - 8);
+ intfDef = intfDef + "Event>" + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+
+ return intfDef;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaCodeSnippetGen.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaCodeSnippetGen.java
new file mode 100644
index 0000000..b254e87
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaCodeSnippetGen.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getEnumJavaAttribute;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getSmallCase;
+import static org.onosproject.yangutils.utils.UtilConstants.ARRAY_LIST;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTED_INFO;
+import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_CURLY_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
+import static org.onosproject.yangutils.utils.UtilConstants.DIAMOND_CLOSE_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.DIAMOND_OPEN_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.EQUAL;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.LIST;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.PRIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.ENUM_ATTRIBUTE;
+
+/**
+ * Represents utility class to generate the java snippet.
+ */
+public final class JavaCodeSnippetGen {
+
+ /**
+ * Creates an instance of java code snippet gen.
+ */
+ private JavaCodeSnippetGen() {
+ }
+
+ /**
+ * Returns the java file header comment.
+ *
+ * @return the java file header comment
+ */
+ public static String getFileHeaderComment() {
+
+ /**
+ * TODO return the file header.
+ */
+ return null;
+ }
+
+ /**
+ * Returns the textual java code information corresponding to the import list.
+ *
+ * @param importInfo import info
+ * @return the textual java code information corresponding to the import
+ * list
+ */
+ public static String getImportText(JavaQualifiedTypeInfo importInfo) {
+ return IMPORT + importInfo.getPkgInfo() + PERIOD + importInfo.getClassInfo() + SEMI_COLAN + NEW_LINE;
+ }
+
+ /**
+ * Returns the textual java code for attribute definition in class.
+ *
+ * @param javaAttributeTypePkg Package of the attribute type
+ * @param javaAttributeType java attribute type
+ * @param javaAttributeName name of the attribute
+ * @param isList is list attribute
+ * @return the textual java code for attribute definition in class
+ */
+ public static String getJavaAttributeDefination(String javaAttributeTypePkg, String javaAttributeType,
+ String javaAttributeName, boolean isList) {
+
+ String attributeDefination = PRIVATE + SPACE;
+
+ if (!isList) {
+ if (javaAttributeTypePkg != null) {
+ attributeDefination = attributeDefination + javaAttributeTypePkg + PERIOD;
+ }
+
+ attributeDefination = attributeDefination + javaAttributeType + SPACE + javaAttributeName + SEMI_COLAN
+ + NEW_LINE;
+ } else {
+ attributeDefination = attributeDefination + LIST + DIAMOND_OPEN_BRACKET;
+ if (javaAttributeTypePkg != null) {
+ attributeDefination = attributeDefination + javaAttributeTypePkg + PERIOD;
+ }
+
+ attributeDefination = attributeDefination + javaAttributeType + DIAMOND_CLOSE_BRACKET + SPACE
+ + javaAttributeName + SEMI_COLAN + NEW_LINE;
+ }
+ return attributeDefination;
+ }
+
+ /**
+ * Returns list attribute string.
+ *
+ * @param type attribute type
+ * @return list attribute string
+ */
+ public static String getListAttribute(String type) {
+ return LIST + DIAMOND_OPEN_BRACKET + type + DIAMOND_CLOSE_BRACKET;
+ }
+
+ /**
+ * Returns attribute of augmented info for generated impl file.
+ *
+ * @return attribute of augmented info for generated impl file
+ */
+ public static String getAugmentedInfoAttribute() {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + PRIVATE + SPACE + getListAttribute(AUGMENTED_INFO) + SPACE
+ + getSmallCase(AUGMENTED_INFO) + LIST + SPACE + EQUAL + SPACE + NEW + SPACE + ARRAY_LIST
+ + DIAMOND_OPEN_BRACKET + DIAMOND_CLOSE_BRACKET + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN;
+ }
+
+ /**
+ * Returns based on the file type and the YANG name of the file, generate the class
+ * / interface definition close.
+ *
+ * @return corresponding textual java code information
+ */
+ public static String getJavaClassDefClose() {
+ return CLOSE_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns string for enum's attribute.
+ *
+ * @param name name of attribute
+ * @param value value of the enum
+ * @param pluginConfig plugin configurations
+ * @return string for enum's attribute
+ */
+ public static String generateEnumAttributeString(String name, int value, YangPluginConfig pluginConfig) {
+ return getJavaDoc(ENUM_ATTRIBUTE, name, false, pluginConfig) + FOUR_SPACE_INDENTATION
+ + getEnumJavaAttribute(name).toUpperCase() + OPEN_PARENTHESIS
+ + value + CLOSE_PARENTHESIS + COMMA + NEW_LINE;
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaExtendsListHolder.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaExtendsListHolder.java
new file mode 100644
index 0000000..36986b8
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaExtendsListHolder.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.JavaImportData;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.getTempJavaFragement;
+
+/**
+ * Represent the extends list for generated java classes. It holds the class details which needs
+ * to be extended by the generated java code.
+ */
+public class JavaExtendsListHolder {
+
+ /**
+ * Creates an instance of JavaExtendsListHolder.
+ */
+ public JavaExtendsListHolder() {
+ setExtendedClassStore(new HashMap<>());
+ setExtendsList(new ArrayList<>());
+ }
+
+ private Map<JavaQualifiedTypeInfo, Boolean> extendedClassStore;
+ private List<JavaQualifiedTypeInfo> extendsList;
+
+ /**
+ * Returns extends list.
+ *
+ * @return extends list
+ */
+ public Map<JavaQualifiedTypeInfo, Boolean> getExtendedClassStore() {
+ return extendedClassStore;
+ }
+
+ /**
+ * Sets extends list.
+ *
+ * @param extendedClass map of classes need to be extended
+ */
+ private void setExtendedClassStore(Map<JavaQualifiedTypeInfo, Boolean> extendedClass) {
+ this.extendedClassStore = extendedClass;
+ }
+
+ /**
+ * Adds to the extends list.
+ *
+ * @param info java file info
+ * @param node YANG node
+ */
+ public void addToExtendsList(JavaQualifiedTypeInfo info, YangNode node) {
+ JavaFileInfo fileInfo = ((JavaFileInfoContainer) node).getJavaFileInfo();
+
+ JavaImportData importData = getTempJavaFragement(node).getJavaImportData();
+ boolean qualified = importData.addImportInfo(info,
+ getCapitalCase(fileInfo.getJavaName()), fileInfo.getPackage());
+
+ /*true means import should be added*/
+ getExtendedClassStore().put(info, qualified);
+
+ addToExtendsList(info);
+ }
+
+ /**
+ * Returns extends list.
+ *
+ * @return the extendsList
+ */
+ public List<JavaQualifiedTypeInfo> getExtendsList() {
+ return extendsList;
+ }
+
+ /**
+ * Sets extends info list.
+ *
+ * @param classInfoList the extends List to set
+ */
+ private void setExtendsList(List<JavaQualifiedTypeInfo> classInfoList) {
+ this.extendsList = classInfoList;
+ }
+
+ /**
+ * Adds extends info to list.
+ *
+ * @param classInfo class info
+ */
+ private void addToExtendsList(JavaQualifiedTypeInfo classInfo) {
+ getExtendsList().add(classInfo);
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaFileGenerator.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaFileGenerator.java
new file mode 100644
index 0000000..c082d26
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaFileGenerator.java
@@ -0,0 +1,915 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
+import org.onosproject.yangutils.translator.tojava.TempJavaEnumerationFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaServiceFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.javamodel.JavaCodeGeneratorInfo;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_ENUM_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_TYPEDEF_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_UNION_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.IMPL_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ATTRIBUTES_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_FOR_TYPE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ENUM_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EQUALS_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_ENUM_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_METHOD_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_ATTRIBUTE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_GETTER_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_SETTER_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.FROM_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.HASH_CODE_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.OF_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.RPC_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.RPC_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.TO_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getAugmentedInfoAttribute;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGeneratorUtils.getDataFromTempFileHandle;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGeneratorUtils.getEnumsValueAttribute;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGeneratorUtils.initiateJavaFileGeneration;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.addActivateMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.addDeActivateMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getAddAugmentInfoMethodImpl;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getAugmentInfoListImpl;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getConstructorStart;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEnumsConstrcutor;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEnumsOfMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEqualsMethodClose;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEqualsMethodOpen;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getFromStringMethodClose;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getFromStringMethodSignature;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getGetter;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getHashCodeMethodClose;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getHashCodeMethodOpen;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getOmitNullValueString;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getRemoveAugmentationImpl;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getToStringMethodClose;
+import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getToStringMethodOpen;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.getEventEnumTypeStart;
+import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.isAugmentationHolderExtended;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER;
+import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_CURLY_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_LISTENER_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_SUBJECT_NAME_SUFFIX;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPL;
+import static org.onosproject.yangutils.utils.UtilConstants.INT;
+import static org.onosproject.yangutils.utils.UtilConstants.LOGGER_STATEMENT;
+import static org.onosproject.yangutils.utils.UtilConstants.MANAGER;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.PRIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.PUBLIC;
+import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.SERVICE_METHOD_STRING;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.GETTER_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.TYPE_CONSTRUCTOR;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.insertDataIntoJavaFile;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.trimAtLast;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.validateLineLength;
+
+/**
+ * Representation of java file generator.
+ */
+public final class JavaFileGenerator {
+
+ private JavaFileGenerator() {
+ }
+
+ /**
+ * Returns generated interface file for current node.
+ *
+ * @param file file
+ * @param imports imports for the file
+ * @param curNode current YANG node
+ * @param isAttrPresent if any attribute is present or not
+ * @return interface file
+ * @throws IOException when fails to write in file
+ */
+ public static File generateInterfaceFile(File file, List<String> imports, YangNode curNode,
+ boolean isAttrPresent)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+
+ String className = getCapitalCase(javaFileInfo.getJavaName());
+
+ initiateJavaFileGeneration(file, INTERFACE_MASK, imports, curNode, className);
+
+ if (isAttrPresent) {
+ /**
+ * Add getter methods to interface file.
+ */
+ try {
+ /**
+ * Getter methods.
+ */
+ insertDataIntoJavaFile(file, getDataFromTempFileHandle(GETTER_FOR_INTERFACE_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()));
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while interface file generation");
+ }
+ }
+ return validateLineLength(file);
+ }
+
+ /**
+ * Returns generated builder interface file for current node.
+ *
+ * @param file file
+ * @param curNode current YANG node
+ * @param isAttrPresent if any attribute is present or not
+ * @return builder interface file
+ * @throws IOException when fails to write in file
+ */
+ public static File generateBuilderInterfaceFile(File file, YangNode curNode, boolean isAttrPresent)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+ YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
+
+ String className = getCapitalCase(javaFileInfo.getJavaName());
+ String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
+
+ initiateJavaFileGeneration(file, className, BUILDER_INTERFACE_MASK, null, path, pluginConfig);
+ List<String> methods = new ArrayList<>();
+ if (isAttrPresent) {
+ try {
+ /**
+ * Getter methods.
+ */
+ methods.add(FOUR_SPACE_INDENTATION + getDataFromTempFileHandle(GETTER_FOR_INTERFACE_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()));
+ /**
+ * Setter methods.
+ */
+ methods.add(NEW_LINE);
+ methods.add(FOUR_SPACE_INDENTATION + getDataFromTempFileHandle(SETTER_FOR_INTERFACE_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()));
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while builder interface file generation");
+ }
+ }
+ /**
+ * Add build method to builder interface file.
+ */
+ methods.add(
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .addBuildMethodForInterface(pluginConfig));
+
+ /**
+ * Add getters and setters in builder interface.
+ */
+ for (String method : methods) {
+ insertDataIntoJavaFile(file, method);
+ }
+
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+ return validateLineLength(file);
+ }
+
+ /**
+ * Returns generated builder class file for current node.
+ *
+ * @param file file
+ * @param imports imports for the file
+ * @param curNode current YANG node
+ * @param isAttrPresent if any attribute is present or not
+ * @return builder class file
+ * @throws IOException when fails to write in file
+ */
+ public static File generateBuilderClassFile(File file, List<String> imports, YangNode curNode,
+ boolean isAttrPresent)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+ YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
+
+ String className = getCapitalCase(javaFileInfo.getJavaName());
+ String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
+
+ initiateJavaFileGeneration(file, className, BUILDER_CLASS_MASK, imports, path, pluginConfig);
+
+ List<String> methods = new ArrayList<>();
+
+ if (isAttrPresent) {
+ /**
+ * Add attribute strings.
+ */
+ try {
+ insertDataIntoJavaFile(file,
+ NEW_LINE + FOUR_SPACE_INDENTATION + getDataFromTempFileHandle(ATTRIBUTES_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()));
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while builder class file generation");
+ }
+
+ try {
+ /**
+ * Getter methods.
+ */
+ methods.add(getDataFromTempFileHandle(GETTER_FOR_CLASS_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()));
+ /**
+ * Setter methods.
+ */
+ methods.add(getDataFromTempFileHandle(SETTER_FOR_CLASS_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()) +
+ NEW_LINE);
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while builder class file generation");
+ }
+ } else {
+ insertDataIntoJavaFile(file, NEW_LINE);
+ }
+ /**
+ * Add default constructor and build method impl.
+ */
+ methods.add(((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .addBuildMethodImpl());
+ methods.add(((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .addDefaultConstructor(PUBLIC, BUILDER, pluginConfig));
+
+ /**
+ * Add methods in builder class.
+ */
+ for (String method : methods) {
+ insertDataIntoJavaFile(file, method);
+ }
+ return validateLineLength(file);
+ }
+
+ /**
+ * Returns generated manager class file for current node.
+ *
+ * @param file file
+ * @param imports imports for the file
+ * @param curNode current YANG node
+ * @param isAttrPresent if any attribute is present or not
+ * @return builder class file
+ * @throws IOException when fails to write in file
+ */
+ public static File generateManagerClassFile(File file, List<String> imports, YangNode curNode,
+ boolean isAttrPresent)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+
+ String className = getCapitalCase(javaFileInfo.getJavaName()) + MANAGER;
+
+ initiateJavaFileGeneration(file, GENERATE_SERVICE_AND_MANAGER, imports, curNode, className);
+
+ List<String> methods = new ArrayList<>();
+
+ insertDataIntoJavaFile(file, LOGGER_STATEMENT);
+ methods.add(addActivateMethod());
+ methods.add(addDeActivateMethod());
+
+ try {
+ if (isAttrPresent) {
+ /**
+ * Getter methods.
+ */
+ methods.add(
+ getDataFromTempFileHandle(GETTER_FOR_CLASS_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode)
+ .getTempJavaCodeFragmentFiles().getServiceTempFiles()));
+ /**
+ * Setter methods.
+ */
+ methods.add(
+ getDataFromTempFileHandle(SETTER_FOR_CLASS_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode)
+ .getTempJavaCodeFragmentFiles().getServiceTempFiles())
+ + NEW_LINE);
+
+ }
+ if (((JavaCodeGeneratorInfo) curNode).getTempJavaCodeFragmentFiles().getServiceTempFiles() != null) {
+ JavaCodeGeneratorInfo javaGeninfo = (JavaCodeGeneratorInfo) curNode;
+ /**
+ * Rpc methods
+ */
+ methods.add(getDataFromTempFileHandle(RPC_IMPL_MASK,
+ javaGeninfo.getTempJavaCodeFragmentFiles().getServiceTempFiles()));
+ }
+ insertDataIntoJavaFile(file, NEW_LINE);
+
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while manager class file generation");
+ }
+
+ /**
+ * Add methods in builder class.
+ */
+ for (String method : methods) {
+ insertDataIntoJavaFile(file, method);
+ }
+ return validateLineLength(file);
+ }
+
+ /**
+ * Returns generated impl class file for current node.
+ *
+ * @param file file
+ * @param curNode current YANG node
+ * @param isAttrPresent if any attribute is present or not
+ * @return impl class file
+ * @throws IOException when fails to write in file
+ */
+ public static File generateImplClassFile(File file, YangNode curNode, boolean isAttrPresent)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+ YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
+
+ String className = getCapitalCase(javaFileInfo.getJavaName());
+ String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
+
+ initiateJavaFileGeneration(file, className, IMPL_CLASS_MASK, null, path, pluginConfig);
+
+ List<String> methods = new ArrayList<>();
+
+ TempJavaCodeFragmentFiles javaCodeFragmentFiles = ((TempJavaCodeFragmentFilesContainer) curNode)
+ .getTempJavaCodeFragmentFiles();
+ boolean isAugmentationHolderExtended = isAugmentationHolderExtended(
+ javaCodeFragmentFiles.getBeanTempFiles().getJavaExtendsListHolder().getExtendsList());
+ /**
+ * Add attribute for augmented info's list.
+ */
+ if (isAugmentationHolderExtended) {
+ insertDataIntoJavaFile(file, getAugmentedInfoAttribute());
+ }
+ if (isAttrPresent) {
+ /**
+ * Add attribute strings.
+ */
+ try {
+ insertDataIntoJavaFile(file,
+ NEW_LINE + FOUR_SPACE_INDENTATION + getDataFromTempFileHandle(ATTRIBUTES_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()));
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while impl class file generation");
+ }
+
+ insertDataIntoJavaFile(file, NEW_LINE);
+ try {
+ /**
+ * Getter methods.
+ */
+ methods.add(getDataFromTempFileHandle(GETTER_FOR_CLASS_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()));
+
+ /**
+ * Hash code method.
+ */
+ methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() +
+ getDataFromTempFileHandle(HASH_CODE_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles()).replace(NEW_LINE, EMPTY_STRING)));
+ /**
+ * Equals method.
+ */
+ methods.add(getEqualsMethodClose(
+ getEqualsMethodOpen(className + IMPL) + getDataFromTempFileHandle(EQUALS_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles())));
+ /**
+ * To string method.
+ */
+ methods.add(getToStringMethodOpen() + getDataFromTempFileHandle(TO_STRING_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles())
+ + getToStringMethodClose());
+
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while impl class file generation");
+ }
+ } else {
+ insertDataIntoJavaFile(file, NEW_LINE);
+ }
+ try {
+
+ /**
+ * Constructor.
+ */
+ String constructor =
+ getConstructorStart(className, pluginConfig) + getDataFromTempFileHandle(CONSTRUCTOR_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles());
+
+ methods.add(constructor + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET);
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while impl class file generation");
+ }
+
+ /**
+ * Add method for augment info's list.
+ */
+ if (isAugmentationHolderExtended) {
+ methods.add(getAddAugmentInfoMethodImpl());
+ methods.add(getAugmentInfoListImpl());
+ methods.add(getRemoveAugmentationImpl());
+ }
+
+ /**
+ * Add methods in impl class.
+ */
+ for (String method : methods) {
+ insertDataIntoJavaFile(file, FOUR_SPACE_INDENTATION + method + NEW_LINE);
+ }
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+
+ return validateLineLength(file);
+ }
+
+ /**
+ * Generates class file for type def.
+ *
+ * @param file generated file
+ * @param curNode current YANG node
+ * @param imports imports for file
+ * @return type def class file
+ * @throws IOException when fails to generate class file
+ */
+ public static File generateTypeDefClassFile(File file, YangNode curNode, List<String> imports)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+ YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
+
+ String className = getCapitalCase(javaFileInfo.getJavaName());
+ String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
+
+ initiateJavaFileGeneration(file, className, GENERATE_TYPEDEF_CLASS, imports, path, pluginConfig);
+
+ List<String> methods = new ArrayList<>();
+
+ /**
+ * Add attribute strings.
+ */
+ try {
+ insertDataIntoJavaFile(file,
+ NEW_LINE + FOUR_SPACE_INDENTATION + getDataFromTempFileHandle(ATTRIBUTES_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getTypeTempFiles()));
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while type def class file generation");
+ }
+
+ /**
+ * Default constructor.
+ */
+ methods.add(((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .addDefaultConstructor(PRIVATE, EMPTY_STRING, pluginConfig));
+
+ try {
+
+ /**
+ * Type constructor.
+ */
+ methods.add(getDataFromTempFileHandle(CONSTRUCTOR_FOR_TYPE_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles()));
+
+ /**
+ * Of method.
+ */
+ methods.add(getDataFromTempFileHandle(OF_STRING_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles()));
+
+ /**
+ * Getter method.
+ */
+ methods.add(getDataFromTempFileHandle(GETTER_FOR_CLASS_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles()));
+
+ /**
+ * Hash code method.
+ */
+ methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() +
+ getDataFromTempFileHandle(HASH_CODE_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getTypeTempFiles())
+ .replace(NEW_LINE, EMPTY_STRING)));
+
+ /**
+ * Equals method.
+ */
+ methods.add(getEqualsMethodClose(getEqualsMethodOpen(className + EMPTY_STRING)
+ + getDataFromTempFileHandle(EQUALS_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles())));
+
+ /**
+ * To string method.
+ */
+ methods.add(getToStringMethodOpen() + getDataFromTempFileHandle(TO_STRING_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles())
+ + getToStringMethodClose());
+
+ JavaCodeGeneratorInfo javaGeninfo = (JavaCodeGeneratorInfo) curNode;
+ /**
+ * From string method.
+ */
+ methods.add(getFromStringMethodSignature(className, pluginConfig)
+ + getDataFromTempFileHandle(FROM_STRING_IMPL_MASK, javaGeninfo.getTempJavaCodeFragmentFiles()
+ .getTypeTempFiles()) + getFromStringMethodClose());
+
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while type def class file generation");
+ }
+
+ for (String method : methods) {
+ insertDataIntoJavaFile(file, method);
+ }
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+
+ return validateLineLength(file);
+ }
+
+ /**
+ * Generates class file for union type.
+ *
+ * @param file generated file
+ * @param curNode current YANG node
+ * @param imports imports for file
+ * @return type def class file
+ * @throws IOException when fails to generate class file
+ */
+ public static File generateUnionClassFile(File file, YangNode curNode, List<String> imports)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+ YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
+
+ String className = getCapitalCase(javaFileInfo.getJavaName());
+ String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
+
+ initiateJavaFileGeneration(file, className, GENERATE_UNION_CLASS, imports, path, pluginConfig);
+
+ List<String> methods = new ArrayList<>();
+
+ /**
+ * Add attribute strings.
+ */
+ try {
+ insertDataIntoJavaFile(file,
+ NEW_LINE + FOUR_SPACE_INDENTATION + getDataFromTempFileHandle(ATTRIBUTES_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getTypeTempFiles()));
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while union class file generation");
+ }
+
+ /**
+ * Default constructor.
+ */
+ methods.add(((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .addDefaultConstructor(PRIVATE, EMPTY_STRING, pluginConfig));
+
+ try {
+
+ /**
+ * Type constructor.
+ */
+ methods.add(getDataFromTempFileHandle(CONSTRUCTOR_FOR_TYPE_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles()));
+
+ /**
+ * Of string method.
+ */
+ methods.add(getDataFromTempFileHandle(OF_STRING_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles()));
+
+ /**
+ * Getter method.
+ */
+ methods.add(getDataFromTempFileHandle(GETTER_FOR_CLASS_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles()));
+
+ /**
+ * Hash code method.
+ */
+ methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() +
+ getDataFromTempFileHandle(HASH_CODE_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getTypeTempFiles())
+ .replace(NEW_LINE, EMPTY_STRING)));
+
+ /**
+ * Equals method.
+ */
+ methods.add(getEqualsMethodClose(getEqualsMethodOpen(className + EMPTY_STRING)
+ + getDataFromTempFileHandle(EQUALS_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles())));
+
+ /**
+ * To string method.
+ */
+ methods.add(getToStringMethodOpen() + getOmitNullValueString() +
+ getDataFromTempFileHandle(TO_STRING_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getTypeTempFiles()) + getToStringMethodClose());
+
+ /**
+ * From string method.
+ */
+ methods.add(getFromStringMethodSignature(className, pluginConfig)
+ + getDataFromTempFileHandle(FROM_STRING_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles())
+ + getFromStringMethodClose());
+
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while union class file generation");
+ }
+
+ for (String method : methods) {
+ insertDataIntoJavaFile(file, method);
+ }
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+
+ return validateLineLength(file);
+ }
+
+ /**
+ * Generates class file for type enum.
+ *
+ * @param file generated file
+ * @param curNode current YANG node
+ * @return class file for type enum
+ * @throws IOException when fails to generate class file
+ */
+ public static File generateEnumClassFile(File file, YangNode curNode)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+ YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
+
+ String className = javaFileInfo.getJavaName();
+ String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
+
+ initiateJavaFileGeneration(file, getCapitalCase(className), GENERATE_ENUM_CLASS, null, path, pluginConfig);
+ /**
+ * Add attribute strings.
+ */
+ try {
+ JavaCodeGeneratorInfo javaGeninfo = (JavaCodeGeneratorInfo) curNode;
+ insertDataIntoJavaFile(file,
+ trimAtLast(trimAtLast(getDataFromTempFileHandle(ENUM_IMPL_MASK, javaGeninfo
+ .getTempJavaCodeFragmentFiles().getEnumerationTempFiles()), COMMA), NEW_LINE)
+ + SEMI_COLAN + NEW_LINE);
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + getCapitalCase(className)
+ + " while enum class file generation");
+ }
+
+ /**
+ * Add an
+ * attribute to get the enum's values.
+ */
+ insertDataIntoJavaFile(file, getEnumsValueAttribute(getCapitalCase(className)));
+
+ /**
+ * Add a constructor for enum.
+ */
+ insertDataIntoJavaFile(file, getJavaDoc(TYPE_CONSTRUCTOR, className, false, pluginConfig)
+ + getEnumsConstrcutor(getCapitalCase(className)) + NEW_LINE);
+
+ TempJavaEnumerationFragmentFiles enumFragFiles =
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getEnumerationTempFiles();
+ insertDataIntoJavaFile(file, getEnumsOfMethod(className,
+ enumFragFiles.getJavaAttributeForEnum(pluginConfig),
+ enumFragFiles.getEnumSetJavaMap(),
+ enumFragFiles.getEnumStringList(), pluginConfig)
+ + NEW_LINE);
+
+ /**
+ * Add a getter method for enum.
+ */
+ insertDataIntoJavaFile(file, getJavaDoc(GETTER_METHOD, className, false, pluginConfig)
+ + getGetter(INT, className, GENERATE_ENUM_CLASS) + NEW_LINE);
+
+ try {
+ insertDataIntoJavaFile(file, getFromStringMethodSignature(getCapitalCase(className), pluginConfig)
+ + getDataFromTempFileHandle(FROM_STRING_IMPL_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getEnumerationTempFiles())
+ + getFromStringMethodClose());
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " +
+ getCapitalCase(className) + " while enum class file generation");
+ }
+
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+
+ return validateLineLength(file);
+ }
+
+ /**
+ * Generates interface file for rpc.
+ *
+ * @param file generated file
+ * @param curNode current YANG node
+ * @param imports imports for file
+ * @param isAttributePresent is attribute present
+ * @return rpc class file
+ * @throws IOException when fails to generate class file
+ */
+ public static File generateServiceInterfaceFile(File file, YangNode curNode, List<String> imports,
+ boolean isAttributePresent)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+
+ String className = getCapitalCase(javaFileInfo.getJavaName()) + SERVICE_METHOD_STRING;
+ initiateJavaFileGeneration(file, GENERATE_SERVICE_AND_MANAGER, imports, curNode, className);
+
+ List<String> methods = new ArrayList<>();
+
+ try {
+ if (isAttributePresent) {
+
+ /**
+ * Getter methods.
+ */
+ methods.add(getDataFromTempFileHandle(GETTER_FOR_INTERFACE_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles()));
+ /**
+ * Setter methods.
+ */
+ methods.add(getDataFromTempFileHandle(SETTER_FOR_INTERFACE_MASK,
+ ((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles()));
+ }
+ if (((JavaCodeGeneratorInfo) curNode).getTempJavaCodeFragmentFiles().getServiceTempFiles() != null) {
+ JavaCodeGeneratorInfo javaGeninfo = (JavaCodeGeneratorInfo) curNode;
+ /**
+ * Rpc methods
+ */
+ methods.add(getDataFromTempFileHandle(RPC_INTERFACE_MASK,
+ javaGeninfo.getTempJavaCodeFragmentFiles().getServiceTempFiles()));
+ }
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while rpc class file generation");
+ }
+
+ for (String method : methods) {
+ insertDataIntoJavaFile(file, method);
+ }
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+
+ return validateLineLength(file);
+ }
+
+ /**
+ * Generates event file.
+ *
+ * @param file generated file
+ * @param curNode current YANG node
+ * @param imports imports for file
+ * @throws IOException when fails to generate class file
+ */
+ public static void generateEventFile(File file, YangNode curNode, List<String> imports) throws IOException {
+
+ String className =
+ getCapitalCase(((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName())
+ + EVENT_STRING;
+
+ TempJavaServiceFragmentFiles tempFiles = ((TempJavaCodeFragmentFilesContainer) curNode)
+ .getTempJavaCodeFragmentFiles().getServiceTempFiles();
+
+ initiateJavaFileGeneration(file, GENERATE_EVENT_CLASS, imports, curNode, className);
+ try {
+ insertDataIntoJavaFile(file, NEW_LINE + getEventEnumTypeStart() +
+ trimAtLast(getDataFromTempFileHandle(EVENT_ENUM_MASK, tempFiles), COMMA)
+ + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET + NEW_LINE);
+
+ insertDataIntoJavaFile(file, getDataFromTempFileHandle(EVENT_METHOD_MASK, tempFiles));
+
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while event class file generation");
+ }
+
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+ validateLineLength(file);
+ }
+
+ /**
+ * Generates event listener file.
+ *
+ * @param file generated file
+ * @param curNode current YANG node
+ * @param imports imports for file
+ * @throws IOException when fails to generate class file
+ */
+ public static void generateEventListenerFile(File file, YangNode curNode, List<String> imports)
+ throws IOException {
+
+ String className =
+ getCapitalCase(((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName())
+ + EVENT_LISTENER_STRING;
+
+ initiateJavaFileGeneration(file, GENERATE_EVENT_LISTENER_INTERFACE, imports, curNode, className);
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+ validateLineLength(file);
+ }
+
+ /**
+ * Generates event subject's file.
+ *
+ * @param file file handle
+ * @param curNode current YANG node
+ * @throws IOException when fails to do IO exceptions
+ */
+ public static void generateEventSubjectFile(File file, YangNode curNode)
+ throws IOException {
+
+ String className = getCapitalCase(((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName())
+ + EVENT_SUBJECT_NAME_SUFFIX;
+
+ initiateJavaFileGeneration(file, GENERATE_EVENT_SUBJECT_CLASS, null, curNode, className);
+
+ TempJavaServiceFragmentFiles tempFiles = ((TempJavaCodeFragmentFilesContainer) curNode)
+ .getTempJavaCodeFragmentFiles().getServiceTempFiles();
+
+ insertDataIntoJavaFile(file, NEW_LINE);
+ try {
+ insertDataIntoJavaFile(file, getDataFromTempFileHandle(EVENT_SUBJECT_ATTRIBUTE_MASK, tempFiles));
+
+ insertDataIntoJavaFile(file, getDataFromTempFileHandle(EVENT_SUBJECT_GETTER_MASK, tempFiles));
+
+ insertDataIntoJavaFile(file, getDataFromTempFileHandle(EVENT_SUBJECT_SETTER_MASK, tempFiles));
+
+ } catch (IOException e) {
+ throw new IOException("No data found in temporary java code fragment files for " + className
+ + " while event class file generation");
+ }
+
+ insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
+ validateLineLength(file);
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaFileGeneratorUtils.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaFileGeneratorUtils.java
new file mode 100644
index 0000000..c940791
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaFileGeneratorUtils.java
@@ -0,0 +1,513 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.TempJavaBeanFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaEnumerationFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaServiceFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaTypeFragmentFiles;
+import org.onosproject.yangutils.utils.io.impl.CopyrightHeader;
+import org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_ENUM_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_TYPEDEF_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_UNION_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.IMPL_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ATTRIBUTES_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_FOR_TYPE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ENUM_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EQUALS_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_ENUM_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_METHOD_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_ATTRIBUTE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_GETTER_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_SETTER_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.FROM_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.HASH_CODE_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.OF_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.RPC_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.RPC_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_CLASS_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_INTERFACE_MASK;
+import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.TO_STRING_IMPL_MASK;
+import static org.onosproject.yangutils.translator.tojava.utils.ClassDefinitionGenerator.generateClassDefinition;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getJavaPackageFromPackagePath;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getSmallCase;
+import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.COMPONENT_ANNOTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.EQUAL;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.IMMEDIATE;
+import static org.onosproject.yangutils.utils.UtilConstants.INT;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.PACKAGE;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.PRIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE;
+import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.SERVICE_ANNOTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.UtilConstants.TRUE;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.BUILDER_CLASS;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.BUILDER_INTERFACE;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.ENUM_CLASS;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.EVENT;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.EVENT_LISTENER;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.IMPL_CLASS;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.INTERFACE;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.RPC_INTERFACE;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.RPC_MANAGER;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.insertDataIntoJavaFile;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.parsePkg;
+
+/**
+ * Represents utilities for java file generator.
+ */
+public final class JavaFileGeneratorUtils {
+
+ /**
+ * Creates an instance of java file generator util.
+ */
+ private JavaFileGeneratorUtils() {
+ }
+
+ /**
+ * Returns a file object for generated file.
+ *
+ * @param fileName file name
+ * @param filePath file package path
+ * @param extension file extension
+ * @param handle cached file handle
+ * @return file object
+ */
+ public static File getFileObject(String filePath, String fileName, String extension, JavaFileInfo handle) {
+
+ return new File(handle.getBaseCodeGenPath() + filePath + SLASH + fileName + extension);
+ }
+
+ /**
+ * Returns data stored in temporary files.
+ *
+ * @param generatedTempFiles temporary file types
+ * @param tempJavaFragmentFiles temp java fragment files
+ * @return data stored in temporary files
+ * @throws IOException when failed to get the data from temporary file handle
+ */
+ public static String getDataFromTempFileHandle(int generatedTempFiles,
+ TempJavaFragmentFiles tempJavaFragmentFiles)
+ throws IOException {
+
+ TempJavaTypeFragmentFiles typeFragmentFiles = null;
+
+ if (tempJavaFragmentFiles instanceof TempJavaTypeFragmentFiles) {
+ typeFragmentFiles = (TempJavaTypeFragmentFiles) tempJavaFragmentFiles;
+ }
+
+ TempJavaBeanFragmentFiles beanFragmentFiles = null;
+
+ if (tempJavaFragmentFiles instanceof TempJavaBeanFragmentFiles) {
+ beanFragmentFiles = (TempJavaBeanFragmentFiles) tempJavaFragmentFiles;
+ }
+
+ TempJavaServiceFragmentFiles serviceFragmentFiles = null;
+ if (tempJavaFragmentFiles instanceof TempJavaServiceFragmentFiles) {
+ serviceFragmentFiles = (TempJavaServiceFragmentFiles) tempJavaFragmentFiles;
+ }
+
+ if ((generatedTempFiles & ATTRIBUTES_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getAttributesTempFileHandle());
+ } else if ((generatedTempFiles & GETTER_FOR_INTERFACE_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getGetterInterfaceTempFileHandle());
+ } else if ((generatedTempFiles & SETTER_FOR_INTERFACE_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getSetterInterfaceTempFileHandle());
+ } else if ((generatedTempFiles & GETTER_FOR_CLASS_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getGetterImplTempFileHandle());
+ } else if ((generatedTempFiles & SETTER_FOR_CLASS_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getSetterImplTempFileHandle());
+ } else if ((generatedTempFiles & CONSTRUCTOR_IMPL_MASK) != 0) {
+ if (beanFragmentFiles == null) {
+ throw new TranslatorException("Required constructor info is missing.");
+ }
+ return beanFragmentFiles
+ .getTemporaryDataFromFileHandle(beanFragmentFiles.getConstructorImplTempFileHandle());
+ } else if ((generatedTempFiles & HASH_CODE_IMPL_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getHashCodeImplTempFileHandle());
+ } else if ((generatedTempFiles & EQUALS_IMPL_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getEqualsImplTempFileHandle());
+ } else if ((generatedTempFiles & TO_STRING_IMPL_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getToStringImplTempFileHandle());
+ } else if ((generatedTempFiles & OF_STRING_IMPL_MASK) != 0) {
+ if (typeFragmentFiles == null) {
+ throw new TranslatorException("Required of string implementation info is missing.");
+ }
+ return typeFragmentFiles
+ .getTemporaryDataFromFileHandle(typeFragmentFiles.getOfStringImplTempFileHandle());
+ } else if ((generatedTempFiles & CONSTRUCTOR_FOR_TYPE_MASK) != 0) {
+ if (typeFragmentFiles == null) {
+ throw new TranslatorException("Required constructor implementation info is missing.");
+ }
+ return typeFragmentFiles
+ .getTemporaryDataFromFileHandle(typeFragmentFiles.getConstructorForTypeTempFileHandle());
+ } else if ((generatedTempFiles & FROM_STRING_IMPL_MASK) != 0) {
+ return tempJavaFragmentFiles
+ .getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getFromStringImplTempFileHandle());
+ } else if ((generatedTempFiles & ENUM_IMPL_MASK) != 0) {
+ if (!(tempJavaFragmentFiles instanceof TempJavaEnumerationFragmentFiles)) {
+ throw new TranslatorException("Required enum info is missing.");
+ }
+ TempJavaEnumerationFragmentFiles enumFragmentFiles =
+ (TempJavaEnumerationFragmentFiles) tempJavaFragmentFiles;
+ return enumFragmentFiles
+ .getTemporaryDataFromFileHandle(enumFragmentFiles.getEnumClassTempFileHandle());
+ } else if ((generatedTempFiles & RPC_INTERFACE_MASK) != 0) {
+ if (serviceFragmentFiles == null) {
+ throw new TranslatorException("Required rpc interface info is missing.");
+ }
+ return serviceFragmentFiles
+ .getTemporaryDataFromFileHandle(serviceFragmentFiles.getRpcInterfaceTempFileHandle());
+ } else if ((generatedTempFiles & RPC_IMPL_MASK) != 0) {
+ if (serviceFragmentFiles == null) {
+ throw new TranslatorException("Required rpc implementation info is missing.");
+ }
+ return serviceFragmentFiles
+ .getTemporaryDataFromFileHandle(serviceFragmentFiles.getRpcImplTempFileHandle());
+ } else if ((generatedTempFiles & EVENT_ENUM_MASK) != 0) {
+ if (serviceFragmentFiles == null) {
+ throw new TranslatorException("Required rpc implementation info is missing.");
+ }
+ return serviceFragmentFiles
+ .getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventEnumTempFileHandle());
+ } else if ((generatedTempFiles & EVENT_METHOD_MASK) != 0) {
+ if (serviceFragmentFiles == null) {
+ throw new TranslatorException("Required rpc implementation info is missing.");
+ }
+ return serviceFragmentFiles
+ .getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventMethodTempFileHandle());
+ } else if ((generatedTempFiles & EVENT_SUBJECT_GETTER_MASK) != 0) {
+ if (serviceFragmentFiles == null) {
+ throw new TranslatorException("Required rpc implementation info is missing.");
+ }
+ return serviceFragmentFiles
+ .getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventSubjectGetterTempFileHandle());
+ } else if ((generatedTempFiles & EVENT_SUBJECT_SETTER_MASK) != 0) {
+ if (serviceFragmentFiles == null) {
+ throw new TranslatorException("Required rpc implementation info is missing.");
+ }
+ return serviceFragmentFiles
+ .getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventSubjectSetterTempFileHandle());
+ } else if ((generatedTempFiles & EVENT_SUBJECT_ATTRIBUTE_MASK) != 0) {
+ if (serviceFragmentFiles == null) {
+ throw new TranslatorException("Required rpc implementation info is missing.");
+ }
+ return serviceFragmentFiles
+ .getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventSubjectAttributeTempFileHandle());
+ }
+ return null;
+ }
+
+ /**
+ * Initiates generation of file based on generated file type.
+ *
+ * @param file generated file
+ * @param className generated file class name
+ * @param genType generated file type
+ * @param imports imports for the file
+ * @param pkg generated file package
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to generate a file
+ */
+ public static void initiateJavaFileGeneration(File file, String className, int genType, List<String> imports,
+ String pkg, YangPluginConfig pluginConfig)
+ throws IOException {
+
+ try {
+ file.createNewFile();
+ appendContents(file, className, genType, imports, pkg, pluginConfig);
+ } catch (IOException e) {
+ throw new IOException("Failed to create " + file.getName() + " class file.");
+ }
+ }
+
+ /**
+ * Initiates generation of file based on generated file type.
+ *
+ * @param file generated file
+ * @param genType generated file type
+ * @param imports imports for the file
+ * @param curNode current YANG node
+ * @param className class name
+ * @throws IOException when fails to generate a file
+ */
+ public static void initiateJavaFileGeneration(File file, int genType, List<String> imports,
+ YangNode curNode, String className)
+ throws IOException {
+
+ try {
+ if (file.exists()) {
+ throw new IOException(file.getName() + " is reused due to YANG naming");
+ }
+
+ file.createNewFile();
+ appendContents(file, genType, imports, curNode, className);
+ } catch (IOException e) {
+ throw new IOException("Failed to create " + file.getName() + " class file.");
+ }
+ }
+
+ /**
+ * Appends all the contents into a generated java file.
+ *
+ * @param file generated file
+ * @param genType generated file type
+ * @param importsList list of java imports
+ * @param curNode current YANG node
+ * @param className class name
+ * @throws IOException
+ */
+ private static void appendContents(File file, int genType, List<String> importsList, YangNode curNode,
+ String className)
+ throws IOException {
+
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
+
+ String name = javaFileInfo.getJavaName();
+ String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
+
+ String pkgString = null;
+ if (genType == GENERATE_EVENT_CLASS
+ || genType == GENERATE_EVENT_LISTENER_INTERFACE
+ || genType == GENERATE_EVENT_SUBJECT_CLASS) {
+ pkgString = parsePackageString((path + PERIOD + name).toLowerCase(), importsList);
+ } else {
+ pkgString = parsePackageString(path, importsList);
+ }
+ switch (genType) {
+ case INTERFACE_MASK:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, genType, INTERFACE, curNode, className);
+ break;
+ case GENERATE_SERVICE_AND_MANAGER:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, genType, RPC_INTERFACE, curNode, className);
+ break;
+ case GENERATE_EVENT_CLASS:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, genType, EVENT, curNode, className);
+ break;
+ case GENERATE_EVENT_LISTENER_INTERFACE:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, genType, EVENT_LISTENER, curNode, className);
+ break;
+ case GENERATE_EVENT_SUBJECT_CLASS:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, genType, EVENT_SUBJECT_CLASS, curNode, className);
+ break;
+ default:
+ break;
+ }
+ }
+
+ /**
+ * Appends all the contents into a generated java file.
+ *
+ * @param file generated file
+ * @param fileName generated file name
+ * @param genType generated file type
+ * @param importsList list of java imports
+ * @param pkg generated file package
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to append contents
+ */
+ private static void appendContents(File file, String fileName, int genType, List<String> importsList, String pkg,
+ YangPluginConfig pluginConfig)
+ throws IOException {
+
+ String pkgString = parsePackageString(pkg, importsList);
+
+ switch (genType) {
+ case IMPL_CLASS_MASK:
+ write(file, fileName, genType, IMPL_CLASS, pluginConfig);
+ break;
+ case BUILDER_INTERFACE_MASK:
+ write(file, fileName, genType, BUILDER_INTERFACE, pluginConfig);
+ break;
+ case GENERATE_TYPEDEF_CLASS:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, fileName, genType, IMPL_CLASS, pluginConfig);
+ break;
+ case BUILDER_CLASS_MASK:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, fileName, genType, BUILDER_CLASS, pluginConfig);
+ break;
+ case GENERATE_UNION_CLASS:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, fileName, genType, IMPL_CLASS, pluginConfig);
+ break;
+ case GENERATE_ENUM_CLASS:
+ appendHeaderContents(file, pkgString, importsList);
+ write(file, fileName, genType, ENUM_CLASS, pluginConfig);
+ break;
+ default:
+ break;
+ }
+ }
+
+ /**
+ * Removes base directory path from package and generates package string for file.
+ *
+ * @param javaPkg generated java package
+ * @param importsList list of imports
+ * @return package string
+ */
+ private static String parsePackageString(String javaPkg, List<String> importsList) {
+
+ javaPkg = parsePkg(getJavaPackageFromPackagePath(javaPkg));
+ if (importsList != null) {
+ if (!importsList.isEmpty()) {
+ return PACKAGE + SPACE + javaPkg + SEMI_COLAN + NEW_LINE;
+ } else {
+ return PACKAGE + SPACE + javaPkg + SEMI_COLAN;
+ }
+ } else {
+ return PACKAGE + SPACE + javaPkg + SEMI_COLAN;
+ }
+ }
+
+ /**
+ * Appends other contents to interface, builder and typedef classes.
+ * for example : ONOS copyright, imports and package.
+ *
+ * @param file generated file
+ * @param pkg generated package
+ * @param importsList list of imports
+ * @throws IOException when fails to append contents
+ */
+ private static void appendHeaderContents(File file, String pkg, List<String> importsList)
+ throws IOException {
+
+ insertDataIntoJavaFile(file, CopyrightHeader.getCopyrightHeader());
+ insertDataIntoJavaFile(file, pkg);
+
+ /*
+ * TODO: add the file header using
+ * JavaCodeSnippetGen.getFileHeaderComment
+ */
+
+ if (importsList != null) {
+ insertDataIntoJavaFile(file, NEW_LINE);
+ for (String imports : importsList) {
+ insertDataIntoJavaFile(file, imports);
+ }
+ }
+ }
+
+ /**
+ * Writes data to the specific generated file.
+ *
+ * @param file generated file
+ * @param genType generated file type
+ * @param javaDocType java doc type
+ * @param curNode current YANG node
+ * @param fileName file name
+ * @throws IOException when fails to write into a file
+ */
+ private static void write(File file, int genType, JavaDocType javaDocType, YangNode curNode, String fileName)
+ throws IOException {
+
+ YangPluginConfig pluginConfig = ((JavaFileInfoContainer) curNode).getJavaFileInfo().getPluginConfig();
+ if ((genType & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ if (!fileName.matches(REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE)) {
+ insertDataIntoJavaFile(file, getJavaDoc(RPC_MANAGER, fileName, false, pluginConfig));
+ insertDataIntoJavaFile(file, addComponentString());
+ } else {
+ insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false, pluginConfig));
+ }
+ } else {
+ insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false, pluginConfig));
+ }
+ insertDataIntoJavaFile(file, generateClassDefinition(genType, fileName, curNode));
+ }
+
+ /**
+ * Writes data to the specific generated file.
+ *
+ * @param file generated file
+ * @param fileName file name
+ * @param genType generated file type
+ * @param javaDocType java doc type
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to write into a file
+ */
+ private static void write(File file, String fileName, int genType, JavaDocType javaDocType,
+ YangPluginConfig pluginConfig)
+ throws IOException {
+ insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false, pluginConfig));
+ insertDataIntoJavaFile(file, generateClassDefinition(genType, fileName));
+ }
+
+ /**
+ * Returns integer attribute for enum's class to get the values.
+ *
+ * @param className enum's class name
+ * @return enum's attribute
+ */
+ public static String getEnumsValueAttribute(String className) {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + PRIVATE + SPACE + INT + SPACE + getSmallCase(className)
+ + SEMI_COLAN + NEW_LINE;
+ }
+
+ /**
+ * Returns component string.
+ *
+ * @return component string
+ */
+ public static String addComponentString() {
+ return NEW_LINE + COMPONENT_ANNOTATION + SPACE + OPEN_PARENTHESIS + IMMEDIATE + SPACE
+ + EQUAL + SPACE + TRUE + CLOSE_PARENTHESIS + NEW_LINE + SERVICE_ANNOTATION;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaIdentifierSyntax.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaIdentifierSyntax.java
new file mode 100644
index 0000000..95355aa
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/JavaIdentifierSyntax.java
@@ -0,0 +1,490 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.utils.DataModelUtils;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+
+import static org.onosproject.yangutils.utils.UtilConstants.COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.DEFAULT_BASE_PKG;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.HYPHEN;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_KEY_WORDS;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.QUOTES;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_DIGITS_WITH_SINGLE_LETTER;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_FIRST_DIGIT;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_HYPHEN;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_IDENTIFIER_SPECIAL_CHAR;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_SINGLE_LETTER;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_UNDERSCORE;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_WITH_ALL_SPECIAL_CHAR;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_WITH_DIGITS;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_WITH_SINGLE_CAPITAL_CASE;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_WITH_SINGLE_CAPITAL_CASE_AND_DIGITS_SMALL_CASES;
+import static org.onosproject.yangutils.utils.UtilConstants.REGEX_WITH_UPPERCASE;
+import static org.onosproject.yangutils.utils.UtilConstants.REVISION_PREFIX;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.UtilConstants.UNDER_SCORE;
+import static org.onosproject.yangutils.utils.UtilConstants.VERSION_PREFIX;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_AUTO_PREFIX;
+
+/**
+ * Represents an utility Class for translating the name from YANG to java convention.
+ */
+public final class JavaIdentifierSyntax {
+
+ private static final int MAX_MONTHS = 12;
+ private static final int MAX_DAYS = 31;
+ private static final int INDEX_ZERO = 0;
+ private static final int INDEX_ONE = 1;
+ private static final int INDEX_TWO = 2;
+ private static final int VALUE_CHECK = 10;
+ private static final String ZERO = "0";
+
+ /**
+ * Create instance of java identifier syntax.
+ */
+ private JavaIdentifierSyntax() {
+ }
+
+ /**
+ * Returns the root package string.
+ *
+ * @param version YANG version
+ * @param nameSpace name space of the module
+ * @param revision revision of the module defined
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return the root package string
+ */
+ public static String getRootPackage(byte version, String nameSpace, String revision,
+ YangToJavaNamingConflictUtil conflictResolver) {
+
+ String pkg;
+ pkg = DEFAULT_BASE_PKG;
+ pkg = pkg + PERIOD;
+ pkg = pkg + getYangVersion(version);
+ pkg = pkg + PERIOD;
+ pkg = pkg + getPkgFromNameSpace(nameSpace, conflictResolver);
+ pkg = pkg + PERIOD;
+ pkg = pkg + getYangRevisionStr(revision);
+
+ return pkg.toLowerCase();
+ }
+
+ /**
+ * Returns the node package string.
+ *
+ * @param curNode current java node whose package string needs to be set
+ * @return returns the root package string
+ */
+ public static String getCurNodePackage(YangNode curNode) {
+
+ String pkg;
+ if (!(curNode instanceof JavaFileInfoContainer)
+ || curNode.getParent() == null) {
+ throw new TranslatorException("missing parent node to get current node's package");
+ }
+
+ YangNode parentNode = DataModelUtils.getParentNodeInGenCode(curNode);
+ if (!(parentNode instanceof JavaFileInfoContainer)) {
+ throw new TranslatorException("missing parent java node to get current node's package");
+ }
+ JavaFileInfo parentJavaFileHandle = ((JavaFileInfoContainer) parentNode).getJavaFileInfo();
+ pkg = parentJavaFileHandle.getPackage() + PERIOD + parentJavaFileHandle.getJavaName();
+ return pkg.toLowerCase();
+ }
+
+ /**
+ * Returns version.
+ *
+ * @param ver YANG version
+ * @return version
+ */
+ private static String getYangVersion(byte ver) {
+ return VERSION_PREFIX + ver;
+ }
+
+ /**
+ * Returns package name from name space.
+ *
+ * @param nameSpace name space of YANG module
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return java package name as per java rules
+ */
+ private static String getPkgFromNameSpace(String nameSpace, YangToJavaNamingConflictUtil conflictResolver) {
+
+ ArrayList<String> pkgArr = new ArrayList<String>();
+ nameSpace = nameSpace.replace(QUOTES, EMPTY_STRING);
+ String properNameSpace = nameSpace.replaceAll(REGEX_WITH_ALL_SPECIAL_CHAR, COLAN);
+ String[] nameSpaceArr = properNameSpace.split(COLAN);
+
+ for (String nameSpaceString : nameSpaceArr) {
+ pkgArr.add(nameSpaceString);
+ }
+ return getPkgFrmArr(pkgArr, conflictResolver);
+ }
+
+ /**
+ * Returns revision string array.
+ *
+ * @param date YANG module revision
+ * @return revision string
+ * @throws TranslatorException when date is invalid.
+ */
+ private static String getYangRevisionStr(String date) throws TranslatorException {
+
+ String[] revisionArr = date.split(HYPHEN);
+
+ String rev = REVISION_PREFIX;
+ rev = rev + revisionArr[INDEX_ZERO];
+
+ if (Integer.parseInt(revisionArr[INDEX_ONE]) <= MAX_MONTHS
+ && Integer.parseInt(revisionArr[INDEX_TWO]) <= MAX_DAYS) {
+ for (int i = INDEX_ONE; i < revisionArr.length; i++) {
+
+ Integer val = Integer.parseInt(revisionArr[i]);
+ if (val < VALUE_CHECK) {
+ rev = rev + ZERO;
+ }
+ rev = rev + val;
+ }
+
+ return rev;
+ } else {
+ throw new TranslatorException("Date in revision is not proper: " + date);
+ }
+ }
+
+ /**
+ * Returns the package string.
+ *
+ * @param pkgArr package array
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return package string
+ */
+ private static String getPkgFrmArr(ArrayList<String> pkgArr, YangToJavaNamingConflictUtil conflictResolver) {
+
+ String pkg = EMPTY_STRING;
+ int size = pkgArr.size();
+ int i = 0;
+ for (String member : pkgArr) {
+ boolean presenceOfKeyword = JAVA_KEY_WORDS.contains(member.toLowerCase());
+ if (presenceOfKeyword || member.matches(REGEX_FOR_FIRST_DIGIT)) {
+ String prefix = getPrefixForIdentifier(conflictResolver);
+ member = prefix + member;
+ }
+ pkg = pkg + member;
+ if (i != size - 1) {
+ pkg = pkg + PERIOD;
+ }
+ i++;
+ }
+ return pkg;
+ }
+
+ /**
+ * Prefix for adding with identifier and namespace, when it is a java keyword or starting with digits.
+ *
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return prefix which needs to be added
+ */
+ public static String getPrefixForIdentifier(YangToJavaNamingConflictUtil conflictResolver) {
+
+ String prefixForIdentifier = null;
+ if (conflictResolver != null) {
+ prefixForIdentifier = conflictResolver.getPrefixForIdentifier();
+ }
+ if (prefixForIdentifier != null) {
+ prefixForIdentifier = prefixForIdentifier.replaceAll(REGEX_WITH_ALL_SPECIAL_CHAR, COLAN);
+ String[] strArray = prefixForIdentifier.split(COLAN);
+ try {
+ if (strArray[0].isEmpty()) {
+ List<String> stringArrangement = new ArrayList<String>();
+ for (int i = 1; i < strArray.length; i++) {
+ stringArrangement.add(strArray[i]);
+ }
+ strArray = stringArrangement.toArray(new String[stringArrangement.size()]);
+ }
+ prefixForIdentifier = strArray[0];
+ for (int j = 1; j < strArray.length; j++) {
+ prefixForIdentifier = prefixForIdentifier + strArray[j].substring(0, 1).toUpperCase() +
+ strArray[j].substring(1);
+ }
+ } catch (ArrayIndexOutOfBoundsException outOfBoundsException) {
+ throw new TranslatorException("The given prefix in pom.xml is invalid.");
+ }
+ } else {
+ prefixForIdentifier = YANG_AUTO_PREFIX;
+ }
+ return prefixForIdentifier;
+ }
+
+ /**
+ * Returns the YANG identifier name as java identifier.
+ *
+ * @param yangIdentifier identifier in YANG file
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return corresponding java identifier
+ */
+ public static String getCamelCase(String yangIdentifier, YangToJavaNamingConflictUtil conflictResolver) {
+
+ if (conflictResolver != null) {
+ String replacementForHyphen = conflictResolver.getReplacementForHyphen();
+ String replacementForPeriod = conflictResolver.getReplacementForPeriod();
+ String replacementForUnderscore = conflictResolver.getReplacementForUnderscore();
+ if (replacementForPeriod != null) {
+ yangIdentifier = yangIdentifier.replaceAll(REGEX_FOR_PERIOD,
+ PERIOD + replacementForPeriod.toLowerCase() + PERIOD);
+ }
+ if (replacementForUnderscore != null) {
+ yangIdentifier = yangIdentifier.replaceAll(REGEX_FOR_UNDERSCORE,
+ UNDER_SCORE + replacementForUnderscore.toLowerCase() + UNDER_SCORE);
+ }
+ if (replacementForHyphen != null) {
+ yangIdentifier = yangIdentifier.replaceAll(REGEX_FOR_HYPHEN,
+ HYPHEN + replacementForHyphen.toLowerCase() + HYPHEN);
+ }
+ }
+ yangIdentifier = yangIdentifier.replaceAll(REGEX_FOR_IDENTIFIER_SPECIAL_CHAR, COLAN);
+ String[] strArray = yangIdentifier.split(COLAN);
+ if (strArray[0].isEmpty()) {
+ List<String> stringArrangement = new ArrayList<String>();
+ for (int i = 1; i < strArray.length; i++) {
+ stringArrangement.add(strArray[i]);
+ }
+ strArray = stringArrangement.toArray(new String[stringArrangement.size()]);
+ }
+ return upperCaseConflictResolver(strArray, conflictResolver);
+ }
+
+ /**
+ * Resolves the conflict when input has upper case.
+ *
+ * @param stringArray containing strings for upper case conflict resolver
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return camel cased string
+ */
+ private static String upperCaseConflictResolver(String[] stringArray,
+ YangToJavaNamingConflictUtil conflictResolver) {
+
+ for (int l = 0; l < stringArray.length; l++) {
+ String[] upperCaseSplitArray = stringArray[l].split(REGEX_WITH_UPPERCASE);
+ for (int m = 0; m < upperCaseSplitArray.length; m++) {
+ if (upperCaseSplitArray[m].matches(REGEX_WITH_SINGLE_CAPITAL_CASE)) {
+ int check = m;
+ while (check + 1 < upperCaseSplitArray.length) {
+ if (upperCaseSplitArray[check + 1].matches(REGEX_WITH_SINGLE_CAPITAL_CASE)) {
+ upperCaseSplitArray[check + 1] = upperCaseSplitArray[check + 1].toLowerCase();
+ check = check + 1;
+ } else if (upperCaseSplitArray[check + 1]
+ .matches(REGEX_WITH_SINGLE_CAPITAL_CASE_AND_DIGITS_SMALL_CASES)) {
+ upperCaseSplitArray[check + 1] = upperCaseSplitArray[check + 1].toLowerCase();
+ break;
+ } else {
+ break;
+ }
+ }
+ }
+ }
+ StringBuilder strBuilder = new StringBuilder();
+ for (String element : upperCaseSplitArray) {
+ strBuilder.append(element);
+ }
+ stringArray[l] = strBuilder.toString();
+ }
+ List<String> result = new ArrayList<String>();
+ for (String element : stringArray) {
+ String[] capitalCaseSplitArray = element.split(REGEX_WITH_UPPERCASE);
+ for (String letter : capitalCaseSplitArray) {
+ String[] arrayForAddition = letter.split(REGEX_WITH_DIGITS);
+ List<String> list = Arrays.asList(arrayForAddition);
+ for (String str : list) {
+ if (str != null && !str.isEmpty()) {
+ result.add(str);
+ }
+ }
+ }
+ }
+ stringArray = result.toArray(new String[result.size()]);
+ return applyCamelCaseRule(stringArray, conflictResolver);
+ }
+
+ /**
+ * Applies the rule that a string does not end with a capitalized letter and capitalizes
+ * the letter next to a number in an array.
+ *
+ * @param stringArray containing strings for camel case separation
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return camel case rule checked string
+ */
+ private static String applyCamelCaseRule(String[] stringArray, YangToJavaNamingConflictUtil conflictResolver) {
+
+ String ruleChecker = stringArray[0].toLowerCase();
+ int i;
+ if (ruleChecker.matches(REGEX_FOR_FIRST_DIGIT)) {
+ i = 0;
+ ruleChecker = EMPTY_STRING;
+ } else {
+ i = 1;
+ }
+ for (; i < stringArray.length; i++) {
+ if (i + 1 == stringArray.length) {
+ if (stringArray[i].matches(REGEX_FOR_SINGLE_LETTER)
+ || stringArray[i].matches(REGEX_FOR_DIGITS_WITH_SINGLE_LETTER)) {
+ ruleChecker = ruleChecker + stringArray[i].toLowerCase();
+ break;
+ }
+ }
+ if (stringArray[i].matches(REGEX_FOR_FIRST_DIGIT)) {
+ for (int j = 0; j < stringArray[i].length(); j++) {
+ char letterCheck = stringArray[i].charAt(j);
+ if (Character.isLetter(letterCheck)) {
+ stringArray[i] = stringArray[i].substring(0, j)
+ + stringArray[i].substring(j, j + 1).toUpperCase() + stringArray[i].substring(j + 1);
+ break;
+ }
+ }
+ ruleChecker = ruleChecker + stringArray[i];
+ } else {
+ ruleChecker = ruleChecker + stringArray[i].substring(0, 1).toUpperCase() + stringArray[i].substring(1);
+ }
+ }
+ String ruleCheckerWithPrefix = addPrefix(ruleChecker, conflictResolver);
+ return restrictConsecutiveCapitalCase(ruleCheckerWithPrefix);
+ }
+
+ /**
+ * Adds prefix, if the string begins with digit or is a java key word.
+ *
+ * @param camelCasePrefix string for adding prefix
+ * @param conflictResolver object of YANG to java naming conflict util
+ * @return prefixed camel case string
+ */
+ private static String addPrefix(String camelCasePrefix, YangToJavaNamingConflictUtil conflictResolver) {
+
+ String prefix = getPrefixForIdentifier(conflictResolver);
+ if (camelCasePrefix.matches(REGEX_FOR_FIRST_DIGIT)) {
+ camelCasePrefix = prefix + camelCasePrefix;
+ }
+ if (JAVA_KEY_WORDS.contains(camelCasePrefix)) {
+ camelCasePrefix = prefix + camelCasePrefix.substring(0, 1).toUpperCase()
+ + camelCasePrefix.substring(1);
+ }
+ return camelCasePrefix;
+ }
+
+ /**
+ * Restricts consecutive capital cased string as a rule in camel case.
+ *
+ * @param consecCapitalCaseRemover which requires the restriction of consecutive capital case
+ * @return string without consecutive capital case
+ */
+ private static String restrictConsecutiveCapitalCase(String consecCapitalCaseRemover) {
+
+ for (int k = 0; k < consecCapitalCaseRemover.length(); k++) {
+ if (k + 1 < consecCapitalCaseRemover.length()) {
+ if (Character.isUpperCase(consecCapitalCaseRemover.charAt(k))) {
+ if (Character.isUpperCase(consecCapitalCaseRemover.charAt(k + 1))) {
+ consecCapitalCaseRemover = consecCapitalCaseRemover.substring(0, k + 1)
+ + consecCapitalCaseRemover.substring(k + 1, k + 2).toLowerCase()
+ + consecCapitalCaseRemover.substring(k + 2);
+ }
+ }
+ }
+ }
+ return consecCapitalCaseRemover;
+ }
+
+ /**
+ * Returns the YANG identifier name as java identifier with first letter
+ * in capital.
+ *
+ * @param yangIdentifier identifier in YANG file
+ * @return corresponding java identifier
+ */
+ public static String getCapitalCase(String yangIdentifier) {
+ yangIdentifier = yangIdentifier.substring(0, 1).toUpperCase() + yangIdentifier.substring(1);
+ return restrictConsecutiveCapitalCase(yangIdentifier);
+ }
+
+ /**
+ * Returns the YANG identifier name as java identifier with first letter
+ * in small.
+ *
+ * @param yangIdentifier identifier in YANG file.
+ * @return corresponding java identifier
+ */
+ public static String getSmallCase(String yangIdentifier) {
+ return yangIdentifier.substring(0, 1).toLowerCase() + yangIdentifier.substring(1);
+ }
+
+ /**
+ * Returns the java Package from package path.
+ *
+ * @param packagePath package path
+ * @return java package
+ */
+ public static String getJavaPackageFromPackagePath(String packagePath) {
+ return packagePath.replace(SLASH, PERIOD);
+ }
+
+ /**
+ * Returns enum's java name.
+ *
+ * @param name enum's name
+ * @return enum's java name
+ */
+ public static String getEnumJavaAttribute(String name) {
+
+ name = name.replaceAll(REGEX_WITH_ALL_SPECIAL_CHAR, COLAN);
+ String[] strArray = name.split(COLAN);
+ String output = EMPTY_STRING;
+ if (strArray[0].isEmpty()) {
+ List<String> stringArrangement = new ArrayList<String>();
+ for (int i = 1; i < strArray.length; i++) {
+ stringArrangement.add(strArray[i]);
+ }
+ strArray = stringArrangement.toArray(new String[stringArrangement.size()]);
+ }
+ for (int i = 0; i < strArray.length; i++) {
+ if (i > 0 && i < strArray.length) {
+ output = output + UNDER_SCORE;
+ }
+ output = output + strArray[i];
+ }
+ return output;
+ }
+
+ /**
+ * Returns the directory path corresponding to java package.
+ *
+ * @param packagePath package path
+ * @return java package
+ */
+ public static String getPackageDirPathFromJavaJPackage(String packagePath) {
+ return packagePath.replace(PERIOD, SLASH);
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/MethodsGenerator.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/MethodsGenerator.java
new file mode 100644
index 0000000..b6889c8
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/MethodsGenerator.java
@@ -0,0 +1,1086 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import java.util.List;
+import java.util.Map;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNodeIdentifier;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaAttributeInfo;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaAugment;
+import org.onosproject.yangutils.utils.io.impl.JavaDocGen;
+
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getParseFromStringMethod;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getSmallCase;
+import static org.onosproject.yangutils.utils.UtilConstants.ACTIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.ACTIVATE_ANNOTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.ADD_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.AND;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTABLE;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTED_INFO;
+import static org.onosproject.yangutils.utils.UtilConstants.BOOLEAN_DATA_TYPE;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILD;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER;
+import static org.onosproject.yangutils.utils.UtilConstants.BYTE;
+import static org.onosproject.yangutils.utils.UtilConstants.CASE;
+import static org.onosproject.yangutils.utils.UtilConstants.CATCH;
+import static org.onosproject.yangutils.utils.UtilConstants.CHECK_NOT_NULL_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.CLEAR;
+import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_CURLY_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
+import static org.onosproject.yangutils.utils.UtilConstants.DEACTIVATE;
+import static org.onosproject.yangutils.utils.UtilConstants.DEACTIVATE_ANNOTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.DEFAULT;
+import static org.onosproject.yangutils.utils.UtilConstants.DIAMOND_CLOSE_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.DIAMOND_OPEN_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.EIGHT_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EQUAL;
+import static org.onosproject.yangutils.utils.UtilConstants.EQUALS_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.EXCEPTION;
+import static org.onosproject.yangutils.utils.UtilConstants.EXCEPTION_VAR;
+import static org.onosproject.yangutils.utils.UtilConstants.FALSE;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.FROM_STRING_METHOD_NAME;
+import static org.onosproject.yangutils.utils.UtilConstants.FROM_STRING_PARAM_NAME;
+import static org.onosproject.yangutils.utils.UtilConstants.GET_METHOD_PREFIX;
+import static org.onosproject.yangutils.utils.UtilConstants.GOOGLE_MORE_OBJECT_METHOD_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.HASH;
+import static org.onosproject.yangutils.utils.UtilConstants.HASH_CODE_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.IF;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPL;
+import static org.onosproject.yangutils.utils.UtilConstants.INSTANCE_OF;
+import static org.onosproject.yangutils.utils.UtilConstants.INT;
+import static org.onosproject.yangutils.utils.UtilConstants.LIST;
+import static org.onosproject.yangutils.utils.UtilConstants.LONG;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.NULL;
+import static org.onosproject.yangutils.utils.UtilConstants.OBJ;
+import static org.onosproject.yangutils.utils.UtilConstants.OBJECT;
+import static org.onosproject.yangutils.utils.UtilConstants.OBJECT_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.OF;
+import static org.onosproject.yangutils.utils.UtilConstants.OMIT_NULL_VALUE_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_CURLY_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.OTHER;
+import static org.onosproject.yangutils.utils.UtilConstants.OVERRIDE;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.PUBLIC;
+import static org.onosproject.yangutils.utils.UtilConstants.QUOTES;
+import static org.onosproject.yangutils.utils.UtilConstants.RETURN;
+import static org.onosproject.yangutils.utils.UtilConstants.RPC_INPUT_VAR_NAME;
+import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.SET_METHOD_PREFIX;
+import static org.onosproject.yangutils.utils.UtilConstants.SHORT;
+import static org.onosproject.yangutils.utils.UtilConstants.SIXTEEN_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.UtilConstants.STARTED_LOG_INFO;
+import static org.onosproject.yangutils.utils.UtilConstants.STATIC;
+import static org.onosproject.yangutils.utils.UtilConstants.STOPPED_LOG_INFO;
+import static org.onosproject.yangutils.utils.UtilConstants.STRING_DATA_TYPE;
+import static org.onosproject.yangutils.utils.UtilConstants.SUFFIX_S;
+import static org.onosproject.yangutils.utils.UtilConstants.SWITCH;
+import static org.onosproject.yangutils.utils.UtilConstants.THIS;
+import static org.onosproject.yangutils.utils.UtilConstants.TMP_VAL;
+import static org.onosproject.yangutils.utils.UtilConstants.TO;
+import static org.onosproject.yangutils.utils.UtilConstants.TRUE;
+import static org.onosproject.yangutils.utils.UtilConstants.TRY;
+import static org.onosproject.yangutils.utils.UtilConstants.TWELVE_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.VALUE;
+import static org.onosproject.yangutils.utils.UtilConstants.VOID;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_UTILS_TODO;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.BUILD_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.CONSTRUCTOR;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.DEFAULT_CONSTRUCTOR;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.FROM_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.GETTER_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.MANAGER_SETTER_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.OF_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.SETTER_METHOD;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.TYPE_CONSTRUCTOR;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.trimAtLast;
+
+/**
+ * Represents generator for methods of generated files based on the file type.
+ */
+public final class MethodsGenerator {
+
+ /**
+ * Creates an instance of method generator.
+ */
+ private MethodsGenerator() {
+ }
+
+ /**
+ * Returns the methods strings for builder interface.
+ *
+ * @param name attribute name
+ * @param pluginConfig plugin configurations
+ * @return method string for builder interface
+ */
+ public static String parseBuilderInterfaceBuildMethodString(String name, YangPluginConfig pluginConfig) {
+ return getJavaDoc(BUILD_METHOD, name, false, pluginConfig) + getBuildForInterface(name);
+ }
+
+ /**
+ * Returns getter string.
+ *
+ * @param attr attribute info
+ * @param generatedJavaFiles generated java files
+ * @param pluginConfig plugin configurations
+ * @return getter string
+ */
+ public static String getGetterString(JavaAttributeInfo attr, int generatedJavaFiles,
+ YangPluginConfig pluginConfig) {
+
+ String returnType = getReturnType(attr);
+ String attributeName = attr.getAttributeName();
+
+ return getJavaDoc(GETTER_METHOD, attributeName, attr.isListAttr(), pluginConfig)
+ + getGetterForInterface(attributeName, returnType, attr.isListAttr(), generatedJavaFiles);
+ }
+
+ /**
+ * Returns setter string.
+ *
+ * @param attr attribute info
+ * @param className java class name
+ * @param generatedJavaFiles generated java files
+ * @param pluginConfig plugin configurations
+ * @return setter string
+ */
+ public static String getSetterString(JavaAttributeInfo attr, String className, int generatedJavaFiles,
+ YangPluginConfig pluginConfig) {
+
+ String attrType = getReturnType(attr);
+ String attributeName = attr.getAttributeName();
+ JavaDocGen.JavaDocType type;
+ if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ type = MANAGER_SETTER_METHOD;
+ } else {
+ type = SETTER_METHOD;
+ }
+
+ return getJavaDoc(type, attributeName, attr.isListAttr(), pluginConfig)
+ + getSetterForInterface(attributeName, attrType, className, attr.isListAttr(), generatedJavaFiles);
+ }
+
+ /**
+ * Returns constructor method string.
+ *
+ * @param name class name
+ * @param pluginConfig plugin configurations
+ * @return constructor string
+ */
+ public static String getConstructorString(String name, YangPluginConfig pluginConfig) {
+ return getJavaDoc(CONSTRUCTOR, name, false, pluginConfig);
+ }
+
+ /**
+ * Returns default constructor method string.
+ *
+ * @param name class name
+ * @param modifierType modifier type
+ * @param pluginConfig plugin configurations
+ * @return default constructor string
+ */
+ public static String getDefaultConstructorString(String name, String modifierType,
+ YangPluginConfig pluginConfig) {
+ return getJavaDoc(DEFAULT_CONSTRUCTOR, name, false, pluginConfig)
+ + getDefaultConstructor(name, modifierType)
+ + NEW_LINE;
+ }
+
+ /**
+ * Returns check not null string.
+ *
+ * @param name attribute name
+ * @return check not null string
+ */
+ public static String getCheckNotNull(String name) {
+ return EIGHT_SPACE_INDENTATION + CHECK_NOT_NULL_STRING + OPEN_PARENTHESIS + name + COMMA + SPACE + name
+ + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE;
+ }
+
+ /**
+ * Returns build method string.
+ *
+ * @param name class name
+ * @return build string
+ */
+ public static String getBuildString(String name) {
+ return FOUR_SPACE_INDENTATION + OVERRIDE + NEW_LINE + getBuild(name);
+ }
+
+ /**
+ * Returns the getter method strings for class file.
+ *
+ * @param attr attribute info
+ * @param generatedJavaFiles for the type of java file being generated
+ * @return getter method for class
+ */
+ public static String getGetterForClass(JavaAttributeInfo attr, int generatedJavaFiles) {
+
+ String attrQuaifiedType = getReturnType(attr);
+ String attributeName = attr.getAttributeName();
+
+ if (!attr.isListAttr()) {
+ return getGetter(attrQuaifiedType, attributeName, generatedJavaFiles);
+ }
+ String listAttr = getListString() + attrQuaifiedType + DIAMOND_CLOSE_BRACKET;
+ return getGetter(listAttr, attributeName, generatedJavaFiles);
+ }
+
+ /**
+ * Returns getter for attribute.
+ *
+ * @param type return type
+ * @param name attribute name
+ * @param generatedJavaFiles generated java files
+ * @return getter for attribute
+ */
+ public static String getGetter(String type, String name, int generatedJavaFiles) {
+ String ret = parseTypeForReturnValue(type);
+ if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + type + SPACE + GET_METHOD_PREFIX + getCapitalCase(name)
+ + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE +
+ EIGHT_SPACE_INDENTATION + YANG_UTILS_TODO + NEW_LINE + EIGHT_SPACE_INDENTATION +
+ RETURN + SPACE + ret + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ } else {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + type + SPACE + name
+ + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE +
+ EIGHT_SPACE_INDENTATION + RETURN + SPACE + name + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION
+ + CLOSE_CURLY_BRACKET;
+ }
+
+ }
+
+ /*Provides string to return for type.*/
+ private static String parseTypeForReturnValue(String type) {
+ switch (type) {
+ case BYTE:
+ case INT:
+ case SHORT:
+ case LONG:
+ return "0";
+ case BOOLEAN_DATA_TYPE:
+ return FALSE;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Returns the setter method strings for class file.
+ *
+ * @param attr attribute info
+ * @param className name of the class
+ * @param generatedJavaFiles generated java files
+ * @return setter method for class
+ */
+ public static String getSetterForClass(JavaAttributeInfo attr, String className, int generatedJavaFiles) {
+
+ String attrQuaifiedType = getReturnType(attr);
+ String attributeName = attr.getAttributeName();
+ if (!attr.isListAttr()) {
+ return getSetter(className, attributeName, attrQuaifiedType, generatedJavaFiles);
+ }
+ String listAttr = getListString() + attrQuaifiedType + DIAMOND_CLOSE_BRACKET;
+ return getSetter(className, attributeName, listAttr, generatedJavaFiles);
+ }
+
+ /**
+ * Returns setter for attribute.
+ *
+ * @param className class name
+ * @param name attribute name
+ * @param type return type
+ * @return setter for attribute
+ */
+ private static String getSetter(String className, String name, String type, int generatedJavaFiles) {
+ if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + VOID + SPACE + SET_METHOD_PREFIX
+ + getCapitalCase(name) + OPEN_PARENTHESIS + type + SPACE + name + CLOSE_PARENTHESIS + SPACE +
+ OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + YANG_UTILS_TODO +
+ NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ } else if (generatedJavaFiles == GENERATE_EVENT_SUBJECT_CLASS) {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + VOID + SPACE + name + OPEN_PARENTHESIS + type + SPACE
+ + name + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + THIS + PERIOD + name + SPACE + EQUAL + SPACE + name + SEMI_COLAN + NEW_LINE
+ + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ } else {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + className + BUILDER + SPACE +
+ name + OPEN_PARENTHESIS + type + SPACE + name + CLOSE_PARENTHESIS + SPACE
+ + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + THIS + PERIOD + name + SPACE
+ + EQUAL + SPACE + name + SEMI_COLAN + NEW_LINE + EIGHT_SPACE_INDENTATION + RETURN + SPACE
+ + THIS + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ }
+ }
+
+ /**
+ * Returns the setter method strings for class file.
+ *
+ * @param attr attribute info
+ * @return setter method for class
+ */
+ public static String getSetterForTypeDefClass(JavaAttributeInfo attr) {
+
+ String attrQuaifiedType = getReturnType(attr);
+ String attributeName = attr.getAttributeName();
+ return getTypeDefSetter(attrQuaifiedType, attributeName);
+ }
+
+ /**
+ * Returns type def's setter for attribute.
+ *
+ * @param type data type
+ * @param name attribute name
+ * @return setter for type def's attribute
+ */
+ private static String getTypeDefSetter(String type, String name) {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + VOID + SPACE + SET_METHOD_PREFIX + getCapitalCase(name)
+ + OPEN_PARENTHESIS + type + SPACE + VALUE + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + THIS + PERIOD + name + SPACE + EQUAL + SPACE + VALUE + SEMI_COLAN + NEW_LINE
+ + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns override string.
+ *
+ * @return override string
+ */
+ public static String getOverRideString() {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + OVERRIDE + NEW_LINE;
+ }
+
+ /**
+ * Returns the getter method strings for interface file.
+ *
+ * @param yangName name of the attribute
+ * @param returnType return type of attribute
+ * @param isList is list attribute
+ * @param generatedJavaFiles generated java files
+ * @return getter method for interface
+ */
+ public static String getGetterForInterface(String yangName, String returnType, boolean isList,
+ int generatedJavaFiles) {
+
+ if (!isList) {
+ return getGetterInterfaceString(returnType, yangName, generatedJavaFiles);
+ }
+ String listAttr = getListString() + returnType + DIAMOND_CLOSE_BRACKET;
+ return getGetterInterfaceString(listAttr, yangName, generatedJavaFiles);
+ }
+
+ /**
+ * Returns getter for attribute in interface.
+ *
+ * @param returnType return type
+ * @param yangName attribute name
+ * @return getter for interface
+ */
+ private static String getGetterInterfaceString(String returnType, String yangName,
+ int generatedJavaFiles) {
+ if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ return FOUR_SPACE_INDENTATION + returnType + SPACE + GET_METHOD_PREFIX + getCapitalCase(yangName)
+ + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN;
+ } else {
+ return FOUR_SPACE_INDENTATION + returnType + SPACE + yangName
+ + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN;
+ }
+ }
+
+ /**
+ * Returns the setter method strings for interface file.
+ *
+ * @param attrName name of the attribute
+ * @param attrType return type of attribute
+ * @param className name of the java class being generated
+ * @param isList is list attribute
+ * @param generatedJavaFiles generated java files
+ * @return setter method for interface
+ */
+ public static String getSetterForInterface(String attrName, String attrType, String className,
+ boolean isList, int generatedJavaFiles) {
+
+ if (!isList) {
+ return getSetterInterfaceString(className, attrName, attrType, generatedJavaFiles);
+ }
+ String listAttr = getListString() + attrType + DIAMOND_CLOSE_BRACKET;
+ return getSetterInterfaceString(className, attrName, listAttr, generatedJavaFiles);
+ }
+
+ /**
+ * Returns setter string for interface.
+ *
+ * @param className class name
+ * @param attrName attribute name
+ * @param attrType attribute type
+ * @return setter string
+ */
+ private static String getSetterInterfaceString(String className, String attrName, String attrType,
+ int generatedJavaFiles) {
+ if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
+
+ return FOUR_SPACE_INDENTATION + VOID + SPACE + SET_METHOD_PREFIX + getCapitalCase(attrName)
+ + OPEN_PARENTHESIS + attrType + SPACE + attrName + CLOSE_PARENTHESIS + SEMI_COLAN;
+ } else {
+ return FOUR_SPACE_INDENTATION + className + BUILDER + SPACE + attrName
+ + OPEN_PARENTHESIS + attrType + SPACE + attrName + CLOSE_PARENTHESIS + SEMI_COLAN;
+ }
+ }
+
+ /**
+ * Returns list string.
+ *
+ * @return list string
+ */
+ private static String getListString() {
+ return LIST + DIAMOND_OPEN_BRACKET;
+ }
+
+ /**
+ * Returns return type for attribute.
+ *
+ * @param attr attribute info
+ * @return return type
+ */
+ private static String getReturnType(JavaAttributeInfo attr) {
+
+ String returnType = EMPTY_STRING;
+ if (attr.isQualifiedName() && attr.getImportInfo().getPkgInfo() != null) {
+ returnType = attr.getImportInfo().getPkgInfo() + PERIOD;
+ }
+ returnType = returnType + attr.getImportInfo().getClassInfo();
+ return returnType;
+ }
+
+ /**
+ * Returns the build method strings for interface file.
+ *
+ * @param yangName name of the interface
+ * @return build method for interface
+ */
+ public static String getBuildForInterface(String yangName) {
+ return FOUR_SPACE_INDENTATION + yangName + SPACE + BUILD + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN
+ + NEW_LINE;
+ }
+
+ /**
+ * Returns constructor string for impl class.
+ *
+ * @param yangName class name
+ * @param pluginConfig plugin configurations
+ * @return constructor string
+ */
+ public static String getConstructorStart(String yangName, YangPluginConfig pluginConfig) {
+
+ String javadoc = getConstructorString(yangName, pluginConfig);
+ String constructor =
+ FOUR_SPACE_INDENTATION + PUBLIC + SPACE + yangName + IMPL + OPEN_PARENTHESIS + yangName
+ + BUILDER + SPACE + BUILDER.toLowerCase() + OBJECT + CLOSE_PARENTHESIS + SPACE
+ + OPEN_CURLY_BRACKET
+ + NEW_LINE;
+ return javadoc + constructor;
+ }
+
+ /**
+ * Returns the constructor strings for class file.
+ *
+ * @param yangName name of the class
+ * @param attr attribute info
+ * @param generatedJavaFiles generated java files
+ * @param pluginConfig plugin configurations
+ * @return constructor for class
+ */
+ public static String getConstructor(String yangName, JavaAttributeInfo attr, int generatedJavaFiles,
+ YangPluginConfig pluginConfig) {
+
+ String attributeName = attr.getAttributeName();
+ String constructor;
+
+ if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
+ constructor =
+ EIGHT_SPACE_INDENTATION + THIS + PERIOD
+ + getCamelCase(attributeName, pluginConfig.getConflictResolver()) + SPACE + EQUAL
+ + SPACE + BUILDER.toLowerCase() + OBJECT + PERIOD + GET_METHOD_PREFIX
+ + getCapitalCase(getCamelCase(attributeName, pluginConfig.getConflictResolver()))
+ + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE;
+ } else {
+ constructor =
+ EIGHT_SPACE_INDENTATION + THIS + PERIOD
+ + getCamelCase(attributeName, pluginConfig.getConflictResolver()) + SPACE + EQUAL
+ + SPACE + BUILDER.toLowerCase() + OBJECT + PERIOD
+ + getCamelCase(attributeName, pluginConfig.getConflictResolver()) +
+ OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE;
+ }
+ return constructor;
+ }
+
+ /**
+ * Returns the rpc strings for service interface.
+ *
+ * @param rpcName name of the rpc
+ * @param inputName name of input
+ * @param outputName name of output
+ * @param pluginConfig plugin configurations
+ * @return rpc method string
+ */
+ public static String getRpcServiceMethod(String rpcName, String inputName, String outputName,
+ YangPluginConfig pluginConfig) {
+
+ rpcName = getCamelCase(rpcName, pluginConfig.getConflictResolver());
+ if (!inputName.equals(EMPTY_STRING)) {
+ inputName = inputName + SPACE + RPC_INPUT_VAR_NAME;
+ }
+ return FOUR_SPACE_INDENTATION + outputName + SPACE + rpcName + OPEN_PARENTHESIS + inputName
+ + CLOSE_PARENTHESIS + SEMI_COLAN;
+ }
+
+ /**
+ * Returns the rpc strings for manager impl.
+ *
+ * @param rpcName name of the rpc
+ * @param inputName name of input
+ * @param outputName name of output
+ * @param pluginConfig plugin configurations
+ * @return rpc method string
+ */
+ public static String getRpcManagerMethod(String rpcName, String inputName, String outputName,
+ YangPluginConfig pluginConfig) {
+
+ rpcName = getCamelCase(rpcName, pluginConfig.getConflictResolver());
+ if (!inputName.equals(EMPTY_STRING)) {
+ inputName = inputName + SPACE + RPC_INPUT_VAR_NAME;
+ }
+
+ String method =
+ getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + outputName + SPACE + rpcName
+ + OPEN_PARENTHESIS + inputName + CLOSE_PARENTHESIS + SPACE
+ + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + YANG_UTILS_TODO + NEW_LINE;
+ if (!outputName.contentEquals(VOID)) {
+ method += EIGHT_SPACE_INDENTATION + RETURN + SPACE + parseTypeForReturnValue(outputName) + SEMI_COLAN
+ + NEW_LINE;
+ }
+ method += FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+
+ return method;
+ }
+
+ /**
+ * Returns the build method strings for class file.
+ *
+ * @param yangName class name
+ * @return build method string for class
+ */
+ public static String getBuild(String yangName) {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + yangName + SPACE + BUILD + OPEN_PARENTHESIS + CLOSE_PARENTHESIS
+ + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + RETURN + SPACE + NEW + SPACE
+ + yangName + IMPL + OPEN_PARENTHESIS + THIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE
+ + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns the Default constructor strings for class file.
+ *
+ * @param name name of the class
+ * @param modifierType modifier type for default constructor
+ * @return Default constructor for class
+ */
+ private static String getDefaultConstructor(String name, String modifierType) {
+ return FOUR_SPACE_INDENTATION + modifierType + SPACE + name + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SPACE
+ + OPEN_CURLY_BRACKET + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns to string method's open strings.
+ *
+ * @return string method's open string
+ */
+ public static String getToStringMethodOpen() {
+ return getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + STRING_DATA_TYPE + SPACE + TO
+ + STRING_DATA_TYPE + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + RETURN + GOOGLE_MORE_OBJECT_METHOD_STRING + NEW_LINE;
+ }
+
+ /**
+ * Returns omit null value string.
+ *
+ * @return omit null value string
+ */
+ public static String getOmitNullValueString() {
+ return TWELVE_SPACE_INDENTATION + PERIOD + OMIT_NULL_VALUE_STRING + NEW_LINE;
+ }
+
+ /**
+ * Returns to string method's close string.
+ *
+ * @return to string method close string
+ */
+ public static String getToStringMethodClose() {
+ return TWELVE_SPACE_INDENTATION + PERIOD + TO + STRING_DATA_TYPE + OPEN_PARENTHESIS + CLOSE_PARENTHESIS
+ + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns to string method for class.
+ *
+ * @param attr attribute info
+ * @return to string method
+ */
+ public static String getToStringMethod(JavaAttributeInfo attr) {
+
+ String attributeName = attr.getAttributeName();
+ return TWELVE_SPACE_INDENTATION + PERIOD + ADD_STRING + OPEN_PARENTHESIS + QUOTES + attributeName + QUOTES
+ + COMMA + SPACE + attributeName + CLOSE_PARENTHESIS;
+ }
+
+ /**
+ * Returns from string method's open string.
+ *
+ * @param className name of the class
+ * @param pluginConfig plugin configurations
+ * @return from string method's open string
+ */
+ public static String getFromStringMethodSignature(String className, YangPluginConfig pluginConfig) {
+ return getJavaDoc(FROM_METHOD, className, false, pluginConfig) + FOUR_SPACE_INDENTATION + PUBLIC + SPACE
+ + STATIC + SPACE + className + SPACE + FROM_STRING_METHOD_NAME + OPEN_PARENTHESIS
+ + STRING_DATA_TYPE + SPACE + FROM_STRING_PARAM_NAME + CLOSE_PARENTHESIS + SPACE
+ + OPEN_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Return from string method's close string.
+ *
+ * @return from string method's close string
+ */
+ public static String getFromStringMethodClose() {
+ return EIGHT_SPACE_INDENTATION + RETURN + SPACE + NULL + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION +
+ CLOSE_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Return from string method's body string.
+ *
+ * @param attr attribute info
+ * @param fromStringAttributeInfo attribute info for the from string
+ * wrapper type
+ * @return from string method's body string
+ */
+ public static String getFromStringMethod(JavaAttributeInfo attr,
+ JavaAttributeInfo fromStringAttributeInfo) {
+
+ return EIGHT_SPACE_INDENTATION + getTrySubString() + NEW_LINE + TWELVE_SPACE_INDENTATION
+ + getParsedSubString(attr, fromStringAttributeInfo) + SEMI_COLAN + NEW_LINE + TWELVE_SPACE_INDENTATION
+ + getReturnOfSubString() + NEW_LINE + EIGHT_SPACE_INDENTATION + getCatchSubString()
+ + NEW_LINE + EIGHT_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns sub string with try statement for union's from string method.
+ *
+ * @return sub string with try statement for union's from string method
+ */
+ public static String getTrySubString() {
+ return TRY + SPACE + OPEN_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns sub string with return statement for union's from string method.
+ *
+ * @return sub string with return statement for union's from string method
+ */
+ public static String getReturnOfSubString() {
+ return RETURN + SPACE + OF + OPEN_PARENTHESIS + TMP_VAL + CLOSE_PARENTHESIS + SEMI_COLAN;
+ }
+
+ /**
+ * Returns sub string with catch statement for union's from string method.
+ *
+ * @return sub string with catch statement for union's from string method
+ */
+ public static String getCatchSubString() {
+ return CLOSE_CURLY_BRACKET + SPACE + CATCH + SPACE + OPEN_PARENTHESIS + EXCEPTION + SPACE + EXCEPTION_VAR
+ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns sub string with parsed statement for union's from string method.
+ *
+ * @param attr attribute info
+ * @return sub string with parsed statement for union's from string method
+ */
+ private static String getParsedSubString(JavaAttributeInfo attr,
+ JavaAttributeInfo fromStringAttributeInfo) {
+
+ String targetDataType = getReturnType(attr);
+ String parseFromStringMethod = getParseFromStringMethod(targetDataType,
+ fromStringAttributeInfo.getAttributeType());
+ return targetDataType + SPACE + TMP_VAL + SPACE + EQUAL + SPACE + parseFromStringMethod
+ + OPEN_PARENTHESIS + FROM_STRING_PARAM_NAME + CLOSE_PARENTHESIS;
+ }
+
+ /**
+ * Returns hash code method open strings.
+ *
+ * @return hash code method open string
+ */
+ public static String getHashCodeMethodOpen() {
+ return getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + INT + SPACE + HASH_CODE_STRING
+ + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + RETURN + SPACE + OBJECT_STRING + SUFFIX_S + PERIOD + HASH + OPEN_PARENTHESIS;
+ }
+
+ /**
+ * Returns hash code methods close string.
+ *
+ * @param hashcodeString hash code string
+ * @return to hash code method close string
+ */
+ public static String getHashCodeMethodClose(String hashcodeString) {
+ hashcodeString = trimAtLast(hashcodeString, COMMA);
+ hashcodeString = trimAtLast(hashcodeString, SPACE);
+ return hashcodeString + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET
+ + NEW_LINE;
+ }
+
+ /**
+ * Returns hash code method for class.
+ *
+ * @param attr attribute info
+ * @return hash code method
+ */
+ public static String getHashCodeMethod(JavaAttributeInfo attr) {
+ return attr.getAttributeName() + COMMA + SPACE;
+ }
+
+ /**
+ * Returns equals method open strings.
+ *
+ * @param className class name
+ * @return equals method open string
+ */
+ public static String getEqualsMethodOpen(String className) {
+ return getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + BOOLEAN_DATA_TYPE + SPACE + EQUALS_STRING
+ + OPEN_PARENTHESIS + OBJECT_STRING + SPACE + OBJ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET
+ + NEW_LINE + getEqualsMethodsCommonIfCondition() + getEqualsMethodsSpecificIfCondition(className);
+ }
+
+ /**
+ * Returns equal methods if condition string.
+ *
+ * @return if condition string
+ */
+ private static String getEqualsMethodsCommonIfCondition() {
+ return EIGHT_SPACE_INDENTATION + IF + SPACE + OPEN_PARENTHESIS + THIS + SPACE + EQUAL + EQUAL + SPACE + OBJ
+ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + TWELVE_SPACE_INDENTATION + RETURN + SPACE
+ + TRUE + SEMI_COLAN + NEW_LINE + EIGHT_SPACE_INDENTATION + CLOSE_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns if condition for specific class object in equals method.
+ *
+ * @param className class name
+ * @return if condition string
+ */
+ private static String getEqualsMethodsSpecificIfCondition(String className) {
+ return EIGHT_SPACE_INDENTATION + IF + SPACE + OPEN_PARENTHESIS + OBJ + INSTANCE_OF + className
+ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + TWELVE_SPACE_INDENTATION + className
+ + SPACE + OTHER + SPACE + EQUAL + SPACE + OPEN_PARENTHESIS + className + CLOSE_PARENTHESIS + SPACE
+ + OBJ + SEMI_COLAN + NEW_LINE + TWELVE_SPACE_INDENTATION + RETURN + NEW_LINE;
+ }
+
+ /**
+ * Returns equals methods close string.
+ *
+ * @param equalMethodString equal method string
+ * @return equals method close string
+ */
+ public static String getEqualsMethodClose(String equalMethodString) {
+ equalMethodString = trimAtLast(equalMethodString, AND);
+ equalMethodString = trimAtLast(equalMethodString, AND);
+ equalMethodString = trimAtLast(equalMethodString, SPACE);
+ equalMethodString = trimAtLast(equalMethodString, NEW_LINE) + SEMI_COLAN + NEW_LINE;
+ return equalMethodString + EIGHT_SPACE_INDENTATION + CLOSE_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + RETURN + SPACE + FALSE + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET
+ + NEW_LINE;
+ }
+
+ /**
+ * Returns equals method for class.
+ *
+ * @param attr attribute info
+ * @return equals method
+ */
+ public static String getEqualsMethod(JavaAttributeInfo attr) {
+
+ String attributeName = attr.getAttributeName();
+ return SIXTEEN_SPACE_INDENTATION + SPACE + OBJECT_STRING + SUFFIX_S + PERIOD + EQUALS_STRING + OPEN_PARENTHESIS
+ + attributeName + COMMA + SPACE + OTHER + PERIOD + attributeName + CLOSE_PARENTHESIS + SPACE + AND
+ + AND;
+ }
+
+ /**
+ * Returns of method string for class.
+ *
+ * @param name class name
+ * @param attr attribute info
+ * @return of method string
+ */
+ public static String getOfMethod(String name, JavaAttributeInfo attr) {
+
+ String attrQualifiedType = getReturnType(attr);
+
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + STATIC + SPACE + name + SPACE + OF + OPEN_PARENTHESIS
+ + attrQualifiedType + SPACE + VALUE + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + RETURN + SPACE + NEW + SPACE + name + OPEN_PARENTHESIS + VALUE
+ + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns of method's string and java doc for special type.
+ *
+ * @param attr attribute info
+ * @param generatedJavaClassName class name
+ * @param pluginConfig plugin configurations
+ * @return of method's string and java doc for special type
+ */
+ public static String getOfMethodStringAndJavaDoc(JavaAttributeInfo attr, String generatedJavaClassName,
+ YangPluginConfig pluginConfig) {
+
+ String attrType = getReturnType(attr);
+ String attrName = attr.getAttributeName();
+
+ return getJavaDoc(OF_METHOD, generatedJavaClassName + " for type " + attrName, false, pluginConfig)
+ + getOfMethodString(attrType, generatedJavaClassName);
+ }
+
+ /**
+ * Returns of method's string.
+ *
+ * @param type data type
+ * @param className class name
+ * @return of method's string
+ */
+ private static String getOfMethodString(String type, String className) {
+
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + STATIC + SPACE + className + SPACE + OF + OPEN_PARENTHESIS
+ + type + SPACE + VALUE + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + RETURN + SPACE + NEW + SPACE + className + OPEN_PARENTHESIS + VALUE
+ + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns string and java doc for constructor of type class.
+ *
+ * @param attr attribute info
+ * @param generatedJavaClassName class name
+ * @param pluginConfig plugin configurations
+ * @return string and java doc for constructor of type class
+ */
+ public static String getTypeConstructorStringAndJavaDoc(JavaAttributeInfo attr,
+ String generatedJavaClassName, YangPluginConfig pluginConfig) {
+
+ String attrType = getReturnType(attr);
+ String attrName = attr.getAttributeName();
+
+ return getJavaDoc(TYPE_CONSTRUCTOR, generatedJavaClassName + " for type " + attrName, false, pluginConfig)
+ + getTypeConstructorString(attrType, attrName, generatedJavaClassName);
+ }
+
+ /**
+ * Returns type constructor string.
+ *
+ * @param type data type
+ * @param name attribute name
+ * @param className class name
+ * @return type constructor string
+ */
+ private static String getTypeConstructorString(String type, String name, String className) {
+
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + className + OPEN_PARENTHESIS + type + SPACE + VALUE
+ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + THIS + PERIOD
+ + name + SPACE + EQUAL + SPACE + VALUE + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION
+ + CLOSE_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns implementation of add augmentation method of AugmentationHolder class.
+ *
+ * @return implementation of add augmentation method of AugmentationHolder class
+ */
+ public static String getAddAugmentInfoMethodImpl() {
+ String method = FOUR_SPACE_INDENTATION;
+ method = method + getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + VOID + SPACE + ADD_STRING
+ + AUGMENTATION + OPEN_PARENTHESIS + AUGMENTED_INFO + SPACE + VALUE + CLOSE_PARENTHESIS + SPACE
+ + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + GET_METHOD_PREFIX + AUGMENTED_INFO + LIST
+ + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + PERIOD + ADD_STRING + OPEN_PARENTHESIS + VALUE
+ + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+
+ return method;
+ }
+
+ /**
+ * Returns implementation of get augment info list method of AugmentationHolder class.
+ *
+ * @return implementation of get augment info list method of AugmentationHolder class
+ */
+ public static String getAugmentInfoListImpl() {
+
+ String method = FOUR_SPACE_INDENTATION;
+ method = method + getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + LIST + DIAMOND_OPEN_BRACKET
+ + AUGMENTED_INFO + DIAMOND_CLOSE_BRACKET + SPACE + GET_METHOD_PREFIX + AUGMENTED_INFO + LIST
+ + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + RETURN + SPACE + getSmallCase(AUGMENTED_INFO) + LIST + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION
+ + CLOSE_CURLY_BRACKET;
+ return method;
+ }
+
+ /**
+ * Returns implementation of remove augmentation method of AugmentationHolder class.
+ *
+ * @return implementation of remove augmentation method of AugmentationHolder class
+ */
+ public static String getRemoveAugmentationImpl() {
+ String method = FOUR_SPACE_INDENTATION;
+ method = method + getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + VOID + SPACE + "remove"
+ + AUGMENTATION + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + GET_METHOD_PREFIX + AUGMENTED_INFO + LIST + OPEN_PARENTHESIS
+ + CLOSE_PARENTHESIS + PERIOD + CLEAR + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE
+ + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ return method;
+ }
+
+ /**
+ * Returns enum's constructor.
+ *
+ * @param className enum's class name
+ * @return enum's constructor
+ */
+ public static String getEnumsConstrcutor(String className) {
+ return FOUR_SPACE_INDENTATION + className + OPEN_PARENTHESIS + INT + SPACE + VALUE + CLOSE_PARENTHESIS + SPACE
+ + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + getSmallCase(className) + SPACE + EQUAL
+ + SPACE + VALUE + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ }
+
+ /**
+ * Provides string to be added in augment node's constructor.
+ *
+ * @param curNode current YANG node
+ * @return constructors string
+ */
+ public static String getAugmentsAddToAugmentedMethod(YangNode curNode) {
+
+ if (!(curNode instanceof YangJavaAugment)) {
+ throw new TranslatorException("current node should be of type augment node.");
+ }
+ YangJavaAugment augment = (YangJavaAugment) curNode;
+ List<YangNodeIdentifier> targetNodes = augment.getTargetNode();
+
+ String name = targetNodes.get(targetNodes.size() - 1).getName();
+ String captialCase = getCapitalCase(name);
+ String smallCase = getSmallCase(captialCase);
+ return EIGHT_SPACE_INDENTATION + captialCase + IMPL + SPACE + smallCase + IMPL + SPACE + EQUAL + SPACE
+ + NEW + SPACE + captialCase + BUILDER + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + PERIOD + NEW + SPACE
+ + captialCase + IMPL + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + smallCase + IMPL + PERIOD + ADD_STRING + AUGMENTATION
+ + OPEN_PARENTHESIS + THIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE;
+
+ }
+
+ private static String getAugmentsAddToAugmentedMethodStart() {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + VOID + SPACE + ADD_STRING + AUGMENTABLE + OPEN_PARENTHESIS
+ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET;
+ }
+
+ /**
+ * Returns of method for enum class.
+ *
+ * @param className class name
+ * @param attr java attribute
+ * @param enumMap enum's sets map
+ * @param enumList enum's sets list
+ * @param pluginConfig plugin configurations
+ * @return of method
+ */
+ public static String getEnumsOfMethod(String className, JavaAttributeInfo attr,
+ Map<String, Integer> enumMap, List<String> enumList, YangPluginConfig pluginConfig) {
+ String attrType = getReturnType(attr);
+ String attrName = attr.getAttributeName();
+
+ String method = FOUR_SPACE_INDENTATION + PUBLIC + SPACE + STATIC + SPACE + getCapitalCase(className) + SPACE
+ + OF + OPEN_PARENTHESIS
+ + attrType + SPACE + VALUE + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + SWITCH + SPACE + OPEN_PARENTHESIS + VALUE
+ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
+ int value = 0;
+ for (String str : enumList) {
+
+ value = enumMap.get(str);
+ method = method + TWELVE_SPACE_INDENTATION + CASE + SPACE + value + COLAN + NEW_LINE
+ + SIXTEEN_SPACE_INDENTATION + RETURN + SPACE + getCapitalCase(className) + PERIOD
+ + str + SEMI_COLAN + NEW_LINE;
+ }
+ method = method + TWELVE_SPACE_INDENTATION + DEFAULT + SPACE + COLAN + NEW_LINE + SIXTEEN_SPACE_INDENTATION
+ + RETURN + SPACE + NULL + SEMI_COLAN + NEW_LINE + EIGHT_SPACE_INDENTATION + CLOSE_CURLY_BRACKET
+ + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+
+ return getJavaDoc(OF_METHOD, getCapitalCase(className) + " for type " + attrName, false, pluginConfig)
+ + method;
+ }
+
+ /**
+ * Returns activate method string.
+ *
+ * @return activate method string
+ */
+ public static String addActivateMethod() {
+ return FOUR_SPACE_INDENTATION + ACTIVATE_ANNOTATION + FOUR_SPACE_INDENTATION
+ + PUBLIC + SPACE + VOID + SPACE + ACTIVATE + OPEN_PARENTHESIS
+ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET
+ + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + YANG_UTILS_TODO
+ + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + STARTED_LOG_INFO + FOUR_SPACE_INDENTATION
+ + CLOSE_CURLY_BRACKET + NEW_LINE;
+ }
+
+ /**
+ * Returns deactivate method string.
+ *
+ * @return deactivate method string
+ */
+ public static String addDeActivateMethod() {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + DEACTIVATE_ANNOTATION + FOUR_SPACE_INDENTATION
+ + PUBLIC + SPACE + VOID + SPACE + DEACTIVATE + OPEN_PARENTHESIS
+ + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + YANG_UTILS_TODO + NEW_LINE + EIGHT_SPACE_INDENTATION
+ + STOPPED_LOG_INFO + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET + NEW_LINE;
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/TempJavaCodeFragmentFilesUtils.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/TempJavaCodeFragmentFilesUtils.java
new file mode 100644
index 0000000..f70ec53
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/TempJavaCodeFragmentFilesUtils.java
@@ -0,0 +1,349 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangNodeIdentifier;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
+import org.onosproject.yangutils.translator.tojava.TempJavaFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaAugment;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
+
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getSmallCase;
+import static org.onosproject.yangutils.utils.UtilConstants.ACTIVATE_ANNOTATION_IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.ADD_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTATION_HOLDER;
+import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTED_INFO;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER;
+import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.COMPONENT_ANNOTATION_IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.DEACTIVATE_ANNOTATION_IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.EIGHT_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.ENUM;
+import static org.onosproject.yangutils.utils.UtilConstants.EQUAL;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPL;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_SERVICE;
+import static org.onosproject.yangutils.utils.UtilConstants.LOGGER_FACTORY_IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.LOGGER_IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_CURLY_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.PUBLIC;
+import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.SERVICE_ANNOTATION_IMPORT;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.UtilConstants.THIS;
+import static org.onosproject.yangutils.utils.UtilConstants.TYPE;
+import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.updateFileHandle;
+
+import static java.util.Collections.sort;
+
+/**
+ * Represents utilities for temporary java code fragments.
+ */
+public final class TempJavaCodeFragmentFilesUtils {
+
+ /**
+ * Creates a private instance of temporary java code fragment utils.
+ */
+ private TempJavaCodeFragmentFilesUtils() {
+ }
+
+ /**
+ * Adds import for AugmentationHolders class.
+ *
+ * @param curNode current YANG node
+ * @param imports list of imports
+ * @param operation add or delete import
+ */
+ public static void addAugmentationHoldersImport(YangNode curNode, List<String> imports, boolean operation) {
+ String thisImport = getTempJavaFragement(curNode).getJavaImportData().getAugmentationHolderImport();
+ performOperationOnImports(imports, thisImport, operation);
+ }
+
+ /**
+ * Adds import for AugmentedInfo class.
+ *
+ * @param curNode current YANG node
+ * @param imports list of imports
+ * @param operation add or delete import
+ */
+ public static void addAugmentedInfoImport(YangNode curNode, List<String> imports, boolean operation) {
+ String thisImport = getTempJavaFragement(curNode).getJavaImportData().getAugmentedInfoImport();
+ performOperationOnImports(imports, thisImport, operation);
+ }
+
+ /**
+ * Returns temp java fragment.
+ *
+ * @param curNode current YANG node
+ * @return temp java fragments
+ */
+ public static TempJavaFragmentFiles getTempJavaFragement(YangNode curNode) {
+ TempJavaCodeFragmentFiles container = ((TempJavaCodeFragmentFilesContainer) curNode)
+ .getTempJavaCodeFragmentFiles();
+ if (container.getBeanTempFiles() != null) {
+ return container.getBeanTempFiles();
+ }
+ if (container.getServiceTempFiles() != null) {
+ return container.getServiceTempFiles();
+ }
+
+ return null;
+ }
+
+ /**
+ * Updated imports with augmented nodes import.
+ *
+ * @param curNode current YANG node
+ * @param imports list of imports
+ * @param operation to add or to delete
+ */
+ public static void addAugmentedNodesImport(YangNode curNode, List<String> imports, boolean operation) {
+
+ String nodesImport = "";
+
+ if (!(curNode instanceof YangJavaAugment)) {
+ throw new TranslatorException("current node should be of type augment node.");
+ }
+ YangJavaAugment augment = (YangJavaAugment) curNode;
+ List<YangNodeIdentifier> targetNodes = augment.getTargetNode();
+ YangNode parent = curNode.getParent();
+ if (parent instanceof YangJavaModule) {
+ // Add impl class import.
+ nodesImport = getAugmendtedNodesImports(parent, targetNodes, true) + SEMI_COLAN + NEW_LINE;
+ performOperationOnImports(imports, nodesImport, operation);
+ // Add builder class import.
+ if (targetNodes.size() > 2) {
+ nodesImport = getAugmendtedNodesImports(parent, targetNodes, false) + SEMI_COLAN + NEW_LINE;
+ performOperationOnImports(imports, nodesImport, operation);
+ }
+ }
+ // TODO: add functionality for submodule and uses.
+ }
+
+ /**
+ * Returns imports for augmented node.
+ *
+ * @param parent parent YANG node
+ * @param targetNodes list of target nodes
+ * @param isImplClass if impl class's import required
+ * @return imports for augmented node
+ */
+ private static String getAugmendtedNodesImports(YangNode parent, List<YangNodeIdentifier> targetNodes,
+ boolean isImplClass) {
+ String pkgInfo = ((JavaFileInfoContainer) parent).getJavaFileInfo().getPackage();
+
+ for (int i = 0; i < targetNodes.size() - 1; i++) {
+ pkgInfo = pkgInfo + PERIOD + targetNodes.get(i).getName();
+ }
+ String classInfo = targetNodes.get(targetNodes.size() - 1).getName();
+ if (!isImplClass) {
+ return IMPORT + pkgInfo.toLowerCase() + PERIOD + getCapitalCase(classInfo) + BUILDER;
+ }
+ return IMPORT + pkgInfo.toLowerCase() + PERIOD + getCapitalCase(classInfo) + BUILDER + PERIOD
+ + getCapitalCase(classInfo) + IMPL;
+ }
+
+ /**
+ * Provides string to be added in augment node's constructor.
+ *
+ * @param curNode current YANG node
+ * @return constructors string
+ */
+ public static String getAugmentsAddToAugmentedClassString(YangNode curNode) {
+
+ if (!(curNode instanceof YangJavaAugment)) {
+ throw new TranslatorException("current node should be of type augment node.");
+ }
+ YangJavaAugment augment = (YangJavaAugment) curNode;
+ List<YangNodeIdentifier> targetNodes = augment.getTargetNode();
+
+ String name = targetNodes.get(targetNodes.size() - 1).getName();
+ String captialCase = getCapitalCase(name);
+ String smallCase = getSmallCase(captialCase);
+ return EIGHT_SPACE_INDENTATION + captialCase + IMPL + SPACE + smallCase + IMPL + SPACE + EQUAL + SPACE + NEW
+ + SPACE + captialCase + BUILDER + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + PERIOD + NEW + SPACE
+ + captialCase + IMPL + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE
+ + EIGHT_SPACE_INDENTATION + smallCase + IMPL + PERIOD + ADD_STRING + AUGMENTATION + OPEN_PARENTHESIS
+ + THIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE;
+
+ }
+
+ /**
+ * Adds import for array list.
+ *
+ * @param curNode current YANG node
+ * @param imports list of imports
+ * @param operation add or delete import
+ */
+ public static void addArrayListImport(YangNode curNode, List<String> imports, boolean operation) {
+ String arrayListImport = getTempJavaFragement(curNode).getJavaImportData().getImportForArrayList();
+ String listImport = getTempJavaFragement(curNode).getJavaImportData().getImportForList();
+ performOperationOnImports(imports, arrayListImport, operation);
+ if (!imports.contains(listImport)) {
+ /**
+ * List can be there because of attribute also , so no need to remove it and operation will
+ * always be add(true).
+ */
+ performOperationOnImports(imports, listImport, true);
+ }
+ }
+
+ /**
+ * Adds listener's imports.
+ *
+ * @param curNode currentYangNode.
+ * @param imports import list
+ * @param operation add or remove
+ * @param classInfo class info to be added to import list
+ */
+ public static void addListnersImport(YangNode curNode, List<String> imports, boolean operation,
+ String classInfo) {
+ String thisImport = "";
+ if (classInfo.equals(LISTENER_SERVICE)) {
+ thisImport = getTempJavaFragement(curNode).getJavaImportData().getListenerServiceImport();
+ performOperationOnImports(imports, thisImport, operation);
+ } else {
+ thisImport = getTempJavaFragement(curNode).getJavaImportData().getListenerRegistryImport();
+ performOperationOnImports(imports, thisImport, operation);
+ }
+ }
+
+ /**
+ * Adds annotations imports.
+ *
+ * @param imports list if imports
+ * @param operation to add or to delete
+ */
+ public static void addAnnotationsImports(List<String> imports, boolean operation) {
+ if (operation) {
+ imports.add(ACTIVATE_ANNOTATION_IMPORT);
+ imports.add(DEACTIVATE_ANNOTATION_IMPORT);
+ imports.add(COMPONENT_ANNOTATION_IMPORT);
+ imports.add(SERVICE_ANNOTATION_IMPORT);
+ imports.add(LOGGER_FACTORY_IMPORT);
+ imports.add(LOGGER_IMPORT);
+ } else {
+ imports.remove(ACTIVATE_ANNOTATION_IMPORT);
+ imports.remove(DEACTIVATE_ANNOTATION_IMPORT);
+ imports.remove(COMPONENT_ANNOTATION_IMPORT);
+ imports.remove(SERVICE_ANNOTATION_IMPORT);
+ imports.remove(LOGGER_FACTORY_IMPORT);
+ imports.remove(LOGGER_IMPORT);
+ }
+ sortImports(imports);
+ }
+
+ /**
+ * Performs given operations on import list.
+ *
+ * @param imports list of imports
+ * @param curImport current import
+ * @param operation add or remove
+ * @return import list
+ */
+ private static List<String> performOperationOnImports(List<String> imports, String curImport,
+ boolean operation) {
+ if (operation) {
+ imports.add(curImport);
+ } else {
+ imports.remove(curImport);
+ }
+ sortImports(imports);
+ return imports;
+ }
+
+ /**
+ * Returns true if AugmentationHolder class needs to be extended.
+ *
+ * @param extendsList list of classes need to be extended
+ * @return true or false
+ */
+ public static boolean isAugmentationHolderExtended(List<JavaQualifiedTypeInfo> extendsList) {
+ for (JavaQualifiedTypeInfo info : extendsList) {
+ return info.getClassInfo().equals(AUGMENTATION_HOLDER);
+ }
+ return false;
+ }
+
+ /**
+ * Returns true if AugmentedInfo class needs to be extended.
+ *
+ * @param extendsList list of classes need to be extended
+ * @return true or false
+ */
+ public static boolean isAugmentedInfoExtended(List<JavaQualifiedTypeInfo> extendsList) {
+ for (JavaQualifiedTypeInfo info : extendsList) {
+ return info.getClassInfo().equals(AUGMENTED_INFO);
+ }
+ return false;
+ }
+
+ /**
+ * Closes the file handle for temporary file.
+ *
+ * @param file file to be closed
+ * @param toBeDeleted flag to indicate if file needs to be deleted
+ * @throws IOException when failed to close the file handle
+ */
+ public static void closeFile(File file, boolean toBeDeleted)
+ throws IOException {
+
+ if (file != null) {
+ updateFileHandle(file, null, true);
+ if (toBeDeleted) {
+ file.delete();
+ }
+ }
+ }
+
+ /**
+ * Returns sorted import list.
+ *
+ * @param imports import list
+ * @return sorted import list
+ */
+ public static List<String> sortImports(List<String> imports) {
+ sort(imports);
+ return imports;
+ }
+
+ /**
+ * Returns event enum start.
+ *
+ * @return event enum start
+ */
+ public static String getEventEnumTypeStart() {
+ return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + ENUM + SPACE + TYPE + SPACE + OPEN_CURLY_BRACKET
+ + NEW_LINE;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangJavaModelUtils.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangJavaModelUtils.java
new file mode 100644
index 0000000..3f378c7
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangJavaModelUtils.java
@@ -0,0 +1,352 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+import java.io.IOException;
+
+import org.onosproject.yangutils.datamodel.RpcNotificationContainer;
+import org.onosproject.yangutils.datamodel.YangCase;
+import org.onosproject.yangutils.datamodel.YangChoice;
+import org.onosproject.yangutils.datamodel.YangLeavesHolder;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangTypeHolder;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
+import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
+import org.onosproject.yangutils.translator.tojava.javamodel.JavaCodeGeneratorInfo;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaEnumeration;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
+import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
+
+import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.isRpcChildNodePresent;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
+import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
+import static org.onosproject.yangutils.translator.tojava.TempJavaFragmentFiles.addCurNodeInfoInParentTempFile;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCurNodePackage;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
+
+/**
+ * Represents utility class for YANG java model.
+ */
+public final class YangJavaModelUtils {
+
+ /**
+ * Creates an instance of YANG java model utility.
+ */
+ private YangJavaModelUtils() {
+ }
+
+ /**
+ * Updates YANG java file package information.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @param yangPluginConfig YANG plugin config
+ * @throws IOException IO operations fails
+ */
+ public static void updatePackageInfo(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
+ YangPluginConfig yangPluginConfig)
+ throws IOException {
+
+ javaCodeGeneratorInfo.getJavaFileInfo()
+ .setJavaName(getCamelCase(((YangNode) javaCodeGeneratorInfo).getName(),
+ yangPluginConfig.getConflictResolver()));
+ javaCodeGeneratorInfo.getJavaFileInfo().setPackage(getCurNodePackage((YangNode) javaCodeGeneratorInfo));
+ javaCodeGeneratorInfo.getJavaFileInfo().setPackageFilePath(
+ getPackageDirPathFromJavaJPackage(javaCodeGeneratorInfo.getJavaFileInfo().getPackage()));
+ javaCodeGeneratorInfo.getJavaFileInfo().setBaseCodeGenPath(yangPluginConfig.getCodeGenDir());
+ javaCodeGeneratorInfo.getJavaFileInfo().setPluginConfig(yangPluginConfig);
+ }
+
+ /**
+ * Updates YANG java file package information for specified package.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @param yangPlugin YANG plugin config
+ * @throws IOException IO operations fails
+ */
+ private static void updatePackageInfo(JavaCodeGeneratorInfo javaCodeGeneratorInfo, YangPluginConfig yangPlugin,
+ String pkg)
+ throws IOException {
+ javaCodeGeneratorInfo.getJavaFileInfo()
+ .setJavaName(getCamelCase(((YangNode) javaCodeGeneratorInfo).getName(),
+ yangPlugin.getConflictResolver()));
+ javaCodeGeneratorInfo.getJavaFileInfo().setPackage(pkg);
+ javaCodeGeneratorInfo.getJavaFileInfo().setPackageFilePath(
+ getPackageDirPathFromJavaJPackage(javaCodeGeneratorInfo.getJavaFileInfo().getPackage()));
+ javaCodeGeneratorInfo.getJavaFileInfo().setBaseCodeGenPath(yangPlugin.getCodeGenDir());
+ javaCodeGeneratorInfo.getJavaFileInfo().setPluginConfig(yangPlugin);
+ }
+
+ /**
+ * Updates temporary java code fragment files.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @throws IOException IO operations fails
+ */
+ private static void createTempFragmentFile(JavaCodeGeneratorInfo javaCodeGeneratorInfo)
+ throws IOException {
+ javaCodeGeneratorInfo.setTempJavaCodeFragmentFiles(
+ new TempJavaCodeFragmentFiles(javaCodeGeneratorInfo.getJavaFileInfo()));
+ }
+
+ /**
+ * Updates leaf information in temporary java code fragment files.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @throws IOException IO operations fails
+ */
+ private static void updateTempFragmentFiles(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
+ YangPluginConfig yangPluginConfig)
+ throws IOException {
+ if (javaCodeGeneratorInfo instanceof RpcNotificationContainer) {
+ /*
+ * Module / sub module node code generation.
+ */
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles().addCurNodeLeavesInfoToTempFiles(
+ (YangNode) javaCodeGeneratorInfo, yangPluginConfig);
+ if ((YangNode) javaCodeGeneratorInfo instanceof YangJavaModule) {
+ if (!((YangJavaModule) javaCodeGeneratorInfo).getNotificationNodes().isEmpty()) {
+ updateNotificaitonNodeInfo(javaCodeGeneratorInfo, yangPluginConfig);
+ }
+ } else if ((YangNode) javaCodeGeneratorInfo instanceof YangJavaSubModule) {
+ if (!((YangJavaSubModule) javaCodeGeneratorInfo).getNotificationNodes().isEmpty()) {
+ updateNotificaitonNodeInfo(javaCodeGeneratorInfo, yangPluginConfig);
+ }
+ }
+
+ } else if (javaCodeGeneratorInfo instanceof YangLeavesHolder) {
+ /*
+ * Container
+ * Case
+ * Grouping
+ * Input
+ * List
+ * Notification
+ * Output
+ */
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles()
+ .getBeanTempFiles().addCurNodeLeavesInfoToTempFiles(
+ (YangNode) javaCodeGeneratorInfo, yangPluginConfig);
+ } else if (javaCodeGeneratorInfo instanceof YangTypeHolder) {
+ /*
+ * Typedef
+ * Union
+ */
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles()
+ .addTypeInfoToTempFiles((YangTypeHolder) javaCodeGeneratorInfo, yangPluginConfig);
+ } else if (javaCodeGeneratorInfo instanceof YangJavaEnumeration) {
+ /*
+ * Enumeration
+ */
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles().getEnumerationTempFiles()
+ .addEnumAttributeToTempFiles((YangNode) javaCodeGeneratorInfo, yangPluginConfig);
+
+ } else if (javaCodeGeneratorInfo instanceof YangChoice) {
+ /*Do nothing, only the interface needs to be generated*/
+ } else {
+ throw new TranslatorException("Unsupported Node Translation");
+ }
+ }
+
+ /**
+ * Process generate code entry of YANG node.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @throws IOException IO operations fails
+ */
+ private static void generateTempFiles(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
+ YangPluginConfig yangPluginConfig)
+ throws IOException {
+ if (!(javaCodeGeneratorInfo instanceof YangNode)) {
+ throw new TranslatorException("translation is not supported for the node");
+ }
+ createTempFragmentFile(javaCodeGeneratorInfo);
+ updateTempFragmentFiles(javaCodeGeneratorInfo, yangPluginConfig);
+
+ }
+
+ /**
+ * Updates notification node info in service temporary file.
+ *
+ * @param javaCodeGeneratorInfo java code generator info
+ * @param yangPluginConfig plugin configurations
+ * @throws IOException when fails to do IO operations
+ */
+ private static void updateNotificaitonNodeInfo(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
+ YangPluginConfig yangPluginConfig)
+ throws IOException {
+ if ((YangNode) javaCodeGeneratorInfo instanceof YangJavaModule) {
+ for (YangNode notificaiton : ((YangJavaModule) javaCodeGeneratorInfo).getNotificationNodes()) {
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles()
+ .addJavaSnippetOfEvent(notificaiton, yangPluginConfig);
+ }
+ }
+ if ((YangNode) javaCodeGeneratorInfo instanceof YangJavaSubModule) {
+ for (YangNode notificaiton : ((YangJavaSubModule) javaCodeGeneratorInfo)
+ .getNotificationNodes()) {
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles()
+ .getServiceTempFiles()
+ .addJavaSnippetOfEvent(notificaiton, yangPluginConfig);
+ }
+ }
+ }
+
+ /**
+ * Generates code for the current ata model node and adds itself as an attribute in the parent.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @param yangPlugin YANG plugin config
+ * @param isMultiInstance flag to indicate whether it's a list
+ * @throws IOException IO operations fails
+ */
+ public static void generateCodeAndUpdateInParent(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
+ YangPluginConfig yangPlugin, boolean isMultiInstance)
+ throws IOException {
+ if (!(javaCodeGeneratorInfo instanceof YangNode)) {
+ throw new TranslatorException("Invalid node for translation");
+ }
+
+ /*
+ * Generate the Java files corresponding to the current node.
+ */
+ generateCodeOfAugmentableNode(javaCodeGeneratorInfo, yangPlugin);
+
+ /*
+ * Update the current nodes info in its parent nodes generated files.
+ */
+ addCurNodeInfoInParentTempFile((YangNode) javaCodeGeneratorInfo, isMultiInstance, yangPlugin);
+ }
+
+ /**
+ * Generates code for the current data model node and adds support for it to be augmented.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @param yangPlugin YANG plugin config
+ * @throws IOException IO operations fails
+ */
+ public static void generateCodeOfAugmentableNode(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
+ YangPluginConfig yangPlugin)
+ throws IOException {
+ if (!(javaCodeGeneratorInfo instanceof YangNode)) {
+ throw new TranslatorException("invalid node for translation");
+ }
+
+ generateCodeOfNode(javaCodeGeneratorInfo, yangPlugin);
+
+ /*
+ TODO: Need to use this, when augmentation is added in YMS
+ * For augmentation of nodes.
+
+ if (javaCodeGeneratorInfo instanceof YangAugmentationHolder) {
+ JavaQualifiedTypeInfo augmentationHoldersInfo = new JavaQualifiedTypeInfo();
+ augmentationHoldersInfo.setClassInfo(AUGMENTATION_HOLDER);
+ augmentationHoldersInfo.setPkgInfo(PROVIDED_AUGMENTATION_CLASS_IMPORT_PKG);
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles().getBeanTempFiles().getJavaExtendsListHolder()
+ .addToExtendsList(augmentationHoldersInfo, (YangNode) javaCodeGeneratorInfo);
+
+ } else if (javaCodeGeneratorInfo instanceof YangAugment) {
+ JavaQualifiedTypeInfo augmentedInfo = new JavaQualifiedTypeInfo();
+ augmentedInfo.setClassInfo(AUGMENTED_INFO);
+ augmentedInfo.setPkgInfo(PROVIDED_AUGMENTATION_CLASS_IMPORT_PKG);
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles().getBeanTempFiles().getJavaExtendsListHolder()
+ .addToExtendsList(augmentedInfo, (YangNode) javaCodeGeneratorInfo);
+
+ }
+ */
+ if (javaCodeGeneratorInfo instanceof YangCase) {
+ YangNode parent = ((YangCase) javaCodeGeneratorInfo).getParent();
+ JavaQualifiedTypeInfo parentsInfo = new JavaQualifiedTypeInfo();
+ String parentName = getCapitalCase(((JavaFileInfoContainer) parent).getJavaFileInfo().getJavaName());
+ String parentPkg = ((JavaFileInfoContainer) parent).getJavaFileInfo().getPackage();
+ parentsInfo.setClassInfo(parentName);
+ parentsInfo.setPkgInfo(parentPkg);
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles().getBeanTempFiles().getJavaExtendsListHolder()
+ .addToExtendsList(parentsInfo, (YangNode) javaCodeGeneratorInfo);
+
+ javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles().getBeanTempFiles()
+ .addParentInfoInCurNodeTempFile((YangNode) javaCodeGeneratorInfo, yangPlugin);
+
+ }
+ }
+
+ /**
+ * Generates code for the current data model node.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @param yangPluginConfig YANG plugin config
+ * @throws IOException IO operations fails
+ */
+ public static void generateCodeOfNode(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
+ YangPluginConfig yangPluginConfig)
+ throws IOException {
+ if (!(javaCodeGeneratorInfo instanceof YangNode)) {
+ // TODO:throw exception
+ }
+ updatePackageInfo(javaCodeGeneratorInfo, yangPluginConfig);
+ generateTempFiles(javaCodeGeneratorInfo, yangPluginConfig);
+ }
+
+ /**
+ * Generates code for the root module/sub-module node.
+ *
+ * @param javaCodeGeneratorInfo YANG java file info node
+ * @param yangPluginConfig YANG plugin config
+ * @param rootPkg package of the root node
+ * @throws IOException IO operations fails
+ */
+ public static void generateCodeOfRootNode(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
+ YangPluginConfig yangPluginConfig, String rootPkg)
+ throws IOException {
+ if (!(javaCodeGeneratorInfo instanceof YangNode)) {
+ // TODO:throw exception
+ }
+ updatePackageInfo(javaCodeGeneratorInfo, yangPluginConfig, rootPkg);
+
+ if (isRpcChildNodePresent((YangNode) javaCodeGeneratorInfo)) {
+ javaCodeGeneratorInfo.getJavaFileInfo().addGeneratedFileTypes(GENERATE_SERVICE_AND_MANAGER);
+ }
+
+ if ((YangNode) javaCodeGeneratorInfo instanceof YangJavaModule) {
+ if (!((YangJavaModule) javaCodeGeneratorInfo)
+ .isNotificationChildNodePresent((YangNode) javaCodeGeneratorInfo)) {
+ updateCodeGenInfoForEvent(javaCodeGeneratorInfo);
+ }
+ } else if ((YangNode) javaCodeGeneratorInfo instanceof YangJavaSubModule) {
+ if (!((YangJavaSubModule) javaCodeGeneratorInfo)
+ .isNotificationChildNodePresent((YangNode) javaCodeGeneratorInfo)) {
+ updateCodeGenInfoForEvent(javaCodeGeneratorInfo);
+ }
+ }
+
+ generateTempFiles(javaCodeGeneratorInfo, yangPluginConfig);
+ }
+
+ /*Updates java code generator info with events info.*/
+ private static void updateCodeGenInfoForEvent(JavaCodeGeneratorInfo javaCodeGeneratorInfo) {
+ javaCodeGeneratorInfo.getJavaFileInfo().addGeneratedFileTypes(GENERATE_EVENT_SUBJECT_CLASS);
+ javaCodeGeneratorInfo.getJavaFileInfo().addGeneratedFileTypes(GENERATE_EVENT_CLASS);
+ javaCodeGeneratorInfo.getJavaFileInfo().addGeneratedFileTypes(GENERATE_EVENT_LISTENER_INTERFACE);
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangPluginConfig.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangPluginConfig.java
new file mode 100644
index 0000000..f827698
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangPluginConfig.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+/**
+ * Representation of plugin configurations required for YANG utils.
+ */
+public final class YangPluginConfig {
+
+ /**
+ * Contains the code generation directory.
+ */
+ private String codeGenDir;
+
+ /**
+ * Contains information of naming conflicts that can be resolved.
+ */
+ private YangToJavaNamingConflictUtil conflictResolver;
+
+ /**
+ * Creates an object for YANG plugin config.
+ */
+ public YangPluginConfig() {
+ }
+
+ /**
+ * Sets the path of the java code where it has to be generated.
+ *
+ * @param codeGenDir path of the directory
+ */
+ public void setCodeGenDir(String codeGenDir) {
+ this.codeGenDir = codeGenDir;
+ }
+
+ /**
+ * Returns the code generation directory path.
+ *
+ * @return code generation directory
+ */
+ public String getCodeGenDir() {
+ return codeGenDir;
+ }
+
+ /**
+ * Sets the object.
+ *
+ * @param conflictResolver object of the class
+ */
+ public void setConflictResolver(YangToJavaNamingConflictUtil conflictResolver) {
+ this.conflictResolver = conflictResolver;
+ }
+
+ /**
+ * Returns the object.
+ *
+ * @return object of the class
+ */
+ public YangToJavaNamingConflictUtil getConflictResolver() {
+ return conflictResolver;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangToJavaNamingConflictUtil.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangToJavaNamingConflictUtil.java
new file mode 100644
index 0000000..4f701b6
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/YangToJavaNamingConflictUtil.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.translator.tojava.utils;
+
+/**
+ * Representation of YANG to java naming conflict resolver util.
+ */
+public final class YangToJavaNamingConflictUtil {
+
+ /**
+ * Contains the replacement value for a period.
+ */
+ private static String replacementForPeriodInIdentifier;
+
+ /**
+ * Contains the replacement value for an underscore.
+ */
+ private static String replacementForUnderscoreInIdentifier;
+
+ /**
+ * Contains the replacement value for a hyphen.
+ */
+ private static String replacementForHyphenInIdentifier;
+
+ /**
+ * Contains the prefix value for adding with the identifier.
+ */
+ private static String prefixForIdentifier;
+
+ /**
+ * Creates an object for YANG to java naming conflict util.
+ */
+ public YangToJavaNamingConflictUtil() {
+ }
+
+ /**
+ * Sets the replacement value for a period.
+ *
+ * @param periodReplacement replacement value for period
+ */
+ public void setReplacementForPeriod(String periodReplacement) {
+ replacementForPeriodInIdentifier = periodReplacement;
+ }
+
+ /**
+ * Returns the replaced period value.
+ *
+ * @return replaced period
+ */
+ public String getReplacementForPeriod() {
+ return replacementForPeriodInIdentifier;
+ }
+
+ /**
+ * Sets the replacement value for a hyphen.
+ *
+ * @param hyphenReplacement replacement value for hyphen
+ */
+ public void setReplacementForHyphen(String hyphenReplacement) {
+ replacementForHyphenInIdentifier = hyphenReplacement;
+ }
+
+ /**
+ * Returns the replaced hyphen value.
+ *
+ * @return replaced hyphen
+ */
+ public String getReplacementForHyphen() {
+ return replacementForHyphenInIdentifier;
+ }
+
+ /**
+ * Sets the replacement value for an underscore.
+ *
+ * @param underscoreReplacement replacement value for underscore
+ */
+ public void setReplacementForUnderscore(String underscoreReplacement) {
+ replacementForUnderscoreInIdentifier = underscoreReplacement;
+ }
+
+ /**
+ * Returns the replaced underscore value.
+ *
+ * @return replaced underscore
+ */
+ public String getReplacementForUnderscore() {
+ return replacementForUnderscoreInIdentifier;
+ }
+
+ /**
+ * Sets the prefix value for adding with the identifier.
+ *
+ * @param prefix prefix for identifier
+ */
+ public void setPrefixForIdentifier(String prefix) {
+ prefixForIdentifier = prefix;
+ }
+
+ /**
+ * Returns the prefix for identifier.
+ *
+ * @return prefix for identifier
+ */
+ public String getPrefixForIdentifier() {
+ return prefixForIdentifier;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/package-info.java
new file mode 100644
index 0000000..709e704
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/translator/tojava/utils/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Translator's utils for YANG plugin.
+ */
+package org.onosproject.yangutils.translator.tojava.utils;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/AugmentationHolder.java b/plugin/src/main/java/org/onosproject/yangutils/utils/AugmentationHolder.java
new file mode 100644
index 0000000..b306fe2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/AugmentationHolder.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.utils;
+
+import java.util.List;
+
+/**
+ * Abstraction of an entity which represents augmentation of a YANG node.
+ */
+public interface AugmentationHolder {
+
+ /**
+ * Adds augment info to the augment info list.
+ *
+ * @param augmentInfo augment info of node
+ */
+ void addAugmentation(AugmentedInfo augmentInfo);
+
+ /**
+ * Removes augment info from the node.
+ */
+ void removeAugmentation();
+
+ /**
+ * Returns list of augment info.
+ *
+ * @return list of augment info
+ */
+ List<AugmentedInfo> getAugmentedInfoList();
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/AugmentedInfo.java b/plugin/src/main/java/org/onosproject/yangutils/utils/AugmentedInfo.java
new file mode 100644
index 0000000..566caf0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/AugmentedInfo.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.utils;
+
+/**
+ * Abstraction of an entity which represents augmented info.
+ */
+public interface AugmentedInfo {
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/UtilConstants.java b/plugin/src/main/java/org/onosproject/yangutils/utils/UtilConstants.java
new file mode 100644
index 0000000..37b8992
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/UtilConstants.java
@@ -0,0 +1,1162 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.utils;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Represents utilities constants which are used while generating java files.
+ */
+public final class UtilConstants {
+
+ /**
+ * JavaDocs for impl class.
+ */
+ public static final String IMPL_CLASS_JAVA_DOC = " * Represents the implementation of ";
+
+ /**
+ * JavaDocs for builder class.
+ */
+ public static final String BUILDER_CLASS_JAVA_DOC = " * Represents the builder implementation of ";
+
+ /**
+ * JavaDocs for interface class.
+ */
+ public static final String INTERFACE_JAVA_DOC = " * Abstraction of an entity which represents the"
+ + " functionality of ";
+
+ /**
+ * JavaDocs for event.
+ */
+ public static final String EVENT_JAVA_DOC = " * Represents event implementation of ";
+
+ /**
+ * JavaDocs for event listener.
+ */
+ public static final String EVENT_LISTENER_JAVA_DOC = " * Abstraction for event listener of ";
+
+ /**
+ * JavaDocs for builder interface class.
+ */
+ public static final String BUILDER_INTERFACE_JAVA_DOC = " * Builder for ";
+
+ /**
+ * JavaDocs for enum class.
+ */
+ public static final String ENUM_CLASS_JAVADOC = " * Represents ENUM data of ";
+
+ /**
+ * JavaDocs for enum attribute.
+ */
+ public static final String ENUM_ATTRIBUTE_JAVADOC = " * Represents ";
+
+ /**
+ * JavaDocs for package info class.
+ */
+ public static final String PACKAGE_INFO_JAVADOC = " * Implementation of YANG node ";
+
+ /**
+ * JavaDocs for package info class.
+ */
+ public static final String PACKAGE_INFO_JAVADOC_OF_CHILD = "'s children nodes";
+
+ /**
+ * JavaDocs's first line.
+ */
+ public static final String JAVA_DOC_FIRST_LINE = "/**\n";
+
+ /**
+ * JavaDocs's last line.
+ */
+ public static final String JAVA_DOC_END_LINE = " */\n";
+
+ /**
+ * JavaDocs's param annotation.
+ */
+ public static final String JAVA_DOC_PARAM = " * @param ";
+
+ /**
+ * JavaDocs's return annotation.
+ */
+ public static final String JAVA_DOC_RETURN = " * @return ";
+
+ /**
+ * JavaDocs's throw annotation.
+ */
+ public static final String JAVA_DOC_THROWS = " * @throws ";
+
+ /**
+ * JavaDocs's description for setter method.
+ */
+ public static final String JAVA_DOC_SETTERS = " * Returns the builder object of ";
+
+ /**
+ * JavaDocs's description for setter method.
+ */
+ public static final String JAVA_DOC_MANAGER_SETTERS = " * Sets the value to attribute ";
+
+ /**
+ * JavaDocs's description for OF method.
+ */
+ public static final String JAVA_DOC_OF = " * Returns the object of ";
+
+ /**
+ * JavaDocs's description for typedef' setter method.
+ */
+ public static final String JAVA_DOC_SETTERS_COMMON = " * Sets the value of ";
+
+ /**
+ * JavaDocs's description for getter method.
+ */
+ public static final String JAVA_DOC_GETTERS = " * Returns the attribute ";
+
+ /**
+ * JavaDocs's description for constructor.
+ */
+ public static final String JAVA_DOC_CONSTRUCTOR = " * Creates an instance of ";
+
+ /**
+ * JavaDocs's description for build method.
+ */
+ public static final String JAVA_DOC_BUILD = " * Builds object of ";
+
+ /**
+ * JavaDocs's return statement for build method.
+ */
+ public static final String JAVA_DOC_BUILD_RETURN = "object of ";
+
+ /**
+ * JavaDocs's statement for builder object.
+ */
+ public static final String BUILDER_OBJECT = "builder object of ";
+
+ /**
+ * JavaDocs's statement for rpc method.
+ */
+ public static final String JAVA_DOC_RPC = " * Service interface of ";
+
+ /**
+ * JavaDocs's statement for rpc's input string.
+ */
+ public static final String RPC_INPUT_STRING = "input of service interface ";
+
+ /**
+ * JavaDocs's statement for rpc's output string.
+ */
+ public static final String RPC_OUTPUT_STRING = "output of service interface ";
+
+ /**
+ * Static attribute for new line.
+ */
+ public static final String NEW_LINE = "\n";
+
+ /**
+ * Static attribute for default.
+ */
+ public static final String DEFAULT = "default";
+
+ /**
+ * Static attribute for multiple new line.
+ */
+ public static final String MULTIPLE_NEW_LINE = "\n\n";
+
+ /**
+ * Static attribute for empty line.
+ */
+ public static final String EMPTY_STRING = "";
+
+ /**
+ * Static attribute for new line with asterisk.
+ */
+ public static final String NEW_LINE_ASTERISK = " *\n";
+
+ /**
+ * Static attribute for period.
+ */
+ public static final String PERIOD = ".";
+
+ /**
+ * Static attribute for parse byte.
+ */
+ public static final String PARSE_BYTE = "parseByte";
+
+ /**
+ * Static attribute for parse boolean.
+ */
+ public static final String PARSE_BOOLEAN = "parseBoolean";
+
+ /**
+ * Static attribute for parse short.
+ */
+ public static final String PARSE_SHORT = "parseShort";
+
+ /**
+ * Static attribute for parse int.
+ */
+ public static final String PARSE_INT = "parseInt";
+
+ /**
+ * Static attribute for parse long.
+ */
+ public static final String PARSE_LONG = "parseLong";
+
+ /**
+ * Static attribute for omit null value.
+ */
+ public static final String OMIT_NULL_VALUE_STRING = "omitNullValues()";
+
+ /**
+ * Static attribute for colan.
+ */
+ public static final String COLAN = ":";
+
+ /**
+ * Static attribute for underscore.
+ */
+ public static final String UNDER_SCORE = "_";
+
+ /**
+ * Static attribute for semi-colan.
+ */
+ public static final String SEMI_COLAN = ";";
+
+ /**
+ * Static attribute for hyphen.
+ */
+ public static final String HYPHEN = "-";
+
+ /**
+ * Static attribute for space.
+ */
+ public static final String SPACE = " ";
+
+ /**
+ * Static attribute for subject.
+ */
+ public static final String SUBJECT = "Subject";
+
+ /**
+ * Static attribute for ListenerRegistry.
+ */
+ public static final String LISTENER_REG = "ListenerRegistry";
+
+ /**
+ * Static attribute for ListenerService.
+ */
+ public static final String LISTENER_SERVICE = "ListenerService";
+
+ /**
+ * Static attribute for listener package.
+ */
+ public static final String ONOS_EVENT_PKG = "org.onosproject.event";
+
+ /**
+ * Static attribute for colon.
+ */
+ public static final String COLON = ":";
+
+ /**
+ * Static attribute for caret.
+ */
+ public static final String CARET = "^";
+
+ /**
+ * Static attribute for input string.
+ */
+ public static final String INPUT = "input";
+
+ /**
+ * Static attribute for leafref string.
+ */
+ public static final String LEAFREF = "leafref";
+
+ /**
+ * Static attribute for identityref string.
+ */
+ public static final String IDENTITYREF = "identityref";
+
+ /**
+ * Static attribute for instance identifier string.
+ */
+ public static final String INSTANCE_IDENTIFIER = "instance-identifier";
+
+ /**
+ * Static attribute for output variable of rpc.
+ */
+ public static final String RPC_INPUT_VAR_NAME = "inputVar";
+
+ /**
+ * Static attribute for new line.
+ */
+ public static final String EQUAL = "=";
+
+ /**
+ * Static attribute for slash syntax.
+ */
+ public static final String SLASH = File.separator;
+
+ /**
+ * Static attribute for add syntax.
+ */
+ public static final String ADD = "+";
+
+ /**
+ * Static attribute for asterisk.
+ */
+ public static final String ASTERISK = "*";
+
+ /**
+ * Static attribute for at.
+ */
+ public static final String AT = "@";
+
+ /**
+ * Static attribute for quotes.
+ */
+ public static final String QUOTES = "\"";
+
+ /**
+ * Static attribute for ampersand.
+ */
+ public static final String AND = "&";
+
+ /**
+ * Static attribute for comma.
+ */
+ public static final String COMMA = ",";
+
+ /**
+ * Static attribute for add syntax.
+ */
+ public static final String ADD_STRING = "add";
+
+ /**
+ * Static attribute for from syntax.
+ */
+ public static final String FROM_STRING_METHOD_NAME = "fromString";
+
+ /**
+ * Static attribute for check not null syntax.
+ */
+ public static final String CHECK_NOT_NULL_STRING = "checkNotNull";
+
+ /**
+ * Static attribute for hash code syntax.
+ */
+ public static final String HASH_CODE_STRING = "hashCode";
+
+ /**
+ * Static attribute for equals syntax.
+ */
+ public static final String EQUALS_STRING = "equals";
+
+ /**
+ * Static attribute for object.
+ */
+ public static final String OBJECT_STRING = "Object";
+
+ /**
+ * Static attribute for instance of syntax.
+ */
+ public static final String INSTANCE_OF = " instanceof ";
+
+ /**
+ * Static attribute for value syntax.
+ */
+ public static final String VALUE = "value";
+
+ /**
+ * Static attribute for enumValue syntax.
+ */
+ public static final String ENUM_VALUE = "enumValue";
+
+ /**
+ * Static attribute for suffix s.
+ */
+ public static final String SUFFIX_S = "s";
+
+ /**
+ * Static attribute for if.
+ */
+ public static final String IF = "if";
+
+ /**
+ * Static attribute for for.
+ */
+ public static final String FOR = "for";
+
+ /**
+ * Static attribute for while.
+ */
+ public static final String WHILE = "while";
+
+ /**
+ * Static attribute for of.
+ */
+ public static final String OF = "of";
+
+ /**
+ * Static attribute for other.
+ */
+ public static final String OTHER = "other";
+
+ /**
+ * Static attribute for obj syntax.
+ */
+ public static final String OBJ = "obj";
+
+ /**
+ * Static attribute for hash syntax.
+ */
+ public static final String HASH = "hash";
+
+ /**
+ * Static attribute for to syntax.
+ */
+ public static final String TO = "to";
+
+ /**
+ * Static attribute for true syntax.
+ */
+ public static final String TRUE = "true";
+
+ /**
+ * Static attribute for false syntax.
+ */
+ public static final String FALSE = "false";
+
+ /**
+ * Static attribute for org.
+ */
+ public static final String ORG = "org";
+
+ /**
+ * Static attribute for temp.
+ */
+ public static final String TEMP = "temp";
+
+ /**
+ * Static attribute for YANG file directory.
+ */
+ public static final String YANG_RESOURCES = "yang/resources";
+
+ /**
+ * Static attribute for diamond close bracket syntax.
+ */
+ public static final String DIAMOND_OPEN_BRACKET = "<";
+
+ /**
+ * Static attribute for diamond close bracket syntax.
+ */
+ public static final String DIAMOND_CLOSE_BRACKET = ">";
+
+ /**
+ * Static attribute for exception syntax.
+ */
+ public static final String EXCEPTION = "Exception";
+
+ /**
+ * Static attribute for exception variable syntax.
+ */
+ public static final String EXCEPTION_VAR = "e";
+
+ /**
+ * Static attribute for open parenthesis syntax.
+ */
+ public static final String OPEN_PARENTHESIS = "(";
+
+ /**
+ * Static attribute for clear syntax.
+ */
+ public static final String CLEAR = "clear";
+
+ /**
+ * Static attribute for switch syntax.
+ */
+ public static final String SWITCH = "switch";
+
+ /**
+ * Static attribute for case syntax.
+ */
+ public static final String CASE = "case";
+
+ /**
+ * Static attribute for temp val syntax.
+ */
+ public static final String TMP_VAL = "tmpVal";
+
+ /**
+ * From string parameter name.
+ */
+ public static final String FROM_STRING_PARAM_NAME = "valInString";
+
+ /**
+ * Static attribute for close parenthesis syntax.
+ */
+ public static final String CLOSE_PARENTHESIS = ")";
+
+ /**
+ * Static attribute for open curly bracket syntax.
+ */
+ public static final String OPEN_CURLY_BRACKET = "{";
+
+ /**
+ * Static attribute for close curly bracket syntax.
+ */
+ public static final String CLOSE_CURLY_BRACKET = "}";
+
+ /**
+ * Static attribute for getter method prefix.
+ */
+ public static final String GET_METHOD_PREFIX = "get";
+
+ /**
+ * Static attribute for setter method prefix.
+ */
+ public static final String SET_METHOD_PREFIX = "set";
+
+ /**
+ * Static attribute for four space indentation.
+ */
+ public static final String FOUR_SPACE_INDENTATION = " ";
+
+ /**
+ * Static attribute for not syntax.
+ */
+ public static final String NOT = "!";
+
+ /**
+ * Static attribute for try syntax.
+ */
+ public static final String TRY = "try";
+
+ /**
+ * Static attribute for catch syntax.
+ */
+ public static final String CATCH = "catch";
+
+ /**
+ * Static attribute for eight space indentation.
+ */
+ public static final String EIGHT_SPACE_INDENTATION = FOUR_SPACE_INDENTATION + FOUR_SPACE_INDENTATION;
+
+ /**
+ * Static attribute for twelve space indentation.
+ */
+ public static final String TWELVE_SPACE_INDENTATION = FOUR_SPACE_INDENTATION + EIGHT_SPACE_INDENTATION;
+
+ /**
+ * Static attribute for sixteen space indentation.
+ */
+ public static final String SIXTEEN_SPACE_INDENTATION = EIGHT_SPACE_INDENTATION + EIGHT_SPACE_INDENTATION;
+
+ /**
+ * Static attribute for generated code path.
+ */
+ public static final String YANG_GEN_DIR = "src/main/java/";
+
+ /**
+ * Static attribute for base package.
+ */
+ public static final String DEFAULT_BASE_PKG = "org.onosproject.yang.gen";
+
+ /**
+ * Static attribute for YANG date prefix.
+ */
+ public static final String REVISION_PREFIX = "rev";
+
+ /**
+ * Static attribute for YANG automatic prefix for identifiers with keywords and beginning with digits.
+ */
+ public static final String YANG_AUTO_PREFIX = "yangAutoPrefix";
+
+ /**
+ * Static attribute for YANG version perifx.
+ */
+ public static final String VERSION_PREFIX = "v";
+
+ /**
+ * Static attribute for private modifier.
+ */
+ public static final String PRIVATE = "private";
+
+ /**
+ * Static attribute for public modifier.
+ */
+ public static final String PUBLIC = "public";
+
+ /**
+ * Static attribute for protected modifier.
+ */
+ public static final String PROTECTED = "protected";
+
+ /**
+ * Void java type.
+ */
+ public static final String VOID = "void";
+
+ /**
+ * String built in java type.
+ */
+ public static final String STRING_DATA_TYPE = "String";
+
+ /**
+ * Java.lang.* packages.
+ */
+ public static final String JAVA_LANG = "java.lang";
+
+ /**
+ * Java.math.* packages.
+ */
+ public static final String JAVA_MATH = "java.math";
+
+ /**
+ * Boolean built in java type.
+ */
+ public static final String BOOLEAN_DATA_TYPE = "boolean";
+
+ /**
+ * BigInteger built in java type.
+ */
+ public static final String BIG_INTEGER = "BigInteger";
+
+ /**
+ * Byte java built in type.
+ */
+ public static final String BYTE = "byte";
+
+ /**
+ * Short java built in type.
+ */
+ public static final String SHORT = "short";
+
+ /**
+ * Int java built in type.
+ */
+ public static final String INT = "int";
+
+ /**
+ * Long java built in type.
+ */
+ public static final String LONG = "long";
+
+ /**
+ * Float java built in type.
+ */
+ public static final String FLOAT = "float";
+
+ /**
+ * Double java built in type.
+ */
+ public static final String DOUBLE = "double";
+
+ /**
+ * Boolean built in java wrapper type.
+ */
+ public static final String BOOLEAN_WRAPPER = "Boolean";
+
+ /**
+ * Byte java built in wrapper type.
+ */
+ public static final String BYTE_WRAPPER = "Byte";
+
+ /**
+ * Short java built in wrapper type.
+ */
+ public static final String SHORT_WRAPPER = "Short";
+
+ /**
+ * Integer java built in wrapper type.
+ */
+ public static final String INTEGER_WRAPPER = "Integer";
+
+ /**
+ * Long java built in wrapper type.
+ */
+ public static final String LONG_WRAPPER = "Long";
+
+ /**
+ * YangUint64 java built in wrapper type.
+ */
+ public static final String YANG_UINT64 = "YangUint64";
+
+ /**
+ * List of keywords in java, this is used for checking if the input does not contain these keywords.
+ */
+ public static final List<String> JAVA_KEY_WORDS = Arrays.asList(
+ "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue",
+ "default", "do", "double", "else", "extends", "false", "final", "finally", "float", "for", "goto", "if",
+ "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package",
+ "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch",
+ "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while");
+
+ /**
+ * Static attribute for regex for all the special characters.
+ */
+ public static final String REGEX_WITH_ALL_SPECIAL_CHAR = "\\p{Punct}+";
+
+ /**
+ * Static attribute for regex for three special characters used in identifier.
+ */
+ public static final String REGEX_FOR_IDENTIFIER_SPECIAL_CHAR = "[. _ -]+";
+
+ /**
+ * Static attribute for regex for period.
+ */
+ public static final String REGEX_FOR_PERIOD = "[.]";
+
+ /**
+ * Static attribute for regex for underscore.
+ */
+ public static final String REGEX_FOR_UNDERSCORE = "[_]";
+
+ /**
+ * Static attribute for regex for hyphen.
+ */
+ public static final String REGEX_FOR_HYPHEN = "[-]";
+
+ /**
+ * Static attribute for regex for digits.
+ */
+ public static final String REGEX_FOR_FIRST_DIGIT = "\\d.*";
+
+ /**
+ * Static attribute for regex with digits.
+ */
+ public static final String REGEX_WITH_DIGITS = "(?=\\d+)";
+
+ /**
+ * Static attribute for regex for single letter.
+ */
+ public static final String REGEX_FOR_SINGLE_LETTER = "[a-zA-Z]";
+
+ /**
+ * Static attribute for regex for digits with single letter.
+ */
+ public static final String REGEX_FOR_DIGITS_WITH_SINGLE_LETTER = "[0-9]+[a-zA-Z]";
+
+ /**
+ * Static attribute for regex with uppercase.
+ */
+ public static final String REGEX_WITH_UPPERCASE = "(?=\\p{Upper})";
+
+ /**
+ * Static attribute for regex for single capital case letter.
+ */
+ public static final String REGEX_WITH_SINGLE_CAPITAL_CASE = "[A-Z]";
+
+ /**
+ * Static attribute for regex for capital case letter with any number of digits and small case letters.
+ */
+ public static final String REGEX_WITH_SINGLE_CAPITAL_CASE_AND_DIGITS_SMALL_CASES = "[A-Z][0-9a-z]+";
+
+ /**
+ * Static attribute for regex for any string ending with service.
+ */
+ public static final String REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE = ".+Service";
+
+ /**
+ * Static attribute for class syntax.
+ */
+ public static final String CLASS = "class";
+
+ /**
+ * Static attribute for builder syntax.
+ */
+ public static final String BUILDER = "Builder";
+
+ /**
+ * Static attribute for manager syntax.
+ */
+ public static final String MANAGER = "Manager";
+
+ /**
+ * Static attribute for service syntax.
+ */
+ public static final String SERVICE = "Service";
+
+ /**
+ * Static attribute for interface syntax.
+ */
+ public static final String INTERFACE = "interface";
+
+ /**
+ * Static attribute for enum syntax.
+ */
+ public static final String ENUM = "enum";
+
+ /**
+ * Static attribute for type syntax.
+ */
+ public static final String TYPE = "Type";
+
+ /**
+ * Static attribute for static syntax.
+ */
+ public static final String STATIC = "static";
+
+ /**
+ * Static attribute for final syntax.
+ */
+ public static final String FINAL = "final";
+
+ /**
+ * Static attribute for package syntax.
+ */
+ public static final String PACKAGE = "package";
+
+ /**
+ * Static attribute for import syntax.
+ */
+ public static final String IMPORT = "import ";
+
+ /**
+ * Static attribute for null syntax.
+ */
+ public static final String NULL = "null";
+
+ /**
+ * Static attribute for return syntax.
+ */
+ public static final String RETURN = "return";
+
+ /**
+ * Static attribute for java new syntax.
+ */
+ public static final String NEW = "new";
+
+ /**
+ * Static attribute for this syntax.
+ */
+ public static final String THIS = "this";
+
+ /**
+ * Static attribute for implements syntax.
+ */
+ public static final String IMPLEMENTS = "implements";
+
+ /**
+ * Static attribute for extends syntax.
+ */
+ public static final String EXTEND = "extends";
+
+ /**
+ * Static attribute for service interface suffix syntax.
+ */
+ public static final String SERVICE_METHOD_STRING = "Service";
+
+ /**
+ * For event file generation.
+ */
+ public static final String EVENT_STRING = "Event";
+
+ /**
+ * For event listener file generation.
+ */
+ public static final String EVENT_LISTENER_STRING = "Listener";
+
+ /**
+ * For event subject file generation.
+ */
+ public static final String EVENT_SUBJECT_NAME_SUFFIX = "EventSubject";
+
+ /**
+ * Static attribute for impl syntax.
+ */
+ public static final String IMPL = "Impl";
+
+ /**
+ * Static attribute for build method syntax.
+ */
+ public static final String BUILD = "build";
+
+ /**
+ * Static attribute for object.
+ */
+ public static final String OBJECT = "Object";
+
+ /**
+ * Static attribute for override annotation.
+ */
+ public static final String OVERRIDE = "@Override";
+
+ /**
+ * Static attribute for new line.
+ */
+ public static final String COLLECTION_IMPORTS = "java.util";
+
+ /**
+ * Static attribute for more object import package.
+ */
+ public static final String GOOGLE_MORE_OBJECT_IMPORT_PKG = "com.google.common.base";
+
+ /**
+ * Static attribute for more object import class.
+ */
+ public static final String GOOGLE_MORE_OBJECT_IMPORT_CLASS = "MoreObjects;\n";
+
+ /**
+ * Static attribute for to string method.
+ */
+ public static final String GOOGLE_MORE_OBJECT_METHOD_STRING = " MoreObjects.toStringHelper(getClass())";
+
+ /**
+ * Static attribute for java utilities import package.
+ */
+ public static final String JAVA_UTIL_OBJECTS_IMPORT_PKG = "java.util";
+
+ /**
+ * Static attribute for java utilities objects import class.
+ */
+ public static final String JAVA_UTIL_OBJECTS_IMPORT_CLASS = "Objects;\n";
+
+ /**
+ * Static attribute for AugmentationHolder class import package.
+ */
+ public static final String PROVIDED_AUGMENTATION_CLASS_IMPORT_PKG =
+ "org.onosproject.yangutils.utils";
+
+ /**
+ * Static attribute for AugmentationHolder class import class.
+ */
+ public static final String AUGMENTATION_HOLDER_CLASS_IMPORT_CLASS = "AugmentationHolder;\n";
+
+ /**
+ * Static attribute for AugmentedInfo class import package.
+ */
+ public static final String AUGMENTED_INFO_CLASS_IMPORT_PKG = "org.onosproject.yangutils.utils";
+
+ /**
+ * Static attribute for AugmentedInfo class import class.
+ */
+ public static final String AUGMENTED_INFO_CLASS_IMPORT_CLASS = "AugmentedInfo;\n";
+
+ /**
+ * Static attribute for augmentation class.
+ */
+ public static final String AUGMENTATION = "Augmentation";
+
+ /**
+ * Static attribute for AugmentationHolder class.
+ */
+ public static final String AUGMENTATION_HOLDER = "AugmentationHolder";
+
+ /**
+ * Static attribute for AugmentedInfo class.
+ */
+ public static final String AUGMENTED_INFO = "AugmentedInfo";
+
+ /**
+ * Static attribute for augmentable.
+ */
+ public static final String AUGMENTABLE = "Augmentable";
+
+ /**
+ * Static attribute for list.
+ */
+ public static final String LIST = "List";
+
+ /**
+ * Static attribute for array list.
+ */
+ public static final String ARRAY_LIST = "ArrayList";
+
+ /**
+ * Comment to be added for autogenerated impl methods.
+ */
+ public static final String YANG_UTILS_TODO = "//TODO: YANG utils generated code";
+
+ /**
+ * Static attribute for activate annotation.
+ */
+ public static final String ACTIVATE_ANNOTATION = "@Activate\n";
+
+ /**
+ * Static attribute for activate.
+ */
+ public static final String ACTIVATE = "activate";
+
+ /**
+ * Static attribute for activate annotation import.
+ */
+ public static final String ACTIVATE_ANNOTATION_IMPORT = "import org.apache.felix.scr.annotations.Activate;\n";
+
+ /**
+ * Static attribute for deactivate annotation.
+ */
+ public static final String DEACTIVATE_ANNOTATION = "@Deactivate\n";
+
+ /**
+ * Static attribute for deactivate.
+ */
+ public static final String DEACTIVATE = "deactivate";
+
+ /**
+ * Static attribute for deactivate annotation import.
+ */
+ public static final String DEACTIVATE_ANNOTATION_IMPORT =
+ "import org.apache.felix.scr.annotations.Deactivate;\n";
+
+ /**
+ * Static attribute for component annotation.
+ */
+ public static final String COMPONENT_ANNOTATION = "@Component";
+
+ /**
+ * Static attribute for component.
+ */
+ public static final String COMPONENT = "Component";
+
+ /**
+ * Static attribute for immediate.
+ */
+ public static final String IMMEDIATE = "immediate";
+
+ /**
+ * Static attribute for component annotation import.
+ */
+ public static final String COMPONENT_ANNOTATION_IMPORT =
+ "import org.apache.felix.scr.annotations.Component;\n";
+
+ /**
+ * Static attribute for service annotation.
+ */
+ public static final String SERVICE_ANNOTATION = "@Service\n";
+
+ /**
+ * Static attribute for service annotation import.
+ */
+ public static final String SERVICE_ANNOTATION_IMPORT =
+ "import org.apache.felix.scr.annotations.Service;\n";
+
+ /**
+ * Static attribute for logger factory import.
+ */
+ public static final String LOGGER_FACTORY_IMPORT =
+ "import static org.slf4j.LoggerFactory.getLogger;\n";
+
+ /**
+ * Static attribute for logger import.
+ */
+ public static final String LOGGER_IMPORT =
+ "import org.slf4j.Logger;\n";
+
+ /**
+ * Static attribute for logger statement.
+ */
+ public static final String LOGGER_STATEMENT =
+ "\n private final Logger log = getLogger(getClass());\n";
+
+ /**
+ * Static attribute for logger statement for started.
+ */
+ public static final String STARTED_LOG_INFO =
+ "log.info(\"Started\");\n";
+
+ /**
+ * Static attribute for logger statement for stopped.
+ */
+ public static final String STOPPED_LOG_INFO =
+ "log.info(\"Stopped\");\n";
+
+ /**
+ * Static attribute for AbstractEvent.
+ */
+ public static final String ABSTRACT_EVENT = "AbstractEvent";
+
+ /**
+ * Static attribute for EventListener.
+ */
+ public static final String EVENT_LISTENER = "EventListener";
+
+ /**
+ * Static attribute for YangBinary class.
+ */
+ public static final String YANG_BINARY_CLASS = "YangBinary";
+
+ /**
+ * Static attribute for YangBinary class.
+ */
+ public static final String YANG_BITS_CLASS = "YangBits";
+
+ /**
+ * Static attribute for YANG types package.
+ */
+ public static final String YANG_TYPES_PKG = "org.onosproject.yangutils.datamodel.utils.builtindatatype";
+
+ /**
+ * Static attribute for MathContext class.
+ */
+ public static final String MATH_CONTEXT = "MathContext";
+
+ /**
+ * Static attribute for DECIMAL64 class.
+ */
+ public static final String YANG_DECIMAL64_CLASS = "YangDecimal64";
+
+
+ /**
+ * Static attribute for YANG file error.
+ */
+ public static final String YANG_FILE_ERROR = "YANG file error : ";
+
+ /**
+ * Static attribute for unsupported error information.
+ */
+ public static final String UNSUPPORTED_YANG_CONSTRUCT = " is not supported.";
+
+ /**
+ * Static attribute for currently unsupported error information.
+ */
+ public static final String CURRENTLY_UNSUPPORTED = " is not supported in current version, please check wiki" +
+ " for YANG utils road map.";
+
+ /**
+ * Static attribute for typedef linker error information.
+ */
+ public static final String TYPEDEF_LINKER_ERROR = "YANG file error: Unable to find base "
+ + "typedef for given type";
+
+ /**
+ * Static attribute for grouping linker error information.
+ */
+ public static final String GROUPING_LINKER_ERROR = "YANG file error: Unable to find base "
+ + "grouping for given uses";
+
+ /**
+ * Static attribute for reference.
+ */
+ public static final String REFERENCE = "Reference";
+
+ /**
+ * Static attribute for ReferenceCardinality.
+ */
+ public static final String REFERENCE_CARDINALITY = "ReferenceCardinality";
+
+ /**
+ * Static attribute for jar.
+ */
+ public static final String JAR = "jar";
+
+ /**
+ * Creates an instance of util constants.
+ */
+ private UtilConstants() {
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/CopyrightHeader.java b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/CopyrightHeader.java
new file mode 100644
index 0000000..5833de2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/CopyrightHeader.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.utils.io.impl;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Calendar;
+
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+
+/**
+ * Represents the license header for the generated files.
+ */
+public final class CopyrightHeader {
+
+ private static final int EOF = -1;
+ private static final String COPYRIGHT_HEADER_FILE = "CopyrightHeader.txt";
+ private static final String COPYRIGHTS_FIRST_LINE = "/*\n * Copyright " + Calendar.getInstance().get(Calendar.YEAR)
+ + "-present Open Networking Laboratory\n";
+ private static final String TEMP_FILE = "temp.txt";
+ private static ClassLoader classLoader = CopyrightHeader.class.getClassLoader();
+
+ private static String copyrightHeader;
+
+ /**
+ * Creates an instance of copyright header.
+ */
+ private CopyrightHeader() {
+ }
+
+ /**
+ * Returns copyright file header.
+ *
+ * @return copyright file header
+ * @throws IOException when fails to parse copyright header
+ */
+ public static String getCopyrightHeader() throws IOException {
+
+ if (copyrightHeader == null) {
+ parseCopyrightHeader();
+ }
+ return copyrightHeader;
+ }
+
+ /**
+ * Sets the copyright header.
+ *
+ * @param header copyright header
+ */
+ private static void setCopyrightHeader(String header) {
+
+ copyrightHeader = header;
+ }
+
+ /**
+ * parses Copyright to the temporary file.
+ *
+ * @throws IOException when fails to get the copyright header
+ */
+ private static void parseCopyrightHeader() throws IOException {
+
+ File temp = new File(TEMP_FILE);
+
+ try {
+ InputStream stream = classLoader.getResourceAsStream(COPYRIGHT_HEADER_FILE);
+ OutputStream out = new FileOutputStream(temp);
+
+ int index;
+ out.write(COPYRIGHTS_FIRST_LINE.getBytes());
+ while ((index = stream.read()) != EOF) {
+ out.write(index);
+ }
+ out.close();
+ stream.close();
+ getStringFileContent(temp);
+ setCopyrightHeader(getStringFileContent(temp));
+ } catch (IOException e) {
+ throw new IOException("failed to parse the Copyright header");
+ } finally {
+ temp.delete();
+ }
+ }
+
+ /**
+ * Converts it to string.
+ *
+ * @param toAppend file to be converted.
+ * @return string of file.
+ * @throws IOException when fails to convert to string
+ */
+ private static String getStringFileContent(File toAppend) throws IOException {
+
+ FileReader fileReader = new FileReader(toAppend);
+ BufferedReader bufferReader = new BufferedReader(fileReader);
+ try {
+ StringBuilder stringBuilder = new StringBuilder();
+ String line = bufferReader.readLine();
+
+ while (line != null) {
+ stringBuilder.append(line);
+ stringBuilder.append(NEW_LINE);
+ line = bufferReader.readLine();
+ }
+ return stringBuilder.toString();
+ } finally {
+ fileReader.close();
+ bufferReader.close();
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/FileSystemUtil.java b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/FileSystemUtil.java
new file mode 100644
index 0000000..7ae17d4
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/FileSystemUtil.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.utils.io.impl;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.translator.exception.TranslatorException;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
+import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
+
+import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.getParentNodeInGenCode;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getJavaPackageFromPackagePath;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
+import static org.onosproject.yangutils.utils.UtilConstants.EIGHT_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.MULTIPLE_NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.addPackageInfo;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.createDirectories;
+import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getAbsolutePackagePath;
+
+/**
+ * Represents utility to handle file system operations.
+ */
+public final class FileSystemUtil {
+
+ /**
+ * Creates an instance of file system util.
+ */
+ private FileSystemUtil() {
+ }
+
+ /**
+ * Checks if the package directory structure created.
+ *
+ * @param pkg Package to check if it is created
+ * @return existence status of package
+ */
+ public static boolean doesPackageExist(String pkg) {
+ File pkgDir = new File(getPackageDirPathFromJavaJPackage(pkg));
+ File pkgWithFile = new File(pkgDir + SLASH + "package-info.java");
+ return pkgDir.exists() && pkgWithFile.isFile();
+ }
+
+ /**
+ * Creates a package structure with package info java file if not present.
+ *
+ * @param yangNode YANG node for which code is being generated
+ * @throws IOException any IO exception
+ */
+ public static void createPackage(YangNode yangNode) throws IOException {
+ if (!(yangNode instanceof JavaFileInfoContainer)) {
+ throw new TranslatorException("current node must have java file info");
+ }
+ String pkgInfo;
+ JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) yangNode).getJavaFileInfo();
+ String pkg = getAbsolutePackagePath(javaFileInfo.getBaseCodeGenPath(), javaFileInfo.getPackageFilePath());
+ if (!doesPackageExist(pkg)) {
+ try {
+ File pack = createDirectories(pkg);
+ YangNode parent = getParentNodeInGenCode(yangNode);
+ if (parent != null) {
+ pkgInfo = ((JavaFileInfoContainer) parent).getJavaFileInfo().getJavaName();
+ addPackageInfo(pack, pkgInfo, getJavaPackageFromPackagePath(pkg), true,
+ ((JavaFileInfoContainer) parent).getJavaFileInfo().getPluginConfig());
+ } else {
+ pkgInfo = ((JavaFileInfoContainer) yangNode).getJavaFileInfo().getJavaName();
+ addPackageInfo(pack, pkgInfo, getJavaPackageFromPackagePath(pkg), false,
+ ((JavaFileInfoContainer) yangNode).getJavaFileInfo().getPluginConfig());
+ }
+ } catch (IOException e) {
+ throw new IOException("failed to create package-info file");
+ }
+ }
+ }
+
+ /**
+ * Reads the contents from source file and append its contents to append
+ * file.
+ *
+ * @param toAppend destination file in which the contents of source file is
+ * appended
+ * @param srcFile source file from which data is read and added to to append
+ * file
+ * @throws IOException any IO errors
+ */
+ public static void appendFileContents(File toAppend, File srcFile)
+ throws IOException {
+ updateFileHandle(srcFile, NEW_LINE + readAppendFile(toAppend.toString(), FOUR_SPACE_INDENTATION), false);
+ }
+
+ /**
+ * Reads file and convert it to string.
+ *
+ * @param toAppend file to be converted
+ * @param spaces spaces to be appended
+ * @return string of file
+ * @throws IOException when fails to convert to string
+ */
+ public static String readAppendFile(String toAppend, String spaces)
+ throws IOException {
+
+ FileReader fileReader = new FileReader(toAppend);
+ BufferedReader bufferReader = new BufferedReader(fileReader);
+ try {
+ StringBuilder stringBuilder = new StringBuilder();
+ String line = bufferReader.readLine();
+
+ while (line != null) {
+ if (line.equals(SPACE) || line.equals(EMPTY_STRING) || line.equals(EIGHT_SPACE_INDENTATION)
+ || line.equals(MULTIPLE_NEW_LINE)) {
+ stringBuilder.append(NEW_LINE);
+ } else if (line.equals(FOUR_SPACE_INDENTATION)) {
+ stringBuilder.append(EMPTY_STRING);
+ } else {
+ stringBuilder.append(spaces + line);
+ stringBuilder.append(NEW_LINE);
+ }
+ line = bufferReader.readLine();
+ }
+ return stringBuilder.toString();
+ } finally {
+ fileReader.close();
+ bufferReader.close();
+ }
+ }
+
+ /**
+ * Updates the generated file handle.
+ *
+ * @param inputFile input file
+ * @param contentTobeAdded content to be appended to the file
+ * @param isClose when close of file is called.
+ * @throws IOException if the named file exists but is a directory rather than a regular file,
+ * does not exist but cannot be created, or cannot be opened for any other reason
+ */
+ public static void updateFileHandle(File inputFile, String contentTobeAdded, boolean isClose)
+ throws IOException {
+
+ List<FileWriter> fileWriterStore = new ArrayList<>();
+
+ FileWriter fileWriter = new FileWriter(inputFile, true);
+ fileWriterStore.add(fileWriter);
+ PrintWriter outputPrintWriter = new PrintWriter(fileWriter, true);
+ if (!isClose) {
+ outputPrintWriter.write(contentTobeAdded);
+ outputPrintWriter.flush();
+ outputPrintWriter.close();
+ } else {
+ for (FileWriter curWriter : fileWriterStore) {
+ curWriter.flush();
+ curWriter.close();
+ curWriter = null;
+ }
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/JavaDocGen.java b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/JavaDocGen.java
new file mode 100644
index 0000000..fb8f981
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/JavaDocGen.java
@@ -0,0 +1,602 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.utils.io.impl;
+
+import org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER_CLASS_JAVA_DOC;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER_INTERFACE_JAVA_DOC;
+import static org.onosproject.yangutils.utils.UtilConstants.BUILDER_OBJECT;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.ENUM_ATTRIBUTE_JAVADOC;
+import static org.onosproject.yangutils.utils.UtilConstants.ENUM_CLASS_JAVADOC;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_JAVA_DOC;
+import static org.onosproject.yangutils.utils.UtilConstants.EVENT_LISTENER_JAVA_DOC;
+import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.FROM_STRING_METHOD_NAME;
+import static org.onosproject.yangutils.utils.UtilConstants.FROM_STRING_PARAM_NAME;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPL;
+import static org.onosproject.yangutils.utils.UtilConstants.IMPL_CLASS_JAVA_DOC;
+import static org.onosproject.yangutils.utils.UtilConstants.INPUT;
+import static org.onosproject.yangutils.utils.UtilConstants.INTERFACE_JAVA_DOC;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_BUILD;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_BUILD_RETURN;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_CONSTRUCTOR;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_END_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_FIRST_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_GETTERS;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_MANAGER_SETTERS;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_OF;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_PARAM;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_RETURN;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_RPC;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_SETTERS;
+import static org.onosproject.yangutils.utils.UtilConstants.JAVA_DOC_SETTERS_COMMON;
+import static org.onosproject.yangutils.utils.UtilConstants.LIST;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE_ASTERISK;
+import static org.onosproject.yangutils.utils.UtilConstants.OBJECT;
+import static org.onosproject.yangutils.utils.UtilConstants.OF;
+import static org.onosproject.yangutils.utils.UtilConstants.PACKAGE_INFO_JAVADOC;
+import static org.onosproject.yangutils.utils.UtilConstants.PACKAGE_INFO_JAVADOC_OF_CHILD;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.RPC_INPUT_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.RPC_OUTPUT_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.UtilConstants.STRING_DATA_TYPE;
+import static org.onosproject.yangutils.utils.UtilConstants.VALUE;
+import static org.onosproject.yangutils.utils.UtilConstants.VOID;
+
+/**
+ * Represents javadoc for the generated classes.
+ */
+public final class JavaDocGen {
+
+ /**
+ * Creates an instance of java doc gen.
+ */
+ private JavaDocGen() {
+ }
+
+ /**
+ * JavaDocs types.
+ */
+ public enum JavaDocType {
+
+ /**
+ * For class.
+ */
+ IMPL_CLASS,
+
+ /**
+ * For builder class.
+ */
+ BUILDER_CLASS,
+
+ /**
+ * For interface.
+ */
+ INTERFACE,
+
+ /**
+ * For builder interface.
+ */
+ BUILDER_INTERFACE,
+
+ /**
+ * For package-info.
+ */
+ PACKAGE_INFO,
+
+ /**
+ * For getters.
+ */
+ GETTER_METHOD,
+
+ /**
+ * For rpc service.
+ */
+ RPC_INTERFACE,
+
+ /**
+ * For rpc manager.
+ */
+ RPC_MANAGER,
+
+ /**
+ * For event.
+ */
+ EVENT,
+
+ /**
+ * For event listener.
+ */
+ EVENT_LISTENER,
+
+ /**
+ * For setters.
+ */
+ SETTER_METHOD,
+
+ /**
+ * For type def's setters.
+ */
+ TYPE_DEF_SETTER_METHOD,
+
+ /**
+ * For of method.
+ */
+ OF_METHOD,
+
+ /**
+ * For default constructor.
+ */
+ DEFAULT_CONSTRUCTOR,
+
+ /**
+ * For constructor.
+ */
+ CONSTRUCTOR,
+
+ /**
+ * For from method.
+ */
+ FROM_METHOD,
+
+ /**
+ * For type constructor.
+ */
+ TYPE_CONSTRUCTOR,
+
+ /**
+ * For build.
+ */
+ BUILD_METHOD,
+
+ /**
+ * For enum.
+ */
+ ENUM_CLASS,
+
+ /**
+ * For enum's attributes.
+ */
+ ENUM_ATTRIBUTE,
+
+ /**
+ * For manager setters.
+ */
+ MANAGER_SETTER_METHOD,
+
+ /**
+ * For event subject.
+ */
+ EVENT_SUBJECT_CLASS
+ }
+
+ /**
+ * Returns java docs.
+ *
+ * @param type java doc type
+ * @param name name of the YangNode
+ * @param isList is list attribute
+ * @param pluginConfig plugin configurations
+ * @return javadocs.
+ */
+ public static String getJavaDoc(JavaDocType type, String name, boolean isList, YangPluginConfig pluginConfig) {
+
+ name = JavaIdentifierSyntax.getSmallCase(getCamelCase(name, pluginConfig.getConflictResolver()));
+ switch (type) {
+ case IMPL_CLASS: {
+ return generateForClass(name);
+ }
+ case BUILDER_CLASS: {
+ return generateForBuilderClass(name);
+ }
+ case INTERFACE: {
+ return generateForInterface(name);
+ }
+ case BUILDER_INTERFACE: {
+ return generateForBuilderInterface(name);
+ }
+ case PACKAGE_INFO: {
+ return generateForPackage(name, isList);
+ }
+ case GETTER_METHOD: {
+ return generateForGetters(name, isList);
+ }
+ case TYPE_DEF_SETTER_METHOD: {
+ return generateForTypeDefSetter(name);
+ }
+ case SETTER_METHOD: {
+ return generateForSetters(name, isList);
+ }
+ case MANAGER_SETTER_METHOD: {
+ return generateForManagerSetters(name, isList);
+ }
+ case OF_METHOD: {
+ return generateForOf(name);
+ }
+ case DEFAULT_CONSTRUCTOR: {
+ return generateForDefaultConstructors(name);
+ }
+ case BUILD_METHOD: {
+ return generateForBuild(name);
+ }
+ case TYPE_CONSTRUCTOR: {
+ return generateForTypeConstructor(name);
+ }
+ case FROM_METHOD: {
+ return generateForFromString(name);
+ }
+ case ENUM_CLASS: {
+ return generateForEnum(name);
+ }
+ case ENUM_ATTRIBUTE: {
+ return generateForEnumAttr(name);
+ }
+ case RPC_INTERFACE: {
+ return generateForRpcService(name);
+ }
+ case RPC_MANAGER: {
+ return generateForClass(name);
+ }
+ case EVENT: {
+ return generateForEvent(name);
+ }
+ case EVENT_LISTENER: {
+ return generateForEventListener(name);
+ }
+ case EVENT_SUBJECT_CLASS: {
+ return generateForClass(name);
+ }
+ default: {
+ return generateForConstructors(name);
+ }
+ }
+ }
+
+ /**
+ * Generates javaDocs for enum's attributes.
+ *
+ * @param name attribute name
+ * @return javaDocs
+ */
+ private static String generateForEnumAttr(String name) {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION + ENUM_ATTRIBUTE_JAVADOC
+ + name + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for rpc method.
+ *
+ * @param rpcName name of the rpc
+ * @param inputName name of input
+ * @param outputName name of output
+ * @param pluginConfig plugin configurations
+ * @return javaDocs of rpc method
+ */
+ public static String generateJavaDocForRpc(String rpcName, String inputName, String outputName,
+ YangPluginConfig pluginConfig) {
+ rpcName = getCamelCase(rpcName, pluginConfig.getConflictResolver());
+
+ String javadoc =
+ NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_RPC
+ + rpcName + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK;
+ if (!inputName.equals(EMPTY_STRING)) {
+ javadoc = javadoc + getInputString(inputName, rpcName);
+ }
+ if (!outputName.equals(VOID)) {
+ javadoc = javadoc + getOutputString(outputName, rpcName);
+ }
+ return javadoc + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Returns output string of rpc.
+ *
+ * @param outputName name of output
+ * @param rpcName name of rpc
+ * @return javaDocs for output string of rpc
+ */
+ private static String getOutputString(String outputName, String rpcName) {
+ return FOUR_SPACE_INDENTATION + JAVA_DOC_RETURN + outputName + SPACE + RPC_OUTPUT_STRING + rpcName + NEW_LINE;
+ }
+
+ /**
+ * Returns input string of rpc.
+ *
+ * @param inputName name of input
+ * @param rpcName name of rpc
+ * @return javaDocs for input string of rpc
+ */
+ private static String getInputString(String inputName, String rpcName) {
+ if (inputName.equals("")) {
+ return null;
+ } else {
+ return FOUR_SPACE_INDENTATION + JAVA_DOC_PARAM + inputName + SPACE + RPC_INPUT_STRING + rpcName + NEW_LINE;
+ }
+ }
+
+ /**
+ * Generates javaDoc for the interface.
+ *
+ * @param interfaceName interface name
+ * @return javaDocs
+ */
+ private static String generateForRpcService(String interfaceName) {
+ return NEW_LINE + JAVA_DOC_FIRST_LINE + INTERFACE_JAVA_DOC + interfaceName + PERIOD + NEW_LINE
+ + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDoc for the event.
+ *
+ * @param eventClassName event class name
+ * @return javaDocs
+ */
+ private static String generateForEvent(String eventClassName) {
+ return NEW_LINE + JAVA_DOC_FIRST_LINE + EVENT_JAVA_DOC + eventClassName + PERIOD + NEW_LINE
+ + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDoc for the event listener.
+ *
+ * @param eventListenerInterfaceName event class name
+ * @return javaDocs
+ */
+ private static String generateForEventListener(String eventListenerInterfaceName) {
+ return NEW_LINE + JAVA_DOC_FIRST_LINE + EVENT_LISTENER_JAVA_DOC + eventListenerInterfaceName
+ + PERIOD + NEW_LINE + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for getter method.
+ *
+ * @param attribute attribute
+ * @param isList is list attribute
+ * @return javaDocs
+ */
+ private static String generateForGetters(String attribute, boolean isList) {
+
+ String getter = NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION
+ + JAVA_DOC_GETTERS + attribute + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_RETURN;
+ if (isList) {
+ String listAttribute = LIST.toLowerCase() + SPACE + OF + SPACE;
+ getter = getter + listAttribute;
+ } else {
+ getter = getter + VALUE + SPACE + OF + SPACE;
+ }
+
+ getter = getter + attribute + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ return getter;
+ }
+
+ /**
+ * Generates javaDocs for setter method.
+ *
+ * @param attribute attribute
+ * @param isList is list attribute
+ * @return javaDocs
+ */
+ private static String generateForSetters(String attribute, boolean isList) {
+
+ String setter = NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION
+ + JAVA_DOC_SETTERS + attribute + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_PARAM + attribute + SPACE;
+ if (isList) {
+ String listAttribute = LIST.toLowerCase() + SPACE + OF + SPACE;
+ setter = setter + listAttribute;
+ } else {
+ setter = setter + VALUE + SPACE + OF + SPACE;
+ }
+ setter = setter + attribute + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_RETURN + BUILDER_OBJECT
+ + attribute
+ + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ return setter;
+ }
+
+ /**
+ * Generates javaDocs for setter method.
+ *
+ * @param attribute attribute
+ * @param isList is list attribute
+ * @return javaDocs
+ */
+ private static String generateForManagerSetters(String attribute, boolean isList) {
+
+ String setter = NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION
+ + JAVA_DOC_MANAGER_SETTERS + attribute + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_PARAM + attribute + SPACE;
+ if (isList) {
+ String listAttribute = LIST.toLowerCase() + SPACE + OF + SPACE;
+ setter = setter + listAttribute;
+ } else {
+ setter = setter + VALUE + SPACE + OF + SPACE;
+ }
+ setter = setter + attribute
+ + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ return setter;
+ }
+
+ /**
+ * Generates javaDocs for of method.
+ *
+ * @param attribute attribute
+ * @return javaDocs
+ */
+ private static String generateForOf(String attribute) {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_OF
+ + attribute + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK + FOUR_SPACE_INDENTATION
+ + JAVA_DOC_PARAM + VALUE + SPACE + VALUE + SPACE + OF + SPACE + attribute + NEW_LINE
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_RETURN + OBJECT + SPACE + OF + SPACE + attribute + NEW_LINE
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for from method.
+ *
+ * @param attribute attribute
+ * @return javaDocs
+ */
+ private static String generateForFromString(String attribute) {
+
+ return NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_OF
+ + attribute + SPACE + FROM_STRING_METHOD_NAME + SPACE + INPUT + SPACE + STRING_DATA_TYPE + PERIOD
+ + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK + FOUR_SPACE_INDENTATION + JAVA_DOC_PARAM
+ + FROM_STRING_PARAM_NAME + SPACE + INPUT + SPACE + STRING_DATA_TYPE + NEW_LINE
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_RETURN + OBJECT + SPACE + OF + SPACE + attribute + NEW_LINE
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for typedef setter method.
+ *
+ * @param attribute attribute
+ * @return javaDocs
+ */
+ private static String generateForTypeDefSetter(String attribute) {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION
+ + JAVA_DOC_SETTERS_COMMON + attribute + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_PARAM + VALUE + SPACE + VALUE + SPACE + OF + SPACE + attribute
+ + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for the impl class.
+ *
+ * @param className class name
+ * @return javaDocs
+ */
+ private static String generateForClass(String className) {
+ return NEW_LINE + JAVA_DOC_FIRST_LINE + IMPL_CLASS_JAVA_DOC + className + PERIOD + NEW_LINE + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for enum.
+ *
+ * @param className enum class name
+ * @return javaDocs
+ */
+ private static String generateForEnum(String className) {
+ return NEW_LINE + NEW_LINE + JAVA_DOC_FIRST_LINE + ENUM_CLASS_JAVADOC + className + PERIOD + NEW_LINE
+ + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for the builder class.
+ *
+ * @param className class name
+ * @return javaDocs
+ */
+ private static String generateForBuilderClass(String className) {
+ return NEW_LINE + JAVA_DOC_FIRST_LINE + BUILDER_CLASS_JAVA_DOC + className + PERIOD + NEW_LINE
+ + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDoc for the interface.
+ *
+ * @param interfaceName interface name
+ * @return javaDocs
+ */
+ private static String generateForInterface(String interfaceName) {
+ return NEW_LINE + JAVA_DOC_FIRST_LINE + INTERFACE_JAVA_DOC + interfaceName + PERIOD + NEW_LINE
+ + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDoc for the builder interface.
+ *
+ * @param builderforName builder for name
+ * @return javaDocs
+ */
+ private static String generateForBuilderInterface(String builderforName) {
+ return JAVA_DOC_FIRST_LINE + BUILDER_INTERFACE_JAVA_DOC + builderforName + PERIOD + NEW_LINE
+ + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for package-info.
+ *
+ * @param packageName package name
+ * @param isChildNode is it child node
+ * @return javaDocs
+ */
+ private static String generateForPackage(String packageName, boolean isChildNode) {
+ String javaDoc = JAVA_DOC_FIRST_LINE + PACKAGE_INFO_JAVADOC + packageName;
+ if (isChildNode) {
+ javaDoc = javaDoc + PACKAGE_INFO_JAVADOC_OF_CHILD;
+ }
+ return javaDoc + PERIOD + NEW_LINE + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for default constructor.
+ *
+ * @param className class name
+ * @return javaDocs
+ */
+ private static String generateForDefaultConstructors(String className) {
+ return FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_CONSTRUCTOR + className
+ + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for constructor with parameters.
+ *
+ * @param className class name
+ * @return javaDocs
+ */
+ private static String generateForConstructors(String className) {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_CONSTRUCTOR
+ + className + IMPL + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_PARAM + BUILDER.toLowerCase() + OBJECT + SPACE + BUILDER_OBJECT
+ + className + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for build.
+ *
+ * @param buildName builder name
+ * @return javaDocs
+ */
+ private static String generateForBuild(String buildName) {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_BUILD
+ + buildName + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK + FOUR_SPACE_INDENTATION
+ + JAVA_DOC_RETURN + JAVA_DOC_BUILD_RETURN + buildName + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION
+ + JAVA_DOC_END_LINE;
+ }
+
+ /**
+ * Generates javaDocs for type constructor.
+ *
+ * @param attribute attribute string
+ * @return javaDocs for type constructor
+ */
+ private static String generateForTypeConstructor(String attribute) {
+ return NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_FIRST_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_CONSTRUCTOR
+ + attribute + PERIOD + NEW_LINE + FOUR_SPACE_INDENTATION + NEW_LINE_ASTERISK + FOUR_SPACE_INDENTATION
+ + JAVA_DOC_PARAM + VALUE + SPACE + VALUE + SPACE + OF + SPACE + attribute + NEW_LINE
+ + FOUR_SPACE_INDENTATION + JAVA_DOC_END_LINE;
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/YangFileScanner.java b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/YangFileScanner.java
new file mode 100644
index 0000000..ff2e3e7
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/YangFileScanner.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.utils.io.impl;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Stack;
+
+/**
+ * Represents utility for searching the files in a directory.
+ */
+public final class YangFileScanner {
+
+ private static final String JAVA_FILE_EXTENTION = ".java";
+ private static final String YANG_FILE_EXTENTION = ".yang";
+
+ /**
+ * Creates an instance of YANG file scanner.
+ */
+ private YangFileScanner() {
+ }
+
+ /**
+ * Returns the list of java files.
+ *
+ * @param root specified directory
+ * @return list of java files
+ * @throws NullPointerException when no files are there.
+ * @throws IOException when files get deleted while performing the
+ * operations
+ */
+ public static List<String> getJavaFiles(String root) throws IOException {
+
+ return getFiles(root, JAVA_FILE_EXTENTION);
+ }
+
+ /**
+ * Returns the list of YANG file.
+ *
+ * @param root specified directory
+ * @return list of YANG file information
+ * @throws NullPointerException when no files are there
+ * @throws IOException when files get deleted while performing the
+ * operations
+ */
+ public static List<String> getYangFiles(String root) throws IOException {
+
+ return getFiles(root, YANG_FILE_EXTENTION);
+ }
+
+ /**
+ * Returns the list of required files.
+ *
+ * @param root specified directory
+ * @param extension file extension
+ * @return list of required files
+ * @throws NullPointerException when no file is there
+ * @throws IOException when files get deleted while performing the operations
+ */
+ public static List<String> getFiles(String root, String extension) throws IOException {
+
+ List<String> store = new LinkedList<>();
+ Stack<String> stack = new Stack<>();
+ stack.push(root);
+ File file;
+ File[] filelist;
+ try {
+ while (!stack.empty()) {
+ root = stack.pop();
+ file = new File(root);
+ filelist = file.listFiles();
+ if ((filelist == null) || (filelist.length == 0)) {
+ continue;
+ }
+ for (File current : filelist) {
+ if (current.isDirectory()) {
+ stack.push(current.toString());
+ } else {
+ String yangFile = current.getCanonicalPath();
+ if (yangFile.endsWith(extension)) {
+ store.add(yangFile);
+ }
+ }
+ }
+ }
+ return store;
+ } catch (IOException e) {
+ throw new IOException("No File found of " + extension + " extension in " + root + " directory.");
+ }
+ }
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/YangIoUtils.java b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/YangIoUtils.java
new file mode 100644
index 0000000..05cd471
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/YangIoUtils.java
@@ -0,0 +1,673 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.utils.io.impl;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.nio.file.Files;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.Stack;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.regex.Pattern;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.maven.artifact.repository.ArtifactRepository;
+import org.apache.maven.model.Dependency;
+import org.apache.maven.model.Resource;
+import org.apache.maven.project.MavenProject;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.plugin.manager.YangFileInfo;
+import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
+import org.slf4j.Logger;
+import org.sonatype.plexus.build.incremental.BuildContext;
+
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
+import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
+import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
+import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
+import static org.onosproject.yangutils.utils.UtilConstants.HASH;
+import static org.onosproject.yangutils.utils.UtilConstants.HYPHEN;
+import static org.onosproject.yangutils.utils.UtilConstants.JAR;
+import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_PARENTHESIS;
+import static org.onosproject.yangutils.utils.UtilConstants.ORG;
+import static org.onosproject.yangutils.utils.UtilConstants.PACKAGE;
+import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
+import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
+import static org.onosproject.yangutils.utils.UtilConstants.TEMP;
+import static org.onosproject.yangutils.utils.UtilConstants.TWELVE_SPACE_INDENTATION;
+import static org.onosproject.yangutils.utils.UtilConstants.YANG_RESOURCES;
+import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.appendFileContents;
+import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.updateFileHandle;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
+import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.PACKAGE_INFO;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Represents common utility functionalities for code generation.
+ */
+public final class YangIoUtils {
+
+ private static final Logger log = getLogger(YangIoUtils.class);
+ private static final String TARGET_RESOURCE_PATH = SLASH + TEMP + SLASH + YANG_RESOURCES + SLASH;
+ private static final int LINE_SIZE = 118;
+ private static final int SUB_LINE_SIZE = 112;
+ private static final int ZERO = 0;
+ private static final String SERIALIZED_FILE_EXTENSION = ".ser";
+
+ /**
+ * Creates an instance of YANG io utils.
+ */
+ private YangIoUtils() {
+ }
+
+ /**
+ * Creates the directory structure.
+ *
+ * @param path directory path
+ * @return directory structure
+ */
+ public static File createDirectories(String path) {
+ File generatedDir = new File(path);
+ generatedDir.mkdirs();
+ return generatedDir;
+ }
+
+ /**
+ * Adds package info file for the created directory.
+ *
+ * @param path directory path
+ * @param classInfo class info for the package
+ * @param pack package of the directory
+ * @param isChildNode is it a child node
+ * @param pluginConfig plugin configurations
+ * @throws IOException when fails to create package info file
+ */
+ public static void addPackageInfo(File path, String classInfo, String pack, boolean isChildNode,
+ YangPluginConfig pluginConfig)
+ throws IOException {
+
+ pack = parsePkg(pack);
+
+ try {
+
+ File packageInfo = new File(path + SLASH + "package-info.java");
+ packageInfo.createNewFile();
+
+ FileWriter fileWriter = new FileWriter(packageInfo);
+ BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
+
+ bufferedWriter.write(CopyrightHeader.getCopyrightHeader());
+ bufferedWriter.write(getJavaDoc(PACKAGE_INFO, classInfo, isChildNode, pluginConfig));
+ String pkg = PACKAGE + SPACE + pack + SEMI_COLAN;
+ if (pkg.length() > LINE_SIZE) {
+ pkg = whenDelimiterIsPersent(pkg, LINE_SIZE);
+ }
+ bufferedWriter.write(pkg);
+ bufferedWriter.close();
+ fileWriter.close();
+ } catch (IOException e) {
+ throw new IOException("Exception occured while creating package info file.");
+ }
+ }
+
+ /**
+ * Parses package and returns updated package.
+ *
+ * @param pack package needs to be updated
+ * @return updated package
+ */
+ public static String parsePkg(String pack) {
+
+ if (pack.contains(ORG)) {
+ String[] strArray = pack.split(ORG);
+ if (strArray.length >= 3) {
+ for (int i = 1; i < strArray.length; i++) {
+ if (i == 1) {
+ pack = ORG + strArray[1];
+ } else {
+ pack = pack + ORG + strArray[i];
+ }
+ }
+ } else {
+ pack = ORG + strArray[1];
+ }
+ }
+
+ return pack;
+ }
+
+ /**
+ * Cleans the generated directory if already exist in source folder.
+ *
+ * @param dir generated directory in previous build
+ * @throws IOException when failed to delete directory
+ */
+ public static void deleteDirectory(String dir)
+ throws IOException {
+ File generatedDirectory = new File(dir);
+ if (generatedDirectory.exists()) {
+ try {
+ FileUtils.deleteDirectory(generatedDirectory);
+ } catch (IOException e) {
+ throw new IOException(
+ "Failed to delete the generated files in " + generatedDirectory + " directory");
+ }
+ }
+ }
+
+ /**
+ * Searches and deletes generated temporary directories.
+ *
+ * @param root root directory
+ * @throws IOException when fails to do IO operations.
+ */
+ public static void searchAndDeleteTempDir(String root)
+ throws IOException {
+ List<File> store = new LinkedList<>();
+ Stack<String> stack = new Stack<>();
+ stack.push(root);
+
+ while (!stack.empty()) {
+ root = stack.pop();
+ File file = new File(root);
+ File[] filelist = file.listFiles();
+ if (filelist == null || filelist.length == 0) {
+ continue;
+ }
+ for (File current : filelist) {
+ if (current.isDirectory()) {
+ stack.push(current.toString());
+ if (current.getName().endsWith("-Temp")) {
+ store.add(current);
+ }
+ }
+ }
+ }
+
+ for (File dir : store) {
+ FileUtils.deleteDirectory(dir);
+ }
+ }
+
+ /**
+ * Adds generated source directory to the compilation root.
+ *
+ * @param source directory
+ * @param project current maven project
+ * @param context current build context
+ */
+ public static void addToCompilationRoot(String source, MavenProject project, BuildContext context) {
+ project.addCompileSourceRoot(source);
+ context.refresh(project.getBasedir());
+ log.info("Source directory added to compilation root: " + source);
+ }
+
+ /**
+ * Removes extra char from the string.
+ *
+ * @param valueString string to be trimmed
+ * @param removealStirng extra chars
+ * @return new string
+ */
+ public static String trimAtLast(String valueString, String removealStirng) {
+ StringBuilder stringBuilder = new StringBuilder(valueString);
+ int index = valueString.lastIndexOf(removealStirng);
+ stringBuilder.deleteCharAt(index);
+ return stringBuilder.toString();
+ }
+
+ /**
+ * Returns new parted string.
+ *
+ * @param partString string to be parted
+ * @return parted string
+ */
+ public static String partString(String partString) {
+ String[] strArray = partString.split(COMMA);
+ String newString = EMPTY_STRING;
+ for (int i = 0; i < strArray.length; i++) {
+ if (i % 4 != 0 || i == 0) {
+ newString = newString + strArray[i] + COMMA;
+ } else {
+ newString = newString + NEW_LINE + TWELVE_SPACE_INDENTATION
+ + strArray[i] + COMMA;
+ }
+ }
+ return trimAtLast(newString, COMMA);
+ }
+
+ /**
+ * Returns the directory path of the package in canonical form.
+ *
+ * @param baseCodeGenPath base path where the generated files needs to be
+ * put
+ * @param pathOfJavaPkg java package of the file being generated
+ * @return absolute path of the package in canonical form
+ */
+ public static String getDirectory(String baseCodeGenPath, String pathOfJavaPkg) {
+
+ if (pathOfJavaPkg.charAt(pathOfJavaPkg.length() - 1) == File.separatorChar) {
+ pathOfJavaPkg = trimAtLast(pathOfJavaPkg, SLASH);
+ }
+ String[] strArray = pathOfJavaPkg.split(SLASH);
+ if (strArray[0].equals(EMPTY_STRING)) {
+ return pathOfJavaPkg;
+ } else {
+ return baseCodeGenPath + SLASH + pathOfJavaPkg;
+ }
+ }
+
+ /**
+ * Returns the absolute path of the package in canonical form.
+ *
+ * @param baseCodeGenPath base path where the generated files needs to be
+ * put
+ * @param pathOfJavaPkg java package of the file being generated
+ * @return absolute path of the package in canonical form
+ */
+ public static String getAbsolutePackagePath(String baseCodeGenPath, String pathOfJavaPkg) {
+ return baseCodeGenPath + pathOfJavaPkg;
+ }
+
+ /**
+ * Copies YANG files to the current project's output directory.
+ *
+ * @param yangFileInfo list of YANG files
+ * @param outputDir project's output directory
+ * @param project maven project
+ * @throws IOException when fails to copy files to destination resource directory
+ */
+ public static void copyYangFilesToTarget(Set<YangFileInfo> yangFileInfo, String outputDir, MavenProject project)
+ throws IOException {
+
+ List<File> files = getListOfFile(yangFileInfo);
+
+ String path = outputDir + TARGET_RESOURCE_PATH;
+ File targetDir = new File(path);
+ targetDir.mkdirs();
+
+ for (File file : files) {
+ Files.copy(file.toPath(),
+ new File(path + file.getName()).toPath(),
+ StandardCopyOption.REPLACE_EXISTING);
+ }
+ addToProjectResource(outputDir + SLASH + TEMP + SLASH, project);
+ }
+
+ /**
+ * Provides a list of files from list of strings.
+ *
+ * @param yangFileInfo set of yang file information
+ * @return list of files
+ */
+ private static List<File> getListOfFile(Set<YangFileInfo> yangFileInfo) {
+ List<File> files = new ArrayList<>();
+ Iterator<YangFileInfo> yangFileIterator = yangFileInfo.iterator();
+ while (yangFileIterator.hasNext()) {
+ YangFileInfo yangFile = yangFileIterator.next();
+ if (yangFile.isForTranslator()) {
+ files.add(new File(yangFile.getYangFileName()));
+ }
+ }
+ return files;
+ }
+
+ /**
+ * Merges the temp java files to main java files.
+ *
+ * @param appendFile temp file
+ * @param srcFile main file
+ * @throws IOException when fails to append contents
+ */
+ public static void mergeJavaFiles(File appendFile, File srcFile)
+ throws IOException {
+ try {
+ appendFileContents(appendFile, srcFile);
+ } catch (IOException e) {
+ throw new IOException("Failed to append " + appendFile + " in " + srcFile);
+ }
+ }
+
+ /**
+ * Inserts data in the generated file.
+ *
+ * @param file file in which need to be inserted
+ * @param data data which need to be inserted
+ * @throws IOException when fails to insert into file
+ */
+ public static void insertDataIntoJavaFile(File file, String data)
+ throws IOException {
+ try {
+ updateFileHandle(file, data, false);
+ } catch (IOException e) {
+ throw new IOException("Failed to insert in " + file + "file");
+ }
+ }
+
+ /**
+ * Validates a line size in given file whether it is having more then 120 characters.
+ * If yes it will update and give a new file.
+ *
+ * @param dataFile file in which need to verify all lines.
+ * @return updated file
+ * @throws IOException when fails to do IO operations.
+ */
+ public static File validateLineLength(File dataFile)
+ throws IOException {
+ File tempFile = dataFile;
+ FileReader fileReader = new FileReader(dataFile);
+ BufferedReader bufferReader = new BufferedReader(fileReader);
+ try {
+ StringBuilder stringBuilder = new StringBuilder();
+ String line = bufferReader.readLine();
+
+ while (line != null) {
+ if (line.length() > LINE_SIZE) {
+ if (line.contains(PERIOD)) {
+ line = whenDelimiterIsPersent(line, LINE_SIZE);
+ } else if (line.contains(SPACE)) {
+ line = whenSpaceIsPresent(line, LINE_SIZE);
+ }
+ stringBuilder.append(line);
+ } else {
+ stringBuilder.append(line + NEW_LINE);
+ }
+ line = bufferReader.readLine();
+ }
+ FileWriter writer = new FileWriter(tempFile);
+ writer.write(stringBuilder.toString());
+ writer.close();
+ return tempFile;
+ } finally {
+ fileReader.close();
+ bufferReader.close();
+ }
+ }
+
+ /* When delimiters are present in the given line. */
+ private static String whenDelimiterIsPersent(String line, int lineSize) {
+ StringBuilder stringBuilder = new StringBuilder();
+
+ if (line.length() > lineSize) {
+ String[] strArray = line.split(Pattern.quote(PERIOD));
+ stringBuilder = updateString(strArray, stringBuilder, PERIOD, lineSize);
+ } else {
+ stringBuilder.append(line + NEW_LINE);
+ }
+ String[] strArray = stringBuilder.toString().split(NEW_LINE);
+ StringBuilder tempBuilder = new StringBuilder();
+ for (String str : strArray) {
+ if (str.length() > SUB_LINE_SIZE) {
+ if (line.contains(PERIOD) && !line.contains(PERIOD + HASH + OPEN_PARENTHESIS)) {
+ String[] strArr = str.split(Pattern.quote(PERIOD));
+ tempBuilder = updateString(strArr, tempBuilder, PERIOD, SUB_LINE_SIZE);
+ } else if (str.contains(SPACE)) {
+ tempBuilder.append(whenSpaceIsPresent(str, SUB_LINE_SIZE));
+ }
+ } else {
+ tempBuilder.append(str + NEW_LINE);
+ }
+ }
+ return tempBuilder.toString();
+
+ }
+
+ /* When spaces are present in the given line. */
+ private static String whenSpaceIsPresent(String line, int lineSize) {
+ StringBuilder stringBuilder = new StringBuilder();
+ if (line.length() > lineSize) {
+ String[] strArray = line.split(SPACE);
+ stringBuilder = updateString(strArray, stringBuilder, SPACE, lineSize);
+ } else {
+ stringBuilder.append(line + NEW_LINE);
+ }
+
+ String[] strArray = stringBuilder.toString().split(NEW_LINE);
+ StringBuilder tempBuilder = new StringBuilder();
+ for (String str : strArray) {
+ if (str.length() > SUB_LINE_SIZE) {
+ if (str.contains(SPACE)) {
+ String[] strArr = str.split(SPACE);
+ tempBuilder = updateString(strArr, tempBuilder, SPACE, SUB_LINE_SIZE);
+ }
+ } else {
+ tempBuilder.append(str + NEW_LINE);
+ }
+ }
+ return tempBuilder.toString();
+ }
+
+ /* Updates the given line with the given size conditions. */
+ private static StringBuilder updateString(String[] strArray, StringBuilder stringBuilder, String string,
+ int lineSize) {
+
+ StringBuilder tempBuilder = new StringBuilder();
+ for (String str : strArray) {
+ tempBuilder.append(str + string);
+ if (tempBuilder.length() > lineSize) {
+ String tempString = stringBuilder.toString();
+ stringBuilder.delete(ZERO, stringBuilder.length());
+ tempString = trimAtLast(tempString, string);
+ stringBuilder.append(tempString);
+ if (string.equals(PERIOD)) {
+ stringBuilder.append(NEW_LINE + TWELVE_SPACE_INDENTATION + PERIOD + str + string);
+ } else {
+ stringBuilder.append(NEW_LINE + TWELVE_SPACE_INDENTATION + str + string);
+ }
+ tempBuilder.delete(ZERO, tempBuilder.length());
+ tempBuilder.append(TWELVE_SPACE_INDENTATION);
+ } else {
+ stringBuilder.append(str + string);
+ }
+ }
+ String tempString = stringBuilder.toString();
+ tempString = trimAtLast(tempString, string);
+ stringBuilder.delete(ZERO, stringBuilder.length());
+ stringBuilder.append(tempString + NEW_LINE);
+ return stringBuilder;
+ }
+
+ /**
+ * Serializes data-model.
+ *
+ * @param directory base directory for serialized files
+ * @param fileInfoSet YANG file info set
+ * @param project maven project
+ * @param operation true if need to add to resource
+ * @throws IOException when fails to do IO operations
+ */
+ public static void serializeDataModel(String directory, Set<YangFileInfo> fileInfoSet,
+ MavenProject project, boolean operation) throws IOException {
+
+ String serFileDirPath = directory + TARGET_RESOURCE_PATH;
+ File dir = new File(serFileDirPath);
+ dir.mkdirs();
+
+ if (operation) {
+ addToProjectResource(directory + SLASH + TEMP + SLASH, project);
+ }
+
+ for (YangFileInfo fileInfo : fileInfoSet) {
+
+ String serFileName = serFileDirPath + getCamelCase(fileInfo.getRootNode().getName(), null)
+ + SERIALIZED_FILE_EXTENSION;
+ fileInfo.setSerializedFile(serFileName);
+ FileOutputStream fileOutputStream = new FileOutputStream(serFileName);
+ ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
+ objectOutputStream.writeObject(fileInfo.getRootNode());
+ objectOutputStream.close();
+ fileOutputStream.close();
+ }
+ }
+
+ /* Adds directory to resources of project */
+ private static void addToProjectResource(String dir, MavenProject project) {
+ Resource rsc = new Resource();
+ rsc.setDirectory(dir);
+ project.addResource(rsc);
+ }
+
+ /**
+ * Returns de-serializes YANG data-model nodes.
+ *
+ * @param serailizedfileInfoSet YANG file info set
+ * @return de-serializes YANG data-model nodes
+ * @throws IOException when fails do IO operations
+ */
+ public static List<YangNode> deSerializeDataModel(List<String> serailizedfileInfoSet) throws IOException {
+
+ List<YangNode> nodes = new ArrayList<>();
+ for (String fileInfo : serailizedfileInfoSet) {
+ YangNode node = null;
+ try {
+ FileInputStream fileInputStream = new FileInputStream(fileInfo);
+ ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
+ node = (YangNode) objectInputStream.readObject();
+ nodes.add(node);
+ objectInputStream.close();
+ fileInputStream.close();
+ } catch (IOException | ClassNotFoundException e) {
+ throw new IOException(fileInfo + " not found.");
+ }
+ }
+ return nodes;
+ }
+
+ /**
+ * Resolves inter jar dependencies.
+ *
+ * @param project current maven project
+ * @param localRepository local maven repository
+ * @param remoteRepos list of remote repository
+ * @param directory directory for serialized files
+ * @return list of resolved datamodel nodes
+ * @throws IOException when fails to do IO operations
+ */
+ public static List<YangNode> resolveInterJarDependencies(MavenProject project, ArtifactRepository localRepository,
+ List<ArtifactRepository> remoteRepos, String directory) throws IOException {
+
+ List<String> dependeciesJarPaths = resolveDependecyJarPath(project, localRepository, remoteRepos);
+ List<YangNode> resolvedDataModelNodes = new ArrayList<>();
+ for (String dependecy : dependeciesJarPaths) {
+ resolvedDataModelNodes.addAll(deSerializeDataModel(parseJarFile(dependecy, directory)));
+ }
+ return resolvedDataModelNodes;
+ }
+
+ /**
+ * Returns list of jar path.
+ *
+ * @return list of jar paths
+ */
+ private static List<String> resolveDependecyJarPath(MavenProject project, ArtifactRepository localRepository,
+ List<ArtifactRepository> remoteRepos) {
+
+ StringBuilder path = new StringBuilder();
+ List<String> jarPaths = new ArrayList<>();
+ for (Dependency dependency : project.getDependencies()) {
+
+ path.append(localRepository.getBasedir());
+ path.append(SLASH);
+ path.append(getPackageDirPathFromJavaJPackage(dependency.getGroupId()));
+ path.append(SLASH);
+ path.append(dependency.getArtifactId());
+ path.append(SLASH);
+ path.append(dependency.getVersion());
+ path.append(SLASH);
+ path.append(dependency.getArtifactId() + HYPHEN + dependency.getVersion() + PERIOD + JAR);
+ File jarFile = new File(path.toString());
+ if (jarFile.exists()) {
+ jarPaths.add(path.toString());
+ }
+ path.delete(0, path.length());
+ }
+
+ for (ArtifactRepository repo : remoteRepos) {
+ // TODO: add resolver for remote repo.
+ }
+ return jarPaths;
+ }
+
+ /**
+ * Parses jar file and returns list of serialized file names.
+ *
+ * @param jarFile jar file to be parsed
+ * @param directory directory for keeping the searized files
+ * @return list of serialized files
+ * @throws IOException when fails to do IO operations
+ */
+ public static List<String> parseJarFile(String jarFile, String directory)
+ throws IOException {
+
+ List<String> serailizedFiles = new ArrayList<>();
+ JarFile jar = new JarFile(jarFile);
+ Enumeration<?> enumEntries = jar.entries();
+
+ File serializedFileDir = new File(directory);
+ serializedFileDir.mkdirs();
+ while (enumEntries.hasMoreElements()) {
+ JarEntry file = (JarEntry) enumEntries.nextElement();
+ if (file.getName().endsWith(SERIALIZED_FILE_EXTENSION)) {
+ if (file.getName().contains(SLASH)) {
+ String[] strArray = file.getName().split(SLASH);
+ String tempPath = "";
+ for (int i = 0; i < strArray.length - 1; i++) {
+ tempPath = SLASH + tempPath + SLASH + strArray[i];
+ }
+ File dir = new File(directory + tempPath);
+ dir.mkdirs();
+ }
+ File serailizedFile = new File(directory + SLASH + file.getName());
+ if (file.isDirectory()) {
+ serailizedFile.mkdirs();
+ continue;
+ }
+ InputStream inputStream = jar.getInputStream(file);
+
+ FileOutputStream fileOutputStream = new FileOutputStream(serailizedFile);
+ while (inputStream.available() > 0) {
+ fileOutputStream.write(inputStream.read());
+ }
+ fileOutputStream.close();
+ inputStream.close();
+ serailizedFiles.add(serailizedFile.toString());
+ }
+ }
+ jar.close();
+ return serailizedFiles;
+ }
+
+}
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/package-info.java
new file mode 100644
index 0000000..a128fa2
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/io/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * File system utilities implementation.
+ */
+package org.onosproject.yangutils.utils.io.impl;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/io/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/utils/io/package-info.java
new file mode 100644
index 0000000..856653e
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/io/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * File system utilities.
+ */
+package org.onosproject.yangutils.utils.io;
diff --git a/plugin/src/main/java/org/onosproject/yangutils/utils/package-info.java b/plugin/src/main/java/org/onosproject/yangutils/utils/package-info.java
new file mode 100644
index 0000000..2123da0
--- /dev/null
+++ b/plugin/src/main/java/org/onosproject/yangutils/utils/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Utilities for YANG maven plugin.
+ */
+package org.onosproject.yangutils.utils;
diff --git a/plugin/src/main/resources/CopyrightHeader.txt b/plugin/src/main/resources/CopyrightHeader.txt
new file mode 100644
index 0000000..2cbed45
--- /dev/null
+++ b/plugin/src/main/resources/CopyrightHeader.txt
@@ -0,0 +1,14 @@
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
diff --git a/plugin/src/main/resources/GeneratedYang.g4 b/plugin/src/main/resources/GeneratedYang.g4
new file mode 100644
index 0000000..55a7a35
--- /dev/null
+++ b/plugin/src/main/resources/GeneratedYang.g4
@@ -0,0 +1,1299 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This is a YANG grammar for parser based on which ANTLR will generate YANG parser.
+ */
+
+grammar GeneratedYang;
+import YangLexer;
+
+@header {
+package org.onosproject.yangutils.parser.antlrgencode;
+}
+
+ yangfile : moduleStatement EOF
+ | subModuleStatement EOF;
+
+ /**
+ * module-stmt = optsep module-keyword sep identifier-arg-str
+ * optsep
+ * "{" stmtsep
+ * module-header-stmts
+ * linkage-stmts
+ * meta-stmts
+ * revision-stmts
+ * body-stmts
+ * "}" optsep
+ */
+
+ moduleStatement : MODULE_KEYWORD identifier LEFT_CURLY_BRACE moduleBody RIGHT_CURLY_BRACE;
+
+ moduleBody : moduleHeaderStatement linkageStatements metaStatements revisionStatements bodyStatements;
+
+ /**
+ * module-header-stmts = ;; these stmts can appear in any order
+ * [yang-version-stmt stmtsep]
+ * namespace-stmt stmtsep
+ * prefix-stmt stmtsep
+ */
+
+ moduleHeaderStatement : yangVersionStatement? namespaceStatement prefixStatement
+ | yangVersionStatement? prefixStatement namespaceStatement
+ | namespaceStatement yangVersionStatement? prefixStatement
+ | namespaceStatement prefixStatement yangVersionStatement?
+ | prefixStatement namespaceStatement yangVersionStatement?
+ | prefixStatement yangVersionStatement? namespaceStatement
+ ;
+
+ /**
+ * linkage-stmts = ;; these stmts can appear in any order
+ * *(import-stmt stmtsep)
+ * *(include-stmt stmtsep)
+ */
+ linkageStatements : (importStatement
+ | includeStatement)*;
+
+ /**
+ * meta-stmts = ;; these stmts can appear in any order
+ * [organization-stmt stmtsep]
+ * [contact-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ */
+ metaStatements : organizationStatement? contactStatement? descriptionStatement? referenceStatement?
+ | organizationStatement? contactStatement? referenceStatement? descriptionStatement?
+ | organizationStatement? descriptionStatement? contactStatement? referenceStatement?
+ | organizationStatement? descriptionStatement? referenceStatement? contactStatement?
+ | organizationStatement? referenceStatement? contactStatement? descriptionStatement?
+ | organizationStatement? referenceStatement? descriptionStatement? contactStatement?
+ | contactStatement? organizationStatement? descriptionStatement? referenceStatement?
+ | contactStatement? organizationStatement? referenceStatement? descriptionStatement?
+ | contactStatement? referenceStatement? organizationStatement? descriptionStatement?
+ | contactStatement? referenceStatement? descriptionStatement? organizationStatement?
+ | contactStatement? descriptionStatement? referenceStatement? organizationStatement?
+ | contactStatement? descriptionStatement? organizationStatement? referenceStatement?
+ | referenceStatement? contactStatement? organizationStatement? descriptionStatement?
+ | referenceStatement? contactStatement? descriptionStatement? organizationStatement?
+ | referenceStatement? organizationStatement? contactStatement? descriptionStatement?
+ | referenceStatement? organizationStatement? descriptionStatement? contactStatement?
+ | referenceStatement? descriptionStatement? organizationStatement? contactStatement?
+ | referenceStatement? descriptionStatement? contactStatement? organizationStatement?
+ | descriptionStatement? referenceStatement? contactStatement? organizationStatement?
+ | descriptionStatement? referenceStatement? organizationStatement? contactStatement?
+ | descriptionStatement? contactStatement? referenceStatement? organizationStatement?
+ | descriptionStatement? contactStatement? organizationStatement? referenceStatement?
+ | descriptionStatement? organizationStatement? contactStatement? referenceStatement?
+ | descriptionStatement? organizationStatement? referenceStatement? contactStatement?
+ ;
+
+ // revision-stmts = *(revision-stmt stmtsep)
+ revisionStatements : revisionStatement*;
+
+ /**
+ * body-stmts = *((extension-stmt /
+ * feature-stmt /
+ * identity-stmt /
+ * typedef-stmt /
+ * grouping-stmt /
+ * data-def-stmt /
+ * augment-stmt /
+ * rpc-stmt /
+ * notification-stmt /
+ * deviation-stmt) stmtsep)
+ */
+ bodyStatements : (extensionStatement
+ | featureStatement
+ | identityStatement
+ | typedefStatement
+ | groupingStatement
+ | dataDefStatement
+ | augmentStatement
+ | rpcStatement
+ | notificationStatement
+ | deviationStatement)*
+ ;
+
+ /**
+ * yang-version-stmt = yang-version-keyword sep yang-version-arg-str
+ * optsep stmtend
+ */
+ yangVersionStatement : YANG_VERSION_KEYWORD version STMTEND;
+
+
+ /**
+ * namespace-stmt = namespace-keyword sep uri-str optsep stmtend
+ * For namespace validation TODO in Listener
+ */
+ namespaceStatement : NAMESPACE_KEYWORD string STMTEND;
+
+ /**
+ * prefix-stmt = prefix-keyword sep prefix-arg-str
+ * optsep stmtend
+ */
+ prefixStatement : PREFIX_KEYWORD identifier STMTEND;
+
+ /**
+ * import-stmt = import-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * prefix-stmt stmtsep
+ * [revision-date-stmt stmtsep]
+ * "}"
+ */
+ importStatement : IMPORT_KEYWORD identifier LEFT_CURLY_BRACE importStatementBody RIGHT_CURLY_BRACE;
+
+ importStatementBody : prefixStatement revisionDateStatement?;
+
+ // revision-date-stmt = revision-date-keyword sep revision-date stmtend
+ revisionDateStatement : REVISION_DATE_KEYWORD dateArgumentString STMTEND;
+
+ /**
+ * include-stmt = include-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * [revision-date-stmt stmtsep]
+ * "}")
+ */
+ includeStatement : INCLUDE_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE revisionDateStatement? RIGHT_CURLY_BRACE);
+
+ /**
+ * organization-stmt = organization-keyword sep string
+ * optsep stmtend
+ */
+ organizationStatement : ORGANIZATION_KEYWORD string STMTEND;
+
+ // contact-stmt = contact-keyword sep string optsep stmtend
+ contactStatement : CONTACT_KEYWORD string STMTEND;
+
+ // description-stmt = description-keyword sep string optsep stmtend
+ descriptionStatement : DESCRIPTION_KEYWORD string STMTEND;
+
+ // reference-stmt = reference-keyword sep string optsep stmtend
+ referenceStatement : REFERENCE_KEYWORD string STMTEND;
+
+ /**
+ * revision-stmt = revision-keyword sep revision-date optsep
+ * (";" /
+ * "{" stmtsep
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ revisionStatement : REVISION_KEYWORD dateArgumentString (STMTEND | LEFT_CURLY_BRACE revisionStatementBody RIGHT_CURLY_BRACE);
+ revisionStatementBody : descriptionStatement? referenceStatement?;
+
+ /**
+ * submodule-stmt = optsep submodule-keyword sep identifier-arg-str
+ * optsep
+ * "{" stmtsep
+ * submodule-header-stmts
+ * linkage-stmts
+ * meta-stmts
+ * revision-stmts
+ * body-stmts
+ * "}" optsep
+ */
+ subModuleStatement : SUBMODULE_KEYWORD identifier LEFT_CURLY_BRACE submoduleBody RIGHT_CURLY_BRACE;
+ submoduleBody : submoduleHeaderStatement linkageStatements metaStatements revisionStatements bodyStatements;
+
+ /** submodule-header-stmts =
+ * ;; these stmts can appear in any order
+ * [yang-version-stmt stmtsep]
+ * belongs-to-stmt stmtsep
+ */
+ submoduleHeaderStatement : yangVersionStatement? belongstoStatement
+ | belongstoStatement yangVersionStatement?
+ ;
+
+ /**
+ * belongs-to-stmt = belongs-to-keyword sep identifier-arg-str
+ * optsep
+ * "{" stmtsep
+ * prefix-stmt stmtsep
+ * "}"
+ */
+ belongstoStatement : BELONGS_TO_KEYWORD identifier LEFT_CURLY_BRACE belongstoStatementBody RIGHT_CURLY_BRACE;
+ belongstoStatementBody : prefixStatement;
+
+ /**
+ * extension-stmt = extension-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [argument-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ extensionStatement : EXTENSION_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE extensionBody RIGHT_CURLY_BRACE);
+ extensionBody : argumentStatement? statusStatement? descriptionStatement? referenceStatement?
+ | argumentStatement? statusStatement? referenceStatement? descriptionStatement?
+ | argumentStatement? descriptionStatement? statusStatement? referenceStatement?
+ | argumentStatement? descriptionStatement? referenceStatement? statusStatement?
+ | argumentStatement? referenceStatement? descriptionStatement? statusStatement?
+ | argumentStatement? referenceStatement? statusStatement? descriptionStatement?
+ | statusStatement? referenceStatement? argumentStatement? descriptionStatement?
+ | statusStatement? referenceStatement? descriptionStatement? argumentStatement?
+ | statusStatement? descriptionStatement? referenceStatement? argumentStatement?
+ | statusStatement? descriptionStatement? argumentStatement? referenceStatement?
+ | statusStatement? argumentStatement? referenceStatement? descriptionStatement?
+ | statusStatement? argumentStatement? descriptionStatement? referenceStatement?
+ | descriptionStatement? argumentStatement? statusStatement? referenceStatement?
+ | descriptionStatement? argumentStatement? referenceStatement? statusStatement?
+ | descriptionStatement? statusStatement? argumentStatement? referenceStatement?
+ | descriptionStatement? statusStatement? referenceStatement? argumentStatement?
+ | descriptionStatement? referenceStatement? statusStatement? argumentStatement?
+ | descriptionStatement? referenceStatement? argumentStatement? statusStatement?
+ | referenceStatement? descriptionStatement? argumentStatement? statusStatement?
+ | referenceStatement? descriptionStatement? statusStatement? argumentStatement?
+ | referenceStatement? statusStatement? argumentStatement? descriptionStatement?
+ | referenceStatement? statusStatement? descriptionStatement? argumentStatement?
+ | referenceStatement? argumentStatement? descriptionStatement? statusStatement?
+ | referenceStatement? argumentStatement? statusStatement? descriptionStatement?
+ ;
+
+ /**
+ * argument-stmt = argument-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * [yin-element-stmt stmtsep]
+ * "}")
+ */
+ argumentStatement : ARGUMENT_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE argumentBody RIGHT_CURLY_BRACE);
+ argumentBody : yinElementStatement?;
+
+ /**
+ * yin-element-stmt = yin-element-keyword sep yin-element-arg-str
+ * stmtend
+ */
+ yinElementStatement : YIN_ELEMENT_KEYWORD (TRUE_KEYWORD | FALSE_KEYWORD) STMTEND;
+
+ /**
+ * identity-stmt = identity-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [base-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ identityStatement : IDENTITY_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE identityBody RIGHT_CURLY_BRACE);
+ identityBody : baseStatement? statusStatement? descriptionStatement? referenceStatement?
+ | baseStatement? statusStatement? referenceStatement? descriptionStatement?
+ | baseStatement? descriptionStatement? statusStatement? referenceStatement?
+ | baseStatement? descriptionStatement? referenceStatement? statusStatement?
+ | baseStatement? referenceStatement? descriptionStatement? statusStatement?
+ | baseStatement? referenceStatement? statusStatement? descriptionStatement?
+ | referenceStatement? baseStatement? statusStatement? descriptionStatement?
+ | referenceStatement? baseStatement? descriptionStatement? statusStatement?
+ | referenceStatement? statusStatement? baseStatement? descriptionStatement?
+ | referenceStatement? statusStatement? descriptionStatement? baseStatement?
+ | referenceStatement? descriptionStatement? statusStatement? baseStatement?
+ | referenceStatement? descriptionStatement? baseStatement? statusStatement?
+ | descriptionStatement? referenceStatement? statusStatement? baseStatement?
+ | descriptionStatement? referenceStatement? statusStatement? baseStatement?
+ | descriptionStatement? referenceStatement? baseStatement? statusStatement?
+ | descriptionStatement? statusStatement? baseStatement? referenceStatement?
+ | descriptionStatement? statusStatement? referenceStatement? baseStatement?
+ | descriptionStatement? baseStatement? referenceStatement? statusStatement?
+ | descriptionStatement? baseStatement? statusStatement? referenceStatement?
+ | statusStatement? baseStatement? descriptionStatement? referenceStatement?
+ | statusStatement? baseStatement? referenceStatement? descriptionStatement?
+ | statusStatement? descriptionStatement? baseStatement? referenceStatement?
+ | statusStatement? descriptionStatement? referenceStatement? baseStatement?
+ | statusStatement? referenceStatement? descriptionStatement? baseStatement?
+ | statusStatement? referenceStatement? baseStatement? descriptionStatement?
+ ;
+
+ /**
+ * base-stmt = base-keyword sep identifier-ref-arg-str
+ * optsep stmtend*
+ * identifier-ref-arg = [prefix ":"] identifier
+ */
+ baseStatement : BASE_KEYWORD string STMTEND;
+
+ /**
+ * feature-stmt = feature-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ featureStatement : FEATURE_KEYWORD string (STMTEND | LEFT_CURLY_BRACE featureBody RIGHT_CURLY_BRACE);
+ featureBody : ifFeatureStatement* statusStatement? descriptionStatement? referenceStatement?
+ | ifFeatureStatement* statusStatement? referenceStatement? descriptionStatement?
+ | ifFeatureStatement* descriptionStatement? statusStatement? referenceStatement?
+ | ifFeatureStatement* descriptionStatement? referenceStatement? statusStatement?
+ | ifFeatureStatement* referenceStatement? statusStatement? descriptionStatement?
+ | ifFeatureStatement* referenceStatement? descriptionStatement? statusStatement?
+ | statusStatement? ifFeatureStatement* descriptionStatement? referenceStatement?
+ | statusStatement? ifFeatureStatement* referenceStatement? descriptionStatement?
+ | statusStatement? descriptionStatement? ifFeatureStatement* referenceStatement?
+ | statusStatement? descriptionStatement? referenceStatement? ifFeatureStatement*
+ | statusStatement? referenceStatement? ifFeatureStatement* descriptionStatement?
+ | statusStatement? referenceStatement? descriptionStatement? ifFeatureStatement*
+ | descriptionStatement? ifFeatureStatement* statusStatement? referenceStatement?
+ | descriptionStatement? ifFeatureStatement* referenceStatement? statusStatement?
+ | descriptionStatement? statusStatement? ifFeatureStatement* referenceStatement?
+ | descriptionStatement? statusStatement? referenceStatement? ifFeatureStatement*
+ | descriptionStatement? referenceStatement* statusStatement? ifFeatureStatement*
+ | descriptionStatement? referenceStatement* ifFeatureStatement? statusStatement?
+ | referenceStatement? ifFeatureStatement* statusStatement? descriptionStatement?
+ | referenceStatement? ifFeatureStatement* descriptionStatement? statusStatement?
+ | referenceStatement? descriptionStatement? statusStatement? ifFeatureStatement*
+ | referenceStatement? descriptionStatement? ifFeatureStatement* statusStatement?
+ | referenceStatement? statusStatement? descriptionStatement? ifFeatureStatement*
+ | referenceStatement? statusStatement? ifFeatureStatement* descriptionStatement?
+ ;
+
+ /**
+ * data-def-stmt = container-stmt /
+ * leaf-stmt /
+ * leaf-list-stmt /
+ * list-stmt /
+ * choice-stmt /
+ * anyxml-stmt /
+ * uses-stmt
+ */
+ dataDefStatement : containerStatement
+ | leafStatement
+ | leafListStatement
+ | listStatement
+ | choiceStatement
+ | anyxmlStatement
+ | usesStatement;
+
+ /**
+ * if-feature-stmt = if-feature-keyword sep identifier-ref-arg-str
+ * optsep stmtend
+ */
+ ifFeatureStatement : IF_FEATURE_KEYWORD string STMTEND;
+
+ /**
+ * units-stmt = units-keyword sep string optsep stmtend
+ */
+ unitsStatement : UNITS_KEYWORD string STMTEND;
+
+ /**
+ * typedef-stmt = typedef-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * type-stmt stmtsep
+ * [units-stmt stmtsep]
+ * [default-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ * TODO : 0..1 occurance to be validated in listener
+ */
+ typedefStatement : TYPEDEF_KEYWORD identifier LEFT_CURLY_BRACE
+ (typeStatement | unitsStatement | defaultStatement | statusStatement | descriptionStatement | referenceStatement)*
+ RIGHT_CURLY_BRACE;
+
+ /**
+ * type-stmt = type-keyword sep identifier-ref-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * type-body-stmts
+ * "}")
+ */
+ typeStatement : TYPE_KEYWORD string (STMTEND | LEFT_CURLY_BRACE typeBodyStatements RIGHT_CURLY_BRACE);
+
+ /**
+ * type-body-stmts = numerical-restrictions /
+ * decimal64-specification /
+ * string-restrictions /
+ * enum-specification /
+ * leafref-specification /
+ * identityref-specification /
+ * instance-identifier-specification /
+ * bits-specification /
+ * union-specification
+ *
+ */
+ typeBodyStatements : numericalRestrictions | decimal64Specification | stringRestrictions | enumSpecification
+ | leafrefSpecification | identityrefSpecification | instanceIdentifierSpecification
+ | bitsSpecification | unionSpecification;
+
+ /**
+ * fraction-digits-stmt = fraction-digits-keyword sep
+ * fraction-digits-arg-str stmtend
+ *
+ * fraction-digits-arg-str = < a string that matches the rule
+ * fraction-digits-arg >
+ *
+ * fraction-digits-arg = ("1" ["0" / "1" / "2" / "3" / "4" /
+ * "5" / "6" / "7" / "8"])
+ * / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
+ */
+ decimal64Specification : FRACTION_DIGITS_KEYWORD fraction STMTEND;
+
+ /**
+ * numerical-restrictions = range-stmt stmtsep
+ */
+ numericalRestrictions : rangeStatement;
+
+ /**
+ * range-stmt = range-keyword sep range-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [error-message-stmt stmtsep]
+ * [error-app-tag-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ rangeStatement : RANGE_KEYWORD range (STMTEND | LEFT_CURLY_BRACE commonStatements RIGHT_CURLY_BRACE);
+
+ commonStatements : errorMessageStatement? errorAppTagStatement? descriptionStatement? referenceStatement?
+ | errorMessageStatement? errorAppTagStatement? referenceStatement? descriptionStatement?
+ | errorMessageStatement? descriptionStatement? errorAppTagStatement? referenceStatement?
+ | errorMessageStatement? descriptionStatement? referenceStatement? errorAppTagStatement?
+ | errorMessageStatement? referenceStatement? errorAppTagStatement? descriptionStatement?
+ | errorMessageStatement? referenceStatement? descriptionStatement? errorAppTagStatement?
+ | errorAppTagStatement? errorMessageStatement? descriptionStatement? referenceStatement?
+ | errorAppTagStatement? errorMessageStatement? referenceStatement? descriptionStatement?
+ | errorAppTagStatement? descriptionStatement? descriptionStatement? errorMessageStatement?
+ | errorAppTagStatement? descriptionStatement? errorMessageStatement? descriptionStatement?
+ | errorAppTagStatement? referenceStatement? errorMessageStatement? descriptionStatement?
+ | errorAppTagStatement? referenceStatement? descriptionStatement? errorMessageStatement?
+ | descriptionStatement? errorMessageStatement? errorAppTagStatement? referenceStatement?
+ | descriptionStatement? errorMessageStatement? referenceStatement? errorAppTagStatement?
+ | descriptionStatement? errorAppTagStatement? errorMessageStatement? referenceStatement?
+ | descriptionStatement? errorAppTagStatement? referenceStatement? errorMessageStatement?
+ | descriptionStatement? referenceStatement? errorMessageStatement? errorAppTagStatement?
+ | descriptionStatement? referenceStatement? errorAppTagStatement? errorMessageStatement?
+ | referenceStatement? errorMessageStatement? descriptionStatement? errorAppTagStatement?
+ | referenceStatement? errorMessageStatement? errorAppTagStatement? descriptionStatement?
+ | referenceStatement? errorAppTagStatement? descriptionStatement? errorMessageStatement?
+ | referenceStatement? errorAppTagStatement? errorMessageStatement? descriptionStatement?
+ | referenceStatement? descriptionStatement? errorMessageStatement? errorAppTagStatement?
+ | referenceStatement? descriptionStatement? errorAppTagStatement? errorMessageStatement?
+ ;
+
+ /**
+ * string-restrictions = ;; these stmts can appear in any order
+ * [length-stmt stmtsep]
+ * *(pattern-stmt stmtsep)
+ */
+ stringRestrictions : ((lengthStatement)? (patternStatement)*) | ((patternStatement)* (lengthStatement)?);
+
+ /**
+ * length-stmt = length-keyword sep length-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [error-message-stmt stmtsep]
+ * [error-app-tag-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ lengthStatement : LENGTH_KEYWORD length
+ (STMTEND | LEFT_CURLY_BRACE commonStatements RIGHT_CURLY_BRACE);
+
+ /**
+ * pattern-stmt = pattern-keyword sep string optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [error-message-stmt stmtsep]
+ * [error-app-tag-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ patternStatement : PATTERN_KEYWORD string (STMTEND | LEFT_CURLY_BRACE commonStatements RIGHT_CURLY_BRACE);
+
+ /**
+ * default-stmt = default-keyword sep string stmtend
+ */
+ defaultStatement : DEFAULT_KEYWORD string STMTEND;
+
+ /**
+ * enum-specification = 1*(enum-stmt stmtsep)
+ */
+ enumSpecification : enumStatement+;
+
+ /**
+ * enum-stmt = enum-keyword sep string optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [value-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ enumStatement : ENUM_KEYWORD string (STMTEND | LEFT_CURLY_BRACE enumStatementBody RIGHT_CURLY_BRACE);
+
+ enumStatementBody : valueStatement? statusStatement? descriptionStatement? referenceStatement?
+ | valueStatement? statusStatement? referenceStatement? descriptionStatement?
+ | valueStatement? descriptionStatement? statusStatement? referenceStatement?
+ | valueStatement? descriptionStatement? referenceStatement? statusStatement?
+ | valueStatement? referenceStatement? statusStatement? descriptionStatement?
+ | valueStatement? referenceStatement? descriptionStatement? statusStatement?
+ | statusStatement? valueStatement? descriptionStatement? referenceStatement?
+ | statusStatement? valueStatement? referenceStatement? descriptionStatement?
+ | statusStatement? descriptionStatement? descriptionStatement? valueStatement?
+ | statusStatement? descriptionStatement? valueStatement? descriptionStatement?
+ | statusStatement? referenceStatement? valueStatement? descriptionStatement?
+ | statusStatement? referenceStatement? descriptionStatement? valueStatement?
+ | descriptionStatement? valueStatement? statusStatement? referenceStatement?
+ | descriptionStatement? valueStatement? referenceStatement? statusStatement?
+ | descriptionStatement? statusStatement? valueStatement? referenceStatement?
+ | descriptionStatement? statusStatement? referenceStatement? valueStatement?
+ | descriptionStatement? referenceStatement? valueStatement? statusStatement?
+ | descriptionStatement? referenceStatement? statusStatement? valueStatement?
+ | referenceStatement? valueStatement? descriptionStatement? statusStatement?
+ | referenceStatement? valueStatement? statusStatement? descriptionStatement?
+ | referenceStatement? statusStatement? descriptionStatement? valueStatement?
+ | referenceStatement? statusStatement? valueStatement? descriptionStatement?
+ | referenceStatement? descriptionStatement? valueStatement? statusStatement?
+ | referenceStatement? descriptionStatement? statusStatement? valueStatement?
+ ;
+
+ /**
+ * leafref-specification =
+ * ;; these stmts can appear in any order
+ * path-stmt stmtsep
+ * [require-instance-stmt stmtsep]
+ */
+ leafrefSpecification : (pathStatement (requireInstanceStatement)?) | ((requireInstanceStatement)? pathStatement);
+
+ /**
+ * path-stmt = path-keyword sep path-arg-str stmtend
+ */
+ pathStatement : PATH_KEYWORD path STMTEND;
+
+ /**
+ * require-instance-stmt = require-instance-keyword sep
+ * require-instance-arg-str stmtend
+ * require-instance-arg-str = < a string that matches the rule
+ * require-instance-arg >
+ * require-instance-arg = true-keyword / false-keyword
+ */
+ requireInstanceStatement : REQUIRE_INSTANCE_KEYWORD (TRUE_KEYWORD | FALSE_KEYWORD) STMTEND;
+
+ /**
+ * instance-identifier-specification =
+ * [require-instance-stmt stmtsep]
+ */
+ instanceIdentifierSpecification : requireInstanceStatement?;
+
+ /**
+ * identityref-specification =
+ * base-stmt stmtsep
+ */
+ identityrefSpecification : baseStatement;
+
+ /**
+ * union-specification = 1*(type-stmt stmtsep)
+ */
+ unionSpecification : typeStatement+;
+
+ /**
+ * bits-specification = 1*(bit-stmt stmtsep)
+ */
+ bitsSpecification : bitStatement+;
+
+ /**
+ * bit-stmt = bit-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [position-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ * "}")
+ */
+ bitStatement : BIT_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE bitBodyStatement RIGHT_CURLY_BRACE);
+
+ bitBodyStatement : positionStatement? statusStatement? descriptionStatement? referenceStatement?
+ | positionStatement? statusStatement? referenceStatement? descriptionStatement?
+ | positionStatement? descriptionStatement? statusStatement? referenceStatement?
+ | positionStatement? descriptionStatement? referenceStatement? statusStatement?
+ | positionStatement? referenceStatement? statusStatement? descriptionStatement?
+ | positionStatement? referenceStatement? descriptionStatement? statusStatement?
+ | statusStatement? positionStatement? descriptionStatement? referenceStatement?
+ | statusStatement? positionStatement? referenceStatement? descriptionStatement?
+ | statusStatement? descriptionStatement? descriptionStatement? positionStatement?
+ | statusStatement? descriptionStatement? positionStatement? descriptionStatement?
+ | statusStatement? referenceStatement? positionStatement? descriptionStatement?
+ | statusStatement? referenceStatement? descriptionStatement? positionStatement?
+ | descriptionStatement? positionStatement? statusStatement? referenceStatement?
+ | descriptionStatement? positionStatement? referenceStatement? statusStatement?
+ | descriptionStatement? statusStatement? positionStatement? referenceStatement?
+ | descriptionStatement? statusStatement? referenceStatement? positionStatement?
+ | descriptionStatement? referenceStatement? positionStatement? statusStatement?
+ | descriptionStatement? referenceStatement? statusStatement? positionStatement?
+ | referenceStatement? positionStatement? descriptionStatement? statusStatement?
+ | referenceStatement? positionStatement? statusStatement? descriptionStatement?
+ | referenceStatement? statusStatement? descriptionStatement? positionStatement?
+ | referenceStatement? statusStatement? positionStatement? descriptionStatement?
+ | referenceStatement? descriptionStatement? positionStatement? statusStatement?
+ | referenceStatement? descriptionStatement? statusStatement? positionStatement?
+ ;
+
+ /**
+ * position-stmt = position-keyword sep
+ * position-value-arg-str stmtend
+ * position-value-arg-str = < a string that matches the rule
+ * position-value-arg >
+ * position-value-arg = non-negative-integer-value
+ */
+ positionStatement : POSITION_KEYWORD position STMTEND;
+
+ /**
+ * status-stmt = status-keyword sep status-arg-str stmtend
+ * status-arg-str = < a string that matches the rule
+ * status-arg >
+ * status-arg = current-keyword /
+ * obsolete-keyword /
+ * deprecated-keyword
+ */
+ statusStatement : STATUS_KEYWORD status STMTEND;
+
+ /**
+ * config-stmt = config-keyword sep
+ * config-arg-str stmtend
+ * config-arg-str = < a string that matches the rule
+ * config-arg >
+ * config-arg = true-keyword / false-keyword
+ */
+ configStatement : CONFIG_KEYWORD config STMTEND;
+
+ /**
+ * mandatory-stmt = mandatory-keyword sep
+ * mandatory-arg-str stmtend
+ *
+ * mandatory-arg-str = < a string that matches the rule
+ * mandatory-arg >
+ *
+ * mandatory-arg = true-keyword / false-keyword
+ */
+ mandatoryStatement : MANDATORY_KEYWORD mandatory STMTEND;
+
+ /**
+ * presence-stmt = presence-keyword sep string stmtend
+ */
+ presenceStatement : PRESENCE_KEYWORD string STMTEND;
+
+ /**
+ * ordered-by-stmt = ordered-by-keyword sep
+ * ordered-by-arg-str stmtend
+ *
+ * ordered-by-arg-str = < a string that matches the rule
+ * ordered-by-arg >
+ *
+ * ordered-by-arg = user-keyword / system-keyword
+ */
+ orderedByStatement : ORDERED_BY_KEYWORD orderedBy STMTEND;
+
+ /**
+ * must-stmt = must-keyword sep string optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [error-message-stmt stmtsep]
+ * [error-app-tag-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ mustStatement : MUST_KEYWORD string (STMTEND | LEFT_CURLY_BRACE commonStatements RIGHT_CURLY_BRACE);
+
+ /**
+ * error-message-stmt = error-message-keyword sep string stmtend
+ */
+ errorMessageStatement : ERROR_MESSAGE_KEYWORD string STMTEND;
+
+ /**
+ * error-app-tag-stmt = error-app-tag-keyword sep string stmtend
+ */
+ errorAppTagStatement : ERROR_APP_TAG_KEYWORD string STMTEND;
+
+ /**
+ * min-elements-stmt = min-elements-keyword sep
+ * min-value-arg-str stmtend
+ * min-value-arg-str = < a string that matches the rule
+ * min-value-arg >
+ * min-value-arg = non-negative-integer-value
+ */
+ minElementsStatement : MIN_ELEMENTS_KEYWORD minValue STMTEND;
+
+ /**
+ * max-elements-stmt = max-elements-keyword sep
+ * max-value-arg-str stmtend
+ * max-value-arg-str = < a string that matches the rule
+ * max-value-arg >
+ * max-value-arg = unbounded-keyword /
+ * positive-integer-value
+ */
+ maxElementsStatement : MAX_ELEMENTS_KEYWORD maxValue STMTEND;
+
+ /**
+ * value-stmt = value-keyword sep integer-value stmtend
+ */
+ valueStatement : VALUE_KEYWORD value STMTEND;
+
+ /**
+ * grouping-stmt = grouping-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * *(data-def-stmt stmtsep)
+ * "}")
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ groupingStatement : GROUPING_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE
+ (statusStatement | descriptionStatement | referenceStatement | typedefStatement | groupingStatement
+ | dataDefStatement)* RIGHT_CURLY_BRACE);
+
+ /**
+ * container-stmt = container-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * *(must-stmt stmtsep)
+ * [presence-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * *(data-def-stmt stmtsep)
+ * "}")
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ containerStatement : CONTAINER_KEYWORD identifier
+ (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | mustStatement | presenceStatement | configStatement
+ | statusStatement | descriptionStatement | referenceStatement | typedefStatement | groupingStatement
+ | dataDefStatement)* RIGHT_CURLY_BRACE);
+
+ /**
+ * leaf-stmt = leaf-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * type-stmt stmtsep
+ * [units-stmt stmtsep]
+ * *(must-stmt stmtsep)
+ * [default-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ leafStatement : LEAF_KEYWORD identifier LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | typeStatement | unitsStatement
+ | mustStatement | defaultStatement | configStatement | mandatoryStatement | statusStatement | descriptionStatement
+ | referenceStatement)* RIGHT_CURLY_BRACE;
+
+ /**
+ * leaf-list-stmt = leaf-list-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * type-stmt stmtsep
+ * [units-stmt stmtsep]
+ * *(must-stmt stmtsep)
+ * [config-stmt stmtsep]
+ * [min-elements-stmt stmtsep]
+ * [max-elements-stmt stmtsep]
+ * [ordered-by-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}"
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ leafListStatement : LEAF_LIST_KEYWORD identifier LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | typeStatement
+ | unitsStatement | mustStatement | configStatement | minElementsStatement | maxElementsStatement | orderedByStatement
+ | statusStatement | descriptionStatement | referenceStatement)* RIGHT_CURLY_BRACE;
+
+ /**
+ * list-stmt = list-keyword sep identifier-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * *(must-stmt stmtsep)
+ * [key-stmt stmtsep]
+ * *(unique-stmt stmtsep)
+ * [config-stmt stmtsep]
+ * [min-elements-stmt stmtsep]
+ * [max-elements-stmt stmtsep]
+ * [ordered-by-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * 1*(data-def-stmt stmtsep)
+ * "}"
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ listStatement : LIST_KEYWORD identifier LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | mustStatement | keyStatement
+ | uniqueStatement | configStatement | minElementsStatement | maxElementsStatement | orderedByStatement | statusStatement
+ | descriptionStatement | referenceStatement | typedefStatement | groupingStatement| dataDefStatement)* RIGHT_CURLY_BRACE;
+
+ /**
+ * key-stmt = key-keyword sep key-arg-str stmtend
+ */
+ keyStatement : KEY_KEYWORD key STMTEND;
+
+ /**
+ * unique-stmt = unique-keyword sep unique-arg-str stmtend
+ */
+ uniqueStatement: UNIQUE_KEYWORD unique STMTEND;
+
+ /**
+ * choice-stmt = choice-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * [default-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((short-case-stmt / case-stmt) stmtsep)
+ * "}")
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ choiceStatement : CHOICE_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | defaultStatement
+ | configStatement | mandatoryStatement | statusStatement | descriptionStatement | referenceStatement | shortCaseStatement
+ | caseStatement)* RIGHT_CURLY_BRACE);
+
+ /**
+ * short-case-stmt = container-stmt /
+ * leaf-stmt /
+ * leaf-list-stmt /
+ * list-stmt /
+ * anyxml-stmt
+ */
+ shortCaseStatement : containerStatement | leafStatement | leafListStatement | listStatement | anyxmlStatement;
+
+ /**
+ * case-stmt = case-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *(data-def-stmt stmtsep)
+ * "}")
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ caseStatement : CASE_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | statusStatement
+ | descriptionStatement | referenceStatement | dataDefStatement)* RIGHT_CURLY_BRACE);
+
+ /**
+ * anyxml-stmt = anyxml-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * *(must-stmt stmtsep)
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ */
+ anyxmlStatement : ANYXML_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement
+ | mustStatement | configStatement | mandatoryStatement | statusStatement | descriptionStatement
+ | referenceStatement)* RIGHT_CURLY_BRACE);
+
+ /**
+ * uses-stmt = uses-keyword sep identifier-ref-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *(refine-stmt stmtsep)
+ * *(uses-augment-stmt stmtsep)
+ * "}")
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ usesStatement : USES_KEYWORD string (STMTEND | LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | statusStatement
+ | descriptionStatement | referenceStatement | refineStatement | augmentStatement)* RIGHT_CURLY_BRACE);
+
+ /**
+ * refine-stmt = refine-keyword sep refine-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * (refine-container-stmts /
+ * refine-leaf-stmts /
+ * refine-leaf-list-stmts /
+ * refine-list-stmts /
+ * refine-choice-stmts /
+ * refine-case-stmts /
+ * refine-anyxml-stmts)
+ * "}")
+ */
+ refineStatement : REFINE_KEYWORD refine (STMTEND | LEFT_CURLY_BRACE (refineContainerStatements
+ | refineLeafStatements | refineLeafListStatements | refineListStatements | refineChoiceStatements
+ | refineCaseStatements | refineAnyxmlStatements) RIGHT_CURLY_BRACE);
+
+ /**
+ * refine-container-stmts =
+ * ;; these stmts can appear in any order
+ * *(must-stmt stmtsep)
+ * [presence-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ refineContainerStatements : (mustStatement | presenceStatement | configStatement | descriptionStatement | referenceStatement)* ;
+
+ /**
+ * refine-leaf-stmts = ;; these stmts can appear in any order
+ * *(must-stmt stmtsep)
+ * [default-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ refineLeafStatements : (mustStatement | defaultStatement | configStatement | mandatoryStatement | descriptionStatement | referenceStatement)*;
+
+ /**
+ * refine-leaf-list-stmts =
+ * ;; these stmts can appear in any order
+ * *(must-stmt stmtsep)
+ * [config-stmt stmtsep]
+ * [min-elements-stmt stmtsep]
+ * [max-elements-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ refineLeafListStatements : (mustStatement | configStatement | minElementsStatement | maxElementsStatement | descriptionStatement
+ | referenceStatement)*;
+
+ /**
+ * refine-list-stmts = ;; these stmts can appear in any order
+ * *(must-stmt stmtsep)
+ * [config-stmt stmtsep]
+ * [min-elements-stmt stmtsep]
+ * [max-elements-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ refineListStatements : (mustStatement | configStatement | minElementsStatement | maxElementsStatement | descriptionStatement
+ | referenceStatement)*;
+
+ /**
+ * refine-choice-stmts = ;; these stmts can appear in any order
+ * [default-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ refineChoiceStatements : (defaultStatement | configStatement | mandatoryStatement | descriptionStatement | referenceStatement)*;
+
+ /**
+ * refine-case-stmts = ;; these stmts can appear in any order
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ *
+ */
+ refineCaseStatements : (descriptionStatement | referenceStatement)? | (referenceStatement | descriptionStatement)?;
+
+ /**
+ * refine-anyxml-stmts = ;; these stmts can appear in any order
+ * *(must-stmt stmtsep)
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ */
+ refineAnyxmlStatements : (mustStatement | configStatement | mandatoryStatement | descriptionStatement
+ | referenceStatement)*;
+
+ /**
+ * augment-stmt = augment-keyword sep augment-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [when-stmt stmtsep]
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * 1*((data-def-stmt stmtsep) /
+ * (case-stmt stmtsep))
+ * "}"
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ augmentStatement : AUGMENT_KEYWORD augment LEFT_CURLY_BRACE (whenStatement | ifFeatureStatement | statusStatement
+ | descriptionStatement | referenceStatement | dataDefStatement | caseStatement)* RIGHT_CURLY_BRACE;
+
+ /**
+ * when-stmt = when-keyword sep string optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * "}")
+ *
+ */
+ whenStatement : WHEN_KEYWORD string (STMTEND | LEFT_CURLY_BRACE ((descriptionStatement? referenceStatement?)
+ | (referenceStatement? descriptionStatement?)) RIGHT_CURLY_BRACE);
+
+ /**
+ * rpc-stmt = rpc-keyword sep identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * [input-stmt stmtsep]
+ * [output-stmt stmtsep]
+ * "}")
+ */
+ rpcStatement : RPC_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (ifFeatureStatement | statusStatement | descriptionStatement
+ | referenceStatement | typedefStatement | groupingStatement | inputStatement | outputStatement)* RIGHT_CURLY_BRACE);
+
+ /**
+ * input-stmt = input-keyword optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * 1*(data-def-stmt stmtsep)
+ * "}"
+ */
+ inputStatement : INPUT_KEYWORD LEFT_CURLY_BRACE (typedefStatement | groupingStatement | dataDefStatement)* RIGHT_CURLY_BRACE;
+
+ /**
+ * output-stmt = output-keyword optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * 1*(data-def-stmt stmtsep)
+ * "}"
+ */
+ outputStatement : OUTPUT_KEYWORD LEFT_CURLY_BRACE (typedefStatement | groupingStatement | dataDefStatement)* RIGHT_CURLY_BRACE;
+
+ /**
+ * notification-stmt = notification-keyword sep
+ * identifier-arg-str optsep
+ * (";" /
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * *(if-feature-stmt stmtsep)
+ * [status-stmt stmtsep]
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * *((typedef-stmt /
+ * grouping-stmt) stmtsep)
+ * *(data-def-stmt stmtsep)
+ * "}")
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ notificationStatement : NOTIFICATION_KEYWORD identifier (STMTEND | LEFT_CURLY_BRACE (ifFeatureStatement
+ | statusStatement | descriptionStatement | referenceStatement | typedefStatement
+ | groupingStatement | dataDefStatement)* RIGHT_CURLY_BRACE);
+
+ /**
+ * deviation-stmt = deviation-keyword sep
+ * deviation-arg-str optsep
+ * "{" stmtsep
+ * ;; these stmts can appear in any order
+ * [description-stmt stmtsep]
+ * [reference-stmt stmtsep]
+ * (deviate-not-supported-stmt /
+ * 1*(deviate-add-stmt /
+ * deviate-replace-stmt /
+ * deviate-delete-stmt))
+ * "}"
+ * TODO : 0..1 occurance to be checked in listener
+ */
+ deviationStatement: DEVIATION_KEYWORD deviation LEFT_CURLY_BRACE (descriptionStatement | referenceStatement
+ | deviateNotSupportedStatement | deviateAddStatement | deviateReplaceStatement
+ | deviateDeleteStatement)* RIGHT_CURLY_BRACE;
+
+ /**
+ * deviate-not-supported-stmt =
+ * deviate-keyword sep
+ * not-supported-keyword optsep
+ * (";" /
+ * "{" stmtsep
+ * "}")
+ */
+ deviateNotSupportedStatement: DEVIATE_KEYWORD NOT_SUPPORTED_KEYWORD (STMTEND | LEFT_CURLY_BRACE RIGHT_CURLY_BRACE);
+
+ /**
+ * deviate-add-stmt = deviate-keyword sep add-keyword optsep
+ * (";" /
+ * "{" stmtsep
+ * [units-stmt stmtsep]
+ * *(must-stmt stmtsep)
+ * *(unique-stmt stmtsep)
+ * [default-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [min-elements-stmt stmtsep]
+ * [max-elements-stmt stmtsep]
+ * "}")
+ */
+ deviateAddStatement: DEVIATE_KEYWORD ADD_KEYWORD (STMTEND | (LEFT_CURLY_BRACE unitsStatement? mustStatement* uniqueStatement*
+ defaultStatement? configStatement? mandatoryStatement? minElementsStatement? maxElementsStatement?
+ RIGHT_CURLY_BRACE));
+
+ /**
+ * deviate-delete-stmt = deviate-keyword sep delete-keyword optsep
+ * (";" /
+ * "{" stmtsep
+ * [units-stmt stmtsep]
+ * *(must-stmt stmtsep)
+ * *(unique-stmt stmtsep)
+ * [default-stmt stmtsep]
+ * "}")
+ */
+ deviateDeleteStatement: DEVIATE_KEYWORD DELETE_KEYWORD (STMTEND
+ | (LEFT_CURLY_BRACE unitsStatement? mustStatement* uniqueStatement* defaultStatement? RIGHT_CURLY_BRACE));
+
+ /**
+ * deviate-replace-stmt = deviate-keyword sep replace-keyword optsep
+ * (";" /
+ * "{" stmtsep
+ * [type-stmt stmtsep]
+ * [units-stmt stmtsep]
+ * [default-stmt stmtsep]
+ * [config-stmt stmtsep]
+ * [mandatory-stmt stmtsep]
+ * [min-elements-stmt stmtsep]
+ * [max-elements-stmt stmtsep]
+ * "}")
+ */
+ deviateReplaceStatement: DEVIATE_KEYWORD REPLACE_KEYWORD (STMTEND | (LEFT_CURLY_BRACE typeStatement? unitsStatement?
+ defaultStatement? configStatement? mandatoryStatement? minElementsStatement?
+ maxElementsStatement? RIGHT_CURLY_BRACE));
+
+ string : STRING (PLUS STRING)*
+ | IDENTIFIER
+ | INTEGER
+ | yangConstruct;
+
+ identifier : STRING (PLUS STRING)*
+ | IDENTIFIER
+ | yangConstruct;
+
+ dateArgumentString : DATE_ARG
+ | STRING (PLUS STRING)*;
+
+ version : string;
+
+ range : string;
+
+ length : string;
+
+ path : string;
+
+ position : string;
+
+ status : string;
+
+ config : string;
+
+ mandatory : string;
+
+ orderedBy : string;
+
+ minValue : string;
+
+ maxValue : string;
+
+ key : string;
+
+ unique : string;
+
+ refine : string;
+
+ augment : string;
+
+ deviation : string;
+
+ value : string;
+
+ fraction : string;
+
+ yangConstruct : ANYXML_KEYWORD | ARGUMENT_KEYWORD | AUGMENT_KEYWORD | BASE_KEYWORD | BELONGS_TO_KEYWORD
+ | BIT_KEYWORD | CASE_KEYWORD | CHOICE_KEYWORD | CONFIG_KEYWORD | CONTACT_KEYWORD | CONTAINER_KEYWORD
+ | DEFAULT_KEYWORD | DESCRIPTION_KEYWORD | ENUM_KEYWORD ERROR_APP_TAG_KEYWORD | ERROR_MESSAGE_KEYWORD
+ | EXTENSION_KEYWORD | DEVIATION_KEYWORD | DEVIATE_KEYWORD | FEATURE_KEYWORD
+ | FRACTION_DIGITS_KEYWORD | GROUPING_KEYWORD | IDENTITY_KEYWORD | IF_FEATURE_KEYWORD
+ | IMPORT_KEYWORD | INCLUDE_KEYWORD | INPUT_KEYWORD | KEY_KEYWORD | LEAF_KEYWORD | LEAF_LIST_KEYWORD
+ | LENGTH_KEYWORD | LIST_KEYWORD | MANDATORY_KEYWORD | MAX_ELEMENTS_KEYWORD | MIN_ELEMENTS_KEYWORD
+ | MODULE_KEYWORD | MUST_KEYWORD | NAMESPACE_KEYWORD | NOTIFICATION_KEYWORD | ORDERED_BY_KEYWORD
+ | ORGANIZATION_KEYWORD | OUTPUT_KEYWORD | PATH_KEYWORD | PATTERN_KEYWORD |POSITION_KEYWORD
+ | PREFIX_KEYWORD | PRESENCE_KEYWORD | RANGE_KEYWORD | REFERENCE_KEYWORD | REFINE_KEYWORD
+ | REQUIRE_INSTANCE_KEYWORD | REVISION_KEYWORD | REVISION_DATE_KEYWORD | RPC_KEYWORD
+ | STATUS_KEYWORD | SUBMODULE_KEYWORD | TYPE_KEYWORD | TYPEDEF_KEYWORD | UNIQUE_KEYWORD
+ | UNITS_KEYWORD | USES_KEYWORD | VALUE_KEYWORD | WHEN_KEYWORD | YANG_VERSION_KEYWORD
+ | YIN_ELEMENT_KEYWORD | ADD_KEYWORD | CURRENT_KEYWORD | DELETE_KEYWORD | DEPRECATED_KEYWORD
+ | FALSE_KEYWORD | MAX_KEYWORD | MIN_KEYWORD | NOT_SUPPORTED_KEYWORD | OBSOLETE_KEYWORD
+ | REPLACE_KEYWORD | SYSTEM_KEYWORD | TRUE_KEYWORD | UNBOUNDED_KEYWORD | USER_KEYWORD;
\ No newline at end of file
diff --git a/plugin/src/main/resources/YangLexer.g4 b/plugin/src/main/resources/YangLexer.g4
new file mode 100644
index 0000000..da20fd8
--- /dev/null
+++ b/plugin/src/main/resources/YangLexer.g4
@@ -0,0 +1,137 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This is a YANG grammar for lexer based on which ANTLR will generate YANG lexer.
+ */
+
+lexer grammar YangLexer;
+
+ // Statements keywords
+ ANYXML_KEYWORD : 'anyxml';
+ ARGUMENT_KEYWORD : 'argument';
+ AUGMENT_KEYWORD : 'augment';
+ BASE_KEYWORD : 'base';
+ BELONGS_TO_KEYWORD : 'belongs-to';
+ BIT_KEYWORD : 'bit';
+ CASE_KEYWORD : 'case';
+ CHOICE_KEYWORD : 'choice';
+ CONFIG_KEYWORD : 'config';
+ CONTACT_KEYWORD : 'contact';
+ CONTAINER_KEYWORD : 'container';
+ DEFAULT_KEYWORD : 'default';
+ DESCRIPTION_KEYWORD : 'description';
+ ENUM_KEYWORD : 'enum';
+ ERROR_APP_TAG_KEYWORD : 'error-app-tag';
+ ERROR_MESSAGE_KEYWORD : 'error-message';
+ EXTENSION_KEYWORD : 'extension';
+ DEVIATION_KEYWORD : 'deviation';
+ DEVIATE_KEYWORD : 'deviate';
+ FEATURE_KEYWORD : 'feature';
+ FRACTION_DIGITS_KEYWORD : 'fraction-digits';
+ GROUPING_KEYWORD : 'grouping';
+ IDENTITY_KEYWORD : 'identity';
+ IF_FEATURE_KEYWORD : 'if-feature';
+ IMPORT_KEYWORD : 'import';
+ INCLUDE_KEYWORD : 'include';
+ INPUT_KEYWORD : 'input';
+ KEY_KEYWORD : 'key';
+ LEAF_KEYWORD : 'leaf';
+ LEAF_LIST_KEYWORD : 'leaf-list';
+ LENGTH_KEYWORD : 'length';
+ LIST_KEYWORD : 'list';
+ MANDATORY_KEYWORD : 'mandatory';
+ MAX_ELEMENTS_KEYWORD : 'max-elements';
+ MIN_ELEMENTS_KEYWORD : 'min-elements';
+ MODULE_KEYWORD : 'module';
+ MUST_KEYWORD : 'must';
+ NAMESPACE_KEYWORD : 'namespace';
+ NOTIFICATION_KEYWORD: 'notification';
+ ORDERED_BY_KEYWORD : 'ordered-by';
+ ORGANIZATION_KEYWORD: 'organization';
+ OUTPUT_KEYWORD : 'output';
+ PATH_KEYWORD : 'path';
+ PATTERN_KEYWORD : 'pattern';
+ POSITION_KEYWORD : 'position';
+ PREFIX_KEYWORD : 'prefix';
+ PRESENCE_KEYWORD : 'presence';
+ RANGE_KEYWORD : 'range';
+ REFERENCE_KEYWORD : 'reference';
+ REFINE_KEYWORD : 'refine';
+ REQUIRE_INSTANCE_KEYWORD : 'require-instance';
+ REVISION_KEYWORD : 'revision';
+ REVISION_DATE_KEYWORD : 'revision-date';
+ RPC_KEYWORD : 'rpc';
+ STATUS_KEYWORD : 'status';
+ SUBMODULE_KEYWORD : 'submodule';
+ TYPE_KEYWORD : 'type';
+ TYPEDEF_KEYWORD : 'typedef';
+ UNIQUE_KEYWORD : 'unique';
+ UNITS_KEYWORD : 'units';
+ USES_KEYWORD : 'uses';
+ VALUE_KEYWORD : 'value';
+ WHEN_KEYWORD : 'when';
+ YANG_VERSION_KEYWORD: 'yang-version';
+ YIN_ELEMENT_KEYWORD : 'yin-element';
+ ADD_KEYWORD : 'add';
+ CURRENT_KEYWORD : 'current';
+ DELETE_KEYWORD : 'delete';
+ DEPRECATED_KEYWORD : 'deprecated';
+ FALSE_KEYWORD : 'false';
+ MAX_KEYWORD : 'max';
+ MIN_KEYWORD : 'min';
+ NOT_SUPPORTED_KEYWORD : 'not-supported';
+ OBSOLETE_KEYWORD : 'obsolete';
+ REPLACE_KEYWORD : 'replace';
+ SYSTEM_KEYWORD : 'system';
+ TRUE_KEYWORD : 'true';
+ UNBOUNDED_KEYWORD : 'unbounded';
+ USER_KEYWORD : 'user';
+
+ // Lexer tokens to be skipped
+ COMMENT
+ : '/*' .*? '*/' -> channel(HIDDEN)
+ ;
+ WS : [ \r\t\u000C\n]+ -> channel(HIDDEN)
+ ;
+ LINE_COMMENT
+ : '//' ~[\r\n]* '\r'? '\n' -> channel(HIDDEN)
+ ;
+
+ // Additional rules
+ INTEGER : DIGIT+;
+ DATE_ARG : DIGIT DIGIT DIGIT DIGIT '-' DIGIT DIGIT '-' DIGIT DIGIT;
+ LEFT_CURLY_BRACE : '{';
+ RIGHT_CURLY_BRACE : '}';
+ IDENTIFIER : (ALPHA | '_')
+ (ALPHA | DIGIT | '_' | '-' | '.')*;
+ STMTEND : ';';
+ DQUOTE : '"';
+ COLON : ':';
+ PLUS : '+';
+ MINUS: '-';
+
+ STRING : ((~( '\r' | '\n' | '\t' | ' ' | ';' | '{' | '"' | '\'')~( '\r' | '\n' | '\t' | ' ' | ';' | '{' )* ) | SUB_STRING );
+
+ //Fragment rules
+ fragment SUB_STRING : ('"' (ESC | ~["])*'"') | ('\'' (ESC | ~['])*'\'') ;
+ fragment ESC : '\\' (["\\/bfnrt] | UNICODE) ;
+ fragment UNICODE : 'u' HEX HEX HEX HEX ;
+ fragment HEX : [0-9a-fA-F] ;
+ fragment ALPHA : [A-Za-z];
+ fragment DIGIT : [0-9];
+ fragment URN : [u][r][n];
+ fragment HTTP : [h][t][t][p];
\ No newline at end of file