adding base project

This commit is contained in:
Azmat-7860
2026-10-22 16:06:48 +05:30
commit 147d52120c
718 changed files with 38983 additions and 0 deletions
@@ -0,0 +1,537 @@
//package com.realnet.codeextractor.controller;
//
//import java.io.BufferedWriter;
//import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.FileWriter;
//import java.io.IOException;
//import java.nio.charset.StandardCharsets;
//import java.util.List;
//
//import org.apache.commons.io.FileUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//import com.realnet.codeextractor.entity.Rn_Bcf_Extractor;
//import com.realnet.codeextractor.entity.Rn_Bcf_Extractor_Params;
//import com.realnet.codeextractor.service.Rn_Bcf_Exception_Rule_Library_Service;
//import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Params_Service;
//import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Service;
//import com.realnet.codeextractor.service.Rn_Bcf_Rule_Library_Service;
//import com.realnet.flf.service.FieldTypeService;
//import com.realnet.fnd.entity.Error;
//import com.realnet.fnd.entity.ErrorPojo;
//import com.realnet.fnd.entity.Success;
//import com.realnet.fnd.entity.SuccessPojo;
//import com.realnet.fnd.service.Rn_ModuleSetup_Service;
//import com.realnet.utils.Constant;
//
//import io.swagger.annotations.Api;
//
//@RestController
//@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
//@Api(tags = { "Build Master Builder" })
//public class BuildMasterBuilderController {
//
// @Value("${projectPath}")
// private String projectPath;
//
// @Value("${angularProjectPath}")
// private String angularProjectPath;
//
// @Autowired
// private Rn_ModuleSetup_Service rn_module_setup_service;
//
// @Autowired
// private Rn_Bcf_Extractor_Service rn_bcf_extractor_service;
//
// @Autowired
// private Rn_Bcf_Extractor_Params_Service rn_bcf_extractor_params_service;
//
// @Autowired
// private Rn_Bcf_Rule_Library_Service rn_bcf_rule_library_service;
//
// @Autowired
// private Rn_Bcf_Exception_Rule_Library_Service rn_bcf_rule_exception_library_service;
//
// @Autowired
// private FieldTypeService fieldTypeService;
// //private static final Logger logger = Logger.getLogger(BuildMasterBuilderController.class);
//
// @GetMapping("/build_master_builder")
// public ResponseEntity<?> masterControllerBuilder(@RequestParam(value = "id") Integer id) throws IOException, FileNotFoundException {
// StringBuilder variablesDynamicCode = new StringBuilder();
// StringBuilder stringBuilderDynamicCode = new StringBuilder();
// StringBuilder moduleCode = new StringBuilder();
//
//
// // RN_BCF_CODE_EXTRACTOR_T ID
// //int eid = Integer.parseInt(id);
//
// Rn_Bcf_Extractor extractor = rn_bcf_extractor_service.getById(id);
// String technology_stack = extractor.getTech_stack();
// String object_type = extractor.getObject_type();
// String sub_object_type = extractor.getSub_object_type();
//
// // RN_BCF_CODE_EXTRACTOR_PARAMS_T VALUES
// //List<Rn_Bcf_Extractor_Params> params = rn_bcf_extractor_params_service.getByHeaderId(eid);
// List<Rn_Bcf_Extractor_Params> params = extractor.getRn_bcf_extractor_Params();
//
// // PARAMETERS TABLE VALUE
// int i = 0;
// int j=0;
// for (Rn_Bcf_Extractor_Params param : params)
// {
// boolean is_creation_enabled = param.isIs_creation_enabled();
// boolean is_extraction_enabled = param.isIs_extraction_enabled();
// String path = param.getMoved_address_string();
// File file = new File(path);
// String parentPath = file.getParent();
//
// String name = file.getName();
// String convertedFileName = "SE_" + name;
//
// // STATIC CODE DIRECTORY
// String staticFileParentDir = parentPath + File.separator + "static_code";
// File staticFile = new File(staticFileParentDir + File.separator + convertedFileName);
// String fileToString = FileUtils.readFileToString(staticFile, StandardCharsets.UTF_8);
//
// // ex. controller_file (FROM PARAMS TABLE)
// String file_name_var = param.getFile_name_var();
//
// // ex. ui_name + "controller"
// String file_name_dynamic_string = param.getFile_name_dynamic_string();
//
// // ex. String controller_file = ui_name + "controller";
// variablesDynamicCode.append("String " + file_name_var + " = " + file_name_dynamic_string + ";\r\n");
//
// System.out.println("file name dynamic str "+file_name_dynamic_string);
// //change file name entity
//// String mainstr1=file_name_dynamic_string;
//// String saleesent1=mainstr1.replace(".java", " ");
//// System.out.println("updated filename"+saleesent1);
//// System.out.println(file_name_dynamic_string.contains(".java"));
//// System.out.println(file_name_dynamic_string.contains(".ts"));
//// System.out.println(file_name_dynamic_string.contains(".scss"));
//// System.out.println(file_name_dynamic_string.contains(".html"));
//
// if(file_name_dynamic_string.contains(".java")) {
// variablesDynamicCode.append("String mainstr"+j+" = " + file_name_var + ";\r\n"+
// "String "+file_name_var+""+1+"=mainstr"+j+".replace(\".java\", \"\");\r\n"+
// "" + "\r\n"+"\n" );
// }else if(file_name_dynamic_string.contains(".ts")) {
// variablesDynamicCode.append("String mainstr"+j+" = " + file_name_var + ";\r\n"+
// "String "+file_name_var+""+1+"=mainstr"+j+".replace(\".ts\", \"\");\r\n"+
// "" + "\r\n"+
// "String "+file_name_var+""+2+"=mainstr"+j+".replace(\".component.ts\", \"\");\r\n"+
// "" + "\r\n"+"\n"
// );
//
// }else if(file_name_dynamic_string.contains(".html")) {
// variablesDynamicCode.append("String mainstr"+j+" = " + file_name_var + ";\r\n"+
// "String "+file_name_var+""+1+"=mainstr"+j+".replace(\".html\", \"\");\r\n"+
// "" + "\r\n"+"\n" );
// }else if(file_name_dynamic_string.contains(".scss")) {
// variablesDynamicCode.append("String mainstr"+j+" = " + file_name_var + ";\r\n"+
// "String "+file_name_var+""+1+"=mainstr"+j+".replace(\".scss\", \"\");\r\n"+
// "" + "\r\n"+"\n" );
// }else {System.out.println("not found");}
//
//
//
// // ======= MODULE NAME SHOULD COME FROM THE SESSION ========
// //String moduleName = "\" + module_name + \"/\"";
// String moduleName = "\" + module_name + \"/";
//
// String modulePath = param.getTotal_project_path_dynamic_string();
// //System.out.println("MODULE PATH = " + modulePath);
// if(modulePath.endsWith(".java")) {
// String parent = modulePath.substring(0, modulePath.lastIndexOf("/")); // 1
// String lvl2Parent = parent.substring(0, parent.lastIndexOf("/")+1); // 2
// String tail0 = modulePath.substring(parent.lastIndexOf("/") +1); // 3
// tail0 = tail0.substring(0, tail0.lastIndexOf("/")+1); // remove the .java file name
// modulePath = lvl2Parent + moduleName + tail0;
// } else {
// // add module name in spring project
// modulePath = modulePath.substring(0, modulePath.lastIndexOf("/")+1);
// String data0 = modulePath.substring(0, modulePath.lastIndexOf("/") + 1);
// String tail0 = modulePath.substring(modulePath.lastIndexOf("/") + 1);
// data0 += moduleName + tail0;
// modulePath = data0;
// }
//// System.out.println("MANUPULATED module PATH = " + modulePath);
//
//// String ref_address_string = param.getReference_address_string();
//// ref_address_string = ref_address_string.substring(0, ref_address_string.lastIndexOf("/")+1);
//
// String total_address_path = param.getTotal_project_path_dynamic_string();
// total_address_path = total_address_path.substring(0, total_address_path.lastIndexOf("/")+1);
// System.out.println("total path : "+total_address_path +"\n");
// String module_dest_path = "";
// String finalDir = "";
//
//
//// module_dest_path = "angularProjectPath + \"" + modulePath;
//// // CREATE MODULE FOLDER STRUCTURE [DYNAMIC PATH]
//// moduleCode.append("File file" + (++i) + " = new File(" + module_dest_path +"\");\n"
//// + "if(!file" + (i) +".exists()) {\n"
//// + " file" + (i) + ".mkdirs();\n"
//// + "}\n");
//
// /*
// * MAKE {{test1}} dynamic
// * INPUT : /frontend/src/app/admin/test1/details/rn_header_test1-details.component.html
// * OUTPUT : /frontend/src/app/admin/{{test1}}/details/
// *
// * */
// // DYNAMIC FOLDER NAME LOGIC FOR ANGULAR
// // start
//// final String ng_prj_struct = "/frontend/src/app/admin/";
//// if (ref_address_string.contains(ng_prj_struct)) {
//// int len = ng_prj_struct.length();
//// String data = ref_address_string.substring(0,len) + "\" + ng_folder_name + \"";
//// int tail = ref_address_string.indexOf("/", len + 1);
//// String temp = ref_address_string.substring(tail);
//// data += temp;
//// ref_address_string = data;
//// }
////
// // end
// String dest_path = "projectPath + \"" + "/Projects/\" + project_name + \"" + total_address_path;
// System.out.println("dest path : "+dest_path);
// // String finalDir = dirString + "/" + "\" + " + file_name_var;
// finalDir = dest_path + "\" + " + file_name_var;
// System.out.println(finalDir);
//
//
// //module_dest_path = "projectPath + \"" + "/Projects/\" + project_name + " + modulePath;
//// String dest_path = "projectPath + \"" + "/Projects/\" + project_name + \"" + modulePath;
//
//
// // String finalDir = dirString + "/" + "\" + " + file_name_var;
// finalDir = dest_path + "\" + " + file_name_var;
// System.out.println("NIL FINAL DIR = " + finalDir+"\n");
//
// if(is_creation_enabled) {
// StringBuilder fileCode = new StringBuilder();
// // EMPTY FILE CODE WILL NOT GO IN THIS LOOP
// if(fileToString.isEmpty()) {
// fileCode.append(" " + file_name_var + "Code.append(\"" + fileToString + "\");\r\n");
// } else {
// fileCode.append(" " + file_name_var + "Code.append(" + fileToString + ");\r\n");
// }
// stringBuilderDynamicCode.append(" StringBuilder " + file_name_var + "Code = new StringBuilder();\r\n"
// //+ " " + file_name_var + "Code.append(" + fileToString + ");\r\n"
// + fileCode
// + "\r\n"
// + " File " + file_name_var + "File = new File(" + finalDir + ");\r\n"
// + " System.out.println(\"Directory name = \" + " + file_name_var + "File);\r\n"
// //== CREATE PARENT DIR IF NOT EXIST===
// + " File " + file_name_var + "FileParentDir = new File(" + file_name_var + "File.getParent());\r\n"
// + " if(!" + file_name_var +"FileParentDir.exists()) {\r\n"
// + " " + file_name_var + "FileParentDir.mkdirs();\r\n"
// + " }\r\n"
// //==
// + " if (!" + file_name_var + "File.exists()) {\r\n"
// + " " + file_name_var + "File.createNewFile();\r\n"
// + " }\r\n"
// + " fw = new FileWriter(" + file_name_var + "File.getAbsoluteFile());\r\n"
// + " bw = new BufferedWriter(fw);\r\n"
// + " bw.write(" + file_name_var + "Code.toString());\r\n"
// + " bw.close();\r\n"
// + "\r\n");
//
// }
// j++;
// }
//
//
//
// // CHILD MASTER BUILDER NAME DEPENDS ON (TECH_STACK, OBJ_TYPE, SUB_OBJ_TYPE)
// String childMasterBuilderName = technology_stack + "_" + object_type + "_" + sub_object_type + "_Builder";
// childMasterBuilderName = childMasterBuilderName.replace(" ", "_");
// childMasterBuilderName = childMasterBuilderName.replaceAll("[-]+", "_");
//
// StringBuilder childMasterBuilderCode = new StringBuilder();
// childMasterBuilderCode.append(
// "package com.realnet.builders;\r\n"
// + "\r\n"
// + "import java.io.BufferedReader;\r\n"
// + "import java.io.BufferedWriter;\r\n"
// + "import java.io.File;\r\n"
// + "import java.io.FileNotFoundException;\r\n"
// + "import java.io.FileReader;\r\n"
// + "import java.io.FileWriter;\r\n"
// + "import java.io.IOException;\r\n"
// + "import java.util.List;\r\n"
// + "import java.util.stream.Collectors;\r\n"
// + "\r\n"
// + "import org.modelmapper.ModelMapper;\r\n"
// + "import org.springframework.beans.factory.annotation.Autowired;\r\n"
// + "import org.springframework.beans.factory.annotation.Value;\r\n"
// + "import org.springframework.http.HttpStatus;\r\n"
// + "import org.springframework.http.MediaType;\r\n"
// + "import org.springframework.http.ResponseEntity;\r\n"
// + "import org.springframework.web.bind.annotation.GetMapping;\r\n"
// + "import org.springframework.web.bind.annotation.RequestMapping;\r\n"
// + "import org.springframework.web.bind.annotation.RequestParam;\r\n"
// + "import org.springframework.web.bind.annotation.RestController;\r\n"
// + "\r\n"
// + "import com.realnet.actionbuilder.entity.Rn_cff_ActionBuilder_Header;\r\n"
// + "import com.realnet.actionbuilder.entity.Rn_cff_ActionBuilder_Header;\r\n"
// + "import com.realnet.actionbuilder.service.Rn_Cff_ActionBuilder_Service;\r\n"
// + "import com.realnet.flf.service.FieldTypeService;\r\n"
// + "import com.realnet.fnd.entity.Error;\r\n"
// + "import com.realnet.fnd.entity.ErrorPojo;\r\n"
// + "import com.realnet.fnd.entity.Rn_Lookup_Values;\r\n"
// + "import com.realnet.fnd.entity.Rn_Module_Setup;\r\n"
// + "import com.realnet.fnd.entity.Rn_Project_Setup;\r\n"
// + "import com.realnet.fnd.entity.Success;\r\n"
// + "import com.realnet.fnd.entity.SuccessPojo;\r\n"
// + "import com.realnet.fnd.service.Rn_LookUp_Service;\r\n"
// + "import com.realnet.utils.Constant;\r\n"
// + "import com.realnet.utils.RealNetUtils;\r\n"
// + "import com.realnet.wfb.entity.Rn_Fb_Header;\r\n"
// + "import com.realnet.wfb.entity.Rn_Fb_Line;\r\n"
// + "import com.realnet.wfb.entity.Rn_Fb_Line_DTO;\r\n"
// + "import com.realnet.wfb.service.Rn_WireFrame_Service;\r\n"
// + "\r\n"
// + "import io.swagger.annotations.Api;\r\n"
// + "\r\n"
// + "@RestController\r\n"
// // CONTROLLER NAME SHOULD CHANGE
// // DEPENDS ON TECH_STACK/OBJECT_tYPE/SUB_OBJECT_TYPE
// + "@RequestMapping(value = \"/api\", produces = MediaType.APPLICATION_JSON_VALUE)\r\n"
// + "@Api(tags = { \"Master Builder\" })\r\n"
// + "public class " + childMasterBuilderName + " {\r\n" + "\r\n" + "\r\n"
// + " @Value(\"${angularProjectPath}\")\r\n"
// + " private String angularProjectPath;"
// + " @Value(\"${projectPath}\")\r\n"
// + " private String projectPath;"
//
// // DEPENDENCIES FOR WIREFRAME
// + " @Autowired\r\n"
// + " private Rn_WireFrame_Service wireFrameService;\r\n" +
// "\r\n" +
// " @Autowired\r\n"
// + " private Rn_LookUp_Service lookUpService;\r\n"
// + "\r\n"
// + " @Autowired\r\n"
// + " private Rn_Cff_ActionBuilder_Service actionBuilderService;\r\n"
// + "\r\n"
// + " @Autowired\r\n"
// + " private ModelMapper modelMapper;\r\n"
// + "\r\n"
// + " @Autowired\r\n"
// + " private FieldTypeService fieldTypeService;\r\n"
//
// + " @GetMapping(value = \"/" + childMasterBuilderName + "\")\r\n"
// + " public ResponseEntity<?> build_wireframe(@RequestParam(\"header_id\") Integer id) throws IOException {\r\n" + "\r\n"
// + " System.out.println(\"id ::\"+id);"
// + "\n lookUpService.createTable(id);"
// + " \n // extra button \n List<Rn_Fb_Line> extraButton = wireFrameService.getExtraButton(id);"
// + " \n // HEADER VALUE\r\n"
// + " Rn_Fb_Header rn_fb_header = wireFrameService.getById(id);\r\n"
// + " \r\n"
// + " // LINE VALUES\r\n"
// + " List<Rn_Fb_Line> rn_fb_lines = rn_fb_header.getRn_fb_lines();\r\n"
// + " \r\n"
// + " // MODULE DETAILS\r\n"
// + " Rn_Module_Setup module = rn_fb_header.getModule();\r\n"
// + " \r\n"
// + " // PROJECT DETAILS\r\n"
// + " Rn_Project_Setup project = module.getProject();\r\n"
// + " \r\n"
// // ATTRIBUTE FLEX
// + " // ATTRIBUTE FLEX VALUES\r\n"
// + " List<Rn_Lookup_Values> attribute_flex_values = lookUpService.getExtensions();\r\n"
// + " String project_name = project.getProjectName();\r\n"
// + " String module_name = module.getModuleName();"
//
// // header table values
// + " /*\r\n"
// + " * Header Table Values\r\n"
// + " * @GET UI_NAME\r\n"
// + " * @SET controller, model, repository, service name.\r\n"
// + " */\r\n"
// + " String technology_stack = rn_fb_header.getTechStack();\r\n"
// + " String ui_name = RealNetUtils.toFirstUpperCase(rn_fb_header.getUiName());\r\n"
// + " String form_code = rn_fb_header.getFormCode(); // value will come from db\r\n"
//
// + " String controller_name = ui_name.concat(\"_Controller\");\r\n"
// + " String dao_name = ui_name.concat(\"_Dao\");\r\n"
// + " String dao_name_lower = dao_name.toLowerCase();"
// + " String dao_impl_name = ui_name.concat(\"_DaoImpl\");\r\n"
// + " String repository_name = ui_name.concat(\"_Repository\");\r\n"
// + " String service_name = ui_name.concat(\"_Service\");\r\n"
// + " String service_impl_name = ui_name.concat(\"_ServiceImpl\");\r\n" + "\r\n"
// + " String table_name = ui_name.concat(\"_t\"); // For @Column(table=\"table_name\") && Model class name\r\n"
// + "\r\n"
// //+ " String line_table_name = ui_name.concat(\"_line_t\");\r\n" + "\r\n"
// + " /*----First Upper names (back-end)----------*/\r\n"
// + " String controller_name_first_upper = RealNetUtils.toFirstUpperCase(controller_name);\r\n"
// + " String repository_name_first_upper = RealNetUtils.toFirstUpperCase(repository_name);\r\n"
// + " String dao_name_first_upper = RealNetUtils.toFirstUpperCase(dao_name);\r\n"
// + " String dao_impl_name_first_upper = RealNetUtils.toFirstUpperCase(dao_impl_name);\r\n"
// + " String service_name_first_upper = RealNetUtils.toFirstUpperCase(service_name);\r\n"
// + " String service_impl_name_first_upper = RealNetUtils.toFirstUpperCase(service_impl_name);\r\n"
// + " String table_name_first_upper = RealNetUtils.toFirstUpperCase(table_name);\r\n"
// + " String table_name_upper = table_name.toUpperCase(); // For Model class\r\n" + "\r\n"
// //+ " String line_table_name_first_upper = RealNetUtils.toFirstUpperCase(line_table_name);\r\n"
// + " /*-------------lower names (back-end)----------*/\r\n"
// + " String table_name_lower = table_name.toLowerCase();\r\n"
// + " String repository_name_lower = repository_name.toLowerCase();\r\n"
// + " String service_name_lower = service_name.toLowerCase();\r\n"
// + "\r\n"
//
// //DTO APPROACH FOR CALLING A SERVICE
// + " List<Rn_Fb_Line_DTO> lineListDto = rn_fb_lines.stream().map(line -> modelMapper.map(line, Rn_Fb_Line_DTO.class))\r\n"
// + " .collect(Collectors.toList());\r\n"
// + " \r\n"
// + " // set table name in the dto class\r\n"
// + " for(Rn_Fb_Line_DTO dto : lineListDto) {\r\n"
// + " dto.setTable_name(table_name_lower);\r\n"
// + " }\r\n"
//
// // ======= NEED TO IMPLEMENT LOGIC FOR DIFFERENT TECHNOLOGY TYPE ====
// ); //
//
//
// // =========== FRONT-END OBJECT NAMES ==============
// childMasterBuilderCode.append("// ===========FRONT END FILE NAMES DEPENDS ON UI NAME===============\r\n"
// + " String ng_ui_name = RealNetUtils.toFirstUpperCase(ui_name);\r\n"
// + " String ng_model_ts_name = ng_ui_name.concat(\"_t\");\r\n"
// + " String ng_component_ts_name = ng_ui_name.concat(\"Component\");\r\n"
// + " String ng_module_ts_name = ng_ui_name.concat(\"Module\");\r\n"
// + " String ng_service_ts_name = ng_ui_name.concat(\"Service\");\r\n"
// + " String ng_routing_module_ts_name = ng_ui_name.concat(\"RoutingModule\");\r\n" + "\r\n"
// + " String ng_service_ts_name_lower = ui_name.toLowerCase().concat(\"Service\");\r\n"
// + " String ng_model_ts_name_lower = ng_model_ts_name.toLowerCase();\r\n"
// + " // Routing Path names\r\n"
// + " String ng_path_name = ui_name.toLowerCase();\r\n"
// + " // CRUD Components name\r\n"
// + " String ng_all_grid_view_component_name = \"All\" + ng_ui_name.concat(\"Component\");\r\n"
// + " String ng_add_form_component_name = \"Add\" + ng_ui_name.concat(\"Component\");\r\n"
// + " String ng_edit_component_name = \"Edit\" + ng_ui_name.concat(\"Component\");\r\n"
// + " String ng_read_only_component_name = ng_ui_name + \"DetailsComponent\";\r\n"
// + " // Extension Components name\r\n"
// + " String ng_extension_add_component_name = \"AddExt\" + ng_ui_name.concat(\"Component\");\r\n"
// + " // File Folder name\r\n"
// + " String ng_folder_name = ui_name.toLowerCase();\r\n"
// + " String ng_file_name = ui_name.toLowerCase();\r\n"
// + "\r\n");
//
// String action_builder_code = fieldTypeService.angular_action_builder_code();
//
// // DYNAMIC VARIABLE FOR FILE-NAME DEPENDS ON UI NAME
// childMasterBuilderCode.append(
// variablesDynamicCode // this is the file name with extension(from params table)
// + "\r\n"
// // MASTER CONTROLLER CODE START
// + " FileWriter fw = null;\r\n"
// + " BufferedWriter bw = null;\r\n"
// + " try { \r\n"
// // ACTION BUILDER CODE
// + action_builder_code
// + // =========== VARIABLE CODE WILL BE APPEND HERE ===============//
// stringBuilderDynamicCode
// + "\r\n");
//
// // UPDATE MENU
// // String angular_update_sidenav = "";
// childMasterBuilderCode.append(moduleCode +"\r\n" +
// // 22:30 UPDATE SIDE BAR START
// "/*-----------------------UPDATE ADMIN ROUTING TS FILE --------------------*/\r\n"
// + " // String frontEndDir = angularProjectPath.concat(\"/frontend/\");\n"
// + " File adminRoutingModule = new File(projectPath+\"/Projects/\"+project_name+ \"/webui/src/app/app-routing.module.ts\");\r\n"
// + " File tempRoutingModule = new File(projectPath+\"/Projects/\"+project_name+\"/webui/src/app/temp-routing.module.ts\");\r\n"
// + "\r\n" +
// " BufferedReader reader = new BufferedReader(new FileReader(adminRoutingModule));\r\n" +
// " BufferedWriter writer = new BufferedWriter(new FileWriter(tempRoutingModule));\r\n" +
// " String removeStr = \"]}];@NgModule({imports: [RouterModule.forChild(routes)],exports: [RouterModule]})export class AdminRoutingModule{}\";\r\n" +
// " String currentLine;\r\n" +
// " System.out.println(adminRoutingModule.getName());\r\n" +
// " while ((currentLine = reader.readLine()) != null) {\r\n" +
// " String trimmedLine = currentLine.trim();\r\n" +
// " if (trimmedLine.equals(removeStr)) {\r\n" +
// " currentLine = \"\";\r\n" +
// " }\r\n" +
// " writer.write(currentLine + System.getProperty(\"line.separator\"));\r\n" +
// "\r\n" +
// " }\r\n" +
// " writer.close();\r\n" +
// " reader.close();\r\n" +
// " boolean delete = adminRoutingModule.delete();\r\n" +
// " boolean b22 = tempRoutingModule.renameTo(adminRoutingModule);\r\n" +
// "\r\n" +
// " StringBuilder admin_routing_module_string = new StringBuilder();\r\n" +
// " admin_routing_module_string.append(\" \");\r\n" +
// " String adminRoutingModuleName = projectPath+\"/Projects/\"+project_name+ \"/webui/src/app/app-routing.module.ts\";\r\n" +
// "\r\n" +
// " fw = new FileWriter(adminRoutingModuleName, true);\r\n" +
// " fw.write(admin_routing_module_string.toString());\r\n" +
// " fw.close();\r\n" +
// "\r\n"
//
// );
//
// // MODULE CREATE CODE
// childMasterBuilderCode.append(" } catch (FileNotFoundException e) {\r\n"
// + " e.printStackTrace();\r\n"
// + " ErrorPojo errorPojo = new ErrorPojo();\r\n"
// + " Error error = new Error();\r\n"
// + " error.setTitle(Constant.FORM_BUILDER_API_TITLE);\r\n"
// + " error.setMessage(Constant.FORM_BUILD_FAILURE);\r\n"
// + " errorPojo.setError(error);\r\n"
// + " return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);\r\n"
// + " }\r\n"
// + " SuccessPojo successPojo = new SuccessPojo();\r\n"
// + " Success success = new Success();\r\n"
// + " success.setTitle(Constant.FORM_BUILDER_API_TITLE);\r\n"
// + " success.setMessage(Constant.FORM_BUILD_SUCCESS);\r\n"
// + " successPojo.setSuccess(success);\r\n"
// + " return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);\r\n"
// + "\r\n"
// +"\n}"
// +"}");
//
// // System.out.println(masterBuilderCode.toString());
//
// FileWriter fw = null;
// BufferedWriter bw = null;
// try {
// // FILE NAME SHOULD CHANGE DEPENDS ON TECH_STACK/OBJECT_tYPE/SUB_OBJECT_TYPE
// File masterBuilderFile = new File(
// projectPath + "/src/main/java/com/realnet/builders/" + childMasterBuilderName + ".java");
// if (!masterBuilderFile.exists()) {
// masterBuilderFile.createNewFile();
// }
// fw = new FileWriter(masterBuilderFile.getAbsoluteFile());
// bw = new BufferedWriter(fw);
// bw.write(childMasterBuilderCode.toString());
// bw.close();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// ErrorPojo errorPojo = new ErrorPojo();
// Error error = new Error();
// error.setTitle(Constant.MASTER_BUILDER_API_TITLE);
// error.setMessage(Constant.MASTER_BUILDER_FAILURE);
// errorPojo.setError(error);
// return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
// }
//
// SuccessPojo successPojo = new SuccessPojo();
// Success success = new Success();
// success.setTitle(Constant.MASTER_BUILDER_API_TITLE);
// success.setMessage(Constant.MASTER_BUILDER_SUCCESS);
// successPojo.setSuccess(success);
// return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
// }
//}
@@ -0,0 +1,778 @@
package com.realnet.codeextractor.controller;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.realnet.codeextractor.entity.FileDetails;
import com.realnet.codeextractor.entity.FileListDto;
import com.realnet.codeextractor.entity.Rn_Bcf_Extractor;
import com.realnet.codeextractor.entity.Rn_Bcf_Extractor_Params;
import com.realnet.codeextractor.response.CodeExtractorParamsResponse;
import com.realnet.codeextractor.response.CodeExtractorResponse;
import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Params_Service;
import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Service;
import com.realnet.fnd.entity.Error;
import com.realnet.fnd.entity.ErrorPojo;
import com.realnet.fnd.entity.Success;
import com.realnet.fnd.entity.SuccessPojo;
import com.realnet.fnd.service.FileStorageService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.utils.Constant;
import com.realnet.utils.RealNetUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
@Slf4j
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = { "Code Extractor" })
public class CodeExtractorController {
@Autowired
private AppUserServiceImpl userService;
@Autowired
private FileStorageService fileStorageService;
@Autowired
private Rn_Bcf_Extractor_Service extractorService;
@Autowired
private Rn_Bcf_Extractor_Params_Service extractorParamsService;
@Value("${projectPath}")
private String projectPath;
// GET ALL SORTED AND PAGINATED DATA
@ApiOperation(value = "List of of Bcf Extractor", response = Rn_Bcf_Extractor.class)
@GetMapping("/bcf-extractor")
public CodeExtractorResponse getExtractors(
@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
@RequestParam(value = "size", defaultValue = "20", required = false) Integer size) {
// sorted data
Pageable paging = PageRequest.of(page, size, Sort.by("createdAt").descending());
Page<Rn_Bcf_Extractor> result = extractorService.getAll(paging);
CodeExtractorResponse resp = new CodeExtractorResponse();
resp.setPageStats(result, true);
resp.setItems(result.getContent());
// //Map<String, List<Rn_Bcf_Extractor>> extractorMap = Collections.singletonMap("extractior", result.getContent());
// return new ResponseEntity<Map<String, List<Rn_Bcf_Extractor>>>(extractorMap, HttpStatus.OK);
return resp;
}
// // GET ALL
// @ApiOperation(value = "List of Bcf Extractor")
// @GetMapping("/bcf-extractor")
// public ResponseEntity<?> getExtractors() {
// List<Rn_Bcf_Extractor> result = extractorService.getAll();
// Map<String, List<Rn_Bcf_Extractor>> extractorMap = Collections.singletonMap("extractior", result);
// System.out.println(extractorMap);
// return ResponseEntity.ok().body(result);
// }
// GET BY ID
@ApiOperation(value = "Get an Bcf Extractor", response = Rn_Bcf_Extractor.class)
@GetMapping("/bcf-extractor/{id}")
public ResponseEntity<?> getExtractorById(@PathVariable(value = "id") int id) {
Rn_Bcf_Extractor bcf_extractor = extractorService.getById(id);
// Map<String, Rn_Bcf_Extractor> extractorMap =
// Collections.singletonMap("extractior", bcf_extractor);
// return new ResponseEntity<Map<String, Rn_Bcf_Extractor>>(extractorMap,
// HttpStatus.OK);
// return ResponseEntity.ok().body(bcf_extractor);
return new ResponseEntity<Rn_Bcf_Extractor>(bcf_extractor, HttpStatus.OK);
}
// ========= SAVE AND UNZIP FILE AND MOVE TO A SPECIFIC PATH ========
@ApiOperation(value = "Add new Bcf Extractor")
@PostMapping(value = "/bcf-extractor")
public ResponseEntity<?> saveExtractor(// @Valid @RequestBody Rn_Bcf_Extractor bcf_extractor,
@RequestParam(value = "bcf_extractor", required = true) String extractorReq,
@RequestParam(value = "file", required = true) MultipartFile file)
throws IOException, JsonParseException, JsonMappingException {
System.out.println("extractorReq = " + extractorReq);
System.out.println("file = " + file.getOriginalFilename());
log.debug("extractorReq => {} ", extractorReq);
log.debug("file => {} ", file.getOriginalFilename());
ObjectMapper mapper = new ObjectMapper();
Rn_Bcf_Extractor bcf_extractor = mapper.readValue(extractorReq, Rn_Bcf_Extractor.class);
log.debug("bcf_extractor => {}", bcf_extractor);
AppUser loggedInUser = userService.getLoggedInUser();
bcf_extractor.setAccountId(loggedInUser.getAccount().getAccount_id());
bcf_extractor.setCreatedBy(loggedInUser.getUserId());
String techStackKey = RealNetUtils.getTechnologyStackKey(bcf_extractor.getTech_stack());
System.out.println("TECHNOLOGY STACK KEY = " + techStackKey);
bcf_extractor.setTech_stack_key(techStackKey);
// upload to directory
String uploadPath = projectPath.concat("/src/main/resources/zip-uploads/");
fileStorageService.uploadFile(file, uploadPath);
String fileName = file.getOriginalFilename();
System.out.println(
"UPLOAD PATH = " + uploadPath + "\nFILE NAME = " + fileName + "\nFile Size = " + file.getSize());
// SAVE ZIP FILE NAME INTO DATABASE
bcf_extractor.setSample_file_name(fileName);
extractorService.save(bcf_extractor);
// ZIP TO UNZIP
String zipFilePath = uploadPath + fileName;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
Date d = new Date();
String destFolderName = fileNameWithOutExt + "_" + d.getTime();
String destPath = projectPath.concat("/src/main/resources/extracted-files/" + destFolderName);
System.out.println("ZIP FILE PATH = " + zipFilePath + "\nDESTINATION PATH = " + destPath);
try {
ZipFile zipFile = new ZipFile(zipFilePath);
/*
* // Get the list of file headers from the zip file List fileHeaderList =
* zipFile.getFileHeaders(); // Loop through the file headers for (int i = 0; i<
* fileHeaderList.size(); i++) { FileHeader fileHeader = (FileHeader)
* fileHeaderList.get(i); String name = fileHeader.getFileName();
* if(name.contains(".html") || name.contains(".css") || name.contains(".java")
* || name.contains(".jsp") || name.contains(".ts") ) {
* zipFile.extractFile(fileHeader, destPath); } }
*/
zipFile.extractAll(destPath);
} catch (ZipException e) {
e.printStackTrace();
}
int headerId = bcf_extractor.getId();
System.out.println("Code Extractor Parameter Header Id = " + headerId);
String tech_stack = bcf_extractor.getTech_stack();
String obj_type = bcf_extractor.getObject_type();
String sub_obj_type = bcf_extractor.getSub_object_type();
// MOVE FILES TO PARENT DIRECTORY & DELETE EMPTY FILES & SAVE PATHS INTO PARAMS
// TABLE
extractorService.saveListOFiles(headerId, tech_stack, obj_type, sub_obj_type, destPath);
// SAVE MOVED PATHS INTO DB
extractorService.moveFiles(headerId, destPath);
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.EXTRACTOR_CREATED_SUCCESSFULLY);
successPojo.setSuccess(success);
log.debug("Response {} ", successPojo);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
// Map<String, Boolean> response = new HashMap<>();
// response.put("SUCCESS", Boolean.TRUE);
// return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
// UPDATE bcf extractor
@ApiOperation(value = "Update an Extension", response = Rn_Bcf_Extractor.class)
@PutMapping("/bcf-extractor/{id}")
public ResponseEntity<?> updateExtractor(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
@PathVariable(value = "id") int id, @Valid @RequestBody Rn_Bcf_Extractor bcf_extractor) {
AppUser loggedInUser = userService.getLoggedInUser();
bcf_extractor.setUpdatedBy(loggedInUser.getUserId());
Rn_Bcf_Extractor updatedExtractor = extractorService.updateById(id, bcf_extractor);
if (bcf_extractor.getId() != updatedExtractor.getId()) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.EXTRACTOR_NOT_DELETED);
errorPojo.setError(error);
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.EXTRACTOR_UPDATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
// return ResponseEntity.status(HttpStatus.ACCEPTED).body(updatedRn_Ext_Field);
}
// DELETE bcf extractor
@DeleteMapping("/bcf-extractor/{id}")
public ResponseEntity<?> deleteExtractor(@PathVariable(value = "id") int id) {
boolean deleted = extractorService.deleteById(id);
// Map<String, Boolean> response = new HashMap<>();
if (deleted) {
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.EXTRACTOR_DELETED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
// response.put("deleted", Boolean.TRUE);
// return ResponseEntity.status(HttpStatus.OK).body(response);
}
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.EXTRACTOR_NOT_DELETED);
errorPojo.setError(error);
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
// =============== BCF CODE EXTRACTOR PARAMS ================
// GET ALL SORTED AND PAGINATED DATA BY HEADER ID
@ApiOperation(value = "List of of Bcf Extractor Parameters", response = Rn_Bcf_Extractor.class)
@GetMapping("/bcf-extractor-params")
public CodeExtractorParamsResponse codeExtractorParameters(
@RequestParam(value = "header_id", required = true) Integer headerId, // use param id to get data
@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
@RequestParam(value = "size", defaultValue = "20", required = false) Integer size) {
// sorted data
// Pageable paging = PageRequest.of(page, size,
// Sort.by("createdAt").descending());
List<Rn_Bcf_Extractor_Params> result = extractorParamsService.getByHeaderIdOrderByDate(headerId);
// log.debug("extractor params sorted data : {}", result.toString());
CodeExtractorParamsResponse resp = new CodeExtractorParamsResponse();
// resp.setPageStats(result, true);
resp.setItems(result);
return resp;
// Map<String, List<Rn_Bcf_Extractor_Params>> extractorMap = Collections.singletonMap("extractorParams", result);
// return new ResponseEntity<Map<String, Page<Rn_Bcf_Extractor_Params>>>(extractorMap, HttpStatus.OK);
}
// GET BY ID
@ApiOperation(value = "Get an Bcf Extractor Parameter", response = Rn_Bcf_Extractor_Params.class)
@GetMapping("/bcf-extractor-params/{id}")
public ResponseEntity<?> codeExtractorParamsById(@PathVariable(value = "id") int id) {
Rn_Bcf_Extractor_Params bcf_extractor_params = extractorParamsService.getById(id);
// Map<String, Rn_Bcf_Extractor_Params> extractorMap =
// Collections.singletonMap("extractorParams",bcf_extractor_params);
// return new ResponseEntity<Map<String, Rn_Bcf_Extractor_Params>>(extractorMap,
// HttpStatus.OK);
return new ResponseEntity<Rn_Bcf_Extractor_Params>(bcf_extractor_params, HttpStatus.OK);
}
@ApiOperation(value = "Add new Extractor Parameter", response = Rn_Bcf_Extractor_Params.class)
@PostMapping(value = "/bcf-extractor-params") // use param id to update data
public ResponseEntity<?> addNewExtractorParam(@RequestParam(value = "header_id", required = true) Integer headerId,
@Valid @RequestBody Rn_Bcf_Extractor_Params bcf_extractor_param) {
Rn_Bcf_Extractor extractor = extractorService.getById(headerId);
bcf_extractor_param.setRn_bcf_extractor(extractor); // set header id
Rn_Bcf_Extractor_Params savedParam = extractorParamsService.save(bcf_extractor_param);
if (savedParam == null) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.EXTRACTOR_NOT_CREATED);
errorPojo.setError(error);
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.EXTRACTOR_CREATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// UPDATE bcf extractor param
@ApiOperation(value = "Update an Extension Parameter", response = Rn_Bcf_Extractor_Params.class)
@PutMapping("/bcf-extractor-params/{id}")
public ResponseEntity<?> updatecodeExtractorParam(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
@RequestParam(value = "header_id", required = false) Integer headerId, @PathVariable(value = "id") int id,
@Valid @RequestBody Rn_Bcf_Extractor_Params bcf_extractor_param) {
AppUser loggedInUser = userService.getLoggedInUser();
bcf_extractor_param.setUpdatedBy(loggedInUser.getUserId());
Rn_Bcf_Extractor_Params updatedExtractorParam = extractorParamsService.updateById(id, bcf_extractor_param);
if (bcf_extractor_param.getId() != updatedExtractorParam.getId()) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.EXTRACTOR_NOT_UPDATED);
errorPojo.setError(error);
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.EXTRACTOR_UPDATED_SUCCESSFULLY);
successPojo.setSuccess(success);
// return ResponseEntity.status(HttpStatus.ACCEPTED).body(updatedRn_Ext_Field);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// ========= TOGGLE BUTTON SERVICE FOR EXTRACTION AND CREATION ENABLE DISABLE
// BUTTON //
// EXTRACTION STATUS CHANGE
@GetMapping(value = "/bcf-extractor-params/extraction-status-change")
public ResponseEntity<?> extractionStatusChange(@RequestParam(value = "id") int id) throws IOException {
AppUser loggedInUser = userService.getLoggedInUser();
Rn_Bcf_Extractor_Params param = extractorParamsService.getById(id);
log.debug("Extractor Param : {} ", param);
param.setIs_extraction_enabled(!param.isIs_extraction_enabled());
param.setUpdatedBy(loggedInUser.getUserId());
Rn_Bcf_Extractor_Params updatedParam = extractorParamsService.save(param);
log.debug("UPDATED Extractor Param : {} ", updatedParam);
if (param.getId() != updatedParam.getId()) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.EXTRACTOR_NOT_UPDATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.EXTRACTOR_UPDATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// CREATION STATUS CHANGE
@GetMapping(value = "/bcf-extractor-params/creation-status-change")
public ResponseEntity<?> creationStatusChange(@RequestParam(value = "id") int id) throws IOException {
AppUser loggedInUser = userService.getLoggedInUser();
Rn_Bcf_Extractor_Params param = extractorParamsService.getById(id);
log.debug("Extractor Param : {} ", param);
param.setIs_creation_enabled(!param.isIs_creation_enabled());
param.setUpdatedBy(loggedInUser.getUserId());
Rn_Bcf_Extractor_Params updatedParam = extractorParamsService.save(param);
log.debug("UPDATED Extractor Param : {} ", updatedParam);
if (param.getId() != updatedParam.getId()) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.EXTRACTOR_NOT_UPDATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.EXTRACTOR_UPDATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// ========== FILE CODE EDITOR PART ============//
/*
* File list(from code extractor params table) for dropDown in file editor
*/
@ApiOperation(value = "Get Extracted File List", response = FileDetails.class)
@GetMapping("/bcf-extractor-file-list/{id}")
public ResponseEntity<?> getFileListBy(@PathVariable(value = "id") int headerId) {
List<Rn_Bcf_Extractor_Params> params = extractorParamsService.getByHeaderId(headerId);
ArrayList<FileListDto> response = new ArrayList<>();
for (Rn_Bcf_Extractor_Params param : params) {
int id = param.getId();
String fileName = param.getName_string();
FileListDto fileList = new FileListDto();
fileList.setId(id);
fileList.setFileName(fileName);
response.add(fileList);
}
if (response.isEmpty()) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.FILE_LIST_API_TITLE);
error.setMessage(Constant.FILE_LIST_IS_EMPTY);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
} else {
return new ResponseEntity<List<FileListDto>>(response, HttpStatus.OK);
}
}
// =====read files and get file contents =========//
@ApiOperation(value = "Get an Bcf Extractor Parameter", response = FileDetails.class)
@GetMapping("/file-code-read/{id}")
public ResponseEntity<?> readFilesById(@PathVariable(value = "id") int id) {
Rn_Bcf_Extractor_Params params = extractorParamsService.getById(id);
String address_string = params.getAddress_string(); // uploaded path
String moved_address_string = params.getMoved_address_string(); // in a same folder
// String reference_address_string = params.getReference_address_string();
String filePath = moved_address_string.replace(projectPath, "");
filePath = projectPath.concat(filePath);
StringBuilder code = new StringBuilder();
File file = null;
try {
file = new File(filePath);
String fileName = file.getName();
// String fileType = FilenameUtils.getExtension(fileName);
log.info("File Name : {}", fileName);
// log.info("File Type : {} ", fileType);
// BufferedReader br = new BufferedReader(new FileReader(file));
// String fileString = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
code.append(line + "\n");
}
fr.close();
br.close();
} catch (IOException e) {
log.debug("IO Exception Handled...");
log.error(e.getMessage());
e.getMessage();
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.FILE_OPERATION_API_TITLE);
error.setMessage(Constant.FILE_NOT_FOUND_EXCEPTION);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
FileDetails fileDetails = new FileDetails();
fileDetails.setId(id);
fileDetails.setText(code.toString());
return new ResponseEntity<FileDetails>(fileDetails, HttpStatus.OK);
}
// ============= code editor (save data into file) =========
@ApiOperation(value = "Save File Data")
@PostMapping(value = "/file-code-save")
public ResponseEntity<?> codeSaveInFile(@Valid @RequestBody FileDetails fileDetails) {
int paramsId = fileDetails.getId();
String code = fileDetails.getText();
log.debug("updated code : {}", code);
Rn_Bcf_Extractor_Params params = extractorParamsService.getById(paramsId);
// String address_string = params.getAddress_string();
String moved_address_string = params.getMoved_address_string();
// String reference_address_string = params.getReference_address_string();
// projectPath
// String filePath = projectPath.concat(reference_address_string);
String filePath = moved_address_string.replace(projectPath, "");
filePath = projectPath.concat(filePath);
File file = null;
try {
file = new File(filePath);
String fileName = file.getName();
String fileType = FilenameUtils.getExtension(fileName);
log.info("File Name : {}", fileName);
log.info("File Type : {} ", fileType);
// if(fileType.equalsIgnoreCase("java") || fileType.equalsIgnoreCase("ts")|| fileType.equalsIgnoreCase("txt")) {
// code = Jsoup.parse(code).text();
// }
BufferedWriter bw = new BufferedWriter(new FileWriter(file, false)); // OVER WRITE FILE
bw.write(code);
bw.close();
} catch (FileNotFoundException e) {
log.debug("File Not Found Exception Handled...");
log.error(e.getMessage());
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.FILE_OPERATION_API_TITLE);
error.setMessage(Constant.FILE_NOT_FOUND_EXCEPTION);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
} catch (IOException e) {
log.error(e.getMessage());
log.debug("IOException Handled...");
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.FILE_OPERATION_API_TITLE);
error.setMessage(Constant.FILE_CODE_SAVE_FAILURE);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.FILE_OPERATION_API_TITLE);
success.setMessage(Constant.FILE_CODE_SAVE_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// ======= STATIC CODE READ =========
@ApiOperation(value = "Read Static File and Return Code", response = FileDetails.class)
@GetMapping("/static-file-code-read/{id}")
public ResponseEntity<?> readStaticFilesById(@PathVariable(value = "id") int id) {
Rn_Bcf_Extractor_Params param = extractorParamsService.getById(id);
String name_string = param.getName_string();
String moved_address_string = param.getMoved_address_string(); // in a same folder
String staticFileName = "SE_".concat(name_string);
String staticPath = moved_address_string.replace(projectPath, "");
staticPath = staticPath.substring(0, staticPath.lastIndexOf("/"));
staticPath = staticPath.concat("/static_code/"); // static code folder
staticPath = staticPath.concat(staticFileName); // static filde name
// projectPath
String filePath = projectPath.concat(staticPath);
// String filePath = staticPath; //by gk
StringBuilder code = new StringBuilder();
File file = null;
try {
file = new File(filePath);
String fileName = file.getName();
// String fileType = FilenameUtils.getExtension(fileName);
log.info("Static File Name : {}", fileName);
// BufferedReader br = new BufferedReader(new FileReader(file));
// String fileString = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
code.append(line + "\n");
}
fr.close();
br.close();
} catch (IOException e) {
log.debug("IO Exception Handled...");
log.error(e.getMessage());
e.getMessage();
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.FILE_OPERATION_API_TITLE);
error.setMessage(Constant.FILE_NOT_FOUND_EXCEPTION);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
String codee = code.substring(0, code.lastIndexOf("\n")); // remove last line break
FileDetails fileDetails = new FileDetails();
fileDetails.setId(id);
fileDetails.setText(codee);
return new ResponseEntity<FileDetails>(fileDetails, HttpStatus.OK);
}
// ======= STATIC CODE SAVE INTO FILE =========
@ApiOperation(value = "Save File Data")
@PostMapping(value = "/static-file-code-save")
public ResponseEntity<?> staticCodeSaveInFile(@Valid @RequestBody FileDetails fileDetails) {
int paramsId = fileDetails.getId();
String code = fileDetails.getText();
// log.debug("updated code : {}", code);
Rn_Bcf_Extractor_Params param = extractorParamsService.getById(paramsId);
// String address_string = param.getAddress_string();
String name_string = param.getName_string();
String moved_address_string = param.getMoved_address_string(); // in a same folder
String staticFileName = "SE_".concat(name_string);
String staticPath = moved_address_string.replace(projectPath, "");
staticPath = staticPath.substring(0, staticPath.lastIndexOf("/"));
staticPath = staticPath.concat("/static_code/"); // static code folder
staticPath = staticPath.concat(staticFileName); // static file name
// projectPath
String filePath = projectPath.concat(staticPath);
File file = null;
try {
file = new File(filePath);
String fileName = file.getName();
log.info("Static File Name : {}", fileName);
BufferedWriter bw = new BufferedWriter(new FileWriter(file, false)); // OVER WRITE FILE
bw.write(code);
bw.close();
} catch (FileNotFoundException e) {
log.debug("File Not Found Exception Handled...");
e.printStackTrace();
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.FILE_OPERATION_API_TITLE);
error.setMessage(Constant.FILE_NOT_FOUND_EXCEPTION);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
} catch (IOException e) {
e.printStackTrace();
log.debug("IOException Handled...");
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.FILE_OPERATION_API_TITLE);
error.setMessage(Constant.FILE_CODE_SAVE_FAILURE);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.FILE_OPERATION_API_TITLE);
success.setMessage(Constant.FILE_CODE_SAVE_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// @PostMapping("/upload")
@PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> uploadToLocalFileSystem(@RequestParam("file") MultipartFile file) {
System.out.println("calling upload controller");
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
Path path = Paths.get(projectPath + fileName);
try {
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/files/download/")
.path(fileName).toUriString();
return ResponseEntity.ok(fileDownloadUri);
}
@RequestMapping(value = "/redirect", produces = { MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
public ResponseEntity<?> registerBatchUser(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(projectPath)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
Map<String, Object> FeedBackStatus = new HashMap<String, Object>();
return ResponseEntity.ok(FeedBackStatus);
}
}
return ResponseEntity.ok(null);
}
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
return fileName;
}
@RequestMapping(value = "/upload-file-2", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<Map<String, Object>> handleFileUpload(
@RequestParam("file") MultipartFile file) {
String name = file.getName();
System.out.println(name);
Map<String, Object> FeedBackStatus = new HashMap<String, Object>();
FeedBackStatus.put("status", "success");
return ResponseEntity.ok(FeedBackStatus);
}
/*
* @PostMapping(value = "/uploadFile", consumes =
* MediaType.MULTIPART_FORM_DATA_VALUE) public String
* uploadFile2(@RequestParam("file") MultipartFile file)throws IOException {
* Path tempFile = Files.createTempFile(null, null);
*
* Files.write(tempFile, MultipartFile.getBytes()); File fileToSend =
* tempFile.toFile();
*
* MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
*
* parameters.add("file", new FileSystemResource(fileToSend));
*
* HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type",
* "multipart/form-data");
*
* HttpEntity httpEntity = new HttpEntity<>(parameters, headers);
*
* try { restTemplate.exchange(apiUrl, HttpMethod.POST, httpEntity,
* MyClazz.class); } finally { fileAEnviar.delete(); }
*
* }
*/
@PostMapping("/upload-gb")
public ResponseEntity<String> uploadFileGb(@RequestParam("file") MultipartFile file) {
return ResponseEntity.ok("working");
}
}
@@ -0,0 +1,352 @@
package com.realnet.codeextractor.controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.hibernate.boot.model.source.spi.CascadeStyleSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.realnet.codeextractor.entity.Rn_Bcf_Exception_Rules;
import com.realnet.codeextractor.entity.Rn_Bcf_Extractor;
import com.realnet.codeextractor.entity.Rn_Bcf_Extractor_Params;
import com.realnet.codeextractor.entity.Rn_Bcf_Rules;
import com.realnet.codeextractor.service.Rn_Bcf_Exception_Rule_Library_Service;
import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Params_Service;
import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Service;
import com.realnet.codeextractor.service.Rn_Bcf_Rule_Library_Service;
import com.realnet.fnd.entity.Error;
import com.realnet.fnd.entity.ErrorPojo;
import com.realnet.fnd.entity.Success;
import com.realnet.fnd.entity.SuccessPojo;
import com.realnet.logging.LogExecutionTime;
import com.realnet.utils.Constant;
import com.realnet.utils.RealNetUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = { "Code Extractor" })
public class DynamicCodeExtractionController {
@Value("${projectPath}")
private String projectPath;
@Autowired
private Rn_Bcf_Extractor_Service rn_bcf_extractor_service;
@Autowired
private Rn_Bcf_Extractor_Params_Service rn_bcf_extractor_params_service;
@Autowired
private Rn_Bcf_Rule_Library_Service bcfRuleLibraryService;
// @Autowired
// private RealNetUtils utils;
@Autowired
Rn_Bcf_Exception_Rule_Library_Service rn_bcf_rule_exception_library_service;
@LogExecutionTime
@ApiOperation(value = "Dynamic Code Extraction")
@GetMapping(value = "/dynamic_code_extraction")
public ResponseEntity<?> dynamicCodeExtraction(@RequestParam(value = "header_id") Integer headerId)
throws IOException
{
Rn_Bcf_Extractor extractor = rn_bcf_extractor_service.getById(headerId);
String technology_stack = extractor.getTech_stack();
String object_type = extractor.getObject_type();
String sub_object_type = extractor.getSub_object_type();
System.out.println("FROM Rn_Bcf_Extractor = " + technology_stack + " || " + object_type + " || " + sub_object_type+"||"+headerId);
// PARAMS
List<Rn_Bcf_Extractor_Params> params = extractor.getRn_bcf_extractor_Params();
//
// // FILE NAME VARIABLE NAMES IN BUILDER CODE
// Map<String, String> map = new HashMap<String, String>();
// map.put("controller_name_first_upper", "Nil_final_controller");
// map.put("table_name_first_upper", "Rn_nil_final");
// map.put("table_name_lower", "rn_nil_final");
// map.put("table_name_upper", "RN_NIL_FINAL");
// map.put("service_name_first_upper", "Nil_final_service");
// map.put("service_name_lower", "nil_final_service");
// map.put("service_impl_name_first_upper", "Nil_final_serviceimpl");
// map.put("repository_name_first_upper", "Rn_header_test1_repository");
// map.put("repository_name_lower", "rn_header_test1_repository");
// map.put("ng_add_form_component_name", "AddRn_header_test1Component");
// map.put("ng_all_grid_view_component_name", "AllRn_header_test1Component");
// map.put("ng_read_only_component_name", "Rn_header_test1DetailsComponent");
// map.put("ng_edit_component_name", "EditRn_header_test1Component");
// map.put("ng_extension_add_component_name", "AddExtRn_header_test1Component");
// map.put("ng_routing_module_ts_name", "Rn_header_test1RoutingModule");
// map.put("ng_component_ts_name", "Rn_header_test1Component");
// map.put("ng_module_ts_name", "Rn_header_test1Module");
// map.put("ng_service_ts_name", "Rn_header_test1Service");
// map.put("ng_model_ts_name ", "Rn_header_test1_t");
// STATIC FILES ( SE_FILE_NAME.EXT)
ArrayList<String> staticFiles = new ArrayList<String>();
try {
// PARAMETERS TABLE VALUE
for (Rn_Bcf_Extractor_Params param : params)
{
// System.out.println("---Exception rule for loop--");
boolean is_extraction_enabled = param.isIs_extraction_enabled();
boolean is_creation_enabled = param.isIs_creation_enabled();
String path = param.getMoved_address_string();
File file = new File(path);
String parentPath = file.getParent();
String name = file.getName();
String ConvertedFileName = "SE_" + name;
// STATIC FILES DIRECTORY
String staticFileParentDir = parentPath + File.separator + "static_code";
File staticFile = new File(staticFileParentDir + File.separator + ConvertedFileName);
// STATIC FILE PATH
String staticFileDir = staticFile.getAbsolutePath().replace("\\", "/");
// ADD STATIC FILE PATH TO ARRAYLIST
if (is_extraction_enabled && is_creation_enabled) {
// System.out.println("STATIC FILE DIR ADDED TO ARRAYLIST = " + staticFileDir);
staticFiles.add(staticFileDir);
}
}
// package part MODULE_NAME ADD
for (String staticDir : staticFiles)
{
File file = new File(staticDir);
Path path = Paths.get(staticDir);
StringBuilder code = new StringBuilder();
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines)
{
if (line.startsWith("\"package"))
{
int i = line.lastIndexOf(".");
String head = line.substring(0, i + 1);
String tail = line.substring(i);
String moduleName = "\" + module_name + \"";
line = head + moduleName + tail;
}
code.append(line + "\n");
}
//System.out.println(code);
BufferedWriter br = new BufferedWriter(new FileWriter(file)); // replaced string
br.write(code.toString());
br.close();
}
int count=0;
for (String staticDir : staticFiles)
{
File file1 = new File(staticDir);
Path path1 = Paths.get(staticDir);
StringBuilder code = new StringBuilder();
StringBuilder code2 = new StringBuilder();
List<String> lines = Files.readAllLines(path1, StandardCharsets.UTF_8);
for (String line : lines)
{
if (line.startsWith("\"public class"))
{
//
String file_name_var=params.get(count).getFile_name_var();
// System.out.println("file namevar "+file_name_var);
line = "\"public class \" + "+file_name_var+""+1+" + \"{\"+";
}
if (line.startsWith("\"public interface"))
{
//
String file_name_var=params.get(count).getFile_name_var();
// System.out.println("file namevar "+file_name_var);
line = "\"public interface \" + "+file_name_var+""+1+" + \"{\"+";
}
if (line.startsWith("\" templateUrl"))
{
// " templateUrl: './readonly.component.html'," + "\r\n" +
String file_name_var=params.get(count).getFile_name_var();
// System.out.println("file namevar "+file_name_var);
line = " \" templateUrl: './\"+"+file_name_var+""+1+"+\".html',\"" + "\r\n \n" +"+" ;
}
if (line.startsWith("\" styleUrls"))
{
// " styleUrls: ['./readonly.component.scss']" + "\r\n" +
String file_name_var=params.get(count).getFile_name_var();
// System.out.println("file namevar "+file_name_var);
line = " \" styleUrls: ['./\"+"+file_name_var+""+1+"+\".scss']\"" + "\r\n \n"+"+" ;
}
if (line.startsWith("\"export class"))
{
// "export class ReadonlyComponent implements OnInit {" + "\r\n" +
String file_name_var=params.get(count).getFile_name_var();
// System.out.println("file namevar "+file_name_var);
line = "\"export class \"+"+file_name_var+""+2+"+\"Component implements OnInit {\"" + "\r\n"+"+" ;
}
code.append(line + "\n");
}
count++;
BufferedWriter br = new BufferedWriter(new FileWriter(file1)); // replaced string
br.write(code.toString());
br.close();
}
// APPLY ALL RULES PRESENT HERE
List<Rn_Bcf_Rules> rules = bcfRuleLibraryService.getAll();
int rulesOuterCount = 0;
for (Rn_Bcf_Rules rule : rules)
{
rulesOuterCount++;
// System.out.println("RULES FOR COUNT = " + ++rulesOuterCount);
String start = rule.getIdentifier_start_string();
String end = rule.getIdentifier_end_string();
String replaceWith = rule.getReplacement_string();
String tech_stack = rule.getTech_stack();
String sub_object_type2 = rule.getSub_object_type();
String object_type2 = rule.getObject_type();
replaceWith = replaceWith.concat("");
if(technology_stack.equals(tech_stack) && sub_object_type.equals(sub_object_type2) && object_type.equals(object_type2))
{
// System.out.println("main tech stack"+technology_stack+" new "+tech_stack);
// System.out.println("main subobject "+sub_object_type+" new "+sub_object_type2);
// System.out.println("main object "+object_type+" new "+object_type2);
int dirCount = 0;
for (String staticDir : staticFiles)
{
dirCount++;
File staticFile = new File(staticDir);
String staticFileName = staticFile.getName();
// System.out.println("========" + staticFileName + "=============");
String fileString = FileUtils.readFileToString(staticFile, StandardCharsets.UTF_8);
String fileType = FilenameUtils.getExtension(staticFileName);
// don't check empty file for replacement..
if (!fileString.isEmpty()) {
// RULE APPLY
String finalString = RealNetUtils.stringReplace(fileString, start, end, replaceWith,
fileType);
BufferedWriter bw = new BufferedWriter(new FileWriter(staticFile, false)); // replaced
// string
bw.write(finalString);
bw.close();
}
}
}
// System.out.println("loop count::"+dirCount);
}
System.out.println("rules outer countt::"+rulesOuterCount);
} catch (FileNotFoundException e) {
e.printStackTrace();
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.DYNAMIC_EXTRACTION_FAILED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.DYNAMIC_EXTRACTION_SUCCESS);
successPojo.setSuccess(success);
log.debug("Response {} ", successPojo);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
}
@@ -0,0 +1,39 @@
package com.realnet.codeextractor.controller;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.SerializationFeature;
//@JsonIgnoreProperties(ignoreUnknown=true)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
//@JacksonFeatures(serializationDisable = {SerializationFeature.FAIL_ON_EMPTY_BEANS})
@JsonSerialize
@RestController
public class FileUploadController {
@PostMapping("/upload-gb")
public ResponseEntity<Void> uploadFileGb(@RequestParam("file") MultipartFile file[]){
for(MultipartFile files:file) {
System.out.println("File name::"+files.getOriginalFilename());
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@PostMapping("/upload-string")
public ResponseEntity<String> uploadFileString(){
return ResponseEntity.ok("working");
}
}
@@ -0,0 +1,684 @@
package com.realnet.codeextractor.controller;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.codeextractor.entity.Rn_Bcf_Extractor;
import com.realnet.codeextractor.entity.Rn_Bcf_Extractor_Params;
import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Service;
import com.realnet.flf.service.FieldTypeService;
import com.realnet.fnd.entity.Error;
import com.realnet.fnd.entity.ErrorPojo;
import com.realnet.fnd.entity.Success;
import com.realnet.fnd.entity.SuccessPojo;
import com.realnet.utils.Constant;
import io.swagger.annotations.Api;
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = { "Build Master Builder" })
public class MasterCodeBuild_gk {
@Value("${projectPath}")
private String projectPath;
@Value("${angularProjectPath}")
private String angularProjectPath;
@Autowired
private Rn_Bcf_Extractor_Service rn_bcf_extractor_service;
@Autowired
private FieldTypeService fieldTypeService;
// private static final Logger logger =
// Logger.getLogger(BuildMasterBuilderController.class);
@GetMapping("/build_master_builder")
public ResponseEntity<?> masterControllerBuilder(@RequestParam(value = "id") Integer id)
throws IOException, FileNotFoundException {
StringBuilder variablesDynamicCode = new StringBuilder();
StringBuilder stringBuilderDynamicCode = new StringBuilder();
// StringBuilder stringBuilder = new StringBuilder();
// RN_BCF_CODE_EXTRACTOR_T ID
// int eid = Integer.parseInt(id);
Rn_Bcf_Extractor extractor = rn_bcf_extractor_service.getById(id);
String technology_stack = extractor.getTech_stack();
String object_type = extractor.getObject_type();
String sub_object_type = extractor.getSub_object_type();
// RN_BCF_CODE_EXTRACTOR_PARAMS_T VALUES
// List<Rn_Bcf_Extractor_Params> params =
// rn_bcf_extractor_params_service.getByHeaderId(eid);
List<Rn_Bcf_Extractor_Params> params = extractor.getRn_bcf_extractor_Params();
int j = 0;
for (Rn_Bcf_Extractor_Params param : params) {
boolean is_creation_enabled = param.isIs_creation_enabled();
// param.isIs_extraction_enabled();
String path = param.getMoved_address_string();
File file = new File(path);
String parentPath = file.getParent();
String name = file.getName();
String convertedFileName = "SE_" + name;
// STATIC CODE DIRECTORY
String staticFileParentDir = parentPath + File.separator + "static_code";
File staticFile = new File(staticFileParentDir + File.separator + convertedFileName);
// HERE WE GET FILE INSIDE DATA
String fileToString = FileUtils.readFileToString(staticFile, StandardCharsets.UTF_8);
// ex. controller_file (FROM PARAMS TABLE)
String file_name_var = param.getFile_name_var() + j;
// ex. ui_name + "controller"
String file_name_dynamic_string = param.getFile_name_dynamic_string();
// ex. String controller_file = ui_name + "controller";
variablesDynamicCode
.append("String " + file_name_var + " = " + "\"" + file_name_dynamic_string + "\"" + ";\r\n");
System.out.println("file name dynamic str " + file_name_dynamic_string);
// change file name entity
// String mainstr1=file_name_dynamic_string;
// String saleesent1=mainstr1.replace(".java", " ");
// System.out.println("updated filename"+saleesent1);
// System.out.println(file_name_dynamic_string.contains(".java"));
// System.out.println(file_name_dynamic_string.contains(".ts"));
// System.out.println(file_name_dynamic_string.contains(".scss"));
// System.out.println(file_name_dynamic_string.contains(".html"));
// HERE WE CHECK AND APPEND FILE NAME
if (file_name_dynamic_string.contains(".java")) {
variablesDynamicCode
.append("String mainstr" + j + " = " + file_name_var + ";\r\n" + "String " + file_name_var + ""
+ 1 + "=mainstr" + j + ".replace(\".java\", \"\");\r\n" + "" + "\r\n" + "\n");
} else if (file_name_dynamic_string.contains(".ts")) {
variablesDynamicCode.append("String mainstr" + j + " = " + file_name_var + ";\r\n" + "String "
+ file_name_var + "" + 1 + "=mainstr" + j + ".replace(\".ts\", \"\");\r\n" + "" + "\r\n"
+ "String " + file_name_var + "" + 2 + "=mainstr" + j + ".replace(\".component.ts\", \"\");\r\n"
+ "" + "\r\n" + "\n");
} else if (file_name_dynamic_string.contains(".html")) {
variablesDynamicCode
.append("String mainstr" + j + " = " + file_name_var + ";\r\n" + "String " + file_name_var + ""
+ 1 + "=mainstr" + j + ".replace(\".html\", \"\");\r\n" + "" + "\r\n" + "\n");
} else if (file_name_dynamic_string.contains(".scss")) {
variablesDynamicCode
.append("String mainstr" + j + " = " + file_name_var + ";\r\n" + "String " + file_name_var + ""
+ 1 + "=mainstr" + j + ".replace(\".scss\", \"\");\r\n" + "" + "\r\n" + "\n");
} else {
System.out.println("not found");
}
// ======= MODULE NAME SHOULD COME FROM THE SESSION ========
// String moduleName = "\" + module_name + \"/\"";
String moduleName = "\" + module_name + \"/";
String modulePath = param.getTotal_project_path_dynamic_string();
// System.out.println("MODULE PATH = " + modulePath);
if (modulePath.endsWith(".java")) {
String parent = modulePath.substring(0, modulePath.lastIndexOf("/")); // 1
String lvl2Parent = parent.substring(0, parent.lastIndexOf("/") + 1); // 2
String tail0 = modulePath.substring(parent.lastIndexOf("/") + 1); // 3
tail0 = tail0.substring(0, tail0.lastIndexOf("/") + 1); // remove the .java file name
modulePath = lvl2Parent + moduleName + tail0;
} else {
// add module name in spring project
modulePath = modulePath.substring(0, modulePath.lastIndexOf("/") + 1);
String data0 = modulePath.substring(0, modulePath.lastIndexOf("/") + 1);
String tail0 = modulePath.substring(modulePath.lastIndexOf("/") + 1);
data0 += moduleName + tail0;
modulePath = data0;
}
// System.out.println("MANUPULATED module PATH = " + modulePath);
// String ref_address_string = param.getReference_address_string();
// ref_address_string = ref_address_string.substring(0, ref_address_string.lastIndexOf("/")+1);
String total_address_path = param.getTotal_project_path_dynamic_string();
total_address_path = total_address_path.substring(0, total_address_path.lastIndexOf("/") + 1);
System.out.println("total path : " + total_address_path + "\n");
String finalDir = "";
//
// here we set file path
String dest_path = "projectPath + \"" + "/Projects/\" + project_name + \"" + total_address_path;
System.out.println("dest path : " + dest_path);
// String finalDir = dirString + "/" + "\" + " + file_name_var;
finalDir = dest_path + "\" + " + file_name_var;
System.out.println(finalDir);
// module_dest_path = "projectPath + \"" + "/Projects/\" + project_name + " +
// modulePath;
// String dest_path = "projectPath + \"" + "/Projects/\" + project_name + \"" + modulePath;
// String finalDir = dirString + "/" + "\" + " + file_name_var;
finalDir = dest_path + "\" + " + file_name_var;
System.out.println("NIL FINAL DIR = " + finalDir + "\n");
if (is_creation_enabled) {
StringBuilder fileCode = new StringBuilder();
if (file_name_dynamic_string.contains("entity")) {
// String entity = entity(path, "test");
if (fileToString.isEmpty()) {
fileCode.append(" " + file_name_var + "Code.append(\"" + fileToString + "\");\r\n");
} else {
fileCode.append(" " + file_name_var + "Code.append(" + fileToString + ");\r\n");
}
} else if (file_name_dynamic_string.contains("repository")
|| file_name_dynamic_string.contains("repo")) {
// String repo = repo(path, "test");
if (fileToString.isEmpty()) {
fileCode.append(" " + file_name_var + "Code.append(\"" + fileToString + "\");\r\n");
} else {
fileCode.append(" " + file_name_var + "Code.append(" + fileToString + ");\r\n");
}
} else if (file_name_dynamic_string.contains("service")) {
// String service = service(path, "test");
if (fileToString.isEmpty()) {
fileCode.append(" " + file_name_var + "Code.append(\"" + fileToString + "\");\r\n");
} else {
fileCode.append(" " + file_name_var + "Code.append(" + fileToString + ");\r\n");
}
} else if (file_name_dynamic_string.contains("controller")) {
// String controller = controller(path, "test");
if (fileToString.isEmpty()) {
fileCode.append(" " + file_name_var + "Code.append(\"" + fileToString + "\");\r\n");
} else {
fileCode.append(" " + file_name_var + "Code.append(" + fileToString + ");\r\n");
}
} else {
// String other = other(path, "test");
if (file_name_dynamic_string.isEmpty()) {
fileCode.append(" " + file_name_var + "Code.append(\"" + fileToString + "\"\r\n");
} else {
fileCode.append(" " + file_name_var + "Code.append(" + fileToString + "\r\n");
}
}
// EMPTY FILE CODE WILL NOT GO IN THIS LOOP
stringBuilderDynamicCode.append(" StringBuilder " + file_name_var + "Code = new StringBuilder();\r\n"
// + " " + file_name_var + "Code.append(" + fileToString + ");\r\n"
+ fileCode + "\r\n"
+ " File " + file_name_var + "File = new File(" + finalDir + ");\r\n"
+ " System.out.println(\"Directory name = \" + " + file_name_var + "File);\r\n"
// == CREATE PARENT DIR IF NOT EXIST===
+ " File " + file_name_var + "FileParentDir = new File(" + file_name_var
+ "File.getParent());\r\n" + " if(!" + file_name_var + "FileParentDir.exists()) {\r\n" + " "
+ file_name_var + "FileParentDir.mkdirs();\r\n" + " }\r\n"
// ==
+ " if (!" + file_name_var + "File.exists()) {\r\n" + " " + file_name_var
+ "File.createNewFile();\r\n" + " }\r\n" + " " + "fw = new FileWriter("
+ file_name_var + "File.getAbsoluteFile());\r\n" + " bw = new BufferedWriter(fw);\r\n"
+ " " + " bw.write(" + file_name_var + "Code.toString());\r\n" + " bw.close();\r\n"
+ "\r\n");
}
j++;
}
// CHILD MASTER BUILDER NAME DEPENDS ON (TECH_STACK, OBJ_TYPE, SUB_OBJ_TYPE)
String childMasterBuilderName = technology_stack + "_" + object_type + "_" + sub_object_type + "_Builder";
childMasterBuilderName = childMasterBuilderName.replace(" ", "_");
childMasterBuilderName = childMasterBuilderName.replaceAll("[-]+", "_");
StringBuilder childMasterBuilderCode = new StringBuilder();
// String action_builder_code = fieldTypeService.angular_action_builder_code();
childMasterBuilderCode.append("package com.realnet.builders;\r\n" + "\r\n"
+ "import java.io.BufferedWriter;\r\n" + "import java.io.File;\r\n" + "import java.io.FileWriter;\r\n"
+ "import java.io.IOException;\r\n" + "import java.util.ArrayList;\r\n" + "import java.util.Date;\r\n"
+ "import java.util.List;\r\n" + "import java.util.Optional;\r\n" + "\r\n"
+ "import org.modelmapper.ModelMapper;\r\n"
+ "import org.springframework.beans.factory.annotation.Autowired;\r\n"
+ "import org.springframework.beans.factory.annotation.Value;\r\n"
+ "import org.springframework.http.HttpStatus;\r\n" + "import org.springframework.http.MediaType;\r\n"
+ "import org.springframework.http.ResponseEntity;\r\n"
+ "import org.springframework.web.bind.annotation.GetMapping;\r\n"
+ "import org.springframework.web.bind.annotation.PathVariable;\r\n"
+ "import org.springframework.web.bind.annotation.RequestMapping;\r\n"
+ "import org.springframework.web.bind.annotation.RestController;\r\n" + "\r\n"
+ "import com.google.gson.JsonElement;\r\n" + "import com.google.gson.JsonObject;\r\n"
+ "import com.google.gson.JsonParser;\r\n" + "import com.google.gson.JsonArray;\r\n" + "\r\n"
+ "import com.realnet.actionbuilder.service.Rn_Cff_ActionBuilder_Service;\r\n"
+ "import com.realnet.flf.service.FieldTypeService;\r\n"
+ "import com.realnet.fnd.service.Rn_LookUp_Service;\r\n"
+ "import com.realnet.formdrag.repository.Rn_wf_lines_3Repository;\r\n"
+ "import com.realnet.formdrag.entity.Rn_wf_lines_3;\r\n" + ""
+ "import com.realnet.wfb.service.Rn_WireFrame_Service;\r\n" + "\r\n"
+ "import io.swagger.annotations.Api;"
+ "\r\n" + "@RestController\r\n"
// CONTROLLER NAME SHOULD CHANGE
// DEPENDS ON TECH_STACK/OBJECT_tYPE/SUB_OBJECT_TYPE
+ "@RequestMapping(value = \"/api\", produces = MediaType.APPLICATION_JSON_VALUE)\r\n"
+ "@Api(tags = { \"Master Builder\" })\r\n" + "public class " + childMasterBuilderName + " {\r\n"
+ "\r\n" + "\r\n" + " @Value(\"${angularProjectPath}\")\r\n" + " private String angularProjectPath;"
+ " @Value(\"${projectPath}\")\r\n" + " private String projectPath;"
// DEPENDENCIES FOR WIREFRAME
+ " @Autowired\r\n" + " private Rn_WireFrame_Service wireFrameService;\r\n" + "\r\n" +
" @Autowired\r\n" + " private Rn_LookUp_Service lookUpService;\r\n" + "@Autowired\r\n"
+ " private Rn_wf_lines_3Repository repo;\n"
+ "\r\n" + " @Autowired\r\n" + " private Rn_Cff_ActionBuilder_Service actionBuilderService;\r\n"
+ "\r\n" + " @Autowired\r\n" + " private ModelMapper modelMapper;\r\n" + "\r\n" + " @Autowired\r\n"
+ " private FieldTypeService fieldTypeService;\r\n\n\n" + "@GetMapping(value = \"/"
+ childMasterBuilderName + "/{header_id}\")\r\n"
+ " public ResponseEntity<?> createbyjson(@PathVariable Integer header_id) throws IOException {\r\n"
+ " Optional<Rn_wf_lines_3> wireframe = repo.findheader(header_id);\r\n" + "\r\n"
+ " List<String> tablename = new ArrayList<>();\r\n"
+ " List<String> entityname = new ArrayList<>();\r\n" + "\r\n"
+ " JsonParser parser = new JsonParser();\r\n"
+ " JsonElement element = parser.parse(wireframe.get().getModel());\r\n"
+ " JsonObject jsonObject = element.getAsJsonObject();\r\n" + "\r\n"
+ " JsonElement name = jsonObject.get(\"name\");\r\n" + " System.out.println(name);\r\n"
+ " tablename.add(name.getAsString());\r\n" + "\r\n"
+ " JsonElement desc = jsonObject.get(\"description\");\r\n"
+ " System.out.println(desc);\r\n" + "// keys.add(\"desc :\"+desc.getAsString());\r\n"
+ "\r\n" + " JsonElement element2 = jsonObject.get(\"attributes\");\r\n"
+ " System.out.println(element2);\r\n" + "\r\n"
+ " JsonArray jsonArray = element2.getAsJsonArray();\r\n"
+ " System.out.println(jsonArray);\r\n" + "\r\n" + " for (JsonElement ar : jsonArray) {\r\n"
+ "\r\n" + " JsonObject obj = ar.getAsJsonObject();\r\n" + "\r\n"
+ " JsonElement type = obj.get(\"type\");\r\n" + " System.out.println(type);\r\n"
+ "// keys.add(\"type :\"+type.getAsString());\r\n" + "\r\n"
+ " JsonElement description = obj.get(\"description\");\r\n"
+ " System.out.println(description);\r\n"
+ "// keys.add(\"description :\"+description.getAsString());\r\n" + "\r\n"
+ " JsonElement placeholder = obj.get(\"placeholder\");\r\n"
+ "// System.out.println(placeholder);\r\n"
+ "// keys.add(\"placeholder :\"+placeholder.getAsString());\r\n" + "\r\n"
+ " JsonElement label = obj.get(\"label\");\r\n" + " System.out.println(label);\r\n"
+ " entityname.add(label.getAsString());\r\n" + "\r\n" + " }\r\n" + "\r\n"
+ " Date d = new Date();\r\n" + " String addString = \"_\";\r\n" + "\r\n"
+ " // CALL BACKEND\r\n"
// + " backendservice.buildbackend(tablename, entityname, addString);\r\n" + "\r\n"
// + " // CALL FRONTEND\r\n"
// + " frontendservice.buildFrontend(tablename, entityname, addString);\r\n"
// + ""
// + "\r\n" + " System.out.println(\"id ::\"+id);"
// + "\n lookUpService.createTable(id);"
// + " \n // extra button \n List<Rn_Fb_Line> extraButton = wireFrameService.getExtraButton(id);"
// + " \n // HEADER VALUE\r\n" + " Rn_Fb_Header rn_fb_header = wireFrameService.getById(id);\r\n"
// + " \r\n" + " // LINE VALUES\r\n"
// + " List<Rn_Fb_Line> rn_fb_lines = rn_fb_header.getRn_fb_lines();\r\n" + " \r\n"
// + " // MODULE DETAILS\r\n" + " Rn_Module_Setup module = rn_fb_header.getModule();\r\n"
// + " \r\n" + " // PROJECT DETAILS\r\n"
// + " Rn_Project_Setup project = module.getProject();\r\n" + " \r\n"
// // ATTRIBUTE FLEX
// + " // ATTRIBUTE FLEX VALUES\r\n"
// + " List<Rn_Lookup_Values> attribute_flex_values = lookUpService.getExtensions();\r\n"
// + " String project_name = project.getProjectName();\r\n"
+ " String project_name =" + "\"" + "test" + j + "\"" + ";\r\n"
// + " String module_name = module.getModuleName();\r\n\n"
+ "\r\r\rFileWriter fw = null;\r\n" + "BufferedWriter bw = null;\r\n" + variablesDynamicCode);
childMasterBuilderCode.append(""
// ACTION BUILDER CODE
+ // =========== VARIABLE CODE WILL BE APPEND HERE ===============//
"\n" + stringBuilderDynamicCode.toString() + "\r\n"
+ " return new ResponseEntity<>(\"created\", HttpStatus.CREATED);\r\n" + "}\r\n }");
//
FileWriter fw = null;
BufferedWriter bw = null;
try {
// FILE NAME SHOULD CHANGE DEPENDS ON TECH_STACK/OBJECT_tYPE/SUB_OBJECT_TYPE
File masterBuilderFile = new File(
projectPath + "/src/main/java/com/realnet/builders/" + childMasterBuilderName + ".java");
if (!masterBuilderFile.exists()) {
masterBuilderFile.createNewFile();
}
fw = new FileWriter(masterBuilderFile.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write(childMasterBuilderCode.toString());
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.MASTER_BUILDER_API_TITLE);
error.setMessage(Constant.MASTER_BUILDER_FAILURE);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.MASTER_BUILDER_API_TITLE);
success.setMessage(Constant.MASTER_BUILDER_SUCCESS);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
}
public String entity(String path, String classname) throws IOException {
return UpdateEntity(path, classname);
}
public String repo(String path, String classname) throws IOException {
return UpdateRepo(path, classname);
}
public String service(String path, String classname) throws IOException {
return UpdateService(path, classname);
}
public String controller(String path, String classname) throws IOException {
return UpdateController(path, classname);
}
public String other(String path, String classname) throws IOException {
return UpdateRepo(path, classname);
}
public String UpdateEntity(String path, String classname) throws IOException {
// String path = "C:\\Users\\Aniket\\Documents\\Entity.txt";
// String classname = "gk";
String addition = "for (int i = 0; i < entityname.size(); i++) {\r\n"
+ " String string = entityname.get(i);\r\n"
+ " String lowerCase = string.replaceAll(\" \", \"_\").toLowerCase();\r\n"
+ " String add = \"\\n private \" + \"String\" + \" \" + lowerCase + \";\";\r\n"
+ " intialize.append(add);\r\n"
+ " }";
/*
* RandomAccessFile writer=new
* RandomAccessFile("C:/Users/lenovo/Documents/demo.txt","rw");
*
* writer.seek(position); writer.writeBytes(addition); writer.close();
*/
String line = "";
StringBuilder intialize = new StringBuilder();
StringBuilder class_name = new StringBuilder();
StringBuilder middle = new StringBuilder();
StringBuilder end = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
for (String d : data) {
if (d.contains("import") || d.contains("@Data") || d.contains("@Entity")) {
intialize.append("\"");
intialize.append(d);
intialize.append("\"+\n");
} else if (d.contains("public")) {
class_name.append("\"public class "+classname +" {\"+ \n");
// intialize.append("\"+\n");
} else if (d.contains("}")) {
intialize.append("\"");
end.append(d);
intialize.append("\"+\n");
}
}
}
br.close();
middle.append(addition);
StringBuilder finalstring = new StringBuilder();
finalstring.append("\"StringBuilder intialize = new StringBuilder();\"+\r\n"
+ "\" intialize.append(\"+");
finalstring.append(intialize.toString());
finalstring.append(class_name.toString());
finalstring.append("\t\"@Id\"+\r\n"
+ "\" @GeneratedValue(strategy = GenerationType.IDENTITY)\"+\r\n"
+ "\" private int id;\");\n");
finalstring.append(middle.toString());
return finalstring.toString();
}
public String UpdateRepo(String path, String classname) throws IOException {
String line = "";
StringBuilder intialize = new StringBuilder();
StringBuilder class_name = new StringBuilder();
StringBuilder middle = new StringBuilder();
StringBuilder end = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(path));
intialize.append("\"");
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
for (String d : data) {
if (d.contains("import") || d.contains("@Repository") ) {
intialize.append("\""+d);
intialize.append("\"+\n");
} else if (d.contains("public")) {
class_name.append("\""+"public class "+classname +" extends JpaRepository<"+classname + ", Long> " +"{"+"\"+");
class_name.append("\n");
}
}
}
br.close();
StringBuilder finalstring = new StringBuilder();
finalstring.append(" \""+" StringBuilder repo = new StringBuilder();"+"\"+\n"
+" \""+""
+" "+ "repo.append(");
finalstring.append(intialize.toString());
finalstring.append(class_name.toString());
finalstring.append("\"+}\"");
finalstring.append("\");"+"\"");
return finalstring.toString();
}
public String UpdateService(String path, String classname) throws IOException {
String line = "";
String apiName ="Api";
StringBuilder intialize = new StringBuilder();
StringBuilder class_name = new StringBuilder();
StringBuilder middle = new StringBuilder();
StringBuilder end = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(path));
intialize.append("\"import java.util.List;\"+\r\n"
+ "\r\n" + "\"import org.springframework.beans.factory.annotation.Autowired;\"+\r\n"
+ "\" import org.springframework.stereotype.Service;\"+\n");
intialize.append("\n\"@Service\"+\n");
intialize.append("\"@RequestMapping(value = " +"\"/"+ apiName+ "\")\"+\n"
+ "\"@RestController\"+\r\n");
class_name.append("\"public class "+ classname +"Service {\"+\r\n"
+ "\" @Autowired\"+\r\n"
+ "\" private " + classname+ "Service Service;\"+\n");
middle.append(
"\" @Autowired\r\n" + "private " + classname + "Repository " + "Repository;\"+\n");
middle.append("\"public "+ classname +" Savedata("+classname+ " data) {\"+\r\n"
+ " \" return Repository.save(data);\"+ \r\n" + " \" }\"+\r\n" + "\r\n"
+ " \" \r\n" + "public List<" + classname + "> getdetails() {\"+\r\n"
+ " \" return (List<" + classname + ">) Repository.findAll();\"+\r\n" + " }\r\n"
+ "\r\n" + "\r\n" + "\"public "+ classname +" getdetailsbyId(Long id) {\"+\r\n"
+ "\" return Repository.findById(id).get();\"+\r\n" + "\" }\"+\r\n" + "\r\n" + "\r\n"
+ "\" public void delete_by_id(Long id) {\"+\r\n"
+ "\" Repository.deleteById(id);\"+\r\n" + "}\"+\r\n" + "\r\n" + "\r\n");
middle.append("\"public "+ classname +" update("+ classname +" data,Long id) {\"+\n"
+ " \""+ classname +" old = Repository.findById(id).get();\"+\n");
// middle.append(" for (EntityBuild en : ent) {
// String name = en.getName();
//
// String string = name.substring(0,1).toUpperCase()+name.substring(1);
// middle.append("old.set"+string+ "(data.get"+string+"());\r\n");
// }
middle.append("\"final "+ classname +" test = Repository.save(old);\"+\r\n"
+ " \" return test;\"+"
+ "\"}\"+"
+ "\"}\"+");
br.close();
StringBuilder finalstring = new StringBuilder();
finalstring.append("\" StringBuilder service = new StringBuilder();\"+\r\n"
+ "\" service.append(\"+");
finalstring.append(intialize.toString());
finalstring.append(class_name.toString());
finalstring.append(middle.toString());
finalstring.append("\");");
//
// FileWriter fw = null;
// BufferedWriter bw = null;
// File masterBuilderFile = new File(newpath + "test" + ".java");
// if (!masterBuilderFile.exists()) {
// masterBuilderFile.createNewFile();
// }
// fw = new FileWriter(masterBuilderFile.getAbsoluteFile());
// bw = new BufferedWriter(fw);
// bw.write(finalstring.toString());
// bw.close();
return finalstring.toString();
}
public String UpdateController(String path, String classname) throws IOException {
String line = "";
String apiName ="Api";
StringBuilder intialize = new StringBuilder();
StringBuilder class_name = new StringBuilder();
StringBuilder middle = new StringBuilder();
StringBuilder end = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(path));
intialize.append("import org.springframework.beans.factory.annotation.Autowired;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.DeleteMapping;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.GetMapping;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.PathVariable;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.PostMapping;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.PutMapping;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.RequestBody;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.RequestParam;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.RestController;\"+\r\n"
+ "\" import org.springframework.web.bind.annotation.*;\"+\r\n");
intialize.append("\" @RequestMapping(value = " +"\"/"+ apiName+ "\")\"+\n"
+ "\" @RestController \"+\r\n ");
class_name.append("\" public class "+ classname +"Controller {\"+\r\n"
+ "\" @Autowired \"+ \r\n"
+ "\" private " + classname+ "Service Service; \"+\n");
middle.append( "\" @PostMapping("+"\"/" + classname+")\"+\r\n"
+ " \r\n"
+ " \" public " + classname+ " Savedata(@RequestBody " + classname+ " data) { \"+ \r\n"
+ " \" " + classname+ " save = Service.Savedata(data) ;\"+\r\n"
+ " \" return save;\"+\r\n"
+ " \"+ }\"+\r\n"
// + " \" \r\n \"+"
// + " \" \r\n \"+"
+ " \" @GetMapping(\"/" + classname+ "\")\"+\r\n"
+ " \" public List<" + classname+ "> getdetails() { \"+ \r\n"
+ " \" List<" + classname+ "> get = Service.getdetails(); \"+ \r\n"
+ " \" return get;\"+\r\n\" } \"+\n"
+ "\" @GetMapping(\"/" + classname+ "/{id}\")\"+\r\n"
+ " \" public " + classname+ " getdetailsbyId(@PathVariable Long id ) {\"+\r\n"
+ " \" " + classname+ " get = Service.getdetailsbyId(id);\"+\r\n"
+ "\" return get;\"+\r\n"
+ " \" }\"+\n"
+ "\" @DeleteMapping(\"/" + classname+ "/{id}\")\"+\r\n"
+ " \" public void delete_by_id(@PathVariable Long id ) {\"+\r\n"
+ " \" Service.delete_by_id(id);\"+\r\n"
// + " \" \"+ \r\n"
+ " \"\"+ }\n"
+ "\" @PutMapping(\"/" + classname+"/{id}\")\"+\r\n"
+ "\" public " + classname+ " update(@RequestBody " + classname+ " data,@PathVariable Long id ) {\"+\r\n"
+ " \" " + classname+ " update = Service.update(data,id);\"+\r\n"
+ "\" return update;\"+\r\n"
+ "\" }\"+\n\"}\"+");
br.close();
StringBuilder finalstring = new StringBuilder();
finalstring.append("\" StringBuilder controller = new StringBuilder();\"+\r\n"
+ "\"controller.append(");
finalstring.append(intialize.toString());
finalstring.append(class_name.toString());
finalstring.append(middle.toString());
// finalstring.append("}");
finalstring.append("\");");
//
// FileWriter fw = null;
// BufferedWriter bw = null;
// File masterBuilderFile = new File(newpath + "test" + ".java");
// if (!masterBuilderFile.exists()) {
// masterBuilderFile.createNewFile();
// }
// fw = new FileWriter(masterBuilderFile.getAbsoluteFile());
// bw = new BufferedWriter(fw);
// bw.write(finalstring.toString());
// bw.close();
return finalstring.toString();
}
}
@@ -0,0 +1,69 @@
package com.realnet.codeextractor.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.codeextractor.entity.NamingConvension;
import com.realnet.codeextractor.repository.NamingConvension_Repository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = { "Naming Convension" })
public class NamingConvensionController {
@Autowired
private NamingConvension_Repository namingConvensionRepository;
// @Autowired
// private TokenUtil tokenUtil;
// GET ALL
@ApiOperation(value = "List of Naming", response = NamingConvension.class)
@GetMapping("/naming-convension")
public ResponseEntity<?> getAll() {
List<NamingConvension> namingConvension = namingConvensionRepository.findAll();
return ResponseEntity.status(HttpStatus.OK).body(namingConvension);
}
// // GET BY ID
// @ApiOperation(value = "Get a Form", response = NamingConvension.class)
// @GetMapping("/form_setup/{id}")
// public ResponseEntity<NamingConvension> getFormsById(@PathVariable(value = "id") int id) {
// NamingConvension NamingConvension = NamingConvension_service.getById(id);
// return ResponseEntity.ok().body(NamingConvension);
// }
// // SAVE
// @ApiOperation(value = "naming-convension", response = NamingConvension.class)
// @PostMapping("/naming-convension")
// public ResponseEntity<NamingConvension> create(
// @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
// @Valid @RequestBody NamingConvension namingConvension) {
// NamingConvension savedNamingConvension = namingConvensionRepository.save(namingConvension);
// return ResponseEntity.status(HttpStatus.CREATED).body(savedNamingConvension);
// }
// // UPDATE
// @ApiOperation(value = "Update A Form", response = NamingConvension.class)
// @PutMapping("/form_setup/{id}")
// public ResponseEntity<NamingConvension> updateNamingConvension(
// @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
// @PathVariable(value = "id") Integer id, @Valid @RequestBody List<NamingConvension> NamingConvensionRequest) {
//
// NamingConvension namingConvension = namingConvensionRepository.findById(id).get();
//
//
// NamingConvension updatedNamingConvension = namingConvensionRepository.update(id, NamingConvension);
// return ResponseEntity.status(HttpStatus.ACCEPTED).body(updatedNamingConvension);
// }
}
@@ -0,0 +1,161 @@
package com.realnet.codeextractor.controller;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.codeextractor.service.Rule_library_service_gk;
@RestController
@RequestMapping("/codeextractor/rulelib_new")
public class RuleLibraryNew_gk {
@Autowired
private Rule_library_service_gk rule_service;
@GetMapping("/test13")
public ResponseEntity<?> getKeysInJsonUsingMaps(@RequestParam String keyword) throws ParseException, IOException {
//ENTITY
if (keyword.contains("entity_package")) {
String path ="C:\\Users\\Dell\\Desktop\\26 AUG\\CallingAnotherAPi\\testing/Abc.java";
String start ="package com";
String end =";\r\n"
+ "\r\n"
+ "import javax.persistence.GeneratedValue;";
String replaceWith ="Test_1";
rule_service.rule(path,start,end,replaceWith);
}
if (keyword.contains("ENTITYCLASS")) {
String path ="C:\\Users\\Dell\\Desktop\\26 AUG\\CallingAnotherAPi\\testing/Abc.java";
String start ="public class";
String end ="{";
String replaceWith ="Test";
rule_service.rule(path,start,end,replaceWith);
}
if (keyword.contains("entity_loop")) {
String path ="C:\\Users\\Dell\\Desktop\\26 AUG\\CallingAnotherAPi\\testing/Abc.java";
String start ="private int id;";
String end ="}";
String replaceWith =" \nfor (int i = 0; i < entityname.size(); i++) {\r\n"
+ " String string = entityname.get(i);\r\n"
+ " String lowerCase = string.replaceAll(\" \", \"_\").toLowerCase();\r\n"
+ " String add = \"\\n private \" + \"String\" + \" \" + lowerCase + \";\";\r\n"
+ " entityclass.append(add);\r\n"
+ " }";
rule_service.rule(path,start,end,replaceWith);
}
//REPOSITORY
if (keyword.contains("repo_class")) {
String path ="C:\\Users\\Dell\\Desktop\\Demo Code Extractor\\Abc_1665647440047_back\\Repository/AbcRepository.java";
String start ="public interface";
String end ="JpaRepository<Abc, Long> { ";
String replaceWith ="Test_1";
rule_service.rule(path,start,end,replaceWith);
}
//SERVICE
if (keyword.contains("service_class")) {
String path ="C:\\Users\\Dell\\Desktop\\Demo Code Extractor\\Abc_1665647440047_back\\Services/AbcService.java";
String start ="public class";
String end ="{";
String replaceWith ="Test_1";
rule_service.rule(path,start,end,replaceWith);
}
if (keyword.contains("service_body")) {
String path ="C:\\Users\\Dell\\Desktop\\Demo Code Extractor\\Abc_1665647440047_back\\Services/AbcService.java";
File staticFile = new File(path);
String fileString = FileUtils.readFileToString(staticFile, StandardCharsets.UTF_8);
int length = fileString.length();
String start ="@Autowired";
String end ="";
String replaceWith ="sericeclass.append(\"\\r\\n\" + \"private \" + table_name + addString + \"Repository \" + \"Repository;\\n\");\r\n"
+ "\r\n"
+ " sericeclass.append(\"public \" + table_name + addString + \" Savedata(\" + table_name + addString + \" data) {\\r\\n\"\r\n"
+ " + \" return Repository.save(data); \\r\\n\" + \" }\\r\\n\" + \"\\r\\n\" + \" \\r\\n\"\r\n"
+ " + \"public List<\" + table_name + addString + \"> getdetails() {\\r\\n\" + \" return (List<\"\r\n"
+ " + table_name + addString + \">) Repository.findAll();\\r\\n\" + \" }\\r\\n\" + \"\\r\\n\" + \"\\r\\n\"\r\n"
+ " + \"public \" + table_name + addString + \" getdetailsbyId(Long id) {\\r\\n\"\r\n"
+ " + \" return Repository.findById(id).get();\\r\\n\" + \" }\\r\\n\" + \"\\r\\n\" + \"\\r\\n\"\r\n"
+ " + \" public void delete_by_id(Long id) {\\r\\n\" + \" Repository.deleteById(id);\\r\\n\" + \"}\\r\\n\" + \"\\r\\n\"\r\n"
+ " + \"\\r\\n\");\r\n"
+ "\r\n"
+ " sericeclass.append(\"public \" + table_name + addString + \" update(\" + table_name + addString\r\n"
+ " + \" data,Long id) {\\n\" + \" \" + table_name + addString + \" old = Repository.findById(id).get();\\n\");\r\n"
+ " for (int i = 0; i < entityname.size(); i++) {\r\n"
+ " String name1 = entityname.get(i);\r\n"
+ " String name3 = name1.replaceAll(\" \", \"_\").toLowerCase();\r\n"
+ " String string = name3.substring(0, 1).toUpperCase() + name3.substring(1);\r\n"
+ " sericeclass.append(\"old.set\" + string + \"(data.get\" + string + \"());\\r\\n\");\r\n"
+ " }\r\n"
+ " sericeclass.append(\"final \" + table_name + addString + \" test = Repository.save(old);\\r\\n\"\r\n"
+ " + \" return test;\" + \"}}\" + \"\");\r\n"
+ "";
rule_service.rule(path,start,end,replaceWith);
}
//CONTROLLER
if (keyword.contains("controller_class")) {
String path ="C:\\Users\\Dell\\Desktop\\Demo Code Extractor\\Abc_1665647440047_back\\Controllers/AbcController.java";
String start ="public class";
String end ="{";
String replaceWith ="Test_1";
rule_service.rule(path,start,end,replaceWith);
}
if (keyword.contains("controller_body")) {
String path ="C:\\Users\\Dell\\Desktop\\Demo Code Extractor\\Abc_1665647440047_back\\Controllers/AbcController.java";
String start ="@Autowired";
String end ="";
String replaceWith ="controllerclass.append(\"\r\n"
+ " + \" private \" + table_name + addString + \"Service Service;\\n\\n\"\r\n"
+ "\r\n"
+ " + \" @PostMapping(\" + \"\\\"/\" + table_name + \"\\\")\\r\\n\" + \" public \" + table_name + addString\r\n"
+ " + \" Savedata(@RequestBody \" + table_name + addString + \" data) {\\r\\n\" + \" \" + table_name\r\n"
+ " + addString + \" save = Service.Savedata(data) ;\\r\\n\" + \" return save;\\r\\n\" + \" }\\r\\n\"\r\n"
+ " + \" \\r\\n\" + \" \\r\\n\" + \" @GetMapping(\\\"/\" + table_name + \"\\\")\\r\\n\" + \" public List<\"\r\n"
+ " + table_name + addString + \"> getdetails() {\\r\\n\" + \" List<\" + table_name + addString\r\n"
+ " + \"> get = Service.getdetails(); \\r\\n\" + \" return get;\\r\\n}\\n\" + \"@GetMapping(\\\"/\"\r\n"
+ " + table_name + \"/{id}\\\")\\r\\n\" + \" public \" + table_name + addString\r\n"
+ " + \" getdetailsbyId(@PathVariable Long id ) {\\r\\n\" + \" \" + table_name + addString\r\n"
+ " + \" get = Service.getdetailsbyId(id);\\r\\n\" + \" return get;\\r\\n\" + \" }\\n\" + \"@DeleteMapping(\\\"/\"\r\n"
+ " + table_name + \"/{id}\\\")\\r\\n\" + \" public void delete_by_id(@PathVariable Long id ) {\\r\\n\"\r\n"
+ " + \" Service.delete_by_id(id);\\r\\n\" + \" \\r\\n\" + \" }\\n\" + \"@PutMapping(\\\"/\" + table_name\r\n"
+ " + \"/{id}\\\")\\r\\n\" + \" public \" + table_name + addString + \" update(@RequestBody \" + table_name\r\n"
+ " + addString + \" data,@PathVariable Long id ) {\\r\\n\" + \" \" + table_name + addString\r\n"
+ " + \" update = Service.update(data,id);\\r\\n\" + \" return update;\\r\\n\" + \" }\\n}\");\r\n"
+ "";
rule_service.rule(path,start,end,replaceWith);
}
return new ResponseEntity<>("created", HttpStatus.CREATED);
}
}
@@ -0,0 +1,378 @@
package com.realnet.codeextractor.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.codeextractor.entity.Rn_Bcf_Exception_Rules;
import com.realnet.codeextractor.entity.Rn_Bcf_Rules;
import com.realnet.codeextractor.entity.RuleCopyDTO;
import com.realnet.codeextractor.response.ExceptionRuleLibraryResponse;
import com.realnet.codeextractor.response.RuleLibraryResponse;
import com.realnet.codeextractor.service.Rn_Bcf_Exception_Rule_Library_Service;
import com.realnet.codeextractor.service.Rn_Bcf_Rule_Library_Service;
import com.realnet.fnd.entity.Error;
import com.realnet.fnd.entity.ErrorPojo;
import com.realnet.fnd.entity.Success;
import com.realnet.fnd.entity.SuccessPojo;
import com.realnet.userDTO.User;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserService;
import com.realnet.utils.Constant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = { "Rule Library" })
public class Rule_Library_Controller {
@Autowired
private AppUserService userService;
@Autowired
private Rn_Bcf_Rule_Library_Service ruleLibraryService;
@Autowired
private Rn_Bcf_Exception_Rule_Library_Service exceptionRuleLibraryService;
// @Autowired
// private TokenUtil tokenUtil;
// ==== RULE LIBRARY AND EXCEPTION RULE LIBRARY REST APIS ==== //
// COPY RULES
@ApiOperation(value = "Add A New Rule", response = Rn_Bcf_Rules.class)
@PostMapping("/rule-copy")
public ResponseEntity<?> copyRule(@Valid @RequestBody RuleCopyDTO ruleReq) {
AppUser user = userService.getLoggedInUser();
Long userId = user.getUserId();
Long accId = user.getAccount().getAccount_id();
String from_tech_stack = ruleReq.getFrom_tech_stack();
String from_object_type = ruleReq.getFrom_object_type();
String from_sub_object_type = ruleReq.getFrom_sub_object_type();
String to_tech_stack = ruleReq.getTo_tech_stack();
String to_object_type = ruleReq.getTo_object_type();
String to_sub_object_type = ruleReq.getTo_sub_object_type();
// GET ALL RULES
List<Rn_Bcf_Rules> rules = ruleLibraryService.copyRules2(from_tech_stack, from_object_type, from_sub_object_type);
log.debug("RULE COPPIED {}", rules);
for (Rn_Bcf_Rules rule : rules) {
Rn_Bcf_Rules newRule = new Rn_Bcf_Rules();
newRule.setCreatedBy(userId);
newRule.setAccountId(accId);
newRule.setGroup_id(rule.getGroup_id());
newRule.setFile_code(rule.getFile_code());
newRule.setRule_name(rule.getRule_name());
newRule.setRule_type(rule.getRule_type());
newRule.setTech_stack(to_tech_stack);
newRule.setObject_type(to_object_type);
newRule.setSub_object_type(to_sub_object_type);
newRule.setIdentifier_start_string(rule.getIdentifier_start_string());
newRule.setIdentifier_end_string(rule.getIdentifier_end_string());
newRule.setReplacement_string(rule.getReplacement_string());
Rn_Bcf_Rules savedRule = ruleLibraryService.save(newRule);
log.debug("SAVED RULE {}", savedRule);
if (savedRule == null) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.RULE_NOT_CREATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.RULE_CREATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
}
// GET ALL
@ApiOperation(value = "List of Rules", response = RuleLibraryResponse.class)
@GetMapping("/rule-library")
public RuleLibraryResponse getAllRules(
@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
@RequestParam(value = "size", defaultValue = "20", required = false) Integer size) {
RuleLibraryResponse resp = new RuleLibraryResponse();
Pageable paging = PageRequest.of(page, size);
Page<Rn_Bcf_Rules> result = ruleLibraryService.getAll(paging);
resp.setPageStats(result, true);
resp.setItems(result.getContent());
return resp;
}
// GET BY ID
@ApiOperation(value = "Get a Rule", response = Rn_Bcf_Rules.class)
@GetMapping("/rule-library/{id}")
public ResponseEntity<Rn_Bcf_Rules> getRuleDetails(@PathVariable(value = "id") int id) {
Rn_Bcf_Rules rule = ruleLibraryService.getById(id);
return ResponseEntity.ok().body(rule);
}
// SAVE
@ApiOperation(value = "Add A New Rule", response = Rn_Bcf_Rules.class)
@PostMapping("/rule-library")
public ResponseEntity<?> createRule(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
@Valid @RequestBody Rn_Bcf_Rules bcf_rule) {
// String userId = tokenUtil.getUserId(authToken);
// rn_forms_setup.setCreatedBy(userId);
// rn_forms_setup.setAccountId(userId);
Long userId = userService.getLoggedInUserId();
bcf_rule.setCreatedBy(userId);
Rn_Bcf_Rules savedRule = ruleLibraryService.save(bcf_rule);
if (savedRule == null) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.RULE_NOT_CREATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.RULE_CREATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
}
/* for testing purpose */
// SAVE LIST OF DATA
@ApiOperation(value = "Add AList Of New Rules", response = Rn_Bcf_Rules.class)
@PostMapping("/rule-library/all")
public ResponseEntity<?> createListOfRules(@RequestBody List<@Valid Rn_Bcf_Rules> bcf_rule) {
for (Rn_Bcf_Rules rule : bcf_rule) {
Long userId = userService.getLoggedInUserId();
rule.setCreatedBy(userId);
Rn_Bcf_Rules savedRule = ruleLibraryService.save(rule);
if (savedRule == null) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.RULE_NOT_CREATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.RULE_CREATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
}
// UPDATE
@ApiOperation(value = "Update A Form", response = Rn_Bcf_Rules.class)
@PutMapping("/rule-library/{id}")
public ResponseEntity<?> updateRule(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
@PathVariable(value = "id") Integer id, @Valid @RequestBody Rn_Bcf_Rules rule) {
// String userId = tokenUtil.getUserId(authToken);
// rn_forms_setup.setUpdatedBy(userId);
Long userId = userService.getLoggedInUserId();
rule.setUpdatedBy(userId);
Rn_Bcf_Rules updatedRule = ruleLibraryService.updateById(id, rule);
if (id != updatedRule.getId()) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.RULE_NOT_UPDATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.RULE_UPDATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// DELETE
@DeleteMapping("/rule-library/{id}")
public ResponseEntity<?> deleteRule(@PathVariable(value = "id") Integer id) {
boolean deleted = ruleLibraryService.deleteById(id);
if (deleted) {
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.RULE_DELETED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
} else {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.RULE_NOT_DELETED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
}
// =========== EXCEPTION RULE =================== //
// GET ALL
@ApiOperation(value = "List of Exception Rules", response = ExceptionRuleLibraryResponse.class)
@GetMapping("/exception-rule-library")
public ExceptionRuleLibraryResponse getAllExceptionRules(
@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
@RequestParam(value = "size", defaultValue = "20", required = false) Integer size) {
ExceptionRuleLibraryResponse resp = new ExceptionRuleLibraryResponse();
Pageable paging = PageRequest.of(page, size);
Page<Rn_Bcf_Exception_Rules> result = exceptionRuleLibraryService.getAll(paging);
resp.setPageStats(result, true);
resp.setItems(result.getContent());
return resp;
}
// GET BY ID
@ApiOperation(value = "Get a Exception Rule", response = Rn_Bcf_Exception_Rules.class)
@GetMapping("/exception-rule-library/{id}")
public ResponseEntity<Rn_Bcf_Exception_Rules> getExceptionRuleDetails(@PathVariable(value = "id") int id) {
Rn_Bcf_Exception_Rules rule = exceptionRuleLibraryService.getById(id);
return ResponseEntity.ok().body(rule);
}
// SAVE
@ApiOperation(value = "Add A New Rule", response = Rn_Bcf_Exception_Rules.class)
@PostMapping("/exception-rule-library")
public ResponseEntity<?> createExceptionRule(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
@Valid @RequestBody Rn_Bcf_Exception_Rules bcf_rule) {
// String userId = tokenUtil.getUserId(authToken);
// rn_forms_setup.setCreatedBy(userId);
// rn_forms_setup.setAccountId(userId);
Long userId = userService.getLoggedInUserId();
bcf_rule.setCreatedBy(userId);
Rn_Bcf_Exception_Rules savedRule = exceptionRuleLibraryService.save(bcf_rule);
if (savedRule == null) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXCEPTION_RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.EXCEPTION_RULE_NOT_CREATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXCEPTION_RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.EXCEPTION_RULE_CREATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
}
/* for testing purpose */
// SAVE LIST OF DATA
@ApiOperation(value = "Add A New Rule", response = Rn_Bcf_Exception_Rules.class)
@PostMapping("/exception-rule-library/all")
public ResponseEntity<?> createListOfExceptionRule(@RequestBody List<@Valid Rn_Bcf_Exception_Rules> bcf_rule) {
Long userId = userService.getLoggedInUserId();
for (Rn_Bcf_Exception_Rules rule : bcf_rule) {
rule.setCreatedBy(userId);
Rn_Bcf_Exception_Rules savedRule = exceptionRuleLibraryService.save(rule);
if (savedRule == null) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXCEPTION_RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.EXCEPTION_RULE_NOT_CREATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXCEPTION_RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.EXCEPTION_RULE_CREATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
}
// UPDATE
@ApiOperation(value = "Update A Form", response = Rn_Bcf_Exception_Rules.class)
@PutMapping("/exception-rule-library/{id}")
public ResponseEntity<?> updateExcetionRule(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
@PathVariable(value = "id") Integer id, @Valid @RequestBody Rn_Bcf_Exception_Rules rule) {
// String userId = tokenUtil.getUserId(authToken);
// rn_forms_setup.setUpdatedBy(userId);
Long userId = userService.getLoggedInUserId();
rule.setUpdatedBy(userId);
Rn_Bcf_Exception_Rules updatedRule = exceptionRuleLibraryService.updateById(id, rule);
if (id != updatedRule.getId()) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXCEPTION_RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.EXCEPTION_RULE_NOT_UPDATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXCEPTION_RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.EXCEPTION_RULE_UPDATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// DELETE
@DeleteMapping("/exception-rule-library/{id}")
public ResponseEntity<?> deleteExceptionRule(@PathVariable(value = "id") Integer id) {
boolean deleted = exceptionRuleLibraryService.deleteById(id);
if (deleted) {
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXCEPTION_RULE_LIBRARY_API_TITLE);
success.setMessage(Constant.EXCEPTION_RULE_DELETED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
} else {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXCEPTION_RULE_LIBRARY_API_TITLE);
error.setMessage(Constant.EXCEPTION_RULE_NOT_DELETED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
}
}
@@ -0,0 +1,53 @@
package com.realnet.codeextractor.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.codeextractor.entity.Rule_library_keyword;
import com.realnet.codeextractor.service.Rule_library_keywordService;
@RequestMapping(value = "/code_extractor/rule_keyword")
@RestController
public class Rule_library_keywordController {
@Autowired
private Rule_library_keywordService Service;
@PostMapping("/Rule_library_keyword")
public Rule_library_keyword Savedata(@RequestBody Rule_library_keyword data) {
Rule_library_keyword save = Service.Savedata(data);
return save;
}
@GetMapping("/Rule_library_keyword")
public List<Rule_library_keyword> getdetails() {
List<Rule_library_keyword> get = Service.getdetails();
return get;
}
@GetMapping("/Rule_library_keyword/{id}")
public Rule_library_keyword getdetailsbyId(@PathVariable Integer id) {
Rule_library_keyword get = Service.getdetailsbyId(id);
return get;
}
@DeleteMapping("/Rule_library_keyword/{id}")
public void delete_by_id(@PathVariable Integer id) {
Service.delete_by_id(id);
}
@PutMapping("/Rule_library_keyword/{id}")
public Rule_library_keyword update(@RequestBody Rule_library_keyword data, @PathVariable Integer id) {
Rule_library_keyword update = Service.update(data, id);
return update;
}
}
@@ -0,0 +1,164 @@
package com.realnet.codeextractor.controller;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.codeextractor.entity.Rn_Bcf_Extractor;
import com.realnet.codeextractor.entity.Rn_Bcf_Extractor_Params;
import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Params_Service;
import com.realnet.codeextractor.service.Rn_Bcf_Extractor_Service;
import com.realnet.fnd.entity.ErrorPojo;
import com.realnet.fnd.entity.Success;
import com.realnet.fnd.entity.SuccessPojo;
import com.realnet.utils.Constant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = { "Code Extractor" })
public class StaticCodeExtractionController {
@Value("${projectPath}")
private String projectPath;
@Autowired
private Rn_Bcf_Extractor_Service bcf_extractorService;
@Autowired
private Rn_Bcf_Extractor_Params_Service bcf_extractor_params_service;
@ApiOperation(value = "Static Code Extraction")
@GetMapping(value = "/static_code_extraction")
public ResponseEntity<?> staticCodeExtraction(@RequestParam(value = "header_id") Integer headerId) throws IOException {
Rn_Bcf_Extractor bcf_extractor = bcf_extractorService.getById(headerId);
List<Rn_Bcf_Extractor_Params> bcf_extractor_params_t_values = bcf_extractor.getRn_bcf_extractor_Params();
log.debug("bcf_extractor_params_t_values {}", bcf_extractor_params_t_values);
List<Rn_Bcf_Extractor_Params> bcf_extractor_params = bcf_extractor_params_service.getByHeaderId(headerId);
log.debug("bcf_extractor_params {}", bcf_extractor_params);
for (Rn_Bcf_Extractor_Params params : bcf_extractor_params_t_values) {
String path = params.getMoved_address_string();
boolean is_extraction_enabled = params.isIs_extraction_enabled();
boolean is_creation_enabled = params.isIs_creation_enabled();
if (is_creation_enabled && is_extraction_enabled) {
try {
File file = new File(path);
// STEP 1. CONVERT THE FILE INTO STRING
String fileContents = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
//if (!fileContents.isEmpty()) {
fileContents = fileContents.replace("\\", "\\\\");
fileContents = fileContents.replace("\"", (File.separator + "\""));
// STEP 2. CREATE A TEMP FILE AND WRITE THE CONVERTED STRING
String parentPath = file.getParent();
String name = file.getName();
String fileName = "temp_" + name;
File tempFile = new File(parentPath + File.separator + fileName);
if (tempFile.createNewFile()) {
System.out.println("------ TEMP FILE CREATED-------\n" + tempFile.getAbsolutePath());
}
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
writer.write(fileContents);
writer.close();
System.out.println("Successfully wrote to the file...");
StringBuilder code = new StringBuilder();
// STEP 3. READ THE TEMP FILE AND MAKE IT "STRING"
BufferedReader br = new BufferedReader(new FileReader(tempFile));
String line = br.readLine();
while (line != null) {
code.append("\"" + line + "\" + \"\\r\\n\" + \r\n");
line = br.readLine();
}
br.close();
// STEP 4: REMOVING WHITE SPACE
String finalString = code.toString().trim();
if (!finalString.isEmpty()) {
// STEP 5: REMOVING LAST CHARS(+ "\r\n" +)
finalString = finalString.substring(0, finalString.length() - 10);
// System.out.println(finalString);
}
boolean deleted = tempFile.delete();
if(deleted) {
log.info(tempFile.getName(), "{} File deleted");
}
// MODIFIED NAME
// CONVERT EVERY FILE INTO .JAVA FILE
// String ext = FilenameUtils.getExtension(name);
// String fileNameWithOutExt = FilenameUtils.removeExtension(name);
String ConvertedFileName = "SE_" + name;
// STAIC CODE OUTPUT DIRECTORY & PATH
String staticDirString = parentPath + File.separator + "static_code";
File staticDir = new File(staticDirString);
if (!staticDir.exists()) {
staticDir.mkdir();
}
File staticFile = new File(staticDirString + File.separator + ConvertedFileName);
System.out.println("FILES WITH STATIC CODE DIRECTORY = " + staticFile);
if (!staticFile.exists()) {
staticFile.createNewFile();
}
BufferedWriter writer2 = new BufferedWriter(new FileWriter(staticFile.getAbsoluteFile()));
writer2.write(finalString);
writer2.close();
/*
* //===========DELETE MAIN FILES=========== if(deleted) { file.delete();
* logger.info("Deleted = " + file.getName() + " File"); }
*/
//}
} catch (FileNotFoundException e) {
log.error("File Not Found... " + e);
ErrorPojo errorPojo = new ErrorPojo();
com.realnet.fnd.entity.Error error = new com.realnet.fnd.entity.Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.STATIC_EXTRACTION_FAILED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
}
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.STATIC_EXTRACTION_SUCCESS);
successPojo.setSuccess(success);
log.debug("Response {} ", successPojo);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
}
@@ -0,0 +1,295 @@
package com.realnet.codeextractor.controller;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.realnet.codeextractor.entity.ActiveTechStack_DTO;
import com.realnet.codeextractor.entity.Rn_Bcf_Technology_Stack1;
import com.realnet.codeextractor.repository.Rn_Bcf_TechnologyStack_Repository1;
import com.realnet.codeextractor.response.TechnologyStackResponse;
import com.realnet.codeextractor.service.Rn_Bcf_TechnologyStack_Service;
import com.realnet.fnd.entity.Error;
import com.realnet.fnd.entity.ErrorPojo;
import com.realnet.fnd.entity.Success;
import com.realnet.fnd.entity.SuccessPojo;
import com.realnet.fnd.service.FileStorageService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserService;
import com.realnet.utils.Constant;
import com.realnet.utils.RealNetUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
@JsonIgnoreProperties(ignoreUnknown = true)
@Slf4j
@RestController
@RequestMapping(value = "/codeextractor/technologystack", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = { "Technology Stack" })
public class TechnologyStackController_codeextractor {
@Autowired
private AppUserService userService;
@Autowired
private FileStorageService fileStorageService;
@Autowired
private Rn_Bcf_TechnologyStack_Service technologyStackService;
@Autowired
private Rn_Bcf_TechnologyStack_Repository1 technologyStackRepo;
@Value("${projectPath}")
private String projectPath;
// GET ALL SORTED AND PAGINATED DATA
@ApiOperation(value = "List of Technology Stack", response = Rn_Bcf_Technology_Stack1.class)
@GetMapping("/technology-stack")
public TechnologyStackResponse getTechnologyStack(
@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
@RequestParam(value = "size", defaultValue = "20", required = false) Integer size) {
// sorted data
Pageable paging = PageRequest.of(page, size, Sort.by(Constant.SORT_BY_CREATION_DATE).descending());
Page<Rn_Bcf_Technology_Stack1> result = technologyStackService.getAll(paging);
System.out.println("ganesh bute"+result.getContent());
TechnologyStackResponse resp = new TechnologyStackResponse();
resp.setPageStats(result, true);
resp.setItems(result.getContent());
return resp;
}
// GET BY ID
@ApiOperation(value = "Get A Technology Stack", response = Rn_Bcf_Technology_Stack1.class)
@GetMapping("/technology-stack/{id}")
public ResponseEntity<?> getTechnologyStackDetails(@PathVariable(value = "id") int id) {
Rn_Bcf_Technology_Stack1 bcf_tech_stack = technologyStackService.getById(id);
// Map<String, Rn_Bcf_Technology_Stack1> extractorMap =
// Collections.singletonMap("extractior", bcf_extractor);
// return new ResponseEntity<Map<String, Rn_Bcf_Technology_Stack1>>(extractorMap,
// HttpStatus.OK);
// return ResponseEntity.ok().body(bcf_extractor);
return new ResponseEntity<Rn_Bcf_Technology_Stack1>(bcf_tech_stack, HttpStatus.OK);
}
// ========= SAVE AND UNZIP FILE AND MOVE TO A SPECIFIC PATH ========
@ApiOperation(value = "Add new Technology Stack")
@PostMapping(value = "/technology-stack")
public ResponseEntity<?> saveTechnologyStack(// @Valid @RequestBody Rn_Bcf_Technology_Stack1 bcf_extractor,
@RequestParam(value = "bcf_technology_stack", required = true) String techStackRequest,
@RequestParam(value = "file", required = true) MultipartFile file)
throws IOException, JsonParseException, JsonMappingException {
System.out.println("techStackRequest = " + techStackRequest);
System.out.println("file = " + file.getOriginalFilename());
log.debug("techStackRequest => {} ", techStackRequest);
log.debug("file => {} ", file.getOriginalFilename());
ObjectMapper mapper = new ObjectMapper();
mapper.configOverride(FileDescriptor.class).setIsIgnoredType(true);
//mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
mapper.setVisibility(mapper.getVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY));
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
Rn_Bcf_Technology_Stack1 bcf_tech_stack = mapper.readValue(techStackRequest, Rn_Bcf_Technology_Stack1.class);
log.debug("bcf_tech_stack => {}", bcf_tech_stack);
AppUser loggedInUser = userService.getLoggedInUser();
bcf_tech_stack.setAccountId(loggedInUser.getAccount().getAccount_id());
bcf_tech_stack.setCreatedBy(loggedInUser.getUserId());
String techStackKey = RealNetUtils.getTechnologyStackKey(bcf_tech_stack.getTech_stack());
bcf_tech_stack.setTech_stack_key(techStackKey);
// upload to directory
String uploadPath = projectPath.concat("/src/main/resources/technology-stack-zip-uploads/");
fileStorageService.uploadFile(file, uploadPath);
String fileName = file.getOriginalFilename();
String folderName = fileName.substring(0, fileName.lastIndexOf("."));
System.out.println("UPLOAD PATH = " + uploadPath + "\nFILE NAME = " + fileName + "\nFile Size = " + file.getSize());
// SAVE ZIP FILE NAME INTO DATABASE
bcf_tech_stack.setBase_prj_file_name(folderName);
bcf_tech_stack.setActive(false);
System.out.println("before save");
Rn_Bcf_Technology_Stack1 savedTechnology = technologyStackService.save(bcf_tech_stack);
System.out.println("after save");
if (savedTechnology == null) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.TECHNOLOGY_STACK_API_TITLE);
error.setMessage(Constant.TECHNOLOGY_STACK_NOT_CREATED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
/*
* ZIP TO UNZIP
*/
// ZIP FILE BASE PATH
String zipFilePath = uploadPath + fileName;
String tech_stack = savedTechnology.getTech_stack();
// UNZIP DESTINATION PATH
String destPath = projectPath.concat("/BaseProject/" + tech_stack);
File path = new File(destPath);
if (!path.exists()) {
path.mkdirs();
}
System.out.println("ZIP FILE PATH = " + zipFilePath + "\nDESTINATION PATH = " + destPath);
try {
ZipFile zipFile = new ZipFile(zipFilePath);
zipFile.extractAll(destPath);
} catch (ZipException e) {
e.printStackTrace();
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.TECHNOLOGY_STACK_API_TITLE);
error.setMessage(Constant.UNZIP_EXCEPTION);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.TECHNOLOGY_STACK_API_TITLE);
success.setMessage(Constant.TECHNOLOGY_STACK_CREATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.CREATED);
}
// UPDATE
@ApiOperation(value = "Update Technology Stack", response = Rn_Bcf_Technology_Stack1.class)
@PutMapping("/technology-stack/{id}")
public ResponseEntity<?> updateTechnology(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authToken,
@PathVariable(value = "id") int id, @Valid @RequestBody Rn_Bcf_Technology_Stack1 bcf_tech_stack) {
AppUser loggedInUser = userService.getLoggedInUser();
bcf_tech_stack.setUpdatedBy(loggedInUser.getUserId());
Rn_Bcf_Technology_Stack1 updatedTech = technologyStackService.updateById(id, bcf_tech_stack);
if (bcf_tech_stack.getId() != updatedTech.getId()) {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.EXTRACTOR_API_TITLE);
error.setMessage(Constant.EXTRACTOR_NOT_DELETED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.EXTRACTOR_API_TITLE);
success.setMessage(Constant.EXTRACTOR_UPDATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// DELETE
@DeleteMapping("/technology-stack/{id}")
public ResponseEntity<?> deleteTechnologyStack(@PathVariable(value = "id") int id) {
boolean deleted = technologyStackService.deleteById(id);
if (deleted) {
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.TECHNOLOGY_STACK_API_TITLE);
success.setMessage(Constant.TECHNOLOGY_STACK_DELETED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
} else {
ErrorPojo errorPojo = new ErrorPojo();
Error error = new Error();
error.setTitle(Constant.TECHNOLOGY_STACK_API_TITLE);
error.setMessage(Constant.TECHNOLOGY_STACK_NOT_DELETED);
errorPojo.setError(error);
return new ResponseEntity<ErrorPojo>(errorPojo, HttpStatus.EXPECTATION_FAILED);
}
}
// ACTIVE
@GetMapping(value = "/tech-stack-active")
public ResponseEntity<?> technologyActive(@RequestParam(value = "id") int id) throws IOException {
//log.info("technologyActive controller start {}", id);
AppUser loggedInUser = userService.getLoggedInUser();
Rn_Bcf_Technology_Stack1 tech_stack = technologyStackService.getById(id);
log.debug("TECH STACK : {} ", tech_stack);
if (tech_stack.isActive() == false) {
tech_stack.setActive(true);
} else if (tech_stack.isActive()) {
tech_stack.setActive(false);
}
//tech_stack.setActive(!tech_stack.isActive()); // LOL
tech_stack.setUpdatedBy(loggedInUser.getUserId());
Rn_Bcf_Technology_Stack1 tech = technologyStackService.save(tech_stack);
log.debug("UPDATED TECH STACK : {} ", tech);
System.out.println("UPDATED TECH STACK : " + tech);
SuccessPojo successPojo = new SuccessPojo();
Success success = new Success();
success.setTitle(Constant.TECHNOLOGY_STACK_API_TITLE);
success.setMessage(Constant.TECHNOLOGY_STACK_UPDATED_SUCCESSFULLY);
successPojo.setSuccess(success);
return new ResponseEntity<SuccessPojo>(successPojo, HttpStatus.OK);
}
// get activate technology stack list (id and name)
@ApiOperation(value = "Get Activate Technology Stack List ", response = ActiveTechStack_DTO.class)
@GetMapping("/active-technology")
@ResponseBody
public List<ActiveTechStack_DTO> getActiveTechnology() {
//List<Rn_Bcf_Technology_Stack1> technologyStack = technologyStackService.getAll();
List<ActiveTechStack_DTO> activeTechDTO = technologyStackService.getListOfActivateTechnology();
return activeTechDTO;
}
}