Vinod Kumar S
Committed by Gerrit Code Review

YANG Translator optimization

Change-Id: Ie6a6b9d371a4fc5fd973cf56d6f3c7b44a3146ba
Showing 70 changed files with 4898 additions and 2630 deletions
......@@ -21,7 +21,6 @@ import java.util.List;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.utils.YangConstructType;
import org.onosproject.yangutils.translator.CachedFileHandle;
/*-
* Reference RFC 6020.
......@@ -77,7 +76,8 @@ import org.onosproject.yangutils.translator.CachedFileHandle;
/**
* Data model node to maintain information defined in YANG augment.
*/
public class YangAugment extends YangNode implements YangLeavesHolder, YangCommonInfo, Parsable {
public class YangAugment extends YangNode
implements YangLeavesHolder, YangCommonInfo, Parsable {
/**
* Augment target node.
......@@ -110,11 +110,6 @@ public class YangAugment extends YangNode implements YangLeavesHolder, YangCommo
private YangStatusType status;
/**
* Package of the generated java code.
*/
private String pkg;
/**
* Create a YANG augment node.
*/
public YangAugment() {
......@@ -316,57 +311,4 @@ public class YangAugment extends YangNode implements YangLeavesHolder, YangCommo
}
/**
* Get the mapped java package.
*
* @return the java package
*/
@Override
public String getPackage() {
return pkg;
}
/**
* Set the mapped java package.
*
* @param pakg the package to set
*/
@Override
public void setPackage(String pakg) {
pkg = pakg;
}
/**
* Prepare the information for java code generation corresponding to YANG
* grouping info.
*
* @param codeGenDir code generation directory
*/
@Override
public void generateJavaCodeEntry(String codeGenDir) {
// TODO Auto-generated method stub
}
/**
* Create a java file using the YANG grouping info.
*/
@Override
public void generateJavaCodeExit() {
// TODO Auto-generated method stub
}
@Override
public CachedFileHandle getFileHandle() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFileHandle(CachedFileHandle fileHandle) {
// TODO Auto-generated method stub
}
}
......
......@@ -15,15 +15,15 @@
*/
package org.onosproject.yangutils.datamodel;
import java.util.LinkedList;
import java.util.List;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.utils.YangConstructType;
import static org.onosproject.yangutils.utils.YangConstructType.CASE_DATA;
import java.util.LinkedList;
import java.util.List;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
import static org.onosproject.yangutils.utils.YangConstructType.CASE_DATA;
/*-
* Reference RFC 6020.
......@@ -127,11 +127,6 @@ public class YangCase extends YangNode
private YangStatusType status;
/**
* Package of the generated java code.
*/
private String pkg;
/**
* Create a choice node.
*/
public YangCase() {
......@@ -314,76 +309,23 @@ public class YangCase extends YangNode
// TODO auto-generated method stub, to be implemented by parser
}
/**
* Get the mapped java package.
*
* @return the java package
*/
@Override
public String getPackage() {
return pkg;
}
/**
* Set the mapped java package.
*
* @param pakg the package to set
*/
@Override
public void setPackage(String pakg) {
pkg = pakg;
}
/**
* Generate the code corresponding to YANG case info.
*
* @param codeGenDir code generation directory
*/
@Override
public void generateJavaCodeEntry(String codeGenDir) {
// TODO Auto-generated method stub
}
/**
* Free resource used for generating code and generate valid java files
* corresponding to YANG case info.
*/
@Override
public void generateJavaCodeExit() {
// TODO Auto-generated method stub
}
@Override
public CachedFileHandle getFileHandle() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFileHandle(CachedFileHandle fileHandle) {
// TODO Auto-generated method stub
}
@Override
public void detectCollidingChild(String identifierName, YangConstructType dataType) throws DataModelException {
if ((this.getParent() == null) || (!(this.getParent() instanceof YangChoice))) {
if (getParent() == null || !(getParent() instanceof YangChoice)) {
throw new DataModelException("Internal Data Model Tree Error: Invalid/Missing holder in case " +
this.getName());
getName());
}
// Traverse up in tree to ask parent choice start collision detection.
((CollisionDetector) this.getParent()).detectCollidingChild(identifierName, dataType);
((CollisionDetector) getParent()).detectCollidingChild(identifierName, dataType);
}
@Override
public void detectSelfCollision(String identifierName, YangConstructType dataType) throws DataModelException {
if (dataType == CASE_DATA) {
if (this.getName().equals(identifierName)) {
if (getName().equals(identifierName)) {
throw new DataModelException("YANG File Error: Identifier collision detected in case \"" +
this.getName() + "\"");
getName() + "\"");
}
return;
}
......
......@@ -17,8 +17,8 @@ package org.onosproject.yangutils.datamodel;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.utils.YangConstructType;
import static org.onosproject.yangutils.utils.YangConstructType.CHOICE_DATA;
/*-
......@@ -140,11 +140,21 @@ public class YangChoice extends YangNode implements YangCommonInfo, Parsable, Co
super(YangNodeType.CHOICE_NODE);
}
/**
* Get the choice name.
*
* @return choice name
*/
@Override
public String getName() {
return name;
}
/**
* Set the choice name.
*
* @param name choice name
*/
@Override
public void setName(String name) {
this.name = name;
......@@ -295,46 +305,13 @@ public class YangChoice extends YangNode implements YangCommonInfo, Parsable, Co
}
@Override
public String getPackage() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setPackage(String pkg) {
// TODO Auto-generated method stub
}
@Override
public void generateJavaCodeEntry(String codeGenDir) {
// TODO Auto-generated method stub
}
@Override
public void generateJavaCodeExit() {
// TODO Auto-generated method stub
}
@Override
public CachedFileHandle getFileHandle() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFileHandle(CachedFileHandle fileHandle) {
// TODO Auto-generated method stub
}
@Override
public void detectCollidingChild(String identifierName, YangConstructType dataType) throws DataModelException {
YangNode node = this.getChild();
while ((node != null)) {
if (this.getParent() instanceof YangCase && dataType != YangConstructType.CASE_DATA) {
((CollisionDetector) getParent()).detectCollidingChild(identifierName, dataType);
}
YangNode node = getChild();
while (node != null) {
if (node instanceof CollisionDetector) {
((CollisionDetector) node).detectSelfCollision(identifierName, dataType);
}
......@@ -346,15 +323,15 @@ public class YangChoice extends YangNode implements YangCommonInfo, Parsable, Co
public void detectSelfCollision(String identifierName, YangConstructType dataType) throws DataModelException {
if (dataType == CHOICE_DATA) {
if (this.getName().equals(identifierName)) {
if (getName().equals(identifierName)) {
throw new DataModelException("YANG file error: Identifier collision detected in choice \"" +
this.getName() + "\"");
getName() + "\"");
}
return;
}
YangNode node = this.getChild();
while ((node != null)) {
YangNode node = getChild();
while (node != null) {
if (node instanceof CollisionDetector) {
((CollisionDetector) node).detectSelfCollision(identifierName, dataType);
}
......
......@@ -16,20 +16,15 @@
package org.onosproject.yangutils.datamodel;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax;
import org.onosproject.yangutils.utils.UtilConstants;
import org.onosproject.yangutils.utils.YangConstructType;
import org.onosproject.yangutils.utils.io.impl.FileSystemUtil;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
/*-
* Reference RFC 6020.
*
......@@ -136,16 +131,6 @@ public class YangContainer extends YangNode implements YangLeavesHolder, YangCom
private YangStatusType status = YangStatusType.CURRENT;
/**
* Package of the generated java code.
*/
private String pkg;
/**
* Cached Java File Handle.
*/
private CachedFileHandle fileHandle;
/**
* Create a container node.
*/
public YangContainer() {
......@@ -335,26 +320,6 @@ public class YangContainer extends YangNode implements YangLeavesHolder, YangCom
}
/**
* Get the cached file handle.
*
* @return the fileHandle
*/
@Override
public CachedFileHandle getFileHandle() {
return fileHandle;
}
/**
* Set the cached file handle.
*
* @param handle the fileHandle to set
*/
@Override
public void setFileHandle(CachedFileHandle handle) {
fileHandle = handle;
}
/**
* Returns the type of the data.
*
* @return returns CONTAINER_DATA
......@@ -435,7 +400,7 @@ public class YangContainer extends YangNode implements YangLeavesHolder, YangCom
* If a node has "config" set to "false", no node underneath it can have
* "config" set to "true".
*/
if ((!isConfig) && (leaves != null)) {
if (!isConfig && leaves != null) {
for (YangLeaf leaf : leaves) {
if (leaf.isConfig()) {
throw new DataModelException("If a container has \"config\" set to \"false\", no node underneath " +
......@@ -444,7 +409,7 @@ public class YangContainer extends YangNode implements YangLeavesHolder, YangCom
}
}
if ((!isConfig) && (leafLists != null)) {
if (!isConfig && leafLists != null) {
for (YangLeafList leafList : leafLists) {
if (leafList.isConfig()) {
throw new DataModelException("If a container has \"config\" set to \"false\", no node underneath " +
......@@ -454,98 +419,6 @@ public class YangContainer extends YangNode implements YangLeavesHolder, YangCom
}
}
/**
* Get the mapped java package.
*
* @return the java package
*/
@Override
public String getPackage() {
return pkg;
}
/**
* Set the mapped java package.
*
* @param pcg the package to set
*/
@Override
public void setPackage(String pcg) {
pkg = pcg;
}
/**
* Generate the java code corresponding to YANG container.
*
* @param codeGenDir code generation directory
* @throws IOException when fails to generate the source files.
*/
@Override
public void generateJavaCodeEntry(String codeGenDir) throws IOException {
YangNode parent = getParent();
String contPkg = JavaIdentifierSyntax.getPackageFromParent(parent.getPackage(), parent.getName());
contPkg = JavaIdentifierSyntax.getCamelCase(contPkg).toLowerCase();
setPackage(contPkg);
CachedFileHandle handle = null;
try {
FileSystemUtil.createPackage(codeGenDir + getPackage(), parent.getName() + UtilConstants.CHILDREN);
handle = FileSystemUtil.createSourceFiles(getPackage(), getName(),
GeneratedFileType.GENERATE_INTERFACE_WITH_BUILDER);
handle.setRelativeFilePath(getPackage().replace(".", "/"));
handle.setCodeGenFilePath(codeGenDir);
} catch (IOException e) {
throw new IOException("Failed to create the source files.");
}
setFileHandle(handle);
addLeavesAttributes();
addLeafListAttributes();
addAttributeInParent();
}
/**
* Adds current node attribute to parent file.
*/
private void addAttributeInParent() {
if (getParent() != null) {
getParent().getFileHandle().addAttributeInfo(null, getName(), false);
}
}
@Override
public void generateJavaCodeExit() throws IOException {
getFileHandle().close();
return;
}
/**
* Adds leaf attributes in generated files.
*/
private void addLeavesAttributes() {
List<YangLeaf> leaves = getListOfLeaf();
if (leaves != null) {
for (YangLeaf leaf : leaves) {
getFileHandle().addAttributeInfo(leaf.getDataType(), leaf.getLeafName(), false);
}
}
}
/**
* Adds leaf list's attributes in generated files.
*/
private void addLeafListAttributes() {
List<YangLeafList> leavesList = getListOfLeafList();
if (leavesList != null) {
for (YangLeafList leafList : leavesList) {
getFileHandle().addAttributeInfo(leafList.getDataType(), leafList.getLeafName(), true);
}
}
return;
}
@Override
public void detectCollidingChild(String identifierName, YangConstructType dataType) throws DataModelException {
// Asks helper to detect colliding child.
......@@ -554,9 +427,9 @@ public class YangContainer extends YangNode implements YangLeavesHolder, YangCom
@Override
public void detectSelfCollision(String identifierName, YangConstructType dataType) throws DataModelException {
if (this.getName().equals(identifierName)) {
if (getName().equals(identifierName)) {
throw new DataModelException("YANG file error: Duplicate input identifier detected, same as container \""
+ this.getName() + "\"");
+ getName() + "\"");
}
}
}
......
......@@ -21,7 +21,6 @@ import java.util.List;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.utils.YangConstructType;
import org.onosproject.yangutils.translator.CachedFileHandle;
/*-
* Reference RFC 6020.
......@@ -110,11 +109,6 @@ public class YangGrouping extends YangNode
private YangStatusType status;
/**
* Package of the generated java code.
*/
private String pkg;
/**
* Creates the grouping node.
*/
public YangGrouping() {
......@@ -296,58 +290,4 @@ public class YangGrouping extends YangNode
public void validateDataOnExit() throws DataModelException {
// TODO auto-generated method stub, to be implemented by parser
}
/**
* Generate the code for YANG grouping.
*
* @param codeGenDir code generated directory.
*/
@Override
public void generateJavaCodeEntry(String codeGenDir) {
// TODO Auto-generated method stub
}
/**
* Free the resources used to generate java files corresponding to YANG
* grouping info and generate valid java files.
*/
@Override
public void generateJavaCodeExit() {
// TODO Auto-generated method stub
}
/**
* Get the mapped java package.
*
* @return the java package
*/
@Override
public String getPackage() {
return pkg;
}
/**
* Set the mapped java package.
*
* @param pakg the package to set
*/
@Override
public void setPackage(String pakg) {
pkg = pakg;
}
@Override
public CachedFileHandle getFileHandle() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFileHandle(CachedFileHandle fileHandle) {
// TODO Auto-generated method stub
}
}
......
......@@ -16,16 +16,16 @@
package org.onosproject.yangutils.datamodel;
import java.util.LinkedList;
import java.util.List;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.utils.YangConstructType;
import java.util.LinkedList;
import java.util.List;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
/*-
/*
* The "list" statement is used to define an interior data node in the
* schema tree. A list node may exist in multiple instances in the data
* tree. Each such instance is known as a list entry. The "list"
......@@ -166,11 +166,6 @@ public class YangList extends YangNode
private YangStatusType status = YangStatusType.CURRENT;
/**
* Package of the generated java code.
*/
private String pkg;
/**
* Constructor.
*/
public YangList() {
......@@ -619,61 +614,6 @@ public class YangList extends YangNode
}
}
/**
* Populate the cached handle with information about the list attributes to
* generate java code.
*
* @param codeGenDir code generated directory
*/
@Override
public void generateJavaCodeEntry(String codeGenDir) {
// TODO Auto-generated method stub
}
/**
* Free the resources used to generate the java file corresponding to YANG
* list info.
*/
@Override
public void generateJavaCodeExit() {
// TODO Auto-generated method stub
}
/**
* Get the mapped java package.
*
* @return the java package
*/
@Override
public String getPackage() {
return pkg;
}
/**
* Set the mapped java package.
*
* @param pakg the package to set
*/
@Override
public void setPackage(String pakg) {
pkg = pakg;
}
@Override
public CachedFileHandle getFileHandle() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFileHandle(CachedFileHandle fileHandle) {
// TODO Auto-generated method stub
}
@Override
public void detectCollidingChild(String identifierName, YangConstructType dataType) throws DataModelException {
// Asks helper to detect colliding child.
......@@ -682,9 +622,9 @@ public class YangList extends YangNode
@Override
public void detectSelfCollision(String identifierName, YangConstructType dataType) throws DataModelException {
if (this.getName().equals(identifierName)) {
if (getName().equals(identifierName)) {
throw new DataModelException("YANG file error: Duplicate input identifier detected, same as list \"" +
this.getName() + "\"");
getName() + "\"");
}
}
}
......
......@@ -15,20 +15,14 @@
*/
package org.onosproject.yangutils.datamodel;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.translator.CodeGenerator;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax;
import org.onosproject.yangutils.utils.YangConstructType;
import org.onosproject.yangutils.utils.io.impl.FileSystemUtil;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
/*-
* Reference:RFC 6020.
......@@ -74,7 +68,7 @@ import org.onosproject.yangutils.utils.io.impl.FileSystemUtil;
* Data model node to maintain information defined in YANG module.
*/
public class YangModule extends YangNode
implements YangLeavesHolder, YangDesc, YangReference, Parsable, CodeGenerator, CollisionDetector {
implements YangLeavesHolder, YangDesc, YangReference, Parsable, CollisionDetector {
/**
* Name of the module.
......@@ -157,11 +151,6 @@ public class YangModule extends YangNode
*/
private byte version;
/**
* Cached Java File Handle.
*/
private CachedFileHandle fileHandle;
/*-
* Reference RFC 6020.
*
......@@ -510,52 +499,6 @@ public class YangModule extends YangNode
}
/**
* Get the mapped java package.
*
* @return the java package
*/
@Override
public String getPackage() {
if (getFileHandle() != null) {
return getFileHandle().getRelativeFilePath().replace("/", ".");
}
return null;
}
/**
* Set the mapped java package.
*
* @param pcg the package to set
*/
@Override
public void setPackage(String pcg) {
if (getFileHandle() != null) {
pcg.replace(".", "/");
getFileHandle().setRelativeFilePath(pcg);
}
}
/**
* Get the cached file handle.
*
* @return the fileHandle
*/
@Override
public CachedFileHandle getFileHandle() {
return fileHandle;
}
/**
* Set the cached file handle.
*
* @param handle the fileHandle to set
*/
@Override
public void setFileHandle(CachedFileHandle handle) {
fileHandle = handle;
}
/**
* Get the list of nested reference's which required resolution.
*
* @return list of nested reference's which required resolution
......@@ -623,64 +566,6 @@ public class YangModule extends YangNode
}
/**
* Generates java code for module.
*
* @param codeGenDir code generation directory
* @throws IOException when fails to generate the source files
*/
@Override
public void generateJavaCodeEntry(String codeGenDir) throws IOException {
String modPkg = JavaIdentifierSyntax.getRootPackage(getVersion(), getNameSpace().getUri(),
getRevision().getRevDate());
modPkg = JavaIdentifierSyntax.getCamelCase(modPkg);
CachedFileHandle handle = null;
try {
FileSystemUtil.createPackage(codeGenDir + modPkg, getName());
handle = FileSystemUtil.createSourceFiles(modPkg, getName(),
GeneratedFileType.GENERATE_INTERFACE_WITH_BUILDER);
handle.setCodeGenFilePath(codeGenDir);
} catch (IOException e) {
throw new IOException("Failed to create the source files.");
}
setFileHandle(handle);
addLeavesAttributes();
addLeafListAttributes();
}
@Override
public void generateJavaCodeExit() throws IOException {
getFileHandle().close();
return;
}
/**
* Adds leaf attributes in generated files.
*/
private void addLeavesAttributes() {
List<YangLeaf> leaves = getListOfLeaf();
if (leaves != null) {
for (YangLeaf leaf : leaves) {
getFileHandle().addAttributeInfo(leaf.getDataType(), leaf.getLeafName(), false);
}
}
}
/**
* Adds leaf list's attributes in generated files.
*/
private void addLeafListAttributes() {
List<YangLeafList> leavesList = getListOfLeafList();
if (leavesList != null) {
for (YangLeafList leafList : leavesList) {
getFileHandle().addAttributeInfo(leafList.getDataType(), leafList.getLeafName(), true);
}
}
}
/**
* Add a type to resolve the nested references.
*
* @param node grouping or typedef node which needs to be resolved
......@@ -715,4 +600,5 @@ public class YangModule extends YangNode
public void detectSelfCollision(String identifierName, YangConstructType dataType) throws DataModelException {
// Not required as module doesn't have any parent.
}
}
......
......@@ -16,13 +16,11 @@
package org.onosproject.yangutils.datamodel;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.translator.CodeGenerator;
/**
* Base class of a node in data model tree.
*/
public abstract class YangNode implements CodeGenerator {
public abstract class YangNode {
/**
* Type of node.
......@@ -50,6 +48,20 @@ public abstract class YangNode implements CodeGenerator {
private YangNode previousSibling;
/**
* Get the nodes name.
*
* @return nodes name
*/
public abstract String getName();
/**
* Set the nodes name.
*
* @param name nodes name
*/
public abstract void setName(String name);
/**
* Default constructor is made private to ensure node type is always set.
*/
@SuppressWarnings("unused")
......@@ -195,19 +207,25 @@ public abstract class YangNode implements CodeGenerator {
YangNode curNode;
curNode = getChild();
/* If the new node needs to be the first child */
/*-
* If the new node needs to be the first child
if (newChild.getNodeType().ordinal() < curNode.getNodeType().ordinal()) {
newChild.setNextSibling(curNode);
curNode.setPreviousSibling(newChild);
setChild(newChild);
return;
}
*/
/*
* Get the predecessor child of new child
*/
while (curNode.getNextSibling() != null
&& newChild.getNodeType().ordinal() >= curNode.getNextSibling().getNodeType().ordinal()) {
/*
* && newChild.getNodeType().ordinal() >=
* curNode.getNextSibling().getNodeType().ordinal()
*/) {
curNode = curNode.getNextSibling();
}
......@@ -218,54 +236,13 @@ public abstract class YangNode implements CodeGenerator {
return;
}
/* Insert the new node in child node list sorted by type */
/*-
* Insert the new node in child node list sorted by type
newChild.setNextSibling(curNode.getNextSibling());
newChild.setPreviousSibling(curNode);
curNode.getNextSibling().setPreviousSibling(newChild);
curNode.setNextSibling(newChild);
return;
}
/**
* Get the YANG name of the node.
*
* @return the name of node as defined in YANG file.
*/
public abstract String getName();
/**
* Set the YANG name of the node.
*
* @param name the name of node as defined in YANG file.
*/
public abstract void setName(String name);
/**
* Get the mapped java package.
*
* @return the java package
*/
public abstract String getPackage();
/**
* Set the mapped java package.
*
* @param pkg the package to set
*/
public abstract void setPackage(String pkg);
/**
* Get the mapped java file handler.
*
* @return the file handle.
*/
public abstract CachedFileHandle getFileHandle();
/**
* Set the mapped java file handle.
*
* @param fileHandle the file handle to set of current node.
*/
public abstract void setFileHandle(CachedFileHandle fileHandle);
}
}
......
......@@ -15,14 +15,14 @@
*/
package org.onosproject.yangutils.datamodel;
import java.util.LinkedList;
import java.util.List;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.utils.YangConstructType;
import java.util.LinkedList;
import java.util.List;
import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.detectCollidingChildUtil;
/*
* Reference RFC 6020.
......@@ -144,11 +144,6 @@ public class YangSubModule extends YangNode
private byte version;
/**
* package of the generated java code.
*/
private String pkg;
/**
* Create a sub module node.
*/
public YangSubModule() {
......@@ -468,57 +463,6 @@ public class YangSubModule extends YangNode
// TODO auto-generated method stub, to be implemented by parser
}
/**
* Generates java code for sub-module.
*
* @param codeGenDir code generation directory.
*/
@Override
public void generateJavaCodeEntry(String codeGenDir) {
// TODO Auto-generated method stub
}
/**
* Free resources used to generate code.
*/
@Override
public void generateJavaCodeExit() {
// TODO Auto-generated method stub
}
/**
* Get the mapped java package.
*
* @return the java package
*/
@Override
public String getPackage() {
return pkg;
}
/**
* Set the mapped java package.
*
* @param pakg the package to set
*/
@Override
public void setPackage(String pakg) {
pkg = pakg;
}
@Override
public CachedFileHandle getFileHandle() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFileHandle(CachedFileHandle fileHandle) {
// TODO Auto-generated method stub
}
@Override
public void detectCollidingChild(String identifierName, YangConstructType dataType) throws DataModelException {
// Asks helper to detect colliding child.
......
......@@ -15,16 +15,9 @@
*/
package org.onosproject.yangutils.datamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax;
import org.onosproject.yangutils.utils.UtilConstants;
import org.onosproject.yangutils.utils.YangConstructType;
import org.onosproject.yangutils.utils.io.impl.FileSystemUtil;
/*-
* Reference RFC 6020.
......@@ -92,16 +85,6 @@ public class YangTypeDef extends YangNode implements YangCommonInfo, Parsable {
private String units;
/**
* package of the generated java code.
*/
private String pkg;
/**
* Cached Java File Handle.
*/
private CachedFileHandle fileHandle;
/**
* Create a typedef node.
*/
public YangTypeDef() {
......@@ -307,103 +290,4 @@ public class YangTypeDef extends YangNode implements YangCommonInfo, Parsable {
getDerivedType().setDataType(YangDataTypes.DERIVED);
}
/**
* Generate java code snippet corresponding to YANG typedef.
*
* @param codeGenDir code generation directory
* @throws IOException when fails to generate files for typedef
*/
@Override
public void generateJavaCodeEntry(String codeGenDir) throws IOException {
YangNode parent = getParent();
String typeDefPkg = JavaIdentifierSyntax.getPackageFromParent(parent.getPackage(), parent.getName());
typeDefPkg = JavaIdentifierSyntax.getCamelCase(typeDefPkg).toLowerCase();
setPackage(typeDefPkg);
CachedFileHandle handle = null;
try {
FileSystemUtil.createPackage(codeGenDir + getPackage(), parent.getName() + UtilConstants.CHILDREN);
handle = FileSystemUtil.createSourceFiles(getPackage(), getName(),
GeneratedFileType.GENERATE_TYPEDEF_CLASS);
handle.setRelativeFilePath(getPackage().replace(".", "/"));
handle.setCodeGenFilePath(codeGenDir);
} catch (IOException e) {
throw new IOException("Failed to create the source files.");
}
setFileHandle(handle);
getDerivedType().getDataTypeExtendedInfo().getBaseType().setJavaPackage(getPackage());
addAttributeInfo();
addAttributeInParent();
}
/**
* Adds current node attribute to parent file.
*/
private void addAttributeInParent() {
if (getParent() != null) {
getParent().getFileHandle().addAttributeInfo(null, getName(), false);
}
}
/**
* Adds attribute to file handle.
*/
private void addAttributeInfo() {
getFileHandle().addAttributeInfo(getDerivedType().getDataTypeExtendedInfo().getBaseType(),
JavaIdentifierSyntax.getCamelCase(getName()), false);
}
/**
* Free resource used for code generation of YANG typedef.
*
* @throws IOException when fails to generate files
*/
@Override
public void generateJavaCodeExit() throws IOException {
getFileHandle().close();
return;
}
/**
* Get the mapped java package.
*
* @return the java package
*/
@Override
public String getPackage() {
return pkg;
}
/**
* Set the mapped java package.
*
* @param pakg mapped java package
*/
@Override
public void setPackage(String pakg) {
pkg = pakg;
}
/**
* Get the file handle of the cached file used during code generation.
*
* @return cached file handle
*/
@Override
public CachedFileHandle getFileHandle() {
return fileHandle;
}
/**
* Set the file handle to be used used for code generation.
*
* @param handle cached file handle
*/
@Override
public void setFileHandle(CachedFileHandle handle) {
fileHandle = handle;
}
}
......
......@@ -18,7 +18,6 @@ package org.onosproject.yangutils.datamodel;
import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.utils.YangConstructType;
import org.onosproject.yangutils.translator.CachedFileHandle;
/*-
* Reference RFC 6020.
......@@ -213,51 +212,26 @@ public class YangUses extends YangNode implements YangCommonInfo, Parsable {
// TODO auto-generated method stub, to be implemented by parser
}
/**
* Get uses name.
*
* @return uses name
*/
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
/**
* Set uses name.
*
* @param name uses name
*/
@Override
public void setName(String name) {
// TODO Auto-generated method stub
}
@Override
public void generateJavaCodeEntry(String codeGenDir) {
// TODO Auto-generated method stub
}
@Override
public void generateJavaCodeExit() {
// TODO Auto-generated method stub
}
@Override
public String getPackage() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setPackage(String pkg) {
// TODO Auto-generated method stub
}
@Override
public CachedFileHandle getFileHandle() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFileHandle(CachedFileHandle fileHandle) {
// TODO Auto-generated method stub
}
}
......
......@@ -63,7 +63,7 @@ public final class DataModelUtils {
}
}
node = node.getChild();
while ((node != null)) {
while (node != null) {
if (node instanceof CollisionDetector) {
((CollisionDetector) node).detectSelfCollision(identifierName, dataType);
}
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.datamodel.utils;
/**
* The target language in which the YANG information is modeled.
*/
public enum GeneratedLanguage {
/**
* Java.
*/
JAVA_GENERATION;
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.datamodel.utils;
import org.onosproject.yangutils.datamodel.YangAugment;
import org.onosproject.yangutils.datamodel.YangCase;
import org.onosproject.yangutils.datamodel.YangChoice;
import org.onosproject.yangutils.datamodel.YangContainer;
import org.onosproject.yangutils.datamodel.YangGrouping;
import org.onosproject.yangutils.datamodel.YangList;
import org.onosproject.yangutils.datamodel.YangModule;
import org.onosproject.yangutils.datamodel.YangSubModule;
import org.onosproject.yangutils.datamodel.YangTypeDef;
import org.onosproject.yangutils.datamodel.YangUses;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaAugment;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaCase;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaChoice;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaContainer;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaGrouping;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaList;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaModule;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaSubModule;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaTypeDef;
import org.onosproject.yangutils.translator.tojava.javamodel.YangJavaUses;
/**
* Factory to create data model objects based on the target file type.
*/
public final class YangDataModelFactory {
/**
* Utility class, hence private to prevent creating objects.
*/
private YangDataModelFactory() {
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangModule getYangModuleNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaModule();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangAugment getYangAugmentNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaAugment();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangCase getYangCaseNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaCase();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangChoice getYangChoiceNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaChoice();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangContainer getYangContainerNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaContainer();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangGrouping getYangGroupingNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaGrouping();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangList getYangListNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaList();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangSubModule getYangSubModuleNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaSubModule();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangTypeDef getYangTypeDefNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaTypeDef();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
/**
* Based on the target language generate the inherited data model node.
*
* @param targetLanguage target language in which YANG mapping needs to be
* generated.
* @return the corresponding inherited node based on the target language.
*/
public static YangUses getYangUsesNode(GeneratedLanguage targetLanguage) {
switch (targetLanguage) {
case JAVA_GENERATION: {
return new YangJavaUses();
}
default: {
throw new RuntimeException("Only YANG to Java is supported.");
}
}
}
}
......@@ -24,11 +24,12 @@ import org.onosproject.yangutils.parser.Parsable;
import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.TreeWalkListener;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidBooleanValue;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidBooleanValue;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
import static org.onosproject.yangutils.utils.YangConstructType.CONFIG_DATA;
......
......@@ -27,7 +27,8 @@ import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.TreeWalkListener;
import org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
import static org.onosproject.yangutils.datamodel.utils.YangDataModelFactory.getYangContainerNode;
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;
......@@ -37,6 +38,7 @@ import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorTyp
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
import static org.onosproject.yangutils.utils.YangConstructType.CONFIG_DATA;
......@@ -110,7 +112,7 @@ public final class ContainerListener {
int charPositionInLine = ctx.getStart().getCharPositionInLine();
detectCollidingChildUtil(listener, line, charPositionInLine, identifier, CONTAINER_DATA);
YangContainer container = new YangContainer();
YangContainer container = getYangContainerNode(JAVA_GENERATION);
container.setName(identifier);
/*
......@@ -123,8 +125,8 @@ public final class ContainerListener {
}
Parsable curData = listener.getParsedDataStack().peek();
if ((curData instanceof YangModule) || (curData instanceof YangContainer)
|| (curData instanceof YangList)) {
if (curData instanceof YangModule || curData instanceof YangContainer
|| curData instanceof YangList) {
YangNode curNode = (YangNode) curData;
try {
curNode.addChild(container);
......
......@@ -27,7 +27,8 @@ import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.TreeWalkListener;
import org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
import static org.onosproject.yangutils.datamodel.utils.YangDataModelFactory.getYangListNode;
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;
......@@ -37,6 +38,7 @@ import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorTyp
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityNonZero;
......@@ -117,7 +119,7 @@ public final class ListListener {
int charPositionInLine = ctx.getStart().getCharPositionInLine();
detectCollidingChildUtil(listener, line, charPositionInLine, identifier, LIST_DATA);
YangList yangList = new YangList();
YangList yangList = getYangListNode(JAVA_GENERATION);
yangList.setName(identifier);
/*
......
......@@ -21,13 +21,15 @@ import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.TreeWalkListener;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
import static org.onosproject.yangutils.datamodel.utils.YangDataModelFactory.getYangModuleNode;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsEmpty;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
import static org.onosproject.yangutils.utils.YangConstructType.MODULE_DATA;
......@@ -76,7 +78,7 @@ public final class ModuleListener {
String identifier = getValidIdentifier(ctx.identifier().getText(), MODULE_DATA, ctx);
YangModule yangModule = new YangModule();
YangModule yangModule = getYangModuleNode(JAVA_GENERATION);
yangModule.setName(identifier);
if (ctx.moduleBody().moduleHeaderStatement().yangVersionStatement() == null) {
......
......@@ -21,13 +21,15 @@ import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.TreeWalkListener;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
import static org.onosproject.yangutils.datamodel.utils.YangDataModelFactory.getYangSubModuleNode;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsEmpty;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
import static org.onosproject.yangutils.utils.YangConstructType.SUB_MODULE_DATA;
......@@ -79,7 +81,7 @@ public final class SubModuleListener {
String identifier = getValidIdentifier(ctx.identifier().getText(), SUB_MODULE_DATA, ctx);
YangSubModule yangSubModule = new YangSubModule();
YangSubModule yangSubModule = getYangSubModuleNode(JAVA_GENERATION);
yangSubModule.setName(identifier);
if (ctx.submoduleBody().submoduleHeaderStatement().yangVersionStatement() == null) {
......
......@@ -31,7 +31,8 @@ import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.TreeWalkListener;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
import static org.onosproject.yangutils.datamodel.utils.YangDataModelFactory.getYangTypeDefNode;
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;
......@@ -41,6 +42,7 @@ import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorTyp
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidIdentifier;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityEqualsOne;
import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.validateCardinalityMaxOne;
......@@ -121,7 +123,7 @@ public final class TypeDefListener {
derivedType.setDataType(YangDataTypes.DERIVED);
derivedType.setDataTypeName(identifier);
YangTypeDef typeDefNode = new YangTypeDef();
YangTypeDef typeDefNode = getYangTypeDefNode(JAVA_GENERATION);
typeDefNode.setDerivedType(derivedType);
Parsable curData = listener.getParsedDataStack().peek();
......
......@@ -33,13 +33,16 @@ import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.parser.YangUtilsParser;
import org.onosproject.yangutils.parser.exceptions.ParserException;
import org.onosproject.yangutils.parser.impl.YangUtilsParserManager;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.utils.UtilConstants;
import org.onosproject.yangutils.utils.io.impl.CopyrightHeader;
import org.onosproject.yangutils.utils.io.impl.YangFileScanner;
import org.onosproject.yangutils.utils.io.impl.YangIoUtils;
import org.sonatype.plexus.build.incremental.BuildContext;
import static org.onosproject.yangutils.translator.tojava.JavaCodeGeneratorUtil.generateJavaCode;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.addToSource;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.clean;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.copyYangFilesToTarget;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getDirectory;
/**
* ONOS YANG utility maven plugin. Goal of plugin is yang2java Execution phase
* in generate-sources requiresDependencyResolution at compile time.
......@@ -70,7 +73,7 @@ public class YangUtilManager extends AbstractMojo {
* Output directory.
*/
@Parameter(property = "project.build.outputDirectory", required = true, defaultValue = "target/classes")
private File outputDirectory;
private String outputDirectory;
/**
* Current maven project.
......@@ -84,6 +87,9 @@ public class YangUtilManager extends AbstractMojo {
@Component
private BuildContext context;
private static final String DEFAULT_PKG = File.separator
+ UtilConstants.DEFAULT_BASE_PKG.replace(UtilConstants.PERIOD, UtilConstants.SLASH);
private YangUtilsParser yangUtilsParser = new YangUtilsParserManager();
private String searchDir;
private String codeGenDir;
......@@ -94,6 +100,7 @@ public class YangUtilManager extends AbstractMojo {
* @param curProject maven project
*/
public void setCurrentProject(final MavenProject curProject) {
project = curProject;
}
......@@ -102,15 +109,14 @@ public class YangUtilManager extends AbstractMojo {
try {
CopyrightHeader.parseCopyrightHeader();
/**
* For deleting the generated code in previous build.
*/
YangIoUtils.clean(baseDir);
clean(getDirectory(baseDir, genFilesDir) + DEFAULT_PKG);
clean(getDirectory(baseDir, outputDirectory));
searchDir = baseDir + File.separator + yangFilesDir;
codeGenDir = baseDir + File.separator + genFilesDir + File.separator;
searchDir = getDirectory(baseDir, yangFilesDir);
codeGenDir = getDirectory(baseDir, genFilesDir) + File.separator;
List<String> yangFiles = YangFileScanner.getYangFiles(searchDir);
Iterator<String> yangFileIterator = yangFiles.iterator();
......@@ -118,7 +124,7 @@ public class YangUtilManager extends AbstractMojo {
String yangFile = yangFileIterator.next();
try {
YangNode yangNode = yangUtilsParser.getDataModel(yangFile);
JavaCodeGenerator.generateJavaCode(yangNode, codeGenDir);
generateJavaCode(yangNode, codeGenDir);
} catch (ParserException e) {
String logInfo = "Error in file: " + e.getFileName();
if (e.getLineNumber() != 0) {
......@@ -127,16 +133,17 @@ public class YangUtilManager extends AbstractMojo {
}
if (e.getMessage() != null) {
logInfo = logInfo + "\n" + e.getMessage();
logInfo = logInfo + UtilConstants.NEW_LINE + e.getMessage();
}
getLog().info(logInfo);
}
}
YangIoUtils.addToSource(baseDir + File.separator + UtilConstants.YANG_GEN_DIR, project, context);
addToSource(getDirectory(baseDir, genFilesDir) + DEFAULT_PKG, project, context);
copyYangFilesToTarget(yangFiles, getDirectory(baseDir, outputDirectory), project);
} catch (Exception e) {
getLog().info(e);
//throw new MojoExecutionException("Exception occured due to " + e.getLocalizedMessage());
}
}
}
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.tojava.utils.TempDataStoreTypes;
/**
* Cached java file handle, which supports the addition of member attributes and
* methods.
*/
public interface CachedFileHandle {
/**
* Add a new attribute to the file(s).
*
* @param attrType data type of the added attribute
* @param name name of the attribute
* @param isListAttr if the current added attribute needs to be maintained
* in a list
*/
void addAttributeInfo(YangType<?> attrType, String name, boolean isListAttr);
/**
* Flushes the cached contents to the target file, frees used resources.
*
* @throws IOException when failes to generated java files
*/
void close() throws IOException;
/**
* Sets directory package path for code generation.
*
* @param filePath directory package path for code generation
*/
void setRelativeFilePath(String filePath);
/**
* Gets directory package path for code generation.
*
* @return directory package path for code generation
*/
String getRelativeFilePath();
/**
* Gets base directory package path for code generation.
*
* @return directory package path for code generation
*/
String getCodeGenFilePath();
/**
* Sets base directory package path for code generation.
*
* @param path base directory path
*/
void setCodeGenFilePath(String path);
/**
* Writes specific info to a Temp file.
*
* @param data data to be stored
* @param type type of Temp data store
* @param className class name
* @param genDir generated directory
* @throws IOException when fails to create a Temp data file
*/
void setTempData(String data, TempDataStoreTypes type, String className, String genDir) throws IOException;
/**
* Get the Temp data.
*
* @param type type of Temp data store
* @param className name of the class
* @param genDir generated directory
* @return temp data
* @throws IOException when fails to read from the file
* @throws ClassNotFoundException when class is missing
* @throws FileNotFoundException when file is missing
*/
String getTempData(TempDataStoreTypes type, String className, String genDir)
throws IOException, FileNotFoundException, ClassNotFoundException;
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType;
import org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator;
import org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax;
import org.onosproject.yangutils.translator.tojava.utils.TempDataStoreTypes;
import org.onosproject.yangutils.utils.UtilConstants;
import org.onosproject.yangutils.utils.io.impl.FileSystemUtil;
/**
* Maintain the information about the java file to be generated.
*/
public class CachedJavaFileHandle implements CachedFileHandle {
private static final int MAX_CACHABLE_ATTR = 64;
private static final String JAVA_FILE_EXTENSION = ".java";
private static final String TEMP_FILE_EXTENSION = ".tmp";
private static final String GETTER_METHOD_FILE_NAME = "GetterMethod";
private static final String SETTER_METHOD_FILE_NAME = "SetterMethod";
private static final String GETTER_METHOD_IMPL_FILE_NAME = "GetterMethodImpl";
private static final String SETTER_METHOD_IMPL_FILE_NAME = "SetterMethodImpl";
private static final String CONSTRUCTOR_FILE_NAME = "Constructor";
private static final String ATTRIBUTE_FILE_NAME = "Attributes";
private static final String TO_STRING_METHOD_FILE_NAME = "ToString";
private static final String HASH_CODE_METHOD_FILE_NAME = "HashCode";
private static final String EQUALS_METHOD_FILE_NAME = "Equals";
private static final String TYPE_DEF_FILE_NAME = "TypeDef";
private static final String TEMP_FOLDER_NAME_SUFIX = "-Temp";
/**
* The type(s) of java source file(s) to be generated when the cached file
* handle is closed.
*/
private int genFileTypes;
/**
* Name of the object in YANG file.
*/
private String yangName;
/**
* Sorted set of import info, to be used to maintain the set of classes to
* be imported in the generated class.
*/
private SortedSet<ImportInfo> importSet;
/**
* Cached list of attribute info.
*/
private List<AttributeInfo> attributeList;
/**
* File generation directory path.
*/
private String relativeFilePath;
/**
* File generation base directory path.
*/
private String codeGenDirFilePath;
/**
* Prevent invoking default constructor.
*/
public CachedJavaFileHandle() {
setCachedAttributeList(new LinkedList<AttributeInfo>());
}
/**
* Create a cached file handle which takes care of adding attributes to the
* generated java file.
*
* @param pcg package in which class/interface need to be generated
* @param yangName name of the attribute in YANG file
* @param types the types of files that needs to be generated
* @throws IOException file IO exception
*/
public CachedJavaFileHandle(String pcg, String yangName, int types) throws IOException {
setCachedAttributeList(new LinkedList<AttributeInfo>());
setImportSet(new TreeSet<ImportInfo>());
setRelativeFilePath(pcg.replace(".", "/"));
setGeneratedFileTypes(types);
setYangName(yangName);
}
/**
* Get the types of files being generated corresponding to the YANG
* definition.
*
* @return the types of files being generated corresponding to the YANG
* definition
*/
public int getGeneratedFileTypes() {
return genFileTypes;
}
/**
* Set the types of files being generated corresponding to the YANG
* definition.
*
* @param fileTypes the types of files being generated corresponding to the
* YANG definition
*/
public void setGeneratedFileTypes(int fileTypes) {
genFileTypes = fileTypes;
}
/**
* Get the corresponding name defined in YANG.
*
* @return the corresponding name defined in YANG
*/
public String getYangName() {
return yangName;
}
/**
* Set the corresponding name defined in YANG.
*
* @param yangName the corresponding name defined in YANG
*/
public void setYangName(String yangName) {
this.yangName = yangName;
}
/**
* Get the set containing the imported class/interface info.
*
* @return the set containing the imported class/interface info
*/
public SortedSet<ImportInfo> getImportSet() {
return importSet;
}
/**
* Assign the set containing the imported class/interface info.
*
* @param importSet the set containing the imported class/interface info
*/
private void setImportSet(SortedSet<ImportInfo> importSet) {
this.importSet = importSet;
}
/**
* Add an imported class/interface info is it is not already part of the
* set. If already part of the set, return false, else add to set and return
* true.
*
* @param importInfo class/interface info being imported
* @return status of new addition of class/interface to the import set
*/
public boolean addImportInfo(ImportInfo importInfo) {
return getImportSet().add(importInfo);
}
/**
* Get the list of cached attribute list.
*
* @return the set containing the imported class/interface info
*/
public List<AttributeInfo> getCachedAttributeList() {
return attributeList;
}
/**
* Set the cached attribute list.
*
* @param attrList attribute list
*/
private void setCachedAttributeList(List<AttributeInfo> attrList) {
attributeList = attrList;
}
@Override
public void setRelativeFilePath(String path) {
relativeFilePath = path;
}
@Override
public String getRelativeFilePath() {
return relativeFilePath;
}
@Override
public String getCodeGenFilePath() {
return codeGenDirFilePath;
}
@Override
public void setCodeGenFilePath(String path) {
codeGenDirFilePath = path;
}
/**
* Flush the cached attribute list to the corresponding temporary file.
*/
private void flushCacheAttrToTempFile() {
for (AttributeInfo attr : getCachedAttributeList()) {
JavaFileGenerator.parseAttributeInfo(attr, getGeneratedFileTypes(), getYangName(), getCodeGenFilePath() +
getRelativeFilePath().replace(UtilConstants.PERIOD, UtilConstants.SLASH), this);
}
/*
* clear the contents from the cached attribute list.
*/
getCachedAttributeList().clear();
}
@Override
public void addAttributeInfo(YangType<?> attrType, String name, boolean isListAttr) {
/* YANG name is mapped to java name */
name = JavaIdentifierSyntax.getCamelCase(name);
ImportInfo importInfo = new ImportInfo();
boolean isImport = false;
AttributeInfo newAttr = new AttributeInfo();
if (attrType != null) {
newAttr.setAttributeType(attrType);
String importStr = AttributesJavaDataType.getJavaImportClass(attrType, isListAttr);
if (importStr != null) {
importInfo.setClassInfo(importStr);
importStr = AttributesJavaDataType.getJavaImportPackage(attrType, isListAttr);
importInfo.setPkgInfo(importStr);
isImport = true;
} else {
importStr = AttributesJavaDataType.getJavaDataType(attrType);
if (importStr == null) {
throw new RuntimeException("not supported data type");
//TODO: need to change to translator exception.
}
importInfo.setClassInfo(importStr);
}
} else {
importInfo.setClassInfo(JavaIdentifierSyntax.getCaptialCase(name));
importInfo.setPkgInfo(getRelativeFilePath().replace('/', '.')
+ "." + getYangName().toLowerCase());
isImport = true;
}
newAttr.setQualifiedName(false);
if (isImport) {
addImportInfo(importInfo);
}
if (isListAttr) {
ImportInfo listImportInfo = new ImportInfo();
listImportInfo.setPkgInfo(UtilConstants.COLLECTION_IMPORTS);
listImportInfo.setClassInfo(UtilConstants.LIST);
addImportInfo(listImportInfo);
}
/**
* If two classes with different packages have same class info for import than use qualified name.
*/
for (ImportInfo imports : getImportSet()) {
if (imports.getClassInfo().equals(importInfo.getClassInfo())
&& !imports.getPkgInfo().equals(importInfo.getPkgInfo())) {
newAttr.setQualifiedName(true);
}
}
newAttr.setAttributeName(name);
newAttr.setListAttr(isListAttr);
newAttr.setImportInfo(importInfo);
if (getCachedAttributeList().size() == MAX_CACHABLE_ATTR) {
flushCacheAttrToTempFile();
}
getCachedAttributeList().add(newAttr);
}
@Override
public void close() throws IOException {
List<AttributeInfo> attrList = getCachedAttributeList();
flushCacheAttrToTempFile();
String className = getYangName();
className = JavaIdentifierSyntax.getCaptialCase(className);
String path = getRelativeFilePath();
int fileType = getGeneratedFileTypes();
/*
* TODO: add the file header using
* JavaCodeSnippetGen.getFileHeaderComment
*/
List<String> imports = new ArrayList<>();
String importString;
for (ImportInfo importInfo : new ArrayList<ImportInfo>(getImportSet())) {
importString = UtilConstants.IMPORT;
if (importInfo.getPkgInfo() != "" && importInfo.getClassInfo() != null
&& importInfo.getPkgInfo() != UtilConstants.JAVA_LANG) {
importString = importString + importInfo.getPkgInfo() + ".";
importString = importString + importInfo.getClassInfo() + UtilConstants.SEMI_COLAN
+ UtilConstants.NEW_LINE;
imports.add(importString);
}
}
java.util.Collections.sort(imports);
/**
* Start generation of files.
*/
if ((fileType & GeneratedFileType.INTERFACE_MASK) != 0
|| fileType == GeneratedFileType.GENERATE_INTERFACE_WITH_BUILDER) {
/**
* Create interface file.
*/
String interfaceFileName = className;
File interfaceFile = JavaFileGenerator.getFileObject(path, interfaceFileName, JAVA_FILE_EXTENSION, this);
interfaceFile = JavaFileGenerator.generateInterfaceFile(interfaceFile, className, imports,
attrList, path.replace('/', '.'), this);
/**
* Create temp builder interface file.
*/
String builderInterfaceFileName = className + UtilConstants.BUILDER + UtilConstants.INTERFACE;
File builderInterfaceFile = JavaFileGenerator.getFileObject(path, builderInterfaceFileName,
TEMP_FILE_EXTENSION, this);
builderInterfaceFile = JavaFileGenerator.generateBuilderInterfaceFile(builderInterfaceFile, className,
path.replace('/', '.'), attrList, this);
/**
* Append builder interface file to interface file and close it.
*/
JavaFileGenerator.appendFileContents(builderInterfaceFile, interfaceFile);
JavaFileGenerator.insert(interfaceFile,
JavaFileGenerator.closeFile(GeneratedFileType.INTERFACE_MASK, interfaceFileName));
/**
* Close file handle for interface files.
*/
JavaFileGenerator.closeFileHandles(builderInterfaceFile);
JavaFileGenerator.closeFileHandles(interfaceFile);
/**
* Remove temp files.
*/
JavaFileGenerator.clean(builderInterfaceFile);
}
if (!attrList.isEmpty()) {
imports.add(UtilConstants.MORE_OBJECT_IMPORT);
imports.add(UtilConstants.JAVA_UTIL_OBJECTS_IMPORT);
java.util.Collections.sort(imports);
}
if ((fileType & GeneratedFileType.BUILDER_CLASS_MASK) != 0
|| fileType == GeneratedFileType.GENERATE_INTERFACE_WITH_BUILDER) {
/**
* Create builder class file.
*/
String builderFileName = className + UtilConstants.BUILDER;
File builderFile = JavaFileGenerator.getFileObject(path, builderFileName, JAVA_FILE_EXTENSION, this);
builderFile = JavaFileGenerator.generateBuilderClassFile(builderFile, className, imports,
path.replace('/', '.'), attrList, this);
/**
* Create temp impl class file.
*/
String implFileName = className + UtilConstants.IMPL;
File implTempFile = JavaFileGenerator.getFileObject(path, implFileName, TEMP_FILE_EXTENSION, this);
implTempFile = JavaFileGenerator.generateImplClassFile(implTempFile, className,
path.replace('/', '.'), attrList, this);
/**
* Append impl class to builder class and close it.
*/
JavaFileGenerator.appendFileContents(implTempFile, builderFile);
JavaFileGenerator.insert(builderFile,
JavaFileGenerator.closeFile(GeneratedFileType.BUILDER_CLASS_MASK, builderFileName));
/**
* Close file handle for classes files.
*/
JavaFileGenerator.closeFileHandles(implTempFile);
JavaFileGenerator.closeFileHandles(builderFile);
/**
* Remove temp files.
*/
JavaFileGenerator.clean(implTempFile);
}
if ((fileType & GeneratedFileType.GENERATE_TYPEDEF_CLASS) != 0) {
/**
* Create builder class file.
*/
String typeDefFileName = className;
File typeDefFile = JavaFileGenerator.getFileObject(path, typeDefFileName, JAVA_FILE_EXTENSION, this);
typeDefFile = JavaFileGenerator.generateTypeDefClassFile(typeDefFile, className, imports,
path.replace('/', '.'), attrList, this);
JavaFileGenerator.insert(typeDefFile,
JavaFileGenerator.closeFile(GeneratedFileType.GENERATE_TYPEDEF_CLASS, typeDefFileName));
/**
* Close file handle for classes files.
*/
JavaFileGenerator.closeFileHandles(typeDefFile);
}
if (!getCachedAttributeList().isEmpty()) {
closeTempDataFileHandles(className, getCodeGenFilePath() + getRelativeFilePath());
JavaFileGenerator
.cleanTempFiles(new File(getCodeGenFilePath() + getRelativeFilePath() + File.separator + className
+ TEMP_FOLDER_NAME_SUFIX));
}
/*
* clear the contents from the cached attribute list.
*/
getCachedAttributeList().clear();
}
@Override
public void setTempData(String data, TempDataStoreTypes type, String className, String genDir)
throws IOException {
String fileName = "";
if (type.equals(TempDataStoreTypes.ATTRIBUTE)) {
fileName = ATTRIBUTE_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.GETTER_METHODS)) {
fileName = GETTER_METHOD_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.GETTER_METHODS_IMPL)) {
fileName = GETTER_METHOD_IMPL_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.SETTER_METHODS)) {
fileName = SETTER_METHOD_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.SETTER_METHODS_IMPL)) {
fileName = SETTER_METHOD_IMPL_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.TYPE_DEF)) {
fileName = TYPE_DEF_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.TO_STRING)) {
fileName = TO_STRING_METHOD_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.HASH_CODE)) {
fileName = HASH_CODE_METHOD_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.EQUALS)) {
fileName = EQUALS_METHOD_FILE_NAME;
} else {
fileName = CONSTRUCTOR_FILE_NAME;
}
String path = genDir.replace(UtilConstants.PERIOD, UtilConstants.SLASH)
+ File.separator + className
+ TEMP_FOLDER_NAME_SUFIX + File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(path + fileName + TEMP_FILE_EXTENSION);
try {
if (!file.exists()) {
file.createNewFile();
JavaFileGenerator.insert(file, data);
} else {
JavaFileGenerator.insert(file, data);
}
} catch (IOException ex) {
throw new IOException("failed to write in temp file.");
}
}
@Override
public String getTempData(TempDataStoreTypes type, String className, String genDir)
throws IOException, FileNotFoundException, ClassNotFoundException {
String fileName = "";
if (type.equals(TempDataStoreTypes.ATTRIBUTE)) {
fileName = ATTRIBUTE_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.GETTER_METHODS)) {
fileName = GETTER_METHOD_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.GETTER_METHODS_IMPL)) {
fileName = GETTER_METHOD_IMPL_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.SETTER_METHODS)) {
fileName = SETTER_METHOD_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.SETTER_METHODS_IMPL)) {
fileName = SETTER_METHOD_IMPL_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.TYPE_DEF)) {
fileName = TYPE_DEF_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.TO_STRING)) {
fileName = TO_STRING_METHOD_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.HASH_CODE)) {
fileName = HASH_CODE_METHOD_FILE_NAME;
} else if (type.equals(TempDataStoreTypes.EQUALS)) {
fileName = EQUALS_METHOD_FILE_NAME;
} else {
fileName = CONSTRUCTOR_FILE_NAME;
}
String path = genDir.replace(UtilConstants.PERIOD, UtilConstants.SLASH)
+ File.separator + className + TEMP_FOLDER_NAME_SUFIX + File.separator;
try {
String file = path + fileName + TEMP_FILE_EXTENSION;
if (new File(file).exists()) {
return readFile(path + fileName + TEMP_FILE_EXTENSION);
} else {
return "";
}
} catch (FileNotFoundException e) {
throw new FileNotFoundException("No such file or directory.");
}
}
/**
* Reads file and convert it to string.
*
* @param toAppend file to be converted
* @return string of file
* @throws IOException when fails to convert to string
*/
private static String readFile(String toAppend) throws IOException {
BufferedReader bufferReader = new BufferedReader(new FileReader(toAppend));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = bufferReader.readLine();
while (line != null) {
if (line.equals(UtilConstants.FOUR_SPACE_INDENTATION)
|| line.equals(UtilConstants.EIGHT_SPACE_INDENTATION)
|| line.equals(UtilConstants.SPACE) || line.equals("") || line.equals(UtilConstants.NEW_LINE)) {
stringBuilder.append("\n");
} else {
stringBuilder.append(line);
stringBuilder.append("\n");
}
line = bufferReader.readLine();
}
return stringBuilder.toString();
} finally {
bufferReader.close();
}
}
/**
* Closes the temp file handles.
*
* @param className class name
* @param genDir generated directory
* @throws IOException when failes to close file handle
*/
private void closeTempDataFileHandles(String className, String genDir)
throws IOException {
String path = genDir.replace(UtilConstants.PERIOD, UtilConstants.SLASH) + File.separator + className
+ TEMP_FOLDER_NAME_SUFIX + File.separator;
String fileName = "";
fileName = ATTRIBUTE_FILE_NAME;
closeTempFile(fileName, path);
fileName = GETTER_METHOD_FILE_NAME;
closeTempFile(fileName, path);
fileName = GETTER_METHOD_IMPL_FILE_NAME;
closeTempFile(fileName, path);
fileName = SETTER_METHOD_FILE_NAME;
closeTempFile(fileName, path);
fileName = SETTER_METHOD_IMPL_FILE_NAME;
closeTempFile(fileName, path);
fileName = TYPE_DEF_FILE_NAME;
closeTempFile(fileName, path);
fileName = TO_STRING_METHOD_FILE_NAME;
closeTempFile(fileName, path);
fileName = HASH_CODE_METHOD_FILE_NAME;
closeTempFile(fileName, path);
fileName = EQUALS_METHOD_FILE_NAME;
closeTempFile(fileName, path);
fileName = CONSTRUCTOR_FILE_NAME;
closeTempFile(fileName, path);
}
/**
* Closes the specific temp file.
*
* @param fileName temp file name
* @param path path
* @throws IOException when failed to close file handle
*/
private void closeTempFile(String fileName, String path) throws IOException {
File file = new File(path + fileName + TEMP_FILE_EXTENSION);
try {
if (!file.exists()) {
FileSystemUtil.updateFileHandle(file, null, true);
}
} catch (IOException ex) {
throw new IOException("failed to close the temp file handle.");
}
}
}
......@@ -14,17 +14,17 @@
* limitations under the License.
*/
package org.onosproject.yangutils.translator;
package org.onosproject.yangutils.translator.tojava;
/**
* Type of files generated.
*/
public final class GeneratedFileType {
public final class GeneratedJavaFileType {
/**
* prevent creating attributes.
*/
private GeneratedFileType() {
private GeneratedJavaFileType() {
}
/**
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
/**
* Type of files generated.
*/
public final class GeneratedTempFileType {
/**
* prevent creating attributes.
*/
private GeneratedTempFileType() {
}
/**
* attributes definition temporary file.
*/
public static final int ATTRIBUTES_MASK = 1;
/**
* getter methods for interface.
*/
public static final int GETTER_FOR_INTERFACE_MASK = 2;
/**
* getter methods for class.
*/
public static final int GETTER_FOR_CLASS_MASK = 4;
/**
* setter methods for interface.
*/
public static final int SETTER_FOR_INTERFACE_MASK = 8;
/**
* setter methods for class.
*/
public static final int SETTER_FOR_CLASS_MASK = 16;
/**
* constructor method of class.
*/
public static final int CONSTRUCTOR_IMPL_MASK = 32;
/**
* hash code implementation of class.
*/
public static final int HASH_CODE_IMPL_MASK = 64;
/**
* equals implementation of class.
*/
public static final int EQUALS_IMPL_MASK = 128;
/**
* to string implementation of class.
*/
public static final int TO_STRING_IMPL_MASK = 256;
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
/**
* Data model nodes which are required to generate java classes, need to support
* java file info.
*/
public interface HasJavaFileInfo {
/**
* Get the generated java file information.
*
* @return generated java file information
*/
public JavaFileInfo getJavaFileInfo();
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
public void setJavaFileInfo(JavaFileInfo javaInfo);
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
/**
* Maintains the information of the java import data.
*/
public interface HasJavaImportData {
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
public JavaImportData getJavaImportData();
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
public void setJavaImportData(JavaImportData javaImportData);
}
......@@ -13,29 +13,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator;
import java.io.IOException;
package org.onosproject.yangutils.translator.tojava;
/**
* Abstraction of an entity which provides Code generator functionalities.
* Has temporary file handle.
*/
public interface CodeGenerator {
public interface HasTempJavaCodeFragmentFiles {
/**
* Traverse the schema of application and generate corresponding code.
* Get the temporary file handle.
*
* @param codeGenDir code generation directory
* @throws IOException when fails to translate the data model tree
* @return temporary file handle
*/
void generateJavaCodeEntry(String codeGenDir) throws IOException;
TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles();
/**
* Traverse the schema of application and generate corresponding code.
* Set temporary file handle.
*
* @throws IOException when fails to generate java code
* @param fileHandle temporary file handle
*/
void generateJavaCodeExit() throws IOException;
void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle);
}
......
......@@ -16,12 +16,18 @@
package org.onosproject.yangutils.translator.tojava;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.datamodel.YangType;
import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getIsQualifiedAccessOrAddToImportList;
import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getQualifiedTypeInfoOfCurNode;
import static org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo.getQualifiedTypeInfoOfLeafAttribute;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
/**
* Maintains the attribute info corresponding to class/interface generated.
*/
public class AttributeInfo {
public final class JavaAttributeInfo {
/**
* The data type info of attribute.
......@@ -47,12 +53,12 @@ public class AttributeInfo {
* The class info will be used to set the attribute type and package info
* will be use for qualified name.
*/
private ImportInfo importInfo;
private JavaQualifiedTypeInfo importInfo;
/**
* Default constructor.
*/
public AttributeInfo() {
private JavaAttributeInfo() {
}
/**
......@@ -61,6 +67,10 @@ public class AttributeInfo {
* @return the data type info of attribute
*/
public YangType<?> getAttributeType() {
if (attrType == null) {
throw new RuntimeException("Expected java attribute type is null");
}
return attrType;
}
......@@ -80,6 +90,10 @@ public class AttributeInfo {
* @return name of the attribute
*/
public String getAttributeName() {
if (name == null) {
throw new RuntimeException("Expected java attribute name is null");
}
return name;
}
......@@ -89,6 +103,7 @@ public class AttributeInfo {
* @param attrName name of the attribute
*/
public void setAttributeName(String attrName) {
name = attrName;
}
......@@ -98,6 +113,7 @@ public class AttributeInfo {
* @return the if the added attribute is a list of info
*/
public boolean isListAttr() {
return isListAttr;
}
......@@ -107,6 +123,7 @@ public class AttributeInfo {
* @param isList if the added attribute is a list of info
*/
public void setListAttr(boolean isList) {
isListAttr = isList;
}
......@@ -118,6 +135,7 @@ public class AttributeInfo {
* qualified manner.
*/
public boolean isQualifiedName() {
return isQualifiedName;
}
......@@ -128,7 +146,8 @@ public class AttributeInfo {
* @param isQualified if the added attribute has to be accessed in a fully
* qualified manner
*/
public void setQualifiedName(boolean isQualified) {
public void setIsQualifiedAccess(boolean isQualified) {
isQualifiedName = isQualified;
}
......@@ -138,7 +157,8 @@ public class AttributeInfo {
*
* @return import info
*/
public ImportInfo getImportInfo() {
public JavaQualifiedTypeInfo getImportInfo() {
return importInfo;
}
......@@ -147,8 +167,83 @@ public class AttributeInfo {
*
* @param importInfo import info for the attribute type
*/
public void setImportInfo(ImportInfo importInfo) {
public void setImportInfo(JavaQualifiedTypeInfo importInfo) {
this.importInfo = importInfo;
}
/**
* Create an attribute info object corresponding to the passed leaf
* information and return it.
*
* @param curNode current data model node for which the java file is being
* generated
* @param attributeType leaf data type
* @param attributeName leaf name
* @param isListAttribute is the current added attribute needs to be a list
* @return AttributeInfo attribute details required to add in temporary
* files
*/
public static JavaAttributeInfo getAttributeInfoOfLeaf(YangNode curNode,
YangType<?> attributeType, String attributeName,
boolean isListAttribute) {
JavaAttributeInfo newAttr = new JavaAttributeInfo();
/*
* Get the import info corresponding to the attribute for import in
* generated java files or qualified access
*/
JavaQualifiedTypeInfo importInfo = getQualifiedTypeInfoOfLeafAttribute(curNode,
attributeType, attributeName, isListAttribute);
newAttr.setImportInfo(importInfo);
newAttr.setIsQualifiedAccess(getIsQualifiedAccessOrAddToImportList(
curNode, importInfo));
newAttr.setAttributeName(getCamelCase(attributeName));
newAttr.setListAttr(isListAttribute);
newAttr.setImportInfo(importInfo);
newAttr.setAttributeType(attributeType);
return newAttr;
}
/**
* Create an attribute info object corresponding to a data model node and
* return it.
*
* @param curNode current data model node for which the java code generation
* is being handled
* @param parentNode parent node in which the current node is an attribute
* @param isListNode is the current added attribute needs to be a list
* @return AttributeInfo attribute details required to add in temporary
* files
*/
public static JavaAttributeInfo getCurNodeAsAttributeInParent(
YangNode curNode, YangNode parentNode, boolean isListNode) {
JavaAttributeInfo newAttr = new JavaAttributeInfo();
// if (curNode instanceof HasJavaFileInfo) {
// throw new RuntimeException("translator data model node does not have java info");
// }
String curNodeName = ((HasJavaFileInfo) curNode).getJavaFileInfo().getJavaName();
/*
* Get the import info corresponding to the attribute for import in
* generated java files or qualified access
*/
JavaQualifiedTypeInfo qualifiedTypeInfo = getQualifiedTypeInfoOfCurNode(parentNode,
curNodeName, isListNode);
newAttr.setImportInfo(qualifiedTypeInfo);
newAttr.setIsQualifiedAccess(
getIsQualifiedAccessOrAddToImportList(parentNode,
qualifiedTypeInfo));
newAttr.setAttributeName(getCamelCase(curNodeName));
newAttr.setListAttr(isListNode);
newAttr.setImportInfo(qualifiedTypeInfo);
newAttr.setAttributeType(null);
return newAttr;
}
}
......
......@@ -18,46 +18,24 @@ package org.onosproject.yangutils.translator.tojava;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangNode;
/**
* Implementation of Java code generator based on application schema.
* Abstraction of an entity which provides Code generator functionalities.
*/
public final class JavaCodeGenerator {
public interface JavaCodeGenerator {
/**
* Default constructor.
* Traverse the schema of application and generate corresponding code.
*
* @param codeGenDir code generation directory
* @throws IOException when fails to translate the data model tree
*/
private JavaCodeGenerator() {
}
void generateCodeEntry(String codeGenDir) throws IOException;
/**
* Generate Java code files corresponding to the YANG schema.
* Traverse the schema of application and generate corresponding code.
*
* @param rootNode root node of the data model tree
* @param codeGenDir code generation directory
* @throws IOException when fails to generate java code file the current node
* @throws IOException when fails to generate java code
*/
public static void generateJavaCode(YangNode rootNode, String codeGenDir) throws IOException {
YangNode curNode = rootNode;
TraversalType curTraversal = TraversalType.ROOT;
void generateCodeExit() throws IOException;
while (!(curNode == null)) {
if (curTraversal != TraversalType.PARENT) {
curNode.generateJavaCodeEntry(codeGenDir);
}
if (curTraversal != TraversalType.PARENT && curNode.getChild() != null) {
curTraversal = TraversalType.CHILD;
curNode = curNode.getChild();
} else if (curNode.getNextSibling() != null) {
curNode.generateJavaCodeExit();
curTraversal = TraversalType.SIBILING;
curNode = curNode.getNextSibling();
} else {
curNode.generateJavaCodeExit();
curTraversal = TraversalType.PARENT;
curNode = curNode.getParent();
}
}
}
}
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangNode;
/**
* Implementation of Java code generator based on application schema.
*/
public final class JavaCodeGeneratorUtil {
/**
* Default constructor.
*/
private JavaCodeGeneratorUtil() {
}
/**
* Generate Java code files corresponding to the YANG schema.
*
* @param rootNode root node of the data model tree
* @param codeGenDir code generation directory
* @throws IOException when fails to generate java code file the current
* node
*/
public static void generateJavaCode(YangNode rootNode, String codeGenDir) throws IOException {
YangNode curNode = rootNode;
TraversalType curTraversal = TraversalType.ROOT;
while (!(curNode == null)) {
if (curTraversal != TraversalType.PARENT) {
generateCodeEntry(curNode, codeGenDir);
}
if (curTraversal != TraversalType.PARENT && curNode.getChild() != null) {
curTraversal = TraversalType.CHILD;
curNode = curNode.getChild();
} else if (curNode.getNextSibling() != null) {
generateCodeExit(curNode);
curTraversal = TraversalType.SIBILING;
curNode = curNode.getNextSibling();
} else {
generateCodeExit(curNode);
curTraversal = TraversalType.PARENT;
curNode = curNode.getParent();
}
}
}
/**
* Generates the current nodes code snippet.
*
* @param curNode current data model node for which the code needs to be
* generated
* @param codeGenDir the base directory where the code needs to be generated
* @throws IOException IO operation exception
*/
private static void generateCodeEntry(YangNode curNode,
String codeGenDir) throws IOException {
if (curNode instanceof JavaCodeGenerator) {
((JavaCodeGenerator) curNode).generateCodeEntry(codeGenDir);
} else {
throw new RuntimeException(
"Gnenerated data model node cannot be translated to target language code");
}
}
/**
* Generates the current nodes code target code from the snippet.
*
* @param curNode current data model node for which the code needs to be
* generated
* @throws IOException IO operation exception
*/
private static void generateCodeExit(YangNode curNode) throws IOException {
if (curNode instanceof JavaCodeGenerator) {
((JavaCodeGenerator) curNode).generateCodeExit();
} else {
throw new RuntimeException(
"Gnenerated data model node cannot be translated to target language code");
}
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
/**
* Cached java file handle, which supports the addition of member attributes and
* methods.
*/
public class JavaFileInfo {
/**
* The type(s) of java source file(s) to be generated when the cached file
* handle is closed.
*/
private int genFileTypes;
/**
* Name of the module.
*/
private String javaName;
/**
* java Package of the mapped java class.
*/
private String pkg;
/**
* File generation directory path.
*/
private String relativeFilePath;
/**
* File generation base directory path.
*/
private String codeGenDirFilePath;
/**
* Get the types of files being generated corresponding to the YANG
* definition.
*
* @return the types of files being generated corresponding to the YANG
* definition
*/
public int getGeneratedFileTypes() {
return genFileTypes;
}
/**
* Set the types of files being generated corresponding to the YANG
* definition.
*
* @param fileTypes the types of files being generated corresponding to the
* YANG definition
*/
public void setGeneratedFileTypes(int fileTypes) {
genFileTypes = fileTypes;
}
/**
* Get the java name of the node.
*
* @return the java name of node
*/
public String getJavaName() {
return javaName;
}
/**
* Set the java name of the node.
*
* @param name the java name of node
*/
public void setJavaName(String name) {
javaName = name;
}
/**
* Get the mapped java package.
*
* @return the java package
*/
public String getPackage() {
if (pkg == null) {
throw new RuntimeException("Referencing package of a generated java file which is not set");
}
return pkg;
}
/**
* Set the node's package.
*
* @param nodePackage node's package
*/
public void setPackage(String nodePackage) {
pkg = nodePackage;
}
/**
* Sets directory package path for code generation.
*
* @param path directory package path for code generation
*/
public void setPackageFilePath(String path) {
relativeFilePath = path;
}
/**
* Gets directory package path for code generation.
*
* @return directory package path for code generation
*/
public String getPackageFilePath() {
return relativeFilePath;
}
/**
* Gets base directory package path for code generation.
*
* @return directory package path for code generation
*/
public String getBaseCodeGenPath() {
return codeGenDirFilePath;
}
/**
* Sets base directory package path for code generation.
*
* @param path base directory path
*/
public void setBaseCodeGenPath(String path) {
codeGenDirFilePath = path;
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
import java.util.SortedSet;
import java.util.TreeSet;
import org.onosproject.yangutils.datamodel.YangNode;
/**
* Generated Java file can contain imports.
*/
public class JavaImportData {
/**
* Flag to denote if any list in imported.
*/
private boolean isListToImport;
/**
* Sorted set of import info, to be used to maintain the set of classes to
* be imported in the generated class.
*/
private SortedSet<JavaQualifiedTypeInfo> importSet;
/**
* Default constructor.
*/
public JavaImportData() {
setImportSet(new TreeSet<JavaQualifiedTypeInfo>());
}
/**
* Get if the list needs to be imported.
*
* @return true if any of the attribute needs to be maintained as a list.
*/
public boolean getIfListImported() {
return isListToImport;
}
/**
* Set the status of importing list.
*
* @param isList status to mention list is bing imported.
*/
public void setIfListImported(boolean isList) {
isListToImport = isList;
}
/**
* Get the set containing the imported class/interface info.
*
* @return the set containing the imported class/interface info
*/
public SortedSet<JavaQualifiedTypeInfo> getImportSet() {
return importSet;
}
/**
* Assign the set containing the imported class/interface info.
*
* @param importSet the set containing the imported class/interface info
*/
private void setImportSet(SortedSet<JavaQualifiedTypeInfo> importSet) {
this.importSet = importSet;
}
/**
* Add an imported class/interface info if it is not already part of the
* collection.
*
* If already part of the collection, check if the packages are same, if so
* then return true, to denote it is already in the import collection, and
* it can be accessed without qualified access. If the packages do not
* match, then do not add to the import collection, and return false to
* denote, it is not added to import collection and needs to be accessed in
* a qualified manner.
*
* @param curNode current data model node
* @param newImportInfo class/interface info being imported
* @return status of new addition of class/interface to the import set
*/
public boolean addImportInfo(YangNode curNode, JavaQualifiedTypeInfo newImportInfo) {
if (!(curNode instanceof HasJavaImportData)) {
throw new RuntimeException("missing import info in data model node");
}
for (JavaQualifiedTypeInfo curImportInfo : ((HasJavaImportData) curNode).getJavaImportData().getImportSet()) {
if (curImportInfo.getClassInfo()
.contentEquals(newImportInfo.getClassInfo())) {
return curImportInfo.getPkgInfo()
.contentEquals(newImportInfo.getPkgInfo());
}
}
((HasJavaImportData) curNode).getJavaImportData().getImportSet().add(newImportInfo);
return true;
}
}
......@@ -18,12 +18,16 @@ package org.onosproject.yangutils.translator.tojava;
import java.util.Objects;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType;
import com.google.common.base.MoreObjects;
/**
* Maintains the information about individual imports in the generated file.
*/
public class ImportInfo implements Comparable {
public class JavaQualifiedTypeInfo implements Comparable<JavaQualifiedTypeInfo> {
/**
* Package location where the imported class/interface is defined.
......@@ -38,7 +42,7 @@ public class ImportInfo implements Comparable {
/**
* Default constructor.
*/
public ImportInfo() {
public JavaQualifiedTypeInfo() {
}
/**
......@@ -47,6 +51,7 @@ public class ImportInfo implements Comparable {
* @return the imported package info
*/
public String getPkgInfo() {
return pkgInfo;
}
......@@ -56,6 +61,7 @@ public class ImportInfo implements Comparable {
* @param pkgInfo the imported package info
*/
public void setPkgInfo(String pkgInfo) {
this.pkgInfo = pkgInfo;
}
......@@ -65,6 +71,7 @@ public class ImportInfo implements Comparable {
* @return the imported class/interface info
*/
public String getClassInfo() {
return classInfo;
}
......@@ -74,21 +81,187 @@ public class ImportInfo implements Comparable {
* @param classInfo the imported class/interface info
*/
public void setClassInfo(String classInfo) {
this.classInfo = classInfo;
}
/**
* Get the import info for an attribute, which needs to be used for code
* generation for import or for qualified access.
*
* @param curNode current data model node for which the java file is being
* generated.
* @param attrType type of attribute being added, it will be null, when the
* child class is added as an attribute
* @param attributeName name of the attribute being added, it will used in
* import info for child class.
* @param isListAttr is the added attribute going to be used as a list
* @return return the import info for this attribute
*/
public static JavaQualifiedTypeInfo getQualifiedTypeInfoOfLeafAttribute(YangNode curNode,
YangType<?> attrType, String attributeName,
boolean isListAttr) {
JavaQualifiedTypeInfo importInfo = new JavaQualifiedTypeInfo();
if (attrType == null) {
throw new RuntimeException("missing data type of leaf " + attributeName);
}
/*
* Current leaves holder is adding a leaf info as a attribute to the
* current class.
*/
String className = AttributesJavaDataType.getJavaImportClass(attrType, isListAttr);
if (className != null) {
/*
* Corresponding to the attribute type a class needs to be imported,
* since it can be a derived type or a usage of wrapper classes.
*/
importInfo.setClassInfo(className);
String classPkg = AttributesJavaDataType.getJavaImportPackage(attrType, isListAttr, className);
if (classPkg == null) {
throw new RuntimeException("import package cannot be null when the class is used");
}
importInfo.setPkgInfo(classPkg);
} else {
/*
* The attribute does not need a class to be imported, for example
* built in java types.
*/
String dataTypeName = AttributesJavaDataType.getJavaDataType(attrType);
if (dataTypeName == null) {
throw new RuntimeException("not supported data type");
}
importInfo.setClassInfo(dataTypeName);
}
return importInfo;
}
/**
* Get the import info for an attribute, which needs to be used for code
* generation for import or for qualified access.
*
* @param curNode current data model node for which the java file is being
* generated.
* @param attributeName name of the attribute being added, it will used in
* import info for child class.
* @param isListAttr is the added attribute going to be used as a list
* @return return the import info for this attribute
*/
public static JavaQualifiedTypeInfo getQualifiedTypeInfoOfCurNode(YangNode curNode,
String attributeName, boolean isListAttr) {
JavaQualifiedTypeInfo importInfo = new JavaQualifiedTypeInfo();
if (!(curNode instanceof HasJavaFileInfo)) {
throw new RuntimeException("missing java file information to get the package details "
+ "of attribute corresponding to child node");
}
/*
* The scenario when we need to add the child class as an attribute in
* the current class. The child class is in the package of the current
* classes package with current classes name.
*/
importInfo.setClassInfo(attributeName);
importInfo.setPkgInfo((((HasJavaFileInfo) curNode).getJavaFileInfo().getPackage() + "."
+ ((HasJavaFileInfo) curNode).getJavaFileInfo().getJavaName()).toLowerCase());
return importInfo;
}
/**
* Get if the attribute needs to be accessed in a qualified manner or not,
* if it needs to be imported, then the same needs to be done.
*
* @param curNode current cache of the data model node for which java file
* is bing generated
* @param importInfo import info for the current attribute being added
* @return status of the qualified access to the attribute
*/
public static boolean getIsQualifiedAccessOrAddToImportList(YangNode curNode,
JavaQualifiedTypeInfo importInfo) {
boolean isImportPkgEqualCurNodePkg;
if (!(curNode instanceof HasJavaFileInfo)) {
throw new RuntimeException("missing java file info for getting the qualified access");
}
if (importInfo.getClassInfo().contentEquals(
((HasJavaFileInfo) curNode).getJavaFileInfo().getJavaName())) {
/*
* if the current class name is same as the attribute class name,
* then the attribute must be accessed in a qualified manner.
*/
return true;
} else if (importInfo.getPkgInfo() != null) {
/*
* If the attribute type is having the package info, it is contender
* for import list and also need to check if it needs to be a
* qualified access.
*/
isImportPkgEqualCurNodePkg = isImportPkgEqualCurNodePkg(curNode, importInfo);
if (!isImportPkgEqualCurNodePkg) {
/*
* If the package of the attribute added is not same as the
* current class package, then it must either be imported for
* access or it must be a qualified access.
*/
if (!(curNode instanceof HasJavaImportData)) {
/*
* If the current data model node is not supposed to import
* data, then this is a usage issue and needs to be fixed.
*/
throw new RuntimeException("Current node needs to support Imports");
}
boolean isImportAdded = ((HasJavaImportData) curNode).getJavaImportData()
.addImportInfo(curNode, importInfo);
if (!isImportAdded) {
/*
* If the attribute type info is not imported, then it must
* be a qualified access.
*/
return true;
}
}
}
return false;
}
/**
* Check if the import info is same as the package of the current generated
* java file.
*
* @param curNode Java identifier of the current data model node
* @param importInfo import info for an attribute
* @return true if the import info is same as the current nodes package
* false otherwise
*/
public static boolean isImportPkgEqualCurNodePkg(
YangNode curNode, JavaQualifiedTypeInfo importInfo) {
if (!(curNode instanceof HasJavaFileInfo)) {
throw new RuntimeException("missing java file info for the data model node");
}
return ((HasJavaFileInfo) curNode).getJavaFileInfo().getPackage()
.contentEquals(importInfo.getPkgInfo()
+ "." + importInfo.getClassInfo());
}
@Override
public int hashCode() {
return Objects.hash(pkgInfo, classInfo);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof ImportInfo) {
ImportInfo other = (ImportInfo) obj;
if (obj instanceof JavaQualifiedTypeInfo) {
JavaQualifiedTypeInfo other = (JavaQualifiedTypeInfo) obj;
return Objects.equals(pkgInfo, other.pkgInfo) &&
Objects.equals(classInfo, other.classInfo);
}
......@@ -101,7 +274,8 @@ public class ImportInfo implements Comparable {
* @param importInfo matched import
* @return if equal or not
*/
public boolean exactMatch(ImportInfo importInfo) {
public boolean exactMatch(JavaQualifiedTypeInfo importInfo) {
return equals(importInfo)
&& Objects.equals(pkgInfo, importInfo.getPkgInfo())
&& Objects.equals(classInfo, importInfo.getClassInfo());
......@@ -109,6 +283,7 @@ public class ImportInfo implements Comparable {
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("pkgInfo", pkgInfo)
.add("classInfo", classInfo).toString();
......@@ -117,16 +292,11 @@ public class ImportInfo implements Comparable {
/**
* Check that there is no 2 objects with the same class name.
*
* @param o compared import info.
* @param other compared import info.
*/
@Override
public int compareTo(Object o) {
ImportInfo other;
if (o instanceof ImportInfo) {
other = (ImportInfo) o;
} else {
return -1;
}
public int compareTo(JavaQualifiedTypeInfo other) {
return getClassInfo().compareTo(other.getClassInfo());
}
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
import java.io.File;
import java.io.IOException;
import java.util.List;
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.translator.tojava.utils.JavaFileGenerator;
import org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax;
import org.onosproject.yangutils.utils.UtilConstants;
import org.onosproject.yangutils.utils.io.impl.FileSystemUtil;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.IMPL_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ATTRIBUTES_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EQUALS_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.HASH_CODE_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.TO_STRING_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getAttributeInfoOfLeaf;
import static org.onosproject.yangutils.translator.tojava.JavaAttributeInfo.getCurNodeAsAttributeInParent;
import static org.onosproject.yangutils.translator.tojava.utils.JavaCodeSnippetGen.getJavaAttributeDefination;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getParentNodeInGenCode;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getBuildString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getConstructor;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getDefaultConstructorString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEqualsMethod;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getGetterForClass;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getGetterString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getHashCodeMethod;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getOverRideString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getSetterForClass;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getSetterString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getToStringMethod;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.parseBuilderInterfaceBuildMethodString;
/**
* Provides implementation of java code fragments temporary implementations.
*/
public class TempJavaCodeFragmentFiles {
/**
* The variable which guides the types of temporary files generated using
* the temporary generated file types mask.
*/
private int generatedTempFiles;
/**
* Absolute path where the target java file needs to be generated.
*/
private String absoluteDirPath;
/**
* Name of java file that needs to be generated.
*/
private String generatedJavaClassName;
/**
* File type extension for temporary classes.
*/
private static final String TEMP_FILE_EXTENSION = ".tmp";
/**
* Folder suffix for temporary files folder.
*/
private static final String TEMP_FOLDER_NAME_SUFIX = "-Temp";
/**
* File name for getter method.
*/
private static final String GETTER_METHOD_FILE_NAME = "GetterMethod";
/**
* File name for getter method implementation.
*/
private static final String GETTER_METHOD_IMPL_FILE_NAME = "GetterMethodImpl";
/**
* File name for setter method.
*/
private static final String SETTER_METHOD_FILE_NAME = "SetterMethod";
/**
* File name for setter method implementation.
*/
private static final String SETTER_METHOD_IMPL_FILE_NAME = "SetterMethodImpl";
/**
* File name for constructor.
*/
private static final String CONSTRUCTOR_FILE_NAME = "Constructor";
/**
* File name for attributes.
*/
private static final String ATTRIBUTE_FILE_NAME = "Attributes";
/**
* File name for to string method.
*/
private static final String TO_STRING_METHOD_FILE_NAME = "ToString";
/**
* File name for hash code method.
*/
private static final String HASH_CODE_METHOD_FILE_NAME = "HashCode";
/**
* File name for equals method.
*/
private static final String EQUALS_METHOD_FILE_NAME = "Equals";
/**
* Temporary file handle for attribute.
*/
private File attributesTempFileHandle;
/**
* Temporary file handle for getter of interface.
*/
private File getterInterfaceTempFileHandle;
/**
* Temporary file handle for getter of class.
*/
private File getterImplTempFileHandle;
/**
* Temporary file handle for setter of interface.
*/
private File setterInterfaceTempFileHandle;
/**
* Temporary file handle for setter of class.
*/
private File setterImplTempFileHandle;
/**
* Temporary file handle for constructor of class.
*/
private File constructorImplTempFileHandle;
/**
* Temporary file handle for hash code method of class.
*/
private File hashCodeImplTempFileHandle;
/**
* Temporary file handle for equals method of class.
*/
private File equalsImplTempFileHandle;
/**
* Temporary file handle for to string method of class.
*/
private File toStringImplTempFileHandle;
/**
* Construct an object of temporary java code fragment.
*
* @param genFileType file generation type
* @param genDir file generation directory
* @param className class name
* @throws IOException when fails to create new file handle
*/
public TempJavaCodeFragmentFiles(int genFileType, String genDir, String className) throws IOException {
generatedTempFiles = 0;
absoluteDirPath = genDir;
generatedJavaClassName = className;
/**
* Initialize getter when generation file type matches to interface
* mask.
*/
if ((genFileType & INTERFACE_MASK) != 0) {
generatedTempFiles |= GETTER_FOR_INTERFACE_MASK;
}
/**
* Initialize getter and setter when generation file type matches to
* builder interface mask.
*/
if ((genFileType & BUILDER_INTERFACE_MASK) != 0) {
generatedTempFiles |= GETTER_FOR_INTERFACE_MASK;
generatedTempFiles |= SETTER_FOR_INTERFACE_MASK;
}
/**
* Initialize getterImpl, setterImpl and attributes when generation file
* type matches to builder class mask.
*/
if ((genFileType & BUILDER_CLASS_MASK) != 0) {
generatedTempFiles |= ATTRIBUTES_MASK;
generatedTempFiles |= GETTER_FOR_CLASS_MASK;
generatedTempFiles |= SETTER_FOR_CLASS_MASK;
}
/**
* Initialize getterImpl, attributes, constructor, hash code, equals and
* to strings when generation file type matches to impl class mask.
*/
if ((genFileType & IMPL_CLASS_MASK) != 0) {
generatedTempFiles |= ATTRIBUTES_MASK;
generatedTempFiles |= GETTER_FOR_CLASS_MASK;
generatedTempFiles |= CONSTRUCTOR_IMPL_MASK;
generatedTempFiles |= HASH_CODE_IMPL_MASK;
generatedTempFiles |= EQUALS_IMPL_MASK;
generatedTempFiles |= TO_STRING_IMPL_MASK;
}
if ((generatedTempFiles & ATTRIBUTES_MASK) != 0) {
setAttributesTempFileHandle(getTemporaryFileHandle(ATTRIBUTE_FILE_NAME));
}
if ((generatedTempFiles & GETTER_FOR_INTERFACE_MASK) != 0) {
setGetterInterfaceTempFileHandle(getTemporaryFileHandle(GETTER_METHOD_FILE_NAME));
}
if ((generatedTempFiles & SETTER_FOR_INTERFACE_MASK) != 0) {
setSetterInterfaceTempFileHandle(getTemporaryFileHandle(SETTER_METHOD_FILE_NAME));
}
if ((generatedTempFiles & GETTER_FOR_CLASS_MASK) != 0) {
setGetterImplTempFileHandle(getTemporaryFileHandle(GETTER_METHOD_IMPL_FILE_NAME));
}
if ((generatedTempFiles & SETTER_FOR_CLASS_MASK) != 0) {
setSetterImplTempFileHandle(getTemporaryFileHandle(SETTER_METHOD_IMPL_FILE_NAME));
}
if ((generatedTempFiles & CONSTRUCTOR_IMPL_MASK) != 0) {
setConstructorImplTempFileHandle(getTemporaryFileHandle(CONSTRUCTOR_FILE_NAME));
}
if ((generatedTempFiles & HASH_CODE_IMPL_MASK) != 0) {
setHashCodeImplTempFileHandle(getTemporaryFileHandle(HASH_CODE_METHOD_FILE_NAME));
}
if ((generatedTempFiles & EQUALS_IMPL_MASK) != 0) {
setEqualsImplTempFileHandle(getTemporaryFileHandle(EQUALS_METHOD_FILE_NAME));
}
if ((generatedTempFiles & TO_STRING_IMPL_MASK) != 0) {
setToStringImplTempFileHandle(getTemporaryFileHandle(TO_STRING_METHOD_FILE_NAME));
}
}
/**
* Returns attribute's temporary file handle.
*
* @return temporary file handle
*/
public File getAttributesTempFileHandle() {
return attributesTempFileHandle;
}
/**
* Sets attribute's temporary file handle.
*
* @param attributeForClass file handle for attribute
*/
public void setAttributesTempFileHandle(File attributeForClass) {
attributesTempFileHandle = attributeForClass;
}
/**
* Returns getter methods's temporary file handle.
*
* @return temporary file handle
*/
public File getGetterInterfaceTempFileHandle() {
return getterInterfaceTempFileHandle;
}
/**
* Sets to getter method's temporary file handle.
*
* @param getterForInterface file handle for to getter method
*/
public void setGetterInterfaceTempFileHandle(File getterForInterface) {
getterInterfaceTempFileHandle = getterForInterface;
}
/**
* Returns getter method's impl's temporary file handle.
*
* @return temporary file handle
*/
public File getGetterImplTempFileHandle() {
return getterImplTempFileHandle;
}
/**
* Sets to getter method's impl's temporary file handle.
*
* @param getterImpl file handle for to getter method's impl
*/
public void setGetterImplTempFileHandle(File getterImpl) {
getterImplTempFileHandle = getterImpl;
}
/**
* Returns setter method's temporary file handle.
*
* @return temporary file handle
*/
public File getSetterInterfaceTempFileHandle() {
return setterInterfaceTempFileHandle;
}
/**
* Sets to setter method's temporary file handle.
*
* @param setterForInterface file handle for to setter method
*/
public void setSetterInterfaceTempFileHandle(File setterForInterface) {
setterInterfaceTempFileHandle = setterForInterface;
}
/**
* Returns setter method's impl's temporary file handle.
*
* @return temporary file handle
*/
public File getSetterImplTempFileHandle() {
return setterImplTempFileHandle;
}
/**
* Sets to setter method's impl's temporary file handle.
*
* @param setterImpl file handle for to setter method's implementation class
*/
public void setSetterImplTempFileHandle(File setterImpl) {
setterImplTempFileHandle = setterImpl;
}
/**
* Returns constructor's temporary file handle.
*
* @return temporary file handle
*/
public File getConstructorImplTempFileHandle() {
return constructorImplTempFileHandle;
}
/**
* Sets to constructor's temporary file handle.
*
* @param constructor file handle for to constructor
*/
public void setConstructorImplTempFileHandle(File constructor) {
constructorImplTempFileHandle = constructor;
}
/**
* Returns hash code method's temporary file handle.
*
* @return temporary file handle
*/
public File getHashCodeImplTempFileHandle() {
return hashCodeImplTempFileHandle;
}
/**
* Sets hash code method's temporary file handle.
*
* @param hashCodeMethod file handle for hash code method
*/
public void setHashCodeImplTempFileHandle(File hashCodeMethod) {
hashCodeImplTempFileHandle = hashCodeMethod;
}
/**
* Returns equals mehtod's temporary file handle.
*
* @return temporary file handle
*/
public File getEqualsImplTempFileHandle() {
return equalsImplTempFileHandle;
}
/**
* Sets equals method's temporary file handle.
*
* @param equalsMethod file handle for to equals method
*/
public void setEqualsImplTempFileHandle(File equalsMethod) {
equalsImplTempFileHandle = equalsMethod;
}
/**
* Returns to string method's temporary file handle.
*
* @return temporary file handle
*/
public File getToStringImplTempFileHandle() {
return toStringImplTempFileHandle;
}
/**
* Sets to string method's temporary file handle.
*
* @param toStringMethod file handle for to string method
*/
public void setToStringImplTempFileHandle(File toStringMethod) {
toStringImplTempFileHandle = toStringMethod;
}
/**
* Adds attribute for class.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addAttribute(JavaAttributeInfo attr) throws IOException {
appendToFile(getAttributesTempFileHandle(), parseAttribute(attr) + UtilConstants.FOUR_SPACE_INDENTATION);
}
/**
* Adds getter for interface.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addGetterForInterface(JavaAttributeInfo attr) throws IOException {
appendToFile(getGetterInterfaceTempFileHandle(),
getGetterString(attr) + UtilConstants.NEW_LINE);
}
/**
* Adds getter method's impl for class.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addGetterImpl(JavaAttributeInfo attr) throws IOException {
appendToFile(getGetterImplTempFileHandle(),
getOverRideString() + getGetterForClass(attr) + UtilConstants.NEW_LINE);
}
/**
* Adds setter for interface.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addSetterForInterface(JavaAttributeInfo attr) throws IOException {
appendToFile(getSetterInterfaceTempFileHandle(),
getSetterString(attr, generatedJavaClassName) + UtilConstants.NEW_LINE);
}
/**
* Adds setter's implementation for class.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addSetterImpl(JavaAttributeInfo attr) throws IOException {
appendToFile(getSetterImplTempFileHandle(),
getOverRideString() + getSetterForClass(attr, generatedJavaClassName) + UtilConstants.NEW_LINE);
}
/**
* Adds build method for interface.
*
* @return build method for interface
* @throws IOException when fails to append to temporary file
*/
public String addBuildMethodForInterface() throws IOException {
return parseBuilderInterfaceBuildMethodString(generatedJavaClassName);
}
/**
* Adds build method's implementation for class.
*
* @return build method implementation for class
* @throws IOException when fails to append to temporary file
*/
public String addBuildMethodImpl() throws IOException {
return getBuildString(generatedJavaClassName) + UtilConstants.NEW_LINE;
}
/**
* Adds constructor for class.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addConstructor(JavaAttributeInfo attr) throws IOException {
appendToFile(getConstructorImplTempFileHandle(), getConstructor(generatedJavaClassName, attr));
}
/**
* Adds default constructor for class.
*
* @return default constructor for class
* @throws IOException when fails to append to file
*/
public String addDefaultConstructor() throws IOException {
return UtilConstants.NEW_LINE + getDefaultConstructorString(generatedJavaClassName + UtilConstants.BUILDER,
UtilConstants.PUBLIC);
}
/**
* Adds hash code method for class.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addHashCodeMethod(JavaAttributeInfo attr) throws IOException {
appendToFile(getHashCodeImplTempFileHandle(), getHashCodeMethod(attr) + UtilConstants.NEW_LINE);
}
/**
* Adds equals method for class.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addEqualsMethod(JavaAttributeInfo attr) throws IOException {
appendToFile(getEqualsImplTempFileHandle(), getEqualsMethod(attr) + UtilConstants.NEW_LINE);
}
/**
* Adds ToString method for class.
*
* @param attr attribute info
* @throws IOException when fails to append to temporary file
*/
public void addToStringMethod(JavaAttributeInfo attr) throws IOException {
appendToFile(getToStringImplTempFileHandle(), getToStringMethod(attr) + UtilConstants.NEW_LINE);
}
/**
* Returns a temporary file handle for the specific file type.
*
* @param fileName file name
* @return temporary file handle
* @throws IOException when fails to create new file handle
*/
private File getTemporaryFileHandle(String fileName) throws IOException {
String path = getTempDirPath();
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(path + fileName + TEMP_FILE_EXTENSION);
if (!file.exists()) {
file.createNewFile();
} else {
file.delete();
file.createNewFile();
}
return file;
}
/**
* Returns data from the temporary files.
*
* @param file temporary file handle
* @return stored data from temporary files
* @throws IOException when failed to get data from the given file
*/
public String getTemporaryDataFromFileHandle(File file) throws IOException {
String path = getTempDirPath();
if (new File(path + file.getName()).exists()) {
return FileSystemUtil.readAppendFile(path + file.getName(), UtilConstants.EMPTY_STRING);
} else {
throw new IOException("Unable to get data from the given "
+ file.getName() + " file for "
+ generatedJavaClassName + UtilConstants.PERIOD);
}
}
/**
* Returns temporary directory path.
*
* @return directory path
*/
private String getTempDirPath() {
return absoluteDirPath.replace(UtilConstants.PERIOD, UtilConstants.SLASH)
+ File.separator + generatedJavaClassName + TEMP_FOLDER_NAME_SUFIX + File.separator;
}
/**
* Parse attribute to get the attribute string.
*
* @param attr attribute info
* @return attribute string
*/
private String parseAttribute(JavaAttributeInfo attr) {
/*
* TODO: check if this utility needs to be called or move to the caller
*/
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (attr.isQualifiedName()) {
return getJavaAttributeDefination(attr.getImportInfo().getPkgInfo(), attr.getImportInfo().getClassInfo(),
attributeName, attr.isListAttr());
} else {
return getJavaAttributeDefination(null, attr.getImportInfo().getClassInfo(), attributeName,
attr.isListAttr());
}
}
/**
* Append content to temporary file.
*
* @param file temporary file
* @param data data to be appended
* @throws IOException when fails to append to file
*/
private void appendToFile(File file, String data) throws IOException {
try {
JavaFileGenerator.insert(file, data);
} catch (IOException ex) {
throw new IOException("failed to write in temp file.");
}
}
/**
* Adds current node info as and attribute to the parent generated file.
*
* @param curNode current node which needs to be added as an attribute in
* the parent generated code
* @param isList is list construct
* @throws IOException IO operation exception
*/
public void addCurNodeInfoInParentTempFile(YangNode curNode,
boolean isList) throws IOException {
YangNode parent = getParentNodeInGenCode(curNode);
if (!(parent instanceof JavaCodeGenerator)) {
throw new RuntimeException("missing parent node to contain current node info in generated file");
}
JavaAttributeInfo javaAttributeInfo = getCurNodeAsAttributeInParent(curNode,
parent, isList);
if (!(parent instanceof HasTempJavaCodeFragmentFiles)) {
throw new RuntimeException("missing parent temp file handle");
}
((HasTempJavaCodeFragmentFiles) parent)
.getTempJavaCodeFragmentFiles()
.addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo);
}
/**
* Adds leaf attributes in generated files.
*
* @param listOfLeaves list of YANG leaf
* @param curNode current data model node
* @throws IOException IO operation fail
*/
private void addLeavesInfoToTempFiles(List<YangLeaf> listOfLeaves,
YangNode curNode) throws IOException {
if (listOfLeaves != null) {
for (YangLeaf leaf : listOfLeaves) {
JavaAttributeInfo javaAttributeInfo = getAttributeInfoOfLeaf(curNode,
leaf.getDataType(),
leaf.getLeafName(), false);
addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo);
}
}
}
/**
* Adds leaf list's attributes in generated files.
*
* @param listOfLeafList list of YANG leaves
* @param curNode cached file handle
* @throws IOException IO operation fail
*/
private void addLeafListInfoToTempFiles(List<YangLeafList> listOfLeafList,
YangNode curNode) throws IOException {
if (listOfLeafList != null) {
/*
* Check if the attribute is of type list, then the java.lang.list
* needs to be imported.
*/
if (listOfLeafList.size() != 0) {
if (!(curNode instanceof HasJavaImportData)) {
throw new RuntimeException("missing import info in current data model node");
}
((HasJavaImportData) curNode).getJavaImportData()
.setIfListImported(true);
}
for (YangLeafList leafList : listOfLeafList) {
JavaAttributeInfo javaAttributeInfo = getAttributeInfoOfLeaf(
curNode, leafList.getDataType(), leafList.getLeafName(),
true);
addJavaSnippetInfoToApplicableTempFiles(javaAttributeInfo);
}
}
}
/**
* Add all the leaves in the current data model node as part of the
* generated temporary file.
*
* @param curNode java file info of the generated file
* @throws IOException IO operation fail
*/
public void addCurNodeLeavesInfoToTempFiles(YangNode curNode) throws IOException {
if (curNode instanceof YangLeavesHolder) {
YangLeavesHolder leavesHolder = (YangLeavesHolder) curNode;
addLeavesInfoToTempFiles(leavesHolder.getListOfLeaf(), curNode);
addLeafListInfoToTempFiles(leavesHolder.getListOfLeafList(), curNode);
}
}
/**
* Add the new attribute info to the target generated temporary files.
*
* @param newAttrInfo the attribute info that needs to be added to temporary
* files
* @throws IOException IO operation fail
*/
void addJavaSnippetInfoToApplicableTempFiles(JavaAttributeInfo newAttrInfo)
throws IOException {
if ((generatedTempFiles & ATTRIBUTES_MASK) != 0) {
addAttribute(newAttrInfo);
}
if ((generatedTempFiles & GETTER_FOR_INTERFACE_MASK) != 0) {
addGetterForInterface(newAttrInfo);
}
if ((generatedTempFiles & SETTER_FOR_INTERFACE_MASK) != 0) {
addSetterForInterface(newAttrInfo);
}
if ((generatedTempFiles & GETTER_FOR_CLASS_MASK) != 0) {
addGetterImpl(newAttrInfo);
}
if ((generatedTempFiles & SETTER_FOR_CLASS_MASK) != 0) {
addSetterImpl(newAttrInfo);
}
if ((generatedTempFiles & CONSTRUCTOR_IMPL_MASK) != 0) {
addConstructor(newAttrInfo);
}
if ((generatedTempFiles & HASH_CODE_IMPL_MASK) != 0) {
addHashCodeMethod(newAttrInfo);
}
if ((generatedTempFiles & EQUALS_IMPL_MASK) != 0) {
addEqualsMethod(newAttrInfo);
}
if ((generatedTempFiles & TO_STRING_IMPL_MASK) != 0) {
addToStringMethod(newAttrInfo);
}
return;
}
/**
* Removes all temporary file handles.
*
* @throws IOException when failed to delete the temporary files
*/
public void close() throws IOException {
closeFile(GETTER_METHOD_FILE_NAME);
getTemporaryFileHandle(GETTER_METHOD_FILE_NAME).delete();
closeFile(GETTER_METHOD_IMPL_FILE_NAME);
getTemporaryFileHandle(GETTER_METHOD_IMPL_FILE_NAME).delete();
closeFile(SETTER_METHOD_FILE_NAME);
getTemporaryFileHandle(SETTER_METHOD_FILE_NAME).delete();
closeFile(SETTER_METHOD_IMPL_FILE_NAME);
getTemporaryFileHandle(SETTER_METHOD_IMPL_FILE_NAME).delete();
closeFile(CONSTRUCTOR_FILE_NAME);
getTemporaryFileHandle(CONSTRUCTOR_FILE_NAME).delete();
closeFile(ATTRIBUTE_FILE_NAME);
getTemporaryFileHandle(ATTRIBUTE_FILE_NAME).delete();
closeFile(HASH_CODE_METHOD_FILE_NAME);
getTemporaryFileHandle(HASH_CODE_METHOD_FILE_NAME).delete();
closeFile(TO_STRING_METHOD_FILE_NAME);
getTemporaryFileHandle(TO_STRING_METHOD_FILE_NAME).delete();
closeFile(EQUALS_METHOD_FILE_NAME);
getTemporaryFileHandle(EQUALS_METHOD_FILE_NAME).delete();
}
/**
* Closes the file handle for temporary file.
*
* @param fileName temporary file's name
* @throws IOException when failed to close the file handle
*/
private void closeFile(String fileName) throws IOException {
FileSystemUtil.updateFileHandle(new File(fileName), null, true);
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangAugment;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
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.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Augment information extended to support java code generation.
*/
public class YangJavaAugment extends YangAugment
implements JavaCodeGenerator, HasJavaFileInfo,
HasJavaImportData, HasTempJavaCodeFragmentFiles {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* File handle to maintain temporary java code fragments as per the code
* snippet types.
*/
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* Default constructor.
*/
public YangJavaAugment() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Get the temporary file handle.
*
* @return temporary file handle
*/
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
if (tempFileHandle == null) {
throw new RuntimeException("missing temp file hand for current node "
+ getJavaFileInfo().getJavaName());
}
return tempFileHandle;
}
/**
* Set temporary file handle.
*
* @param fileHandle temporary file handle
*/
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempFileHandle = fileHandle;
}
/**
* Prepare the information for java code generation corresponding to YANG
* augment info.
*
* @param codeGenDir code generation directory
* @throws IOException IO operation fail
*/
@Override
public void generateCodeEntry(String codeGenDir) throws IOException {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getCurNodePackage(this));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
String absloutePath = getAbsolutePackagePath(
getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath());
setTempJavaCodeFragmentFiles(new TempJavaCodeFragmentFiles(
getJavaFileInfo().getGeneratedFileTypes(), absloutePath,
getJavaFileInfo().getJavaName()));
getTempJavaCodeFragmentFiles().addCurNodeLeavesInfoToTempFiles(this);
getTempJavaCodeFragmentFiles().addCurNodeInfoInParentTempFile(this, false);
}
/**
* Create a java file using the YANG grouping info.
*/
@Override
public void generateCodeExit() {
// TODO Auto-generated method stub
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangCase;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
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.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Case information extended to support java code generation.
*/
public class YangJavaCase extends YangCase
implements JavaCodeGenerator, HasJavaFileInfo,
HasJavaImportData, HasTempJavaCodeFragmentFiles {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* File handle to maintain temporary java code fragments as per the code
* snippet types.
*/
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* Default constructor.
*/
public YangJavaCase() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Get the temporary file handle.
*
* @return temporary file handle
*/
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
if (tempFileHandle == null) {
throw new RuntimeException("missing temp file hand for current node "
+ getJavaFileInfo().getJavaName());
}
return tempFileHandle;
}
/**
* Set temporary file handle.
*
* @param fileHandle temporary file handle
*/
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempFileHandle = fileHandle;
}
/**
* Prepare the information for java code generation corresponding to YANG
* case info.
*
* @param codeGenDir code generation directory
* @throws IOException IO operation fail
*/
@Override
public void generateCodeEntry(String codeGenDir) throws IOException {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getCurNodePackage(this));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
String absloutePath = getAbsolutePackagePath(
getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath());
setTempJavaCodeFragmentFiles(new TempJavaCodeFragmentFiles(
getJavaFileInfo().getGeneratedFileTypes(), absloutePath,
getJavaFileInfo().getJavaName()));
getTempJavaCodeFragmentFiles().addCurNodeLeavesInfoToTempFiles(this);
getTempJavaCodeFragmentFiles().addCurNodeInfoInParentTempFile(this, false);
}
/**
* Create a java file using the YANG grouping info.
*/
@Override
public void generateCodeExit() {
// TODO Auto-generated method stub
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangChoice;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
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.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Choice information extended to support java code generation.
*/
public class YangJavaChoice extends YangChoice
implements JavaCodeGenerator, HasJavaFileInfo,
HasJavaImportData, HasTempJavaCodeFragmentFiles {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* File handle to maintain temporary java code fragments as per the code
* snippet types.
*/
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* Default constructor.
*/
public YangJavaChoice() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Get the temporary file handle.
*
* @return temporary file handle
*/
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
if (tempFileHandle == null) {
throw new RuntimeException("missing temp file hand for current node "
+ getJavaFileInfo().getJavaName());
}
return tempFileHandle;
}
/**
* Set temporary file handle.
*
* @param fileHandle temporary file handle
*/
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempFileHandle = fileHandle;
}
/**
* Prepare the information for java code generation corresponding to YANG
* case info.
*
* @param codeGenDir code generation directory
* @throws IOException IO operation fail
*/
@Override
public void generateCodeEntry(String codeGenDir) throws IOException {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getCurNodePackage(this));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
String absloutePath = getAbsolutePackagePath(
getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath());
setTempJavaCodeFragmentFiles(new TempJavaCodeFragmentFiles(
getJavaFileInfo().getGeneratedFileTypes(), absloutePath,
getJavaFileInfo().getJavaName()));
// TODO:getTempJavaCodeFragmentFiles().addCurNodeLeavesInfoToTempFiles(this);
getTempJavaCodeFragmentFiles().addCurNodeInfoInParentTempFile(this, false);
}
/**
* Create a java file using the YANG grouping info.
*/
@Override
public void generateCodeExit() {
// TODO Auto-generated method stub
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangContainer;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.GenerateJavaCodeExitBuilder.generateJavaFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
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.io.impl.FileSystemUtil.createPackage;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Container information extended to support java code generation.
*/
public class YangJavaContainer extends YangContainer
implements JavaCodeGenerator, HasJavaFileInfo,
HasJavaImportData, HasTempJavaCodeFragmentFiles {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* File handle to maintain temporary java code fragments as per the code
* snippet types.
*/
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* Default constructor.
*/
public YangJavaContainer() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Get the temporary file handle.
*
* @return temporary file handle
*/
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
if (tempFileHandle == null) {
throw new RuntimeException("Missing temp file handle for current node "
+ getJavaFileInfo().getJavaName());
}
return tempFileHandle;
}
/**
* Set temporary file handle.
*
* @param fileHandle temporary file handle
*/
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempFileHandle = fileHandle;
}
/**
* Prepare the information for java code generation corresponding to YANG
* container info.
*
* @param codeGenDir code generation directory
* @throws IOException IO operation fail
*/
@Override
public void generateCodeEntry(String codeGenDir) throws IOException {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getCurNodePackage(this));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
String absloutePath = getAbsolutePackagePath(
getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath());
createPackage(absloutePath, getName());
setTempJavaCodeFragmentFiles(new TempJavaCodeFragmentFiles(
getJavaFileInfo().getGeneratedFileTypes(), absloutePath,
getJavaFileInfo().getJavaName()));
getTempJavaCodeFragmentFiles().addCurNodeLeavesInfoToTempFiles(this);
getTempJavaCodeFragmentFiles().addCurNodeInfoInParentTempFile(this, false);
}
/**
* Create a java file using the YANG grouping info.
*
* @throws IOException IO operation fail
*/
@Override
public void generateCodeExit() throws IOException {
generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
getTempJavaCodeFragmentFiles().close();
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangGrouping;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
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.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Grouping information extended to support java code generation.
*/
public class YangJavaGrouping extends YangGrouping
implements JavaCodeGenerator, HasJavaFileInfo,
HasJavaImportData, HasTempJavaCodeFragmentFiles {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* File handle to maintain temporary java code fragments as per the code
* snippet types.
*/
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* Default constructor.
*/
public YangJavaGrouping() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Get the temporary file handle.
*
* @return temporary file handle
*/
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
if (tempFileHandle == null) {
throw new RuntimeException("missing temp file hand for current node "
+ getJavaFileInfo().getJavaName());
}
return tempFileHandle;
}
/**
* Set temporary file handle.
*
* @param fileHandle temporary file handle
*/
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempFileHandle = fileHandle;
}
/**
* Prepare the information for java code generation corresponding to YANG
* container info.
*
* @param codeGenDir code generation directory
* @throws IOException IO operation fail
*/
@Override
public void generateCodeEntry(String codeGenDir) throws IOException {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getCurNodePackage(this));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
String absloutePath = getAbsolutePackagePath(
getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath());
setTempJavaCodeFragmentFiles(new TempJavaCodeFragmentFiles(
getJavaFileInfo().getGeneratedFileTypes(), absloutePath,
getJavaFileInfo().getJavaName()));
getTempJavaCodeFragmentFiles().addCurNodeLeavesInfoToTempFiles(this);
getTempJavaCodeFragmentFiles().addCurNodeInfoInParentTempFile(this, false);
}
/**
* Create a java file using the YANG grouping info.
*/
@Override
public void generateCodeExit() {
// TODO Auto-generated method stub
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangList;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.GenerateJavaCodeExitBuilder.generateJavaFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
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.io.impl.FileSystemUtil.createPackage;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* YANG List information extended to support java code generation.
*/
public class YangJavaList extends YangList
implements JavaCodeGenerator, HasJavaFileInfo,
HasJavaImportData, HasTempJavaCodeFragmentFiles {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* File handle to maintain temporary java code fragments as per the code
* snippet types.
*/
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* Default constructor.
*/
public YangJavaList() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Get the temporary file handle.
*
* @return temporary file handle
*/
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
if (tempFileHandle == null) {
throw new RuntimeException("missing temp file hand for current node "
+ getJavaFileInfo().getJavaName());
}
return tempFileHandle;
}
/**
* Set temporary file handle.
*
* @param fileHandle temporary file handle
*/
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempFileHandle = fileHandle;
}
/**
* Prepare the information for java code generation corresponding to YANG
* container info.
*
* @param codeGenDir code generation directory
* @throws IOException IO operation fail
*/
@Override
public void generateCodeEntry(String codeGenDir) throws IOException {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getCurNodePackage(this));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
String absloutePath = getAbsolutePackagePath(
getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath());
createPackage(absloutePath, getName());
setTempJavaCodeFragmentFiles(new TempJavaCodeFragmentFiles(
getJavaFileInfo().getGeneratedFileTypes(), absloutePath,
getJavaFileInfo().getJavaName()));
getTempJavaCodeFragmentFiles().addCurNodeLeavesInfoToTempFiles(this);
getTempJavaCodeFragmentFiles().addCurNodeInfoInParentTempFile(this, true);
}
/**
* Create a java file using the YANG grouping info.
*
* @throws IOException IO operation fail
*/
@Override
public void generateCodeExit() throws IOException {
generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
getTempJavaCodeFragmentFiles().close();
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangModule;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.GenerateJavaCodeExitBuilder.generateJavaFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getRootPackage;
import static org.onosproject.yangutils.utils.io.impl.FileSystemUtil.createPackage;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Module information extended to support java code generation.
*/
public class YangJavaModule extends YangModule
implements JavaCodeGenerator, HasJavaFileInfo,
HasJavaImportData, HasTempJavaCodeFragmentFiles {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* File handle to maintain temporary java code fragments as per the code
* snippet types.
*/
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* Create a YANG node of module type.
*/
public YangJavaModule() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Get the temporary file handle.
*
* @return temporary file handle
*/
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
if (tempFileHandle == null) {
throw new RuntimeException("missing temp file hand for current node "
+ getJavaFileInfo().getJavaName());
}
return tempFileHandle;
}
/**
* Set temporary file handle.
*
* @param fileHandle temporary file handle
*/
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempFileHandle = fileHandle;
}
/**
* Generates java code for module.
*
* @param baseCodeGenDir code generation directory
* @throws IOException when fails to generate the source files
*/
@Override
public void generateCodeEntry(String baseCodeGenDir) throws IOException {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getRootPackage(getVersion(), getNameSpace().getUri(),
getRevision().getRevDate()));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(baseCodeGenDir);
String absloutePath = getAbsolutePackagePath(
getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath());
createPackage(absloutePath, getName());
setTempJavaCodeFragmentFiles(new TempJavaCodeFragmentFiles(
getJavaFileInfo().getGeneratedFileTypes(), absloutePath,
getJavaFileInfo().getJavaName()));
getTempJavaCodeFragmentFiles().addCurNodeLeavesInfoToTempFiles(this);
}
@Override
public void generateCodeExit() throws IOException {
generateJavaFile(GENERATE_INTERFACE_WITH_BUILDER, this);
getTempJavaCodeFragmentFiles().close();
return;
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import java.io.IOException;
import org.onosproject.yangutils.datamodel.YangBelongsTo;
import org.onosproject.yangutils.datamodel.YangSubModule;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getRootPackage;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getAbsolutePackagePath;
/**
* Sub module information extended to support java code generation.
*/
public class YangJavaSubModule extends YangSubModule
implements JavaCodeGenerator, HasJavaFileInfo,
HasJavaImportData, HasTempJavaCodeFragmentFiles {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* File handle to maintain temporary java code fragments as per the code
* snippet types.
*/
private TempJavaCodeFragmentFiles tempFileHandle;
/**
* Default constructor.
*/
public YangJavaSubModule() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Get the temporary file handle.
*
* @return temporary file handle
*/
@Override
public TempJavaCodeFragmentFiles getTempJavaCodeFragmentFiles() {
if (tempFileHandle == null) {
throw new RuntimeException("missing temp file hand for current node "
+ getJavaFileInfo().getJavaName());
}
return tempFileHandle;
}
/**
* Set temporary file handle.
*
* @param fileHandle temporary file handle
*/
@Override
public void setTempJavaCodeFragmentFiles(TempJavaCodeFragmentFiles fileHandle) {
tempFileHandle = fileHandle;
}
/**
* Get the name space of the module to which the sub module belongs to.
*
* @param belongsToInfo Information of the module to which the sub module
* belongs
* @return the name space string of the module.
*/
private String getNameSpaceFromModule(YangBelongsTo belongsToInfo) {
// TODO Auto-generated method stub
return "";
}
/**
* Prepare the information for java code generation corresponding to YANG
* container info.
*
* @param codeGenDir code generation directory
* @throws IOException IO operation fail
*/
@Override
public void generateCodeEntry(String codeGenDir) throws IOException {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getRootPackage(getVersion(),
getNameSpaceFromModule(getBelongsTo()),
getRevision().getRevDate()));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
String absloutePath = getAbsolutePackagePath(
getJavaFileInfo().getBaseCodeGenPath(),
getJavaFileInfo().getPackageFilePath());
setTempJavaCodeFragmentFiles(new TempJavaCodeFragmentFiles(
getJavaFileInfo().getGeneratedFileTypes(), absloutePath,
getJavaFileInfo().getJavaName()));
getTempJavaCodeFragmentFiles().addCurNodeLeavesInfoToTempFiles(this);
}
/**
* Create a java file using the YANG grouping info.
*/
@Override
public void generateCodeExit() {
// TODO Auto-generated method stub
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import org.onosproject.yangutils.datamodel.YangTypeDef;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCurNodePackage;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
/**
* Type define information extended to support java code generation.
*/
public class YangJavaTypeDef extends YangTypeDef
implements JavaCodeGenerator, HasJavaFileInfo, HasJavaImportData {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* Default constructor.
*/
public YangJavaTypeDef() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Prepare the information for java code generation corresponding to YANG
* container info.
*
* @param codeGenDir code generation directory
*/
@Override
public void generateCodeEntry(String codeGenDir) {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getCurNodePackage(this));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
// TODO: generate type define temporary files
}
/**
* Create a java file using the YANG grouping info.
*/
@Override
public void generateCodeExit() {
// TODO Auto-generated method stub
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
import org.onosproject.yangutils.datamodel.YangUses;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.JavaCodeGenerator;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCamelCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCurNodePackage;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getPackageDirPathFromJavaJPackage;
/**
* Uses information extended to support java code generation.
*/
public class YangJavaUses extends YangUses implements JavaCodeGenerator, HasJavaFileInfo, HasJavaImportData {
/**
* Contains the information of the java file being generated.
*/
private JavaFileInfo javaFileInfo;
/**
* Contains information of the imports to be inserted in the java file
* generated.
*/
private JavaImportData javaImportData;
/**
* Default constructor.
*/
public YangJavaUses() {
super();
setJavaFileInfo(new JavaFileInfo());
setJavaImportData(new JavaImportData());
getJavaFileInfo().setGeneratedFileTypes(GENERATE_INTERFACE_WITH_BUILDER);
}
/**
* Get the generated java file information.
*
* @return generated java file information
*/
@Override
public JavaFileInfo getJavaFileInfo() {
if (javaFileInfo == null) {
throw new RuntimeException("Missing java info in java datamodel node");
}
return javaFileInfo;
}
/**
* Set the java file info object.
*
* @param javaInfo java file info object
*/
@Override
public void setJavaFileInfo(JavaFileInfo javaInfo) {
javaFileInfo = javaInfo;
}
/**
* Get the data of java imports to be included in generated file.
*
* @return data of java imports to be included in generated file
*/
@Override
public JavaImportData getJavaImportData() {
return javaImportData;
}
/**
* Set the data of java imports to be included in generated file.
*
* @param javaImportData data of java imports to be included in generated
* file
*/
@Override
public void setJavaImportData(JavaImportData javaImportData) {
this.javaImportData = javaImportData;
}
/**
* Prepare the information for java code generation corresponding to YANG
* container info.
*
* @param codeGenDir code generation directory
*/
@Override
public void generateCodeEntry(String codeGenDir) {
getJavaFileInfo().setJavaName(getCaptialCase(getCamelCase(getName())));
getJavaFileInfo().setPackage(getCurNodePackage(this));
getJavaFileInfo().setPackageFilePath(
getPackageDirPathFromJavaJPackage(getJavaFileInfo().getPackage()));
getJavaFileInfo().setBaseCodeGenPath(codeGenDir);
//TODO:addCurNodeLeavesInfoToTempFiles(this);
//TODO:addCurNodeInfoInParentTempFile(this, false);
}
/**
* Create a java file using the YANG grouping info.
*/
@Override
public void generateCodeExit() {
// TODO Auto-generated method stub
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Maintains application's schema mapped to java classes / interfaces.
*/
package org.onosproject.yangutils.translator.tojava.javamodel;
......@@ -16,8 +16,12 @@
package org.onosproject.yangutils.translator.tojava.utils;
import java.util.Set;
import java.util.TreeSet;
import org.onosproject.yangutils.datamodel.YangDataTypes;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
import org.onosproject.yangutils.utils.UtilConstants;
/**
......@@ -25,6 +29,8 @@ import org.onosproject.yangutils.utils.UtilConstants;
*/
public final class AttributesJavaDataType {
private static Set<JavaQualifiedTypeInfo> importInfo = new TreeSet<>();
/**
* Default constructor.
*/
......@@ -32,6 +38,24 @@ public final class AttributesJavaDataType {
}
/**
* Returns import info.
*
* @return import info
*/
public static Set<JavaQualifiedTypeInfo> getImportInfo() {
return importInfo;
}
/**
* Adds import info to the import info set.
*
* @param importData import info
*/
public static void addImportInfo(JavaQualifiedTypeInfo importData) {
getImportInfo().add(importData);
}
/**
* Returns java type.
*
* @param yangType YANG type
......@@ -134,7 +158,8 @@ public final class AttributesJavaDataType {
} else if (type.equals(YangDataTypes.INSTANCE_IDENTIFIER)) {
//TODO:INSTANCE_IDENTIFIER
} else if (type.equals(YangDataTypes.DERIVED)) {
//TODO:DERIVED
return JavaIdentifierSyntax
.getCaptialCase(JavaIdentifierSyntax.getCamelCase(yangType.getDataTypeName()));
}
} else {
if (type.equals(YangDataTypes.UINT64)) {
......@@ -160,7 +185,8 @@ public final class AttributesJavaDataType {
} else if (type.equals(YangDataTypes.INSTANCE_IDENTIFIER)) {
//TODO:INSTANCE_IDENTIFIER
} else if (type.equals(YangDataTypes.DERIVED)) {
//TODO:DERIVED
return JavaIdentifierSyntax
.getCaptialCase(JavaIdentifierSyntax.getCamelCase(yangType.getDataTypeName()));
}
}
return null;
......@@ -171,9 +197,10 @@ public final class AttributesJavaDataType {
*
* @param yangType YANG type
* @param isListAttr if the attribute is of list type
* @param classInfo java import class info
* @return java import package
*/
public static String getJavaImportPackage(YangType<?> yangType, boolean isListAttr) {
public static String getJavaImportPackage(YangType<?> yangType, boolean isListAttr, String classInfo) {
YangDataTypes type = yangType.getDataType();
if (isListAttr) {
......@@ -208,7 +235,11 @@ public final class AttributesJavaDataType {
} else if (type.equals(YangDataTypes.INSTANCE_IDENTIFIER)) {
//TODO:INSTANCE_IDENTIFIER
} else if (type.equals(YangDataTypes.DERIVED)) {
//TODO:DERIVED
for (JavaQualifiedTypeInfo imports : getImportInfo()) {
if (imports.getClassInfo().equals(classInfo)) {
return imports.getPkgInfo();
}
}
}
} else {
......@@ -235,7 +266,11 @@ public final class AttributesJavaDataType {
} else if (type.equals(YangDataTypes.INSTANCE_IDENTIFIER)) {
//TODO:INSTANCE_IDENTIFIER
} else if (type.equals(YangDataTypes.DERIVED)) {
//TODO:DERIVED
for (JavaQualifiedTypeInfo imports : getImportInfo()) {
if (imports.getClassInfo().equals(classInfo)) {
return imports.getPkgInfo();
}
}
}
}
return null;
......
......@@ -16,7 +16,7 @@
package org.onosproject.yangutils.translator.tojava.utils;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType;
import org.onosproject.yangutils.utils.UtilConstants;
/**
......@@ -44,19 +44,19 @@ public final class ClassDefinitionGenerator {
* based on the file type and the YANG name of the file, generate the
* class / interface definition start.
*/
if ((genFileTypes & GeneratedFileType.INTERFACE_MASK) != 0) {
if ((genFileTypes & GeneratedJavaFileType.INTERFACE_MASK) != 0) {
return getInterfaceDefinition(yangName);
} else if ((genFileTypes & GeneratedFileType.BUILDER_CLASS_MASK) != 0) {
} else if ((genFileTypes & GeneratedJavaFileType.BUILDER_CLASS_MASK) != 0) {
return getBuilderClassDefinition(yangName);
} else if ((genFileTypes & GeneratedFileType.IMPL_CLASS_MASK) != 0) {
} else if ((genFileTypes & GeneratedJavaFileType.IMPL_CLASS_MASK) != 0) {
return getImplClassDefinition(yangName);
} else if ((genFileTypes & GeneratedFileType.BUILDER_INTERFACE_MASK) != 0) {
} else if ((genFileTypes & GeneratedJavaFileType.BUILDER_INTERFACE_MASK) != 0) {
return getBuilderInterfaceDefinition(yangName);
} else if ((genFileTypes & GeneratedFileType.GENERATE_TYPEDEF_CLASS) != 0) {
} else if ((genFileTypes & GeneratedJavaFileType.GENERATE_TYPEDEF_CLASS) != 0) {
return getTypeDefClassDefinition(yangName);
}
......@@ -112,7 +112,7 @@ public final class ClassDefinitionGenerator {
return UtilConstants.PUBLIC + UtilConstants.SPACE + UtilConstants.FINAL + UtilConstants.SPACE
+ UtilConstants.CLASS + UtilConstants.SPACE + yangName + UtilConstants.IMPL + UtilConstants.SPACE
+ UtilConstants.IMPLEMENTS + UtilConstants.SPACE + yangName + UtilConstants.SPACE
+ UtilConstants.OPEN_CURLY_BRACKET + UtilConstants.NEW_LINE + UtilConstants.NEW_LINE;
+ UtilConstants.OPEN_CURLY_BRACKET + UtilConstants.NEW_LINE;
}
/**
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava.utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasJavaImportData;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaImportData;
import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
import org.onosproject.yangutils.utils.UtilConstants;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_INTERFACE_WITH_BUILDER;
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.JavaFileGenerator.appendFileContents;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.clean;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.closeFileHandles;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateBuilderClassFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateBuilderInterfaceFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateImplClassFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.generateInterfaceFile;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.getFileObject;
import static org.onosproject.yangutils.translator.tojava.utils.JavaFileGenerator.insert;
/**
* Provides generate java code exit.
*/
public final class GenerateJavaCodeExitBuilder {
private static final String JAVA_FILE_EXTENSION = ".java";
/**
* Default constructor.
*/
private GenerateJavaCodeExitBuilder() {
}
/**
* Sets import for hash and equals method.
*
* @return import string for implementing hash and equals
*/
private static String setImportForHashAndEquals() {
return UtilConstants.IMPORT + UtilConstants.JAVA_UTIL_OBJECTS_IMPORT_PKG + UtilConstants.PERIOD
+ UtilConstants.JAVA_UTIL_OBJECTS_IMPORT_CLASS;
}
/**
* Sets import for to string method.
*
* @return import string for implementing to string
*/
private static String setImportForToString() {
return UtilConstants.IMPORT + UtilConstants.GOOGLE_MORE_OBJECT_IMPORT_PKG + UtilConstants.PERIOD
+ UtilConstants.GOOGLE_MORE_OBJECT_IMPORT_CLASS;
}
/**
* Sets import for to list.
*
* @return import string for list collection
*/
private static String setImportForList() {
return UtilConstants.IMPORT + UtilConstants.COLLECTION_IMPORTS + UtilConstants.PERIOD
+ UtilConstants.LIST + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE;
}
/**
* Construct java code exit.
*
* @param fileType generated file type
* @param curNode current YANG node
* @throws IOException when fails to generate java files
*/
public static void generateJavaFile(int fileType, YangNode curNode) throws IOException {
JavaFileInfo javaFileInfo = ((HasJavaFileInfo) curNode).getJavaFileInfo();
String className = JavaIdentifierSyntax.getCaptialCase(javaFileInfo.getJavaName());
String pkg = javaFileInfo.getPackageFilePath();
List<String> imports = getImports(((HasJavaImportData) curNode).getJavaImportData());
/**
* Start generation of files.
*/
if ((fileType & INTERFACE_MASK) != 0 | (fileType & BUILDER_INTERFACE_MASK) != 0
| fileType == GENERATE_INTERFACE_WITH_BUILDER) {
/**
* Create interface file.
*/
String interfaceFileName = className;
File interfaceFile = getFileObject(pkg, interfaceFileName, JAVA_FILE_EXTENSION, javaFileInfo);
interfaceFile = generateInterfaceFile(interfaceFile, imports, curNode);
/**
* Create temp builder interface file.
*/
String builderInterfaceFileName = className
+ UtilConstants.BUILDER + UtilConstants.INTERFACE;
File builderInterfaceFile = getFileObject(pkg, builderInterfaceFileName, JAVA_FILE_EXTENSION, javaFileInfo);
builderInterfaceFile = generateBuilderInterfaceFile(builderInterfaceFile, curNode);
/**
* Append builder interface file to interface file and close it.
*/
appendFileContents(builderInterfaceFile, interfaceFile);
insert(interfaceFile, JavaCodeSnippetGen.getJavaClassDefClose());
/**
* Close file handle for interface files.
*/
closeFileHandles(builderInterfaceFile);
closeFileHandles(interfaceFile);
/**
* Remove temp files.
*/
clean(builderInterfaceFile);
}
imports.add(setImportForHashAndEquals());
imports.add(setImportForToString());
java.util.Collections.sort(imports);
if ((fileType & BUILDER_CLASS_MASK) != 0 | (fileType & IMPL_CLASS_MASK) != 0
| fileType == GENERATE_INTERFACE_WITH_BUILDER) {
/**
* Create builder class file.
*/
String builderFileName = className
+ UtilConstants.BUILDER;
File builderFile = getFileObject(pkg, builderFileName, JAVA_FILE_EXTENSION, javaFileInfo);
builderFile = generateBuilderClassFile(builderFile, imports, curNode);
/**
* Create temp impl class file.
*/
String implFileName = className + UtilConstants.IMPL;
File implTempFile = getFileObject(pkg, implFileName, JAVA_FILE_EXTENSION, javaFileInfo);
implTempFile = generateImplClassFile(implTempFile, curNode);
/**
* Append impl class to builder class and close it.
*/
appendFileContents(implTempFile, builderFile);
insert(builderFile, JavaCodeSnippetGen.getJavaClassDefClose());
/**
* Close file handle for classes files.
*/
closeFileHandles(implTempFile);
closeFileHandles(builderFile);
/**
* Remove temp files.
*/
clean(implTempFile);
}
/**
* if ((fileType & GENERATE_TYPEDEF_CLASS) != 0) {
*
* /** Create builder class file. //
*/
//String typeDefFileName = className;
//File typeDefFile = JavaFileGenerator.getFileObject(path, typeDefFileName, JAVA_FILE_EXTENSION,
// ((HasJavaFileInfo) curNode).getJavaFileInfo());
//typeDefFile = JavaFileGenerator.generateTypeDefClassFile(typeDefFile, className, imports,
// path.replace('/', '.'), attrList, ((HasJavaFileInfo) curNode).getJavaFileInfo());
// JavaFileGenerator.insert(typeDefFile, JavaCodeSnippetGen.getJavaClassDefClose());
// /**
// * Close file handle for classes files.
// */
// JavaFileGenerator.closeFileHandles(typeDefFile);
// }
//
}
/**
* Returns import for class.
*
* @param javaImportData import data
* @return imports for class
*/
private static List<String> getImports(JavaImportData javaImportData) {
String importString;
List<String> imports = new ArrayList<>();
for (JavaQualifiedTypeInfo importInfo : javaImportData.getImportSet()) {
importString = UtilConstants.IMPORT;
if (importInfo.getPkgInfo() != "" && importInfo.getClassInfo() != null
&& importInfo.getPkgInfo() != UtilConstants.JAVA_LANG) {
importString = importString + importInfo.getPkgInfo() + ".";
importString = importString + importInfo.getClassInfo() + UtilConstants.SEMI_COLAN
+ UtilConstants.NEW_LINE;
imports.add(importString);
}
}
if (javaImportData.getIfListImported()) {
imports.add(setImportForList());
}
java.util.Collections.sort(imports);
return imports;
}
}
......@@ -16,8 +16,7 @@
package org.onosproject.yangutils.translator.tojava.utils;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.translator.tojava.ImportInfo;
import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
import org.onosproject.yangutils.utils.UtilConstants;
/**
......@@ -51,7 +50,8 @@ public final class JavaCodeSnippetGen {
* @return the textual java code information corresponding to the import
* list
*/
public static String getImportText(ImportInfo importInfo) {
public static String getImportText(JavaQualifiedTypeInfo importInfo) {
return UtilConstants.IMPORT + importInfo.getPkgInfo() + UtilConstants.PERIOD + importInfo.getClassInfo()
+ UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE;
}
......@@ -65,6 +65,7 @@ public final class JavaCodeSnippetGen {
* @return corresponding textual java code information
*/
public static String getJavaClassDefStart(int genFileTypes, String yangName) {
/*
* get the camel case name for java class / interface.
*/
......@@ -90,24 +91,24 @@ public final class JavaCodeSnippetGen {
if (!isList) {
if (javaAttributeTypePkg != null) {
attributeDefination = attributeDefination
+ javaAttributeTypePkg + ".";
+ javaAttributeTypePkg + UtilConstants.PERIOD;
}
attributeDefination = attributeDefination
+ javaAttributeType
+ UtilConstants.SPACE
+ javaAttributeName
+ UtilConstants.SEMI_COLAN;
+ UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE;
} else {
attributeDefination = attributeDefination + UtilConstants.LIST + UtilConstants.DIAMOND_OPEN_BRACKET;
if (javaAttributeTypePkg != null) {
attributeDefination = attributeDefination
+ javaAttributeTypePkg + ".";
+ javaAttributeTypePkg + UtilConstants.PERIOD;
}
attributeDefination = attributeDefination
+ javaAttributeType + UtilConstants.DIAMOND_CLOSE_BRACKET + UtilConstants.SPACE
+ javaAttributeName + UtilConstants.SEMI_COLAN;
+ javaAttributeName + UtilConstants.SUFIX_S + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE;
}
return attributeDefination;
}
......@@ -119,6 +120,7 @@ public final class JavaCodeSnippetGen {
* @return list attribute string
*/
public static String getListAttribute(String type) {
return UtilConstants.LIST + UtilConstants.DIAMOND_OPEN_BRACKET + type + UtilConstants.DIAMOND_CLOSE_BRACKET;
}
......@@ -126,23 +128,11 @@ public final class JavaCodeSnippetGen {
* Based on the file type and the YANG name of the file, generate the class
* / interface definition close.
*
* @param genFileTypes type of file being generated
* @param yangName YANG name
* @return corresponding textual java code information
*/
public static String getJavaClassDefClose(int genFileTypes, String yangName) {
if ((genFileTypes & GeneratedFileType.INTERFACE_MASK) != 0) {
public static String getJavaClassDefClose() {
return UtilConstants.CLOSE_CURLY_BRACKET;
} else if ((genFileTypes & GeneratedFileType.BUILDER_CLASS_MASK) != 0) {
return UtilConstants.CLOSE_CURLY_BRACKET;
} else if ((genFileTypes & GeneratedFileType.GENERATE_TYPEDEF_CLASS) != 0) {
return UtilConstants.CLOSE_CURLY_BRACKET;
}
return null;
}
}
......
......@@ -16,36 +16,55 @@
package org.onosproject.yangutils.translator.tojava.utils;
import static org.onosproject.yangutils.translator.GeneratedFileType.BUILDER_CLASS_MASK;
import static org.onosproject.yangutils.translator.GeneratedFileType.BUILDER_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.GeneratedFileType.GENERATE_TYPEDEF_CLASS;
import static org.onosproject.yangutils.translator.GeneratedFileType.IMPL_CLASS_MASK;
import static org.onosproject.yangutils.translator.GeneratedFileType.INTERFACE_MASK;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.translator.tojava.AttributeInfo;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.HasTempJavaCodeFragmentFiles;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.translator.tojava.TempJavaCodeFragmentFiles;
import org.onosproject.yangutils.utils.UtilConstants;
import org.onosproject.yangutils.utils.io.impl.CopyrightHeader;
import org.onosproject.yangutils.utils.io.impl.FileSystemUtil;
import org.onosproject.yangutils.utils.io.impl.JavaDocGen;
import org.onosproject.yangutils.utils.io.impl.JavaDocGen.JavaDocType;
import org.onosproject.yangutils.utils.io.impl.YangIoUtils;
import org.slf4j.Logger;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.BUILDER_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.GENERATE_TYPEDEF_CLASS;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.IMPL_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType.INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.ATTRIBUTES_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.CONSTRUCTOR_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.EQUALS_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.GETTER_FOR_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.HASH_CODE_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_CLASS_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.SETTER_FOR_INTERFACE_MASK;
import static org.onosproject.yangutils.translator.tojava.GeneratedTempFileType.TO_STRING_IMPL_MASK;
import static org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax.getCaptialCase;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getBuildString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getConstructorStart;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getDefaultConstructorString;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEqualsMethodClose;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getEqualsMethodOpen;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getHashCodeMethodClose;
import static org.onosproject.yangutils.translator.tojava.utils.MethodsGenerator.getHashCodeMethodOpen;
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.MethodsGenerator.parseBuilderInterfaceBuildMethodString;
import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.partString;
/**
* Generates java file.
*/
public final class JavaFileGenerator {
private static final Logger log = getLogger(JavaFileGenerator.class);
/**
* Default constructor.
*/
......@@ -61,42 +80,37 @@ public final class JavaFileGenerator {
* @param handle cached file handle
* @return file object
*/
public static File getFileObject(String filePath, String fileName, String extension, CachedFileHandle handle) {
return new File(handle.getCodeGenFilePath() + filePath + File.separator + fileName + extension);
public static File getFileObject(String filePath, String fileName, String extension, JavaFileInfo handle) {
return new File(handle.getBaseCodeGenPath() + filePath + File.separator + fileName + extension);
}
/**
* Returns generated interface file for current node.
*
* @param file file
* @param className class name
* @param imports imports for the file
* @param attrList attribute info
* @param pkg generated file package
* @param handle cached file handle
* @param curNode current YANG node
* @return interface file
* @throws IOException when fails to write in file
*/
public static File generateInterfaceFile(File file, String className, List<String> imports,
List<AttributeInfo> attrList, String pkg, CachedFileHandle handle) throws IOException {
String path = handle.getCodeGenFilePath() + pkg.replace(UtilConstants.PERIOD, UtilConstants.SLASH);
initiateFile(file, className, INTERFACE_MASK, imports, pkg);
public static File generateInterfaceFile(File file, List<String> imports, YangNode curNode) throws IOException {
if (!attrList.isEmpty()) {
List<String> methods = new ArrayList<>();
try {
methods.add(handle.getTempData(TempDataStoreTypes.GETTER_METHODS, className, path));
} catch (ClassNotFoundException | IOException e) {
log.info("There is no attribute info of " + className + " YANG file in the temporary files.");
throw new IOException("Fail to read data from temp file.");
}
JavaFileInfo javaFileInfo = ((HasJavaFileInfo) curNode).getJavaFileInfo();
String className = getCaptialCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateFile(file, className, INTERFACE_MASK, imports, path);
/**
* Add getter methods to interface file.
*/
for (String method : methods) {
appendMethod(file, method);
}
try {
appendMethod(file, getDataFromTempFileHandle(GETTER_FOR_INTERFACE_MASK, curNode));
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while interface file generation");
}
return file;
}
......@@ -105,39 +119,41 @@ public final class JavaFileGenerator {
* Return generated builder interface file for current node.
*
* @param file file
* @param className class name
* @param pkg generated file package
* @param attrList attribute info
* @param handle cached file handle
* @param curNode current YANG node
* @return builder interface file
* @throws IOException when fails to write in file
*/
public static File generateBuilderInterfaceFile(File file, String className, String pkg,
List<AttributeInfo> attrList, CachedFileHandle handle) throws IOException {
String path = handle.getCodeGenFilePath() + pkg.replace(UtilConstants.PERIOD, UtilConstants.SLASH);
initiateFile(file, className, BUILDER_INTERFACE_MASK, null, pkg);
List<String> methods = new ArrayList<>();
public static File generateBuilderInterfaceFile(File file, YangNode curNode) throws IOException {
JavaFileInfo javaFileInfo = ((HasJavaFileInfo) curNode).getJavaFileInfo();
String className = getCaptialCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
if (!attrList.isEmpty()) {
initiateFile(file, className, BUILDER_INTERFACE_MASK, null, path);
List<String> methods = new ArrayList<>();
try {
methods.add(handle.getTempData(TempDataStoreTypes.GETTER_METHODS, className, path));
methods.add(handle.getTempData(TempDataStoreTypes.SETTER_METHODS, className, path));
} catch (ClassNotFoundException | IOException e) {
log.info("There is no attribute info of " + className + " YANG file in the temporary files.");
throw new IOException("Fail to read data from temp file.");
}
methods.add(UtilConstants.FOUR_SPACE_INDENTATION
+ getDataFromTempFileHandle(GETTER_FOR_INTERFACE_MASK, curNode));
methods.add(UtilConstants.NEW_LINE);
methods.add(UtilConstants.FOUR_SPACE_INDENTATION
+ getDataFromTempFileHandle(SETTER_FOR_INTERFACE_MASK, curNode));
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while builder interface file generation");
}
/**
* Add build method to builder interface file.
*/
methods.add(MethodsGenerator.parseBuilderInterfaceBuildMethodString(className));
methods.add(parseBuilderInterfaceBuildMethodString(className));
/**
* Add getters and setters in builder interface.
*/
for (String method : methods) {
appendMethod(file, UtilConstants.FOUR_SPACE_INDENTATION + method);
appendMethod(file, method);
}
insert(file, UtilConstants.CLOSE_CURLY_BRACKET + UtilConstants.NEW_LINE);
......@@ -148,61 +164,53 @@ public final class JavaFileGenerator {
* Returns generated builder class file for current node.
*
* @param file file
* @param className class name
* @param imports imports for the file
* @param pkg generated file package
* @param attrList attribute info
* @param handle cached file handle
* @param curNode current YANG node
* @return builder class file
* @throws IOException when fails to write in file
*/
public static File generateBuilderClassFile(File file, String className, List<String> imports, String pkg,
List<AttributeInfo> attrList, CachedFileHandle handle) throws IOException {
String path = handle.getCodeGenFilePath() + pkg.replace(UtilConstants.PERIOD, UtilConstants.SLASH);
initiateFile(file, className, BUILDER_CLASS_MASK, imports, pkg);
public static File generateBuilderClassFile(File file, List<String> imports, YangNode curNode) throws IOException {
JavaFileInfo javaFileInfo = ((HasJavaFileInfo) curNode).getJavaFileInfo();
String className = getCaptialCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateFile(file, className, BUILDER_CLASS_MASK, imports, path);
List<String> methods = new ArrayList<>();
if (!attrList.isEmpty()) {
/**
* Add attribute strings.
*/
List<String> attributes = new ArrayList<>();
try {
attributes.add(handle.getTempData(TempDataStoreTypes.ATTRIBUTE, className, path));
} catch (ClassNotFoundException | IOException e) {
log.info("There is no attribute info of " + className + " YANG file in the temporary files.");
throw new IOException("Fail to read data from temp file.");
}
/**
* Add attributes to the file.
*/
for (String attribute : attributes) {
insert(file, UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION + attribute);
insert(file, UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ getDataFromTempFileHandle(ATTRIBUTES_MASK, curNode));
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while builder class file generation");
}
try {
methods.add(handle.getTempData(TempDataStoreTypes.GETTER_METHODS_IMPL, className, path));
methods.add(handle.getTempData(TempDataStoreTypes.SETTER_METHODS_IMPL, className, path));
} catch (ClassNotFoundException | IOException e) {
log.info("There is no attribute info of " + className + " YANG file in the temporary files.");
throw new IOException("Fail to read data from temp file.");
methods.add(getDataFromTempFileHandle(GETTER_FOR_CLASS_MASK, curNode));
methods.add(getDataFromTempFileHandle(SETTER_FOR_CLASS_MASK, curNode) + UtilConstants.NEW_LINE);
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while builder class file generation");
}
}
/**
* Add default constructor and build method impl.
*/
methods.add(
UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_FIRST_LINE
+ MethodsGenerator.getDefaultConstructorString(className + UtilConstants.BUILDER,
UtilConstants.PUBLIC));
methods.add(MethodsGenerator.getBuildString(className));
methods.add(getBuildString(className) + UtilConstants.NEW_LINE);
methods.add(UtilConstants.NEW_LINE
+ getDefaultConstructorString(className + UtilConstants.BUILDER, UtilConstants.PUBLIC));
/**
* Add methods in builder class.
*/
for (String method : methods) {
appendMethod(file, method + UtilConstants.NEW_LINE);
appendMethod(file, method);
}
return file;
}
......@@ -211,67 +219,59 @@ public final class JavaFileGenerator {
* Returns generated impl class file for current node.
*
* @param file file
* @param className class name
* @param pkg generated file package
* @param attrList attribute's info
* @param handle cached file handle
* @param curNode current YANG node
* @return impl class file
* @throws IOException when fails to write in file
*/
public static File generateImplClassFile(File file, String className, String pkg, List<AttributeInfo> attrList,
CachedFileHandle handle)
public static File generateImplClassFile(File file, YangNode curNode)
throws IOException {
String path = handle.getCodeGenFilePath() + pkg.replace(UtilConstants.PERIOD, UtilConstants.SLASH);
JavaFileInfo javaFileInfo = ((HasJavaFileInfo) curNode).getJavaFileInfo();
String className = getCaptialCase(javaFileInfo.getJavaName());
String path = javaFileInfo.getBaseCodeGenPath() + javaFileInfo.getPackageFilePath();
initiateFile(file, className, IMPL_CLASS_MASK, null, path);
List<String> methods = new ArrayList<>();
if (!attrList.isEmpty()) {
List<String> attributes = new ArrayList<>();
try {
attributes.add(handle.getTempData(TempDataStoreTypes.ATTRIBUTE, className, path));
} catch (ClassNotFoundException | IOException e) {
log.info("There is no attribute info of " + className + " YANG file in the temporary files.");
throw new IOException("Fail to read data from temp file.");
}
/**
* Add attributes to the file.
* Add attribute strings.
*/
for (String attribute : attributes) {
insert(file, UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION + attribute);
try {
insert(file, UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ getDataFromTempFileHandle(ATTRIBUTES_MASK, curNode));
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while impl class file generation");
}
insert(file, UtilConstants.NEW_LINE);
try {
methods.add(handle.getTempData(TempDataStoreTypes.GETTER_METHODS_IMPL, className, path));
methods.add(getDataFromTempFileHandle(GETTER_FOR_CLASS_MASK, curNode));
methods.add(MethodsGenerator.getHashCodeMethodClose(MethodsGenerator.getHashCodeMethodOpen()
+ YangIoUtils
.partString(handle.getTempData(TempDataStoreTypes.HASH_CODE, className, path).replace(
UtilConstants.NEW_LINE, ""))));
methods.add(getHashCodeMethodClose(getHashCodeMethodOpen() + partString(
getDataFromTempFileHandle(HASH_CODE_IMPL_MASK, curNode).replace(UtilConstants.NEW_LINE,
UtilConstants.EMPTY_STRING))));
methods.add(MethodsGenerator
.getEqualsMethodClose(MethodsGenerator.getEqualsMethodOpen(className + UtilConstants.IMPL)
+ handle.getTempData(TempDataStoreTypes.EQUALS, className, path)));
methods.add(getEqualsMethodClose(getEqualsMethodOpen(className + UtilConstants.IMPL)
+ getDataFromTempFileHandle(EQUALS_IMPL_MASK, curNode)));
methods.add(MethodsGenerator.getToStringMethodOpen()
+ handle.getTempData(TempDataStoreTypes.TO_STRING, className, path)
+ MethodsGenerator.getToStringMethodClose());
} catch (ClassNotFoundException | IOException e) {
log.info("There is no attribute info of " + className + " YANG file in the temporary files.");
throw new IOException("Fail to read data from temp file.");
}
methods.add(getToStringMethodOpen() + getDataFromTempFileHandle(TO_STRING_IMPL_MASK, curNode)
+ getToStringMethodClose());
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while impl class file generation");
}
try {
methods.add(getConstructorString(className)
+ handle.getTempData(TempDataStoreTypes.CONSTRUCTOR, className, path)
methods.add(getConstructorStart(className) + getDataFromTempFileHandle(CONSTRUCTOR_IMPL_MASK, curNode)
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.CLOSE_CURLY_BRACKET);
} catch (ClassNotFoundException | IOException e) {
log.info("There is no attribute info of " + className + " YANG file in the temporary files.");
throw new IOException("Fail to read data from temp file.");
} catch (IOException e) {
throw new IOException("No data found in temporary java code fragment files for " + className
+ " while impl class file generation");
}
/**
* Add methods in impl class.
......@@ -285,56 +285,48 @@ public final class JavaFileGenerator {
}
/**
* Generate class file for type def.
* Return data stored in temporary files.
*
* @param file generated file
* @param className file name
* @param imports imports for file
* @param pkg package path
* @param cachedAttributeList attribute list
* @param handle cached file handle
* @return type def class file
* @throws IOException when fails to generate class file
*/
public static File generateTypeDefClassFile(File file, String className, List<String> imports,
String pkg, List<AttributeInfo> cachedAttributeList, CachedFileHandle handle) throws IOException {
String path = handle.getCodeGenFilePath() + pkg.replace(UtilConstants.PERIOD, UtilConstants.SLASH);
initiateFile(file, className, GENERATE_TYPEDEF_CLASS, imports, pkg);
List<String> typeDef = new ArrayList<>();
try {
typeDef.add(handle.getTempData(TempDataStoreTypes.TYPE_DEF, className, path));
} catch (ClassNotFoundException | IOException e) {
log.info("There is no attribute info of " + className + " YANG file in the temporary files.");
throw new IOException("Fail to read data from temp file.");
}
/**
* Add attributes to the file.
*/
for (String attribute : typeDef) {
insert(file, UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION + attribute);
}
return file;
}
/**
* Returns constructor string for impl class.
*
* @param yangName class name
* @return constructor string
*/
private static String getConstructorString(String yangName) {
String builderAttribute = yangName.substring(0, 1).toLowerCase() + yangName.substring(1);
String javadoc = MethodsGenerator.getConstructorString(yangName);
String constructor = UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.PUBLIC + UtilConstants.SPACE
+ yangName + UtilConstants.IMPL + UtilConstants.OPEN_PARENTHESIS + yangName + UtilConstants.BUILDER
+ UtilConstants.SPACE + builderAttribute + UtilConstants.BUILDER + UtilConstants.OBJECT
+ UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET
+ UtilConstants.NEW_LINE;
return javadoc + constructor;
* @param curNode current YANG node
* @param generatedTempFiles mask for the types of files being generated
* @return data stored in temporary files
* @throws IOException when failed to get the data from temporary file
* handle
*/
private static String getDataFromTempFileHandle(int generatedTempFiles, YangNode curNode) throws IOException {
TempJavaCodeFragmentFiles tempJavaCodeFragmentFiles = ((HasTempJavaCodeFragmentFiles) curNode)
.getTempJavaCodeFragmentFiles();
if ((generatedTempFiles & ATTRIBUTES_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getAttributesTempFileHandle());
} else if ((generatedTempFiles & GETTER_FOR_INTERFACE_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getGetterInterfaceTempFileHandle());
} else if ((generatedTempFiles & SETTER_FOR_INTERFACE_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getSetterInterfaceTempFileHandle());
} else if ((generatedTempFiles & GETTER_FOR_CLASS_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getGetterImplTempFileHandle());
} else if ((generatedTempFiles & SETTER_FOR_CLASS_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getSetterImplTempFileHandle());
} else if ((generatedTempFiles & CONSTRUCTOR_IMPL_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getConstructorImplTempFileHandle());
} else if ((generatedTempFiles & HASH_CODE_IMPL_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getHashCodeImplTempFileHandle());
} else if ((generatedTempFiles & EQUALS_IMPL_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getEqualsImplTempFileHandle());
} else if ((generatedTempFiles & TO_STRING_IMPL_MASK) != 0) {
return tempJavaCodeFragmentFiles
.getTemporaryDataFromFileHandle(tempJavaCodeFragmentFiles.getToStringImplTempFileHandle());
}
return null;
}
/**
......@@ -349,6 +341,7 @@ public final class JavaFileGenerator {
*/
private static void initiateFile(File file, String className, int type, List<String> imports,
String pkg) throws IOException {
try {
file.createNewFile();
appendContents(file, className, type, imports, pkg);
......@@ -365,6 +358,7 @@ public final class JavaFileGenerator {
* @throws IOException when fails to append contents
*/
public static void appendFileContents(File appendFile, File srcFile) throws IOException {
try {
FileSystemUtil.appendFileContents(appendFile, srcFile);
} catch (IOException e) {
......@@ -377,181 +371,11 @@ public final class JavaFileGenerator {
*
* @param file file in which method needs to be appended
* @param method method which needs to be appended
* @throws IOException IO operation failure
*/
private static void appendMethod(File file, String method) throws IOException {
insert(file, method);
}
/**
* Closes the current generated file.
*
* @param fileType generate file type
* @param yangName file name
* @return end of class definition string
*/
public static String closeFile(int fileType, String yangName) {
return JavaCodeSnippetGen.getJavaClassDefClose(fileType, yangName);
}
/**
* Parses attribute info and fetch specific data and creates serialized
* files of it.
*
* @param attr attribute info.
* @param genFileType generated file type
* @param className class name
* @param path file path
* @param handle cached file handle
*/
public static void parseAttributeInfo(AttributeInfo attr, int genFileType, String className, String path,
CachedFileHandle handle) {
String attrString = "";
String getterString = "";
String getterImplString = "";
String setterString = "";
String setterImplString = "";
String constructorString = "";
String typeDefString = "";
String toString = "";
String hashCodeString = "";
String equalsString = "";
className = JavaIdentifierSyntax.getCaptialCase(className);
try {
/*
* Get the attribute definition and save attributes to temporary
* file.
*/
boolean isList = attr.isListAttr();
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (attr.isQualifiedName()) {
attrString = JavaCodeSnippetGen.getJavaAttributeDefination(attr.getImportInfo().getPkgInfo(),
attr.getImportInfo().getClassInfo(),
attributeName, attr.isListAttr());
} else {
attrString = JavaCodeSnippetGen.getJavaAttributeDefination(null, attr.getImportInfo().getClassInfo(),
attributeName, attr.isListAttr());
}
handle.setTempData(attrString + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION,
TempDataStoreTypes.ATTRIBUTE, className,
path);
if ((genFileType & INTERFACE_MASK) != 0) {
getterString = MethodsGenerator.getGetterString(attr);
handle.setTempData(getterString + UtilConstants.NEW_LINE,
TempDataStoreTypes.GETTER_METHODS,
className,
path);
}
if ((genFileType & BUILDER_INTERFACE_MASK) != 0) {
setterString = MethodsGenerator.getSetterString(attr, className);
handle.setTempData(setterString + UtilConstants.NEW_LINE,
TempDataStoreTypes.SETTER_METHODS,
className,
path);
}
if ((genFileType & BUILDER_CLASS_MASK) != 0) {
getterImplString = MethodsGenerator.getGetterForClass(attr);
handle.setTempData(
MethodsGenerator.getOverRideString() + getterImplString + UtilConstants.NEW_LINE,
TempDataStoreTypes.GETTER_METHODS_IMPL, className,
path);
setterImplString = MethodsGenerator.getSetterForClass(attr, className);
handle.setTempData(
MethodsGenerator.getOverRideString() + setterImplString + UtilConstants.NEW_LINE,
TempDataStoreTypes.SETTER_METHODS_IMPL, className,
path);
}
if ((genFileType & IMPL_CLASS_MASK) != 0) {
constructorString = MethodsGenerator.getConstructor(className, attr);
handle.setTempData(constructorString, TempDataStoreTypes.CONSTRUCTOR, className,
path);
hashCodeString = MethodsGenerator.getHashCodeMethod(attr);
handle.setTempData(hashCodeString + UtilConstants.NEW_LINE,
TempDataStoreTypes.HASH_CODE,
className,
path);
equalsString = MethodsGenerator.getEqualsMethod(attr);
handle.setTempData(equalsString + UtilConstants.NEW_LINE,
TempDataStoreTypes.EQUALS,
className,
path);
toString = MethodsGenerator.getToStringMethod(attr);
handle.setTempData(toString + UtilConstants.NEW_LINE,
TempDataStoreTypes.TO_STRING,
className,
path);
}
if ((genFileType & GENERATE_TYPEDEF_CLASS) != 0) {
if (attr.isQualifiedName()) {
typeDefString = JavaCodeSnippetGen.getJavaAttributeDefination(attr.getImportInfo().getPkgInfo(),
attr.getImportInfo().getClassInfo(),
attributeName, attr.isListAttr()) + UtilConstants.NEW_LINE;
} else {
typeDefString = JavaCodeSnippetGen.getJavaAttributeDefination(null,
attr.getImportInfo().getClassInfo(),
attributeName, attr.isListAttr()) + UtilConstants.NEW_LINE;
}
typeDefString = typeDefString + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.JAVA_DOC_FIRST_LINE;
typeDefString = typeDefString
+ MethodsGenerator.getDefaultConstructorString(className, UtilConstants.PRIVATE)
+ UtilConstants.NEW_LINE;
typeDefString = typeDefString
+ JavaDocGen.getJavaDoc(JavaDocType.TYPE_DEF_CONSTRUCTOR, className, isList)
+ MethodsGenerator.getTypeDefConstructor(attr, className)
+ UtilConstants.NEW_LINE;
typeDefString = typeDefString + JavaDocGen.getJavaDoc(JavaDocType.OF, className, isList)
+ MethodsGenerator.getOfMethod(className, attr) + UtilConstants.NEW_LINE;
typeDefString = typeDefString + JavaDocGen.getJavaDoc(JavaDocType.GETTER, className, isList)
+ MethodsGenerator.getGetterForClass(attr) + UtilConstants.NEW_LINE;
typeDefString = typeDefString + JavaDocGen.getJavaDoc(JavaDocType.TYPE_DEF_SETTER, className, isList)
+ MethodsGenerator.getSetterForTypeDefClass(attr)
+ UtilConstants.NEW_LINE;
hashCodeString = MethodsGenerator.getHashCodeMethodOpen()
+ YangIoUtils.partString(
MethodsGenerator.getHashCodeMethod(attr).replace(UtilConstants.NEW_LINE, ""));
hashCodeString = MethodsGenerator.getHashCodeMethodClose(hashCodeString) + UtilConstants.NEW_LINE;
equalsString = MethodsGenerator.getEqualsMethodOpen(className) + UtilConstants.NEW_LINE
+ MethodsGenerator.getEqualsMethod(attr);
equalsString = MethodsGenerator.getEqualsMethodClose(equalsString) + UtilConstants.NEW_LINE;
toString = MethodsGenerator.getToStringMethodOpen()
+ MethodsGenerator.getToStringMethod(attr) + UtilConstants.NEW_LINE
+ MethodsGenerator.getToStringMethodClose()
+ UtilConstants.NEW_LINE;
typeDefString = typeDefString + hashCodeString + equalsString + toString;
handle.setTempData(typeDefString, TempDataStoreTypes.TYPE_DEF, className,
path);
}
} catch (IOException e) {
log.info("Failed to set data for " + attr.getAttributeName() + " in temp data files.");
}
insert(file, method);
}
/**
......@@ -567,10 +391,7 @@ public final class JavaFileGenerator {
private static void appendContents(File file, String fileName, int type, List<String> importsList,
String pkg) throws IOException {
if (pkg.contains(UtilConstants.YANG_GEN_DIR)) {
String[] strArray = pkg.split(UtilConstants.YANG_GEN_DIR);
pkg = strArray[1].replace(UtilConstants.SLASH, UtilConstants.PERIOD);
}
String pkgString = parsePackageString(pkg, importsList);
if ((type & IMPL_CLASS_MASK) != 0) {
......@@ -579,39 +400,69 @@ public final class JavaFileGenerator {
write(file, fileName, type, JavaDocType.BUILDER_INTERFACE);
} else if ((type & GENERATE_TYPEDEF_CLASS) != 0) {
insert(file, CopyrightHeader.getCopyrightHeader());
insert(file, "package" + UtilConstants.SPACE + pkg + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE);
if (importsList != null) {
insert(file, UtilConstants.NEW_LINE);
for (String imports : importsList) {
insert(file, imports);
appendHeaderContents(file, pkgString, importsList);
write(file, fileName, type, JavaDocType.IMPL_CLASS);
} else if ((type & INTERFACE_MASK) != 0) {
appendHeaderContents(file, pkgString, importsList);
write(file, fileName, type, JavaDocType.INTERFACE);
} else if ((type & BUILDER_CLASS_MASK) != 0) {
appendHeaderContents(file, pkgString, importsList);
write(file, fileName, type, JavaDocType.BUILDER_CLASS);
}
}
write(file, fileName, type, JavaDocType.IMPL_CLASS);
} else {
if ((type & INTERFACE_MASK) != 0) {
insert(file, CopyrightHeader.getCopyrightHeader());
insert(file, "package" + UtilConstants.SPACE + pkg + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE);
/**
* Removes base directory path from package and generates package string for
* file.
*
* @param pkg generated package
* @param importsList list of imports
* @return package string
*/
private static String parsePackageString(String pkg, List<String> importsList) {
if (pkg.contains(UtilConstants.ORG)) {
String[] strArray = pkg.split(UtilConstants.ORG);
pkg = UtilConstants.ORG + strArray[1].replace(UtilConstants.SLASH, UtilConstants.PERIOD);
}
if (importsList != null) {
insert(file, UtilConstants.NEW_LINE);
for (String imports : importsList) {
insert(file, imports);
if (!importsList.isEmpty()) {
return UtilConstants.PACKAGE + UtilConstants.SPACE + pkg + UtilConstants.SEMI_COLAN
+ UtilConstants.NEW_LINE;
} else {
return UtilConstants.PACKAGE + UtilConstants.SPACE + pkg + UtilConstants.SEMI_COLAN;
}
} else {
return UtilConstants.PACKAGE + UtilConstants.SPACE + pkg + UtilConstants.SEMI_COLAN;
}
write(file, fileName, type, JavaDocType.INTERFACE);
} else if ((type & BUILDER_CLASS_MASK) != 0) {
}
/**
* Appends other contents to interface, builder and typedef classes. for
* example : ONOS copyright, imports and package.
*
* @param file generated file
* @param pkg generated package
* @param importsList list of imports
* @throws IOException when fails to append contents.
*/
private static void appendHeaderContents(File file, String pkg, List<String> importsList) throws IOException {
insert(file, CopyrightHeader.getCopyrightHeader());
insert(file, "package" + UtilConstants.SPACE + pkg + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE);
insert(file, pkg);
/*
* TODO: add the file header using
* JavaCodeSnippetGen.getFileHeaderComment
*/
if (importsList != null) {
insert(file, UtilConstants.NEW_LINE);
for (String imports : importsList) {
insert(file, imports);
}
insert(file, UtilConstants.NEW_LINE);
}
write(file, fileName, type, JavaDocType.BUILDER_CLASS);
}
}
}
......@@ -639,6 +490,7 @@ public final class JavaFileGenerator {
* @throws IOException when fails to insert into file
*/
public static void insert(File file, String data) throws IOException {
try {
FileSystemUtil.updateFileHandle(file, data, false);
} catch (IOException e) {
......@@ -653,6 +505,7 @@ public final class JavaFileGenerator {
* @throws IOException when failed to close the file handle
*/
public static void closeFileHandles(File file) throws IOException {
try {
FileSystemUtil.updateFileHandle(file, null, true);
} catch (IOException e) {
......@@ -666,6 +519,7 @@ public final class JavaFileGenerator {
* @param file file to be removed
*/
public static void clean(File file) {
if (file.exists()) {
file.delete();
}
......@@ -678,6 +532,7 @@ public final class JavaFileGenerator {
* @throws IOException when fails to delete the directory
*/
public static void cleanTempFiles(File tempDir) throws IOException {
FileUtils.deleteDirectory(tempDir);
}
}
......
......@@ -16,9 +16,13 @@
package org.onosproject.yangutils.translator.tojava.utils;
import java.io.File;
import java.util.ArrayList;
import org.onosproject.yangutils.datamodel.YangNode;
import org.onosproject.yangutils.translator.exception.TranslatorException;
import org.onosproject.yangutils.translator.tojava.HasJavaFileInfo;
import org.onosproject.yangutils.translator.tojava.JavaFileInfo;
import org.onosproject.yangutils.utils.UtilConstants;
/**
......@@ -61,12 +65,52 @@ public final class JavaIdentifierSyntax {
}
/**
* Get the contained data model parent node.
*
* @param currentNode current node which parent contained node is required
* @return parent node in which the current node is an attribute
*/
public static YangNode getParentNodeInGenCode(YangNode currentNode) {
/*
* TODO: recursive parent lookup to support choice/augment/uses. TODO:
* need to check if this needs to be updated for
* choice/case/augment/grouping
*/
return currentNode.getParent();
}
/**
* Get the node package string.
*
* @param curNode current java node whose package string needs to be set
* @return returns the root package string
*/
public static String getCurNodePackage(YangNode curNode) {
String pkg;
if (!(curNode instanceof HasJavaFileInfo)
|| curNode.getParent() == null) {
throw new RuntimeException("missing parent node to get current node's package");
}
YangNode parentNode = getParentNodeInGenCode(curNode);
if (!(parentNode instanceof HasJavaFileInfo)) {
throw new RuntimeException("missing parent java node to get current node's package");
}
JavaFileInfo parentJavaFileHandle = ((HasJavaFileInfo) parentNode).getJavaFileInfo();
pkg = parentJavaFileHandle.getPackage() + UtilConstants.PERIOD + parentJavaFileHandle.getJavaName();
return pkg.toLowerCase();
}
/**
* Returns version.
*
* @param ver YANG version
* @return version
*/
private static String getYangVersion(byte ver) {
return "v" + ver;
}
......@@ -77,6 +121,7 @@ public final class JavaIdentifierSyntax {
* @return java package name as per java rules
*/
public static String getPkgFromNameSpace(String nameSpace) {
ArrayList<String> pkgArr = new ArrayList<String>();
nameSpace = nameSpace.replace(UtilConstants.QUOTES, UtilConstants.EMPTY_STRING);
String properNameSpace = nameSpace.replaceAll(UtilConstants.REGEX_WITH_SPECIAL_CHAR, UtilConstants.COLAN);
......@@ -96,12 +141,13 @@ public final class JavaIdentifierSyntax {
* @throws TranslatorException when date is invalid.
*/
public static String getYangRevisionStr(String date) throws TranslatorException {
String[] revisionArr = date.split(UtilConstants.HYPHEN);
String rev = "rev";
rev = rev + revisionArr[INDEX_ZERO];
if ((Integer.parseInt(revisionArr[INDEX_ONE]) <= MAX_MONTHS)
if (Integer.parseInt(revisionArr[INDEX_ONE]) <= MAX_MONTHS
&& Integer.parseInt(revisionArr[INDEX_TWO]) <= MAX_DAYS) {
for (int i = INDEX_ONE; i < revisionArr.length; i++) {
......@@ -131,7 +177,7 @@ public final class JavaIdentifierSyntax {
int i = 0;
for (String member : pkgArr) {
boolean presenceOfKeyword = UtilConstants.JAVA_KEY_WORDS.contains(member);
if (presenceOfKeyword || (member.matches(UtilConstants.REGEX_FOR_FIRST_DIGIT))) {
if (presenceOfKeyword || member.matches(UtilConstants.REGEX_FOR_FIRST_DIGIT)) {
member = UtilConstants.UNDER_SCORE + member;
}
pkg = pkg + member;
......@@ -144,23 +190,13 @@ public final class JavaIdentifierSyntax {
}
/**
* Get the package from parent's package and string.
*
* @param parentPkg parent's package
* @param parentName parent's name
* @return package string
*/
public static String getPackageFromParent(String parentPkg, String parentName) {
return (parentPkg + UtilConstants.PERIOD + getSubPkgFromName(parentName)).toLowerCase();
}
/**
* Get package sub name from YANG identifier name.
*
* @param name YANG identifier name
* @return java package sub name as per java rules
*/
public static String getSubPkgFromName(String name) {
ArrayList<String> pkgArr = new ArrayList<String>();
String[] nameArr = name.split(UtilConstants.COLAN);
......@@ -177,6 +213,7 @@ public final class JavaIdentifierSyntax {
* @return corresponding java identifier
*/
public static String getCamelCase(String yangIdentifier) {
String[] strArray = yangIdentifier.split(UtilConstants.HYPHEN);
String camelCase = strArray[0];
for (int i = 1; i < strArray.length; i++) {
......@@ -193,16 +230,41 @@ public final class JavaIdentifierSyntax {
* @return corresponding java identifier
*/
public static String getCaptialCase(String yangIdentifier) {
return yangIdentifier.substring(0, 1).toUpperCase() + yangIdentifier.substring(1);
}
/**
* Translate the YANG identifier name to java identifier with first letter in small.
* Translate the YANG identifier name to java identifier with first letter
* in small.
*
* @param yangIdentifier identifier in YANG file.
* @return corresponding java identifier
*/
public static String getLowerCase(String yangIdentifier) {
return yangIdentifier.substring(0, 1).toLowerCase() + yangIdentifier.substring(1);
}
/**
* Get the java Package from package path.
*
* @param packagePath package path
* @return java package
*/
public static String getJavaPackageFromPackagePath(String packagePath) {
return packagePath.replace(File.separator, UtilConstants.PERIOD);
}
/**
* Get the directory path corresponding to java package.
*
* @param packagePath package path
* @return java package
*/
public static String getPackageDirPathFromJavaJPackage(String packagePath) {
return packagePath.replace(UtilConstants.PERIOD, File.separator);
}
}
......
......@@ -16,7 +16,7 @@
package org.onosproject.yangutils.translator.tojava.utils;
import org.onosproject.yangutils.translator.tojava.AttributeInfo;
import org.onosproject.yangutils.translator.tojava.JavaAttributeInfo;
import org.onosproject.yangutils.utils.UtilConstants;
import org.onosproject.yangutils.utils.io.impl.JavaDocGen;
import org.onosproject.yangutils.utils.io.impl.YangIoUtils;
......@@ -35,25 +35,12 @@ public final class MethodsGenerator {
/**
* Returns the methods strings for builder interface.
*
* @param attr attribute info
* @param className name of the java class being generated
* @return method string for builder interface
*/
static String parseBuilderInterfaceMethodString(AttributeInfo attr, String className) {
return getGetterString(attr) + UtilConstants.NEW_LINE + getSetterString(attr, className);
}
/**
* Returns the methods strings for builder interface.
*
* @param name attribute name
* @return method string for builder interface
*/
public static String parseBuilderInterfaceBuildMethodString(String name) {
return JavaDocGen.getJavaDoc(JavaDocGen.JavaDocType.BUILD, name, false)
+ getBuildForInterface(name);
return JavaDocGen.getJavaDoc(JavaDocGen.JavaDocType.BUILD, name, false) + getBuildForInterface(name);
}
/**
......@@ -62,21 +49,13 @@ public final class MethodsGenerator {
* @param attr attribute info
* @return getter string
*/
public static String getGetterString(AttributeInfo attr) {
public static String getGetterString(JavaAttributeInfo attr) {
String returnType = "";
boolean isList = attr.isListAttr();
if (attr.isQualifiedName() && (attr.getImportInfo().getPkgInfo() != null)) {
returnType = attr.getImportInfo().getPkgInfo() + ".";
}
returnType = returnType + attr.getImportInfo().getClassInfo();
String returnType = getReturnType(attr);
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
return JavaDocGen.getJavaDoc(JavaDocGen.JavaDocType.GETTER, attributeName, isList) +
getGetterForInterface(attributeName, returnType, attr.isListAttr())
+ UtilConstants.NEW_LINE;
return JavaDocGen.getJavaDoc(JavaDocGen.JavaDocType.GETTER, attributeName, attr.isListAttr()) +
getGetterForInterface(attributeName, returnType, attr.isListAttr());
}
/**
......@@ -86,20 +65,13 @@ public final class MethodsGenerator {
* @param className java class name
* @return setter string
*/
public static String getSetterString(AttributeInfo attr, String className) {
public static String getSetterString(JavaAttributeInfo attr, String className) {
String attrType = "";
boolean isList = attr.isListAttr();
if (attr.isQualifiedName() && (attr.getImportInfo().getPkgInfo() != null)) {
attrType = attr.getImportInfo().getPkgInfo() + ".";
}
attrType = attrType + attr.getImportInfo().getClassInfo();
String attrType = getReturnType(attr);
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
return JavaDocGen.getJavaDoc(JavaDocGen.JavaDocType.SETTER, attributeName, isList)
+ getSetterForInterface(attributeName, attrType, className, attr.isListAttr())
+ UtilConstants.NEW_LINE;
return JavaDocGen.getJavaDoc(JavaDocGen.JavaDocType.SETTER, attributeName, attr.isListAttr())
+ getSetterForInterface(attributeName, attrType, className, attr.isListAttr());
}
/**
......@@ -133,13 +105,9 @@ public final class MethodsGenerator {
* @param className class name
* @return default constructor string
*/
public static String getTypeDefConstructor(AttributeInfo attr, String className) {
public static String getTypeDefConstructor(JavaAttributeInfo attr, String className) {
String attrQuaifiedType = "";
if (attr.isQualifiedName() && (attr.getImportInfo().getPkgInfo() != null)) {
attrQuaifiedType = attr.getImportInfo().getPkgInfo() + ".";
}
attrQuaifiedType = attrQuaifiedType + attr.getImportInfo().getClassInfo();
String attrQuaifiedType = getReturnType(attr);
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (!attr.isListAttr()) {
......@@ -160,13 +128,12 @@ public final class MethodsGenerator {
private static String getTypeDefConstructorString(String type, String name, String className) {
return UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.PUBLIC + UtilConstants.SPACE
+ className + UtilConstants.OPEN_PARENTHESIS
+ type + UtilConstants.SPACE + "value" + UtilConstants.CLOSE_PARENTHESIS
+ UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET + UtilConstants.NEW_LINE
+ UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.THIS
+ className + UtilConstants.OPEN_PARENTHESIS + type + UtilConstants.SPACE + UtilConstants.VALUE
+ UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET
+ UtilConstants.NEW_LINE + UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.THIS
+ UtilConstants.PERIOD + name + UtilConstants.SPACE + UtilConstants.EQUAL + UtilConstants.SPACE
+ "value" + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.CLOSE_CURLY_BRACKET;
+ UtilConstants.VALUE + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.CLOSE_CURLY_BRACKET;
}
/**
......@@ -176,6 +143,7 @@ public final class MethodsGenerator {
* @return check not null string
*/
public static String getCheckNotNull(String name) {
return UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.CHECK_NOT_NULL_STRING
+ UtilConstants.OPEN_PARENTHESIS + name + UtilConstants.COMMA + UtilConstants.SPACE + name
+ UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE;
......@@ -199,20 +167,16 @@ public final class MethodsGenerator {
* @param attr attribute info
* @return getter method for class
*/
public static String getGetterForClass(AttributeInfo attr) {
public static String getGetterForClass(JavaAttributeInfo attr) {
String attrQuaifiedType = "";
if (attr.isQualifiedName() && (attr.getImportInfo().getPkgInfo() != null)) {
attrQuaifiedType = attr.getImportInfo().getPkgInfo() + ".";
}
attrQuaifiedType = attrQuaifiedType + attr.getImportInfo().getClassInfo();
String attrQuaifiedType = getReturnType(attr);
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (!attr.isListAttr()) {
return getGetter(attrQuaifiedType, attributeName);
}
String listAttr = getListString() + attrQuaifiedType + UtilConstants.DIAMOND_CLOSE_BRACKET;
return getGetter(listAttr, attributeName);
return getGetter(listAttr, attributeName + UtilConstants.SUFIX_S);
}
/**
......@@ -240,19 +204,15 @@ public final class MethodsGenerator {
* @param className name of the class
* @return setter method for class
*/
public static String getSetterForClass(AttributeInfo attr, String className) {
public static String getSetterForClass(JavaAttributeInfo attr, String className) {
String attrQuaifiedType = "";
if (attr.isQualifiedName() && (attr.getImportInfo().getPkgInfo() != null)) {
attrQuaifiedType = attr.getImportInfo().getPkgInfo() + ".";
}
attrQuaifiedType = attrQuaifiedType + attr.getImportInfo().getClassInfo();
String attrQuaifiedType = getReturnType(attr);
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (!attr.isListAttr()) {
return getSetter(className, attributeName, attrQuaifiedType);
}
String listAttr = getListString() + attrQuaifiedType + UtilConstants.DIAMOND_CLOSE_BRACKET;
return getSetter(className, attributeName, listAttr);
return getSetter(className, attributeName + UtilConstants.SUFIX_S, listAttr);
}
/**
......@@ -283,20 +243,16 @@ public final class MethodsGenerator {
* @param attr attribute info
* @return setter method for class
*/
public static String getSetterForTypeDefClass(AttributeInfo attr) {
public static String getSetterForTypeDefClass(JavaAttributeInfo attr) {
String attrQuaifiedType = "";
if (attr.isQualifiedName() && (attr.getImportInfo().getPkgInfo() != null)) {
attrQuaifiedType = attr.getImportInfo().getPkgInfo() + ".";
}
attrQuaifiedType = attrQuaifiedType + attr.getImportInfo().getClassInfo();
String attrQuaifiedType = getReturnType(attr);
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (!attr.isListAttr()) {
return getTypeDefSetter(attrQuaifiedType, attributeName);
}
String listAttr = getListString() + attrQuaifiedType + UtilConstants.DIAMOND_CLOSE_BRACKET;
return getTypeDefSetter(listAttr, attributeName);
return getTypeDefSetter(listAttr, attributeName + UtilConstants.SUFIX_S);
}
/**
......@@ -311,12 +267,12 @@ public final class MethodsGenerator {
return UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.PUBLIC + UtilConstants.SPACE
+ UtilConstants.VOID + UtilConstants.SPACE + UtilConstants.SET_METHOD_PREFIX
+ JavaIdentifierSyntax.getCaptialCase(name) + UtilConstants.OPEN_PARENTHESIS
+ type + UtilConstants.SPACE + "value" + UtilConstants.CLOSE_PARENTHESIS
+ type + UtilConstants.SPACE + UtilConstants.VALUE + UtilConstants.CLOSE_PARENTHESIS
+ UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET + UtilConstants.NEW_LINE
+ UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.THIS + UtilConstants.PERIOD
+ name + UtilConstants.SPACE + UtilConstants.EQUAL + UtilConstants.SPACE
+ "value" + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.CLOSE_CURLY_BRACKET;
+ UtilConstants.VALUE + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.CLOSE_CURLY_BRACKET;
}
/**
......@@ -325,6 +281,7 @@ public final class MethodsGenerator {
* @return override string
*/
public static String getOverRideString() {
return UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.OVERRIDE + UtilConstants.NEW_LINE;
}
......@@ -343,7 +300,7 @@ public final class MethodsGenerator {
return getGetterInterfaceString(returnType, yangName);
}
String listAttr = getListString() + returnType + UtilConstants.DIAMOND_CLOSE_BRACKET;
return getGetterInterfaceString(listAttr, yangName);
return getGetterInterfaceString(listAttr, yangName + UtilConstants.SUFIX_S);
}
/**
......@@ -378,7 +335,7 @@ public final class MethodsGenerator {
return getSetterInterfaceString(className, attrName, attrType);
}
String listAttr = getListString() + attrType + UtilConstants.DIAMOND_CLOSE_BRACKET;
return getSetterInterfaceString(className, attrName, listAttr);
return getSetterInterfaceString(className, attrName + UtilConstants.SUFIX_S, listAttr);
}
/**
......@@ -404,10 +361,27 @@ public final class MethodsGenerator {
* @return list string
*/
private static String getListString() {
return UtilConstants.LIST + UtilConstants.DIAMOND_OPEN_BRACKET;
}
/**
* Returns return type for attribute.
*
* @param attr attribute info
* @return return type
*/
private static String getReturnType(JavaAttributeInfo attr) {
String returnType = UtilConstants.EMPTY_STRING;
if (attr.isQualifiedName() && (attr.getImportInfo().getPkgInfo() != null)) {
returnType = attr.getImportInfo().getPkgInfo() + UtilConstants.PERIOD;
}
returnType = returnType + attr.getImportInfo().getClassInfo();
return returnType;
}
/**
* Returns the build method strings for interface file.
*
* @param yangName name of the interface
......@@ -421,20 +395,39 @@ public final class MethodsGenerator {
}
/**
* Returns constructor string for impl class.
*
* @param yangName class name
* @return constructor string
*/
public static String getConstructorStart(String yangName) {
String javadoc = MethodsGenerator.getConstructorString(yangName);
String constructor = UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.PUBLIC + UtilConstants.SPACE
+ yangName + UtilConstants.IMPL + UtilConstants.OPEN_PARENTHESIS + yangName + UtilConstants.BUILDER
+ UtilConstants.SPACE + UtilConstants.BUILDER.toLowerCase() + UtilConstants.OBJECT
+ UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET
+ UtilConstants.NEW_LINE;
return javadoc + constructor;
}
/**
* Returns the constructor strings for class file.
*
* @param yangName name of the class
* @param attr attribute info
* @return constructor for class
*/
public static String getConstructor(String yangName, AttributeInfo attr) {
public static String getConstructor(String yangName, JavaAttributeInfo attr) {
String builderAttribute = JavaIdentifierSyntax.getLowerCase(yangName);
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (attr.isListAttr()) {
attributeName = attributeName + UtilConstants.SUFIX_S;
}
String constructor = UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.THIS
+ UtilConstants.PERIOD + JavaIdentifierSyntax.getCamelCase(attributeName)
+ UtilConstants.SPACE + UtilConstants.EQUAL + UtilConstants.SPACE + builderAttribute
+ UtilConstants.BUILDER + UtilConstants.OBJECT + UtilConstants.PERIOD + UtilConstants.GET_METHOD_PREFIX
+ UtilConstants.SPACE + UtilConstants.EQUAL + UtilConstants.SPACE + UtilConstants.BUILDER.toLowerCase()
+ UtilConstants.OBJECT + UtilConstants.PERIOD + UtilConstants.GET_METHOD_PREFIX
+ JavaIdentifierSyntax.getCaptialCase(JavaIdentifierSyntax.getCamelCase(attributeName))
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SEMI_COLAN
+ UtilConstants.NEW_LINE;
......@@ -472,7 +465,7 @@ public final class MethodsGenerator {
return UtilConstants.FOUR_SPACE_INDENTATION + modifierType + UtilConstants.SPACE + name
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE
+ UtilConstants.OPEN_CURLY_BRACKET + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.CLOSE_CURLY_BRACKET + UtilConstants.NEW_LINE;
+ UtilConstants.CLOSE_CURLY_BRACKET;
}
/**
......@@ -483,10 +476,10 @@ public final class MethodsGenerator {
public static String getToStringMethodOpen() {
return getOverRideString() + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.PUBLIC + UtilConstants.SPACE
+ UtilConstants.STRING + UtilConstants.SPACE + "to" + UtilConstants.STRING
+ UtilConstants.STRING + UtilConstants.SPACE + UtilConstants.TO + UtilConstants.STRING
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE
+ UtilConstants.OPEN_CURLY_BRACKET + UtilConstants.NEW_LINE + UtilConstants.EIGHT_SPACE_INDENTATION
+ UtilConstants.RETURN + " MoreObjects.toStringHelper(getClass())" + UtilConstants.NEW_LINE;
+ UtilConstants.RETURN + UtilConstants.GOOGLE_MORE_OBJECT_METHOD_STRING + UtilConstants.NEW_LINE;
}
/**
......@@ -495,10 +488,11 @@ public final class MethodsGenerator {
* @return to string method close string
*/
public static String getToStringMethodClose() {
return UtilConstants.TWELVE_SPACE_INDENTATION + ".to" + UtilConstants.STRING
return UtilConstants.TWELVE_SPACE_INDENTATION + UtilConstants.PERIOD + UtilConstants.TO + UtilConstants.STRING
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SEMI_COLAN
+ UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.CLOSE_CURLY_BRACKET;
+ UtilConstants.CLOSE_CURLY_BRACKET + UtilConstants.NEW_LINE;
}
/**
......@@ -507,8 +501,12 @@ public final class MethodsGenerator {
* @param attr attribute info
* @return to string method
*/
public static String getToStringMethod(AttributeInfo attr) {
public static String getToStringMethod(JavaAttributeInfo attr) {
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (attr.isListAttr()) {
attributeName = attributeName + UtilConstants.SUFIX_S;
}
return UtilConstants.TWELVE_SPACE_INDENTATION + UtilConstants.PERIOD + UtilConstants.ADD_STRING
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.QUOTES
+ attributeName + UtilConstants.QUOTES + UtilConstants.COMMA + UtilConstants.SPACE + attributeName
......@@ -527,7 +525,8 @@ public final class MethodsGenerator {
+ UtilConstants.INT + UtilConstants.SPACE + UtilConstants.HASH_CODE_STRING
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE
+ UtilConstants.OPEN_CURLY_BRACKET + UtilConstants.NEW_LINE + UtilConstants.EIGHT_SPACE_INDENTATION
+ UtilConstants.RETURN + " Objects.hash" + UtilConstants.OPEN_PARENTHESIS;
+ UtilConstants.RETURN + UtilConstants.SPACE + UtilConstants.OBJECT_STRING + UtilConstants.SUFIX_S
+ UtilConstants.PERIOD + UtilConstants.HASH + UtilConstants.OPEN_PARENTHESIS;
}
/**
......@@ -537,10 +536,11 @@ public final class MethodsGenerator {
* @return to hash code method close string
*/
public static String getHashCodeMethodClose(String hashcodeString) {
hashcodeString = YangIoUtils.trimAtLast(hashcodeString, UtilConstants.COMMA);
hashcodeString = YangIoUtils.trimAtLast(hashcodeString, UtilConstants.SPACE);
return hashcodeString + UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.CLOSE_CURLY_BRACKET;
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.CLOSE_CURLY_BRACKET + UtilConstants.NEW_LINE;
}
/**
......@@ -549,8 +549,12 @@ public final class MethodsGenerator {
* @param attr attribute info
* @return hash code method
*/
public static String getHashCodeMethod(AttributeInfo attr) {
public static String getHashCodeMethod(JavaAttributeInfo attr) {
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
if (attr.isListAttr()) {
attributeName = attributeName + UtilConstants.SUFIX_S;
}
return attributeName
+ UtilConstants.COMMA + UtilConstants.SPACE;
......@@ -566,7 +570,7 @@ public final class MethodsGenerator {
return getOverRideString() + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.PUBLIC + UtilConstants.SPACE
+ UtilConstants.BOOLEAN + UtilConstants.SPACE + UtilConstants.EQUALS_STRING
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.OBJECT_STRING + UtilConstants.SPACE + "obj"
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.OBJECT_STRING + UtilConstants.SPACE + UtilConstants.OBJ
+ UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET
+ UtilConstants.NEW_LINE + getEqualsMethodsCommonIfCondition()
+ getEqualsMethodsSpecificIfCondition(className);
......@@ -578,12 +582,13 @@ public final class MethodsGenerator {
* @return if condition string
*/
private static String getEqualsMethodsCommonIfCondition() {
return UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.IF + UtilConstants.SPACE
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.THIS
+ UtilConstants.SPACE + UtilConstants.EQUAL + UtilConstants.EQUAL + UtilConstants.SPACE + "obj"
+ UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET
+ UtilConstants.NEW_LINE + UtilConstants.TWELVE_SPACE_INDENTATION + UtilConstants.RETURN
+ UtilConstants.SPACE + UtilConstants.TRUE + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.THIS + UtilConstants.SPACE + UtilConstants.EQUAL
+ UtilConstants.EQUAL + UtilConstants.SPACE + UtilConstants.OBJ + UtilConstants.CLOSE_PARENTHESIS
+ UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET + UtilConstants.NEW_LINE
+ UtilConstants.TWELVE_SPACE_INDENTATION + UtilConstants.RETURN + UtilConstants.SPACE
+ UtilConstants.TRUE + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE
+ UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.CLOSE_CURLY_BRACKET + UtilConstants.NEW_LINE;
}
......@@ -594,14 +599,15 @@ public final class MethodsGenerator {
* @return if condition string
*/
private static String getEqualsMethodsSpecificIfCondition(String className) {
return UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.IF + UtilConstants.SPACE
+ UtilConstants.OPEN_PARENTHESIS + "obj" + UtilConstants.INSTANCE_OF + className
+ UtilConstants.OPEN_PARENTHESIS + UtilConstants.OBJ + UtilConstants.INSTANCE_OF + className
+ UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE + UtilConstants.OPEN_CURLY_BRACKET
+ UtilConstants.NEW_LINE + UtilConstants.TWELVE_SPACE_INDENTATION + className + UtilConstants.SPACE
+ "other " + UtilConstants.EQUAL + UtilConstants.SPACE + UtilConstants.OPEN_PARENTHESIS + className
+ UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE + "obj" + UtilConstants.SEMI_COLAN
+ UtilConstants.NEW_LINE + UtilConstants.TWELVE_SPACE_INDENTATION + UtilConstants.RETURN
+ UtilConstants.NEW_LINE;
+ UtilConstants.OTHER + UtilConstants.SPACE + UtilConstants.EQUAL + UtilConstants.SPACE
+ UtilConstants.OPEN_PARENTHESIS + className + UtilConstants.CLOSE_PARENTHESIS + UtilConstants.SPACE
+ UtilConstants.OBJ + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE
+ UtilConstants.TWELVE_SPACE_INDENTATION + UtilConstants.RETURN + UtilConstants.NEW_LINE;
}
/**
......@@ -611,6 +617,7 @@ public final class MethodsGenerator {
* @return to equals method close string
*/
public static String getEqualsMethodClose(String equalMethodString) {
equalMethodString = YangIoUtils.trimAtLast(equalMethodString, UtilConstants.AND);
equalMethodString = YangIoUtils.trimAtLast(equalMethodString, UtilConstants.AND);
equalMethodString = YangIoUtils.trimAtLast(equalMethodString, UtilConstants.SPACE);
......@@ -621,7 +628,7 @@ public final class MethodsGenerator {
+ UtilConstants.EIGHT_SPACE_INDENTATION + UtilConstants.RETURN + UtilConstants.SPACE
+ UtilConstants.FALSE + UtilConstants.SEMI_COLAN
+ UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.CLOSE_CURLY_BRACKET;
+ UtilConstants.CLOSE_CURLY_BRACKET + UtilConstants.NEW_LINE;
}
/**
......@@ -630,11 +637,16 @@ public final class MethodsGenerator {
* @param attr attribute info
* @return equals method
*/
public static String getEqualsMethod(AttributeInfo attr) {
public static String getEqualsMethod(JavaAttributeInfo attr) {
String attributeName = JavaIdentifierSyntax.getLowerCase(attr.getAttributeName());
return UtilConstants.SIXTEEN_SPACE_INDENTATION + UtilConstants.SPACE + UtilConstants.OBJECT_STRING + "s"
+ UtilConstants.PERIOD + UtilConstants.EQUALS_STRING + UtilConstants.OPEN_PARENTHESIS + attributeName
+ UtilConstants.COMMA + UtilConstants.SPACE + "other." + attributeName + UtilConstants.CLOSE_PARENTHESIS
if (attr.isListAttr()) {
attributeName = attributeName + UtilConstants.SUFIX_S;
}
return UtilConstants.SIXTEEN_SPACE_INDENTATION + UtilConstants.SPACE + UtilConstants.OBJECT_STRING
+ UtilConstants.SUFIX_S + UtilConstants.PERIOD + UtilConstants.EQUALS_STRING
+ UtilConstants.OPEN_PARENTHESIS + attributeName + UtilConstants.COMMA + UtilConstants.SPACE
+ UtilConstants.OTHER + UtilConstants.PERIOD + attributeName + UtilConstants.CLOSE_PARENTHESIS
+ UtilConstants.SPACE + UtilConstants.AND + UtilConstants.AND;
}
......@@ -646,13 +658,9 @@ public final class MethodsGenerator {
* @param attr attribute info
* @return of method string
*/
public static String getOfMethod(String name, AttributeInfo attr) {
public static String getOfMethod(String name, JavaAttributeInfo attr) {
String attrQuaifiedType = "";
if (attr.isQualifiedName() && (attr.getImportInfo().getPkgInfo() != null)) {
attrQuaifiedType = attr.getImportInfo().getPkgInfo() + ".";
}
attrQuaifiedType = attrQuaifiedType + attr.getImportInfo().getClassInfo();
String attrQuaifiedType = getReturnType(attr);
return UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.PUBLIC + UtilConstants.SPACE + UtilConstants.STATIC
+ UtilConstants.SPACE + name + UtilConstants.SPACE + UtilConstants.OF + UtilConstants.OPEN_PARENTHESIS
......
......@@ -16,6 +16,7 @@
package org.onosproject.yangutils.utils;
import java.io.File;
import java.util.Arrays;
import java.util.List;
......@@ -37,7 +38,7 @@ public final class UtilConstants {
public static final String BUILDER_CLASS_JAVA_DOC = " * Provides the builder implementation of ";
public static final String INTERFACE_JAVA_DOC = " * Abstraction of an entity which provides functionalities of ";
public static final String BUILDER_INTERFACE_JAVA_DOC = " * Builder for ";
public static final String PACKAGE_INFO_JAVADOC = " * Generated java code corresponding to YANG ";
public static final String PACKAGE_INFO_JAVADOC = " * Implementation of YANG file ";
public static final String JAVA_DOC_FIRST_LINE = "/**\n";
public static final String JAVA_DOC_END_LINE = " */\n";
public static final String JAVA_DOC_PARAM = " * @param ";
......@@ -56,6 +57,7 @@ public final class UtilConstants {
* Basic requirements.
*/
public static final String NEW_LINE = "\n";
public static final String MULTIPLE_NEW_LINE = "\n\n";
public static final String EMPTY_STRING = "";
public static final String NEW_LINE_ESTRIC = " *\n";
public static final String PERIOD = ".";
......@@ -66,7 +68,7 @@ public final class UtilConstants {
public static final String SPACE = " ";
public static final String TAB = "\t";
public static final String EQUAL = "=";
public static final String SLASH = "/";
public static final String SLASH = File.separator;
public static final String ADD = "+";
public static final String ASTERISK = "*";
public static final String AT = "@";
......@@ -81,14 +83,22 @@ public final class UtilConstants {
public static final String INSTANCE_OF = " instanceof ";
public static final String VALUE = "value";
public static final String SUFIX_S = "s";
public static final String IF = "if";
public static final String FOR = "for";
public static final String WHILE = "while";
public static final String OF = "of";
public static final String OTHER = "other";
public static final String OBJ = "obj";
public static final String HASH = "hash";
public static final String TO = "to";
public static final String TRUE = "true";
public static final String FALSE = "false";
public static final String ORG = "org";
public static final String TEMP = "temp";
public static final String YANG_RESOURCES = "yang/resources";
/**
* For brackets.
......@@ -219,7 +229,8 @@ public final class UtilConstants {
public static final String DOUBLE_WRAPPER = "Double";
/**
* List of keywords in java, this is used for checking if the input does not contain these keywords.
* List of keywords in java, this is used for checking if the input does not
* contain these keywords.
*/
public static final List JAVA_KEY_WORDS = Arrays.asList("abstract", "assert", "boolean", "break", "byte", "case",
"catch", "char", "class", "const", "continue", "default", "do", "double", "else", "extends", "false",
......@@ -262,8 +273,11 @@ public final class UtilConstants {
* For collections.
*/
public static final String COLLECTION_IMPORTS = "java.util";
public static final String MORE_OBJECT_IMPORT = "import com.google.common.base.MoreObjects;\n";
public static final String JAVA_UTIL_OBJECTS_IMPORT = "import java.util.Objects;\n";
public static final String GOOGLE_MORE_OBJECT_IMPORT_PKG = "com.google.common.base";
public static final String GOOGLE_MORE_OBJECT_IMPORT_CLASS = "MoreObjects;\n";
public static final String GOOGLE_MORE_OBJECT_METHOD_STRING = " MoreObjects.toStringHelper(getClass())";
public static final String JAVA_UTIL_OBJECTS_IMPORT_PKG = "java.util";
public static final String JAVA_UTIL_OBJECTS_IMPORT_CLASS = "Objects;\n";
public static final String ABSTRACT_COLLECTION = "AbstractCollection";
public static final String LIST = "List";
......
......@@ -24,16 +24,11 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provides the license header for the generated files.
*/
public final class CopyrightHeader {
private static final Logger log = getLogger(CopyrightHeader.class);
private static final int EOF = -1;
private static ClassLoader classLoader = CopyrightHeader.class.getClassLoader();
......@@ -52,6 +47,9 @@ public final class CopyrightHeader {
* @throws IOException when fails to parse copyright header
*/
public static String getCopyrightHeader() throws IOException {
if (copyrightHeader == null) {
parseCopyrightHeader();
}
return copyrightHeader;
}
......
......@@ -23,15 +23,13 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.translator.tojava.CachedJavaFileHandle;
import org.onosproject.yangutils.translator.tojava.utils.JavaIdentifierSyntax;
import org.onosproject.yangutils.utils.UtilConstants;
/**
* Utility to handle file system operations.
*/
public final class FileSystemUtil {
/**
* Hiding constructor of a utility class.
*/
......@@ -45,6 +43,7 @@ public final class FileSystemUtil {
* @return existence status of package
*/
public static boolean doesPackageExist(String pkg) {
File pkgDir = new File(pkg.replace(UtilConstants.PERIOD, UtilConstants.SLASH));
File pkgWithFile = new File(pkgDir + File.separator + "package-info.java");
if (pkgDir.exists() && pkgWithFile.isFile()) {
......@@ -61,11 +60,11 @@ public final class FileSystemUtil {
* @throws IOException any IO exception
*/
public static void createPackage(String pkg, String pkgInfo) throws IOException {
if (!doesPackageExist(pkg)) {
try {
File pack = YangIoUtils
.createDirectories(pkg.replace(UtilConstants.PERIOD, UtilConstants.SLASH));
YangIoUtils.addPackageInfo(pack, pkgInfo, pkg);
File pack = YangIoUtils.createDirectories(pkg);
YangIoUtils.addPackageInfo(pack, pkgInfo, pkg.replace(UtilConstants.SLASH, UtilConstants.PERIOD));
} catch (IOException e) {
throw new IOException("failed to create package-info file");
}
......@@ -73,26 +72,6 @@ public final class FileSystemUtil {
}
/**
* Create a java source file in the specified package.
*
* @param pkg java package under which the interface file needs to be
* created
* @param yangName YANG name of the node for which java file needs to be
* created
* @param types types of files to be created
* @throws IOException when fails to create interface file
* @return the cached java file handle, which can be used to further add
* methods
*/
public static CachedFileHandle createSourceFiles(String pkg, String yangName, int types)
throws IOException {
yangName = JavaIdentifierSyntax.getCamelCase(yangName);
CachedFileHandle handler = new CachedJavaFileHandle(pkg, yangName, types);
return handler;
}
/**
* Read the contents from source file and append its contents to append
* file.
*
......@@ -104,7 +83,9 @@ public final class FileSystemUtil {
*/
public static void appendFileContents(File toAppend, File srcFile) throws IOException {
updateFileHandle(srcFile, UtilConstants.NEW_LINE + readAppendFile(toAppend.toString()), false);
updateFileHandle(srcFile,
UtilConstants.NEW_LINE + readAppendFile(toAppend.toString(), UtilConstants.FOUR_SPACE_INDENTATION),
false);
return;
}
......@@ -112,28 +93,34 @@ public final class FileSystemUtil {
* Reads file and convert it to string.
*
* @param toAppend file to be converted
* @param spaces spaces to be appended
* @return string of file
* @throws IOException when fails to convert to string
*/
private static String readAppendFile(String toAppend) throws IOException {
BufferedReader bufferReader = new BufferedReader(new FileReader(toAppend));
public static String readAppendFile(String toAppend, String spaces) throws IOException {
FileReader fileReader = new FileReader(toAppend);
BufferedReader bufferReader = new BufferedReader(fileReader);
try {
StringBuilder stringBuilder = new StringBuilder();
String line = bufferReader.readLine();
while (line != null) {
if (line.equals(UtilConstants.FOUR_SPACE_INDENTATION)
|| line.equals(UtilConstants.EIGHT_SPACE_INDENTATION)
|| line.equals(UtilConstants.SPACE) || line.equals("") || line.equals(UtilConstants.NEW_LINE)) {
stringBuilder.append("\n");
if (line.equals(UtilConstants.SPACE) | line.equals(UtilConstants.EMPTY_STRING)
| line.equals(UtilConstants.EIGHT_SPACE_INDENTATION)
| line.equals(UtilConstants.MULTIPLE_NEW_LINE)) {
stringBuilder.append(UtilConstants.NEW_LINE);
} else if (line.equals(UtilConstants.FOUR_SPACE_INDENTATION)) {
stringBuilder.append(UtilConstants.EMPTY_STRING);
} else {
stringBuilder.append(UtilConstants.FOUR_SPACE_INDENTATION + line);
stringBuilder.append("\n");
stringBuilder.append(spaces + line);
stringBuilder.append(UtilConstants.NEW_LINE);
}
line = bufferReader.readLine();
}
return stringBuilder.toString();
} finally {
fileReader.close();
bufferReader.close();
}
}
......@@ -144,11 +131,14 @@ public final class FileSystemUtil {
* @param inputFile input file
* @param contentTobeAdded content to be appended to the file
* @param isClose when close of file is called.
* @throws IOException when fails to append content to the file
* @throws IOException if the named file exists but is a directory rather
* than a regular file, does not exist but cannot be created, or
* cannot be opened for any other reason
*/
public static void updateFileHandle(File inputFile, String contentTobeAdded, boolean isClose) throws IOException {
FileWriter fileWriter = new FileWriter(inputFile, true);
PrintWriter outputPrintWriter = new PrintWriter(fileWriter);
PrintWriter outputPrintWriter = new PrintWriter(fileWriter, true);
if (!isClose) {
outputPrintWriter.write(contentTobeAdded);
outputPrintWriter.flush();
......
......@@ -156,8 +156,9 @@ public final class JavaDocGen {
+ UtilConstants.PERIOD + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.NEW_LINE_ESTRIC + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_RETURN;
if (isList) {
attribute = UtilConstants.LIST.toLowerCase() + UtilConstants.SPACE + UtilConstants.OF + UtilConstants.SPACE
+ attribute;
String listAttribute = UtilConstants.LIST.toLowerCase() + UtilConstants.SPACE + UtilConstants.OF
+ UtilConstants.SPACE;
getter = getter + listAttribute;
}
getter = getter + attribute + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
......@@ -177,17 +178,19 @@ public final class JavaDocGen {
+ UtilConstants.JAVA_DOC_FIRST_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_SETTERS + attribute
+ UtilConstants.PERIOD + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.NEW_LINE_ESTRIC + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_PARAM
+ attribute + UtilConstants.SPACE;
+ UtilConstants.NEW_LINE_ESTRIC + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_PARAM;
if (isList) {
attribute = UtilConstants.LIST.toLowerCase() + UtilConstants.SPACE + UtilConstants.OF + UtilConstants.SPACE
+ attribute;
setter = setter + attribute + UtilConstants.SUFIX_S + UtilConstants.SPACE;
String listAttribute = UtilConstants.LIST.toLowerCase() + UtilConstants.SPACE + UtilConstants.OF
+ UtilConstants.SPACE;
setter = setter + listAttribute;
} else {
setter = setter + attribute + UtilConstants.SPACE;
}
setter = setter + attribute + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_RETURN + UtilConstants.BUILDER_OBJECT
+ attribute + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.JAVA_DOC_END_LINE;
setter = setter + attribute + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.JAVA_DOC_RETURN + UtilConstants.BUILDER_OBJECT + attribute + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_END_LINE;
return setter;
}
......@@ -215,12 +218,12 @@ public final class JavaDocGen {
* @return javaDocs
*/
private static String generateForTypeDefSetter(String attribute) {
return (UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_FIRST_LINE
return UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_FIRST_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_SETTERS_COMMON + attribute
+ UtilConstants.PERIOD + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.NEW_LINE_ESTRIC + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_PARAM
+ UtilConstants.VALUE + UtilConstants.SPACE + UtilConstants.VALUE + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_END_LINE);
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_END_LINE;
}
/**
......@@ -230,12 +233,12 @@ public final class JavaDocGen {
* @return javaDocs
*/
private static String generateForTypeDefConstructor(String attribute) {
return (UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_FIRST_LINE
return UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_FIRST_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_CONSTRUCTOR + attribute
+ UtilConstants.PERIOD + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.NEW_LINE_ESTRIC + UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_PARAM
+ UtilConstants.VALUE + UtilConstants.SPACE + UtilConstants.VALUE + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_END_LINE);
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_END_LINE;
}
/**
......@@ -299,7 +302,8 @@ public final class JavaDocGen {
* @return javaDocs
*/
private static String generateForDefaultConstructors() {
return UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_DEFAULT_CONSTRUCTOR
return UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_FIRST_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_DEFAULT_CONSTRUCTOR
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_END_LINE;
}
......@@ -315,10 +319,9 @@ public final class JavaDocGen {
+ UtilConstants.IMPL + UtilConstants.PERIOD + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.NEW_LINE_ESTRIC
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_PARAM
+ className.substring(0, 1).toLowerCase() + className.substring(1) + UtilConstants.BUILDER
+ UtilConstants.OBJECT + UtilConstants.SPACE + UtilConstants.BUILDER_OBJECT + UtilConstants.SPACE
+ className + UtilConstants.NEW_LINE + UtilConstants.FOUR_SPACE_INDENTATION
+ UtilConstants.JAVA_DOC_END_LINE;
+ UtilConstants.BUILDER.toLowerCase() + UtilConstants.OBJECT + UtilConstants.SPACE
+ UtilConstants.BUILDER_OBJECT + UtilConstants.SPACE + className + UtilConstants.NEW_LINE
+ UtilConstants.FOUR_SPACE_INDENTATION + UtilConstants.JAVA_DOC_END_LINE;
}
/**
......
......@@ -43,6 +43,7 @@ public final class YangFileScanner {
* operations
*/
public static List<String> getJavaFiles(String root) throws NullPointerException, IOException {
return getFiles(root, ".java");
}
......@@ -56,6 +57,7 @@ public final class YangFileScanner {
* operations
*/
public static List<String> getYangFiles(String root) throws NullPointerException, IOException {
return getFiles(root, ".yang");
}
......@@ -65,10 +67,12 @@ public final class YangFileScanner {
* @param root specified directory
* @param extension file extension
* @return list of required files
* @throws NullPointerException when no file is there
* @throws IOException when files get deleted while performing the
* operations
*/
public static List<String> getFiles(String root, String extension) throws NullPointerException, IOException {
List<String> store = new LinkedList<>();
Stack<String> stack = new Stack<>();
stack.push(root);
......
......@@ -16,12 +16,13 @@
package org.onosproject.yangutils.utils.io.impl;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.BufferedWriter;
import java.io.File;
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.List;
import org.apache.commons.io.FileUtils;
......@@ -31,12 +32,16 @@ import org.onosproject.yangutils.utils.UtilConstants;
import org.slf4j.Logger;
import org.sonatype.plexus.build.incremental.BuildContext;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provides common utility functionalities for code generation.
*/
public final class YangIoUtils {
private static final Logger log = getLogger(YangIoUtils.class);
private static final String TARGET_RESOURCE_PATH = UtilConstants.SLASH + UtilConstants.TEMP + UtilConstants.SLASH
+ UtilConstants.YANG_RESOURCES + UtilConstants.SLASH;
/**
* Default constructor.
......@@ -67,9 +72,9 @@ public final class YangIoUtils {
*/
public static void addPackageInfo(File path, String classInfo, String pack) throws IOException {
if (pack.contains(UtilConstants.YANG_GEN_DIR)) {
String[] strArray = pack.split(UtilConstants.YANG_GEN_DIR);
pack = strArray[1];
if (pack.contains(UtilConstants.ORG)) {
String[] strArray = pack.split(UtilConstants.ORG);
pack = UtilConstants.ORG + strArray[1];
}
try {
......@@ -91,19 +96,13 @@ public final class YangIoUtils {
/**
* Cleans the generated directory if already exist in source folder.
*
* @param baseDir generated directory in previous build
* @param dir generated directory in previous build
*/
public static void clean(String baseDir) {
File generatedDirectory = new File(baseDir + File.separator + UtilConstants.YANG_GEN_DIR
+ UtilConstants.DEFAULT_BASE_PKG.replace(UtilConstants.PERIOD, UtilConstants.SLASH));
public static void clean(String dir) {
File generatedDirectory = new File(dir);
if (generatedDirectory.exists()) {
List<String> javafiles;
try {
javafiles = YangFileScanner.getJavaFiles(generatedDirectory.toString());
for (String file : javafiles) {
File currentFile = new File(file);
currentFile.delete();
}
FileUtils.deleteDirectory(generatedDirectory);
} catch (IOException e) {
log.info("Failed to delete the generated files in " + generatedDirectory + " directory");
......@@ -121,9 +120,6 @@ public final class YangIoUtils {
public static void addToSource(String source, MavenProject project, BuildContext context) {
project.addCompileSourceRoot(source);
Resource rsc = new Resource();
rsc.setDirectory(source);
project.addResource(rsc);
context.refresh(project.getBasedir());
log.info("Source directory added to compilation root: " + source);
}
......@@ -136,6 +132,7 @@ public final class YangIoUtils {
* @return new string
*/
public static String trimAtLast(String valueString, String removealStirng) {
StringBuilder stringBuilder = new StringBuilder(valueString);
int index = valueString.lastIndexOf(removealStirng);
stringBuilder.deleteCharAt(index);
......@@ -149,6 +146,7 @@ public final class YangIoUtils {
* @return parted string
*/
public static String partString(String partString) {
String[] strArray = partString.split(UtilConstants.COMMA);
String newString = "";
for (int i = 0; i < strArray.length; i++) {
......@@ -163,4 +161,91 @@ public final class YangIoUtils {
return trimAtLast(newString, UtilConstants.COMMA);
}
/**
* Returns backspaced string.
*
* @param charString char string
* @return backspace string
*/
public static String deleteLastChar(String charString) {
return charString.substring(0, charString.length() - 1);
}
/**
* Get the directory path of the package in canonical form.
*
* @param baseCodeGenPath base path where the generated files needs to be
* put.
* @param pathOfJavaPkg java package of the file being generated
* @return absolute path of the package in canonical form
*/
public static String getDirectory(String baseCodeGenPath, String pathOfJavaPkg) {
if (pathOfJavaPkg.charAt(pathOfJavaPkg.length() - 1) == File.separatorChar) {
pathOfJavaPkg = trimAtLast(pathOfJavaPkg, UtilConstants.SLASH);
}
String[] strArray = pathOfJavaPkg.split(UtilConstants.SLASH);
if (strArray[0].equals(UtilConstants.EMPTY_STRING)) {
return pathOfJavaPkg;
} else {
return baseCodeGenPath + File.separator + pathOfJavaPkg;
}
}
/**
* Get the absolute path of the package in canonical form.
*
* @param baseCodeGenPath base path where the generated files needs to be
* put.
* @param pathOfJavaPkg java package of the file being generated
* @return absolute path of the package in canonical form
*/
public static String getAbsolutePackagePath(String baseCodeGenPath, String pathOfJavaPkg) {
return baseCodeGenPath + pathOfJavaPkg;
}
/**
* Copy YANG files to the current project's output directory.
*
* @param yangFiles list of YANG files
* @param outputDir project's output directory
* @param project maven project
* @throws IOException when fails to copy files to destination resource
* directory
*/
public static void copyYangFilesToTarget(List<String> yangFiles, String outputDir, MavenProject project)
throws IOException {
List<File> files = getListOfFile(yangFiles);
String path = outputDir + TARGET_RESOURCE_PATH;
File targetDir = new File(path);
targetDir.mkdirs();
for (File file : files) {
Files.copy(file.toPath(),
new File(path + file.getName()).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
Resource rsc = new Resource();
rsc.setDirectory(outputDir + UtilConstants.SLASH + UtilConstants.TEMP + UtilConstants.SLASH);
project.addResource(rsc);
}
/**
* Provides a list of files from list of strings.
*
* @param strings list of strings
* @return list of files
*/
private static List<File> getListOfFile(List<String> strings) {
List<File> files = new ArrayList<>();
for (String file : strings) {
files.add(new File(file));
}
return files;
}
}
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yangutils.translator.tojava;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import org.onosproject.yangutils.datamodel.YangDataTypes;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.CachedFileHandle;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.utils.UtilConstants;
import org.onosproject.yangutils.utils.io.impl.CopyrightHeader;
import org.onosproject.yangutils.utils.io.impl.FileSystemUtil;
/**
* Unit test case for cached java file handle.
*/
public class CachedJavaFileHandleTest {
private static final String DIR_PKG = "target/unit/cachedfile/yangmodel/";
private static final String PKG = "org.onosproject.unittest";
private static final String CHILD_PKG = "target/unit/cachedfile/child";
private static final String YANG_NAME = "Test1";
private static final int GEN_TYPE = GeneratedFileType.GENERATE_INTERFACE_WITH_BUILDER;
/**
* Unit test case for add attribute info.
*
* @throws IOException when fails to add an attribute
*/
@Test
public void testForAddAttributeInfo() throws IOException {
AttributeInfo attr = getAttr();
attr.setListAttr(false);
getFileHandle().addAttributeInfo(attr.getAttributeType(), attr.getAttributeName(), attr.isListAttr());
}
/**
* Unit test case for close of cached files.
*
* @throws IOException when fails to generate files
*/
@Test
public void testForClose() throws IOException {
CopyrightHeader.parseCopyrightHeader();
AttributeInfo attr = getAttr();
attr.setListAttr(false);
CachedFileHandle handle = getFileHandle();
handle.addAttributeInfo(attr.getAttributeType(), attr.getAttributeName(), attr.isListAttr());
handle.close();
assertThat(true, is(getStubDir().exists()));
assertThat(true, is(getStubPkgInfo().exists()));
assertThat(true, is(getStubInterfaceFile().exists()));
assertThat(true, is(getStubBuilderFile().exists()));
}
/**
* Returns attribute info.
*
* @return attribute info
*/
@SuppressWarnings("rawtypes")
private AttributeInfo getAttr() {
YangType<?> type = new YangType();
YangDataTypes dataType = YangDataTypes.STRING;
type.setDataTypeName("string");
type.setDataType(dataType);
AttributeInfo attr = new AttributeInfo();
attr.setAttributeName("testAttr");
attr.setAttributeType(type);
return attr;
}
/**
* Returns cached java file handle.
*
* @return java file handle
*/
private CachedFileHandle getFileHandle() throws IOException {
CopyrightHeader.parseCopyrightHeader();
FileSystemUtil.createPackage(DIR_PKG + File.separator + PKG, YANG_NAME);
CachedFileHandle fileHandle = FileSystemUtil.createSourceFiles(PKG, YANG_NAME, GEN_TYPE);
fileHandle.setRelativeFilePath(PKG.replace(".", "/"));
fileHandle.setCodeGenFilePath(DIR_PKG);
return fileHandle;
}
/**
* Returns stub directory file object.
*
* @return stub directory file
*/
private File getStubDir() {
return new File(DIR_PKG);
}
/**
* Returns stub package-info file object.
*
* @return stub package-info file
*/
private File getStubPkgInfo() {
return new File(DIR_PKG + PKG.replace(UtilConstants.PERIOD, UtilConstants.SLASH) + File.separator
+ "package-info.java");
}
/**
* Returns stub interface file object.
*
* @return stub interface file
*/
private File getStubInterfaceFile() {
return new File(DIR_PKG + PKG.replace(UtilConstants.PERIOD, UtilConstants.SLASH) + File.separator + YANG_NAME
+ ".java");
}
/**
* Returns stub builder file.
*
* @return stub builder file
*/
private File getStubBuilderFile() {
return new File(DIR_PKG + PKG.replace(UtilConstants.PERIOD, UtilConstants.SLASH) + File.separator + YANG_NAME
+ "Builder.java");
}
}
......@@ -16,18 +16,19 @@
package org.onosproject.yangutils.translator.tojava.utils;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType;
import org.onosproject.yangutils.translator.tojava.GeneratedMethodTypes;
import org.onosproject.yangutils.translator.tojava.TraversalType;
import org.onosproject.yangutils.utils.UtilConstants;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.assertNotNull;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Unit tests for class definition generator for generated files.
*/
......@@ -46,6 +47,7 @@ public final class ClassDefinitionGeneratorTest {
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InvocationTargetException {
Class<?>[] classesToConstruct = {ClassDefinitionGenerator.class };
for (Class<?> clazz : classesToConstruct) {
Constructor<?> constructor = clazz.getDeclaredConstructor();
......@@ -61,7 +63,7 @@ public final class ClassDefinitionGeneratorTest {
public void generateBuilderClassDefinitionTest() {
String builderClassDefinition = ClassDefinitionGenerator
.generateClassDefinition(GeneratedFileType.BUILDER_CLASS_MASK, "BuilderClass");
.generateClassDefinition(GeneratedJavaFileType.BUILDER_CLASS_MASK, "BuilderClass");
assertThat(true, is(builderClassDefinition.contains(UtilConstants.BUILDER)));
assertThat(true, is(builderClassDefinition.contains(UtilConstants.CLASS)));
}
......@@ -73,7 +75,7 @@ public final class ClassDefinitionGeneratorTest {
public void generateBuilderInterfaceDefinitionTest() {
String builderInterfaceDefinition = ClassDefinitionGenerator
.generateClassDefinition(GeneratedFileType.BUILDER_INTERFACE_MASK, "BuilderInterfaceClass");
.generateClassDefinition(GeneratedJavaFileType.BUILDER_INTERFACE_MASK, "BuilderInterfaceClass");
assertThat(true, is(builderInterfaceDefinition.contains(UtilConstants.BUILDER)));
}
......@@ -83,7 +85,7 @@ public final class ClassDefinitionGeneratorTest {
@Test
public void generateImplDefinitionTest() {
String implDefinition = ClassDefinitionGenerator.generateClassDefinition(GeneratedFileType.IMPL_CLASS_MASK,
String implDefinition = ClassDefinitionGenerator.generateClassDefinition(GeneratedJavaFileType.IMPL_CLASS_MASK,
"ImplClass");
assertThat(true, is(implDefinition.contains(UtilConstants.IMPL)));
}
......@@ -94,7 +96,8 @@ public final class ClassDefinitionGeneratorTest {
@Test
public void generateinterfaceDefinitionTest() {
String interfaceDefinition = ClassDefinitionGenerator.generateClassDefinition(GeneratedFileType.INTERFACE_MASK,
String interfaceDefinition = ClassDefinitionGenerator.generateClassDefinition(
GeneratedJavaFileType.INTERFACE_MASK,
"InterfaceClass");
assertThat(true, is(interfaceDefinition.contains(UtilConstants.INTERFACE)));
}
......@@ -105,7 +108,7 @@ public final class ClassDefinitionGeneratorTest {
@Test
public void generateTypeDefTest() {
String typeDef = ClassDefinitionGenerator.generateClassDefinition(GeneratedFileType.GENERATE_TYPEDEF_CLASS,
String typeDef = ClassDefinitionGenerator.generateClassDefinition(GeneratedJavaFileType.GENERATE_TYPEDEF_CLASS,
"invalid");
assertThat(true, is(typeDef.contains(UtilConstants.CLASS)));
}
......
......@@ -16,21 +16,19 @@
package org.onosproject.yangutils.translator.tojava.utils;
import org.junit.Test;
import org.onosproject.yangutils.datamodel.YangDataTypes;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.onosproject.yangutils.translator.tojava.GeneratedMethodTypes;
import org.onosproject.yangutils.translator.tojava.ImportInfo;
import org.onosproject.yangutils.utils.UtilConstants;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
import org.onosproject.yangutils.translator.tojava.GeneratedJavaFileType;
import org.onosproject.yangutils.translator.tojava.GeneratedMethodTypes;
import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
import org.onosproject.yangutils.utils.UtilConstants;
/**
* Unit test cases for java code snippet generator.
*/
......@@ -38,7 +36,7 @@ public class JavaCodeSnippetGenTest {
private static final String PKG_INFO = "org.onosproject.unittest";
private static final String CLASS_INFO = "JavaCodeSnippetGenTest";
private static final int FILE_GEN_TYPE = GeneratedFileType.INTERFACE_MASK;
private static final int FILE_GEN_TYPE = GeneratedJavaFileType.INTERFACE_MASK;
private static final GeneratedMethodTypes METHOD_GEN_TYPE = GeneratedMethodTypes.GETTER;
private static final String YANG_NAME = "Test";
private static final String STRING = "String";
......@@ -69,7 +67,7 @@ public class JavaCodeSnippetGenTest {
*/
@Test
public void testForImportText() {
ImportInfo importInfo = new ImportInfo();
JavaQualifiedTypeInfo importInfo = new JavaQualifiedTypeInfo();
importInfo.setPkgInfo(PKG_INFO);
importInfo.setClassInfo(CLASS_INFO);
......@@ -107,7 +105,7 @@ public class JavaCodeSnippetGenTest {
*/
@Test
public void testForJavaClassDefInterfaceClose() {
String interfaceDef = JavaCodeSnippetGen.getJavaClassDefClose(FILE_GEN_TYPE, YANG_NAME);
String interfaceDef = JavaCodeSnippetGen.getJavaClassDefClose();
assertThat(true, is(interfaceDef.equals(UtilConstants.CLOSE_CURLY_BRACKET)));
}
......@@ -116,8 +114,7 @@ public class JavaCodeSnippetGenTest {
*/
@Test
public void testForJavaClassDefBuilderClassClose() {
String builderClassDef = JavaCodeSnippetGen.getJavaClassDefClose(GeneratedFileType.BUILDER_CLASS_MASK,
YANG_NAME);
String builderClassDef = JavaCodeSnippetGen.getJavaClassDefClose();
assertThat(true, is(builderClassDef.equals(UtilConstants.CLOSE_CURLY_BRACKET)));
}
......@@ -126,51 +123,40 @@ public class JavaCodeSnippetGenTest {
*/
@Test
public void testForJavaClassDefTypeDefClose() {
String typeDef = JavaCodeSnippetGen.getJavaClassDefClose(GeneratedFileType.GENERATE_TYPEDEF_CLASS, YANG_NAME);
String typeDef = JavaCodeSnippetGen.getJavaClassDefClose();
assertThat(true, is(typeDef.equals(UtilConstants.CLOSE_CURLY_BRACKET)));
}
/**
* Unit test case for java attribute info.
*/
@SuppressWarnings("rawtypes")
@Test
public void testForJavaAttributeInfo() {
String attributeWithoutTypePkg = JavaCodeSnippetGen.getJavaAttributeDefination(null, "String", YANG_NAME,
false);
assertThat(true, is(attributeWithoutTypePkg.equals(UtilConstants.PRIVATE + UtilConstants.SPACE + "String"
+ UtilConstants.SPACE + YANG_NAME + UtilConstants.SEMI_COLAN)));
String attributeWithTypePkg = JavaCodeSnippetGen.getJavaAttributeDefination("java.lang", "String", YANG_NAME,
false);
assertThat(true, is(attributeWithTypePkg.equals(UtilConstants.PRIVATE + UtilConstants.SPACE + "java.lang."
+ "String" + UtilConstants.SPACE + YANG_NAME + UtilConstants.SEMI_COLAN)));
String attributeWithListPkg = JavaCodeSnippetGen.getJavaAttributeDefination("java.lang", "String", YANG_NAME,
true);
String attributeWithoutTypePkg = JavaCodeSnippetGen.getJavaAttributeDefination(null, UtilConstants.STRING,
YANG_NAME, false);
assertThat(true,
is(attributeWithoutTypePkg.equals(UtilConstants.PRIVATE + UtilConstants.SPACE + UtilConstants.STRING
+ UtilConstants.SPACE + YANG_NAME + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE)));
String attributeWithTypePkg = JavaCodeSnippetGen.getJavaAttributeDefination(
UtilConstants.JAVA_LANG, UtilConstants.STRING, YANG_NAME, false);
assertThat(true, is(attributeWithTypePkg
.equals(UtilConstants.PRIVATE + UtilConstants.SPACE + UtilConstants.JAVA_LANG + UtilConstants.PERIOD
+ UtilConstants.STRING + UtilConstants.SPACE + YANG_NAME + UtilConstants.SEMI_COLAN
+ UtilConstants.NEW_LINE)));
String attributeWithListPkg = JavaCodeSnippetGen.getJavaAttributeDefination(
UtilConstants.JAVA_LANG, UtilConstants.STRING, YANG_NAME, true);
assertThat(true,
is(attributeWithListPkg.equals(UtilConstants.PRIVATE + UtilConstants.SPACE + UtilConstants.LIST
+ UtilConstants.DIAMOND_OPEN_BRACKET + "java.lang."
+ "String" + UtilConstants.DIAMOND_CLOSE_BRACKET + UtilConstants.SPACE + YANG_NAME
+ UtilConstants.SEMI_COLAN)));
String attributeWithListWithoutPkg = JavaCodeSnippetGen.getJavaAttributeDefination(null, "String", YANG_NAME,
true);
+ UtilConstants.DIAMOND_OPEN_BRACKET + UtilConstants.JAVA_LANG + UtilConstants.PERIOD
+ UtilConstants.STRING + UtilConstants.DIAMOND_CLOSE_BRACKET + UtilConstants.SPACE + YANG_NAME
+ UtilConstants.SUFIX_S + UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE)));
String attributeWithListWithoutPkg = JavaCodeSnippetGen.getJavaAttributeDefination(null, UtilConstants.STRING,
YANG_NAME, true);
assertThat(true,
is(attributeWithListWithoutPkg.equals(UtilConstants.PRIVATE + UtilConstants.SPACE + UtilConstants.LIST
+ UtilConstants.DIAMOND_OPEN_BRACKET + "String"
+ UtilConstants.DIAMOND_CLOSE_BRACKET + UtilConstants.SPACE + YANG_NAME
+ UtilConstants.SEMI_COLAN)));
}
/**
* Returns YANG type.
*
* @return type
*/
@SuppressWarnings("rawtypes")
private YangType<?> getType() {
YangType<?> type = new YangType();
type.setDataTypeName(STRING);
type.setDataType(YangDataTypes.STRING);
return type;
+ UtilConstants.DIAMOND_OPEN_BRACKET + UtilConstants.STRING
+ UtilConstants.DIAMOND_CLOSE_BRACKET + UtilConstants.SPACE + YANG_NAME + UtilConstants.SUFIX_S
+ UtilConstants.SEMI_COLAN + UtilConstants.NEW_LINE)));
}
}
......
......@@ -16,15 +16,16 @@
package org.onosproject.yangutils.translator.tojava.utils;
import org.junit.Test;
import org.onosproject.yangutils.utils.UtilConstants;
import static org.junit.Assert.assertNotNull;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
import org.onosproject.yangutils.utils.UtilConstants;
/**
* Unit tests for java identifier syntax.
*/
......@@ -54,9 +55,12 @@ public final class JavaIdentifierSyntaxTest {
* @throws SecurityException if any security violation is observed.
* @throws NoSuchMethodException if when the method is not found.
* @throws IllegalArgumentException if there is illegal argument found.
* @throws InstantiationException if instantiation is provoked for the private constructor.
* @throws IllegalAccessException if instance is provoked or a method is provoked.
* @throws InvocationTargetException when an exception occurs by the method or constructor.
* @throws InstantiationException if instantiation is provoked for the
* private constructor.
* @throws IllegalAccessException if instance is provoked or a method is
* provoked.
* @throws InvocationTargetException when an exception occurs by the method
* or constructor.
*/
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
......@@ -70,15 +74,6 @@ public final class JavaIdentifierSyntaxTest {
}
/**
* Unit test for testing the package path generation from a parent package.
*/
@Test
public void getPackageFromParentTest() {
String pkgFromParent = JavaIdentifierSyntax.getPackageFromParent(PARENT_PACKAGE, CHILD_PACKAGE);
assertThat(pkgFromParent.equals(PARENT_WITH_PERIOD + UtilConstants.PERIOD + CHILD_WITH_PERIOD), is(true));
}
/**
* Unit test for root package generation with revision complexity.
*/
@Test
......
......@@ -16,24 +16,24 @@
package org.onosproject.yangutils.translator.tojava.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertNotNull;
import org.onosproject.yangutils.datamodel.YangDataTypes;
import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.tojava.AttributeInfo;
import org.onosproject.yangutils.translator.tojava.ImportInfo;
import org.onosproject.yangutils.translator.tojava.JavaAttributeInfo;
import org.onosproject.yangutils.utils.UtilConstants;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
/**
* Unit tests for generated methods from the file type.
*/
public final class MethodsGeneratorTest {
public static AttributeInfo testAttr = new AttributeInfo();
public static JavaAttributeInfo testAttr;
public static YangType<?> attrType = new YangType<>();
/**
......@@ -42,15 +42,20 @@ public final class MethodsGeneratorTest {
* @throws SecurityException if any security violation is observed
* @throws NoSuchMethodException if when the method is not found
* @throws IllegalArgumentException if there is illegal argument found
* @throws InstantiationException if instantiation is provoked for the private constructor
* @throws IllegalAccessException if instance is provoked or a method is provoked
* @throws InvocationTargetException when an exception occurs by the method or constructor
* @throws InstantiationException if instantiation is provoked for the
* private constructor
* @throws IllegalAccessException if instance is provoked or a method is
* provoked
* @throws InvocationTargetException when an exception occurs by the method
* or constructor
*/
@Test
public void callPrivateConstructors() 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);
......@@ -58,35 +63,32 @@ public final class MethodsGeneratorTest {
}
}
/**
* Unit test case for checking the parse builder and typedef constructor.
*/
@Test
public void getParseBuilderInterfaceMethodConstructorTest() {
ImportInfo forSetter = new ImportInfo();
attrType.setDataTypeName("binary");
attrType.getDataTypeName();
attrType.setDataType(YangDataTypes.BINARY);
attrType.getDataType();
testAttr.setAttributeName("attributeTest");
testAttr.setAttributeType(attrType);
forSetter.setPkgInfo("test1/test3");
forSetter.setClassInfo("This class contains");
testAttr.setImportInfo(forSetter);
String parseBuilderInterface = MethodsGenerator.parseBuilderInterfaceMethodString(testAttr, "newTestName");
assertThat(parseBuilderInterface.contains("attributeTest") && parseBuilderInterface.contains("newTestName"),
is(true));
String parseBuilderInterfaceBuild = MethodsGenerator.parseBuilderInterfaceBuildMethodString("testname7");
assertThat(parseBuilderInterfaceBuild.contains("Builds object of")
&& parseBuilderInterfaceBuild.contains("testname7"), is(true));
String stringTypeDef = MethodsGenerator.getTypeDefConstructor(testAttr, "Testname");
}
// /**
// * Unit test case for checking the parse builder and typedef constructor.
// */
// @Test
// public void getParseBuilderInterfaceMethodConstructorTest() {
//
// JavaQualifiedTypeInfo forSetter = new JavaQualifiedTypeInfo();
// attrType.setDataTypeName("binary");
// attrType.getDataTypeName();
// attrType.setDataType(YangDataTypes.BINARY);
// attrType.getDataType();
// testAttr.setAttributeName("attributeTest");
// testAttr.setAttributeType(attrType);
// forSetter.setPkgInfo("test1/test3");
// forSetter.setClassInfo("This class contains");
// testAttr.setImportInfo(forSetter);
// String stringTypeDef = MethodsGenerator.getTypeDefConstructor(testAttr, "Testname");
// }
/**
* Unit test case for checking the values received from constructor, default constructor and build string formation.
* Unit test case for checking the values received from constructor, default
* constructor and build string formation.
*/
@Test
public void getValuesTest() {
String stringConstructor = MethodsGenerator.getConstructorString("testname");
assertThat(stringConstructor.contains(UtilConstants.JAVA_DOC_CONSTRUCTOR)
&& stringConstructor.contains(UtilConstants.JAVA_DOC_PARAM)
......@@ -102,57 +104,54 @@ public final class MethodsGeneratorTest {
}
/**
* Unit test for checking the values received for class getter, class and typedef setters with list data type.
* Unit test for checking the values received for class getter, class and
* typedef setters with list data type.
*/
@Test
public void getGetterSetterTest() {
ImportInfo forGetterSetter = new ImportInfo();
attrType.setDataTypeName("int");
attrType.getDataTypeName();
attrType.setDataType(YangDataTypes.UINT8);
attrType.getDataType();
testAttr.setAttributeName("AttributeTest1");
testAttr.setAttributeType(attrType);
forGetterSetter.setPkgInfo(null);
forGetterSetter.setClassInfo("This class contains");
testAttr.setImportInfo(forGetterSetter);
testAttr.setListAttr(true);
String getterForClass = MethodsGenerator.getGetterForClass(testAttr);
assertThat(getterForClass.contains(UtilConstants.GET_METHOD_PREFIX) && getterForClass.contains("List<")
&& getterForClass.contains("attributeTest1"), is(true));
String setterForClass = MethodsGenerator.getSetterForClass(testAttr, "TestThis");
assertThat(setterForClass.contains(UtilConstants.SET_METHOD_PREFIX) && setterForClass.contains("List<")
&& setterForClass.contains("attributeTest1"), is(true));
String typeDefSetter = MethodsGenerator.getSetterForTypeDefClass(testAttr);
assertThat(typeDefSetter.contains(UtilConstants.SET_METHOD_PREFIX) && typeDefSetter.contains("List<")
&& typeDefSetter.contains("attributeTest1") && typeDefSetter.contains("this."), is(true));
}
// @Test
// public void getGetterSetterTest() {
//
// JavaQualifiedTypeInfo forGetterSetter = new JavaQualifiedTypeInfo();
// attrType.setDataTypeName("int");
// attrType.getDataTypeName();
// attrType.setDataType(YangDataTypes.UINT8);
// attrType.getDataType();
// testAttr.setAttributeName("AttributeTest1");
// testAttr.setAttributeType(attrType);
// forGetterSetter.setPkgInfo("null");
// forGetterSetter.setClassInfo("This class contains");
// testAttr.setImportInfo(forGetterSetter);
// testAttr.setListAttr(true);
// String getterForClass = MethodsGenerator.getGetterForClass(testAttr);
// assertThat(getterForClass.contains(UtilConstants.GET_METHOD_PREFIX) && getterForClass.contains("List<")
// && getterForClass.contains("attributeTest1"), is(true));
// String setterForClass = MethodsGenerator.getSetterForClass(testAttr, "TestThis");
// assertThat(setterForClass.contains(UtilConstants.SET_METHOD_PREFIX) && setterForClass.contains("List<")
// && setterForClass.contains("attributeTest1"), is(true));
// String typeDefSetter = MethodsGenerator.getSetterForTypeDefClass(testAttr);
// assertThat(typeDefSetter.contains(UtilConstants.SET_METHOD_PREFIX) && typeDefSetter.contains("List<")
// && typeDefSetter.contains("attributeTest1") && typeDefSetter.contains("this."), is(true));
// }
/**
* Unit test case for checking the parse builder and typedef constructor with list data type.
* Unit test case for checking the parse builder and typedef constructor
* with list data type.
*/
@Test
public void getConstructorWithListTypeTest() {
ImportInfo forSetter = new ImportInfo();
attrType.setDataTypeName("binary");
attrType.getDataTypeName();
attrType.setDataType(YangDataTypes.BINARY);
attrType.getDataType();
testAttr.setAttributeName("attributeTest");
testAttr.setAttributeType(attrType);
forSetter.setPkgInfo(null);
forSetter.setClassInfo("This class contains");
testAttr.setImportInfo(forSetter);
testAttr.setListAttr(true);
String parseBuilderInterface = MethodsGenerator.parseBuilderInterfaceMethodString(testAttr, "newTestName");
assertThat(parseBuilderInterface.contains("attributeTest") && parseBuilderInterface.contains("List<"),
is(true));
String parseBuilderInterfaceBuild = MethodsGenerator.parseBuilderInterfaceBuildMethodString("testname7");
assertThat(parseBuilderInterfaceBuild.contains("Builds object of")
&& parseBuilderInterfaceBuild.contains("testname7"), is(true));
String stringTypeDef = MethodsGenerator.getTypeDefConstructor(testAttr, "Testname");
assertThat(stringTypeDef.contains("(List<") && stringTypeDef.contains("Testname")
&& stringTypeDef.contains(UtilConstants.THIS), is(true));
}
// @Test
// public void getConstructorWithListTypeTest() {
//
// JavaQualifiedTypeInfo forSetter = new JavaQualifiedTypeInfo();
// attrType.setDataTypeName("binary");
// attrType.getDataTypeName();
// attrType.setDataType(YangDataTypes.BINARY);
// attrType.getDataType();
// testAttr.setAttributeName("attributeTest");
// testAttr.setAttributeType(attrType);
// forSetter.setPkgInfo("null");
// forSetter.setClassInfo("This class contains");
// testAttr.setImportInfo(forSetter);
// testAttr.setListAttr(true);
// String stringTypeDef = MethodsGenerator.getTypeDefConstructor(testAttr, "Testname");
// assertThat(stringTypeDef.contains("(List<") && stringTypeDef.contains("Testname")
// && stringTypeDef.contains(UtilConstants.THIS), is(true));
// }
}
......
......@@ -34,12 +34,12 @@ public final class UtilConstantsTest {
/**
* A private constructor is tested.
*
* @throws SecurityException if any security violation is observed.
* @throws NoSuchMethodException if when the method is not found.
* @throws IllegalArgumentException if there is illegal argument found.
* @throws InstantiationException if instantiation is provoked for the private constructor.
* @throws IllegalAccessException if instance is provoked or a method is provoked.
* @throws InvocationTargetException when an exception occurs by the method or constructor.
* @throws SecurityException if any security violation is observed
* @throws NoSuchMethodException if when the method is not found
* @throws IllegalArgumentException if there is illegal argument found
* @throws InstantiationException if instantiation is provoked for the private constructor
* @throws IllegalAccessException if instance is provoked or a method is provoked
* @throws InvocationTargetException when an exception occurs by the method or constructor
*/
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
......
......@@ -50,12 +50,12 @@ public final class CopyrightHeaderTest {
/**
* Unit test for testing private constructor.
*
* @throws SecurityException if any security violation is observed.
* @throws NoSuchMethodException if when the method is not found.
* @throws IllegalArgumentException if there is illegal argument found.
* @throws InstantiationException if instantiation is provoked for the private constructor.
* @throws IllegalAccessException if instance is provoked or a method is provoked.
* @throws InvocationTargetException when an exception occurs by the method or constructor.
* @throws SecurityException if any security violation is observed
* @throws NoSuchMethodException if when the method is not found
* @throws IllegalArgumentException if there is illegal argument found
* @throws InstantiationException if instantiation is provoked for the private constructor
* @throws IllegalAccessException if instance is provoked or a method is provoked
* @throws InvocationTargetException when an exception occurs by the method or constructor
*/
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
......
......@@ -16,36 +16,27 @@
package org.onosproject.yangutils.utils.io.impl;
import static org.slf4j.LoggerFactory.getLogger;
import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.onosproject.yangutils.translator.GeneratedFileType;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onosproject.yangutils.utils.UtilConstants;
import org.slf4j.Logger;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests the file handle utilities.
*/
public final class FileSystemUtilTest {
public static String baseDirPkg = "target.UnitTestCase.";
public static String packageInfoContent = "testGeneration6";
public static String baseDir = "target/UnitTestCase";
private final Logger log = getLogger(getClass());
public static final String BASE_DIR_PKG = "target.UnitTestCase.";
public static final String PKG_INFO_CONTENT = "testGeneration6";
public static final String BASE_PKG = "target/UnitTestCase";
@Rule
public ExpectedException thrown = ExpectedException.none();
......@@ -56,15 +47,20 @@ public final class FileSystemUtilTest {
* @throws SecurityException if any security violation is observed
* @throws NoSuchMethodException if when the method is not found
* @throws IllegalArgumentException if there is illegal argument found
* @throws InstantiationException if instantiation is provoked for the private constructor
* @throws IllegalAccessException if instance is provoked or a method is provoked
* @throws InvocationTargetException when an exception occurs by the method or constructor
* @throws InstantiationException if instantiation is provoked for the
* private constructor
* @throws IllegalAccessException if instance is provoked or a method is
* provoked
* @throws InvocationTargetException when an exception occurs by the method
* or constructor
*/
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InvocationTargetException {
Class<?>[] classesToConstruct = {FileSystemUtil.class};
Class<?>[] classesToConstruct = {
FileSystemUtil.class
};
for (Class<?> clazz : classesToConstruct) {
Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
......@@ -73,20 +69,12 @@ public final class FileSystemUtilTest {
}
/**
* This test case checks the creation of source files.
*/
@Test
public void createSourceFilesTest() throws IOException {
FileSystemUtil.createSourceFiles(baseDirPkg + "srcFile1", packageInfoContent, GeneratedFileType.INTERFACE_MASK);
}
/**
* This test case checks the contents to be written in the file.
*/
@Test
public void updateFileHandleTest() throws IOException {
File dir = new File(baseDir + File.separator + "File1");
File dir = new File(BASE_PKG + File.separator + "File1");
dir.mkdirs();
File createFile = new File(dir + "testFile");
createFile.createNewFile();
......@@ -104,31 +92,33 @@ public final class FileSystemUtilTest {
*/
@Test
public void packageExistTest() throws IOException {
String dirPath = "exist1.exist2.exist3";
String strPath = baseDirPkg + dirPath;
String strPath = BASE_DIR_PKG + dirPath;
File createDir = new File(strPath.replace(UtilConstants.PERIOD, UtilConstants.SLASH));
createDir.mkdirs();
File createFile = new File(createDir + File.separator + "package-info.java");
createFile.createNewFile();
assertTrue(FileSystemUtil.doesPackageExist(strPath));
FileSystemUtil.createPackage(strPath, packageInfoContent);
FileSystemUtil.createPackage(strPath, PKG_INFO_CONTENT);
createDir.delete();
}
/**
* This test case checks the package does not exist.
*/
@Test
public void packageNotExistTest() throws IOException {
String dirPath = "notexist1.notexist2";
String strPath = baseDirPkg + dirPath;
File createDir = new File(strPath.replace(UtilConstants.PERIOD, UtilConstants.SLASH));
assertFalse(FileSystemUtil.doesPackageExist(strPath));
createDir.mkdirs();
assertFalse(FileSystemUtil.doesPackageExist(strPath));
CopyrightHeader.parseCopyrightHeader();
FileSystemUtil.createPackage(strPath, packageInfoContent);
assertTrue(FileSystemUtil.doesPackageExist(strPath));
createDir.delete();
}
// @Test
// public void packageNotExistTest() throws IOException {
// String dirPath = "notexist1.notexist2";
// String strPath = BASE_DIR_PKG + dirPath;
// File createDir = new File(strPath.replace(UtilConstants.PERIOD, UtilConstants.SLASH));
// assertFalse(FileSystemUtil.doesPackageExist(strPath));
// createDir.mkdirs();
// assertFalse(FileSystemUtil.doesPackageExist(strPath));
// CopyrightHeader.parseCopyrightHeader();
// FileSystemUtil.createPackage(strPath, PKG_INFO_CONTENT);
// assertTrue(FileSystemUtil.doesPackageExist(strPath));
// createDir.delete();
// }
}
......
......@@ -148,7 +148,7 @@ public final class JavaDocGenTest {
public void packageInfoGenerationTest() {
String packageInfo = JavaDocGen.getJavaDoc(JavaDocType.PACKAGE_INFO, "testGeneration1", false);
assertTrue(packageInfo.contains("Generated java code corresponding to YANG") && packageInfo.contains(" */\n"));
assertTrue(packageInfo.contains("Implementation of YANG file") && packageInfo.contains(" */\n"));
}
/**
......
......@@ -47,12 +47,12 @@ public final class YangFileScannerTest {
/**
* A private constructor is tested.
*
* @throws SecurityException if any security violation is observed.
* @throws NoSuchMethodException if when the method is not found.
* @throws IllegalArgumentException if there is illegal argument found.
* @throws InstantiationException if instantiation is provoked for the private constructor.
* @throws IllegalAccessException if instance is provoked or a method is provoked.
* @throws InvocationTargetException when an exception occurs by the method or constructor.
* @throws SecurityException if any security violation is observed
* @throws NoSuchMethodException if when the method is not found
* @throws IllegalArgumentException if there is illegal argument found
* @throws InstantiationException if instantiation is provoked for the private constructor
* @throws IllegalAccessException if instance is provoked or a method is provoked
* @throws InvocationTargetException when an exception occurs by the method or constructor
*/
@Test
public void callPrivateConstructors() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
......@@ -97,8 +97,8 @@ public final class YangFileScannerTest {
/**
* Method used for creating file inside the specified directory.
*
* @param myDir the path where file has to be created inside.
* @param fileName the name of the file to be created.
* @param myDir the path where file has to be created inside
* @param fileName the name of the file to be created
*/
public void createFile(File myDir, String fileName) throws IOException {
......