Bharat saraswal

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

Change-Id: I1b23f9ed0293edbc2d551efe82982559eb916ede
Showing 109 changed files with 4120 additions and 1343 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)) {
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;
}
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,6 +140,7 @@ public final class JavaCodeGeneratorUtil {
private static void freeRestResources() {
YangNode freedNode = getCurNode();
if (getCurNode() != null) {
YangNode tempNode = freedNode;
TraversalType curTraversal = ROOT;
......@@ -185,6 +164,7 @@ public final class JavaCodeGeneratorUtil {
}
}
}
}
/**
* Free the current node.
......@@ -213,6 +193,7 @@ public final class JavaCodeGeneratorUtil {
public static void translatorErrorHandler(YangNode rootNode)
throws IOException {
if (rootNode != null) {
/**
* Free other resources where translator has failed.
*/
......@@ -244,6 +225,7 @@ public final class JavaCodeGeneratorUtil {
freeRestResources();
}
}
/**
* Closes all the current open file handles of node and delete all generated
......@@ -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);
}
}
......@@ -28,6 +28,12 @@ import org.onosproject.yangutils.datamodel.YangLeavesHolder;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.translator.exception.TranslatorException;
import org.onosproject.yangutils.translator.tojava.javamodel.JavaLeafInfoContainer;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaGrouping;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaInput;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaOutput;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaUses;
import org.onosproject.yangutils.translator.tojava.utils.JavaExtendsListHolder;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
......@@ -61,6 +67,7 @@ import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSy
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getParentNodeInGenCode;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getRootPackage;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getBuildString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getDefaultConstructorString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEqualsMethod;
......@@ -795,35 +802,40 @@ public class TempJavaFragmentFiles {
* Adds attribute for class.
*
* @param attr attribute info
* @param pluginConfig plugin configurations
* @throws IOException when fails to append to temporary file
*/
private void addAttribute(JavaAttributeInfo attr)
private void addAttribute(JavaAttributeInfo attr, YangPluginConfig yangPluginConfig)
throws IOException {
appendToFile(getAttributesTempFileHandle(), parseAttribute(attr) + FOUR_SPACE_INDENTATION);
appendToFile(getAttributesTempFileHandle(), parseAttribute(attr, yangPluginConfig)
+ FOUR_SPACE_INDENTATION);
}
/**
* Adds getter for interface.
*
* @param attr attribute info
* @param pluginConfig plugin configurations
* @throws IOException when fails to append to temporary file
*/
private void addGetterForInterface(JavaAttributeInfo attr)
private void addGetterForInterface(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
throws IOException {
appendToFile(getGetterInterfaceTempFileHandle(),
getGetterString(attr, getGeneratedJavaFiles()) + NEW_LINE);
getGetterString(attr, getGeneratedJavaFiles(), pluginConfig) + NEW_LINE);
}
/**
* Adds setter for interface.
*
* @param attr attribute info
* @param pluginConfig plugin configurations
* @throws IOException when fails to append to temporary file
*/
private void addSetterForInterface(JavaAttributeInfo attr)
private void addSetterForInterface(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
throws IOException {
appendToFile(getSetterInterfaceTempFileHandle(),
getSetterString(attr, getGeneratedJavaClassName(), getGeneratedJavaFiles()) + NEW_LINE);
getSetterString(attr, getGeneratedJavaClassName(), getGeneratedJavaFiles(), pluginConfig)
+ NEW_LINE);
}
/**
......@@ -844,9 +856,10 @@ public class TempJavaFragmentFiles {
* Adds getter method's impl for class.
*
* @param attr attribute info
* @param pluginConfig plugin configurations
* @throws IOException when fails to append to temporary file
*/
private void addGetterImpl(JavaAttributeInfo attr)
private void addGetterImpl(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
throws IOException {
if ((getGeneratedJavaFiles() & BUILDER_CLASS_MASK) != 0
|| (getGeneratedJavaFiles() & GENERATE_SERVICE_AND_MANAGER) != 0) {
......@@ -854,7 +867,7 @@ public class TempJavaFragmentFiles {
getGeneratedJavaFiles()) + NEW_LINE);
} else {
appendToFile(getGetterImplTempFileHandle(),
getJavaDoc(GETTER_METHOD, getCapitalCase(attr.getAttributeName()), false)
getJavaDoc(GETTER_METHOD, getCapitalCase(attr.getAttributeName()), false, pluginConfig)
+ getGetterForClass(attr, getGeneratedJavaFiles()) + NEW_LINE);
}
}
......@@ -863,11 +876,12 @@ public class TempJavaFragmentFiles {
* Adds build method for interface.
*
* @return build method for interface
* @param pluginConfig plugin configurations
* @throws IOException when fails to append to temporary file
*/
String addBuildMethodForInterface()
String addBuildMethodForInterface(YangPluginConfig pluginConfig)
throws IOException {
return parseBuilderInterfaceBuildMethodString(getGeneratedJavaClassName());
return parseBuilderInterfaceBuildMethodString(getGeneratedJavaClassName(), pluginConfig);
}
/**
......@@ -886,23 +900,26 @@ public class TempJavaFragmentFiles {
*
* @param modifier modifier for constructor.
* @param toAppend string which need to be appended with the class name
* @param pluginConfig plugin configurations
* @return default constructor for class
* @throws IOException when fails to append to file
*/
String addDefaultConstructor(String modifier, String toAppend)
String addDefaultConstructor(String modifier, String toAppend, YangPluginConfig pluginConfig)
throws IOException {
return NEW_LINE + getDefaultConstructorString(getGeneratedJavaClassName() + toAppend, modifier);
return NEW_LINE
+ getDefaultConstructorString(getGeneratedJavaClassName() + toAppend, modifier, pluginConfig);
}
/**
* Adds default constructor for class.
*
* @param pluginCnfig plugin configurations
* @return default constructor for class
* @throws IOException when fails to append to file
*/
public String addOfMethod()
public String addOfMethod(YangPluginConfig pluginCnfig)
throws IOException {
return getJavaDoc(OF_METHOD, getGeneratedJavaClassName(), false)
return getJavaDoc(OF_METHOD, getGeneratedJavaClassName(), false, pluginCnfig)
+ getOfMethod(getGeneratedJavaClassName(), null);
}
......@@ -994,6 +1011,7 @@ public class TempJavaFragmentFiles {
*/
public String getTemporaryDataFromFileHandle(File file)
throws IOException {
String path = getTempDirPath();
if (new File(path + file.getName()).exists()) {
return readAppendFile(path + file.getName(), EMPTY_STRING);
......@@ -1017,13 +1035,14 @@ public class TempJavaFragmentFiles {
* Parses attribute to get the attribute string.
*
* @param attr attribute info
* @param pluginConfig plugin configurations
* @return attribute string
*/
private String parseAttribute(JavaAttributeInfo attr) {
public String parseAttribute(JavaAttributeInfo attr, YangPluginConfig pluginConfig) {
/*
* TODO: check if this utility needs to be called or move to the caller
*/
String attributeName = getCamelCase(attr.getAttributeName(), null);
String attributeName = getCamelCase(attr.getAttributeName(), pluginConfig.getConflictResolver());
if (attr.isQualifiedName()) {
return getJavaAttributeDefination(attr.getImportInfo().getPkgInfo(),
attr.getImportInfo().getClassInfo(),
......@@ -1056,22 +1075,26 @@ public class TempJavaFragmentFiles {
* @param curNode current node which needs to be added as an attribute in
* the parent generated code
* @param isList is list construct
* @param pluginConfig plugin configurations
* @throws IOException IO operation exception
*/
public static void addCurNodeInfoInParentTempFile(YangNode curNode,
boolean isList)
boolean isList, YangPluginConfig pluginConfig)
throws IOException {
YangNode parent = getParentNodeInGenCode(curNode);
if (!(parent instanceof JavaCodeGenerator)) {
throw new TranslatorException("missing parent node to contain current node info in generated file");
}
if (curNode instanceof YangJavaUses) {
curNode = ((YangJavaUses) curNode).getRefGroup();
}
JavaAttributeInfo javaAttributeInfo = getCurNodeAsAttributeInParent(curNode,
parent, isList);
if (!(parent instanceof TempJavaCodeFragmentFilesContainer)) {
throw new TranslatorException("missing parent temp file handle");
}
getNodesInterfaceFragmentFiles(parent)
.addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo);
.addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, pluginConfig);
}
/**
......@@ -1087,23 +1110,57 @@ public class TempJavaFragmentFiles {
*/
public static JavaAttributeInfo getCurNodeAsAttributeInParent(
YangNode curNode, YangNode parentNode, boolean isListNode) {
String curNodeName = ((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName();
/*
* Get the import info corresponding to the attribute for import in
* generated java files or qualified access
*/
JavaQualifiedTypeInfo qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(parentNode,
getCapitalCase(curNodeName));
YangPluginConfig pluginConfig = ((JavaFileInfoContainer) parentNode).getJavaFileInfo().getPluginConfig();
JavaFileInfo curNodeJavaInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
String curNodeName = null;
if (curNodeJavaInfo.getJavaName() != null) {
curNodeName = curNodeJavaInfo.getJavaName();
} else {
curNodeName = getCamelCase(curNode.getName(), pluginConfig.getConflictResolver());
}
if (!(parentNode instanceof TempJavaCodeFragmentFilesContainer)) {
throw new TranslatorException("Parent node does not have file info");
}
TempJavaFragmentFiles tempJavaFragmentFiles = getNodesInterfaceFragmentFiles(parentNode);
boolean isQualified = true;
JavaImportData parentImportData = tempJavaFragmentFiles.getJavaImportData();
if (isListNode) {
parentImportData.setIfListImported(true);
}
if (!detectCollisionBwParentAndChildForImport(curNode, qualifiedTypeInfo)) {
/*
* Get the import info corresponding to the attribute for import in
* generated java files or qualified access
*/
JavaQualifiedTypeInfo qualifiedTypeInfo = new JavaQualifiedTypeInfo();
if (curNode instanceof YangJavaGrouping) {
qualifiedTypeInfo = resolveGroupingsQuailifiedInfo(curNode, pluginConfig);
} else {
qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(parentNode,
getCapitalCase(curNodeName));
}
if (parentNode instanceof YangJavaModule
|| parentNode instanceof YangJavaSubModule
|| parentNode instanceof YangJavaInput
|| parentNode instanceof YangJavaOutput) {
parentImportData.addImportInfo(qualifiedTypeInfo);
isQualified = false;
} else if (curNode instanceof YangJavaGrouping) {
JavaFileInfo parentsClassInfo = ((JavaFileInfoContainer) parentNode).getJavaFileInfo();
if (qualifiedTypeInfo.getClassInfo().equals(parentsClassInfo.getJavaName())) {
isQualified = true;
}
if (!qualifiedTypeInfo.getPkgInfo().equals(parentsClassInfo.getPackage())) {
parentImportData.addImportInfo(qualifiedTypeInfo);
isQualified = false;
}
} else if (!detectCollisionBwParentAndChildForImport(curNode, qualifiedTypeInfo)) {
parentImportData.addImportInfo(qualifiedTypeInfo);
isQualified = false;
}
......@@ -1111,6 +1168,63 @@ public class TempJavaFragmentFiles {
}
/**
* Resolves groupings java qualified info.
*
* @param curNode grouping node
* @param pluginConfig plugin configurations
* @return groupings java qualified info
*/
public static JavaQualifiedTypeInfo resolveGroupingsQuailifiedInfo(YangNode curNode,
YangPluginConfig pluginConfig) {
JavaFileInfo groupingFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
JavaQualifiedTypeInfo qualifiedTypeInfo = new JavaQualifiedTypeInfo();
if (groupingFileInfo.getPackage() == null) {
List<String> parentNames = new ArrayList<>();
YangNode tempNode = curNode.getParent();
YangNode groupingSuperParent = null;
while (tempNode != null) {
parentNames.add(tempNode.getName());
groupingSuperParent = tempNode;
tempNode = tempNode.getParent();
}
String pkg = null;
JavaFileInfo parentInfo = ((JavaFileInfoContainer) groupingSuperParent).getJavaFileInfo();
if (parentInfo.getPackage() == null) {
if (groupingSuperParent instanceof YangJavaModule) {
YangJavaModule module = (YangJavaModule) groupingSuperParent;
String modulePkg = getRootPackage(module.getVersion(), module.getNameSpace().getUri(), module
.getRevision().getRevDate(), pluginConfig.getConflictResolver());
pkg = modulePkg;
} else if (groupingSuperParent instanceof YangJavaSubModule) {
YangJavaSubModule submodule = (YangJavaSubModule) groupingSuperParent;
String subModulePkg = getRootPackage(submodule.getVersion(),
submodule.getNameSpaceFromModule(submodule.getBelongsTo()),
submodule.getRevision().getRevDate(), pluginConfig.getConflictResolver());
pkg = subModulePkg;
}
} else {
pkg = parentInfo.getPackage();
}
for (String name : parentNames) {
pkg = pkg + PERIOD + getCamelCase(name, pluginConfig.getConflictResolver());
}
qualifiedTypeInfo.setPkgInfo(pkg.toLowerCase());
qualifiedTypeInfo.setClassInfo(
getCapitalCase(getCamelCase(curNode.getName(), pluginConfig.getConflictResolver())));
return qualifiedTypeInfo;
} else {
qualifiedTypeInfo.setPkgInfo(groupingFileInfo.getPackage().toLowerCase());
qualifiedTypeInfo.setClassInfo(getCapitalCase(groupingFileInfo.getJavaName()));
return qualifiedTypeInfo;
}
}
/**
* Returns interface fragment files for node.
*
* @param node YANG node
......@@ -1134,8 +1248,9 @@ public class TempJavaFragmentFiles {
* Adds parent's info to current node import list.
*
* @param curNode current node for which import list needs to be updated
* @param pluginConfig plugin configurations
*/
public void addParentInfoInCurNodeTempFile(YangNode curNode) {
public void addParentInfoInCurNodeTempFile(YangNode curNode, YangPluginConfig pluginConfig) {
caseImportInfo = new JavaQualifiedTypeInfo();
YangNode parent = getParentNodeInGenCode(curNode);
if (!(parent instanceof JavaCodeGenerator)) {
......@@ -1145,7 +1260,8 @@ public class TempJavaFragmentFiles {
throw new TranslatorException("missing java file information to get the package details "
+ "of attribute corresponding to child node");
}
caseImportInfo.setClassInfo(getCapitalCase(getCamelCase(parent.getName(), null)));
caseImportInfo.setClassInfo(getCapitalCase(getCamelCase(parent.getName(),
pluginConfig.getConflictResolver())));
caseImportInfo.setPkgInfo(((JavaFileInfoContainer) parent).getJavaFileInfo().getPackage());
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.getBeanTempFiles().getJavaImportData().addImportInfo(caseImportInfo);
......@@ -1167,6 +1283,7 @@ public class TempJavaFragmentFiles {
throw new TranslatorException("Leaf does not have java information");
}
JavaLeafInfoContainer javaLeaf = (JavaLeafInfoContainer) leaf;
javaLeaf.setConflictResolveConfig(yangPluginConfig.getConflictResolver());
javaLeaf.updateJavaQualifiedInfo();
JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(
javaLeaf.getJavaQualifiedInfo(),
......@@ -1174,7 +1291,7 @@ public class TempJavaFragmentFiles {
javaLeaf.getDataType(),
getIsQualifiedAccessOrAddToImportList(javaLeaf.getJavaQualifiedInfo()),
false);
addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo);
addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, yangPluginConfig);
}
}
}
......@@ -1194,6 +1311,7 @@ public class TempJavaFragmentFiles {
throw new TranslatorException("Leaf-list does not have java information");
}
JavaLeafInfoContainer javaLeaf = (JavaLeafInfoContainer) leafList;
javaLeaf.setConflictResolveConfig(yangPluginConfig.getConflictResolver());
javaLeaf.updateJavaQualifiedInfo();
getJavaImportData().setIfListImported(true);
JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(
......@@ -1202,7 +1320,7 @@ public class TempJavaFragmentFiles {
javaLeaf.getDataType(),
getIsQualifiedAccessOrAddToImportList(javaLeaf.getJavaQualifiedInfo()),
true);
addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo);
addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo, yangPluginConfig);
}
}
}
......@@ -1231,21 +1349,22 @@ public class TempJavaFragmentFiles {
*
* @param newAttrInfo the attribute info that needs to be added to temporary
* files
* @param pluginConfig plugin configurations
* @throws IOException IO operation fail
*/
void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo)
void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo, YangPluginConfig pluginConfig)
throws IOException {
setAttributePresent(true);
if ((getGeneratedTempFiles() & ATTRIBUTES_MASK) != 0) {
addAttribute(newAttrInfo);
addAttribute(newAttrInfo, pluginConfig);
}
if ((getGeneratedTempFiles() & GETTER_FOR_INTERFACE_MASK) != 0) {
addGetterForInterface(newAttrInfo);
addGetterForInterface(newAttrInfo, pluginConfig);
}
if ((getGeneratedTempFiles() & SETTER_FOR_INTERFACE_MASK) != 0) {
addSetterForInterface(newAttrInfo);
addSetterForInterface(newAttrInfo, pluginConfig);
}
if ((getGeneratedTempFiles() & SETTER_FOR_CLASS_MASK) != 0) {
......@@ -1253,7 +1372,7 @@ public class TempJavaFragmentFiles {
}
if ((getGeneratedTempFiles() & GETTER_FOR_CLASS_MASK) != 0) {
addGetterImpl(newAttrInfo);
addGetterImpl(newAttrInfo, pluginConfig);
}
if ((getGeneratedTempFiles() & HASH_CODE_IMPL_MASK) != 0) {
addHashCodeMethod(newAttrInfo);
......@@ -1266,7 +1385,8 @@ public class TempJavaFragmentFiles {
}
if ((getGeneratedTempFiles() & FROM_STRING_IMPL_MASK) != 0) {
JavaQualifiedTypeInfo qualifiedInfoOfFromString = getQualifiedInfoOfFromString(newAttrInfo);
JavaQualifiedTypeInfo qualifiedInfoOfFromString =
getQualifiedInfoOfFromString(newAttrInfo, pluginConfig.getConflictResolver());
/*
* Create a new java attribute info with qualified information of
* wrapper classes.
......@@ -1309,9 +1429,8 @@ public class TempJavaFragmentFiles {
public void generateJavaFile(int fileType, YangNode curNode)
throws IOException {
List<String> imports = new ArrayList<>();
if (isAttributePresent()) {
imports = getJavaImportData().getImports();
}
createPackage(curNode);
/*
......@@ -1319,19 +1438,6 @@ public class TempJavaFragmentFiles {
*/
if ((fileType & INTERFACE_MASK) != 0 || (fileType &
BUILDER_INTERFACE_MASK) != 0) {
/*
* Adds import for case.
*/
if (curNode instanceof YangCase) {
List<String> importData =
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.getBeanTempFiles().getJavaImportData().getImports();
for (String importInfo : importData) {
if (!imports.contains(importInfo)) {
imports.add(importInfo);
}
}
}
/*
* Create interface file.
......
......@@ -22,26 +22,60 @@ import java.util.ArrayList;
import java.util.List;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaNotification;
import org.onosproject.yangutils.datamodel.YangNotification;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_CLASS;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_LISTENER_INTERFACE;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_ENUM_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_METHOD_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_ATTRIBUTE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_GETTER_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_SETTER_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.RPC_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.RPC_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getAttributeInfoForTheData;
import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getQualifiedTypeInfoOfCurNode;
import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getJavaDataType;
import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getJavaImportClass;
import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getJavaClassDefClose;
import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getListAttribute;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEventFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEventListenerFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateEventSubjectFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateManagerClassFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateServiceInterfaceFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGeneratorUtils.getFileObject;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getEnumJavaAttribute;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getSmallCase;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getGetterForClass;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getRpcManagerMethod;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getRpcServiceMethod;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getSetterForClass;
import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.addAnnotationsImports;
import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.addListnersImport;
import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.closeFile;
import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
import static org.onosproject.yangutils.utils.UtilConstants.EVENT_STRING;
import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_REG;
import static org.onosproject.yangutils.utils.UtilConstants.LISTENER_SERVICE;
import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
import static org.onosproject.yangutils.utils.UtilConstants.RPC_INPUT_VAR_NAME;
import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
import static org.onosproject.yangutils.utils.UtilConstants.VOID;
import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.createPackage;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.generateJavaDocForRpc;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.ENUM_ATTRIBUTE;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.GETTER_METHOD;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.MANAGER_SETTER_METHOD;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.insertDataIntoJavaFile;
/**
......@@ -62,6 +96,30 @@ public class TempJavaServiceFragmentFiles
private static final String RPC_IMPL_FILE_NAME = "RpcImpl";
/**
* File name for event enum temp file.
*/
private static final String EVENT_ENUM_FILE_NAME = "EventEnum";
/**
* File name for event method temp file.
*/
private static final String EVENT_METHOD_FILE_NAME = "EventMethod";
/**
* File name for event subject attribute temp file.
*/
private static final String EVENT_SUBJECT_ATTRIBUTE_FILE_NAME = "EventSubjectAttribute";
/**
* File name for event subject getter temp file.
*/
private static final String EVENT_SUBJECT_GETTER_FILE_NAME = "EventSubjectGetter";
/**
* File name for event subject setter temp file.
*/
private static final String EVENT_SUBJECT_SETTER_FILE_NAME = "EventSubjectSetter";
/**
* File name for generated class file for service
* suffix.
*/
......@@ -74,6 +132,41 @@ public class TempJavaServiceFragmentFiles
private static final String MANAGER_FILE_NAME_SUFFIX = "Manager";
/**
* File name for generated class file for special type like union, typedef
* suffix.
*/
private static final String EVENT_FILE_NAME_SUFFIX = "Event";
/**
* File name for generated class file for special type like union, typedef
* suffix.
*/
private static final String EVENT_LISTENER_FILE_NAME_SUFFIX = "Listener";
/**
* File name for generated class file for special type like union, typedef
* suffix.
*/
public static final String EVENT_SUBJECT_NAME_SUFFIX = "EventSubject";
private static final String JAVA_FILE_EXTENSION = ".java";
/**
* Java file handle for event subject file.
*/
private File eventSubjectJavaFileHandle;
/**
* Java file handle for event listener file.
*/
private File eventListenerJavaFileHandle;
/**
* Java file handle for event file.
*/
private File eventJavaFileHandle;
/**
* Temporary file handle for rpc interface.
*/
private File rpcInterfaceTempFileHandle;
......@@ -94,6 +187,31 @@ public class TempJavaServiceFragmentFiles
private File managerJavaFileHandle;
/**
* Java file handle for event enum impl file.
*/
private File eventEnumTempFileHandle;
/**
* Java file handle for event method impl file.
*/
private File eventMethodTempFileHandle;
/**
* Java file handle for event subject attribute file.
*/
private File eventSubjectAttributeTempFileHandle;
/**
* Java file handle for event subject getter impl file.
*/
private File eventSubjectGetterTempFileHandle;
/**
* Java file handle for event subject setter impl file.
*/
private File eventSubjectSetterTempFileHandle;
/**
* Returns rpc method's java file handle.
*
* @return java file handle
......@@ -166,6 +284,60 @@ public class TempJavaServiceFragmentFiles
}
/**
* Returns event's java file handle.
*
* @return java file handle
*/
private File getEventJavaFileHandle() {
return eventJavaFileHandle;
}
/**
* Sets event's java file handle.
*
* @param eventJavaFileHandle file handle for event
*/
private void setEventJavaFileHandle(File eventJavaFileHandle) {
this.eventJavaFileHandle = eventJavaFileHandle;
}
/**
* Returns event listeners's java file handle.
*
* @return java file handle
*/
private File getEventListenerJavaFileHandle() {
return eventListenerJavaFileHandle;
}
/**
* Sets event's java file handle.
*
* @param eventListenerJavaFileHandle file handle for event
*/
private void setEventListenerJavaFileHandle(File eventListenerJavaFileHandle) {
this.eventListenerJavaFileHandle = eventListenerJavaFileHandle;
}
/**
* Returns event subject's java file handle.
*
* @return java file handle
*/
private File getEventSubjectJavaFileHandle() {
return eventSubjectJavaFileHandle;
}
/**
* Sets event's subject java file handle.
*
* @param eventSubjectJavaFileHandle file handle for event's subject
*/
private void setEventSubjectJavaFileHandle(File eventSubjectJavaFileHandle) {
this.eventSubjectJavaFileHandle = eventSubjectJavaFileHandle;
}
/**
* Creates an instance of temporary java code fragment.
*
* @param javaFileInfo generated file information
......@@ -176,11 +348,22 @@ public class TempJavaServiceFragmentFiles
super(javaFileInfo);
addGeneratedTempFile(RPC_INTERFACE_MASK);
addGeneratedTempFile(RPC_IMPL_MASK);
addGeneratedTempFile(EVENT_ENUM_MASK);
addGeneratedTempFile(EVENT_METHOD_MASK);
addGeneratedTempFile(EVENT_SUBJECT_ATTRIBUTE_MASK);
addGeneratedTempFile(EVENT_SUBJECT_GETTER_MASK);
addGeneratedTempFile(EVENT_SUBJECT_SETTER_MASK);
setRpcInterfaceTempFileHandle(getTemporaryFileHandle(RPC_INTERFACE_FILE_NAME));
setRpcImplTempFileHandle(getTemporaryFileHandle(RPC_IMPL_FILE_NAME));
setEventEnumTempFileHandle(getTemporaryFileHandle(EVENT_ENUM_FILE_NAME));
setEventMethodTempFileHandle(getTemporaryFileHandle(EVENT_METHOD_FILE_NAME));
setEventSubjectAttributeTempFileHandle(getTemporaryFileHandle(EVENT_SUBJECT_ATTRIBUTE_FILE_NAME));
setEventSubjectGetterTempFileHandle(getTemporaryFileHandle(EVENT_SUBJECT_GETTER_FILE_NAME));
setEventSubjectSetterTempFileHandle(getTemporaryFileHandle(EVENT_SUBJECT_SETTER_FILE_NAME));
}
/**
......@@ -199,13 +382,14 @@ public class TempJavaServiceFragmentFiles
createPackage(curNode);
boolean isNotification = false;
YangNode tempNode = curNode.getChild();
while (tempNode != null) {
if (tempNode instanceof YangJavaNotification) {
if (curNode instanceof YangJavaModule) {
if (!((YangJavaModule) curNode).getNotificationNodes().isEmpty()) {
isNotification = true;
}
} else if (curNode instanceof YangJavaSubModule) {
if (!((YangJavaSubModule) curNode).getNotificationNodes().isEmpty()) {
isNotification = true;
break;
}
tempNode = tempNode.getNextSibling();
}
if (isNotification) {
......@@ -221,6 +405,7 @@ public class TempJavaServiceFragmentFiles
addListnersImport(curNode, imports, false, LISTENER_SERVICE);
addListnersImport(curNode, imports, true, LISTENER_REG);
}
addAnnotationsImports(imports, true);
/**
* Create builder class file.
*/
......@@ -231,6 +416,14 @@ public class TempJavaServiceFragmentFiles
if (isNotification) {
addListnersImport(curNode, imports, false, LISTENER_REG);
}
addAnnotationsImports(imports, false);
if (isNotification) {
generateEventJavaFile(GENERATE_EVENT_CLASS, curNode);
generateEventListenerJavaFile(GENERATE_EVENT_LISTENER_INTERFACE, curNode);
generateEventSubjectJavaFile(GENERATE_EVENT_SUBJECT_CLASS, curNode);
}
/**
* Close all the file handles.
*/
......@@ -243,22 +436,115 @@ public class TempJavaServiceFragmentFiles
* @param javaAttributeInfoOfInput rpc's input node attribute info
* @param javaAttributeInfoOfOutput rpc's output node attribute info
* @param rpcName name of the rpc function
* @param pluginConfig plugin configurations
* @throws IOException IO operation fail
*/
private void addRpcString(JavaAttributeInfo javaAttributeInfoOfInput,
JavaAttributeInfo javaAttributeInfoOfOutput,
JavaAttributeInfo javaAttributeInfoOfOutput, YangPluginConfig pluginConfig,
String rpcName) throws IOException {
String rpcInput = EMPTY_STRING;
String rpcOutput = VOID;
String rpcInputJavaDoc = EMPTY_STRING;
if (javaAttributeInfoOfInput != null) {
rpcInput = getCapitalCase(javaAttributeInfoOfInput.getAttributeName());
}
if (javaAttributeInfoOfOutput != null) {
rpcOutput = getCapitalCase(javaAttributeInfoOfOutput.getAttributeName());
}
appendToFile(getRpcInterfaceTempFileHandle(), generateJavaDocForRpc(rpcName, RPC_INPUT_VAR_NAME, rpcOutput)
+ getRpcServiceMethod(rpcName, rpcInput, rpcOutput) + NEW_LINE);
appendToFile(getRpcImplTempFileHandle(), getRpcManagerMethod(rpcName, rpcInput, rpcOutput) + NEW_LINE);
if (!rpcInput.equals(EMPTY_STRING)) {
rpcInputJavaDoc = RPC_INPUT_VAR_NAME;
}
appendToFile(getRpcInterfaceTempFileHandle(),
generateJavaDocForRpc(rpcName, rpcInputJavaDoc, rpcOutput, pluginConfig)
+ getRpcServiceMethod(rpcName, rpcInput, rpcOutput, pluginConfig) + NEW_LINE);
appendToFile(getRpcImplTempFileHandle(),
getRpcManagerMethod(rpcName, rpcInput, rpcOutput, pluginConfig) + NEW_LINE);
}
/**
* Adds rpc string information to applicable temp file.
*
* @param javaAttributeInfoOfInput rpc's input node attribute info
* @param javaAttributeInfoOfOutput rpc's output node attribute info
* @param rpcName name of the rpc function
* @param pluginConfig plugin configurations
* @param isInputLeafHolder if input node is leaf holder
* @param isOutputLeafHolder if output node is leaf holder
* @param isInputSingleChildHolder if input node is single child holder
* @param isOutputSingleChildHolder if input node is single child holder
* @throws IOException IO operation fail
*/
public void addRpcString(JavaAttributeInfo javaAttributeInfoOfInput,
JavaAttributeInfo javaAttributeInfoOfOutput, YangPluginConfig pluginConfig,
String rpcName, boolean isInputLeafHolder, boolean isOutputLeafHolder,
boolean isInputSingleChildHolder, boolean isOutputSingleChildHolder) throws IOException {
String rpcInput = EMPTY_STRING;
String rpcOutput = VOID;
String rpcInputJavaDoc = EMPTY_STRING;
if (javaAttributeInfoOfInput != null) {
rpcInput = getInputOutputNames(javaAttributeInfoOfInput, isInputLeafHolder, isInputSingleChildHolder,
pluginConfig);
}
if (javaAttributeInfoOfOutput != null) {
rpcOutput =
getInputOutputNames(javaAttributeInfoOfOutput, isOutputLeafHolder, isOutputSingleChildHolder,
pluginConfig);
}
if (!rpcInput.equals(EMPTY_STRING)) {
rpcInputJavaDoc = RPC_INPUT_VAR_NAME;
}
appendToFile(getRpcInterfaceTempFileHandle(),
generateJavaDocForRpc(rpcName, rpcInputJavaDoc, rpcOutput, pluginConfig)
+ getRpcServiceMethod(rpcName, rpcInput, rpcOutput, pluginConfig) + NEW_LINE);
appendToFile(getRpcImplTempFileHandle(),
getRpcManagerMethod(rpcName, rpcInput, rpcOutput, pluginConfig) + NEW_LINE);
}
/**
* Returns names for input and output.
*
* @param attr attribute info
* @param isLeafHolder if leaf holder
* @param isSinglechildHolder if single child holder
* @param pluginConfig plugin configurations
* @return names for input and output
*/
private String getInputOutputNames(JavaAttributeInfo attr, boolean isLeafHolder, boolean isSinglechildHolder,
YangPluginConfig pluginConfig) {
if (!attr.isListAttr()) {
if (!isLeafHolder || isSinglechildHolder) {
String attrName = "";
if (!attr.isQualifiedName()) {
attrName = getCapitalCase(attr.getAttributeName());
} else {
attrName = attr.getImportInfo().getPkgInfo() + "." + getCapitalCase(attr.getAttributeName());
}
return attrName;
} else {
String rpcInput = getJavaImportClass(attr.getAttributeType(), false,
pluginConfig.getConflictResolver());
if (rpcInput == null) {
rpcInput = getJavaDataType(attr.getAttributeType());
}
return rpcInput;
}
} else {
if (!isLeafHolder || isSinglechildHolder) {
String attrName = "";
if (!attr.isQualifiedName()) {
attrName = getCapitalCase(attr.getAttributeName());
} else {
attrName = attr.getImportInfo().getPkgInfo() + "." + getCapitalCase(attr.getAttributeName());
}
return getListAttribute(attrName);
} else {
return getListAttribute(getJavaImportClass(attr.getAttributeType(), true,
pluginConfig.getConflictResolver()));
}
}
}
/**
......@@ -266,14 +552,105 @@ public class TempJavaServiceFragmentFiles
*
* @param javaAttributeInfoOfInput rpc's input node attribute info
* @param javaAttributeInfoOfOutput rpc's output node attribute info
* @param pluginConfig plugin configurations
* @param rpcName name of the rpc function
* @param isInputLeafHolder if input node is leaf holder
* @param isOutputLeafHolder if output node is leaf holder
* @param isInputSingleChildHolder if input node is single child holder
* @param isOutputSingleChildHolder if input node is single child holder
* @throws IOException IO operation fail
*/
public void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo javaAttributeInfoOfInput,
JavaAttributeInfo javaAttributeInfoOfOutput,
String rpcName)
JavaAttributeInfo javaAttributeInfoOfOutput, YangPluginConfig pluginConfig,
String rpcName, boolean isInputLeafHolder, boolean isOutputLeafHolder,
boolean isInputSingleChildHolder, boolean isOutputSingleChildHolder)
throws IOException {
addRpcString(javaAttributeInfoOfInput, javaAttributeInfoOfOutput, rpcName);
addRpcString(javaAttributeInfoOfInput, javaAttributeInfoOfOutput, pluginConfig, rpcName, isInputLeafHolder,
isOutputLeafHolder, isInputSingleChildHolder, isOutputSingleChildHolder);
}
/**
* Constructs java code exit.
*
* @param fileType generated file type
* @param curNode current YANG node
* @throws IOException when fails to generate java files
*/
public void generateEventJavaFile(int fileType, YangNode curNode)
throws IOException {
List<String> imports = new ArrayList<>();
imports.add(getJavaImportData().getAbstractEventsImport());
String curNodeInfo =
getCapitalCase(((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName());
String nodeName = curNodeInfo + EVENT_STRING;
addEnumMethod(nodeName, curNodeInfo + EVENT_SUBJECT_NAME_SUFFIX);
/**
* Creates event interface file.
*/
setEventJavaFileHandle(getJavaFileHandle(curNode, curNodeInfo + EVENT_FILE_NAME_SUFFIX));
generateEventFile(getEventJavaFileHandle(), curNode, imports);
/**
* Close all the file handles.
*/
freeTemporaryResources(false);
}
/**
* Constructs java code exit.
*
* @param fileType generated file type
* @param curNode current YANG node
* @throws IOException when fails to generate java files
*/
public void generateEventListenerJavaFile(int fileType, YangNode curNode)
throws IOException {
List<String> imports = new ArrayList<>();
imports.add(getJavaImportData().getEventListenerImport());
String curNodeInfo = getCapitalCase(((JavaFileInfoContainer) curNode)
.getJavaFileInfo().getJavaName());
/**
* Creates event listener interface file.
*/
setEventListenerJavaFileHandle(
getJavaFileHandle(curNode, curNodeInfo + EVENT_LISTENER_FILE_NAME_SUFFIX));
generateEventListenerFile(getEventListenerJavaFileHandle(), curNode, imports);
/**
* Close all the file handles.
*/
freeTemporaryResources(false);
}
/**
* Constructs java code exit.
*
* @param fileType generated file type
* @param curNode current YANG node
* @throws IOException when fails to generate java files
*/
public void generateEventSubjectJavaFile(int fileType, YangNode curNode)
throws IOException {
String curNodeInfo = getCapitalCase(((JavaFileInfoContainer) curNode)
.getJavaFileInfo().getJavaName());
/**
* Creates event interface file.
*/
setEventSubjectJavaFileHandle(getJavaFileHandle(curNode, curNodeInfo +
EVENT_SUBJECT_NAME_SUFFIX));
generateEventSubjectFile(getEventSubjectJavaFileHandle(), curNode);
/**
* Close all the file handles.
*/
freeTemporaryResources(false);
}
/**
......@@ -290,6 +667,18 @@ public class TempJavaServiceFragmentFiles
boolean isError = isErrorOccurred;
closeFile(getServiceInterfaceJavaFileHandle(), isError);
closeFile(getManagerJavaFileHandle(), isError);
if (getEventJavaFileHandle() != null) {
closeFile(getEventJavaFileHandle(), isError);
}
if (getEventListenerJavaFileHandle() != null) {
closeFile(getEventListenerJavaFileHandle(), isError);
}
if (getEventSubjectJavaFileHandle() != null) {
closeFile(getEventSubjectJavaFileHandle(), isError);
}
closeFile(getRpcInterfaceTempFileHandle(), true);
closeFile(getRpcImplTempFileHandle(), true);
closeFile(getGetterInterfaceTempFileHandle(), true);
......@@ -299,4 +688,207 @@ public class TempJavaServiceFragmentFiles
super.freeTemporaryResources(isErrorOccurred);
}
/**
* Returns event enum temp file.
*
* @return event enum temp file
*/
public File getEventEnumTempFileHandle() {
return eventEnumTempFileHandle;
}
/**
* Sets event enum temp file.
*
* @param eventEnumTempFileHandle event enum temp file
*/
public void setEventEnumTempFileHandle(File eventEnumTempFileHandle) {
this.eventEnumTempFileHandle = eventEnumTempFileHandle;
}
/**
* Returns event method temp file.
*
* @return event method temp file
*/
public File getEventMethodTempFileHandle() {
return eventMethodTempFileHandle;
}
/**
* Sets event method temp file.
*
* @param eventMethodTempFileHandle event method temp file
*/
public void setEventMethodTempFileHandle(File eventMethodTempFileHandle) {
this.eventMethodTempFileHandle = eventMethodTempFileHandle;
}
/**
* Returns event subject attribute temp file.
*
* @return event subject attribute temp file
*/
public File getEventSubjectAttributeTempFileHandle() {
return eventSubjectAttributeTempFileHandle;
}
/**
* Sets event subject attribute temp file.
*
* @param eventSubjectAttributeTempFileHandle event subject attribute temp file
*/
public void setEventSubjectAttributeTempFileHandle(File eventSubjectAttributeTempFileHandle) {
this.eventSubjectAttributeTempFileHandle = eventSubjectAttributeTempFileHandle;
}
/**
* Returns event subject getter temp file.
*
* @return event subject getter temp file
*/
public File getEventSubjectGetterTempFileHandle() {
return eventSubjectGetterTempFileHandle;
}
/**
* Sets event subject getter temp file.
*
* @param eventSubjectGetterTempFileHandle event subject getter temp file
*/
public void setEventSubjectGetterTempFileHandle(File eventSubjectGetterTempFileHandle) {
this.eventSubjectGetterTempFileHandle = eventSubjectGetterTempFileHandle;
}
/**
* Returns event subject setter temp file.
*
* @return event subject setter temp file
*/
public File getEventSubjectSetterTempFileHandle() {
return eventSubjectSetterTempFileHandle;
}
/**
* Sets event subject setter temp file.
*
* @param eventSubjectSetterTempFileHandle event subject setter temp file
*/
public void setEventSubjectSetterTempFileHandle(File eventSubjectSetterTempFileHandle) {
this.eventSubjectSetterTempFileHandle = eventSubjectSetterTempFileHandle;
}
/**
* Adds java snippet for events to event subject file.
*
* @param curNode current node
* @param pluginConfig plugin configurations
* @throws IOException when fails to do IO operations
*/
public void addJavaSnippetOfEvent(YangNode curNode, YangPluginConfig pluginConfig) throws IOException {
String currentInfo = getCapitalCase(getCamelCase(((YangNotification) curNode).getName(),
pluginConfig.getConflictResolver()));
String notificationName = ((YangNotification) curNode).getName();
JavaQualifiedTypeInfo qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(curNode.getParent(),
getCapitalCase(currentInfo));
JavaAttributeInfo javaAttributeInfo =
getAttributeInfoForTheData(qualifiedTypeInfo, getSmallCase(currentInfo),
null, false, false);
/*Adds java info for event in respective temp files.*/
addEventEnum(notificationName, pluginConfig);
addEventSubjectAttribute(javaAttributeInfo, pluginConfig);
addEventSubjectGetter(javaAttributeInfo, pluginConfig);
addEventSubjectSetter(javaAttributeInfo, pluginConfig, currentInfo);
}
/*Adds event to enum temp file.*/
private void addEventEnum(String notificationName, YangPluginConfig pluginConfig) throws IOException {
appendToFile(getEventEnumTempFileHandle(),
getJavaDoc(ENUM_ATTRIBUTE, notificationName, false, pluginConfig) + FOUR_SPACE_INDENTATION
+ getEnumJavaAttribute(notificationName).toUpperCase() + COMMA + NEW_LINE);
}
/*Adds event method in event class*/
private void addEnumMethod(String eventClassname, String className) throws IOException {
appendToFile(getEventMethodTempFileHandle(), getEventFileContents(eventClassname, className));
}
/*Adds event method contents to event file.*/
private static String getEventFileContents(String eventClassname, String classname) {
return "\n" +
" /**\n" +
" * Creates " + classname + " event with type and subject.\n" +
" *\n" +
" * @param type event type\n" +
" * @param subject subject " + classname + "\n" +
" */\n" +
" public " + eventClassname + "(Type type, " + getCapitalCase(classname) + " subject) {\n" +
" super(type, subject);\n" +
" }\n" +
"\n" +
" /**\n" +
" * Creates " + classname + " event with type, subject and time.\n" +
" *\n" +
" * @param type event type\n" +
" * @param subject subject " + classname + "\n" +
" * @param time time of event\n" +
" */\n" +
" public " + eventClassname + "(Type type, " + getCapitalCase(classname)
+ " subject, long time) {\n" +
" super(type, subject, time);\n" +
" }\n" +
"\n";
}
/*Adds events to event subject file.*/
private void addEventSubjectAttribute(JavaAttributeInfo attr, YangPluginConfig pluginConfig)
throws IOException {
appendToFile(getEventSubjectAttributeTempFileHandle(),
FOUR_SPACE_INDENTATION + parseAttribute(attr, pluginConfig));
}
/*Adds getter method for event in event subject class.*/
private void addEventSubjectGetter(JavaAttributeInfo attr, YangPluginConfig pluginConfig) throws IOException {
appendToFile(getEventSubjectGetterTempFileHandle(),
getJavaDoc(GETTER_METHOD, getCapitalCase(attr.getAttributeName()), false, pluginConfig)
+ getGetterForClass(attr, GENERATE_EVENT_SUBJECT_CLASS) + NEW_LINE);
}
/*Adds setter method for event in event subject class.*/
private void addEventSubjectSetter(JavaAttributeInfo attr, YangPluginConfig pluginConfig, String className)
throws IOException {
appendToFile(getEventSubjectSetterTempFileHandle(),
getJavaDoc(MANAGER_SETTER_METHOD, getCapitalCase(attr.getAttributeName()), false, pluginConfig)
+ getSetterForClass(attr, className, GENERATE_EVENT_SUBJECT_CLASS) + NEW_LINE);
}
/**
* Returns a temporary file handle for the event's file type.
*
* @param fileName file name
* @return temporary file handle
* @throws IOException when fails to create new file handle
*/
private File getJavaFileHandle(YangNode curNode, String name)
throws IOException {
JavaFileInfo parentInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
return getFileObject(getDirPath(parentInfo), name, JAVA_FILE_EXTENSION,
parentInfo);
}
/**
* Returns the directory path.
*
* @return directory path
*/
private String getDirPath(JavaFileInfo parentInfo) {
return (parentInfo.getPackageFilePath() + SLASH + parentInfo.getJavaName()).toLowerCase();
}
}
......
......@@ -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 {
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 {
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;
}
}
......
......@@ -17,26 +17,36 @@
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import java.util.List;
import org.onosproject.yangutils.datamodel.RpcNotificationContainer;
import org.onosproject.yangutils.datamodel.YangInput;
import org.onosproject.yangutils.datamodel.YangLeaf;
import org.onosproject.yangutils.datamodel.YangLeafList;
import org.onosproject.yangutils.datamodel.YangLeavesHolder;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.datamodel.YangOutput;
import org.onosproject.yangutils.datamodel.YangRpc;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.exception.TranslatorException;
import org.onosproject.yangutils.translator.tojava.JavaAttributeInfo;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
import org.onosproject.yangutils.translator.tojava.TempJavaFragmentFiles;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
import static org.onosproject.yangutils.datamodel.YangNodeType.LIST_NODE;
import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getAttributeInfoForTheData;
import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getQualifiedTypeInfoOfCurNode;
import static org.onosproject.yangutils.translator.tojava.TempJavaFragmentFiles.resolveGroupingsQuailifiedInfo;
import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getJavaDataType;
import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getJavaImportClass;
import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getJavaImportPackage;
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.getParentNodeInGenCode;
import static org.onosproject.yangutils.translator.tojava.utils.YangJavaModelUtils.updatePackageInfo;
......@@ -58,6 +68,11 @@ public class YangJavaRpc
*/
private TempJavaCodeFragmentFiles tempJavaCodeFragmentFiles;
private boolean isInputLeafHolder;
private boolean isOutputLeafHolder;
private boolean isInputSingleChildHolder;
private boolean isOutputSingleChildHolder;
/**
* Creates an instance of YANG java rpc.
*/
......@@ -67,6 +82,40 @@ public class YangJavaRpc
}
/**
* Returns the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new TranslatorException("missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Sets the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
return tempJavaCodeFragmentFiles;
}
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempJavaCodeFragmentFiles = fileHandle;
}
/**
* Prepares the information for java code generation corresponding to YANG
* RPC info.
*
......@@ -83,6 +132,12 @@ public class YangJavaRpc
// Add package information for rpc and create corresponding folder.
try {
updatePackageInfo(this, yangPlugin);
if (this.getChild() != null) {
processNodeEntry(this.getChild(), yangPlugin);
if (this.getChild().getNextSibling() != null) {
processNodeEntry(this.getChild().getNextSibling(), yangPlugin);
}
}
} catch (IOException e) {
throw new TranslatorException("Failed to prepare generate code entry for RPC node " + this.getName());
}
......@@ -116,9 +171,10 @@ public class YangJavaRpc
YangNode yangNode = this.getChild();
while (yangNode != null) {
if (yangNode instanceof YangInput) {
javaAttributeInfoOfInput = getChildNodeAsAttributeInParentService(yangNode, this);
javaAttributeInfoOfInput = processNodeExit(yangNode, getJavaFileInfo().getPluginConfig());
} else if (yangNode instanceof YangOutput) {
javaAttributeInfoOfOutput = getChildNodeAsAttributeInParentService(yangNode, this);
javaAttributeInfoOfOutput = processNodeExit(yangNode, getJavaFileInfo().getPluginConfig());
} else {
// TODO throw exception
}
......@@ -135,7 +191,9 @@ public class YangJavaRpc
try {
((TempJavaCodeFragmentFilesContainer) parent).getTempJavaCodeFragmentFiles().getServiceTempFiles()
.addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfoOfInput, javaAttributeInfoOfOutput,
((YangNode) this).getName());
((JavaFileInfoContainer) parent).getJavaFileInfo().getPluginConfig(),
((YangNode) this).getName(), isInputLeafHolder(), isOutputLeafHolder(),
isInputSingleChildHolder(), isOutputSingleChildHolder());
} catch (IOException e) {
throw new TranslatorException("Failed to generate code for RPC node " + this.getName());
}
......@@ -152,7 +210,7 @@ public class YangJavaRpc
* @return AttributeInfo attribute details required to add in temporary
* files
*/
public static JavaAttributeInfo getChildNodeAsAttributeInParentService(
public JavaAttributeInfo getChildNodeAsAttributeInParentService(
YangNode childNode, YangNode currentNode) {
YangNode parentNode = getParentNodeInGenCode(currentNode);
......@@ -176,44 +234,368 @@ public class YangJavaRpc
if (tempJavaFragmentFiles == null) {
throw new TranslatorException("Parent node does not have service file info");
}
JavaImportData parentImportData = tempJavaFragmentFiles.getJavaImportData();
boolean isQualified = parentImportData.addImportInfo(qualifiedTypeInfo);
boolean isQualified = addImportToService(qualifiedTypeInfo);
return getAttributeInfoForTheData(qualifiedTypeInfo, childNodeName, null, isQualified, false);
}
/**
* Returns the generated java file information.
* Process input/output nodes.
*
* @return generated java file information
* @param node YANG node
* @param yangPluginConfig plugin configurations
*/
@Override
public JavaFileInfo getJavaFileInfo() {
private void processNodeEntry(YangNode node, YangPluginConfig yangPluginConfig) {
YangLeavesHolder holder = (YangLeavesHolder) node;
if (node.getChild() == null) {
if (holder.getListOfLeaf() != null && holder.getListOfLeafList().isEmpty()
&& holder.getListOfLeaf().size() == 1) {
setCodeGenFlagForNode(node, false);
} else if (holder.getListOfLeaf().isEmpty() && holder.getListOfLeafList() != null
&& holder.getListOfLeafList().size() == 1) {
setCodeGenFlagForNode(node, false);
} else {
setCodeGenFlagForNode(node, true);
}
} else if (node.getChild() != null && holder.getListOfLeaf().isEmpty()
&& holder.getListOfLeafList().isEmpty()) {
if (getNumberOfChildNodes(node) == 1) {
setCodeGenFlagForNode(node, false);
} else {
setCodeGenFlagForNode(node, true);
}
} else {
setCodeGenFlagForNode(node, true);
}
}
if (javaFileInfo == null) {
throw new TranslatorException("missing java info in java datamodel node");
/**
* Process input/output nodes.
*
* @param node YANG node
* @param yangPluginConfig plugin configurations
* @return java attribute info
*/
private JavaAttributeInfo processNodeExit(YangNode node, YangPluginConfig yangPluginConfig) {
YangLeavesHolder holder = (YangLeavesHolder) node;
if (node.getChild() == null) {
if (holder.getListOfLeaf() != null && holder.getListOfLeafList().isEmpty()
&& holder.getListOfLeaf().size() == 1) {
return processNodeWhenOnlyOneLeafIsPresent(node, yangPluginConfig);
} else if (holder.getListOfLeaf().isEmpty() && holder.getListOfLeafList() != null
&& holder.getListOfLeafList().size() == 1) {
return processNodeWhenOnlyOneLeafListIsPresent(node, yangPluginConfig);
} else {
return processNodeWhenMultipleContaintsArePresent(node);
}
} else if (node.getChild() != null && holder.getListOfLeaf().isEmpty()
&& holder.getListOfLeafList().isEmpty()) {
if (getNumberOfChildNodes(node) == 1) {
return processNodeWhenOnlyOneChildNodeIsPresent(node, yangPluginConfig);
} else {
return processNodeWhenMultipleContaintsArePresent(node);
}
} else {
return processNodeWhenMultipleContaintsArePresent(node);
}
return javaFileInfo;
}
/**
* Sets the java file info object.
* Process input/output node when one leaf is present.
*
* @param javaInfo java file info object
* @param node input/output node
* @param yangPluginConfig plugin configurations
* @return java attribute for node
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
private JavaAttributeInfo processNodeWhenOnlyOneLeafIsPresent(YangNode node,
YangPluginConfig yangPluginConfig) {
YangLeavesHolder holder = (YangLeavesHolder) node;
List<YangLeaf> listOfLeaves = holder.getListOfLeaf();
for (YangLeaf leaf : listOfLeaves) {
if (!(leaf instanceof JavaLeafInfoContainer)) {
throw new TranslatorException("Leaf does not have java information");
}
JavaLeafInfoContainer javaLeaf = (JavaLeafInfoContainer) leaf;
javaLeaf.setConflictResolveConfig(yangPluginConfig.getConflictResolver());
javaLeaf.updateJavaQualifiedInfo();
JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(
javaLeaf.getJavaQualifiedInfo(),
javaLeaf.getJavaName(yangPluginConfig.getConflictResolver()),
javaLeaf.getDataType(),
addTypeImport(javaLeaf.getDataType(), false, yangPluginConfig), false);
setLeafHolderFlag(node, true);
return javaAttributeInfo;
}
return null;
}
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
return tempJavaCodeFragmentFiles;
/**
* Process input/output node when one leaf list is present.
*
* @param node input/output node
* @param yangPluginConfig plugin configurations
* @return java attribute for node
*/
private JavaAttributeInfo processNodeWhenOnlyOneLeafListIsPresent(YangNode node,
YangPluginConfig yangPluginConfig) {
YangLeavesHolder holder = (YangLeavesHolder) node;
List<YangLeafList> listOfLeafList = holder.getListOfLeafList();
for (YangLeafList leafList : listOfLeafList) {
if (!(leafList instanceof JavaLeafInfoContainer)) {
throw new TranslatorException("Leaf-list does not have java information");
}
JavaLeafInfoContainer javaLeaf = (JavaLeafInfoContainer) leafList;
javaLeaf.setConflictResolveConfig(yangPluginConfig.getConflictResolver());
javaLeaf.updateJavaQualifiedInfo();
((TempJavaCodeFragmentFilesContainer) this.getParent()).getTempJavaCodeFragmentFiles()
.getServiceTempFiles().getJavaImportData().setIfListImported(true);
JavaAttributeInfo javaAttributeInfo = getAttributeInfoForTheData(
javaLeaf.getJavaQualifiedInfo(),
javaLeaf.getJavaName(yangPluginConfig.getConflictResolver()),
javaLeaf.getDataType(),
addTypeImport(javaLeaf.getDataType(), true, yangPluginConfig),
true);
setLeafHolderFlag(node, true);
return javaAttributeInfo;
}
return null;
}
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempJavaCodeFragmentFiles = fileHandle;
/**
* Process input/output node when one child node is present.
*
* @param node input/output node
* @param yangPluginConfig plugin configurations
* @return java attribute for node
*/
private JavaAttributeInfo processNodeWhenOnlyOneChildNodeIsPresent(YangNode node,
YangPluginConfig yangPluginConfig) {
JavaFileInfo rpcInfo = getJavaFileInfo();
String clsInfo = "";
JavaQualifiedTypeInfo childInfo = new JavaQualifiedTypeInfo();
if (node.getChild() instanceof YangJavaUses) {
childInfo = resolveGroupingsQuailifiedInfo(((YangJavaUses) node.getChild()).getRefGroup(),
yangPluginConfig);
clsInfo = getCapitalCase(getCamelCase(((YangJavaUses) node.getChild()).getRefGroup().getName(),
yangPluginConfig.getConflictResolver()));
} else {
String pkg = (rpcInfo.getPackage() + "." + rpcInfo.getJavaName() + "."
+ getCamelCase(node.getName(), yangPluginConfig.getConflictResolver())).toLowerCase();
clsInfo = getCapitalCase(
getCamelCase(node.getChild().getName(), yangPluginConfig.getConflictResolver()));
childInfo.setPkgInfo(pkg);
childInfo.setClassInfo(clsInfo);
}
boolean isList = false;
if (node.getChild().getNodeType().equals(LIST_NODE)) {
isList = true;
}
boolean isQualified = addImportToService(childInfo);
JavaAttributeInfo javaAttributeInfo =
getAttributeInfoForTheData(childInfo, clsInfo, null, isQualified, isList);
setLeafHolderFlag(node, false);
setSingleChildHolderFlag(node, true);
return javaAttributeInfo;
}
/**
* Process input/output node when multiple leaf and child nodes are present.
*
* @param node input/output node
* @return java attribute for node
*/
private JavaAttributeInfo processNodeWhenMultipleContaintsArePresent(YangNode node) {
setLeafHolderFlag(node, false);
setSingleChildHolderFlag(node, false);
return getChildNodeAsAttributeInParentService(node, this);
}
/**
* Adds type import to the RPC import list.
*
* @param type YANG type
* @param isList is list attribute
* @param pluginConfig plugin configurations
* @return type import to the RPC import list
*/
private boolean addTypeImport(YangType<?> type, boolean isList, YangPluginConfig pluginConfig) {
String classInfo = getJavaImportClass(type, isList, pluginConfig.getConflictResolver());
if (classInfo == null) {
classInfo = getJavaDataType(type);
return false;
} else {
classInfo = getJavaImportClass(type, isList, pluginConfig.getConflictResolver());
String pkgInfo = getJavaImportPackage(type, isList, pluginConfig.getConflictResolver());
JavaQualifiedTypeInfo importInfo = new JavaQualifiedTypeInfo();
importInfo.setPkgInfo(pkgInfo);
importInfo.setClassInfo(classInfo);
if (!((JavaFileInfoContainer) this.getParent()).getJavaFileInfo().getJavaName().equals(classInfo)) {
return addImportToService(importInfo);
} else {
return true;
}
}
}
/**
* Adds to service class import list.
*
* @param importInfo import info
* @return true or false
*/
private boolean addImportToService(JavaQualifiedTypeInfo importInfo) {
if (((TempJavaCodeFragmentFilesContainer) this.getParent()).getTempJavaCodeFragmentFiles()
.getServiceTempFiles().getJavaImportData().addImportInfo(importInfo)) {
return !((TempJavaCodeFragmentFilesContainer) this.getParent()).getTempJavaCodeFragmentFiles()
.getServiceTempFiles().getJavaImportData().getImportSet().contains(importInfo);
} else {
return true;
}
}
/**
* Sets leaf holder flag for input/output.
*
* @param node input/output node
* @param flag true or false
*/
private void setLeafHolderFlag(YangNode node, boolean flag) {
if (node instanceof YangJavaInput) {
setInputLeafHolder(flag);
} else {
setOutputLeafHolder(flag);
}
}
/**
* Sets sing child holder flag for input/output.
*
* @param node input/output node
* @param flag true or false
*/
private void setSingleChildHolderFlag(YangNode node, boolean flag) {
if (node instanceof YangJavaInput) {
setInputSingleChildHolder(flag);
} else {
setOutputSingleChildHolder(flag);
}
}
/**
* Sets code generator flag for input and output.
*
* @param node YANG node
* @param flag cod generator flag
*/
private void setCodeGenFlagForNode(YangNode node, boolean flag) {
if (node instanceof YangJavaInput) {
((YangJavaInput) node).setCodeGenFlag(flag);
} else {
((YangJavaOutput) node).setCodeGenFlag(flag);
}
}
/**
* Counts the number of child nodes of a YANG node.
*
* @param node YANG node
* @return count of children
*/
private int getNumberOfChildNodes(YangNode node) {
YangNode tempNode = node.getChild();
int count = 0;
if (tempNode != null) {
count = 1;
}
while (tempNode != null) {
tempNode = tempNode.getNextSibling();
if (tempNode != null) {
count++;
}
}
return count;
}
/**
* Returns true if input is a leaf holder.
*
* @return true if input is a leaf holder
*/
public boolean isInputLeafHolder() {
return isInputLeafHolder;
}
/**
* Sets true if input is a leaf holder.
*
* @param isInputLeafHolder true if input is a leaf holder
*/
public void setInputLeafHolder(boolean isInputLeafHolder) {
this.isInputLeafHolder = isInputLeafHolder;
}
/**
* Returns true if output is a leaf holder.
*
* @return true if output is a leaf holder
*/
public boolean isOutputLeafHolder() {
return isOutputLeafHolder;
}
/**
* Sets true if output is a leaf holder.
*
* @param isOutputLeafHolder true if output is a leaf holder
*/
public void setOutputLeafHolder(boolean isOutputLeafHolder) {
this.isOutputLeafHolder = isOutputLeafHolder;
}
/**
* Returns true if input is single child holder.
*
* @return true if input is single child holder
*/
public boolean isInputSingleChildHolder() {
return isInputSingleChildHolder;
}
/**
* Sets true if input is single child holder.
*
* @param isInputSingleChildHolder true if input is single child holder
*/
public void setInputSingleChildHolder(boolean isInputSingleChildHolder) {
this.isInputSingleChildHolder = isInputSingleChildHolder;
}
/**
* Returns true if output is single child holder.
*
* @return true if output is single child holder
*/
public boolean isOutputSingleChildHolder() {
return isOutputSingleChildHolder;
}
/**
* Sets true if output is single child holder.
*
* @param isOutputSingleChildHolder true if output is single child holder
*/
public void setOutputSingleChildHolder(boolean isOutputSingleChildHolder) {
this.isOutputSingleChildHolder = isOutputSingleChildHolder;
}
}
......
......@@ -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.
}
}
......
......@@ -49,6 +49,7 @@ import static org.onosproject.yangutils.utils.UtilConstants.JAVA_MATH;
import static org.onosproject.yangutils.utils.UtilConstants.LONG;
import static org.onosproject.yangutils.utils.UtilConstants.LONG_WRAPPER;
import static org.onosproject.yangutils.utils.UtilConstants.NEW;
import static org.onosproject.yangutils.utils.UtilConstants.PARSE_BOOLEAN;
import static org.onosproject.yangutils.utils.UtilConstants.PARSE_BYTE;
import static org.onosproject.yangutils.utils.UtilConstants.PARSE_INT;
import static org.onosproject.yangutils.utils.UtilConstants.PARSE_LONG;
......@@ -58,6 +59,10 @@ import static org.onosproject.yangutils.utils.UtilConstants.SHORT;
import static org.onosproject.yangutils.utils.UtilConstants.SHORT_WRAPPER;
import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
import static org.onosproject.yangutils.utils.UtilConstants.STRING_DATA_TYPE;
import static org.onosproject.yangutils.utils.UtilConstants.YANG_BINARY_CLASS;
import static org.onosproject.yangutils.utils.UtilConstants.YANG_BITS_CLASS;
import static org.onosproject.yangutils.utils.UtilConstants.YANG_DECIMAL64_CLASS;
import static org.onosproject.yangutils.utils.UtilConstants.YANG_TYPES_PKG;
/**
* Represents java data types info corresponding to YANG type.
......@@ -97,8 +102,10 @@ public final class AttributesJavaDataType {
return LONG;
case UINT64:
return BIG_INTEGER;
case BINARY:
return YANG_BINARY_CLASS;
case DECIMAL64:
//TODO: DECIMAL64.
return YANG_DECIMAL64_CLASS;
case STRING:
return STRING_DATA_TYPE;
case BOOLEAN:
......@@ -136,18 +143,16 @@ public final class AttributesJavaDataType {
return LONG_WRAPPER + PERIOD + PARSE_LONG;
case UINT64:
return NEW + SPACE + BIG_INTEGER;
case DECIMAL64:
//TODO: DECIMAL64.
case STRING:
return EMPTY_STRING;
case EMPTY:
case BOOLEAN:
return BOOLEAN_DATA_TYPE;
case ENUMERATION:
//TODO:ENUMERATION.
return BOOLEAN_WRAPPER + PERIOD + PARSE_BOOLEAN;
case DECIMAL64:
case BITS:
//TODO:BITS
case BINARY:
//TODO:BINARY
case UNION:
case ENUMERATION:
case DERIVED:
return targetDataType + PERIOD + FROM_STRING_METHOD_NAME;
default:
......@@ -160,9 +165,11 @@ public final class AttributesJavaDataType {
*
* @param yangType YANG type
* @param isListAttr if the attribute need to be a list
* @param pluginConfig plugin configurations
* @return java import class
*/
public static String getJavaImportClass(YangType<?> yangType, boolean isListAttr) {
public static String getJavaImportClass(YangType<?> yangType, boolean isListAttr,
YangToJavaNamingConflictUtil pluginConfig) {
YangDataTypes type = yangType.getDataType();
......@@ -185,21 +192,19 @@ public final class AttributesJavaDataType {
case UINT64:
return BIG_INTEGER;
case DECIMAL64:
//TODO: DECIMAL64.
break;
return YANG_DECIMAL64_CLASS;
case STRING:
return STRING_DATA_TYPE;
case BOOLEAN:
return BOOLEAN_WRAPPER;
case ENUMERATION:
return getCapitalCase(
getCamelCase(((YangJavaEnumeration) yangType.getDataTypeExtendedInfo()).getName(), null));
getCamelCase(((YangJavaEnumeration) yangType.getDataTypeExtendedInfo()).getName(),
pluginConfig));
case BITS:
//TODO:BITS
break;
return YANG_BITS_CLASS;
case BINARY:
//TODO:BINARY
break;
return YANG_BINARY_CLASS;
case LEAFREF:
//TODO:LEAFREF
break;
......@@ -210,11 +215,13 @@ public final class AttributesJavaDataType {
return BOOLEAN_WRAPPER;
case UNION:
return getCapitalCase(getCamelCase(((YangJavaUnion) yangType.getDataTypeExtendedInfo()).getName(),
null));
pluginConfig));
case INSTANCE_IDENTIFIER:
//TODO:INSTANCE_IDENTIFIER
break;
case DERIVED:
return getCapitalCase(getCamelCase(yangType.getDataTypeName(), null));
return getCapitalCase(
getCamelCase(yangType.getDataTypeName(), pluginConfig));
default:
throw new TranslatorException("given data type is not supported.");
}
......@@ -223,19 +230,17 @@ public final class AttributesJavaDataType {
case UINT64:
return BIG_INTEGER;
case DECIMAL64:
//TODO: DECIMAL64.
break;
return YANG_DECIMAL64_CLASS;
case STRING:
return STRING_DATA_TYPE;
case ENUMERATION:
return getCapitalCase(
getCamelCase(((YangJavaEnumeration) yangType.getDataTypeExtendedInfo()).getName(), null));
getCamelCase(((YangJavaEnumeration) yangType.getDataTypeExtendedInfo()).getName(),
pluginConfig));
case BITS:
//TODO:BITS
break;
return YANG_BITS_CLASS;
case BINARY:
//TODO:BINARY
break;
return YANG_BINARY_CLASS;
case LEAFREF:
//TODO:LEAFREF
break;
......@@ -243,16 +248,16 @@ public final class AttributesJavaDataType {
//TODO:IDENTITYREF
break;
case EMPTY:
//TODO:EMPTY
break;
return BOOLEAN_DATA_TYPE;
case UNION:
return getCapitalCase(getCamelCase(((YangJavaUnion) yangType.getDataTypeExtendedInfo()).getName(),
null));
pluginConfig));
case INSTANCE_IDENTIFIER:
//TODO:INSTANCE_IDENTIFIER
break;
case DERIVED:
return getCapitalCase(getCamelCase(yangType.getDataTypeName(), null));
return getCapitalCase(
getCamelCase(yangType.getDataTypeName(), pluginConfig));
default:
return null;
}
......@@ -265,10 +270,11 @@ public final class AttributesJavaDataType {
*
* @param yangType YANG type
* @param isListAttr if the attribute is of list type
* @param classInfo java import class info
* @param conflictResolver object of YANG to java naming conflict util
* @return java import package
*/
public static String getJavaImportPackage(YangType<?> yangType, boolean isListAttr, String classInfo) {
public static String getJavaImportPackage(YangType<?> yangType, boolean isListAttr,
YangToJavaNamingConflictUtil conflictResolver) {
YangDataTypes type = yangType.getDataType();
......@@ -283,36 +289,29 @@ public final class AttributesJavaDataType {
case UINT32:
case STRING:
case BOOLEAN:
case EMPTY:
return JAVA_LANG;
case UINT64:
return JAVA_MATH;
case DECIMAL64:
//TODO: DECIMAL64.
break;
case ENUMERATION:
return getEnumsPackage(yangType);
return getEnumsPackage(yangType, conflictResolver);
case DECIMAL64:
case BITS:
//TODO:BITS
break;
case BINARY:
//TODO:BINARY
break;
return YANG_TYPES_PKG;
case LEAFREF:
//TODO:LEAFREF
break;
case IDENTITYREF:
//TODO:IDENTITYREF
break;
case EMPTY:
//TODO:EMPTY
break;
case UNION:
return getUnionPackage(yangType);
return getUnionPackage(yangType, conflictResolver);
case INSTANCE_IDENTIFIER:
//TODO:INSTANCE_IDENTIFIER
break;
case DERIVED:
return getTypDefsPackage(yangType);
return getTypDefsPackage(yangType, conflictResolver);
default:
throw new TranslatorException("given data type is not supported.");
}
......@@ -320,19 +319,14 @@ public final class AttributesJavaDataType {
switch (type) {
case UINT64:
return JAVA_MATH;
case DECIMAL64:
//TODO: DECIMAL64
break;
case STRING:
return JAVA_LANG;
case ENUMERATION:
return getEnumsPackage(yangType);
return getEnumsPackage(yangType, conflictResolver);
case DECIMAL64:
case BITS:
//TODO:BITS
break;
case BINARY:
//TODO:BINARY
break;
return YANG_TYPES_PKG;
case LEAFREF:
//TODO:LEAFREF
break;
......@@ -340,15 +334,14 @@ public final class AttributesJavaDataType {
//TODO:IDENTITYREF
break;
case EMPTY:
//TODO:EMPTY
break;
return JAVA_LANG;
case UNION:
return getUnionPackage(yangType);
return getUnionPackage(yangType, conflictResolver);
case INSTANCE_IDENTIFIER:
//TODO:INSTANCE_IDENTIFIER
break;
case DERIVED:
return getTypDefsPackage(yangType);
return getTypDefsPackage(yangType, conflictResolver);
default:
return null;
}
......@@ -360,9 +353,10 @@ public final class AttributesJavaDataType {
* Returns java package for typedef node.
*
* @param type YANG type
* @param conflictResolver object of YANG to java naming conflict util
* @return java package for typedef node
*/
private static String getTypDefsPackage(YangType<?> type) {
private static String getTypDefsPackage(YangType<?> type, YangToJavaNamingConflictUtil conflictResolver) {
Object var = type.getDataTypeExtendedInfo();
if (!(var instanceof YangDerivedInfo)) {
throw new TranslatorException("type should have been derived.");
......@@ -374,7 +368,7 @@ public final class AttributesJavaDataType {
YangJavaTypeDef typedef = (YangJavaTypeDef) ((YangDerivedInfo<?>) var).getReferredTypeDef();
if (typedef.getJavaFileInfo().getPackage() == null) {
return getPackageFromParent(typedef.getParent());
return getPackageFromParent(typedef.getParent(), conflictResolver);
}
return typedef.getJavaFileInfo().getPackage();
}
......@@ -383,9 +377,10 @@ public final class AttributesJavaDataType {
* Returns java package for union node.
*
* @param type YANG type
* @param conflictResolver object of YANG to java naming conflict util
* @return java package for union node
*/
private static String getUnionPackage(YangType<?> type) {
private static String getUnionPackage(YangType<?> type, YangToJavaNamingConflictUtil conflictResolver) {
if (!(type.getDataTypeExtendedInfo() instanceof YangUnion)) {
throw new TranslatorException("type should have been union.");
......@@ -393,7 +388,7 @@ public final class AttributesJavaDataType {
YangJavaUnion union = (YangJavaUnion) type.getDataTypeExtendedInfo();
if (union.getJavaFileInfo().getPackage() == null) {
return getPackageFromParent(union.getParent());
return getPackageFromParent(union.getParent(), conflictResolver);
}
return union.getJavaFileInfo().getPackage();
}
......@@ -402,16 +397,17 @@ public final class AttributesJavaDataType {
* Returns YANG enumeration's java package.
*
* @param type YANG type
* @param conflictResolver object of YANG to java naming conflict util
* @return YANG enumeration's java package
*/
private static String getEnumsPackage(YangType<?> type) {
private static String getEnumsPackage(YangType<?> type, YangToJavaNamingConflictUtil conflictResolver) {
if (!(type.getDataTypeExtendedInfo() instanceof YangEnumeration)) {
throw new TranslatorException("type should have been enumeration.");
}
YangJavaEnumeration enumeration = (YangJavaEnumeration) type.getDataTypeExtendedInfo();
if (enumeration.getJavaFileInfo().getPackage() == null) {
return getPackageFromParent(enumeration.getParent());
return getPackageFromParent(enumeration.getParent(), conflictResolver);
}
return enumeration.getJavaFileInfo().getPackage();
}
......@@ -420,9 +416,10 @@ public final class AttributesJavaDataType {
* Returns package from parent node.
*
* @param parent parent YANG node
* @param conflictResolver object of YANG to java naming conflict util
* @return java package from parent node
*/
private static String getPackageFromParent(YangNode parent) {
private static String getPackageFromParent(YangNode parent, YangToJavaNamingConflictUtil conflictResolver) {
if (!(parent instanceof JavaFileInfoContainer)) {
throw new TranslatorException("invalid child node is being processed.");
}
......@@ -431,14 +428,14 @@ public final class AttributesJavaDataType {
if (parent instanceof YangJavaModule) {
YangJavaModule module = (YangJavaModule) parent;
String modulePkg = getRootPackage(module.getVersion(), module.getNameSpace().getUri(), module
.getRevision().getRevDate());
return modulePkg + PERIOD + getCamelCase(module.getName(), null).toLowerCase();
.getRevision().getRevDate(), conflictResolver);
return modulePkg + PERIOD + getCamelCase(module.getName(), conflictResolver).toLowerCase();
} else if (parent instanceof YangJavaSubModule) {
YangJavaSubModule submodule = (YangJavaSubModule) parent;
String subModulePkg = getRootPackage(submodule.getVersion(),
submodule.getNameSpaceFromModule(submodule.getBelongsTo()),
submodule.getRevision().getRevDate());
return subModulePkg + PERIOD + getCamelCase(submodule.getName(), null).toLowerCase();
submodule.getRevision().getRevDate(), conflictResolver);
return subModulePkg + PERIOD + getCamelCase(submodule.getName(), conflictResolver).toLowerCase();
}
}
return parentInfo.getPackage() + PERIOD + parentInfo.getJavaName().toLowerCase();
......
......@@ -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
......
......@@ -27,6 +27,7 @@ import org.onosproject.yangutils.translator.tojava.JavaFileInfoContainer;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFilesContainer;
import org.onosproject.yangutils.translator.tojava.TempJavaEnumerationFragmentFiles;
import org.onosproject.yangutils.translator.tojava.TempJavaServiceFragmentFiles;
import org.onosproject.yangutils.translator.tojava.javamodel.JavaCodeGeneratorInfo;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_CLASS_MASK;
......@@ -34,6 +35,7 @@ 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;
......@@ -44,6 +46,11 @@ import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ENUM_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EQUALS_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_ENUM_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_METHOD_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_ATTRIBUTE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_GETTER_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_SETTER_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.FROM_STRING_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_INTERFACE_MASK;
......@@ -59,6 +66,8 @@ import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerato
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGeneratorUtils.getEnumsValueAttribute;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGeneratorUtils.initiateJavaFileGeneration;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.addActivateMethod;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.addDeActivateMethod;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getAddAugmentInfoMethodImpl;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getAugmentInfoListImpl;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getConstructorStart;
......@@ -75,6 +84,7 @@ import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getRemoveAugmentationImpl;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getToStringMethodClose;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getToStringMethodOpen;
import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.getEventEnumTypeStart;
import static org.onosproject.yangutils.translator.tojava.utils.TempJavaCodeFragmentFilesUtils.isAugmentationHolderExtended;
import static org.onosproject.yangutils.utils.UtilConstants.BUILDER;
import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_CURLY_BRACKET;
......@@ -82,20 +92,23 @@ import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
import static org.onosproject.yangutils.utils.UtilConstants.EVENT_LISTENER_STRING;
import static org.onosproject.yangutils.utils.UtilConstants.EVENT_STRING;
import static org.onosproject.yangutils.utils.UtilConstants.EVENT_SUBJECT_NAME_SUFFIX;
import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
import static org.onosproject.yangutils.utils.UtilConstants.IMPL;
import static org.onosproject.yangutils.utils.UtilConstants.INT;
import static org.onosproject.yangutils.utils.UtilConstants.LOGGER_STATEMENT;
import static org.onosproject.yangutils.utils.UtilConstants.MANAGER;
import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
import static org.onosproject.yangutils.utils.UtilConstants.PRIVATE;
import static org.onosproject.yangutils.utils.UtilConstants.PUBLIC;
import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
import static org.onosproject.yangutils.utils.UtilConstants.SERVICE_METHOD_STRING;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.GETTER_METHOD;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.TYPE_CONSTRUCTOR;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.insertDataIntoJavaFile;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.partString;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.trimAtLast;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.validateLineLength;
/**
* Representation of java file generator.
......@@ -141,7 +154,7 @@ public final class JavaFileGenerator {
+ " while interface file generation");
}
}
return file;
return validateLineLength(file);
}
/**
......@@ -157,11 +170,12 @@ public final class JavaFileGenerator {
throws IOException {
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
String className = getCapitalCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateJavaFileGeneration(file, className, BUILDER_INTERFACE_MASK, null, path);
initiateJavaFileGeneration(file, className, BUILDER_INTERFACE_MASK, null, path, pluginConfig);
List<String> methods = new ArrayList<>();
if (isAttrPresent) {
try {
......@@ -188,7 +202,7 @@ public final class JavaFileGenerator {
*/
methods.add(
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.addBuildMethodForInterface());
.addBuildMethodForInterface(pluginConfig));
/**
* Add getters and setters in builder interface.
......@@ -198,7 +212,7 @@ public final class JavaFileGenerator {
}
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
return file;
return validateLineLength(file);
}
/**
......@@ -216,11 +230,12 @@ public final class JavaFileGenerator {
throws IOException {
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
String className = getCapitalCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateJavaFileGeneration(file, className, BUILDER_CLASS_MASK, imports, path);
initiateJavaFileGeneration(file, className, BUILDER_CLASS_MASK, imports, path, pluginConfig);
List<String> methods = new ArrayList<>();
......@@ -265,7 +280,7 @@ public final class JavaFileGenerator {
methods.add(((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.addBuildMethodImpl());
methods.add(((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.addDefaultConstructor(PUBLIC, BUILDER));
.addDefaultConstructor(PUBLIC, BUILDER, pluginConfig));
/**
* Add methods in builder class.
......@@ -273,7 +288,7 @@ public final class JavaFileGenerator {
for (String method : methods) {
insertDataIntoJavaFile(file, method);
}
return file;
return validateLineLength(file);
}
/**
......@@ -292,12 +307,16 @@ public final class JavaFileGenerator {
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
String className = getCapitalCase(javaFileInfo.getJavaName());
String className = getCapitalCase(javaFileInfo.getJavaName()) + MANAGER;
initiateJavaFileGeneration(file, GENERATE_SERVICE_AND_MANAGER, imports, curNode, className);
List<String> methods = new ArrayList<>();
insertDataIntoJavaFile(file, LOGGER_STATEMENT);
methods.add(addActivateMethod());
methods.add(addDeActivateMethod());
try {
if (isAttrPresent) {
/**
......@@ -338,7 +357,7 @@ public final class JavaFileGenerator {
for (String method : methods) {
insertDataIntoJavaFile(file, method);
}
return file;
return validateLineLength(file);
}
/**
......@@ -354,11 +373,12 @@ public final class JavaFileGenerator {
throws IOException {
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
String className = getCapitalCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateJavaFileGeneration(file, className, IMPL_CLASS_MASK, null, path);
initiateJavaFileGeneration(file, className, IMPL_CLASS_MASK, null, path, pluginConfig);
List<String> methods = new ArrayList<>();
......@@ -398,10 +418,10 @@ public final class JavaFileGenerator {
/**
* Hash code method.
*/
methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() + partString(
methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() +
getDataFromTempFileHandle(HASH_CODE_IMPL_MASK,
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.getBeanTempFiles()).replace(NEW_LINE, EMPTY_STRING))));
.getBeanTempFiles()).replace(NEW_LINE, EMPTY_STRING)));
/**
* Equals method.
*/
......@@ -429,7 +449,8 @@ public final class JavaFileGenerator {
/**
* Constructor.
*/
String constructor = getConstructorStart(className) + getDataFromTempFileHandle(CONSTRUCTOR_IMPL_MASK,
String constructor =
getConstructorStart(className, pluginConfig) + getDataFromTempFileHandle(CONSTRUCTOR_IMPL_MASK,
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.getBeanTempFiles());
......@@ -456,7 +477,7 @@ public final class JavaFileGenerator {
}
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
return file;
return validateLineLength(file);
}
/**
......@@ -472,11 +493,12 @@ public final class JavaFileGenerator {
throws IOException {
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
String className = getCapitalCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateJavaFileGeneration(file, className, GENERATE_TYPEDEF_CLASS, imports, path);
initiateJavaFileGeneration(file, className, GENERATE_TYPEDEF_CLASS, imports, path, pluginConfig);
List<String> methods = new ArrayList<>();
......@@ -497,7 +519,7 @@ public final class JavaFileGenerator {
* Default constructor.
*/
methods.add(((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.addDefaultConstructor(PRIVATE, EMPTY_STRING));
.addDefaultConstructor(PRIVATE, EMPTY_STRING, pluginConfig));
try {
......@@ -522,11 +544,11 @@ public final class JavaFileGenerator {
/**
* Hash code method.
*/
methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() + partString(
methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() +
getDataFromTempFileHandle(HASH_CODE_IMPL_MASK,
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.getTypeTempFiles())
.replace(NEW_LINE, EMPTY_STRING))));
.replace(NEW_LINE, EMPTY_STRING)));
/**
* Equals method.
......@@ -546,7 +568,7 @@ public final class JavaFileGenerator {
/**
* From string method.
*/
methods.add(getFromStringMethodSignature(className)
methods.add(getFromStringMethodSignature(className, pluginConfig)
+ getDataFromTempFileHandle(FROM_STRING_IMPL_MASK, javaGeninfo.getTempJavaCodeFragmentFiles()
.getTypeTempFiles()) + getFromStringMethodClose());
......@@ -560,7 +582,7 @@ public final class JavaFileGenerator {
}
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
return file;
return validateLineLength(file);
}
/**
......@@ -576,11 +598,12 @@ public final class JavaFileGenerator {
throws IOException {
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
String className = getCapitalCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateJavaFileGeneration(file, className, GENERATE_UNION_CLASS, imports, path);
initiateJavaFileGeneration(file, className, GENERATE_UNION_CLASS, imports, path, pluginConfig);
List<String> methods = new ArrayList<>();
......@@ -601,7 +624,7 @@ public final class JavaFileGenerator {
* Default constructor.
*/
methods.add(((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.addDefaultConstructor(PRIVATE, EMPTY_STRING));
.addDefaultConstructor(PRIVATE, EMPTY_STRING, pluginConfig));
try {
......@@ -626,11 +649,11 @@ public final class JavaFileGenerator {
/**
* Hash code method.
*/
methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() + partString(
methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() +
getDataFromTempFileHandle(HASH_CODE_IMPL_MASK,
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.getTypeTempFiles())
.replace(NEW_LINE, EMPTY_STRING))));
.replace(NEW_LINE, EMPTY_STRING)));
/**
* Equals method.
......@@ -650,7 +673,7 @@ public final class JavaFileGenerator {
/**
* From string method.
*/
methods.add(getFromStringMethodSignature(className)
methods.add(getFromStringMethodSignature(className, pluginConfig)
+ getDataFromTempFileHandle(FROM_STRING_IMPL_MASK,
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles().getTypeTempFiles())
+ getFromStringMethodClose());
......@@ -665,7 +688,7 @@ public final class JavaFileGenerator {
}
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
return file;
return validateLineLength(file);
}
/**
......@@ -680,11 +703,12 @@ public final class JavaFileGenerator {
throws IOException {
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
YangPluginConfig pluginConfig = javaFileInfo.getPluginConfig();
String className = javaFileInfo.getJavaName();
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateJavaFileGeneration(file, getCapitalCase(className), GENERATE_ENUM_CLASS, null, path);
initiateJavaFileGeneration(file, getCapitalCase(className), GENERATE_ENUM_CLASS, null, path, pluginConfig);
/**
* Add attribute strings.
*/
......@@ -708,26 +732,26 @@ public final class JavaFileGenerator {
/**
* Add a constructor for enum.
*/
insertDataIntoJavaFile(file, getJavaDoc(TYPE_CONSTRUCTOR, className, false)
insertDataIntoJavaFile(file, getJavaDoc(TYPE_CONSTRUCTOR, className, false, pluginConfig)
+ getEnumsConstrcutor(getCapitalCase(className)) + NEW_LINE);
TempJavaEnumerationFragmentFiles enumFragFiles =
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.getEnumerationTempFiles();
insertDataIntoJavaFile(file, getEnumsOfMethod(className,
enumFragFiles.getJavaAttributeForEnum(),
enumFragFiles.getJavaAttributeForEnum(pluginConfig),
enumFragFiles.getEnumSetJavaMap(),
enumFragFiles.getEnumStringList())
enumFragFiles.getEnumStringList(), pluginConfig)
+ NEW_LINE);
/**
* Add a getter method for enum.
*/
insertDataIntoJavaFile(file, getJavaDoc(GETTER_METHOD, className, false)
insertDataIntoJavaFile(file, getJavaDoc(GETTER_METHOD, className, false, pluginConfig)
+ getGetter(INT, className, GENERATE_ENUM_CLASS) + NEW_LINE);
try {
insertDataIntoJavaFile(file, getFromStringMethodSignature(getCapitalCase(className))
insertDataIntoJavaFile(file, getFromStringMethodSignature(getCapitalCase(className), pluginConfig)
+ getDataFromTempFileHandle(FROM_STRING_IMPL_MASK,
((TempJavaCodeFragmentFilesContainer) curNode).getTempJavaCodeFragmentFiles()
.getEnumerationTempFiles())
......@@ -739,7 +763,7 @@ public final class JavaFileGenerator {
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
return file;
return validateLineLength(file);
}
/**
......@@ -797,7 +821,7 @@ public final class JavaFileGenerator {
}
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
return file;
return validateLineLength(file);
}
/**
......@@ -810,49 +834,28 @@ public final class JavaFileGenerator {
*/
public static void generateEventFile(File file, YangNode curNode, List<String> imports) throws IOException {
YangNode parent = curNode.getParent();
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
String className =
getCapitalCase(((JavaFileInfoContainer) parent).getJavaFileInfo().getJavaName())
getCapitalCase(((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName())
+ EVENT_STRING;
TempJavaServiceFragmentFiles tempFiles = ((TempJavaCodeFragmentFilesContainer) curNode)
.getTempJavaCodeFragmentFiles().getServiceTempFiles();
initiateJavaFileGeneration(file, GENERATE_EVENT_CLASS, imports, curNode, className);
insertDataIntoJavaFile(file, getEventFileContents(className, javaFileInfo.getJavaName()));
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
try {
insertDataIntoJavaFile(file, NEW_LINE + getEventEnumTypeStart() +
trimAtLast(getDataFromTempFileHandle(EVENT_ENUM_MASK, tempFiles), COMMA)
+ FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET + NEW_LINE);
insertDataIntoJavaFile(file, getDataFromTempFileHandle(EVENT_METHOD_MASK, tempFiles));
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while event class file generation");
}
private static String getEventFileContents(String eventClassname, String classname) {
return "\n" +
" public enum Type {\n" +
" /**\n" +
" * " + getCapitalCase(classname) + " notification.\n" +
" */\n" +
" " + classname.toUpperCase() + "_EVENT\n" +
" }\n" +
"\n" +
" /**\n" +
" * Creates " + classname + " event with type and subject.\n" +
" *\n" +
" * @param type event type\n" +
" * @param subject subject " + classname + "\n" +
" */\n" +
" public " + eventClassname + "(Type type, " + getCapitalCase(classname) + " subject) {\n" +
" super(type, subject);\n" +
" }\n" +
"\n" +
" /**\n" +
" * Creates " + classname + " event with type, subject and time.\n" +
" *\n" +
" * @param type event type\n" +
" * @param subject subject " + classname + "\n" +
" * @param time time of event\n" +
" */\n" +
" public " + eventClassname + "(Type type, " + getCapitalCase(classname)
+ " subject, long time) {\n" +
" super(type, subject, time);\n" +
" }\n" +
"\n";
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
validateLineLength(file);
}
/**
......@@ -865,15 +868,48 @@ public final class JavaFileGenerator {
*/
public static void generateEventListenerFile(File file, YangNode curNode, List<String> imports)
throws IOException {
YangNode parent = curNode.getParent();
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
String className =
getCapitalCase(((JavaFileInfoContainer) parent).getJavaFileInfo().getJavaName())
getCapitalCase(((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName())
+ EVENT_LISTENER_STRING;
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateJavaFileGeneration(file, className, GENERATE_EVENT_LISTENER_INTERFACE, imports, path);
initiateJavaFileGeneration(file, GENERATE_EVENT_LISTENER_INTERFACE, imports, curNode, className);
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
validateLineLength(file);
}
/**
* Generates event subject's file.
*
* @param file file handle
* @param curNode current YANG node
* @throws IOException when fails to do IO exceptions
*/
public static void generateEventSubjectFile(File file, YangNode curNode)
throws IOException {
String className = getCapitalCase(((JavaFileInfoContainer) curNode).getJavaFileInfo().getJavaName())
+ EVENT_SUBJECT_NAME_SUFFIX;
initiateJavaFileGeneration(file, GENERATE_EVENT_SUBJECT_CLASS, null, curNode, className);
TempJavaServiceFragmentFiles tempFiles = ((TempJavaCodeFragmentFilesContainer) curNode)
.getTempJavaCodeFragmentFiles().getServiceTempFiles();
insertDataIntoJavaFile(file, NEW_LINE);
try {
insertDataIntoJavaFile(file, getDataFromTempFileHandle(EVENT_SUBJECT_ATTRIBUTE_MASK, tempFiles));
insertDataIntoJavaFile(file, getDataFromTempFileHandle(EVENT_SUBJECT_GETTER_MASK, tempFiles));
insertDataIntoJavaFile(file, getDataFromTempFileHandle(EVENT_SUBJECT_SETTER_MASK, tempFiles));
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while event class file generation");
}
insertDataIntoJavaFile(file, CLOSE_CURLY_BRACKET + NEW_LINE);
validateLineLength(file);
}
}
......
......@@ -37,6 +37,7 @@ 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;
......@@ -47,6 +48,11 @@ import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ENUM_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EQUALS_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_ENUM_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_METHOD_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_ATTRIBUTE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_GETTER_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EVENT_SUBJECT_SETTER_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.FROM_STRING_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_INTERFACE_MASK;
......@@ -60,28 +66,36 @@ import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.
import static org.onosproject.yangutils.translator.tojava.utils.ClassDefinitionGenerator.generateClassDefinition;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getJavaPackageFromPackagePath;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getSmallCase;
import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_PARENTHESIS;
import static org.onosproject.yangutils.utils.UtilConstants.COMPONENT_ANNOTATION;
import static org.onosproject.yangutils.utils.UtilConstants.EQUAL;
import static org.onosproject.yangutils.utils.UtilConstants.FOUR_SPACE_INDENTATION;
import static org.onosproject.yangutils.utils.UtilConstants.IMMEDIATE;
import static org.onosproject.yangutils.utils.UtilConstants.INT;
import static org.onosproject.yangutils.utils.UtilConstants.MANAGER;
import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
import static org.onosproject.yangutils.utils.UtilConstants.ORG;
import static org.onosproject.yangutils.utils.UtilConstants.OPEN_PARENTHESIS;
import static org.onosproject.yangutils.utils.UtilConstants.PACKAGE;
import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
import static org.onosproject.yangutils.utils.UtilConstants.PRIVATE;
import static org.onosproject.yangutils.utils.UtilConstants.REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE;
import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
import static org.onosproject.yangutils.utils.UtilConstants.SERVICE;
import static org.onosproject.yangutils.utils.UtilConstants.SERVICE_ANNOTATION;
import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
import static org.onosproject.yangutils.utils.UtilConstants.TRUE;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.BUILDER_CLASS;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.BUILDER_INTERFACE;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.ENUM_CLASS;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.EVENT;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.EVENT_LISTENER;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.EVENT_SUBJECT_CLASS;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.IMPL_CLASS;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.INTERFACE;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.RPC_INTERFACE;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.RPC_MANAGER;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.insertDataIntoJavaFile;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.parsePkg;
/**
* Represents utilities for java file generator.
......@@ -136,6 +150,7 @@ public final class JavaFileGeneratorUtils {
if (tempJavaFragmentFiles instanceof TempJavaServiceFragmentFiles) {
serviceFragmentFiles = (TempJavaServiceFragmentFiles) tempJavaFragmentFiles;
}
if ((generatedTempFiles & ATTRIBUTES_MASK) != 0) {
return tempJavaFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaFragmentFiles.getAttributesTempFileHandle());
......@@ -201,6 +216,36 @@ public final class JavaFileGeneratorUtils {
}
return serviceFragmentFiles
.getTemporaryDataFromFileHandle(serviceFragmentFiles.getRpcImplTempFileHandle());
} else if ((generatedTempFiles & EVENT_ENUM_MASK) != 0) {
if (serviceFragmentFiles == null) {
throw new TranslatorException("Required rpc implementation info is missing.");
}
return serviceFragmentFiles
.getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventEnumTempFileHandle());
} else if ((generatedTempFiles & EVENT_METHOD_MASK) != 0) {
if (serviceFragmentFiles == null) {
throw new TranslatorException("Required rpc implementation info is missing.");
}
return serviceFragmentFiles
.getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventMethodTempFileHandle());
} else if ((generatedTempFiles & EVENT_SUBJECT_GETTER_MASK) != 0) {
if (serviceFragmentFiles == null) {
throw new TranslatorException("Required rpc implementation info is missing.");
}
return serviceFragmentFiles
.getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventSubjectGetterTempFileHandle());
} else if ((generatedTempFiles & EVENT_SUBJECT_SETTER_MASK) != 0) {
if (serviceFragmentFiles == null) {
throw new TranslatorException("Required rpc implementation info is missing.");
}
return serviceFragmentFiles
.getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventSubjectSetterTempFileHandle());
} else if ((generatedTempFiles & EVENT_SUBJECT_ATTRIBUTE_MASK) != 0) {
if (serviceFragmentFiles == null) {
throw new TranslatorException("Required rpc implementation info is missing.");
}
return serviceFragmentFiles
.getTemporaryDataFromFileHandle(serviceFragmentFiles.getEventSubjectAttributeTempFileHandle());
}
return null;
}
......@@ -213,15 +258,16 @@ public final class JavaFileGeneratorUtils {
* @param type generated file type
* @param imports imports for the file
* @param pkg generated file package
* @param pluginConfig plugin configurations
* @throws IOException when fails to generate a file
*/
public static void initiateJavaFileGeneration(File file, String className, int type, List<String> imports,
String pkg)
String pkg, YangPluginConfig pluginConfig)
throws IOException {
try {
file.createNewFile();
appendContents(file, className, type, imports, pkg);
appendContents(file, className, type, imports, pkg, pluginConfig);
} catch (IOException e) {
throw new IOException("Failed to create " + file.getName() + " class file.");
}
......@@ -263,9 +309,17 @@ public final class JavaFileGeneratorUtils {
JavaFileInfo javaFileInfo = ((JavaFileInfoContainer) curNode).getJavaFileInfo();
String name = javaFileInfo.getJavaName();
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
String pkgString = parsePackageString(path, importsList);
String pkgString = null;
if (type == GENERATE_EVENT_CLASS
|| type == GENERATE_EVENT_LISTENER_INTERFACE
|| type == GENERATE_EVENT_SUBJECT_CLASS) {
pkgString = parsePackageString((path + PERIOD + name).toLowerCase(), importsList);
} else {
pkgString = parsePackageString(path, importsList);
}
switch (type) {
case INTERFACE_MASK:
appendHeaderContents(file, pkgString, importsList);
......@@ -279,6 +333,14 @@ public final class JavaFileGeneratorUtils {
appendHeaderContents(file, pkgString, importsList);
write(file, type, EVENT, curNode, className);
break;
case GENERATE_EVENT_LISTENER_INTERFACE:
appendHeaderContents(file, pkgString, importsList);
write(file, type, EVENT_LISTENER, curNode, className);
break;
case GENERATE_EVENT_SUBJECT_CLASS:
appendHeaderContents(file, pkgString, importsList);
write(file, type, EVENT_SUBJECT_CLASS, curNode, className);
break;
default:
break;
}
......@@ -294,37 +356,34 @@ public final class JavaFileGeneratorUtils {
* @param importsList list of java imports.
* @throws IOException when fails to append contents
*/
private static void appendContents(File file, String fileName, int type, List<String> importsList, String pkg)
private static void appendContents(File file, String fileName, int type, List<String> importsList, String pkg,
YangPluginConfig pluginConfig)
throws IOException {
String pkgString = parsePackageString(pkg, importsList);
switch (type) {
case IMPL_CLASS_MASK:
write(file, fileName, type, IMPL_CLASS);
write(file, fileName, type, IMPL_CLASS, pluginConfig);
break;
case BUILDER_INTERFACE_MASK:
write(file, fileName, type, BUILDER_INTERFACE);
write(file, fileName, type, BUILDER_INTERFACE, pluginConfig);
break;
case GENERATE_TYPEDEF_CLASS:
appendHeaderContents(file, pkgString, importsList);
write(file, fileName, type, IMPL_CLASS);
write(file, fileName, type, IMPL_CLASS, pluginConfig);
break;
case BUILDER_CLASS_MASK:
appendHeaderContents(file, pkgString, importsList);
write(file, fileName, type, BUILDER_CLASS);
write(file, fileName, type, BUILDER_CLASS, pluginConfig);
break;
case GENERATE_UNION_CLASS:
appendHeaderContents(file, pkgString, importsList);
write(file, fileName, type, IMPL_CLASS);
write(file, fileName, type, IMPL_CLASS, pluginConfig);
break;
case GENERATE_ENUM_CLASS:
appendHeaderContents(file, pkgString, importsList);
write(file, fileName, type, ENUM_CLASS);
break;
case GENERATE_EVENT_LISTENER_INTERFACE:
appendHeaderContents(file, pkgString, importsList);
write(file, fileName, type, EVENT_LISTENER);
write(file, fileName, type, ENUM_CLASS, pluginConfig);
break;
default:
break;
......@@ -340,10 +399,7 @@ public final class JavaFileGeneratorUtils {
*/
private static String parsePackageString(String javaPkg, List<String> importsList) {
if (javaPkg.contains(ORG)) {
String[] strArray = javaPkg.split(ORG);
javaPkg = ORG + getJavaPackageFromPackagePath(strArray[1]);
}
javaPkg = parsePkg(getJavaPackageFromPackagePath(javaPkg));
if (importsList != null) {
if (!importsList.isEmpty()) {
return PACKAGE + SPACE + javaPkg + SEMI_COLAN + NEW_LINE;
......@@ -395,14 +451,16 @@ public final class JavaFileGeneratorUtils {
private static void write(File file, int genType, JavaDocType javaDocType, YangNode curNode, String fileName)
throws IOException {
YangPluginConfig pluginConfig = ((JavaFileInfoContainer) curNode).getJavaFileInfo().getPluginConfig();
if ((genType & GENERATE_SERVICE_AND_MANAGER) != 0) {
if (!fileName.contains(SERVICE)) {
insertDataIntoJavaFile(file, getJavaDoc(RPC_MANAGER, fileName + MANAGER, false));
if (!fileName.matches(REGEX_FOR_ANY_STRING_ENDING_WITH_SERVICE)) {
insertDataIntoJavaFile(file, getJavaDoc(RPC_MANAGER, fileName, false, pluginConfig));
insertDataIntoJavaFile(file, addComponentString());
} else {
insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false));
insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false, pluginConfig));
}
} else {
insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false));
insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false, pluginConfig));
}
insertDataIntoJavaFile(file, generateClassDefinition(genType, fileName, curNode));
}
......@@ -416,9 +474,10 @@ public final class JavaFileGeneratorUtils {
* @param javaDocType java doc type
* @throws IOException when fails to write into a file
*/
private static void write(File file, String fileName, int genType, JavaDocType javaDocType)
private static void write(File file, String fileName, int genType, JavaDocType javaDocType,
YangPluginConfig pluginConfig)
throws IOException {
insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false));
insertDataIntoJavaFile(file, getJavaDoc(javaDocType, fileName, false, pluginConfig));
insertDataIntoJavaFile(file, generateClassDefinition(genType, fileName));
}
......@@ -433,4 +492,13 @@ public final class JavaFileGeneratorUtils {
+ SEMI_COLAN + NEW_LINE;
}
/**
* Returns component string.
*
* @return component string
*/
public static String addComponentString() {
return NEW_LINE + COMPONENT_ANNOTATION + SPACE + OPEN_PARENTHESIS + IMMEDIATE + SPACE
+ EQUAL + SPACE + TRUE + CLOSE_PARENTHESIS + NEW_LINE + SERVICE_ANNOTATION;
}
}
......
......@@ -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);
}
return getPkgFrmArr(pkgArr);
} catch (ArrayIndexOutOfBoundsException outOfBoundsException) {
throw new TranslatorException("The given prefix in pom.xml is invalid.");
}
} else {
prefixForIdentifier = YANG_AUTO_PREFIX;
}
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;
}
......
......@@ -26,11 +26,14 @@ import org.onosproject.yangutils.translator.tojava.JavaAttributeInfo;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaAugment;
import org.onosproject.yangutils.utils.io.impl.JavaDocGen;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_EVENT_SUBJECT_CLASS;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
import static org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType.getParseFromStringMethod;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getSmallCase;
import static org.onosproject.yangutils.utils.UtilConstants.ACTIVATE;
import static org.onosproject.yangutils.utils.UtilConstants.ACTIVATE_ANNOTATION;
import static org.onosproject.yangutils.utils.UtilConstants.ADD_STRING;
import static org.onosproject.yangutils.utils.UtilConstants.AND;
import static org.onosproject.yangutils.utils.UtilConstants.AUGMENTABLE;
......@@ -48,6 +51,8 @@ import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_CURLY_BRACKET;
import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_PARENTHESIS;
import static org.onosproject.yangutils.utils.UtilConstants.COLAN;
import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
import static org.onosproject.yangutils.utils.UtilConstants.DEACTIVATE;
import static org.onosproject.yangutils.utils.UtilConstants.DEACTIVATE_ANNOTATION;
import static org.onosproject.yangutils.utils.UtilConstants.DEFAULT;
import static org.onosproject.yangutils.utils.UtilConstants.DIAMOND_CLOSE_BRACKET;
import static org.onosproject.yangutils.utils.UtilConstants.DIAMOND_OPEN_BRACKET;
......@@ -93,7 +98,9 @@ import static org.onosproject.yangutils.utils.UtilConstants.SET_METHOD_PREFIX;
import static org.onosproject.yangutils.utils.UtilConstants.SHORT;
import static org.onosproject.yangutils.utils.UtilConstants.SIXTEEN_SPACE_INDENTATION;
import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
import static org.onosproject.yangutils.utils.UtilConstants.STARTED_LOG_INFO;
import static org.onosproject.yangutils.utils.UtilConstants.STATIC;
import static org.onosproject.yangutils.utils.UtilConstants.STOPPED_LOG_INFO;
import static org.onosproject.yangutils.utils.UtilConstants.STRING_DATA_TYPE;
import static org.onosproject.yangutils.utils.UtilConstants.SUFFIX_S;
import static org.onosproject.yangutils.utils.UtilConstants.SWITCH;
......@@ -106,6 +113,7 @@ import static org.onosproject.yangutils.utils.UtilConstants.TWELVE_SPACE_INDENTA
import static org.onosproject.yangutils.utils.UtilConstants.VALUE;
import static org.onosproject.yangutils.utils.UtilConstants.VOID;
import static org.onosproject.yangutils.utils.UtilConstants.YANG_UTILS_TODO;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.BUILD_METHOD;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.CONSTRUCTOR;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.DEFAULT_CONSTRUCTOR;
......@@ -115,7 +123,6 @@ import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.MAN
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.OF_METHOD;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.SETTER_METHOD;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType.TYPE_CONSTRUCTOR;
import static org.onosproject.yangutils.utils.io.impl.JavaDocGen.getJavaDoc;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.trimAtLast;
/**
......@@ -133,10 +140,11 @@ public final class MethodsGenerator {
* Returns the methods strings for builder interface.
*
* @param name attribute name
* @param pluginConfig plugin configurations
* @return method string for builder interface
*/
public static String parseBuilderInterfaceBuildMethodString(String name) {
return getJavaDoc(BUILD_METHOD, name, false) + getBuildForInterface(name);
public static String parseBuilderInterfaceBuildMethodString(String name, YangPluginConfig pluginConfig) {
return getJavaDoc(BUILD_METHOD, name, false, pluginConfig) + getBuildForInterface(name);
}
/**
......@@ -144,14 +152,16 @@ public final class MethodsGenerator {
*
* @param attr attribute info
* @param generatedJavaFiles generated java files
* @param pluginConfig plugin configurations
* @return getter string
*/
public static String getGetterString(JavaAttributeInfo attr, int generatedJavaFiles) {
public static String getGetterString(JavaAttributeInfo attr, int generatedJavaFiles,
YangPluginConfig pluginConfig) {
String returnType = getReturnType(attr);
String attributeName = attr.getAttributeName();
return getJavaDoc(GETTER_METHOD, attributeName, attr.isListAttr())
return getJavaDoc(GETTER_METHOD, attributeName, attr.isListAttr(), pluginConfig)
+ getGetterForInterface(attributeName, returnType, attr.isListAttr(), generatedJavaFiles);
}
......@@ -161,20 +171,22 @@ public final class MethodsGenerator {
* @param attr attribute info
* @param className java class name
* @param generatedJavaFiles generated java files
* @param pluginConfig plugin configurations
* @return setter string
*/
public static String getSetterString(JavaAttributeInfo attr, String className, int generatedJavaFiles) {
public static String getSetterString(JavaAttributeInfo attr, String className, int generatedJavaFiles,
YangPluginConfig pluginConfig) {
String attrType = getReturnType(attr);
String attributeName = attr.getAttributeName();
JavaDocGen.JavaDocType type;
if (generatedJavaFiles == GENERATE_SERVICE_AND_MANAGER) {
if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
type = MANAGER_SETTER_METHOD;
} else {
type = SETTER_METHOD;
}
return getJavaDoc(type, attributeName, attr.isListAttr())
return getJavaDoc(type, attributeName, attr.isListAttr(), pluginConfig)
+ getSetterForInterface(attributeName, attrType, className, attr.isListAttr(), generatedJavaFiles);
}
......@@ -182,10 +194,11 @@ public final class MethodsGenerator {
* Returns constructor method string.
*
* @param name class name
* @param pluginConfig plugin configurations
* @return constructor string
*/
public static String getConstructorString(String name) {
return getJavaDoc(CONSTRUCTOR, name, false);
public static String getConstructorString(String name, YangPluginConfig pluginConfig) {
return getJavaDoc(CONSTRUCTOR, name, false, pluginConfig);
}
/**
......@@ -193,10 +206,13 @@ public final class MethodsGenerator {
*
* @param name class name
* @param modifierType modifier type
* @param pluginConfig plugin configurations
* @return default constructor string
*/
public static String getDefaultConstructorString(String name, String modifierType) {
return getJavaDoc(DEFAULT_CONSTRUCTOR, name, false) + getDefaultConstructor(name, modifierType)
public static String getDefaultConstructorString(String name, String modifierType,
YangPluginConfig pluginConfig) {
return getJavaDoc(DEFAULT_CONSTRUCTOR, name, false, pluginConfig)
+ getDefaultConstructor(name, modifierType)
+ NEW_LINE;
}
......@@ -249,7 +265,7 @@ public final class MethodsGenerator {
* @return getter for attribute
*/
public static String getGetter(String type, String name, int generatedJavaFiles) {
String ret = parseTypeForGetter(type);
String ret = parseTypeForReturnValue(type);
if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + type + SPACE + GET_METHOD_PREFIX + getCapitalCase(name)
+ OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE +
......@@ -265,7 +281,7 @@ public final class MethodsGenerator {
}
/*Provides string to return for type.*/
private static String parseTypeForGetter(String type) {
private static String parseTypeForReturnValue(String type) {
switch (type) {
case BYTE:
case INT:
......@@ -312,12 +328,17 @@ public final class MethodsGenerator {
+ getCapitalCase(name) + OPEN_PARENTHESIS + type + SPACE + name + CLOSE_PARENTHESIS + SPACE +
OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + YANG_UTILS_TODO +
NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
} else if (generatedJavaFiles == GENERATE_EVENT_SUBJECT_CLASS) {
return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + VOID + SPACE + name + OPEN_PARENTHESIS + type + SPACE
+ name + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION
+ THIS + PERIOD + name + SPACE + EQUAL + SPACE + name + SEMI_COLAN + NEW_LINE
+ FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
} else {
return FOUR_SPACE_INDENTATION + PUBLIC + SPACE + className + BUILDER + SPACE +
name + OPEN_PARENTHESIS + type + SPACE + name + CLOSE_PARENTHESIS + SPACE
+ OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + THIS + PERIOD + name + SPACE + EQUAL +
SPACE + name + SEMI_COLAN + NEW_LINE + EIGHT_SPACE_INDENTATION + RETURN + SPACE + THIS +
SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
+ OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + THIS + PERIOD + name + SPACE
+ EQUAL + SPACE + name + SEMI_COLAN + NEW_LINE + EIGHT_SPACE_INDENTATION + RETURN + SPACE
+ THIS + SEMI_COLAN + NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
}
}
......@@ -474,13 +495,16 @@ public final class MethodsGenerator {
* Returns constructor string for impl class.
*
* @param yangName class name
* @param pluginConfig plugin configurations
* @return constructor string
*/
public static String getConstructorStart(String yangName) {
public static String getConstructorStart(String yangName, YangPluginConfig pluginConfig) {
String javadoc = getConstructorString(yangName);
String constructor = FOUR_SPACE_INDENTATION + PUBLIC + SPACE + yangName + IMPL + OPEN_PARENTHESIS + yangName
+ BUILDER + SPACE + BUILDER.toLowerCase() + OBJECT + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET
String javadoc = getConstructorString(yangName, pluginConfig);
String constructor =
FOUR_SPACE_INDENTATION + PUBLIC + SPACE + yangName + IMPL + OPEN_PARENTHESIS + yangName
+ BUILDER + SPACE + BUILDER.toLowerCase() + OBJECT + CLOSE_PARENTHESIS + SPACE
+ OPEN_CURLY_BRACKET
+ NEW_LINE;
return javadoc + constructor;
}
......@@ -491,24 +515,29 @@ public final class MethodsGenerator {
* @param yangName name of the class
* @param attr attribute info
* @param generatedJavaFiles generated java files
* @param pluginConfig plugin configurations
* @return constructor for class
*/
public static String getConstructor(String yangName, JavaAttributeInfo attr, int generatedJavaFiles) {
public static String getConstructor(String yangName, JavaAttributeInfo attr, int generatedJavaFiles,
YangPluginConfig pluginConfig) {
String attributeName = attr.getAttributeName();
String constructor;
if ((generatedJavaFiles & GENERATE_SERVICE_AND_MANAGER) != 0) {
constructor = EIGHT_SPACE_INDENTATION + THIS + PERIOD + getCamelCase(attributeName, null) + SPACE + EQUAL
constructor =
EIGHT_SPACE_INDENTATION + THIS + PERIOD
+ getCamelCase(attributeName, pluginConfig.getConflictResolver()) + SPACE + EQUAL
+ SPACE + BUILDER.toLowerCase() + OBJECT + PERIOD + GET_METHOD_PREFIX
+ getCapitalCase(getCamelCase(attributeName, null)) + OPEN_PARENTHESIS + CLOSE_PARENTHESIS +
SEMI_COLAN
+ NEW_LINE;
+ getCapitalCase(getCamelCase(attributeName, pluginConfig.getConflictResolver()))
+ OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE;
} else {
constructor = EIGHT_SPACE_INDENTATION + THIS + PERIOD + getCamelCase(attributeName, null) + SPACE + EQUAL
+ SPACE + BUILDER.toLowerCase() + OBJECT + PERIOD + getCamelCase(attributeName, null) +
OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN
+ NEW_LINE;
constructor =
EIGHT_SPACE_INDENTATION + THIS + PERIOD
+ getCamelCase(attributeName, pluginConfig.getConflictResolver()) + SPACE + EQUAL
+ SPACE + BUILDER.toLowerCase() + OBJECT + PERIOD
+ getCamelCase(attributeName, pluginConfig.getConflictResolver()) +
OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN + NEW_LINE;
}
return constructor;
}
......@@ -519,17 +548,18 @@ public final class MethodsGenerator {
* @param rpcName name of the rpc
* @param inputName name of input
* @param outputName name of output
* @param pluginConfig plugin configurations
* @return rpc method string
*/
public static String getRpcServiceMethod(String rpcName, String inputName, String outputName) {
public static String getRpcServiceMethod(String rpcName, String inputName, String outputName,
YangPluginConfig pluginConfig) {
rpcName = getCamelCase(rpcName, null);
inputName = getCapitalCase(inputName);
if (!outputName.equals(VOID)) {
outputName = getCapitalCase(outputName);
rpcName = getCamelCase(rpcName, pluginConfig.getConflictResolver());
if (!inputName.equals(EMPTY_STRING)) {
inputName = inputName + SPACE + RPC_INPUT_VAR_NAME;
}
return FOUR_SPACE_INDENTATION + outputName + SPACE + rpcName + OPEN_PARENTHESIS + inputName + SPACE
+ RPC_INPUT_VAR_NAME + CLOSE_PARENTHESIS + SEMI_COLAN;
return FOUR_SPACE_INDENTATION + outputName + SPACE + rpcName + OPEN_PARENTHESIS + inputName
+ CLOSE_PARENTHESIS + SEMI_COLAN;
}
/**
......@@ -538,21 +568,24 @@ public final class MethodsGenerator {
* @param rpcName name of the rpc
* @param inputName name of input
* @param outputName name of output
* @param pluginConfig plugin configurations
* @return rpc method string
*/
public static String getRpcManagerMethod(String rpcName, String inputName, String outputName) {
public static String getRpcManagerMethod(String rpcName, String inputName, String outputName,
YangPluginConfig pluginConfig) {
rpcName = getCamelCase(rpcName, null);
inputName = getCapitalCase(inputName);
if (!outputName.equals(VOID)) {
outputName = getCapitalCase(outputName);
rpcName = getCamelCase(rpcName, pluginConfig.getConflictResolver());
if (!inputName.equals(EMPTY_STRING)) {
inputName = inputName + SPACE + RPC_INPUT_VAR_NAME;
}
String method = getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + outputName + SPACE + rpcName
+ OPEN_PARENTHESIS + inputName + SPACE + RPC_INPUT_VAR_NAME + CLOSE_PARENTHESIS + SPACE
String method =
getOverRideString() + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + outputName + SPACE + rpcName
+ OPEN_PARENTHESIS + inputName + CLOSE_PARENTHESIS + SPACE
+ OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION + YANG_UTILS_TODO + NEW_LINE;
if (!outputName.contentEquals(VOID)) {
method += EIGHT_SPACE_INDENTATION + RETURN + SPACE + NULL + SEMI_COLAN + NEW_LINE;
method += EIGHT_SPACE_INDENTATION + RETURN + SPACE + parseTypeForReturnValue(outputName) + SEMI_COLAN
+ NEW_LINE;
}
method += FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
......@@ -631,12 +664,14 @@ public final class MethodsGenerator {
* Returns from string method's open string.
*
* @param className name of the class
* @param pluginConfig plugin configurations
* @return from string method's open string
*/
public static String getFromStringMethodSignature(String className) {
return getJavaDoc(FROM_METHOD, className, false) + FOUR_SPACE_INDENTATION + PUBLIC + SPACE + STATIC + SPACE
+ className + SPACE + FROM_STRING_METHOD_NAME + OPEN_PARENTHESIS + STRING_DATA_TYPE + SPACE
+ FROM_STRING_PARAM_NAME + CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE;
public static String getFromStringMethodSignature(String className, YangPluginConfig pluginConfig) {
return getJavaDoc(FROM_METHOD, className, false, pluginConfig) + FOUR_SPACE_INDENTATION + PUBLIC + SPACE
+ STATIC + SPACE + className + SPACE + FROM_STRING_METHOD_NAME + OPEN_PARENTHESIS
+ STRING_DATA_TYPE + SPACE + FROM_STRING_PARAM_NAME + CLOSE_PARENTHESIS + SPACE
+ OPEN_CURLY_BRACKET + NEW_LINE;
}
/**
......@@ -832,14 +867,16 @@ public final class MethodsGenerator {
*
* @param attr attribute info
* @param generatedJavaClassName class name
* @param pluginConfig plugin configurations
* @return of method's string and java doc for special type
*/
public static String getOfMethodStringAndJavaDoc(JavaAttributeInfo attr, String generatedJavaClassName) {
public static String getOfMethodStringAndJavaDoc(JavaAttributeInfo attr, String generatedJavaClassName,
YangPluginConfig pluginConfig) {
String attrType = getReturnType(attr);
String attrName = attr.getAttributeName();
return getJavaDoc(OF_METHOD, generatedJavaClassName + " for type " + attrName, false)
return getJavaDoc(OF_METHOD, generatedJavaClassName + " for type " + attrName, false, pluginConfig)
+ getOfMethodString(attrType, generatedJavaClassName);
}
......@@ -863,14 +900,16 @@ public final class MethodsGenerator {
*
* @param attr attribute info
* @param generatedJavaClassName class name
* @param pluginConfig plugin configurations
* @return string and java doc for constructor of type class
*/
public static String getTypeConstructorStringAndJavaDoc(JavaAttributeInfo attr, String generatedJavaClassName) {
public static String getTypeConstructorStringAndJavaDoc(JavaAttributeInfo attr,
String generatedJavaClassName, YangPluginConfig pluginConfig) {
String attrType = getReturnType(attr);
String attrName = attr.getAttributeName();
return getJavaDoc(TYPE_CONSTRUCTOR, generatedJavaClassName + " for type " + attrName, false)
return getJavaDoc(TYPE_CONSTRUCTOR, generatedJavaClassName + " for type " + attrName, false, pluginConfig)
+ getTypeConstructorString(attrType, attrName, generatedJavaClassName);
}
......@@ -986,10 +1025,11 @@ public final class MethodsGenerator {
* @param attr java attribute
* @param enumMap enum's sets map
* @param enumList enum's sets list
* @param pluginConfig plugin configurations
* @return of method
*/
public static String getEnumsOfMethod(String className, JavaAttributeInfo attr,
Map<String, Integer> enumMap, List<String> enumList) {
Map<String, Integer> enumMap, List<String> enumList, YangPluginConfig pluginConfig) {
String attrType = getReturnType(attr);
String attrName = attr.getAttributeName();
......@@ -1010,6 +1050,37 @@ public final class MethodsGenerator {
+ RETURN + SPACE + NULL + SEMI_COLAN + NEW_LINE + EIGHT_SPACE_INDENTATION + CLOSE_CURLY_BRACKET
+ NEW_LINE + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET;
return getJavaDoc(OF_METHOD, getCapitalCase(className) + " for type " + attrName, false) + method;
return getJavaDoc(OF_METHOD, getCapitalCase(className) + " for type " + attrName, false, pluginConfig)
+ method;
}
/**
* Returns activate method string.
*
* @return activate method string
*/
public static String addActivateMethod() {
return FOUR_SPACE_INDENTATION + ACTIVATE_ANNOTATION + FOUR_SPACE_INDENTATION
+ PUBLIC + SPACE + VOID + SPACE + ACTIVATE + OPEN_PARENTHESIS
+ CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET
+ NEW_LINE + EIGHT_SPACE_INDENTATION
+ YANG_UTILS_TODO
+ NEW_LINE + EIGHT_SPACE_INDENTATION
+ STARTED_LOG_INFO + FOUR_SPACE_INDENTATION
+ CLOSE_CURLY_BRACKET + NEW_LINE;
}
/**
* Returns deactivate method string.
*
* @return deactivate method string
*/
public static String addDeActivateMethod() {
return NEW_LINE + FOUR_SPACE_INDENTATION + DEACTIVATE_ANNOTATION + FOUR_SPACE_INDENTATION
+ PUBLIC + SPACE + VOID + SPACE + DEACTIVATE + OPEN_PARENTHESIS
+ CLOSE_PARENTHESIS + SPACE + OPEN_CURLY_BRACKET + NEW_LINE + EIGHT_SPACE_INDENTATION
+ YANG_UTILS_TODO + NEW_LINE + EIGHT_SPACE_INDENTATION
+ STOPPED_LOG_INFO + FOUR_SPACE_INDENTATION + CLOSE_CURLY_BRACKET + NEW_LINE;
}
}
......
......@@ -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);
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
+ getInputString(inputName, rpcName);
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);
}
/**
......
......@@ -16,32 +16,38 @@
package org.onosproject.yangutils.utils.io.impl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
import java.util.Stack;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Resource;
import org.apache.maven.project.MavenProject;
import org.onosproject.yangutils.plugin.manager.YangFileInfo;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
import org.slf4j.Logger;
import org.sonatype.plexus.build.incremental.BuildContext;
import static org.onosproject.yangutils.utils.UtilConstants.COMMA;
import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
import static org.onosproject.yangutils.utils.UtilConstants.HASH;
import static org.onosproject.yangutils.utils.UtilConstants.NEW_LINE;
import static org.onosproject.yangutils.utils.UtilConstants.OPEN_PARENTHESIS;
import static org.onosproject.yangutils.utils.UtilConstants.ORG;
import static org.onosproject.yangutils.utils.UtilConstants.PACKAGE;
import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
import static org.onosproject.yangutils.utils.UtilConstants.SEMI_COLAN;
import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
import static org.onosproject.yangutils.utils.UtilConstants.SPACE;
......@@ -61,6 +67,9 @@ public final class YangIoUtils {
private static final Logger log = getLogger(YangIoUtils.class);
private static final String TARGET_RESOURCE_PATH = SLASH + TEMP + SLASH + YANG_RESOURCES + SLASH;
private static final int LINE_SIZE = 116;
private static final int SUB_LINE_SIZE = 112;
private static final int ZERO = 0;
/**
* Creates an instance of YANG io utils.
......@@ -87,15 +96,15 @@ public final class YangIoUtils {
* @param classInfo class info for the package
* @param pack package of the directory
* @param isChildNode is it a child node
* @param pluginConfig plugin configurations
* @throws IOException when fails to create package info file
*/
public static void addPackageInfo(File path, String classInfo, String pack, boolean isChildNode)
public static void addPackageInfo(File path, String classInfo, String pack, boolean isChildNode,
YangPluginConfig pluginConfig)
throws IOException {
if (pack.contains(ORG)) {
String[] strArray = pack.split(ORG);
pack = ORG + strArray[1];
}
pack = parsePkg(pack);
try {
File packageInfo = new File(path + SLASH + "package-info.java");
......@@ -105,9 +114,12 @@ public final class YangIoUtils {
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(CopyrightHeader.getCopyrightHeader());
bufferedWriter.write(getJavaDoc(PACKAGE_INFO, classInfo, isChildNode));
bufferedWriter.write(PACKAGE + SPACE + pack + SEMI_COLAN);
bufferedWriter.write(getJavaDoc(PACKAGE_INFO, classInfo, isChildNode, pluginConfig));
String pkg = PACKAGE + SPACE + pack + SEMI_COLAN;
if (pkg.length() > LINE_SIZE) {
pkg = whenDelimiterIsPersent(pkg, LINE_SIZE);
}
bufferedWriter.write(pkg);
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
......@@ -116,6 +128,32 @@ public final class YangIoUtils {
}
/**
* Parses package and returns updated package.
*
* @param pack package needs to be updated
* @return updated package
*/
public static String parsePkg(String pack) {
if (pack.contains(ORG)) {
String[] strArray = pack.split(ORG);
if (strArray.length >= 3) {
for (int i = 1; i < strArray.length; i++) {
if (i == 1) {
pack = ORG + strArray[1];
} else {
pack = pack + ORG + strArray[i];
}
}
} else {
pack = ORG + strArray[1];
}
}
return pack;
}
/**
* Cleans the generated directory if already exist in source folder.
*
* @param dir generated directory in previous build
......@@ -249,7 +287,7 @@ public final class YangIoUtils {
/**
* Copies YANG files to the current project's output directory.
*
* @param yangFileInfo set of YANG files
* @param yangFileInfo list of YANG files
* @param outputDir project's output directory
* @param project maven project
* @throws IOException when fails to copy files to destination resource directory
......@@ -318,4 +356,126 @@ public final class YangIoUtils {
throw new IOException("Failed to insert in " + file + "file");
}
}
/**
* Validates a line size in given file whether it is having more then 120 characters.
* If yes it will update and give a new file.
*
* @param dataFile file in which need to verify all lines.
* @return updated file
* @throws IOException when fails to do IO operations.
*/
public static File validateLineLength(File dataFile) throws IOException {
File tempFile = dataFile;
FileReader fileReader = new FileReader(dataFile);
BufferedReader bufferReader = new BufferedReader(fileReader);
try {
StringBuilder stringBuilder = new StringBuilder();
String line = bufferReader.readLine();
while (line != null) {
if (line.length() > LINE_SIZE) {
if (line.contains(PERIOD)) {
line = whenDelimiterIsPersent(line, LINE_SIZE);
} else if (line.contains(SPACE)) {
line = whenSpaceIsPresent(line, LINE_SIZE);
}
stringBuilder.append(line);
} else {
stringBuilder.append(line + NEW_LINE);
}
line = bufferReader.readLine();
}
FileWriter writer = new FileWriter(tempFile);
writer.write(stringBuilder.toString());
writer.close();
return tempFile;
} finally {
fileReader.close();
bufferReader.close();
}
}
/*When delimiters are present in the given line.*/
private static String whenDelimiterIsPersent(String line, int lineSize) {
StringBuilder stringBuilder = new StringBuilder();
if (line.length() > lineSize) {
String[] strArray = line.split(Pattern.quote(PERIOD));
stringBuilder = updateString(strArray, stringBuilder, PERIOD, lineSize);
} else {
stringBuilder.append(line + NEW_LINE);
}
String[] strArray = stringBuilder.toString().split(NEW_LINE);
StringBuilder tempBuilder = new StringBuilder();
for (String str : strArray) {
if (str.length() > SUB_LINE_SIZE) {
if (line.contains(PERIOD) && !line.contains(PERIOD + HASH + OPEN_PARENTHESIS)) {
String[] strArr = str.split(Pattern.quote(PERIOD));
tempBuilder = updateString(strArr, tempBuilder, PERIOD, SUB_LINE_SIZE);
} else if (str.contains(SPACE)) {
tempBuilder.append(whenSpaceIsPresent(str, SUB_LINE_SIZE));
}
} else {
tempBuilder.append(str + NEW_LINE);
}
}
return tempBuilder.toString();
}
/*When spaces are present in the given line.*/
private static String whenSpaceIsPresent(String line, int lineSize) {
StringBuilder stringBuilder = new StringBuilder();
if (line.length() > lineSize) {
String[] strArray = line.split(SPACE);
stringBuilder = updateString(strArray, stringBuilder, SPACE, lineSize);
} else {
stringBuilder.append(line + NEW_LINE);
}
String[] strArray = stringBuilder.toString().split(NEW_LINE);
StringBuilder tempBuilder = new StringBuilder();
for (String str : strArray) {
if (str.length() > SUB_LINE_SIZE) {
if (str.contains(SPACE)) {
String[] strArr = str.split(SPACE);
tempBuilder = updateString(strArr, tempBuilder, SPACE, SUB_LINE_SIZE);
}
} else {
tempBuilder.append(str + NEW_LINE);
}
}
return tempBuilder.toString();
}
/*Updates the given line with the given size conditions.*/
private static StringBuilder updateString(String[] strArray, StringBuilder stringBuilder, String string,
int lineSize) {
StringBuilder tempBuilder = new StringBuilder();
for (String str : strArray) {
tempBuilder.append(str + string);
if (tempBuilder.length() > lineSize) {
String tempString = stringBuilder.toString();
stringBuilder.delete(ZERO, stringBuilder.length());
tempString = trimAtLast(tempString, string);
stringBuilder.append(tempString);
if (string.equals(PERIOD)) {
stringBuilder.append(NEW_LINE + TWELVE_SPACE_INDENTATION + PERIOD + str + string);
} else {
stringBuilder.append(NEW_LINE + TWELVE_SPACE_INDENTATION + str + string);
}
tempBuilder.delete(ZERO, tempBuilder.length());
tempBuilder.append(TWELVE_SPACE_INDENTATION);
} else {
stringBuilder.append(str + string);
}
}
String tempString = stringBuilder.toString();
tempString = trimAtLast(tempString, string);
stringBuilder.delete(ZERO, stringBuilder.length());
stringBuilder.append(tempString + NEW_LINE);
return stringBuilder;
}
}
......
......@@ -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);
}
}
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.parser.parseutils;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangLexer;
import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.CustomExceptionMatcher;
import org.onosproject.yangutils.parser.impl.YangUtilsParserManager;
import org.onosproject.yangutils.parser.impl.parserutils.ParseTreeErrorListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
/**
* Test case for testing parse tree error listener.
*/
public class ParseTreeErrorListenerTest {
YangUtilsParserManager manager = new YangUtilsParserManager();
File file;
BufferedWriter out;
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Checks that no exception is generated for YANG file with valid syntax.
*/
@Test
public void checkValidYangFileForNoSyntaxError() throws IOException {
ANTLRInputStream input = new ANTLRFileStream("src/test/resources/YangFileWithoutSyntaxError.yang");
// Create a lexer that feeds off of input char stream.
GeneratedYangLexer lexer = new GeneratedYangLexer(input);
// Create a buffer of tokens pulled from the lexer.
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Create a parser that feeds off the tokens buffer.
GeneratedYangParser parser = new GeneratedYangParser(tokens);
// Remove console error listener.
parser.removeErrorListeners();
// Create instance of customized error listener.
ParseTreeErrorListener parseTreeErrorListener = new ParseTreeErrorListener();
// Add customized error listener to catch errors during parsing.
parser.addErrorListener(parseTreeErrorListener);
// Begin parsing YANG file and generate parse tree.
ParseTree tree = parser.yangfile();
}
/**
* Checks that exception is generated for YANG file with invalid syntax.
*/
@Test
public void checkInvalidYangFileForSyntaxError() throws IOException {
// Get the exception occurred during parsing.
thrown.expect(ParserException.class);
thrown.expect(CustomExceptionMatcher.errorLocation(3, 0));
thrown.expectMessage("no viable alternative at input 'yang-version 1\\nnamespace'");
ANTLRInputStream input = new ANTLRFileStream("src/test/resources/YangFileWithSyntaxError.yang");
// Create a lexer that feeds off of input char stream.
GeneratedYangLexer lexer = new GeneratedYangLexer(input);
// Create a buffer of tokens pulled from the lexer.
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Create a parser that feeds off the tokens buffer.
GeneratedYangParser parser = new GeneratedYangParser(tokens);
// Remove console error listener.
parser.removeErrorListeners();
// Create instance of customized error listener.
ParseTreeErrorListener parseTreeErrorListener = new ParseTreeErrorListener();
// Add customized error listener to catch errors during parsing.
parser.addErrorListener(parseTreeErrorListener);
// Begin parsing YANG file and generate parse tree.
ParseTree tree = parser.yangfile();
}
}
\ No newline at end of file
......@@ -59,6 +59,7 @@ public class AttributesJavaDataTypeTest {
private static final String CLASS_INFO5 = "Integer";
private static final String TYPE_DEF_PKG = "target.test";
private static String test = "";
private static YangToJavaNamingConflictUtil pluginConfig = null;
/**
* Unit test for private constructor.
......@@ -71,7 +72,8 @@ public class AttributesJavaDataTypeTest {
* @throws InvocationTargetException when an exception occurs by the method or constructor
*/
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
public void callPrivateConstructors()
throws SecurityException, NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InvocationTargetException {
Class<?>[] classesToConstruct = {AttributesJavaDataType.class };
......@@ -87,16 +89,16 @@ public class AttributesJavaDataTypeTest {
*/
@Test
public void testgetJavaClassInfo() {
test = getJavaImportClass(getStubYangType(TYPE1), false);
test = getJavaImportClass(getStubYangType(TYPE1), false, pluginConfig);
assertThat(true, is(test.equals(CLASS_INFO1)));
test = getJavaImportClass(getStubYangType(TYPE2), true);
test = getJavaImportClass(getStubYangType(TYPE2), true, pluginConfig);
assertThat(true, is(test.equals(CLASS_INFO5)));
test = getJavaImportClass(getStubYangType(TYPE3), false);
test = getJavaImportClass(getStubYangType(TYPE3), false, pluginConfig);
assertThat(null, is(test));
test = getJavaImportClass(getStubYangType(TYPE4), false);
test = getJavaImportClass(getStubYangType(TYPE4), false, pluginConfig);
assertThat(null, is(test));
}
......@@ -123,16 +125,16 @@ public class AttributesJavaDataTypeTest {
*/
@Test
public void testgetJavaPkgInfo() {
test = getJavaImportPackage(getStubYangType(TYPE1), false, CLASS_INFO1);
test = getJavaImportPackage(getStubYangType(TYPE1), false, pluginConfig);
assertThat(true, is(test.equals(JAVA_LANG)));
test = getJavaImportPackage(getStubYangType(TYPE2), true, CLASS_INFO5);
test = getJavaImportPackage(getStubYangType(TYPE2), true, pluginConfig);
assertThat(true, is(test.equals(JAVA_LANG)));
test = getJavaImportPackage(getStubYangType(TYPE3), false, CLASS_INFO3);
test = getJavaImportPackage(getStubYangType(TYPE3), false, pluginConfig);
assertThat(null, is(test));
test = getJavaImportPackage(getStubYangType(TYPE4), false, CLASS_INFO4);
test = getJavaImportPackage(getStubYangType(TYPE4), false, pluginConfig);
assertThat(null, is(test));
}
......@@ -143,7 +145,7 @@ public class AttributesJavaDataTypeTest {
*/
@Test
public void testForTypeDef() throws DataModelException {
test = getJavaImportPackage(getStubExtendedInfo(getStubYangType(TYPE_DEF)), false, TYPE_DEF_PKG);
test = getJavaImportPackage(getStubExtendedInfo(getStubYangType(TYPE_DEF)), false, pluginConfig);
assertThat(true, is(test.equals(TYPE_DEF_PKG)));
}
......
......@@ -17,6 +17,7 @@
package org.onosproject.yangutils.translator.tojava.utils;
import java.io.IOException;
import org.junit.Test;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.parser.exceptions.ParserException;
......@@ -44,7 +45,7 @@ public final class ChoiceCaseTranslatorTest {
YangPluginConfig yangPluginConfig = new YangPluginConfig();
yangPluginConfig.setCodeGenDir(userDir + "/target/ChoiceCaseTestGenFile/");
generateJavaCode(node, yangPluginConfig, "ChoiceCaseTranslator");
generateJavaCode(node, yangPluginConfig);
deleteDirectory(userDir + "/target/ChoiceCaseTestGenFile/");
}
......
......@@ -46,7 +46,7 @@ public final class EnumTranslatorTest {
YangPluginConfig yangPluginConfig = new YangPluginConfig();
yangPluginConfig.setCodeGenDir(userDir + "/target/EnumTestGenFile/");
generateJavaCode(node, yangPluginConfig, "EnumTranslator");
generateJavaCode(node, yangPluginConfig);
deleteDirectory(userDir + "/target/EnumTestGenFile/");
}
......
......@@ -19,7 +19,10 @@ package org.onosproject.yangutils.translator.tojava.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onosproject.yangutils.translator.exception.TranslatorException;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
......@@ -38,6 +41,9 @@ import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
*/
public final class JavaIdentifierSyntaxTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private static final String PARENT_PACKAGE = "test5/test6/test7";
private static final String CHILD_PACKAGE = "test1:test2:test3";
private static final String DATE1 = "2000-1-5";
......@@ -47,10 +53,17 @@ public final class JavaIdentifierSyntaxTest {
private static final String DATE_WITH_REV1 = "rev20000105";
private static final String DATE_WITH_REV2 = "rev19920125";
private static final String VERSION_NUMBER = "v1";
private static final String VALID_PREFIX = "123add-prefix";
private static final String INVALID_PREFIX = "-*()&^&#$%";
private static final String INVALID_PREFIX1 = "abc~!@#$%^&*()_+}{:<>?`1234567890-=[]''|,./SS";
private static final String INVALID_NAME_SPACE_FOR_INVALID_PREFIX = "try:#test3:9case3";
private static final String INVALID_NAME_SPACE1 = "byte:#test2:9test3";
private static final String INVALID_NAME_SPACE2 = "const:#test2://9test3";
private static final String VALID_NAME_SPACE1 = "yangautoprefixbyte.test2.yangautoprefix9test3";
private static final String INVALID_NAME_SPACE3 = "CONST:TRY://9test3";
private static final String VALID_NAME_SPACE1 = "123addprefixbyte.test2.123addprefix9test3";
private static final String VALID_NAME_SPACE2 = "yangautoprefixconst.test2.yangautoprefix9test3";
private static final String VALID_NAME_SPACE3 = "abc1234567890ssconst.test2.abc1234567890ss9test3";
private static final String VALID_NAME_SPACE4 = "yangautoprefixconst.yangautoprefixtry.yangautoprefix9test3";
private static final String WITHOUT_CAMEL_CASE = "test-camel-case-identifier";
private static final String WITH_CAMEL_CASE = "testCamelCaseIdentifier";
private static final String WITHOUT_CAMEL_CASE1 = ".-_try-._-.123";
......@@ -77,9 +90,16 @@ public final class JavaIdentifierSyntaxTest {
private static final String WITH_CAMEL_CASE11 = "test3Name";
private static final String WITHOUT_CAMEL_CASE12 = "TEST3name";
private static final String WITH_CAMEL_CASE12 = "test3Name";
private static final String WITHOUT_CAMEL_CASE13 = "t-RY";
private static final String WITH_CAMEL_CASE13 = "tRy";
private static final String WITHOUT_CAMEL_CASE14 = "TRY";
private static final String WITH_CAMEL_CASE14 = "yangAutoPrefixTry";
private static final String WITHOUT_CAPITAL = "test_this";
private static final String WITH_CAPITAL = "Test_this";
private static final String WITH_SMALL = "test_this";
private static final String WITH_CAMEL_CASE_WITH_PREFIX = "123addPrefixTry";
private static final String WITH_CAMEL_CASE_WITH_PREFIX1 = "abc1234567890Ss1123G123Gaa";
private static YangToJavaNamingConflictUtil conflictResolver = new YangToJavaNamingConflictUtil();
/**
* Unit test for private constructor.
......@@ -111,22 +131,44 @@ public final class JavaIdentifierSyntaxTest {
*/
@Test
public void getRootPackageTest() {
String rootPackage = getRootPackage((byte) 1, CHILD_PACKAGE, DATE1);
conflictResolver.setPrefixForIdentifier(null);
String rootPackage = getRootPackage((byte) 1, CHILD_PACKAGE, DATE1, conflictResolver);
assertThat(rootPackage.equals(DEFAULT_BASE_PKG + PERIOD + VERSION_NUMBER
+ PERIOD + CHILD_WITH_PERIOD + PERIOD + DATE_WITH_REV1), is(true));
}
/**
* Unit test for root package generation with invalid prefix.
*/
@Test
public void getRootPackageWithInvalidPrefix() throws TranslatorException {
thrown.expect(TranslatorException.class);
thrown.expectMessage("The given prefix in pom.xml is invalid.");
conflictResolver.setPrefixForIdentifier(INVALID_PREFIX);
String rootPackage1 = getRootPackage((byte) 1, INVALID_NAME_SPACE_FOR_INVALID_PREFIX, DATE1, conflictResolver);
}
/**
* Unit test for root package generation with special characters presence.
*/
@Test
public void getRootPackageWithSpecialCharactersTest() {
String rootPackage = getRootPackage((byte) 1, INVALID_NAME_SPACE1, DATE1);
conflictResolver.setPrefixForIdentifier(VALID_PREFIX);
String rootPackage = getRootPackage((byte) 1, INVALID_NAME_SPACE1, DATE1, conflictResolver);
assertThat(rootPackage.equals(DEFAULT_BASE_PKG + PERIOD + VERSION_NUMBER
+ PERIOD + VALID_NAME_SPACE1 + PERIOD + DATE_WITH_REV1), is(true));
String rootPackage1 = getRootPackage((byte) 1, INVALID_NAME_SPACE2, DATE1);
conflictResolver.setPrefixForIdentifier(null);
String rootPackage1 = getRootPackage((byte) 1, INVALID_NAME_SPACE2, DATE1, conflictResolver);
assertThat(rootPackage1.equals(DEFAULT_BASE_PKG + PERIOD + VERSION_NUMBER
+ PERIOD + VALID_NAME_SPACE2 + PERIOD + DATE_WITH_REV1), is(true));
String rootPackage2 = getRootPackage((byte) 1, INVALID_NAME_SPACE3, DATE1, conflictResolver);
assertThat(rootPackage2.equals(DEFAULT_BASE_PKG + PERIOD + VERSION_NUMBER
+ PERIOD + VALID_NAME_SPACE4 + PERIOD + DATE_WITH_REV1), is(true));
conflictResolver.setPrefixForIdentifier(INVALID_PREFIX1);
String rootPackage3 = getRootPackage((byte) 1, INVALID_NAME_SPACE2, DATE1, conflictResolver);
assertThat(rootPackage3.equals(DEFAULT_BASE_PKG + PERIOD + VERSION_NUMBER
+ PERIOD + VALID_NAME_SPACE3 + PERIOD + DATE_WITH_REV1), is(true));
}
/**
......@@ -134,7 +176,7 @@ public final class JavaIdentifierSyntaxTest {
*/
@Test
public void getRootPackageWithRevTest() {
String rootPkgWithRev = getRootPackage((byte) 1, CHILD_PACKAGE, DATE2);
String rootPkgWithRev = getRootPackage((byte) 1, CHILD_PACKAGE, DATE2, null);
assertThat(rootPkgWithRev.equals(
DEFAULT_BASE_PKG + PERIOD + VERSION_NUMBER + PERIOD + CHILD_WITH_PERIOD + PERIOD + DATE_WITH_REV2),
is(true));
......@@ -154,32 +196,63 @@ public final class JavaIdentifierSyntaxTest {
*/
@Test
public void getCamelCaseTest() {
String camelCase = getCamelCase(WITHOUT_CAMEL_CASE, null);
conflictResolver.setPrefixForIdentifier(null);
String camelCase = getCamelCase(WITHOUT_CAMEL_CASE, conflictResolver);
assertThat(camelCase.equals(WITH_CAMEL_CASE), is(true));
String camelCase1 = getCamelCase(WITHOUT_CAMEL_CASE1, null);
String camelCase1 = getCamelCase(WITHOUT_CAMEL_CASE1, conflictResolver);
assertThat(camelCase1.equals(WITH_CAMEL_CASE1), is(true));
String camelCase2 = getCamelCase(WITHOUT_CAMEL_CASE2, null);
String camelCase2 = getCamelCase(WITHOUT_CAMEL_CASE2, conflictResolver);
assertThat(camelCase2.equals(WITH_CAMEL_CASE2), is(true));
String camelCase3 = getCamelCase(WITHOUT_CAMEL_CASE3, null);
String camelCase3 = getCamelCase(WITHOUT_CAMEL_CASE3, conflictResolver);
assertThat(camelCase3.equals(WITH_CAMEL_CASE3), is(true));
String camelCase4 = getCamelCase(WITHOUT_CAMEL_CASE4, null);
String camelCase4 = getCamelCase(WITHOUT_CAMEL_CASE4, conflictResolver);
assertThat(camelCase4.equals(WITH_CAMEL_CASE4), is(true));
String camelCase5 = getCamelCase(WITHOUT_CAMEL_CASE5, null);
String camelCase5 = getCamelCase(WITHOUT_CAMEL_CASE5, conflictResolver);
assertThat(camelCase5.equals(WITH_CAMEL_CASE5), is(true));
String camelCase6 = getCamelCase(WITHOUT_CAMEL_CASE6, null);
String camelCase6 = getCamelCase(WITHOUT_CAMEL_CASE6, conflictResolver);
assertThat(camelCase6.equals(WITH_CAMEL_CASE6), is(true));
String camelCase7 = getCamelCase(WITHOUT_CAMEL_CASE7, null);
String camelCase7 = getCamelCase(WITHOUT_CAMEL_CASE7, conflictResolver);
assertThat(camelCase7.equals(WITH_CAMEL_CASE7), is(true));
String camelCase8 = getCamelCase(WITHOUT_CAMEL_CASE8, null);
String camelCase8 = getCamelCase(WITHOUT_CAMEL_CASE8, conflictResolver);
assertThat(camelCase8.equals(WITH_CAMEL_CASE8), is(true));
String camelCase9 = getCamelCase(WITHOUT_CAMEL_CASE9, null);
String camelCase9 = getCamelCase(WITHOUT_CAMEL_CASE9, conflictResolver);
assertThat(camelCase9.equals(WITH_CAMEL_CASE9), is(true));
String camelCase10 = getCamelCase(WITHOUT_CAMEL_CASE10, null);
String camelCase10 = getCamelCase(WITHOUT_CAMEL_CASE10, conflictResolver);
assertThat(camelCase10.equals(WITH_CAMEL_CASE10), is(true));
String camelCase11 = getCamelCase(WITHOUT_CAMEL_CASE11, null);
String camelCase11 = getCamelCase(WITHOUT_CAMEL_CASE11, conflictResolver);
assertThat(camelCase11.equals(WITH_CAMEL_CASE11), is(true));
String camelCase12 = getCamelCase(WITHOUT_CAMEL_CASE12, null);
String camelCase12 = getCamelCase(WITHOUT_CAMEL_CASE12, conflictResolver);
assertThat(camelCase12.equals(WITH_CAMEL_CASE12), is(true));
String camelCase13 = getCamelCase(WITHOUT_CAMEL_CASE13, conflictResolver);
assertThat(camelCase13.equals(WITH_CAMEL_CASE13), is(true));
String camelCase14 = getCamelCase(WITHOUT_CAMEL_CASE14, conflictResolver);
assertThat(camelCase14.equals(WITH_CAMEL_CASE14), is(true));
}
/**
* Unit test for getting the camel case along with the prefix provided.
*/
@Test
public void getCamelCaseWithPrefixTest() {
conflictResolver.setPrefixForIdentifier(VALID_PREFIX);
String camelCase = getCamelCase(WITHOUT_CAMEL_CASE2, conflictResolver);
assertThat(camelCase.equals(WITH_CAMEL_CASE_WITH_PREFIX), is(true));
conflictResolver.setPrefixForIdentifier(INVALID_PREFIX1);
String camelCase2 = getCamelCase(WITHOUT_CAMEL_CASE3, conflictResolver);
assertThat(camelCase2.equals(WITH_CAMEL_CASE_WITH_PREFIX1), is(true));
}
/**
* Unit test for getting the camel case along with the invalid prefix provided.
*/
@Test
public void getCamelCaseWithInvalidPrefixTest() throws TranslatorException {
thrown.expect(TranslatorException.class);
thrown.expectMessage("The given prefix in pom.xml is invalid.");
conflictResolver.setPrefixForIdentifier(INVALID_PREFIX);
String camelCase = getCamelCase(WITHOUT_CAMEL_CASE3, conflictResolver);
}
/**
......
......@@ -29,6 +29,7 @@ import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import static org.onosproject.yangutils.datamodel.YangDataTypes.STRING;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_SERVICE_AND_MANAGER;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCapitalCase;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getBuild;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getBuildForInterface;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getCheckNotNull;
......@@ -105,7 +106,7 @@ public final class MethodsGeneratorTest {
throws SecurityException, NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InvocationTargetException {
Class<?>[] classesToConstruct = {MethodsGenerator.class};
Class<?>[] classesToConstruct = {MethodsGenerator.class };
for (Class<?> clazz : classesToConstruct) {
Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
......@@ -118,8 +119,10 @@ public final class MethodsGeneratorTest {
*/
@Test
public void getTypeConstructorTest() {
YangPluginConfig pluginConfig = new YangPluginConfig();
JavaAttributeInfo testAttr = getTestAttribute();
String test = getTypeConstructorStringAndJavaDoc(testAttr, CLASS_NAME);
String test = getTypeConstructorStringAndJavaDoc(testAttr, CLASS_NAME, pluginConfig);
assertThat(true, is(test.contains(PUBLIC + SPACE + CLASS_NAME + OPEN_PARENTHESIS)));
}
......@@ -162,7 +165,8 @@ public final class MethodsGeneratorTest {
@Test
public void getConstructorTest() {
JavaAttributeInfo testAttr = getTestAttribute();
String method = getConstructor(CLASS_NAME, testAttr, GENERATE_SERVICE_AND_MANAGER);
YangPluginConfig pluginConfig = new YangPluginConfig();
String method = getConstructor(CLASS_NAME, testAttr, GENERATE_SERVICE_AND_MANAGER, pluginConfig);
assertThat(true, is(method.contains(THIS + PERIOD + CLASS_NAME + SPACE + EQUAL + SPACE + "builder" + OBJECT
+ PERIOD + GET_METHOD_PREFIX + "Testname" + OPEN_PARENTHESIS + CLOSE_PARENTHESIS + SEMI_COLAN)));
}
......@@ -172,7 +176,8 @@ public final class MethodsGeneratorTest {
*/
@Test
public void getConstructorStartTest() {
String method = getConstructorStart(CLASS_NAME);
YangPluginConfig pluginConfig = new YangPluginConfig();
String method = getConstructorStart(CLASS_NAME, pluginConfig);
assertThat(true, is(method.contains(PUBLIC + SPACE + CLASS_NAME + IMPL + OPEN_PARENTHESIS + CLASS_NAME
+ BUILDER + SPACE + BUILDER.toLowerCase() + OBJECT + CLOSE_PARENTHESIS + SPACE
+ OPEN_CURLY_BRACKET + NEW_LINE)));
......@@ -227,10 +232,10 @@ public final class MethodsGeneratorTest {
public void getSetterForClassTest() {
JavaAttributeInfo testAttr = getTestAttribute();
String method = getSetterForClass(testAttr, CLASS_NAME, GENERATE_SERVICE_AND_MANAGER);
// assertThat(true, is(
// method.contains(PUBLIC + SPACE + CLASS_NAME + BUILDER + SPACE + SET_METHOD_PREFIX
// + getCaptialCase(ATTRIBUTE_NAME) + OPEN_PARENTHESIS + STRING_DATA_TYPE + SPACE
// + ATTRIBUTE_NAME)));
assertThat(true, is(
method.contains(PUBLIC + SPACE + VOID + SPACE +
SET_METHOD_PREFIX + getCapitalCase(CLASS_NAME) + OPEN_PARENTHESIS +
STRING_DATA_TYPE + SPACE + ATTRIBUTE_NAME)));
}
/**
......@@ -240,7 +245,8 @@ public final class MethodsGeneratorTest {
public void getSetterForInterfaceTest() {
String method = getSetterForInterface(CLASS_NAME, STRING_DATA_TYPE, CLASS_NAME, false,
GENERATE_SERVICE_AND_MANAGER);
// assertThat(true, is(method.contains(CLASS_NAME + BUILDER + SPACE + SET_METHOD_PREFIX + "Testname")));
assertThat(true, is(method.contains(VOID + SPACE +
SET_METHOD_PREFIX + "Testname")));
}
/**
......
......@@ -46,7 +46,7 @@ public final class NotificationTranslatorTest {
YangPluginConfig yangPluginConfig = new YangPluginConfig();
yangPluginConfig.setCodeGenDir(userDir + "/target/NotificationTest/");
generateJavaCode(node, yangPluginConfig, "NotificationTest");
generateJavaCode(node, yangPluginConfig);
deleteDirectory(userDir + "/target/NotificationTest/");
}
......
......@@ -46,7 +46,7 @@ public final class RpcTranslatorTest {
YangPluginConfig yangPluginConfig = new YangPluginConfig();
yangPluginConfig.setCodeGenDir(userDir + "/target/RpcTestGenFile/");
generateJavaCode(node, yangPluginConfig, "RpcTranslator");
generateJavaCode(node, yangPluginConfig);
deleteDirectory(userDir + "/target/RpcTestGenFile/");
}
......
......@@ -46,7 +46,7 @@ public final class UnionTranslatorTest {
YangPluginConfig yangPluginConfig = new YangPluginConfig();
yangPluginConfig.setCodeGenDir("target/UnionTestGenFile/");
generateJavaCode(node, yangPluginConfig, "UnionTranslator");
generateJavaCode(node, yangPluginConfig);
deleteDirectory(userDir + "/target/UnionTestGenFile/");
}
......
......@@ -25,6 +25,7 @@ import org.junit.Test;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
......@@ -125,7 +126,20 @@ public final class FileSystemUtilTest {
javafileInfo.setJavaName(TEST_DATA_1);
javafileInfo.setBaseCodeGenPath("");
javafileInfo.setPackageFilePath(BASE_PKG);
javafileInfo.setPluginConfig(getStubPluginConfig());
module.setJavaFileInfo(javafileInfo);
return module;
}
/**
* Returns stub pluginConfig.
*
* @return stub pluginConfig
*/
private YangPluginConfig getStubPluginConfig() {
YangPluginConfig pluginConfig = new YangPluginConfig();
pluginConfig.setConflictResolver(null);
return pluginConfig;
}
}
......
......@@ -22,6 +22,7 @@ import java.lang.reflect.InvocationTargetException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
......@@ -55,7 +56,7 @@ public final class JavaDocGenTest {
*/
@Test
public void builderClassGenerationTest() {
String builderClassJavaDoc = getJavaDoc(BUILDER_CLASS, TEST_NAME, false);
String builderClassJavaDoc = getJavaDoc(BUILDER_CLASS, TEST_NAME, false, getStubPluginConfig());
assertThat(true, is(builderClassJavaDoc.contains("Represents the builder implementation of")
&& builderClassJavaDoc.contains(END_STRING)));
}
......@@ -65,9 +66,10 @@ public final class JavaDocGenTest {
*/
@Test
public void builderInterfaceGenerationTest() {
String builderInterfaceJavaDoc = getJavaDoc(BUILDER_INTERFACE, TEST_NAME, false);
String builderInterfaceJavaDoc = getJavaDoc(BUILDER_INTERFACE, TEST_NAME, false, getStubPluginConfig());
assertThat(true,
is(builderInterfaceJavaDoc.contains("Builder for") && builderInterfaceJavaDoc.contains(END_STRING)));
is(builderInterfaceJavaDoc.contains("Builder for")
&& builderInterfaceJavaDoc.contains(END_STRING)));
}
/**
......@@ -75,7 +77,7 @@ public final class JavaDocGenTest {
*/
@Test
public void buildGenerationTest() {
String buildDoc = getJavaDoc(BUILD_METHOD, TEST_NAME, false);
String buildDoc = getJavaDoc(BUILD_METHOD, TEST_NAME, false, getStubPluginConfig());
assertThat(true, is(buildDoc.contains("Builds object of") && buildDoc.contains(END_STRING)));
}
......@@ -90,7 +92,8 @@ public final class JavaDocGenTest {
* @throws InvocationTargetException when an exception occurs by the method or constructor
*/
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
public void callPrivateConstructors()
throws SecurityException, NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InvocationTargetException {
Class<?>[] classesToConstruct = {JavaDocGen.class };
......@@ -106,9 +109,10 @@ public final class JavaDocGenTest {
*/
@Test
public void constructorGenerationTest() {
String constructorDoc = getJavaDoc(CONSTRUCTOR, TEST_NAME, false);
String constructorDoc = getJavaDoc(CONSTRUCTOR, TEST_NAME, false, getStubPluginConfig());
assertThat(true,
is(constructorDoc.contains("Creates an instance of ") && constructorDoc.contains("builder object of")
is(constructorDoc.contains("Creates an instance of ")
&& constructorDoc.contains("builder object of")
&& constructorDoc.contains("@param") && constructorDoc.contains("*/\n")));
}
......@@ -117,7 +121,7 @@ public final class JavaDocGenTest {
*/
@Test
public void defaultConstructorGenerationTest() {
String defaultConstructorDoc = getJavaDoc(DEFAULT_CONSTRUCTOR, TEST_NAME, false);
String defaultConstructorDoc = getJavaDoc(DEFAULT_CONSTRUCTOR, TEST_NAME, false, getStubPluginConfig());
assertThat(true, is(defaultConstructorDoc.contains("Creates an instance of ")
&& defaultConstructorDoc.contains(END_STRING)));
}
......@@ -127,8 +131,9 @@ public final class JavaDocGenTest {
*/
@Test
public void getterGenerationTest() {
String getterJavaDoc = getJavaDoc(GETTER_METHOD, TEST_NAME, false);
assertThat(true, is(getterJavaDoc.contains("Returns the attribute") && getterJavaDoc.contains(END_STRING)));
String getterJavaDoc = getJavaDoc(GETTER_METHOD, TEST_NAME, false, getStubPluginConfig());
assertThat(true,
is(getterJavaDoc.contains("Returns the attribute") && getterJavaDoc.contains(END_STRING)));
}
/**
......@@ -136,7 +141,7 @@ public final class JavaDocGenTest {
*/
@Test
public void implClassGenerationTest() {
String implClassJavaDoc = getJavaDoc(IMPL_CLASS, TEST_NAME, false);
String implClassJavaDoc = getJavaDoc(IMPL_CLASS, TEST_NAME, false, getStubPluginConfig());
assertThat(true,
is(implClassJavaDoc.contains("Represents the implementation of")
&& implClassJavaDoc.contains(END_STRING)));
......@@ -147,7 +152,7 @@ public final class JavaDocGenTest {
*/
@Test
public void interfaceGenerationTest() {
String interfaceJavaDoc = getJavaDoc(INTERFACE, TEST_NAME, false);
String interfaceJavaDoc = getJavaDoc(INTERFACE, TEST_NAME, false, getStubPluginConfig());
assertThat(true,
is(interfaceJavaDoc.contains("Abstraction of an entity which represents the functionality of")
&& interfaceJavaDoc.contains(END_STRING)));
......@@ -158,8 +163,9 @@ public final class JavaDocGenTest {
*/
@Test
public void packageInfoGenerationTest() {
String packageInfo = getJavaDoc(PACKAGE_INFO, TEST_NAME, false);
assertThat(true, is(packageInfo.contains("Implementation of YANG node") && packageInfo.contains(END_STRING)));
String packageInfo = getJavaDoc(PACKAGE_INFO, TEST_NAME, false, getStubPluginConfig());
assertThat(true,
is(packageInfo.contains("Implementation of YANG node") && packageInfo.contains(END_STRING)));
}
/**
......@@ -167,7 +173,7 @@ public final class JavaDocGenTest {
*/
@Test
public void packageInfoGenerationForChildNodeTest() {
String packageInfo = getJavaDoc(PACKAGE_INFO, TEST_NAME, true);
String packageInfo = getJavaDoc(PACKAGE_INFO, TEST_NAME, true, getStubPluginConfig());
assertThat(true, is(packageInfo.contains("Implementation of YANG node testName's children nodes")
&& packageInfo.contains(END_STRING)));
}
......@@ -177,7 +183,7 @@ public final class JavaDocGenTest {
*/
@Test
public void setterGenerationTest() {
String setterJavaDoc = getJavaDoc(SETTER_METHOD, TEST_NAME, false);
String setterJavaDoc = getJavaDoc(SETTER_METHOD, TEST_NAME, false, getStubPluginConfig());
assertThat(true,
is(setterJavaDoc.contains("Returns the builder object of") && setterJavaDoc.contains(END_STRING)));
}
......@@ -187,7 +193,18 @@ public final class JavaDocGenTest {
*/
@Test
public void typeDefSetterGenerationTest() {
String typeDefSetter = getJavaDoc(TYPE_DEF_SETTER_METHOD, TEST_NAME, false);
String typeDefSetter = getJavaDoc(TYPE_DEF_SETTER_METHOD, TEST_NAME, false, getStubPluginConfig());
assertThat(true, is(typeDefSetter.contains("Sets the value of") && typeDefSetter.contains(END_STRING)));
}
/**
* Returns stub pluginConfig.
*
* @return stub pluginConfig
*/
private YangPluginConfig getStubPluginConfig() {
YangPluginConfig pluginConfig = new YangPluginConfig();
pluginConfig.setConflictResolver(null);
return pluginConfig;
}
}
\ No newline at end of file
......
......@@ -25,6 +25,7 @@ import org.apache.maven.project.MavenProject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onosproject.yangutils.translator.tojava.utils.YangPluginConfig;
import org.onosproject.yangutils.utils.UtilConstants;
import org.sonatype.plexus.build.incremental.BuildContext;
import org.sonatype.plexus.build.incremental.DefaultBuildContext;
......@@ -68,7 +69,7 @@ public final class YangIoUtilsTest {
File dirPath = new File(CREATE_PATH);
dirPath.mkdirs();
addPackageInfo(dirPath, CHECK1, CREATE_PATH, false);
addPackageInfo(dirPath, CHECK1, CREATE_PATH, false, getStubPluginConfig());
File filePath = new File(dirPath + File.separator + PKG_INFO);
assertThat(filePath.isFile(), is(true));
}
......@@ -83,7 +84,7 @@ public final class YangIoUtilsTest {
File dirPath = new File(CREATE_PATH);
dirPath.mkdirs();
addPackageInfo(dirPath, CHECK1, PATH + CREATE_PATH, false);
addPackageInfo(dirPath, CHECK1, PATH + CREATE_PATH, false, getStubPluginConfig());
File filePath = new File(dirPath + File.separator + PKG_INFO);
assertThat(filePath.isFile(), is(true));
}
......@@ -98,7 +99,7 @@ public final class YangIoUtilsTest {
File dirPath = new File(CREATE_PATH);
dirPath.mkdirs();
addPackageInfo(dirPath, CHECK1, PATH + CREATE_PATH, true);
addPackageInfo(dirPath, CHECK1, PATH + CREATE_PATH, true, getStubPluginConfig());
File filePath = new File(dirPath + File.separator + PKG_INFO);
assertThat(filePath.isFile(), is(true));
}
......@@ -114,7 +115,7 @@ public final class YangIoUtilsTest {
File dirPath = new File("invalid/check");
thrown.expect(IOException.class);
thrown.expectMessage(MSG);
addPackageInfo(dirPath, CHECK1, CREATE_PATH, false);
addPackageInfo(dirPath, CHECK1, CREATE_PATH, false, getStubPluginConfig());
File filePath1 = new File(dirPath + File.separator + PKG_INFO);
assertThat(filePath1.isFile(), is(false));
}
......@@ -130,7 +131,8 @@ public final class YangIoUtilsTest {
* @throws InvocationTargetException when an exception occurs by the method or constructor
*/
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
public void callPrivateConstructors()
throws SecurityException, NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InvocationTargetException {
Class<?>[] classesToConstruct = {YangIoUtils.class };
......@@ -192,7 +194,7 @@ public final class YangIoUtilsTest {
addToSource(sourceDir.toString(), project, context);
}
/*
/**
* Unit test case for trim at last method.
*/
@Test
......@@ -202,4 +204,14 @@ public final class YangIoUtilsTest {
assertThat(test.contains(TRIM_STRING), is(true));
}
/**
* Returns stub pluginConfig.
*
* @return stub pluginConfig
*/
private YangPluginConfig getStubPluginConfig() {
YangPluginConfig pluginConfig = new YangPluginConfig();
pluginConfig.setConflictResolver(null);
return pluginConfig;
}
}
......
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
typedef type15 {
type bits {
bit disable-nagle {
position 0;
}
bit auto-sense-speed {
position 1;
}
bit Mb-only {
position 2;
}
}
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
leaf type15 {
type union {
type bits {
bit disable-nagle {
position 0;
}
bit auto-sense-speed {
position 1;
}
bit Mb-only {
position 2;
}
}
}
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
leaf ifType {
type enumeration {
enum four{
value 7;
}
enum seven {
value 2147483647;
}
enum five {
value 5;
}
}
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
grouping currentcheck {
leaf invalid-interval {
type identityref {
}
}
}
}
module xMlTest {
yang-version 1;
namespace urn:ietf:params:xml:ns:yang:ietf-ospf;
prefix On;
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
container currentcheck {
leaf invalid-interval {
type instance-identifier;
}
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
leaf-list invalid-interval {
type leafref;
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
leaf invalid-interval {
type string {
length " 0 .. 100 ";
}
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
leaf-list invalid-interval {
type "uint16";
max-elements 77777777777777777777777;
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
leaf-list invalid-interval {
type "uint16";
min-elements 77777777777777777777777;
}
}
......@@ -11,5 +11,5 @@ module Test {
bit Ten-Mb-only;
}
}
}
}
......
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
container food {
choice snack {
list sports-arena {
}
}
}
}
}
}
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
import ietf-yang-types {
prefix "P";
}
grouping Percentage {
leaf hello{
type string;
}
leaf invalid1{
type string;
}
}
leaf invalid2{
type string;
}
}
container ospf {
list valid {
key "invalid";
leaf invalid{
type string;
}
uses Ant:FirstClass;
grouping FirstClass {
uses P:PassingClass;
}
}
grouping PassingClass {
uses Ant:Percentage;
}
}
}
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
container food {
choice snack {
list sports-arena {
}
}
}
}
leaf invalid {
module Test {
yang-version 1;
namespace http://huawei.com;
prefix Ant;
leaf invalid-interval {
type int32 {
range " 1 .. 4 | 10 .. 20 ";
}
}
}
......@@ -14,7 +14,7 @@ module rock {
type int32;
}
leaf if-name {
type leafref;
type string;
}
leaf if-admin-status {
type P:admin-status;
......