Bharat saraswal

[ONOS-4616] grouping linker issues fixed and other defect fixed.

Change-Id: I1b23f9ed0293edbc2d551efe82982559eb916ede
Showing 109 changed files with 2041 additions and 891 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;
}
}
......
......@@ -50,7 +50,7 @@ import org.onosproject.yangutils.utils.YangConstructType;
/**
* Represents the ENUM data type information.
*/
public class YangEnum implements YangCommonInfo, Parsable {
public class YangEnum implements YangCommonInfo, Parsable, Comparable<YangEnum> {
/**
* Named value for the ENUM.
......@@ -226,4 +226,12 @@ public class YangEnum implements YangCommonInfo, Parsable {
public void validateDataOnExit() throws DataModelException {
// TODO auto-generated method stub, to be implemented by parser
}
@Override
public int compareTo(YangEnum otherEnum) {
if (this.namedValue.equals(otherEnum.getNamedValue())) {
return 0;
}
return new Integer(this.value).compareTo(otherEnum.getValue());
}
}
......
......@@ -16,8 +16,8 @@
package org.onosproject.yangutils.datamodel;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
......@@ -31,10 +31,10 @@ import org.onosproject.yangutils.utils.YangConstructType;
/**
* Represents the enumeration data type information.
*/
public class YangEnumeration extends YangNode implements Parsable {
public class YangEnumeration extends YangNode implements Parsable, CollisionDetector {
// Enumeration info set.
private Set<YangEnum> enumSet;
private SortedSet<YangEnum> enumSet;
// Enumeration name.
private String name;
......@@ -44,7 +44,7 @@ public class YangEnumeration extends YangNode implements Parsable {
*/
public YangEnumeration() {
super(YangNodeType.ENUMERATION_NODE);
setEnumSet(new HashSet<YangEnum>());
setEnumSet(new TreeSet<YangEnum>());
}
/**
......@@ -52,7 +52,7 @@ public class YangEnumeration extends YangNode implements Parsable {
*
* @return the ENUM set
*/
public Set<YangEnum> getEnumSet() {
public SortedSet<YangEnum> getEnumSet() {
return enumSet;
}
......@@ -61,7 +61,7 @@ public class YangEnumeration extends YangNode implements Parsable {
*
* @param enumSet the ENUM set to set
*/
private void setEnumSet(Set<YangEnum> enumSet) {
private void setEnumSet(SortedSet<YangEnum> enumSet) {
this.enumSet = enumSet;
}
......@@ -126,4 +126,18 @@ public class YangEnumeration extends YangNode implements Parsable {
public void validateDataOnExit() throws DataModelException {
// TODO auto-generated method stub, to be implemented by parser
}
@Override
public void detectCollidingChild(String identifierName, YangConstructType dataType) throws DataModelException {
/*
Do nothing.The implementation for this is not required.
*/
}
@Override
public void detectSelfCollision(String identifierName, YangConstructType dataType) throws DataModelException {
/*
Do nothing.The implementation for this is not required.
*/
}
}
......
......@@ -444,8 +444,8 @@ public class YangList extends YangNode
validateConfig(leaves, leafLists);
/* A list must have atleast one key leaf if config is true */
if (isConfig
&& (keys == null || leaves == null && leafLists == null && !isUsesPresentInList())) {
if (isConfig && (keys == null || leaves == null && leafLists == null) && !isUsesPresentInList()
&& !isListPresentInGrouping()) {
throw new DataModelException("A list must have atleast one key leaf if config is true;");
} else if (keys != null) {
validateKey(leaves, leafLists, keys);
......@@ -565,7 +565,7 @@ public class YangList extends YangNode
}
}
if (!leafFound && !isUsesPresentInList()) {
if (!leafFound && !isUsesPresentInList() && !isListPresentInGrouping()) {
throw new DataModelException("An identifier, in key, must refer to a child leaf of the list");
}
leafFound = false;
......@@ -617,6 +617,18 @@ public class YangList extends YangNode
node = node.getNextSibling();
}
return false;
// TODO When grouping linking is done this method has to be modified.
}
private boolean isListPresentInGrouping() {
YangNode node = this.getParent();
while (node != null) {
if (node instanceof YangGrouping) {
return true;
}
node = node.getParent();
}
return false;
// TODO When grouping linking is done this method has to be modified.
}
}
......
......@@ -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);
}
......
......@@ -21,6 +21,8 @@ import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.utils.YangConstructType;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
/*-
* Reference RFC 6020.
*
......@@ -54,7 +56,7 @@ import org.onosproject.yangutils.utils.YangConstructType;
/**
* Represents data model node to maintain information defined in YANG typedef.
*/
public class YangTypeDef extends YangNode implements YangCommonInfo, Parsable, YangTypeHolder {
public class YangTypeDef extends YangNode implements YangCommonInfo, Parsable, YangTypeHolder, CollisionDetector {
/**
* Default value in string, needs to be converted to the target object,
......@@ -185,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;
......@@ -272,4 +274,18 @@ public class YangTypeDef extends YangNode implements YangCommonInfo, Parsable, Y
public List<YangType<?>> getTypeList() {
return typeList;
}
@Override
public void detectCollidingChild(String identifierName, YangConstructType dataType) throws DataModelException {
// Asks helper to detect colliding child.
detectCollidingChildUtil(identifierName, dataType, this);
}
@Override
public void detectSelfCollision(String identifierName, YangConstructType dataType) throws DataModelException {
if (getName().equals(identifierName)) {
throw new DataModelException("YANG file error: Duplicate input identifier detected, same as typedef \""
+ getName() + "\"");
}
}
}
......
......@@ -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");
}
......
......@@ -65,8 +65,8 @@ public final class DataModelUtils {
while (node != null) {
Parsable parsable = (Parsable) node;
if (node instanceof CollisionDetector
&& (parsable.getYangConstructType() != YangConstructType.USES_DATA)
&& (parsable.getYangConstructType() != YangConstructType.GROUPING_DATA)) {
&& parsable.getYangConstructType() != YangConstructType.USES_DATA
&& parsable.getYangConstructType() != YangConstructType.GROUPING_DATA) {
((CollisionDetector) node).detectSelfCollision(identifierName, dataType);
}
node = node.getNextSibling();
......@@ -90,7 +90,7 @@ public final class DataModelUtils {
while (node != null) {
Parsable parsable = (Parsable) node;
if (node instanceof CollisionDetector
&& (parsable.getYangConstructType() == dataType)) {
&& parsable.getYangConstructType() == dataType) {
((CollisionDetector) node).detectSelfCollision(identifierName, dataType);
}
node = node.getNextSibling();
......
......@@ -34,6 +34,8 @@ import static org.onosproject.yangutils.linker.impl.ResolvableStatus.INTRA_FILE_
import static org.onosproject.yangutils.linker.impl.ResolvableStatus.LINKED;
import static org.onosproject.yangutils.linker.impl.ResolvableStatus.RESOLVED;
import static org.onosproject.yangutils.linker.impl.ResolvableStatus.UNRESOLVED;
import static org.onosproject.yangutils.utils.UtilConstants.TYPEDEF_LINKER_ERROR;
import static org.onosproject.yangutils.utils.UtilConstants.GROUPING_LINKER_ERROR;
/**
* Represents resolution object which will be resolved by linker.
......@@ -180,9 +182,14 @@ public class YangResolutionInfo<T> implements LocationInfo {
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("YANG file error: Unable to find base "
+ "typedef/grouping for given type/uses");
new DataModelException(errorInfo);
dataModelException.setLine(getLineNumber());
dataModelException.setCharPosition(getCharPosition());
throw dataModelException;
......@@ -689,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;
}
......
......@@ -45,6 +45,8 @@ 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.parser.Parsable;
import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
import org.onosproject.yangutils.parser.exceptions.ParserException;
......@@ -101,6 +103,12 @@ public final class BitsListener {
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,
......
......@@ -138,8 +138,8 @@ public final class EnumerationListener {
* integer number, this is done because under union there
* could be multiple child union types.
*/
enumerationNode.setName(yangUnion.getName() + yangUnion.getChildUnionNumber()
+ ENUMERATION_CLASS_SUFFIX);
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.
......
......@@ -106,7 +106,16 @@ public final class MaxElementsListener {
if (value.equals(UNBOUNDED_KEYWORD)) {
maxElementsValue = Integer.MAX_VALUE;
} else if (value.matches(POSITIVE_INTEGER_PATTERN)) {
maxElementsValue = Integer.parseInt(value);
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 " +
......
......@@ -35,6 +35,7 @@ import org.onosproject.yangutils.parser.impl.TreeWalkListener;
import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
import static org.onosproject.yangutils.datamodel.utils.YangDataModelFactory.getYangTypeDefNode;
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;
......@@ -117,6 +118,11 @@ public final class TypeDefListener {
// 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.
......
......@@ -34,12 +34,16 @@ 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.
......@@ -50,6 +54,7 @@ public final class ListenerUtil {
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";
......@@ -98,6 +103,10 @@ public final class ListenerUtil {
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;
}
......@@ -171,7 +180,18 @@ public final class ListenerUtil {
throw parserException;
}
return Integer.parseInt(value);
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;
}
/**
......@@ -263,6 +283,7 @@ public final class ListenerUtil {
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) {
......@@ -281,6 +302,30 @@ public final class ListenerUtil {
}
/**
* 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
......
......@@ -21,6 +21,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
......@@ -35,7 +36,6 @@ 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.exception.TranslatorException;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
import org.onosproject.yangutils.translator.tojava.utils.YangToJavaNamingConflictUtil;
import org.onosproject.yangutils.utils.io.impl.YangFileScanner;
......@@ -69,6 +69,7 @@ public class YangUtilManager extends AbstractMojo {
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);
......@@ -121,6 +122,12 @@ public class YangUtilManager extends AbstractMojo {
private String replacementForHyphen;
/**
* Prefix which is required for adding with the identifier.
*/
@Parameter(property = "prefixForIdentifier")
private String prefixForIdentifier;
/**
* Build context.
*/
@Component
......@@ -145,6 +152,7 @@ public class YangUtilManager extends AbstractMojo {
conflictResolver.setReplacementForPeriod(replacementForPeriod);
conflictResolver.setReplacementForHyphen(replacementForHyphen);
conflictResolver.setReplacementForUnderscore(replacementForUnderscore);
conflictResolver.setPrefixForIdentifier(prefixForIdentifier);
YangPluginConfig yangPlugin = new YangPluginConfig();
yangPlugin.setCodeGenDir(codeGenDir);
yangPlugin.setConflictResolver(conflictResolver);
......@@ -161,7 +169,7 @@ public class YangUtilManager extends AbstractMojo {
return;
}
//Carry out the parsing for all the YANG files.
// Carry out the parsing for all the YANG files.
parseYangFileInfoSet();
// Resolve dependencies using linker.
......@@ -170,13 +178,13 @@ public class YangUtilManager extends AbstractMojo {
// Perform translation to JAVA.
translateToJava(getYangFileInfoSet(), yangPlugin);
addToSource(getDirectory(baseDir, genFilesDir) + DEFAULT_PKG, project, context);
addToSource(getDirectory(baseDir, genFilesDir), project, context);
copyYangFilesToTarget(getYangFileInfoSet(), getDirectory(baseDir, outputDirectory), project);
} catch (Exception e) {
} catch (IOException | ParserException e) {
String fileName = "";
if (e instanceof TranslatorException) {
fileName = ((TranslatorException) e).getFileName();
if (getCurYangFileInfo() != null) {
fileName = getCurYangFileInfo().getYangFileName();
}
try {
translatorErrorHandler(getRootNode());
......@@ -198,6 +206,7 @@ public class YangUtilManager extends AbstractMojo {
*/
public void resolveDependenciesUsingLinker() throws MojoExecutionException {
for (YangFileInfo yangFileInfo : getYangFileInfoSet()) {
setCurYangFileInfo(yangFileInfo);
try {
yangLinker.resolveDependencies(getYangFileInfoSet());
} catch (LinkerException e) {
......@@ -213,6 +222,7 @@ public class YangUtilManager extends AbstractMojo {
*/
public void parseYangFileInfoSet() throws IOException {
for (YangFileInfo yangFileInfo : getYangFileInfoSet()) {
setCurYangFileInfo(yangFileInfo);
try {
YangNode yangNode = yangUtilsParser.getDataModel(yangFileInfo.getYangFileName());
yangFileInfo.setRootNode(yangNode);
......@@ -264,7 +274,8 @@ public class YangUtilManager extends AbstractMojo {
Iterator<YangFileInfo> yangFileIterator = yangFileInfoSet.iterator();
while (yangFileIterator.hasNext()) {
YangFileInfo yangFileInfo = yangFileIterator.next();
generateJavaCode(yangFileInfo.getRootNode(), yangPlugin, yangFileInfo.getYangFileName());
setCurYangFileInfo(yangFileInfo);
generateJavaCode(yangFileInfo.getRootNode(), yangPlugin);
}
}
......@@ -298,4 +309,22 @@ public class YangUtilManager extends AbstractMojo {
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) {
this.curYangFileInfo = yangFileInfo;
}
}
......
......@@ -84,6 +84,11 @@ public final class GeneratedJavaFileType {
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() {
......
......@@ -97,6 +97,31 @@ public final class GeneratedTempFileType {
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() {
......
......@@ -66,11 +66,10 @@ public final class JavaCodeGeneratorUtil {
*
* @param rootNode root node of the data model tree
* @param yangPlugin YANG plugin config
* @param fileName YANG file name
* @throws TranslatorException when fails to generate java code file the current
* node
*/
public static void generateJavaCode(YangNode rootNode, YangPluginConfig yangPlugin, String fileName)
public static void generateJavaCode(YangNode rootNode, YangPluginConfig yangPlugin)
throws TranslatorException {
YangNode codeGenNode = rootNode;
......@@ -78,33 +77,18 @@ public final class JavaCodeGeneratorUtil {
while (codeGenNode != null) {
if (curTraversal != PARENT) {
if (codeGenNode instanceof JavaCodeGenerator) {
setCurNode(codeGenNode);
generateCodeEntry(codeGenNode, yangPlugin, fileName);
} 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;
codeGenNode = codeGenNode.getChild();
} else if (codeGenNode.getNextSibling() != null) {
generateCodeExit(codeGenNode, fileName);
generateCodeExit(codeGenNode);
curTraversal = SIBILING;
codeGenNode = codeGenNode.getNextSibling();
} else {
generateCodeExit(codeGenNode, fileName);
generateCodeExit(codeGenNode);
curTraversal = PARENT;
codeGenNode = codeGenNode.getParent();
}
......@@ -117,20 +101,17 @@ public final class JavaCodeGeneratorUtil {
* @param codeGenNode current data model node for which the code needs to be
* generated
* @param yangPlugin YANG plugin config
* @param fileName YANG file name
* @throws TranslatorException when fails to generate java code file the current
* node
*/
private static void generateCodeEntry(YangNode codeGenNode, YangPluginConfig yangPlugin, String fileName)
private static void generateCodeEntry(YangNode codeGenNode, YangPluginConfig yangPlugin)
throws TranslatorException {
if (codeGenNode instanceof JavaCodeGenerator) {
((JavaCodeGenerator) codeGenNode).generateCodeEntry(yangPlugin);
} else {
TranslatorException ex = new TranslatorException(
throw new TranslatorException(
"Generated data model node cannot be translated to target language code");
ex.setFileName(fileName);
throw ex;
}
}
......@@ -139,19 +120,16 @@ public final class JavaCodeGeneratorUtil {
*
* @param codeGenNode current data model node for which the code needs to be
* generated
* @param fileName YANG file name
* @throws TranslatorException when fails to generate java code file the current
* node
*/
private static void generateCodeExit(YangNode codeGenNode, String fileName) throws TranslatorException {
private static void generateCodeExit(YangNode codeGenNode) throws TranslatorException {
if (codeGenNode instanceof JavaCodeGenerator) {
((JavaCodeGenerator) codeGenNode).generateCodeExit();
} else {
TranslatorException ex = new TranslatorException(
throw new TranslatorException(
"Generated data model node cannot be translated to target language code");
ex.setFileName(fileName);
throw ex;
}
}
......@@ -162,26 +140,28 @@ public final class JavaCodeGeneratorUtil {
private static void freeRestResources() {
YangNode freedNode = getCurNode();
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);
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();
}
freedNode = freedNode.getParent();
}
}
}
......@@ -213,36 +193,38 @@ public final class JavaCodeGeneratorUtil {
public static void translatorErrorHandler(YangNode rootNode)
throws IOException {
/**
* Free other resources where translator has failed.
*/
freeRestResources();
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;
/**
* Start removing all open files.
*/
YangNode tempNode = rootNode;
setCurNode(tempNode.getChild());
TraversalType curTraversal = ROOT;
while (tempNode != null) {
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();
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();
freeRestResources();
}
}
/**
......@@ -254,8 +236,8 @@ public final class JavaCodeGeneratorUtil {
*/
private static void close(YangNode node)
throws IOException {
if (((TempJavaCodeFragmentFilesContainer) node).getTempJavaCodeFragmentFiles() != null) {
if (node instanceof JavaCodeGenerator && ((TempJavaCodeFragmentFilesContainer) node)
.getTempJavaCodeFragmentFiles() != null) {
((TempJavaCodeFragmentFilesContainer) node).getTempJavaCodeFragmentFiles().freeTemporaryResources(true);
}
}
......
......@@ -16,6 +16,8 @@
package org.onosproject.yangutils.translator.tojava;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
/**
* Represents cached java file handle, which supports the addition of member attributes and
* methods.
......@@ -49,6 +51,11 @@ public class JavaFileInfo {
private String codeGenDirFilePath;
/**
* Plugin configuration for naming convention.
*/
private YangPluginConfig pluginConfig;
/**
* Returns the types of files being generated corresponding to the YANG
* definition.
*
......@@ -152,4 +159,22 @@ public class JavaFileInfo {
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;
}
}
......
......@@ -22,12 +22,14 @@ import java.util.TreeSet;
import static java.util.Collections.sort;
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;
......@@ -35,10 +37,10 @@ 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_PKG;
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;
......@@ -218,7 +220,7 @@ public class JavaImportData {
* @return import string for ListenerService class
*/
public String getListenerServiceImport() {
return IMPORT + LISTENER_PKG + PERIOD + LISTENER_SERVICE + SEMI_COLAN + NEW_LINE;
return IMPORT + ONOS_EVENT_PKG + PERIOD + LISTENER_SERVICE + SEMI_COLAN + NEW_LINE;
}
/**
......@@ -227,6 +229,24 @@ public class JavaImportData {
* @return import string for ListenerRegistry class
*/
public String getListenerRegistryImport() {
return IMPORT + LISTENER_PKG + PERIOD + LISTENER_REG + SEMI_COLAN + NEW_LINE;
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;
}
}
......
......@@ -22,6 +22,7 @@ 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;
......@@ -88,7 +89,7 @@ public class JavaQualifiedTypeInfo
/**
* Updates the leaf's java information.
*
* @param leaf leaf whose jave information is being updated
* @param leaf leaf whose java information is being updated
*/
public static void updateLeavesJavaQualifiedInfo(JavaLeafInfoContainer leaf) {
......@@ -102,7 +103,8 @@ public class JavaQualifiedTypeInfo
* Current leaves holder is adding a leaf info as a attribute to the
* current class.
*/
String className = AttributesJavaDataType.getJavaImportClass(leaf.getDataType(), leaf.isLeafList());
String className = AttributesJavaDataType.getJavaImportClass(leaf.getDataType(), leaf.isLeafList(),
leaf.getConflictResolveConfig());
if (className != null) {
/*
* Corresponding to the attribute type a class needs to be imported,
......@@ -110,7 +112,7 @@ public class JavaQualifiedTypeInfo
*/
importInfo.setClassInfo(className);
String classPkg = AttributesJavaDataType.getJavaImportPackage(leaf.getDataType(),
leaf.isLeafList(), className);
leaf.isLeafList(), leaf.getConflictResolveConfig());
if (classPkg == null) {
throw new TranslatorException("import package cannot be null when the class is used");
}
......@@ -163,19 +165,22 @@ public class JavaQualifiedTypeInfo
* 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) {
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));
getJavaImportClass(referredTypesAttrInfo.getAttributeType(), true, conflictResolver));
qualifiedInfoOfFromString.setPkgInfo(
getJavaImportPackage(referredTypesAttrInfo.getAttributeType(), true, null));
getJavaImportPackage(referredTypesAttrInfo.getAttributeType(), true, conflictResolver));
return qualifiedInfoOfFromString;
}
......
......@@ -19,6 +19,8 @@ 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;
......@@ -84,10 +86,10 @@ public class TempJavaBeanFragmentFiles
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
private void addConstructor(JavaAttributeInfo attr)
private void addConstructor(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
throws IOException {
appendToFile(getConstructorImplTempFileHandle(), getConstructor(getGeneratedJavaClassName(), attr,
getGeneratedJavaFiles()));
getGeneratedJavaFiles(), pluginConfig));
}
/**
......@@ -98,10 +100,10 @@ public class TempJavaBeanFragmentFiles
* @throws IOException IO operation fail
*/
@Override
void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo)
void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo, YangPluginConfig pluginConfig)
throws IOException {
super.addJavaSnippetInfoToApplicableTempFiles(newAttrInfo);
addConstructor(newAttrInfo);
super.addJavaSnippetInfoToApplicableTempFiles(newAttrInfo, pluginConfig);
addConstructor(newAttrInfo, pluginConfig);
}
/**
......
......@@ -21,10 +21,9 @@ 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_EVENT_CLASS;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
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;
......@@ -57,16 +56,6 @@ public class TempJavaCodeFragmentFiles {
private TempJavaEnumerationFragmentFiles enumerationTempFiles;
/**
* Has the temporary files required for generated event classes.
*/
private TempJavaEventFragmentFiles eventTempFiles;
/**
* Has the temporary files required for generated event listenerclasses.
*/
private TempJavaEventListenerFragmentFiles eventListenerTempFiles;
/**
* Creates an instance of temporary java code fragment.
*
* @param javaFileInfo generated java file info
......@@ -79,16 +68,10 @@ public class TempJavaCodeFragmentFiles {
setBeanTempFiles(new TempJavaBeanFragmentFiles(javaFileInfo));
}
/**
* Creates user defined data type class file.
*/
if ((javaFileInfo.getGeneratedFileTypes() & GENERATE_TYPE_CLASS) != 0) {
setTypeTempFiles(new TempJavaTypeFragmentFiles(javaFileInfo));
}
/**
* Creates enumeration class file.
*/
if ((javaFileInfo.getGeneratedFileTypes() & GENERATE_ENUM_CLASS) != 0) {
setEnumerationTempFiles(new TempJavaEnumerationFragmentFiles(javaFileInfo));
}
......@@ -97,13 +80,6 @@ public class TempJavaCodeFragmentFiles {
setServiceTempFiles(new TempJavaServiceFragmentFiles(javaFileInfo));
}
if ((javaFileInfo.getGeneratedFileTypes() & GENERATE_EVENT_CLASS) != 0) {
setEventTempFiles(new TempJavaEventFragmentFiles(javaFileInfo));
}
if ((javaFileInfo.getGeneratedFileTypes() & GENERATE_EVENT_LISTENER_INTERFACE) != 0) {
setEventListenerTempFiles(new TempJavaEventListenerFragmentFiles(javaFileInfo));
}
}
/**
......@@ -180,43 +156,6 @@ public class TempJavaCodeFragmentFiles {
}
/**
* Retrieves the temp file handle for event file generation.
*
* @return temp file handle for event file generation
*/
public TempJavaEventFragmentFiles getEventTempFiles() {
return eventTempFiles;
}
/**
* Sets temp file handle for event file generation.
*
* @param eventTempFiles temp file handle for event file generation
*/
public void setEventTempFiles(TempJavaEventFragmentFiles eventTempFiles) {
this.eventTempFiles = eventTempFiles;
}
/**
* Retrieves the temp file handle for event listener file generation.
*
* @return temp file handle for event listener file generation
*/
public TempJavaEventListenerFragmentFiles getEventListenerTempFiles() {
return eventListenerTempFiles;
}
/**
* Sets temp file handle for event listener file generation.
*
* @param eventListenerTempFiles temp file handle for event listener file generation
*/
public void setEventListenerTempFiles(
TempJavaEventListenerFragmentFiles eventListenerTempFiles) {
this.eventListenerTempFiles = eventListenerTempFiles;
}
/**
* Constructs java code exit.
*
* @param fileType generated file type
......@@ -238,7 +177,7 @@ public class TempJavaCodeFragmentFiles {
}
/*
* Creats service and manager class file.
* Creates service and manager class file.
*/
if (fileType == GENERATE_SERVICE_AND_MANAGER) {
getServiceTempFiles().generateJavaFile(GENERATE_SERVICE_AND_MANAGER, curNode);
......@@ -251,22 +190,6 @@ public class TempJavaCodeFragmentFiles {
getEnumerationTempFiles().generateJavaFile(GENERATE_ENUM_CLASS, curNode);
}
if ((fileType & GENERATE_EVENT_CLASS) != 0) {
/*
* Creates event class file.
*/
if (getEventTempFiles() != null) {
getEventTempFiles().generateJavaFile(fileType, curNode);
}
}
if ((fileType & GENERATE_EVENT_LISTENER_INTERFACE) != 0) {
/**
* Creates event listener class file.
*/
getEventListenerTempFiles().generateJavaFile(fileType, curNode);
}
freeTemporaryResources(false);
}
......@@ -275,14 +198,16 @@ public class TempJavaCodeFragmentFiles {
*
* @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)
public void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo,
YangPluginConfig pluginConfig)
throws IOException {
if (getBeanTempFiles() != null) {
getBeanTempFiles()
.addJavaSnippetInfoToApplicableTempFiles(newAttrInfo);
.addJavaSnippetInfoToApplicableTempFiles(newAttrInfo, pluginConfig);
}
/**
......@@ -290,7 +215,7 @@ public class TempJavaCodeFragmentFiles {
*/
if (getTypeTempFiles() != null) {
getTypeTempFiles()
.addJavaSnippetInfoToApplicableTempFiles(newAttrInfo);
.addJavaSnippetInfoToApplicableTempFiles(newAttrInfo, pluginConfig);
}
}
......@@ -299,24 +224,26 @@ public class TempJavaCodeFragmentFiles {
* 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)
public void addTypeInfoToTempFiles(YangTypeHolder yangTypeHolder, YangPluginConfig pluginConfig)
throws IOException {
getTypeTempFiles()
.addTypeInfoToTempFiles(yangTypeHolder);
.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()
public String addBuildMethodForInterface(YangPluginConfig pluginConfig)
throws IOException {
if (getBeanTempFiles() != null) {
return getBeanTempFiles().addBuildMethodForInterface();
return getBeanTempFiles().addBuildMethodForInterface(pluginConfig);
}
throw new TranslatorException("build method only supported for bean class");
}
......@@ -326,18 +253,19 @@ public class TempJavaCodeFragmentFiles {
*
* @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)
public String addDefaultConstructor(String modifier, String toAppend, YangPluginConfig pluginConfig)
throws IOException {
if (getTypeTempFiles() != null) {
return getTypeTempFiles()
.addDefaultConstructor(modifier, toAppend);
.addDefaultConstructor(modifier, toAppend, pluginConfig);
}
if (getBeanTempFiles() != null) {
return getBeanTempFiles().addDefaultConstructor(modifier, toAppend);
return getBeanTempFiles().addDefaultConstructor(modifier, toAppend, pluginConfig);
}
throw new TranslatorException("default constructor should not be added");
......@@ -380,13 +308,10 @@ public class TempJavaCodeFragmentFiles {
getEnumerationTempFiles().freeTemporaryResources(isErrorOccurred);
}
if (getEventTempFiles() != null) {
getEventTempFiles().freeTemporaryResources(isErrorOccurred);
if (getServiceTempFiles() != null) {
getServiceTempFiles().freeTemporaryResources(isErrorOccurred);
}
if (getEventListenerTempFiles() != null) {
getEventListenerTempFiles().freeTemporaryResources(isErrorOccurred);
}
}
}
......
......@@ -28,13 +28,18 @@ 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;
/**
......@@ -172,29 +177,41 @@ public class TempJavaEnumerationFragmentFiles extends TempJavaFragmentFiles {
/**
* Adds enum class attributes to temporary file.
*
* @param curEnumInfo current YANG enum
* @param curEnumName current YANG enum
* @throws IOException when fails to do IO operations.
*/
private void addAttributesForEnumClass(String curEnumName) throws IOException {
appendToFile(getEnumClassTempFileHandle(), generateEnumAttributeString(curEnumName, getEnumValue()));
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) throws IOException {
public void addEnumAttributeToTempFiles(YangNode curNode, YangPluginConfig pluginConfig) throws IOException {
super.addJavaSnippetInfoToApplicableTempFiles(getJavaAttributeForEnum());
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());
addJavaSnippetInfoToApplicableTempFiles(curEnum.getNamedValue(), pluginConfig);
}
} else {
throw new TranslatorException("current node should be of enumeration type.");
......@@ -204,13 +221,14 @@ public class TempJavaEnumerationFragmentFiles extends TempJavaFragmentFiles {
/**
* Returns java attribute for enum class.
*
* @param pluginConfig plugin configurations
* @return java attribute
*/
public JavaAttributeInfo getJavaAttributeForEnum() {
public JavaAttributeInfo getJavaAttributeForEnum(YangPluginConfig pluginConfig) {
YangJavaType<?> javaType = new YangJavaType<>();
javaType.setDataType(YangDataTypes.INT32);
javaType.setDataTypeName("int");
javaType.updateJavaQualifiedInfo();
javaType.updateJavaQualifiedInfo(pluginConfig.getConflictResolver());
return getAttributeInfoForTheData(
javaType.getJavaQualifiedInfo(),
javaType.getDataTypeName(), javaType,
......@@ -224,7 +242,7 @@ public class TempJavaEnumerationFragmentFiles extends TempJavaFragmentFiles {
* @param curEnumName current enum name
*/
private void addToEnumSetJavaMap(String curEnumName, int value) {
getEnumSetJavaMap().put(curEnumName.toUpperCase(), value);
getEnumSetJavaMap().put(getEnumJavaAttribute(curEnumName).toUpperCase(), value);
}
/**
......@@ -234,8 +252,9 @@ public class TempJavaEnumerationFragmentFiles extends TempJavaFragmentFiles {
* files
* @throws IOException IO operation fail
*/
void addJavaSnippetInfoToApplicableTempFiles(String curEnumName) throws IOException {
addAttributesForEnumClass(curEnumName);
void addJavaSnippetInfoToApplicableTempFiles(String curEnumName, YangPluginConfig pluginConfig)
throws IOException {
addAttributesForEnumClass(getEnumJavaAttribute(curEnumName), pluginConfig);
}
/**
......@@ -274,7 +293,7 @@ public class TempJavaEnumerationFragmentFiles extends TempJavaFragmentFiles {
* @param curEnumValue current enum value
*/
private void addToEnumStringList(String curEnumValue) {
getEnumStringList().add(curEnumValue.toUpperCase());
getEnumStringList().add(getEnumJavaAttribute(curEnumValue).toUpperCase());
}
/**
......
/*
* 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.datamodel.YangNode;
import org.onosproject.yangutils.translator.tojava.utils.JavaExtendsListHolder;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEventFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.closeFile;
import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.createPackage;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Represents implementation of java bean code fragments temporary implementations.
* Maintains the temp files required specific for event java snippet generation.
*/
public class TempJavaEventFragmentFiles
extends TempJavaFragmentFiles {
/**
* File name for generated class file for special type like union, typedef
* suffix.
*/
private static final String EVENT_FILE_NAME_SUFFIX = "Event";
/**
* Java file handle for event file.
*/
private File eventJavaFileHandle;
/**
* Creates an instance of temporary java code fragment.
*
* @param javaFileInfo generated java file info
* @throws IOException when fails to create new file handle
*/
public TempJavaEventFragmentFiles(JavaFileInfo javaFileInfo)
throws IOException {
setJavaExtendsListHolder(new JavaExtendsListHolder());
setJavaImportData(new JavaImportData());
setJavaFileInfo(javaFileInfo);
setAbsoluteDirPath(getAbsolutePackagePath(getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath()));
}
/**
* 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;
}
/**
* 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);
String parentInfo = getCapitalCase(((JavaFileInfoContainer) curNode.getParent())
.getJavaFileInfo().getJavaName());
/**
* Creates event interface file.
*/
setEventJavaFileHandle(getJavaFileHandle(parentInfo + EVENT_FILE_NAME_SUFFIX));
generateEventFile(getEventJavaFileHandle(), curNode, null);
/**
* 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;
/**
* Close all java file handles and when error occurs delete the files.
*/
closeFile(getEventJavaFileHandle(), isError);
super.freeTemporaryResources(isErrorOccurred);
}
}
/*
* 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.datamodel.YangNode;
import org.onosproject.yangutils.translator.tojava.utils.JavaExtendsListHolder;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEventListenerFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.closeFile;
import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.createPackage;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Represents implementation of java bean code fragments temporary implementations.
* Maintains the temp files required specific for event listener java snippet generation.
*/
public class TempJavaEventListenerFragmentFiles
extends TempJavaFragmentFiles {
/**
* File name for generated class file for special type like union, typedef
* suffix.
*/
private static final String EVENT_LISTENER_FILE_NAME_SUFFIX = "Listener";
/**
* Java file handle for event listener file.
*/
private File eventListenerJavaFileHandle;
/**
* Creates an instance of temporary java code fragment.
*
* @param javaFileInfo generated java file info
* @throws IOException when fails to create new file handle
*/
public TempJavaEventListenerFragmentFiles(JavaFileInfo javaFileInfo)
throws IOException {
setJavaExtendsListHolder(new JavaExtendsListHolder());
setJavaImportData(new JavaImportData());
setJavaFileInfo(javaFileInfo);
setAbsoluteDirPath(getAbsolutePackagePath(getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath()));
}
/**
* 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;
}
/**
* 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);
String parentInfo = getCapitalCase(((JavaFileInfoContainer) curNode.getParent())
.getJavaFileInfo().getJavaName());
/**
* Creates event listener interface file.
*/
setEventListenerJavaFileHandle(getJavaFileHandle(parentInfo + EVENT_LISTENER_FILE_NAME_SUFFIX));
generateEventListenerFile(getEventListenerJavaFileHandle(), curNode, null);
/**
* 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;
/**
* Close all java file handles and when error occurs delete the files.
*/
closeFile(getEventListenerJavaFileHandle(), isError);
super.freeTemporaryResources(isErrorOccurred);
}
}
......@@ -26,8 +26,8 @@ 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.datamodel.YangDataTypes.DERIVED;
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;
......@@ -196,9 +196,10 @@ public class TempJavaTypeFragmentFiles
*
* @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)
public void addTypeInfoToTempFiles(YangTypeHolder yangTypeHolder, YangPluginConfig pluginConfig)
throws IOException {
List<YangType<?>> typeList = yangTypeHolder.getTypeList();
......@@ -208,18 +209,16 @@ public class TempJavaTypeFragmentFiles
throw new TranslatorException("Type does not have Java info");
}
YangJavaType<?> javaType = (YangJavaType<?>) yangType;
javaType.updateJavaQualifiedInfo();
javaType.updateJavaQualifiedInfo(pluginConfig.getConflictResolver());
String typeName = javaType.getDataTypeName();
if (javaType.getDataType().equals(DERIVED)) {
typeName = getCamelCase(typeName, null);
}
typeName = getCamelCase(typeName, pluginConfig.getConflictResolver());
JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(
javaType.getJavaQualifiedInfo(),
typeName, javaType,
getIsQualifiedAccessOrAddToImportList(javaType.getJavaQualifiedInfo()),
false);
addJavaSnippetInfoToApplicableTempFiles((YangNode) yangTypeHolder, javaAttributeInfo);
addJavaSnippetInfoToApplicableTempFiles((YangNode) yangTypeHolder, javaAttributeInfo,
pluginConfig);
}
}
}
......@@ -231,18 +230,20 @@ public class TempJavaTypeFragmentFiles
* @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)
private void addJavaSnippetInfoToApplicableTempFiles(YangNode hasType, JavaAttributeInfo javaAttributeInfo,
YangPluginConfig pluginConfig)
throws IOException {
super.addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo);
super.addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, pluginConfig);
if ((getGeneratedTempFiles() & OF_STRING_IMPL_MASK) != 0) {
addOfStringMethod(javaAttributeInfo);
addOfStringMethod(javaAttributeInfo, pluginConfig);
}
if ((getGeneratedTempFiles() & CONSTRUCTOR_FOR_TYPE_MASK) != 0) {
addTypeConstructor(javaAttributeInfo);
addTypeConstructor(javaAttributeInfo, pluginConfig);
}
}
......@@ -250,24 +251,26 @@ public class TempJavaTypeFragmentFiles
* 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)
private void addTypeConstructor(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
throws IOException {
appendToFile(getConstructorForTypeTempFileHandle(), getTypeConstructorStringAndJavaDoc(attr,
getGeneratedJavaClassName()) + NEW_LINE);
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)
private void addOfStringMethod(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
throws IOException {
appendToFile(getOfStringImplTempFileHandle(), getOfMethodStringAndJavaDoc(attr,
getGeneratedJavaClassName())
getGeneratedJavaClassName(), pluginConfig)
+ NEW_LINE);
}
......
......@@ -57,4 +57,19 @@ public interface JavaLeafInfoContainer
* 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);
}
......
......@@ -16,7 +16,7 @@
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.
......@@ -26,6 +26,8 @@ public interface JavaQualifiedTypeResolver
/**
* updates the qualified access details of the type.
*
* @param confilictResolver plugin configurations
*/
void updateJavaQualifiedInfo();
void updateJavaQualifiedInfo(YangToJavaNamingConflictUtil confilictResolver);
}
......
......@@ -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;
}
}
......
......@@ -30,6 +30,7 @@ public class YangJavaLeaf
implements JavaLeafInfoContainer {
private JavaQualifiedTypeInfo javaQualifiedAccess;
private YangToJavaNamingConflictUtil conflictResolveConfig;
/**
* Returns a new YANG leaf object with java qualified access details.
......@@ -50,6 +51,7 @@ public class YangJavaLeaf
}
@Override
public String getJavaName(YangToJavaNamingConflictUtil conflictResolveConfig) {
return getCamelCase(getName(), conflictResolveConfig);
}
......@@ -63,4 +65,25 @@ public class YangJavaLeaf
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;
}
}
......
......@@ -29,6 +29,7 @@ public class YangJavaLeafList
extends YangLeafList
implements JavaLeafInfoContainer {
private JavaQualifiedTypeInfo javaQualifiedAccess;
private YangToJavaNamingConflictUtil conflictResolveConfig;
/**
* Returns a new YANG leaf object with java qualified access details.
......@@ -62,4 +63,24 @@ public class YangJavaLeafList
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;
}
}
......
......@@ -16,14 +16,21 @@
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;
......@@ -48,12 +55,24 @@ public class YangJavaModule
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* List of notifications nodes.
*/
private List<YangNode> notificationNodes;
/**
* Creates a YANG node of module type.
*/
public YangJavaModule() {
super();
setJavaFileInfo(new JavaFileInfo());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_SERVICE_AND_MANAGER);
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);
}
/**
......@@ -107,7 +126,8 @@ public class YangJavaModule
*/
@Override
public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
String modulePkg = getRootPackage(getVersion(), getNameSpace().getUri(), getRevision().getRevDate());
String modulePkg = getRootPackage(getVersion(), getNameSpace().getUri(), getRevision().getRevDate(),
yangPlugin.getConflictResolver());
try {
generateCodeOfRootNode(this, yangPlugin, modulePkg);
} catch (IOException e) {
......@@ -121,6 +141,15 @@ public class YangJavaModule
*/
@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() +
......@@ -129,4 +158,53 @@ public class YangJavaModule
throw new TranslatorException("Failed to generate code for module node " + this.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;
}
}
......
......@@ -30,8 +30,6 @@ import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesCont
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_EVENT_CLASS;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
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;
......@@ -62,8 +60,7 @@ public class YangJavaNotification
public YangJavaNotification() {
super();
setJavaFileInfo(new JavaFileInfo());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER
| GENERATE_EVENT_CLASS | GENERATE_EVENT_LISTENER_INTERFACE);
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
......@@ -167,17 +164,8 @@ public class YangJavaNotification
*/
@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".
*
* The manager class needs to extend the "ListenerRegistry".
*/
try {
getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER
| GENERATE_EVENT_CLASS | GENERATE_EVENT_LISTENER_INTERFACE, this);
getTempJavaCodeFragmentFiles().generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
} catch (IOException e) {
throw new TranslatorException("Failed to generate code for notification 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 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;
}
}
......
......@@ -16,8 +16,13 @@
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;
......@@ -25,6 +30,9 @@ 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;
......@@ -49,12 +57,22 @@ public class YangJavaSubModule
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* List of notifications nodes.
*/
private List<YangNode> notificationNodes = new ArrayList<>();
/**
* Creates YANG java sub module object.
*/
public YangJavaSubModule() {
super();
setJavaFileInfo(new JavaFileInfo());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_SERVICE_AND_MANAGER);
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);
}
/**
......@@ -121,7 +139,7 @@ public class YangJavaSubModule
@Override
public void generateCodeEntry(YangPluginConfig yangPlugin) throws TranslatorException {
String subModulePkg = getRootPackage(getVersion(), getNameSpaceFromModule(getBelongsTo()),
getRevision().getRevDate());
getRevision().getRevDate(), yangPlugin.getConflictResolver());
try {
generateCodeOfRootNode(this, yangPlugin, subModulePkg);
} catch (IOException e) {
......@@ -136,6 +154,15 @@ public class YangJavaSubModule
*/
@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() +
......@@ -144,4 +171,44 @@ public class YangJavaSubModule
throw new TranslatorException("Failed to generate code for submodule node " + this.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;
}
}
......
......@@ -19,6 +19,7 @@ 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.
......@@ -40,13 +41,13 @@ public class YangJavaType<T>
}
@Override
public void updateJavaQualifiedInfo() {
public void updateJavaQualifiedInfo(YangToJavaNamingConflictUtil conflictResolver) {
JavaQualifiedTypeInfo importInfo = getJavaQualifiedInfo();
/*
* Type is added as an attribute in the class.
*/
String className = AttributesJavaDataType.getJavaImportClass(this, false);
String className = AttributesJavaDataType.getJavaImportClass(this, false, conflictResolver);
if (className != null) {
/*
* Corresponding to the attribute type a class needs to be imported,
......@@ -54,7 +55,7 @@ public class YangJavaType<T>
*/
importInfo.setClassInfo(className);
String classPkg = AttributesJavaDataType.getJavaImportPackage(this,
false, className);
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.
}
}
......
......@@ -17,7 +17,6 @@
package org.onosproject.yangutils.translator.tojava.utils;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaNotification;
......@@ -27,12 +26,12 @@ import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.
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.utils.JavaIdentifierSyntax.getCapitalCase;
import static org.onosproject.yangutils.utils.UtilConstants.BUILDER;
import static org.onosproject.yangutils.utils.UtilConstants.CLASS;
import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
......@@ -54,8 +53,10 @@ 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;
/**
......@@ -95,8 +96,6 @@ public final class ClassDefinitionGenerator {
return getTypeClassDefinition(yangName);
case GENERATE_ENUM_CLASS:
return getEnumClassDefinition(yangName);
case GENERATE_EVENT_LISTENER_INTERFACE:
return getEventListenerDefinition(yangName);
default:
return null;
}
......@@ -123,9 +122,12 @@ public final class ClassDefinitionGenerator {
case GENERATE_SERVICE_AND_MANAGER:
return getRpcInterfaceDefinition(yangName, curNode);
case GENERATE_EVENT_CLASS:
String eventName = getCapitalCase(((JavaFileInfoContainer) curNode)
.getJavaFileInfo().getJavaName());
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;
}
......@@ -183,7 +185,6 @@ public final class ClassDefinitionGenerator {
* Returns builder file class definition.
*
* @param yangName file name
* @param genFileTypes
* @return definition
*/
private static String getBuilderClassDefinition(String yangName) {
......@@ -198,8 +199,18 @@ public final class ClassDefinitionGenerator {
* @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;
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;
}
/**
......@@ -231,27 +242,28 @@ public final class ClassDefinitionGenerator {
curNode = curNode.getNextSibling();
}
}
if (yangName.contains(SERVICE)) {
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 + MANAGER + SPACE + IMPLEMENTS + SPACE + yangName
+ SERVICE + 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.contains(SERVICE)) {
if (yangName.matches(REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE)) {
String[] strArray = yangName.split(SERVICE);
return PUBLIC + SPACE + INTERFACE + SPACE + yangName + SPACE + NEW_LINE + EIGHT_SPACE_INDENTATION
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;
}
return PUBLIC + SPACE + CLASS + SPACE + yangName + MANAGER + SPACE + NEW_LINE + EIGHT_SPACE_INDENTATION
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 + SPACE + NEW_LINE
+ yangName + EVENT_LISTENER_STRING + DIAMOND_CLOSE_BRACKET + NEW_LINE
+ EIGHT_SPACE_INDENTATION + IMPLEMENTS + SPACE + yangName + SERVICE + SPACE + OPEN_CURLY_BRACKET
+ NEW_LINE;
}
......
......@@ -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;
}
......@@ -145,10 +145,11 @@ public final class JavaCodeSnippetGen {
*
* @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) {
return getJavaDoc(ENUM_ATTRIBUTE, name, false) + FOUR_SPACE_INDENTATION
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;
}
......
......@@ -27,18 +27,7 @@ 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.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.getTempJavaFragement;
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.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.LISTENER_REG;
import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
/**
* Represent the extends list for generated java classes. It holds the class details which needs
......@@ -87,6 +76,7 @@ public class JavaExtendsListHolder {
if (!fileInfo.getPackage().equals(info.getPkgInfo())) {
JavaImportData importData = getTempJavaFragement(node).getJavaImportData();
importData.addImportInfo(info);
/*true means import should be added*/
getExtendedClassStore().put(info, true);
}
......@@ -95,33 +85,6 @@ public class JavaExtendsListHolder {
}
/**
* Returns extends string for class.
*
* @param genFileType generated file type
* @param className class name
* @param isNotificationPresent if notification node is present
* @return extends string
*/
public String getExtendsString(int genFileType, String className, boolean isNotificationPresent) {
String extend = EXTEND + SPACE;
if (genFileType == GENERATE_SERVICE_AND_MANAGER && isNotificationPresent) {
extend = extend + LISTENER_REG + DIAMOND_OPEN_BRACKET + className + EVENT_STRING + COMMA + SPACE
+ className + EVENT_LISTENER_STRING + DIAMOND_CLOSE_BRACKET + NEW_LINE;
} else {
for (JavaQualifiedTypeInfo info : getExtendsList()) {
if (info.getClassInfo().equals(className)) {
if (!getExtendedClassStore().get(info)) {
return extend + info.getClassInfo();
} else {
return extend + info.getPkgInfo() + PERIOD + info.getClassInfo();
}
}
}
}
return null;
}
/**
* Returns extends list.
*
* @return the extendsList
......
......@@ -75,16 +75,18 @@ public final class JavaIdentifierSyntax {
* @param version YANG version
* @param nameSpace name space of the module
* @param revision revision of the module defined
* @return returns the root package string
* @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) {
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);
pkg = pkg + getPkgFromNameSpace(nameSpace, conflictResolver);
pkg = pkg + PERIOD;
pkg = pkg + getYangRevisionStr(revision);
......@@ -144,9 +146,10 @@ public final class JavaIdentifierSyntax {
* 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) {
private static String getPkgFromNameSpace(String nameSpace, YangToJavaNamingConflictUtil conflictResolver) {
ArrayList<String> pkgArr = new ArrayList<String>();
nameSpace = nameSpace.replace(QUOTES, EMPTY_STRING);
......@@ -156,7 +159,7 @@ public final class JavaIdentifierSyntax {
for (String nameSpaceString : nameSpaceArr) {
pkgArr.add(nameSpaceString);
}
return getPkgFrmArr(pkgArr);
return getPkgFrmArr(pkgArr, conflictResolver);
}
/**
......@@ -194,17 +197,19 @@ public final class JavaIdentifierSyntax {
* 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) {
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);
boolean presenceOfKeyword = JAVA_KEY_WORDS.contains(member.toLowerCase());
if (presenceOfKeyword || member.matches(REGEX_FOR_FIRST_DIGIT)) {
member = YANG_AUTO_PREFIX + member;
String prefix = getPrefixForIdentifier(conflictResolver);
member = prefix + member;
}
pkg = pkg + member;
if (i != size - 1) {
......@@ -216,20 +221,40 @@ public final class JavaIdentifierSyntax {
}
/**
* Returns package sub name from YANG identifier name.
* Prefix for adding with identifier and namespace, when it is a java keyword or starting with digits.
*
* @param name YANG identifier name
* @return java package sub name as per java rules
* @param conflictResolver object of YANG to java naming conflict util
* @return prefix which needs to be added
*/
public static String getSubPkgFromName(String name) {
ArrayList<String> pkgArr = new ArrayList<String>();
String[] nameArr = name.split(COLAN);
public static String getPrefixForIdentifier(YangToJavaNamingConflictUtil conflictResolver) {
for (String nameString : nameArr) {
pkgArr.add(nameString);
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 getPkgFrmArr(pkgArr);
return prefixForIdentifier;
}
/**
......@@ -267,16 +292,18 @@ public final class JavaIdentifierSyntax {
}
strArray = stringArrangement.toArray(new String[stringArrangement.size()]);
}
return upperCaseConflictResolver(strArray);
return upperCaseConflictResolver(strArray, conflictResolver);
}
/**
* Resolves the conflict when input has uppercase.
* Resolves the conflict when input has upper case.
*
* @param stringArray containing strings for uppercase conflict resolver
* @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) {
private static String upperCaseConflictResolver(String[] stringArray,
YangToJavaNamingConflictUtil conflictResolver) {
for (int l = 0; l < stringArray.length; l++) {
String[] upperCaseSplitArray = stringArray[l].split(REGEX_WITH_UPPERCASE);
......@@ -317,7 +344,7 @@ public final class JavaIdentifierSyntax {
}
}
stringArray = result.toArray(new String[result.size()]);
return applyCamelCaseRule(stringArray);
return applyCamelCaseRule(stringArray, conflictResolver);
}
/**
......@@ -325,9 +352,10 @@ public final class JavaIdentifierSyntax {
* 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) {
private static String applyCamelCaseRule(String[] stringArray, YangToJavaNamingConflictUtil conflictResolver) {
String ruleChecker = stringArray[0].toLowerCase();
int i;
......@@ -338,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();
......@@ -359,23 +387,25 @@ public final class JavaIdentifierSyntax {
ruleChecker = ruleChecker + stringArray[i].substring(0, 1).toUpperCase() + stringArray[i].substring(1);
}
}
String ruleCheckerWithPrefix = addPrefix(ruleChecker);
String ruleCheckerWithPrefix = addPrefix(ruleChecker, conflictResolver);
return restrictConsecutiveCapitalCase(ruleCheckerWithPrefix);
}
/**
* Adds prefix YANG auto prefix if the string begins with digit or is a java key word.
* 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) {
private static String addPrefix(String camelCasePrefix, YangToJavaNamingConflictUtil conflictResolver) {
String prefix = getPrefixForIdentifier(conflictResolver);
if (camelCasePrefix.matches(REGEX_FOR_FIRST_DIGIT)) {
camelCasePrefix = YANG_AUTO_PREFIX + camelCasePrefix;
camelCasePrefix = prefix + camelCasePrefix;
}
if (JAVA_KEY_WORDS.contains(camelCasePrefix.toLowerCase())) {
camelCasePrefix = YANG_AUTO_PREFIX + camelCasePrefix.substring(0, 1).toUpperCase()
if (JAVA_KEY_WORDS.contains(camelCasePrefix)) {
camelCasePrefix = prefix + camelCasePrefix.substring(0, 1).toUpperCase()
+ camelCasePrefix.substring(1);
}
return camelCasePrefix;
......@@ -444,13 +474,21 @@ public final class JavaIdentifierSyntax {
*/
public static String getEnumJavaAttribute(String name) {
String[] strArray = name.split(HYPHEN);
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++) {
output = output + strArray[i];
if (i > 0 && i < strArray.length - 1) {
if (i > 0 && i < strArray.length) {
output = output + UNDER_SCORE;
}
output = output + strArray[i];
}
return output;
}
......
......@@ -29,30 +29,44 @@ 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;
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;
/**
......@@ -102,12 +116,6 @@ public final class TempJavaCodeFragmentFilesUtils {
if (container.getBeanTempFiles() != null) {
return container.getBeanTempFiles();
}
if (container.getEventTempFiles() != null) {
return container.getEventTempFiles();
}
if (container.getEventListenerTempFiles() != null) {
return container.getEventListenerTempFiles();
}
if (container.getServiceTempFiles() != null) {
return container.getServiceTempFiles();
}
......@@ -234,6 +242,31 @@ public final class TempJavaCodeFragmentFilesUtils {
}
/**
* 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
......@@ -309,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)) {
......@@ -328,4 +367,13 @@ public final class TempJavaCodeFragmentFilesUtils {
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;
}
}
......
......@@ -32,11 +32,17 @@ 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;
import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTATION_HOLDER;
......@@ -49,7 +55,7 @@ import static org.onosproject.yangutils.utils.UtilConstants.PROVIDED_AUGMENTATIO
public final class YangJavaModelUtils {
/**
* Creates YANG java model utility.
* Creates an instance of YANG java model utility.
*/
private YangJavaModelUtils() {
}
......@@ -64,6 +70,7 @@ public final class YangJavaModelUtils {
public static void updatePackageInfo(JavaCodeGeneratorInfo javaCodeGeneratorInfo,
YangPluginConfig yangPluginConfig)
throws IOException {
javaCodeGeneratorInfo.getJavaFileInfo()
.setJavaName(getCamelCase(((YangNode) javaCodeGeneratorInfo).getName(),
yangPluginConfig.getConflictResolver()));
......@@ -71,6 +78,7 @@ public final class YangJavaModelUtils {
javaCodeGeneratorInfo.getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(javaCodeGeneratorInfo.getJavaFileInfo().getPackage()));
javaCodeGeneratorInfo.getJavaFileInfo().setBaseCodeGenPath(yangPluginConfig.getCodeGenDir());
javaCodeGeneratorInfo.getJavaFileInfo().setPluginConfig(yangPluginConfig);
}
/**
......@@ -90,6 +98,7 @@ public final class YangJavaModelUtils {
javaCodeGeneratorInfo.getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(javaCodeGeneratorInfo.getJavaFileInfo().getPackage()));
javaCodeGeneratorInfo.getJavaFileInfo().setBaseCodeGenPath(yangPlugin.getCodeGenDir());
javaCodeGeneratorInfo.getJavaFileInfo().setPluginConfig(yangPlugin);
}
/**
......@@ -120,6 +129,16 @@ public final class YangJavaModelUtils {
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
......@@ -139,13 +158,14 @@ public final class YangJavaModelUtils {
* Union
*/
javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles()
.addTypeInfoToTempFiles((YangTypeHolder) javaCodeGeneratorInfo);
.addTypeInfoToTempFiles((YangTypeHolder) javaCodeGeneratorInfo, yangPluginConfig);
} else if (javaCodeGeneratorInfo instanceof YangJavaEnumeration) {
/*
* Enumeration
*/
javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles().getEnumerationTempFiles()
.addEnumAttributeToTempFiles((YangNode) javaCodeGeneratorInfo);
.addEnumAttributeToTempFiles((YangNode) javaCodeGeneratorInfo, yangPluginConfig);
} else if (javaCodeGeneratorInfo instanceof YangChoice) {
/*Do nothing, only the interface needs to be generated*/
} else {
......@@ -171,6 +191,32 @@ public final class YangJavaModelUtils {
}
/**
* 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
......@@ -193,7 +239,7 @@ public final class YangJavaModelUtils {
/*
* Update the current nodes info in its parent nodes generated files.
*/
addCurNodeInfoInParentTempFile((YangNode) javaCodeGeneratorInfo, isMultiInstance);
addCurNodeInfoInParentTempFile((YangNode) javaCodeGeneratorInfo, isMultiInstance, yangPlugin);
}
/**
......@@ -234,7 +280,7 @@ public final class YangJavaModelUtils {
if (javaCodeGeneratorInfo instanceof YangCase) {
YangNode parent = ((YangCase) javaCodeGeneratorInfo).getParent();
JavaQualifiedTypeInfo parentsInfo = new JavaQualifiedTypeInfo();
String parentName = ((JavaFileInfoContainer) parent).getJavaFileInfo().getJavaName();
String parentName = getCapitalCase(((JavaFileInfoContainer) parent).getJavaFileInfo().getJavaName());
String parentPkg = ((JavaFileInfoContainer) parent).getJavaFileInfo().getPackage();
parentsInfo.setClassInfo(parentName);
parentsInfo.setPkgInfo(parentPkg);
......@@ -242,7 +288,7 @@ public final class YangJavaModelUtils {
.addToExtendsList(parentsInfo, (YangNode) javaCodeGeneratorInfo);
javaCodeGeneratorInfo.getTempJavaCodeFragmentFiles().getBeanTempFiles()
.addParentInfoInCurNodeTempFile((YangNode) javaCodeGeneratorInfo);
.addParentInfoInCurNodeTempFile((YangNode) javaCodeGeneratorInfo, yangPlugin);
}
}
......@@ -284,7 +330,26 @@ public final class YangJavaModelUtils {
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);
}
}
......
......@@ -37,6 +37,11 @@ public final class YangToJavaNamingConflictUtil {
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() {
......@@ -95,4 +100,22 @@ public final class YangToJavaNamingConflictUtil {
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;
}
}
......
......@@ -99,11 +99,11 @@ public final class RestrictionResolver {
}
if (rangeBoundary.length == MIN_RANGE_BOUNDARY) {
startInterval = rangeBoundary[0];
endInterval = rangeBoundary[0];
startInterval = rangeBoundary[0].trim();
endInterval = rangeBoundary[0].trim();
} else {
startInterval = rangeBoundary[0];
endInterval = rangeBoundary[1];
startInterval = rangeBoundary[0].trim();
endInterval = rangeBoundary[1].trim();
}
try {
......@@ -186,11 +186,11 @@ public final class RestrictionResolver {
}
if (rangeBoundary.length == MIN_RANGE_BOUNDARY) {
startInterval = rangeBoundary[0];
endInterval = rangeBoundary[0];
startInterval = rangeBoundary[0].trim();
endInterval = rangeBoundary[0].trim();
} else {
startInterval = rangeBoundary[0];
endInterval = rangeBoundary[1];
startInterval = rangeBoundary[0].trim();
endInterval = rangeBoundary[1].trim();
}
try {
......
......@@ -197,6 +197,11 @@ public final class UtilConstants {
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";
......@@ -242,6 +247,11 @@ public final class UtilConstants {
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";
......@@ -254,7 +264,7 @@ public final class UtilConstants {
/**
* Static attribute for listener package.
*/
public static final String LISTENER_PKG = "org.onosproject.event";
public static final String ONOS_EVENT_PKG = "org.onosproject.event";
/**
* Static attribute for colon.
......@@ -272,6 +282,21 @@ public final class UtilConstants {
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";
......@@ -742,6 +767,11 @@ public final class UtilConstants {
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";
......@@ -772,6 +802,11 @@ public final class UtilConstants {
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";
......@@ -837,6 +872,11 @@ public final class UtilConstants {
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";
......@@ -942,6 +982,130 @@ public final class UtilConstants {
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 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.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 : ";
......@@ -958,6 +1122,18 @@ public final class UtilConstants {
" 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";
/**
* Creates an instance of util constants.
*/
private UtilConstants() {
......
......@@ -350,6 +350,21 @@ public enum YangConstructType {
REFINE_DATA,
/**
* Identifies the YANG leafref element parsed data.
*/
LEAFREF_DATA,
/**
* Identifies the YANG identityref element parsed data.
*/
IDENTITYREF_DATA,
/**
* Identifies the YANG instance identifier element parsed data.
*/
INSTANCE_IDENTIFIER_DATA,
/**
* Identifies the YANG deviation element parsed data.
*/
DEVIATION_DATA,
......@@ -500,6 +515,12 @@ public enum YangConstructType {
return "unique";
case REFINE_DATA:
return "refine";
case LEAFREF_DATA:
return "leafref";
case IDENTITYREF_DATA:
return "identityref";
case INSTANCE_IDENTIFIER_DATA:
return "instance-identifier";
case DEVIATION_DATA:
return "deviation";
case ANYXML_DATA:
......
/*
* 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.builtindatatype;
import java.util.Objects;
import com.google.common.base.MoreObjects;
/**
* Represents binary data type.
*/
public final class YangBinary {
private byte[] byteArray;
/**
* Creates an instance of YANG binary.
*/
private YangBinary() {
}
/**
* Creates an instance of YANG binary.
*
* @param bytes byte array
*/
public YangBinary(byte[] bytes) {
this.byteArray = bytes;
}
/**
* Returns object of YANG binary.
*
* @param bytes byte array
* @return object of YANG binary
*/
public static YangBinary of(byte[] bytes) {
return new YangBinary(bytes);
}
/**
* Returns byte array.
*
* @return byte array
*/
public byte[] byteArray() {
return byteArray;
}
@Override
public int hashCode() {
return Objects.hash(byteArray);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof YangBinary) {
YangBinary other = (YangBinary) obj;
return Objects.equals(byteArray, other.byteArray);
}
return false;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.omitNullValues()
.add("byteArray", byteArray)
.toString();
}
/**
* Returns the object of YANG binary fromString input String.
*
* @param valInString input String
* @return Object of YANG binary
*/
public static YangBinary fromString(String valInString) {
try {
byte[] tmpVal = valInString.getBytes();
return of(tmpVal);
} catch (Exception e) {
}
return null;
}
}
/*
* 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.builtindatatype;
import java.util.Objects;
import com.google.common.base.MoreObjects;
/**
* Represents bits data type.
*/
public class YangBits {
private byte[] byteArray;
/**
* Creates an instance of YANG bits.
*/
private YangBits() {
}
/**
* Creates an instance of YANG bits.
*
* @param bytes byte array
*/
public YangBits(byte[] bytes) {
this.byteArray = bytes;
}
/**
* Returns object of YANG bits.
*
* @param bytes byte array
* @return object of YANG bits
*/
public static YangBits of(byte[] bytes) {
return new YangBits(bytes);
}
/**
* Returns byte array.
*
* @return byte array
*/
public byte[] byteArray() {
return byteArray;
}
@Override
public int hashCode() {
return Objects.hash(byteArray);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof YangBits) {
YangBits other = (YangBits) obj;
return Objects.equals(byteArray, other.byteArray);
}
return false;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.omitNullValues()
.add("byteArray", byteArray)
.toString();
}
/**
* Returns the object of YANG bits fromString input String.
*
* @param valInString input String
* @return Object of YANG bits
*/
public static YangBits fromString(String valInString) {
try {
byte[] tmpVal = valInString.getBytes();
return of(tmpVal);
} catch (Exception e) {
}
return null;
}
}
/*
* 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.builtindatatype;
import java.util.Objects;
import com.google.common.base.MoreObjects;
/**
* Represents YANG decimal 64.
*/
public class YangDecimal64 {
private int fractionDigit;
/**
* Creates an instance of YANG decimal64.
*/
public YangDecimal64() {
}
/**
* Creates an instance of of YANG decimal64.
*
* @param fractionDigit fraction digit
*/
public YangDecimal64(int fractionDigit) {
this.setFractionDigit(fractionDigit);
}
/**
* Returns fraction digit.
*
* @return the fractionDigit
*/
public int getFractionDigit() {
return fractionDigit;
}
/**
* Sets fraction digit.
*
* @param fractionDigit fraction digits.
*/
public void setFractionDigit(int fractionDigit) {
this.fractionDigit = fractionDigit;
}
/**
* Returns object of YANG decimal64.
*
* @param value fraction digit
* @return YANG decimal64
*/
public static YangDecimal64 of(int value) {
return new YangDecimal64(value);
}
@Override
public int hashCode() {
return Objects.hash(fractionDigit);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof YangDecimal64) {
YangDecimal64 other = (YangDecimal64) obj;
return Objects.equals(fractionDigit, other.fractionDigit);
}
return false;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.omitNullValues()
.add("fractionDigit", fractionDigit)
.toString();
}
/**
* Returns the object of YANG decimal64 fromString input String.
*
* @param valInString input String
* @return Object of YANG decimal64
*/
public static YangDecimal64 fromString(String valInString) {
try {
int tmpVal = Integer.parseInt(valInString);
return of(tmpVal);
} catch (Exception e) {
}
return null;
}
}
......@@ -22,6 +22,8 @@ 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;
......@@ -84,10 +86,12 @@ public final class FileSystemUtil {
YangNode parent = getParentNodeInGenCode(yangNode);
if (parent != null) {
pkgInfo = ((JavaFileInfoContainer) parent).getJavaFileInfo().getJavaName();
addPackageInfo(pack, pkgInfo, getJavaPackageFromPackagePath(pkg), true);
addPackageInfo(pack, pkgInfo, getJavaPackageFromPackagePath(pkg), true,
((JavaFileInfoContainer) parent).getJavaFileInfo().getPluginConfig());
} else {
pkgInfo = ((JavaFileInfoContainer) yangNode).getJavaFileInfo().getJavaName();
addPackageInfo(pack, pkgInfo, getJavaPackageFromPackagePath(pkg), false);
addPackageInfo(pack, pkgInfo, getJavaPackageFromPackagePath(pkg), false,
((JavaFileInfoContainer) yangNode).getJavaFileInfo().getPluginConfig());
}
} catch (IOException e) {
throw new IOException("failed to create package-info file");
......@@ -120,6 +124,7 @@ public final class FileSystemUtil {
*/
public static String readAppendFile(String toAppend, String spaces)
throws IOException {
FileReader fileReader = new FileReader(toAppend);
BufferedReader bufferReader = new BufferedReader(fileReader);
try {
......@@ -156,15 +161,22 @@ public final class FileSystemUtil {
*/
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 {
fileWriter.flush();
fileWriter.close();
for (FileWriter curWriter : fileWriterStore) {
curWriter.flush();
curWriter.close();
curWriter = null;
}
}
}
}
......
......@@ -17,12 +17,14 @@
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;
......@@ -181,7 +183,12 @@ public final class JavaDocGen {
/**
* For manager setters.
*/
MANAGER_SETTER_METHOD
MANAGER_SETTER_METHOD,
/**
* For event subject.
*/
EVENT_SUBJECT_CLASS
}
/**
......@@ -190,14 +197,15 @@ public final class JavaDocGen {
* @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) {
public static String getJavaDoc(JavaDocType type, String name, boolean isList, YangPluginConfig pluginConfig) {
name = JavaIdentifierSyntax.getSmallCase(getCamelCase(name, null));
name = JavaIdentifierSyntax.getSmallCase(getCamelCase(name, pluginConfig.getConflictResolver()));
switch (type) {
case IMPL_CLASS: {
return generateForImplClass(name);
return generateForClass(name);
}
case BUILDER_CLASS: {
return generateForBuilderClass(name);
......@@ -248,7 +256,7 @@ public final class JavaDocGen {
return generateForRpcService(name);
}
case RPC_MANAGER: {
return generateForImplClass(name);
return generateForClass(name);
}
case EVENT: {
return generateForEvent(name);
......@@ -256,6 +264,9 @@ public final class JavaDocGen {
case EVENT_LISTENER: {
return generateForEventListener(name);
}
case EVENT_SUBJECT_CLASS: {
return generateForClass(name);
}
default: {
return generateForConstructors(name);
}
......@@ -279,14 +290,19 @@ public final class JavaDocGen {
* @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) {
rpcName = getCamelCase(rpcName, null);
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);
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);
}
......@@ -393,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;
}
......@@ -470,7 +487,7 @@ public final class JavaDocGen {
* @param className class name
* @return javaDocs
*/
private static String generateForImplClass(String className) {
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;
}
......
......@@ -60,8 +60,8 @@ public final class YangFileScanner {
* operations
*/
public static List<String> getYangFiles(String root) throws IOException {
List<String> yangFiles = getFiles(root, YANG_FILE_EXTENTION);
return yangFiles;
return getFiles(root, YANG_FILE_EXTENTION);
}
/**
......
......@@ -25,8 +25,8 @@ import YangLexer;
package org.onosproject.yangutils.parser.antlrgencode;
}
yangfile : moduleStatement
| subModuleStatement;
yangfile : moduleStatement EOF
| subModuleStatement EOF;
/**
* module-stmt = optsep module-keyword sep identifier-arg-str
......
......@@ -564,7 +564,7 @@ public class IntraFileUsesLinkingTest {
thrown.expect(ParserException.class);
thrown.expectMessage(
"YANG file error: Unable to find base typedef/grouping for given type/uses");
"YANG file error: Unable to find base grouping for given uses");
YangNode node = manager
.getDataModel("src/test/resources/SelfResolutionNestedGroupingWithUnresolvedUses.yang");
......
......@@ -52,4 +52,34 @@ public class TreeWalkListenerTest {
thrown.expectMessage("YANG file error : \"anyxml\" is not supported.");
manager.getDataModel("src/test/resources/AnyxmlStatement.yang");
}
/**
* Checks whether exception is thrown when extra brace is added in the EOF.
*/
@Test
public void processFileWithExtraBrace() throws IOException, ParserException {
thrown.expect(ParserException.class);
thrown.expectMessage("mismatched input '}' expecting <EOF>");
manager.getDataModel("src/test/resources/ProcessFileWithExtraBrace.yang");
}
/**
* Checks whether exception is thrown when leaf is given after module ends.
*/
@Test
public void processFileWithExtraLeaf() throws IOException, ParserException {
thrown.expect(ParserException.class);
thrown.expectMessage("mismatched input 'leaf' expecting <EOF>");
manager.getDataModel("src/test/resources/ProcessFileWithExtraLeaf.yang");
}
/**
* Checks whether exception is thrown when extra brace is added in between the EOF.
*/
@Test
public void processFileWithExtraBraceInBetween() throws IOException, ParserException {
thrown.expect(ParserException.class);
thrown.expectMessage("mismatched input 'container' expecting <EOF>");
manager.getDataModel("src/test/resources/ProcessFileWithExtraBraceInBetween.yang");
}
}
......
......@@ -26,10 +26,14 @@ import org.onosproject.yangutils.datamodel.YangLeaf;
import org.onosproject.yangutils.datamodel.YangModule;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.datamodel.YangNodeType;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.datamodel.YangTypeDef;
import org.onosproject.yangutils.datamodel.YangUnion;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.YangUtilsParserManager;
import java.io.IOException;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
......@@ -80,6 +84,84 @@ public class BitListenerTest {
}
/**
* Checks bit statement with typedef.
*/
@Test
public void processBitTypedefStatement() throws IOException, ParserException {
YangNode node = manager.getDataModel("src/test/resources/BitTypedefStatement.yang");
// Check whether the data model tree returned is of type module.
assertThat((node instanceof YangModule), is(true));
// Check whether the node type is set properly to module.
assertThat(node.getNodeType(), is(YangNodeType.MODULE_NODE));
// Check whether the module name is set correctly.
YangModule yangNode = (YangModule) node;
assertThat(yangNode.getName(), is("Test"));
YangTypeDef typedef = (YangTypeDef) yangNode.getChild();
assertThat(typedef.getName(), is("type15"));
YangType type = typedef.getTypeList().iterator().next();
assertThat(type.getDataType(), is(YangDataTypes.BITS));
assertThat(type.getDataTypeName(), is("bits"));
Set<YangBit> bitSet = ((YangBits) type.getDataTypeExtendedInfo()).getBitSet();
for (YangBit tmp : bitSet) {
if (tmp.getBitName().equals("disable-nagle")) {
assertThat(tmp.getPosition(), is(0));
} else if (tmp.getBitName().equals("auto-sense-speed")) {
assertThat(tmp.getPosition(), is(1));
}
}
}
/**
* Checks bit statement with union.
*/
@Test
public void processBitUnionStatement() throws IOException, ParserException {
YangNode node = manager.getDataModel("src/test/resources/BitUnionStatement.yang");
// Check whether the data model tree returned is of type module.
assertThat((node instanceof YangModule), is(true));
// Check whether the node type is set properly to module.
assertThat(node.getNodeType(), is(YangNodeType.MODULE_NODE));
// Check whether the module name is set correctly.
YangModule yangNode = (YangModule) node;
assertThat(yangNode.getName(), is("Test"));
ListIterator<YangLeaf> leafIterator = yangNode.getListOfLeaf().listIterator();
YangLeaf leafInfo = leafIterator.next();
assertThat(leafInfo.getName(), is("type15"));
assertThat(leafInfo.getDataType().getDataType(), is(YangDataTypes.UNION));
assertThat(leafInfo.getDataType().getDataTypeName(), is("union"));
YangUnion yangUnion = (YangUnion) leafInfo.getDataType().getDataTypeExtendedInfo();
List<YangType<?>> typeList = yangUnion.getTypeList();
ListIterator<YangType<?>> typeListIterator = typeList.listIterator();
YangType<?> yangType = typeListIterator.next();
assertThat(yangType.getDataType(), is(YangDataTypes.BITS));
assertThat(yangType.getDataTypeName(), is("bits"));
Set<YangBit> bitSet = ((YangBits) yangType.getDataTypeExtendedInfo()).getBitSet();
for (YangBit tmp : bitSet) {
if (tmp.getBitName().equals("disable-nagle")) {
assertThat(tmp.getPosition(), is(0));
} else if (tmp.getBitName().equals("auto-sense-speed")) {
assertThat(tmp.getPosition(), is(1));
}
}
}
/**
* Checks if enum with same name is not allowed.
*/
@Test(expected = ParserException.class)
......
......@@ -33,8 +33,9 @@ import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.YangUtilsParserManager;
import java.io.IOException;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Set;
import java.util.SortedSet;
/**
* Test cases for enum listener.
......@@ -73,7 +74,7 @@ public class EnumListenerTest {
assertThat(((YangEnumeration) leafInfo.getDataType().getDataTypeExtendedInfo()).getName(),
is("speed_enum"));
Set<YangEnum> enumSet = ((YangEnumeration) leafInfo.getDataType().getDataTypeExtendedInfo()).getEnumSet();
SortedSet<YangEnum> enumSet = ((YangEnumeration) leafInfo.getDataType().getDataTypeExtendedInfo()).getEnumSet();
for (YangEnum tmp : enumSet) {
if (tmp.getNamedValue().equals("10m")) {
assertThat(tmp.getValue(), is(0));
......@@ -114,4 +115,34 @@ public class EnumListenerTest {
+ "with the current highest value");
YangNode node = manager.getDataModel("src/test/resources/EnumMaxNextValue.yang");
}
/**
* Checks enum values stored are sorted.
*/
@Test
public void processEnumSorted() throws IOException, ParserException {
YangNode node = manager.getDataModel("src/test/resources/EnumSorted.yang");
// Check whether the data model tree returned is of type module.
assertThat((node instanceof YangModule), is(true));
// Check whether the node type is set properly to module.
assertThat(node.getNodeType(), is(YangNodeType.MODULE_NODE));
// Check whether the module name is set correctly.
YangModule yangNode = (YangModule) node;
assertThat(yangNode.getName(), is("Test"));
ListIterator<YangLeaf> leafIterator = yangNode.getListOfLeaf().listIterator();
YangLeaf leafInfo = leafIterator.next();
assertThat(leafInfo.getName(), is("ifType"));
assertThat(leafInfo.getDataType().getDataTypeName(), is("enumeration"));
assertThat(leafInfo.getDataType().getDataType(), is(YangDataTypes.ENUMERATION));
assertThat(((YangEnumeration) leafInfo.getDataType().getDataTypeExtendedInfo()).getName(),
is("ifType_enum"));
SortedSet<YangEnum> enumSet = ((YangEnumeration) leafInfo.getDataType().getDataTypeExtendedInfo()).getEnumSet();
Iterator<YangEnum> enumIterator = enumSet.iterator();
assertThat(enumIterator.next().getNamedValue(), is("five"));
}
}
......
......@@ -267,4 +267,36 @@ public class LengthRestrictionListenerTest {
assertThat(((YangUint64) rangeInterval.getStartValue()).getValue(), is(BigInteger.valueOf(0)));
assertThat(((YangUint64) rangeInterval.getEndValue()).getValue(), is(BigInteger.valueOf(100)));
}
/**
* Checks whether space can be allowed when length statement is present.
*/
@Test
public void processLengthStatementWithSpace() throws IOException, ParserException {
YangNode node = manager.getDataModel("src/test/resources/LengthStatementWithSpace.yang");
assertThat((node instanceof YangModule), is(true));
assertThat(node.getNodeType(), is(YangNodeType.MODULE_NODE));
YangModule yangNode = (YangModule) node;
assertThat(yangNode.getName(), is("Test"));
ListIterator<YangLeaf> leafIterator = yangNode.getListOfLeaf().listIterator();
YangLeaf leafInfo = leafIterator.next();
assertThat(leafInfo.getName(), is("invalid-interval"));
assertThat(leafInfo.getDataType().getDataTypeName(), is("string"));
assertThat(leafInfo.getDataType().getDataType(), is(YangDataTypes.STRING));
YangStringRestriction stringRestriction = (YangStringRestriction) leafInfo
.getDataType().getDataTypeExtendedInfo();
YangRangeRestriction lengthRestriction = stringRestriction.getLengthRestriction();
ListIterator<YangRangeInterval> lengthListIterator = lengthRestriction.getAscendingRangeIntervals()
.listIterator();
YangRangeInterval rangeInterval = lengthListIterator.next();
assertThat(((YangUint64) rangeInterval.getStartValue()).getValue(), is(BigInteger.valueOf(0)));
assertThat(((YangUint64) rangeInterval.getEndValue()).getValue(), is(BigInteger.valueOf(100)));
}
}
......
......@@ -176,4 +176,15 @@ public class MaxElementsListenerTest {
assertThat(leafListInfo.getName(), is("invalid-interval"));
assertThat(leafListInfo.getMaxElelements(), is(2147483647));
}
/**
* Checks whether exception is thrown when invalid min-elements value is
* given as input.
*/
@Test
public void processMaxElementsMaxValue() throws IOException, ParserException {
thrown.expect(ParserException.class);
thrown.expectMessage("YANG file error : max-elements value 77777777777777777777777 is not valid.");
YangNode node = manager.getDataModel("src/test/resources/MaxElementsMaxValue.yang");
}
}
......
......@@ -116,6 +116,17 @@ public class MinElementsListenerTest {
}
/**
* Checks whether exception is thrown when invalid min-elements value is
* given as input.
*/
@Test
public void processMinElementsMaxValue() throws IOException, ParserException {
thrown.expect(ParserException.class);
thrown.expectMessage("YANG file error : min-elements value 77777777777777777777777 is not valid.");
YangNode node = manager.getDataModel("src/test/resources/MinElementsMaxValue.yang");
}
/**
* Checks whether exception is thrown when min-elements statement without
* statement end is given as input.
*/
......
......@@ -66,6 +66,6 @@ public class NotificationListenerTest {
YangLeaf leafInfo = leafIterator.next();
assertThat(leafInfo.getName(), is("if-name"));
assertThat(leafInfo.getDataType().getDataTypeName(), is("leafref"));
assertThat(leafInfo.getDataType().getDataTypeName(), is("string"));
}
}
......
......@@ -207,4 +207,33 @@ public class RangeRestrictionListenerTest {
assertThat(((YangInt32) rangeInterval.getEndValue()).getValue(), is(4));
assertThat(((YangInt32) rangeInterval.getEndValue()).getValue(), is(4));
}
/**
* Checks whether space can be allowed when range statement is present.
*/
@Test
public void processRangeStatementWithSpace() throws IOException, ParserException {
YangNode node = manager.getDataModel("src/test/resources/RangeStatementWithSpace.yang");
assertThat((node instanceof YangModule), is(true));
assertThat(node.getNodeType(), is(YangNodeType.MODULE_NODE));
YangModule yangNode = (YangModule) node;
assertThat(yangNode.getName(), is("Test"));
ListIterator<YangLeaf> leafIterator = yangNode.getListOfLeaf().listIterator();
YangLeaf leafInfo = leafIterator.next();
assertThat(leafInfo.getName(), is("invalid-interval"));
assertThat(leafInfo.getDataType().getDataTypeName(), is("int32"));
assertThat(leafInfo.getDataType().getDataType(), is(YangDataTypes.INT32));
YangRangeRestriction rangeRestriction = (YangRangeRestriction) leafInfo
.getDataType().getDataTypeExtendedInfo();
ListIterator<YangRangeInterval> rangeListIterator = rangeRestriction.getAscendingRangeIntervals()
.listIterator();
YangRangeInterval rangeInterval = rangeListIterator.next();
assertThat(((YangInt32) rangeInterval.getStartValue()).getValue(), is(1));
assertThat(((YangInt32) rangeInterval.getEndValue()).getValue(), is(4));
}
}
......
......@@ -17,7 +17,9 @@ package org.onosproject.yangutils.parser.impl.listeners;
import java.io.IOException;
import java.util.ListIterator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onosproject.yangutils.datamodel.YangDataTypes;
import org.onosproject.yangutils.datamodel.YangLeaf;
import org.onosproject.yangutils.datamodel.YangLeafList;
......@@ -35,6 +37,9 @@ import static org.hamcrest.core.Is.is;
*/
public class TypeListenerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private final YangUtilsParserManager manager = new YangUtilsParserManager();
/**
......@@ -114,4 +119,46 @@ public class TypeListenerTest {
assertThat(leafListInfo.getDataType().getDataTypeName(), is("uint16"));
assertThat(leafListInfo.getDataType().getDataType(), is(YangDataTypes.UINT16));
}
/**
* Checks for unsupported type leafref.
*/
@Test
public void processLeafrefType() throws IOException, ParserException {
thrown.expect(ParserException.class);
thrown.expectMessage("YANG file error : \"leafref\" is not supported in current version,"
+ " please check wiki for YANG utils road map.");
YangNode node = manager
.getDataModel("src/test/resources/LeafrefInvalidIdentifier.yang");
}
/**
* Checks for unsupported type identityref.
*/
@Test
public void processIdentityrefType() throws IOException, ParserException {
thrown.expect(ParserException.class);
thrown.expectMessage("YANG file error : \"identityref\" is not supported in current version,"
+ " please check wiki for YANG utils road map.");
YangNode node = manager
.getDataModel("src/test/resources/IdentityrefInvalidIdentifier.yang");
}
/**
* Checks for unsupported type instance identifier.
*/
@Test
public void processInstanceIdentifierType() throws IOException, ParserException {
thrown.expect(ParserException.class);
thrown.expectMessage("YANG file error : \"instance-identifier\" is not supported in current version,"
+ " please check wiki for YANG utils road map.");
YangNode node = manager
.getDataModel("src/test/resources/InstanceIdentifierInvalidIdentifier.yang");
}
}
......
/*
* 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.parseutils;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.YangUtilsParserManager;
/**
* Test case for testing listener util.
*/
public class ListenerUtilTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private final YangUtilsParserManager manager = new YangUtilsParserManager();
/**
* Checks whether exception is thrown when identifier starts with xml.
*/
@Test
public void validateIdentifierStartsWithXml() throws IOException {
thrown.expect(ParserException.class);
thrown.expectMessage("YANG file error : module identifier xMlTest must not start" +
" with (('X'|'x') ('M'|'m') ('L'|'l'))");
manager.getDataModel("src/test/resources/InValidIdentifierXML.yang");
}
}
/*
* 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);
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.