Bharat saraswal
Committed by Ray Milkey

[ONOS-4616] YANG grouping linker issues fixed.

Change-Id: I741aa9ad1008c02c9a9f90cc117cd43729132129
Showing 28 changed files with 541 additions and 394 deletions
......@@ -225,9 +225,7 @@ public class YangDerivedInfo<T> implements LocationInfo {
* @throws DataModelException a violation in data mode rule
*/
public ResolvableStatus resolve() throws DataModelException {
YangType<?> baseType = getReferredTypeDef().getTypeDefBaseType();
/*
* Checks the data type of the referred typedef, if it's derived,
* obtain effective built-in type and restrictions from it's derived
......@@ -240,7 +238,6 @@ public class YangDerivedInfo<T> implements LocationInfo {
if (baseType.getResolvableStatus() != INTRA_FILE_RESOLVED && baseType.getResolvableStatus() != RESOLVED) {
throw new DataModelException("Linker Error: Referred typedef is not resolved for type.");
}
/*
* Check if the referred typedef is intra file resolved, if yes sets
* current status also to intra file resolved .
......@@ -250,7 +247,7 @@ public class YangDerivedInfo<T> implements LocationInfo {
}
setEffectiveBuiltInType(((YangDerivedInfo<?>) baseType.getDataTypeExtendedInfo())
.getEffectiveBuiltInType());
YangDerivedInfo refDerivedInfo = ((YangDerivedInfo<?>) baseType.getDataTypeExtendedInfo());
YangDerivedInfo refDerivedInfo = (YangDerivedInfo<?>) baseType.getDataTypeExtendedInfo();
/*
* Check whether the effective built-in type can have range
* restrictions, if yes call resolution of range.
......@@ -327,7 +324,7 @@ public class YangDerivedInfo<T> implements LocationInfo {
}
}
} else {
setEffectiveBuiltInType((baseType.getDataType()));
setEffectiveBuiltInType(baseType.getDataType());
/*
* Check whether the effective built-in type can have range
* restrictions, if yes call resolution of range.
......@@ -404,7 +401,6 @@ public class YangDerivedInfo<T> implements LocationInfo {
}
}
}
/*
* Check if the data type is the one which can't be restricted, in
* this case check whether no self restrictions should be present.
......@@ -418,7 +414,6 @@ public class YangDerivedInfo<T> implements LocationInfo {
throw new DataModelException("YANG file error: Restrictions can't be applied to a given type");
}
}
// Throw exception for unsupported types
throw new DataModelException("Linker error: Unable to process the derived type.");
}
......@@ -438,7 +433,7 @@ public class YangDerivedInfo<T> implements LocationInfo {
* Check that range restriction should be null when built-in type is
* string.
*/
if (!(Strings.isNullOrEmpty(getRangeRestrictionString()))) {
if (!Strings.isNullOrEmpty(getRangeRestrictionString())) {
DataModelException dataModelException = new DataModelException("YANG file error: Range restriction " +
"should't be present for string data type.");
dataModelException.setLine(lineNumber);
......@@ -605,7 +600,7 @@ public class YangDerivedInfo<T> implements LocationInfo {
* Check that string restriction should be null when built-in type is
* of range type.
*/
if (!(Strings.isNullOrEmpty(getLengthRestrictionString())) || getPatternRestriction() != null) {
if (!Strings.isNullOrEmpty(getLengthRestrictionString()) || getPatternRestriction() != null) {
DataModelException dataModelException = new DataModelException("YANG file error: Length/Pattern " +
"restriction should't be present for int/uint/decimal data type.");
dataModelException.setLine(lineNumber);
......@@ -660,12 +655,12 @@ public class YangDerivedInfo<T> implements LocationInfo {
* @return true, if data type can't be restricted, false otherwise
*/
private boolean isOfValidNonRestrictedType(YangDataTypes dataType) {
return (dataType == BOOLEAN
return dataType == BOOLEAN
|| dataType == ENUMERATION
|| dataType == BITS
|| dataType == EMPTY
|| dataType == UNION
|| dataType == IDENTITYREF
|| dataType == LEAFREF);
|| dataType == LEAFREF;
}
}
......
......@@ -271,6 +271,7 @@ public class YangModule extends YangNode
*
* @return the list of imported modules
*/
@Override
public List<YangImport> getImportList() {
return importList;
}
......@@ -280,6 +281,7 @@ public class YangModule extends YangNode
*
* @param importedModule module being imported
*/
@Override
public void addToImportList(YangImport importedModule) {
getImportList().add(importedModule);
}
......@@ -294,6 +296,7 @@ public class YangModule extends YangNode
*
* @return the included list of sub modules
*/
@Override
public List<YangInclude> getIncludeList() {
return includeList;
}
......@@ -303,6 +306,7 @@ public class YangModule extends YangNode
*
* @param includeModule submodule being included
*/
@Override
public void addToIncludeList(YangInclude includeModule) {
getIncludeList().add(includeModule);
}
......@@ -393,6 +397,7 @@ public class YangModule extends YangNode
*
* @return the prefix
*/
@Override
public String getPrefix() {
return prefix;
}
......@@ -402,6 +407,7 @@ public class YangModule extends YangNode
*
* @param prefix the prefix to set
*/
@Override
public void setPrefix(String prefix) {
this.prefix = prefix;
}
......
......@@ -285,6 +285,7 @@ public class YangSubModule extends YangNode
*
* @return the list of imported modules
*/
@Override
public List<YangImport> getImportList() {
return importList;
}
......@@ -294,6 +295,7 @@ public class YangSubModule extends YangNode
*
* @param importedModule module being imported
*/
@Override
public void addToImportList(YangImport importedModule) {
getImportList().add(importedModule);
}
......@@ -308,6 +310,7 @@ public class YangSubModule extends YangNode
*
* @return the included list of sub modules
*/
@Override
public List<YangInclude> getIncludeList() {
return includeList;
}
......@@ -317,6 +320,7 @@ public class YangSubModule extends YangNode
*
* @param includeModule submodule being included
*/
@Override
public void addToIncludeList(YangInclude includeModule) {
getIncludeList().add(includeModule);
}
......
......@@ -187,7 +187,7 @@ public class YangTypeDef extends YangNode implements YangCommonInfo, Parsable, Y
* @return the data type
*/
public YangType<?> getTypeDefBaseType() {
if (!(getTypeList().isEmpty())) {
if (!getTypeList().isEmpty()) {
return getTypeList().get(0);
}
return null;
......
......@@ -271,8 +271,8 @@ public class YangUses
}
YangNode usesParentNode = getParentNodeInGenCode(this);
if ((!(usesParentNode instanceof YangLeavesHolder))
|| (!(usesParentNode instanceof CollisionDetector))) {
if (!(usesParentNode instanceof YangLeavesHolder)
|| !(usesParentNode instanceof CollisionDetector)) {
throw new LinkerException("Linker Exception: YANG uses holder construct is wrong");
}
......
......@@ -696,7 +696,7 @@ public class YangResolutionInfo<T> implements LocationInfo {
* 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 (getRefPrefix() != null && !getRefPrefix().contentEquals(getCurReferenceResolver().getPrefix())) {
if (resolveWithImport()) {
return;
}
......
......@@ -77,23 +77,8 @@ public final class JavaCodeGeneratorUtil {
while (codeGenNode != null) {
if (curTraversal != PARENT) {
if (codeGenNode instanceof JavaCodeGenerator) {
setCurNode(codeGenNode);
generateCodeEntry(codeGenNode, yangPlugin);
} else {
/*
* For grouping and uses, there is no code generation, skip the generation for the child.
*/
if (codeGenNode.getNextSibling() != null) {
curTraversal = SIBILING;
codeGenNode = codeGenNode.getNextSibling();
} else {
curTraversal = PARENT;
codeGenNode = codeGenNode.getParent();
}
continue;
}
setCurNode(codeGenNode);
generateCodeEntry(codeGenNode, yangPlugin);
}
if (curTraversal != PARENT && codeGenNode.getChild() != null) {
curTraversal = CHILD;
......
......@@ -112,7 +112,7 @@ public class JavaQualifiedTypeInfo
*/
importInfo.setClassInfo(className);
String classPkg = AttributesJavaDataType.getJavaImportPackage(leaf.getDataType(),
leaf.isLeafList(), className, leaf.getConflictResolveConfig());
leaf.isLeafList(), leaf.getConflictResolveConfig());
if (classPkg == null) {
throw new TranslatorException("import package cannot be null when the class is used");
}
......@@ -180,7 +180,7 @@ public class JavaQualifiedTypeInfo
qualifiedInfoOfFromString.setClassInfo(
getJavaImportClass(referredTypesAttrInfo.getAttributeType(), true, conflictResolver));
qualifiedInfoOfFromString.setPkgInfo(
getJavaImportPackage(referredTypesAttrInfo.getAttributeType(), true, null, conflictResolver));
getJavaImportPackage(referredTypesAttrInfo.getAttributeType(), true, conflictResolver));
return qualifiedInfoOfFromString;
}
......
......@@ -28,6 +28,12 @@ import org.onosproject.yangutils.datamodel.YangLeavesHolder;
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.YangJavaInput;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaOutput;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaUses;
import org.onosproject.yangutils.translator.tojava.utils.JavaExtendsListHolder;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
......@@ -61,6 +67,7 @@ import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSy
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.getParentNodeInGenCode;
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;
......@@ -1078,6 +1085,9 @@ public class TempJavaFragmentFiles {
if (!(parent instanceof JavaCodeGenerator)) {
throw new TranslatorException("missing parent node to contain current node info in generated file");
}
if (curNode instanceof YangJavaUses) {
curNode = ((YangJavaUses) curNode).getRefGroup();
}
JavaAttributeInfo javaAttributeInfo = getCurNodeAsAttributeInParent(curNode,
parent, isList);
if (!(parent instanceof TempJavaCodeFragmentFilesContainer)) {
......@@ -1100,23 +1110,57 @@ public class TempJavaFragmentFiles {
*/
public static JavaAttributeInfo getCurNodeAsAttributeInParent(
YangNode curNode, YangNode parentNode, boolean isListNode) {
String 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(parentNode,
getCapitalCase(curNodeName));
YangPluginConfig pluginConfig = ((JavaFileInfoContainer) parentNode).getJavaFileInfo().getPluginConfig();
JavaFileInfo curNodeJavaInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
String curNodeName = null;
if (curNodeJavaInfo.getJavaName() != null) {
curNodeName = curNodeJavaInfo.getJavaName();
} else {
curNodeName = getCamelCase(curNode.getName(), pluginConfig.getConflictResolver());
}
if (!(parentNode instanceof TempJavaCodeFragmentFilesContainer)) {
throw new TranslatorException("Parent node does not have file info");
}
TempJavaFragmentFiles tempJavaFragmentFiles = getNodesInterfaceFragmentFiles(parentNode);
boolean isQualified = true;
JavaImportData parentImportData = tempJavaFragmentFiles.getJavaImportData();
if (isListNode) {
parentImportData.setIfListImported(true);
}
if (!detectCollisionBwParentAndChildForImport(curNode, qualifiedTypeInfo)) {
/*
* Get the import info corresponding to the attribute for import in
* generated java files or qualified access
*/
JavaQualifiedTypeInfo qualifiedTypeInfo = new JavaQualifiedTypeInfo();
if (curNode instanceof YangJavaGrouping) {
qualifiedTypeInfo = resolveGroupingsQuailifiedInfo(curNode, pluginConfig);
} else {
qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(parentNode,
getCapitalCase(curNodeName));
}
if (parentNode instanceof YangJavaModule
|| parentNode instanceof YangJavaSubModule
|| parentNode instanceof YangJavaInput
|| parentNode instanceof YangJavaOutput) {
parentImportData.addImportInfo(qualifiedTypeInfo);
isQualified = false;
} else if (curNode instanceof YangJavaGrouping) {
JavaFileInfo parentsClassInfo = ((JavaFileInfoContainer) parentNode).getJavaFileInfo();
if (qualifiedTypeInfo.getClassInfo().equals(parentsClassInfo.getJavaName())) {
isQualified = true;
}
if (!qualifiedTypeInfo.getPkgInfo().equals(parentsClassInfo.getPackage())) {
parentImportData.addImportInfo(qualifiedTypeInfo);
isQualified = false;
}
} else if (!detectCollisionBwParentAndChildForImport(curNode, qualifiedTypeInfo)) {
parentImportData.addImportInfo(qualifiedTypeInfo);
isQualified = false;
}
......@@ -1124,6 +1168,63 @@ public class TempJavaFragmentFiles {
}
/**
* 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
......
......@@ -39,7 +39,10 @@ import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.
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.AttributesJavaDataType.getJavaDataType;
import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getJavaImportClass;
import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getJavaClassDefClose;
import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getListAttribute;
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;
......@@ -48,6 +51,7 @@ import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerato
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;
......@@ -440,33 +444,129 @@ public class TempJavaServiceFragmentFiles
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 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
* @param isInputLeafHolder if input node is leaf holder
* @param isOutputLeafHolder if output node is leaf holder
* @param isInputSingleChildHolder if input node is single child holder
* @param isOutputSingleChildHolder if input node is single child holder
* @throws IOException IO operation fail
*/
public void addRpcString(JavaAttributeInfo javaAttributeInfoOfInput,
JavaAttributeInfo javaAttributeInfoOfOutput, YangPluginConfig pluginConfig,
String rpcName, boolean isInputLeafHolder, boolean isOutputLeafHolder,
boolean isInputSingleChildHolder, boolean isOutputSingleChildHolder) throws IOException {
String rpcInput = EMPTY_STRING;
String rpcOutput = VOID;
String rpcInputJavaDoc = EMPTY_STRING;
if (javaAttributeInfoOfInput != null) {
rpcInput = getInputOutputNames(javaAttributeInfoOfInput, isInputLeafHolder, isInputSingleChildHolder,
pluginConfig);
}
if (javaAttributeInfoOfOutput != null) {
rpcOutput =
getInputOutputNames(javaAttributeInfoOfOutput, isOutputLeafHolder, isOutputSingleChildHolder,
pluginConfig);
}
if (!rpcInput.equals(EMPTY_STRING)) {
rpcInputJavaDoc = RPC_INPUT_VAR_NAME;
}
appendToFile(getRpcInterfaceTempFileHandle(),
generateJavaDocForRpc(rpcName, RPC_INPUT_VAR_NAME, rpcOutput, pluginConfig)
generateJavaDocForRpc(rpcName, rpcInputJavaDoc, rpcOutput, pluginConfig)
+ getRpcServiceMethod(rpcName, rpcInput, rpcOutput, pluginConfig) + NEW_LINE);
appendToFile(getRpcImplTempFileHandle(),
getRpcManagerMethod(rpcName, rpcInput, rpcOutput, pluginConfig) + NEW_LINE);
}
/**
* Returns names for input and output.
*
* @param attr attribute info
* @param isLeafHolder if leaf holder
* @param isSinglechildHolder if single child holder
* @param pluginConfig plugin configurations
* @return names for input and output
*/
private String getInputOutputNames(JavaAttributeInfo attr, boolean isLeafHolder, boolean isSinglechildHolder,
YangPluginConfig pluginConfig) {
if (!attr.isListAttr()) {
if (!isLeafHolder || isSinglechildHolder) {
String attrName = "";
if (!attr.isQualifiedName()) {
attrName = getCapitalCase(attr.getAttributeName());
} else {
attrName = attr.getImportInfo().getPkgInfo() + "." + getCapitalCase(attr.getAttributeName());
}
return attrName;
} else {
String rpcInput = getJavaImportClass(attr.getAttributeType(), false,
pluginConfig.getConflictResolver());
if (rpcInput == null) {
rpcInput = getJavaDataType(attr.getAttributeType());
}
return rpcInput;
}
} else {
if (!isLeafHolder || isSinglechildHolder) {
String attrName = "";
if (!attr.isQualifiedName()) {
attrName = getCapitalCase(attr.getAttributeName());
} else {
attrName = attr.getImportInfo().getPkgInfo() + "." + getCapitalCase(attr.getAttributeName());
}
return getListAttribute(attrName);
} else {
return getListAttribute(getJavaImportClass(attr.getAttributeType(), true,
pluginConfig.getConflictResolver()));
}
}
}
/**
* 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
* @param isInputLeafHolder if input node is leaf holder
* @param isOutputLeafHolder if output node is leaf holder
* @param isInputSingleChildHolder if input node is single child holder
* @param isOutputSingleChildHolder if input node is single child holder
* @throws IOException IO operation fail
*/
public void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo javaAttributeInfoOfInput,
JavaAttributeInfo javaAttributeInfoOfOutput, YangPluginConfig pluginConfig,
String rpcName)
String rpcName, boolean isInputLeafHolder, boolean isOutputLeafHolder,
boolean isInputSingleChildHolder, boolean isOutputSingleChildHolder)
throws IOException {
addRpcString(javaAttributeInfoOfInput, javaAttributeInfoOfOutput, pluginConfig, rpcName);
addRpcString(javaAttributeInfoOfInput, javaAttributeInfoOfOutput, pluginConfig, rpcName, isInputLeafHolder,
isOutputLeafHolder, isInputSingleChildHolder, isOutputSingleChildHolder);
}
/**
......@@ -690,6 +790,7 @@ public class TempJavaServiceFragmentFiles
String currentInfo = getCapitalCase(getCamelCase(((YangNotification) curNode).getName(),
pluginConfig.getConflictResolver()));
String notificationName = ((YangNotification) curNode).getName();
JavaQualifiedTypeInfo qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(curNode.getParent(),
getCapitalCase(currentInfo));
......@@ -699,7 +800,7 @@ public class TempJavaServiceFragmentFiles
null, false, false);
/*Adds java info for event in respective temp files.*/
addEventEnum(currentInfo, pluginConfig);
addEventEnum(notificationName, pluginConfig);
addEventSubjectAttribute(javaAttributeInfo, pluginConfig);
addEventSubjectGetter(javaAttributeInfo, pluginConfig);
addEventSubjectSetter(javaAttributeInfo, pluginConfig, currentInfo);
......@@ -709,7 +810,7 @@ public class TempJavaServiceFragmentFiles
private void addEventEnum(String notificationName, YangPluginConfig pluginConfig) throws IOException {
appendToFile(getEventEnumTempFileHandle(),
getJavaDoc(ENUM_ATTRIBUTE, notificationName, false, pluginConfig) + FOUR_SPACE_INDENTATION
+ notificationName.toUpperCase() + COMMA + NEW_LINE);
+ getEnumJavaAttribute(notificationName).toUpperCase() + COMMA + NEW_LINE);
}
/*Adds event method in event class*/
......
......@@ -15,18 +15,116 @@
*/
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.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfNode;
/**
* Represents grouping information extended to support java code generation.
*/
public class YangJavaGrouping
extends YangGrouping {
extends YangGrouping implements JavaCodeGeneratorInfo, JavaCodeGenerator {
/**
* 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 TempJavaCodeFragmentFiles tempFileHandle;
/**
* Creates YANG Java grouping object.
*/
public YangJavaGrouping() {
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
* grouping info.
*
* @param yangPlugin YANG plugin config
* @throws TranslatorException translator operation fail
*/
@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 container node " + this.getName());
}
}
/**
* Create a java file using the YANG grouping 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 " + this.getName());
}
}
}
......
......@@ -26,7 +26,7 @@ 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.generateCodeOfNode;
import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfAugmentableNode;
/**
* Represents input information extended to support java code generation.
......@@ -46,6 +46,8 @@ public class YangJavaInput
*/
private TempJavaCodeFragmentFiles tempFileHandle;
private boolean codeGenFlag;
/**
* Creates an instance of java input.
*/
......@@ -108,7 +110,7 @@ public class YangJavaInput
@Override
public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
try {
generateCodeOfNode(this, yangPlugin);
generateCodeOfAugmentableNode(this, yangPlugin);
} catch (IOException e) {
throw new TranslatorException(
"Failed to prepare generate code entry for input node " + this.getName());
......@@ -123,9 +125,29 @@ public class YangJavaInput
@Override
public void generateCodeExit() throws TranslatorException {
try {
getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
if (isCodeGenFlag()) {
getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
}
} catch (IOException e) {
throw new TranslatorException("Failed to generate code for input node " + this.getName());
}
}
/**
* Returns code generator flag.
*
* @return code generator flag
*/
public boolean isCodeGenFlag() {
return codeGenFlag;
}
/**
* Sets code generator flag.
*
* @param codeGenFlag code generator flag
*/
public void setCodeGenFlag(boolean codeGenFlag) {
this.codeGenFlag = codeGenFlag;
}
}
......
......@@ -71,6 +71,7 @@ public class YangJavaLeaf
*
* @return java naming conflict resolve configurations
*/
@Override
public YangToJavaNamingConflictUtil getConflictResolveConfig() {
return conflictResolveConfig;
}
......@@ -80,6 +81,7 @@ public class YangJavaLeaf
*
* @param conflictResolveConfig java naming conflict resolve configurations
*/
@Override
public void setConflictResolveConfig(YangToJavaNamingConflictUtil conflictResolveConfig) {
this.conflictResolveConfig = conflictResolveConfig;
}
......
......@@ -26,7 +26,7 @@ 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.generateCodeOfNode;
import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.generateCodeOfAugmentableNode;
/**
* Represents output information extended to support java code generation.
......@@ -46,6 +46,8 @@ public class YangJavaOutput
*/
private TempJavaCodeFragmentFiles tempFileHandle;
private boolean codeGenFlag;
/**
* Creates an instance of java output.
*/
......@@ -108,7 +110,7 @@ public class YangJavaOutput
@Override
public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
try {
generateCodeOfNode(this, yangPlugin);
generateCodeOfAugmentableNode(this, yangPlugin);
} catch (IOException e) {
throw new TranslatorException(
"Failed to prepare generate code entry for output node " + this.getName());
......@@ -124,10 +126,30 @@ public class YangJavaOutput
@Override
public void generateCodeExit() throws TranslatorException {
try {
getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
if (isCodeGenFlag()) {
getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
}
} catch (IOException e) {
throw new TranslatorException(
"Failed to prepare generate code exit for output node " + this.getName());
}
}
/**
* Returns code generator flag.
*
* @return code generator flag
*/
public boolean isCodeGenFlag() {
return codeGenFlag;
}
/**
* Sets code generator flag.
*
* @param codeGenFlag code generator flag
*/
public void setCodeGenFlag(boolean codeGenFlag) {
this.codeGenFlag = codeGenFlag;
}
}
......
......@@ -55,7 +55,7 @@ public class YangJavaType<T>
*/
importInfo.setClassInfo(className);
String classPkg = AttributesJavaDataType.getJavaImportPackage(this,
false, className, conflictResolver);
false, conflictResolver);
if (classPkg == null) {
throw new TranslatorException("import package cannot be null when the class is used");
}
......
......@@ -15,18 +15,113 @@
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
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.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.TempJavaFragmentFiles.addCurNodeInfoInParentTempFile;
/**
* Represents uses information extended to support java code generation.
*/
public class YangJavaUses
extends YangUses {
extends YangUses implements JavaCodeGeneratorInfo, JavaCodeGenerator {
/**
* 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 TempJavaCodeFragmentFiles tempFileHandle;
/**
* Creates YANG java uses object.
*/
public YangJavaUses() {
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
* uses info.
*
* @param yangPlugin YANG plugin config
* @throws TranslatorException translator operation fail
*/
@Override
public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
try {
addCurNodeInfoInParentTempFile(this, false, yangPlugin);
} catch (IOException e) {
throw new TranslatorException(
"Failed to prepare generate code entry for container node " + this.getName());
}
}
/**
* Create a java file using the YANG uses info.
*
* @throws TranslatorException translator operation fail
*/
@Override
public void generateCodeExit() throws TranslatorException {
// no code generation will be done for uses.
}
}
......
......@@ -270,11 +270,10 @@ public final class AttributesJavaDataType {
*
* @param yangType YANG type
* @param isListAttr if the attribute is of list type
* @param classInfo java import class info
* @param conflictResolver object of YANG to java naming conflict util
* @return java import package
*/
public static String getJavaImportPackage(YangType<?> yangType, boolean isListAttr, String classInfo,
public static String getJavaImportPackage(YangType<?> yangType, boolean isListAttr,
YangToJavaNamingConflictUtil conflictResolver) {
YangDataTypes type = yangType.getDataType();
......@@ -430,13 +429,13 @@ public final class AttributesJavaDataType {
YangJavaModule module = (YangJavaModule) parent;
String modulePkg = getRootPackage(module.getVersion(), module.getNameSpace().getUri(), module
.getRevision().getRevDate(), conflictResolver);
return modulePkg + PERIOD + getCamelCase(module.getName(), null).toLowerCase();
return modulePkg + PERIOD + getCamelCase(module.getName(), conflictResolver).toLowerCase();
} else if (parent instanceof YangJavaSubModule) {
YangJavaSubModule submodule = (YangJavaSubModule) parent;
String subModulePkg = getRootPackage(submodule.getVersion(),
submodule.getNameSpaceFromModule(submodule.getBelongsTo()),
submodule.getRevision().getRevDate(), conflictResolver);
return subModulePkg + PERIOD + getCamelCase(submodule.getName(), null).toLowerCase();
return subModulePkg + PERIOD + getCamelCase(submodule.getName(), conflictResolver).toLowerCase();
}
}
return parentInfo.getPackage() + PERIOD + parentInfo.getJavaName().toLowerCase();
......
......@@ -115,7 +115,7 @@ public final class JavaCodeSnippetGen {
* @param type attribute type
* @return list attribute string
*/
private static String getListAttribute(String type) {
public static String getListAttribute(String type) {
return LIST + DIAMOND_OPEN_BRACKET + type + DIAMOND_CLOSE_BRACKET;
}
......
......@@ -366,7 +366,7 @@ public final class JavaIdentifierSyntax {
i = 1;
}
for (; i < stringArray.length; i++) {
if ((i + 1) == stringArray.length) {
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();
......
......@@ -265,7 +265,7 @@ public final class MethodsGenerator {
* @return getter for attribute
*/
public static String getGetter(String type, String name, int generatedJavaFiles) {
String ret = parseTypeForGetter(type);
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 +
......@@ -281,7 +281,7 @@ public final class MethodsGenerator {
}
/*Provides string to return for type.*/
private static String parseTypeForGetter(String type) {
private static String parseTypeForReturnValue(String type) {
switch (type) {
case BYTE:
case INT:
......@@ -555,12 +555,11 @@ public final class MethodsGenerator {
YangPluginConfig pluginConfig) {
rpcName = getCamelCase(rpcName, pluginConfig.getConflictResolver());
inputName = getCapitalCase(inputName);
if (!outputName.equals(VOID)) {
outputName = getCapitalCase(outputName);
if (!inputName.equals(EMPTY_STRING)) {
inputName = inputName + SPACE + RPC_INPUT_VAR_NAME;
}
return FOUR_SPACE_INDENTATION + outputName + SPACE + rpcName + OPEN_PARENTHESIS + inputName + SPACE
+ RPC_INPUT_VAR_NAME + CLOSE_PARENTHESIS + SEMI_COLAN;
return FOUR_SPACE_INDENTATION + outputName + SPACE + rpcName + OPEN_PARENTHESIS + inputName
+ CLOSE_PARENTHESIS + SEMI_COLAN;
}
/**
......@@ -576,16 +575,17 @@ public final class MethodsGenerator {
YangPluginConfig pluginConfig) {
rpcName = getCamelCase(rpcName, pluginConfig.getConflictResolver());
inputName = getCapitalCase(inputName);
if (!outputName.equals(VOID)) {
outputName = getCapitalCase(outputName);
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 + SPACE + RPC_INPUT_VAR_NAME + CLOSE_PARENTHESIS + SPACE
+ OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + YANG_UTILS_TODO + NEW_LINE;
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 + NULL + SEMI_COLAN + NEW_LINE;
method += EIGHT_SPACE_INDENTATION + RETURN + SPACE + parseTypeForReturnValue(outputName) + SEMI_COLAN
+ NEW_LINE;
}
method += FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
......
......@@ -29,7 +29,10 @@ 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.YangJavaInput;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaOutput;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
import static java.util.Collections.sort;
......@@ -339,6 +342,12 @@ public final class TempJavaCodeFragmentFilesUtils {
JavaQualifiedTypeInfo qualifiedTypeInfo) {
YangNode parent = curNode.getParent();
if (parent instanceof YangJavaModule
|| parent instanceof YangJavaSubModule
|| parent instanceof YangJavaInput
|| parent instanceof YangJavaOutput) {
return false;
}
String parentsClassInfo = getCapitalCase(((JavaFileInfoContainer) parent).getJavaFileInfo().getJavaName());
String childsClassInfo = qualifiedTypeInfo.getClassInfo();
if (childsClassInfo.equals(parentsClassInfo)) {
......
......@@ -24,6 +24,7 @@ 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;
......@@ -298,8 +299,10 @@ public final class JavaDocGen {
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
+ getInputString(inputName, rpcName);
+ 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);
}
......@@ -406,7 +409,8 @@ public final class JavaDocGen {
} else {
setter = setter + VALUE + SPACE + OF + SPACE;
}
setter = setter + attribute + NEW_LINE + FOUR_SPACE_INDENTATION + JAVA_DOC_RETURN + BUILDER_OBJECT + attribute
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;
}
......
......@@ -433,7 +433,20 @@ public final class YangIoUtils {
} else {
stringBuilder.append(line + NEW_LINE);
}
return stringBuilder.toString();
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.*/
......
/*
* 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.parseutils;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.onosproject.yangutils.utils.YangConstructType.CONTACT_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;
/**
* Test case for testing listener error message construction util.
*/
public class ListenerErrorMessageConstructionTest {
/**
* Checks for error message construction with parsable data type name.
*/
@Test
public void checkErrorMsgConstructionWithName() {
// Create an test error message
String testErrorMessage = constructListenerErrorMessage(INVALID_HOLDER, CONTACT_DATA, "Test Instance", ENTRY);
// Check message.
assertThat(testErrorMessage, is("Internal parser error detected: Invalid holder for contact "
+ "\"Test Instance\" before processing."));
}
/**
* Checks for error message construction without parsable data type name.
*/
@Test
public void checkErrorMsgConstructionWithoutName() {
// Create an test error message
String testErrorMessage = constructListenerErrorMessage(INVALID_HOLDER, CONTACT_DATA, "Test Instance", ENTRY);
// Check message.
assertThat(testErrorMessage,
is("Internal parser error detected: Invalid holder for contact \"Test Instance\""
+ " before processing."));
}
/**
* Checks for extended error message construction with parsable data type
* name.
*/
@Test
public void checkExtendedErrorMsgConstructionWithName() {
// Create an test error message
String testErrorMessage = constructExtendedListenerErrorMessage(INVALID_HOLDER, CONTACT_DATA,
"Test Instance", ENTRY,
"Extended Information");
// Check message.
assertThat(testErrorMessage,
is("Internal parser error detected: Invalid holder for contact \"Test Instance\""
+ " before processing.\n" + "Error Information: Extended Information"));
}
/**
* Checks for extended error message construction without parsable data type
* name.
*/
@Test
public void checkExtendedErrorMsgConstructionWithoutName() {
// Create an test error message
String testErrorMessage = constructExtendedListenerErrorMessage(INVALID_HOLDER, CONTACT_DATA, "", ENTRY,
"Extended Information");
// Check message.
assertThat(testErrorMessage, is("Internal parser error detected: Invalid holder for contact"
+ " before processing.\n" + "Error Information: Extended Information"));
}
}
/*
* 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.parseutils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onosproject.yangutils.datamodel.YangRevision;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.TreeWalkListener;
import static org.onosproject.yangutils.utils.YangConstructType.YANGBASE_DATA;
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.MISSING_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsEmpty;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
/**
* Test case for testing listener validation util.
*/
public class ListenerValidationTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Checks for exception in case parsable stack is empty while validating for
* not empty scenario.
*/
@Test
public void validateStackIsNotEmptyForEmptyStack() {
String expectedError = constructListenerErrorMessage(MISSING_HOLDER, YANGBASE_DATA, "", EXIT);
// Get the exception occurred during parsing.
thrown.expect(ParserException.class);
thrown.expectMessage(expectedError);
// Create test walker and assign test error to it.
TreeWalkListener testWalker = new TreeWalkListener();
checkStackIsNotEmpty(testWalker, MISSING_HOLDER, YANGBASE_DATA, "", EXIT);
}
/**
* Checks if there is no exception in case parsable stack is not empty while
* validating for not empty scenario.
*/
@Test
public void validateStackIsNotEmptyForNonEmptyStack() {
// Create test walker and assign test error to it.
TreeWalkListener testWalker = new TreeWalkListener();
// Create a temporary node of parsable.
YangRevision tmpNode = new YangRevision();
testWalker.getParsedDataStack().push(tmpNode);
checkStackIsNotEmpty(testWalker, MISSING_HOLDER, YANGBASE_DATA, "", EXIT);
}
/**
* Checks for exception in case parsable stack is not empty while validating
* for empty scenario.
*/
@Test
public void validateStackIsEmptyForNonEmptyStack() {
String expectedError = constructListenerErrorMessage(MISSING_HOLDER, YANGBASE_DATA, "", EXIT);
// Get the exception occurred during parsing.
thrown.expect(ParserException.class);
thrown.expectMessage(expectedError);
// Create test walker and assign test error to it.
TreeWalkListener testWalker = new TreeWalkListener();
// Create a temporary node of parsable.
YangRevision tmpNode = new YangRevision();
testWalker.getParsedDataStack().push(tmpNode);
checkStackIsEmpty(testWalker, MISSING_HOLDER, YANGBASE_DATA, "", EXIT);
}
/**
* Checks if there is no exception in case parsable stack is empty while
* validating for empty scenario.
*/
@Test
public void validateStackIsEmptyForEmptyStack() {
// Create test walker and assign test error to it.
TreeWalkListener testWalker = new TreeWalkListener();
checkStackIsEmpty(testWalker, MISSING_HOLDER, YANGBASE_DATA, "", EXIT);
}
}
/*
* 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.parseutils;
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.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
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.CustomExceptionMatcher;
import org.onosproject.yangutils.parser.impl.YangUtilsParserManager;
import org.onosproject.yangutils.parser.impl.parserutils.ParseTreeErrorListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
/**
* Test case for testing parse tree error listener.
*/
public class ParseTreeErrorListenerTest {
YangUtilsParserManager manager = new YangUtilsParserManager();
File file;
BufferedWriter out;
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Checks that no exception is generated for YANG file with valid syntax.
*/
@Test
public void checkValidYangFileForNoSyntaxError() throws IOException {
ANTLRInputStream input = new ANTLRFileStream("src/test/resources/YangFileWithoutSyntaxError.yang");
// 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);
// Begin parsing YANG file and generate parse tree.
ParseTree tree = parser.yangfile();
}
/**
* Checks that exception is generated for YANG file with invalid syntax.
*/
@Test
public void checkInvalidYangFileForSyntaxError() throws IOException {
// Get the exception occurred during parsing.
thrown.expect(ParserException.class);
thrown.expect(CustomExceptionMatcher.errorLocation(3, 0));
thrown.expectMessage("no viable alternative at input 'yang-version 1\\nnamespace'");
ANTLRInputStream input = new ANTLRFileStream("src/test/resources/YangFileWithSyntaxError.yang");
// 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);
// Begin parsing YANG file and generate parse tree.
ParseTree tree = parser.yangfile();
}
}
\ No newline at end of file
......@@ -125,16 +125,16 @@ public class AttributesJavaDataTypeTest {
*/
@Test
public void testgetJavaPkgInfo() {
test = getJavaImportPackage(getStubYangType(TYPE1), false, CLASS_INFO1, pluginConfig);
test = getJavaImportPackage(getStubYangType(TYPE1), false, pluginConfig);
assertThat(true, is(test.equals(JAVA_LANG)));
test = getJavaImportPackage(getStubYangType(TYPE2), true, CLASS_INFO5, pluginConfig);
test = getJavaImportPackage(getStubYangType(TYPE2), true, pluginConfig);
assertThat(true, is(test.equals(JAVA_LANG)));
test = getJavaImportPackage(getStubYangType(TYPE3), false, CLASS_INFO3, pluginConfig);
test = getJavaImportPackage(getStubYangType(TYPE3), false, pluginConfig);
assertThat(null, is(test));
test = getJavaImportPackage(getStubYangType(TYPE4), false, CLASS_INFO4, pluginConfig);
test = getJavaImportPackage(getStubYangType(TYPE4), false, pluginConfig);
assertThat(null, is(test));
}
......@@ -145,7 +145,7 @@ public class AttributesJavaDataTypeTest {
*/
@Test
public void testForTypeDef() throws DataModelException {
test = getJavaImportPackage(getStubExtendedInfo(getStubYangType(TYPE_DEF)), false, TYPE_DEF_PKG, pluginConfig);
test = getJavaImportPackage(getStubExtendedInfo(getStubYangType(TYPE_DEF)), false, pluginConfig);
assertThat(true, is(test.equals(TYPE_DEF_PKG)));
}
......