Skip to content

Commit

Permalink
Add private constructors for the util classes
Browse files Browse the repository at this point in the history
Refactor the Code
  • Loading branch information
DimuthuMadushan committed Nov 7, 2023
2 parents 725084a + 08eebd5 commit 1d32ea6
Show file tree
Hide file tree
Showing 17 changed files with 46 additions and 78 deletions.
8 changes: 7 additions & 1 deletion build-config/resources/package/BalTool.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,10 @@
id = "copybook"

[[dependency]]
path = "resources/[email protected]@.jar"
path = "build/libs/[email protected]@.jar"

[[dependency]]
path = "build/libs/[email protected]@.jar"

[[dependency]]
path = "build/libs/[email protected]@.jar"
Original file line number Diff line number Diff line change
Expand Up @@ -71,22 +71,19 @@ public CopybookCmd() {
}

public CopybookCmd(PrintStream outStream, Path executionDir, boolean exitWhenFinish) {

this.outStream = outStream;
this.executionPath = executionDir;
this.exitWhenFinish = exitWhenFinish;
}

private static void exitError(boolean exit) {

if (exit) {
Runtime.getRuntime().exit(1);
}
}

@Override
public void execute() {

try {
if (helpFlag) {
printLongDesc(new StringBuilder());
Expand All @@ -103,7 +100,6 @@ public void execute() {
}

private void validateInputFlags() throws CmdException, IOException {

if (inputPathFlag) {
if (argList == null) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_100, null);
Expand All @@ -129,7 +125,6 @@ private void executeOperation() throws CopybookTypeGenerationException, CmdExcep

private void generateType(String filePath)
throws CmdException, CopybookTypeGenerationException, FormatterException, IOException {

final File copybookFile = new File(filePath);
if (!copybookFile.exists()) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null,
Expand All @@ -149,7 +144,6 @@ private void generateType(String filePath)
}

private Path getTargetOutputPath() {

Path targetOutputPath = executionPath;
if (this.outputPath != null) {
if (Paths.get(outputPath).isAbsolute()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class Constants {
" only the Copybook definition files with .cpy or .cob extension. %nPlease provide the path of the input " +
" file with -i or --input flag.%ne.g: bal copybook --input <Copybook Definition File>";
public static final String MESSAGE_CAN_NOT_READ_COPYBOOK_FILE =
"Provided Definition file \"%s\" is not allowed to be read";
"Provided definition file \"%s\" is not allowed to be read";
public static final String MESSAGE_FOR_INVALID_COPYBOOK_PATH =
"The Copybook definition file does not exist in the given path";
"The copybook definition file does not exist in the given path";
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ public enum DiagnosticMessages {
" is missing. Please provide the path of the Copybook definition file with -i or --input flag.",
DiagnosticSeverity.ERROR),
COPYBOOK_TYPE_GEN_102("COPYBOOK_TYPE_GEN_102", "Copybook types generation failed: %s", DiagnosticSeverity.ERROR),
COPYBOOK_TYPE_GEN_103("COPYBOOK_TYPE_GEN_103", "Failed to create output directory: %s", DiagnosticSeverity.ERROR),
;
COPYBOOK_TYPE_GEN_103("COPYBOOK_TYPE_GEN_103", "Failed to create output directory: %s", DiagnosticSeverity.ERROR);
private final String code;
private final String description;
private final DiagnosticSeverity severity;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
public class AnnotationGenerator {

public static AnnotationNode generateStringConstraint(DataItem node) {

List<String> fields = getStringAnnotFields(node);
if (fields.isEmpty()) {
return null;
Expand All @@ -50,7 +49,6 @@ public static AnnotationNode generateStringConstraint(DataItem node) {
}

public static AnnotationNode generateIntConstraint(DataItem node) {

List<String> fields = getIntAnnotFields(node);
if (fields.isEmpty()) {
return null;
Expand All @@ -61,7 +59,6 @@ public static AnnotationNode generateIntConstraint(DataItem node) {
}

public static AnnotationNode generateNumberConstraint(DataItem node) {

List<String> fields = getNumberAnnotFields(node);
if (fields.isEmpty()) {
return null;
Expand All @@ -72,7 +69,6 @@ public static AnnotationNode generateNumberConstraint(DataItem node) {
}

private static List<String> getStringAnnotFields(DataItem node) {

List<String> fields = new ArrayList<>();
int value = node.getReadLength();
String fieldRef = GeneratorConstants.MAX_LENGTH + GeneratorConstants.COLON + value;
Expand All @@ -81,7 +77,6 @@ private static List<String> getStringAnnotFields(DataItem node) {
}

private static List<String> getIntAnnotFields(DataItem node) {

List<String> fields = new ArrayList<>();
if (!node.isSinged()) {
int minValue = 0;
Expand All @@ -95,11 +90,12 @@ private static List<String> getIntAnnotFields(DataItem node) {
}

private static List<String> getNumberAnnotFields(DataItem node) {

List<String> fields = new ArrayList<>();
int maxIntegerDigits = 1;
if (node.isSinged() || node.getPicture().startsWith(NEGATIVE_DECIMAL_PIC) || node.getPicture().startsWith(
GeneratorConstants.POSITIVE_DECIMAL_PIC)) {
if (node.isSinged()) {
maxIntegerDigits = node.getReadLength() - node.getFloatingPointLength() - 1;
} else if (node.getPicture().startsWith(NEGATIVE_DECIMAL_PIC) ||
node.getPicture().startsWith(GeneratorConstants.POSITIVE_DECIMAL_PIC)) {
maxIntegerDigits = node.getReadLength() - node.getFloatingPointLength() - 2;
} else {
int minValue = 0;
Expand All @@ -116,10 +112,9 @@ private static List<String> getNumberAnnotFields(DataItem node) {
}

public static AnnotationNode createAnnotationNode(String annotationReference, String annotFields) {

MappingConstructorExpressionNode annotationBody = null;
SimpleNameReferenceNode annotReference = createSimpleNameReferenceNode(
createIdentifierToken(annotationReference));
SimpleNameReferenceNode annotReference =
createSimpleNameReferenceNode(createIdentifierToken(annotationReference));
ExpressionNode expressionNode = NodeParser.parseExpression(annotFields);
if (expressionNode.kind() == MAPPING_CONSTRUCTOR) {
annotationBody = (MappingConstructorExpressionNode) expressionNode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ public ArrayTypeGenerator(CopybookNode groupItemNode) {
this.schemaValue = groupItemNode;
}

@Override public TypeDescriptorNode generateTypeDescriptorNode(List<TypeDefinitionNode> typeDefList) {

@Override
public TypeDescriptorNode generateTypeDescriptorNode(List<TypeDefinitionNode> typeDefList) {
if (schemaValue instanceof GroupItem) {
return getGroputItemDescriptorNode(typeDefList);
} else {
Expand All @@ -60,7 +60,6 @@ public ArrayTypeGenerator(CopybookNode groupItemNode) {
}

private TypeDescriptorNode getGroputItemDescriptorNode(List<TypeDefinitionNode> typeDefList) {

BasicLiteralNode length = createBasicLiteralNode(SyntaxKind.NUMERIC_LITERAL,
createLiteralValueToken(SyntaxKind.DECIMAL_INTEGER_LITERAL_TOKEN,
String.valueOf(schemaValue.getOccurringCount()),
Expand All @@ -75,7 +74,6 @@ private TypeDescriptorNode getGroputItemDescriptorNode(List<TypeDefinitionNode>
}

private TypeDescriptorNode getDataItemDescriptorNode(List<TypeDefinitionNode> typeDefList) {

TypeDefinitionNode fieldType = generateFieldTypeDefNode(
(DataItem) schemaValue, getTypeReferenceName(schemaValue, false));
addToFieldTypeDefinitionList(fieldType, typeDefList);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,10 @@
public abstract class CodeGenerator {

protected CodeGenerator() {

}

public static void generate(Path cbFilePath, Path targetOutputPath, PrintStream outStream)
throws CopybookTypeGenerationException, FormatterException, IOException {

Schema schema = Copybook.parse(cbFilePath.toString());
if (!schema.getErrors().isEmpty()) {
List<String> errorList = schema.getErrors();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,39 +72,33 @@ private CodeGeneratorUtils() {
}

public static TypeGenerator getTypeGenerator(CopybookNode schemaValue) {

if (schemaValue.getOccurringCount() > 0) {
return new ArrayTypeGenerator(schemaValue);
} else if (schemaValue instanceof DataItem dataItem) {
return new ReferencedTypeGenerator(dataItem);
} else {
return new RecordTypeGenerator((GroupItem) schemaValue);
}
return new RecordTypeGenerator((GroupItem) schemaValue);
}

public static String getTypeReferenceName(CopybookNode copybookNode, boolean isRecordFieldReference) {

if (copybookNode instanceof DataItem dataItem) {
if (isRecordFieldReference) {
return extractTypeReferenceName(dataItem);
} else {
if (dataItem.isNumeric()) {
if (dataItem.getFloatingPointLength() > 0) {
return DECIMAL;
}
return INT;
} else if (dataItem.getPicture().contains(COMP_PIC)) {
return BYTE_ARRAY;
} else {
return STRING;
}
if (dataItem.isNumeric()) {
if (dataItem.getFloatingPointLength() > 0) {
return DECIMAL;
}
return INT;
} else if (dataItem.getPicture().contains(COMP_PIC)) {
return BYTE_ARRAY;
}
return STRING;
}
return copybookNode.getName();
}

public static ImportDeclarationNode getImportDeclarationNode(String orgName, String moduleName) {

Token importKeyword = AbstractNodeFactory.createIdentifierToken(IMPORT, SINGLE_WS_MINUTIAE,
SINGLE_WS_MINUTIAE);
Token orgNameToken = AbstractNodeFactory.createIdentifierToken(orgName);
Expand All @@ -119,7 +113,6 @@ public static ImportDeclarationNode getImportDeclarationNode(String orgName, Str
}

public static NodeList<ImportDeclarationNode> createImportDeclarationNodes() {

List<ImportDeclarationNode> imports = new ArrayList<>();
ImportDeclarationNode importForHttp = CodeGeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA,
GeneratorConstants.CONSTRAINT);
Expand All @@ -128,25 +121,21 @@ public static NodeList<ImportDeclarationNode> createImportDeclarationNodes() {
}

private static MinutiaeList getSingleWSMinutiae() {

Minutiae whitespace = AbstractNodeFactory.createWhitespaceMinutiae(" ");
return AbstractNodeFactory.createMinutiaeList(whitespace);
}

public static AnnotationNode generateConstraintNode(DataItem dataItem) {

String ballerinaType = getConstraintType(dataItem);
if (ballerinaType.equals(DECIMAL)) {
return generateNumberConstraint(dataItem);
} else if (ballerinaType.equals(INT)) {
return generateIntConstraint(dataItem);
} else {
return generateStringConstraint(dataItem);
}
return generateStringConstraint(dataItem);
}

private static String getConstraintType(DataItem dataItem) {

if (dataItem.isNumeric() && dataItem.getFloatingPointLength() > 0) {
return DECIMAL;
} else if (dataItem.isNumeric()) {
Expand All @@ -156,7 +145,6 @@ private static String getConstraintType(DataItem dataItem) {
}

public static String extractTypeReferenceName(DataItem dataItem) {

String typeName = null;
if (dataItem.isNumeric()) {
if (dataItem.getFloatingPointLength() > 0) {
Expand Down Expand Up @@ -193,7 +181,6 @@ public static String extractTypeReferenceName(DataItem dataItem) {
}

public static String getValidName(String identifier) {

if (!identifier.matches("\\b[0-9]*\\b")) {
String[] split = identifier.split(GeneratorConstants.SPECIAL_CHAR_REGEX);
StringBuilder validName = new StringBuilder();
Expand All @@ -208,7 +195,6 @@ public static String getValidName(String identifier) {
}

public static String escapeIdentifier(String identifier) {

if (identifier.matches("\\b[0-9]*\\b")) {
return "'" + identifier;
} else if (!identifier.matches("\\b[_a-zA-Z][_a-zA-Z0-9]*\\b")
Expand Down Expand Up @@ -238,7 +224,6 @@ public static String escapeIdentifier(String identifier) {
}

public static String getFileName(String filePath) {

String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
return String.join("", fileName, BAL_EXTENSION);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,11 @@ public class CopybookTypeGenerator {
private final List<TypeDefinitionNode> fieldTypeDefinitionList;

public CopybookTypeGenerator(Schema schema) {

this.schema = schema;
this.fieldTypeDefinitionList = new ArrayList<>();
}

public String generateSourceCode() throws FormatterException {

List<CopybookNode> typeDefinitions = schema.getTypeDefinitions();
List<TypeDefinitionNode> typeDefinitionList = new ArrayList<>();
typeDefinitions.forEach(typeDefinition -> typeDefinitionList.add(generateTypeDefNode(typeDefinition)));
Expand All @@ -78,7 +76,6 @@ public String generateSourceCode() throws FormatterException {
}

public List<io.ballerina.compiler.syntax.tree.Node> addRecordFields(List<CopybookNode> fields) {

List<io.ballerina.compiler.syntax.tree.Node> recordFieldList = new ArrayList<>();
for (CopybookNode fieldNode : fields) {
String fieldNameStr = CodeGeneratorUtils.escapeIdentifier(fieldNode.getName().trim());
Expand All @@ -92,7 +89,6 @@ public List<io.ballerina.compiler.syntax.tree.Node> addRecordFields(List<Copyboo
}

public TypeDefinitionNode generateTypeDefNode(CopybookNode node) {

IdentifierToken typeName = AbstractNodeFactory.createIdentifierToken(CodeGeneratorUtils.getValidName(
node.getName().trim()));
TypeDescriptorNode typeDescriptorNode = getTypeDescriptorNode(node);
Expand All @@ -117,7 +113,6 @@ private TypeDescriptorNode getTypeDescriptorNode(CopybookNode node) {
}

public SyntaxTree generateSyntaxTree() {

NodeList<ImportDeclarationNode> imports = createImportDeclarationNodes();
NodeList<ModuleMemberDeclarationNode> moduleMembers = AbstractNodeFactory.createNodeList(
fieldTypeDefinitionList.toArray(new TypeDefinitionNode[0]));
Expand All @@ -129,7 +124,6 @@ public SyntaxTree generateSyntaxTree() {
}

public static void addToFieldTypeDefinitionList(TypeDefinitionNode node, List<TypeDefinitionNode> typeDefList) {

boolean isExist = typeDefList.stream().anyMatch(typeDefinitionNode ->
typeDefinitionNode.typeName().toString().equals(node.typeName().toString()));
if (!isExist) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@

public class GeneratorConstants {

private GeneratorConstants() {
}

public static final String SPECIAL_CHAR_REGEX = "([\\[\\]\\\\?!<>@#&~`*\\=^+();:\\/\\_{}\\s|.$])";
public static final String ESCAPE_PATTERN = "([\\[\\]\\\\?!<>@#&~`*\\-=^+();:\\/\\_{}\\s|.$])";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,11 @@ public class RecordTypeGenerator extends TypeGenerator {
GroupItem groupItemNode;

public RecordTypeGenerator(GroupItem groupItemNode) {

this.groupItemNode = groupItemNode;
}

@Override public TypeDescriptorNode generateTypeDescriptorNode(List<TypeDefinitionNode> typeDefList) {

@Override
public TypeDescriptorNode generateTypeDescriptorNode(List<TypeDefinitionNode> typeDefList) {
List<Node> recordFields = new LinkedList<>();
RecordMetadata metadataBuilder = getRecordMetadata();
List<CopybookNode> fields = groupItemNode.getChildren();
Expand All @@ -63,7 +62,6 @@ public RecordTypeGenerator(GroupItem groupItemNode) {
}

public List<Node> addRecordFields(List<CopybookNode> fields, List<TypeDefinitionNode> typeDefList) {

List<Node> recordFieldList = new ArrayList<>();
for (CopybookNode field : fields) {
String fieldNameStr = CodeGeneratorUtils.escapeIdentifier(field.getName().trim());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ public class ReferencedTypeGenerator extends TypeGenerator {
DataItem fieldSchema;

public ReferencedTypeGenerator(DataItem fieldSchema) {

this.fieldSchema = fieldSchema;
}

Expand All @@ -44,7 +43,6 @@ public ReferencedTypeGenerator(DataItem fieldSchema) {
*/
@Override
public TypeDescriptorNode generateTypeDescriptorNode(List<TypeDefinitionNode> typeDefList) {

String extractName = getTypeReferenceName(fieldSchema, true);
String typeName = CodeGeneratorUtils.getValidName(extractName);
TypeDefinitionNode fieldType = generateFieldTypeDefNode(fieldSchema, getTypeReferenceName(fieldSchema, false));
Expand Down
Loading

0 comments on commit 1d32ea6

Please sign in to comment.