hw2 java

mail@pastecode.io avatar
unknown
java
16 days ago
10 kB
5
Indexable
Never
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class App {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("Please input mermaid file name");
        } else {
            // Get input
            String fileName = args[0];
            String mermaidCode = readMermaidCodeFromFile(fileName);
            List<String> classCodes = Parser.splitByClass(mermaidCode);
            for (String classCode : classCodes) {
                // Extract class name
                String className = extractClassName(classCode);
                if (className == null) {
                    System.err.println("Error: Class name not found in input");
                    continue;
                }
                // Write class code to file
                writeToFile(className + ".java", transformMermaidToJava(classCode));
            }
        }
    }
i
    private static String transformMermaidToJava(String classCode) {
        StringBuilder javaCode = new StringBuilder();
        // Split the class diagram code by lines
        String[] lines = classCode.split("\n");

        // Loop through each line to process each class
        for (String line : lines) {
            // Trim the line
            line = line.trim();
            // If the line starts with "class", it defines a new class
            if (line.startsWith("class ")) {
                // Extract the class name
                String className = line.substring(6).trim();
                List<String> attributes = new ArrayList<>();
                List<String> methods = new ArrayList<>();
                // Loop through the remaining lines to process attributes and methods of the class
                for (String nextLine : lines) {
                    // Skip if it's not related to the current class
                    if (!nextLine.startsWith(className)) {
                        continue;
                    }
                    // Trim the line
                    nextLine = nextLine.trim();
                    // If the line contains attribute or method definitions
                    if (nextLine.contains(":")) {
                        // Split the line by colon to separate attribute/method name and visibility
                        String[] parts = nextLine.split(":");
                        // Trim attribute/method name and visibility
                        String declaration = parts[1].trim();
                        String visibility = declaration.substring(0, 1);
                        // If it's an attribute
                        if (visibility.equals("-")) {
                            // Add the attribute to the list
                            methods.add(generatePrivateMethod(attributes.add(declaration)));
                        }
                        // If it's a method
                        else if (visibility.equals("+")) {
                            // Extract the return type and method name
                            int returnTypeEndIndex = declaration.lastIndexOf(" ");
                            String methodName = declaration.substring(1, returnTypeEndIndex).trim();
                            String returnType = "";
                            if (returnTypeEndIndex > 1) {
                                returnType = declaration.substring(1, returnTypeEndIndex).trim();
                            }
                            if (methodName.contains("(") && methodName.contains(")")) {
                                // Extract parameters
                                int parametersStartIndex = methodName.indexOf("(");
                                int parametersEndIndex = methodName.indexOf(")");
                                String parametersString = methodName.substring(parametersStartIndex + 1, parametersEndIndex);
                                String[] parameters = parametersString.split(",");
                                if (parameters.length > 1){
                                    // Generate method with multiple parameters
                                    methods.add(generateMethodWithParameters(returnType, methodName, parameters, declaration));
                                } 
                            }
                            // Add the method to the list with correct method signature and body
                            if (methodName.startsWith("get")) {
                                methods.add(generateGetterMethodSignature(returnType, methodName, declaration));
                            } else if (methodName.startsWith("set")) {
                                methods.add(generateSetterMethodSignature(returnType, methodName,declaration));
                            } else {
                                methods.add(generateMethodSignature(returnType, methodName, declaration));
                            }
                        }
                    }
                }
                // Generate Java code for the current class
                javaCode.append("public class ").append(className).append(" {\n");
                // Generate method declarations
                for (String method : methods) {
                    javaCode.append("    ").append(method).append("\n");
                }
                javaCode.append("}");
            }
        }
        return javaCode.toString();
    }

    private static String generatePrivateMethod(String attribute) {
        return "private " + attribute.substring(1) + ";\n";
    }
    

    private static String generateGetterMethodSignature(String returnType, String methodName, String declaration) {
        StringBuilder methodSignature = new StringBuilder();
        // Extract method return type
        returnType = extractReturnType(declaration);
        methodSignature.append("public ").append(returnType).append(" ").append(methodName).append(" {\n");
        methodSignature.append("        return ").append(methodName.substring(3,methodName.indexOf("(")).toLowerCase()).append(";\n");
        methodSignature.append("    }");
        return methodSignature.toString();
    }
    
    private static String generateSetterMethodSignature(String returnType, String methodName, String declaration) {
        StringBuilder methodSignature = new StringBuilder();
        // Extract method parameter type
        returnType = extractReturnType(declaration);
        String parameter = methodName.substring(3, methodName.indexOf("(")).toLowerCase();
        // Append method signature with parameter
        methodSignature.append("public ").append(returnType).append(" ").append(methodName).append(" {\n");
        methodSignature.append("        this.").append(parameter).append(" = ").append(parameter).append(";\n");
        methodSignature.append("    }");
        return methodSignature.toString();
    }
    
    private static String generateMethodSignature(String returnType, String methodName, String declaration) {
        StringBuilder methodSignature = new StringBuilder();
        // Extract method return type
        returnType = extractReturnType(declaration);
        methodSignature.append("public ").append(returnType).append(" ").append(methodName);
        methodSignature.append(" {");
        if (returnType.equals("boolean")) {
            methodSignature.append("return false;");
        } else if (returnType.equals("void")) {
            methodSignature.append(";");
        } else {
            methodSignature.append("return 0;");
        }
        methodSignature.append("}");
        return methodSignature.toString();
    }    

    private static String generateMethodWithParameters(String returnType, String methodName, String[] parameters, String declaration) {
        StringBuilder methodSignature = new StringBuilder();
        // Extract method return type
        returnType = extractReturnType(declaration);
        methodSignature.append("public ").append(returnType).append(" ").append(methodName);
        methodSignature.append(" {");
        if (returnType.equals("boolean")) {
            methodSignature.append("return false;");
        } else {
            methodSignature.append("return 0;");
        }
        methodSignature.append("}");
        return methodSignature.toString();
    }

    // Helper method to extract the return type from method declaration
    private static String extractReturnType(String declaration) {
        String[] parts = declaration.split(" ");
        return parts[parts.length - 1]; // The last word represents the return type
    }
    
    
    private static String readMermaidCodeFromFile(String fileName) {
        StringBuilder mermaidCode = new StringBuilder();

        try (FileReader fileReader = new FileReader(fileName)) {
            char[] buffer = new char[1024];
            int length;
            while ((length = fileReader.read(buffer)) > 0) {
                mermaidCode.append(buffer, 0, length);
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }

        return mermaidCode.toString();
    }

    private static String extractClassName(String classCode) {
        int startIndex = classCode.indexOf("class ");
        if (startIndex == -1) {
            return null;
        }
        startIndex += 6; // Skip "class " substring
        int endIndex = classCode.indexOf("\n", startIndex);
        if (endIndex == -1) {
            return null;
        }
        return classCode.substring(startIndex, endIndex).trim();
    }

    private static void writeToFile(String fileName, String classCode) {
        try (FileWriter fileWriter = new FileWriter(fileName)) {
            fileWriter.write(classCode);
        } catch (IOException e) {
            System.err.println("Error writing file: " + e.getMessage());
        }
    }
}
public class Parser {
    public static List<String> splitByClass(String input) {
        List<String> classCodes = new ArrayList<>();
        
        String[] classes = input.split("class ");
       
        for (String cls : classes) {
            if (!cls.trim().isEmpty()) {
         
                cls = "class " + cls;
                classCodes.add(cls);
            }
        }
        
        return classCodes;
    }
}
Leave a Comment