html builder

This commit is contained in:
string 2025-05-13 09:12:21 +05:30
parent 2caa796523
commit 67b719e277
11 changed files with 398 additions and 54 deletions

View File

@ -0,0 +1,61 @@
package com.realnet.Heplers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import com.realnet.fnd.response.EntityResponse;
@Service
public class FileHelper {
public void createFile(String folderPath, String pageName, String htmlContent) throws IOException {
File file = new File(folderPath + "/" + pageName);
// Ensure directory exists
File parentDir = file.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
// Create new file
if (!file.exists()) {
file.createNewFile();
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(htmlContent);
}
System.out.println("✅ File created: " + file.getAbsolutePath());
}
public ResponseEntity<?> readFile(String filepath, String filename) {
File file = new File(filepath + "/" + filename + ".html");
System.out.println(" reading file : " + file);
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("❌ File not found: " + file.getAbsolutePath());
}
try {
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
return ResponseEntity.ok(content);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error reading file: " + e.getMessage());
}
}
}

View File

@ -3,6 +3,7 @@ package com.realnet.OpenAi.Controller;
import java.util.Map;
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.PathVariable;
@ -15,6 +16,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.realnet.OpenAi.Services.HtmlBuilder4;
import com.realnet.OpenAi.Services.HtmlBuilder5;
import com.realnet.OpenAi.Services.HtmlGenerTorService;
import com.realnet.dlf.Entity.Design_lbrary;
import com.realnet.dlf.Services.Design_lbraryService;
@ -49,21 +51,40 @@ public class HtmlGeneratorController {
// return ResponseEntity.ok(result);
// }
@PostMapping("/generate")
public ResponseEntity<?> generateHtml(@RequestBody Map<String, Object> request) {
try {
Object jsonStructure = request.get("jsonStructure");
// @PostMapping("/generate")
// public ResponseEntity<?> generateHtml(@RequestBody Map<String, Object> request) {
// try {
// Object jsonStructure = request.get("jsonStructure");
//
// if (jsonStructure == null) {
// return ResponseEntity.badRequest().body("Missing 'jsonStructure' in request.");
// }
//
// String html = HtmlBuilder5.buildHtml(jsonStructure);
//// String html = HtmlService.buildHtml(jsonStructure);
// return ResponseEntity.ok(new EntityResponse(html));
// } catch (Exception e) {
// e.printStackTrace();
// return ResponseEntity.status(500).body("⚠️ Failed to generate HTML due to server error.");
// }
// }
if (jsonStructure == null) {
return ResponseEntity.badRequest().body("Missing 'jsonStructure' in request.");
@PostMapping("/generate")
public ResponseEntity<?> generateHtml(@RequestBody Map<String, Object> jsonInput) {
try {
StringBuilder html = new StringBuilder();
for (Map.Entry<String, Object> entry : jsonInput.entrySet()) {
Map<String, Object> root = (Map<String, Object>) entry.getValue();
root.put("element", entry.getKey()); // use key as tag like "section"
html.append(HtmlBuilder5.buildHtml(root));
}
// String html = HtmlBuilder4.buildHtml(jsonStructure);
String html = HtmlService.buildHtml(jsonStructure);
return ResponseEntity.ok(new EntityResponse(html));
return ResponseEntity.ok(new EntityResponse(html.toString()));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(500).body("⚠️ Failed to generate HTML due to server error.");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error generating HTML: " + e.getMessage());
}
}
@ -83,8 +104,8 @@ public class HtmlGeneratorController {
return ResponseEntity.badRequest().body("Missing 'jsonStructure' in request.");
}
// String html = HtmlBuilder4.buildHtml(jsonStructure);
String html = HtmlService.buildHtml(jsonStructure);
String html = HtmlBuilder4.buildHtml(jsonStructure);
// String html = HtmlService.buildHtml(jsonStructure);
return ResponseEntity.ok(new EntityResponse(html));
} catch (Exception e) {
e.printStackTrace();

View File

@ -0,0 +1,208 @@
package com.realnet.OpenAi.Services;
import java.util.List;
import java.util.Map;
public class HtmlBuilder5 {
public static String buildHtml(Object nodeObj) {
if (!(nodeObj instanceof Map))
return "";
Map<String, Object> node = (Map<String, Object>) nodeObj;
StringBuilder html = new StringBuilder();
// CASE: {"div": { ... }} or {"section": { ... }}
if (node.size() == 1 && !node.containsKey("element")) {
Map.Entry<String, Object> entry = node.entrySet().iterator().next();
String tag = entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
((Map<String, Object>) value).put("element", tag);
return buildHtml(value);
}
}
// Standard tag name (from 'element' key)
String tag = getString(node, "element", "div");
// Start tag
html.append("<").append(tag);
String clazz = getString(node, "class", "");
if (!clazz.isEmpty()) {
html.append(" class=\"").append(clazz).append("\"");
}
html.append(">");
// Text content
String text = getString(node, "text", "");
if (!text.isEmpty()) {
html.append(text);
}
// placehoder content
// String placeholder = getString(node, "placeholder", "");
// if (!placeholder.isEmpty()) {
// html.append(" placeholder=\"").append(clazz).append("\"");
// }
// Single icon
Object iconObj = node.get("icon");
if (iconObj instanceof String) {
String iconClass = iconObj.toString();
String emoji = getIconEmoji(iconClass);
html.append("<i class=\"").append(iconClass).append("\">").append(emoji).append("</i>");
}
// Multiple icons
Object iconsObj = node.get("icons");
if (iconsObj instanceof List) {
List<?> icons = (List<?>) iconsObj;
for (Object icon : icons) {
if (icon instanceof String) {
String iconClass = icon.toString();
String emoji = getIconEmoji(iconClass);
html.append("<i class=\"").append(iconClass).append("\">").append(emoji).append("</i>");
}
}
}
// Title
if (node.containsKey("title")) {
Object titleObj = node.get("title");
if (titleObj instanceof Map) {
// Expected: title is an object with element/class/text
html.append(buildHtml(titleObj));
} else {
// Fallback: use default <h3> if element not defined
html.append("<h3>").append(titleObj.toString()).append("</h3>");
}
}
// Description
if (node.containsKey("description")) {
Object descObj = node.get("description");
if (descObj instanceof Map) {
html.append(buildHtml(descObj));
} else {
html.append("<p>").append(descObj.toString()).append("</p>");
}
}
// Handle children
Object children = node.get("children");
if (children instanceof List) {
for (Object child : (List<Object>) children) {
if (child instanceof Map) {
html.append(buildHtml((Map<String, Object>) child));
}
}
} else if (children instanceof Map) {
html.append(buildHtml((Map<String, Object>) children));
}
// Handle content (like in 'section' root)
Object content = node.get("content");
if (content instanceof List) {
for (Object child : (List<Object>) content) {
if (child instanceof Map) {
html.append(buildHtml((Map<String, Object>) child));
}
}
} else if (content instanceof Map) {
html.append(buildHtml((Map<String, Object>) content));
}
// Close tag
html.append("</").append(tag).append(">");
return html.toString();
}
private static String getIconEmoji(String label) {
label = label.toLowerCase();
if (label.contains("facebook"))
return "📘";
if (label.contains("instagram"))
return "📷";
if (label.equals("x"))
return "𝕏";
if (label.contains("search"))
return "🔍";
if (label.contains("profile"))
return "👤";
if (label.contains("twitter"))
return "🐦";
if (label.contains("linkedin"))
return "🔗";
if (label.contains("youtube"))
return "▶️";
if (label.contains("fas fa-cube"))
return "📦";
if (label.contains("cube"))
return "📦";
return "";
}
private static String formatKey(String key) {
key = key.replaceAll("([a-z])([A-Z])", "$1 $2"); // camelCase to space
key = key.substring(0, 1).toUpperCase() + key.substring(1); // capitalize first
return key.replace("-", " ");
}
private static void appendStyle(StringBuilder style, String key, Object value) {
if (value != null) {
style.append(key).append(":").append(value).append("; ");
}
}
private static String getWidgetIcon(String widget) {
widget = widget.toLowerCase();
if (widget.contains("search"))
return "🔍";
if (widget.contains("recent"))
return "📝";
if (widget.contains("newsletter"))
return "📬";
return "📦";
}
private static String getString(Map<String, Object> map, String key, String defaultValue) {
Object val = map.get(key);
return val instanceof String ? (String) val : defaultValue;
}
private static String renderImageDiv(Map<String, Object> data) {
StringBuilder html = new StringBuilder();
// Get attributes from JSON
// String className = getString(data, "class", "placeholder-img");
String className = "placeholder-img";
String src = getString(data, "src", "/src/assets/images/place.png");
String width = getString(data, "width", ""); // optional
String height = getString(data, "height", ""); // optional
// Fallback to default image if src is missing or blank
if (src.isEmpty()) {
src = "/src/assets/images/place.png";
}
// Build style
StringBuilder style = new StringBuilder();
style.append("background-image: url('").append(src).append("');");
// Add inline height/width only if provided, else CSS will handle default
if (!width.isEmpty()) {
style.append(" width: ").append(width).append(";");
}
if (!height.isEmpty()) {
style.append(" height: ").append(height).append(";");
}
// Return final div
html.append("<div class=\"").append(className).append("\" style=\"").append(style).append("\"></div>");
return html.toString();
}
}

View File

@ -1,8 +1,6 @@
package com.realnet.OpenAi.Services;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@ -13,6 +11,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.realnet.Heplers.FileHelper;
import com.realnet.utils.PortConstant;
@Service
@ -21,6 +20,9 @@ public class SureopsService {
@Value("${projectPath}")
private String projectPath;
@Autowired
private FileHelper fileHelper;
@Autowired
private Script_Making script_serviceMaking;
@ -35,52 +37,27 @@ public class SureopsService {
String PRJ_NAME = list.get(0);
String folderPath = projectPath + File.separator + projId + File.separator + "index" + File.separator
+ PRJ_NAME;
int i = 0;
String index = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + " <title>Welcome</title>\n" + "</head>\n"
+ "<body>\n" + " <h1>Welcome to the Web App</h1>\n" + " <ul>\n"
+ " <li><a href=\"Home.html\">Home Page</a></li>\n" + " </ul>\n" + "</body>\n" + "</html>";
String filename = "index";
createFile(projId, PRJ_NAME, filename, index);
String filename = "index.html";
fileHelper.createFile(folderPath, filename, index);
for (Map.Entry<String, String> entry : pageHtmlMap.entrySet()) {
String pageName = entry.getKey().trim().replaceAll("\\s+", "_"); // remove spaces from name
String pageName = entry.getKey().trim().replaceAll("\\s+", "_") + ".html"; // remove spaces from name
String htmlContent = entry.getValue();
createFile(projId, PRJ_NAME, pageName, htmlContent);
fileHelper.createFile(folderPath, pageName, htmlContent);
i++;
System.out.println(i + " file created ");
}
}
public void createFile(Integer projId, String PRJ_NAME, String pageName, String htmlContent) throws IOException {
String folderPath = projectPath + File.separator + projId + File.separator + "index" + File.separator
+ PRJ_NAME;
File file = new File(folderPath + "/" + pageName + ".html");
// Ensure directory exists
File parentDir = file.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
// Create new file
if (!file.exists()) {
file.createNewFile();
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(htmlContent);
}
System.out.println("✅ File created: " + file.getAbsolutePath());
}
public ResponseEntity<Object> GET(String get) {
RestTemplate restTemplate = new RestTemplate();

View File

@ -92,6 +92,13 @@ public class Design_lbraryController {
}
@DeleteMapping("/Design_lbrary/range/{startId}/{endId}")
public ResponseEntity<?> delete_by_id(@PathVariable Long startId, @PathVariable Long endId) {
String string = designLibraryService.deleteByRange(startId, endId);
return new ResponseEntity<>(new EntityResponse(string), HttpStatus.OK);
}
@GetMapping("/preview/{id}")
public ResponseEntity<String> getDesignPreview(@PathVariable Integer id) {
String htmlWithCss = dlfService.generateHtmlWithCss(id);

View File

@ -33,7 +33,10 @@ public class Design_lbrary extends Extension {
@Lob
private String htmljson;
@Column(length = 2000)
@Lob
private String html;
@Lob
private String css;
@Column(columnDefinition = "TEXT")

View File

@ -20,12 +20,15 @@ public interface Design_lbraryRepository extends JpaRepository<Design_lbrary, In
@Query(value = "select * from design_lbrary where created_by=?1", nativeQuery = true)
Page<Design_lbrary> findAll(Pageable page, Long creayedBy);
@Query(value = "SELECT * from design_lbrary WHERE operation_type=:operation_type && fieldtype=:fieldtype limit 1", nativeQuery = true)
@Query(value = "SELECT * from design_lbrary WHERE templatetype=:operation_type && uitype=:fieldtype limit 1", nativeQuery = true)
Design_lbrary getallByHeaderIdAndFieldType(@Param("operation_type") String operation_type,
@Param("fieldtype") String fieldtype);
@Query(value = "SELECT * FROM design_lbrary " + "WHERE " + " operation_type = :operation_type "
+ "AND LOWER(fieldtype) LIKE CONCAT(LOWER(:fieldtype), '%')", nativeQuery = true)
@Query(value = "SELECT * FROM design_lbrary " + "WHERE templatetype = :operation_type "
+ "AND LOWER(uitype) LIKE CONCAT(LOWER(:fieldtype), '%')", nativeQuery = true)
List<Design_lbrary> getallFlfLine(@Param("operation_type") String operationType,
@Param("fieldtype") String fieldtype);
@Query(value = "select * from design_lbrary WHERE id BETWEEN :startId AND :endId", nativeQuery = true)
List<Design_lbrary> deleteByIdRange(@Param("startId") Long startId, @Param("endId") Long endId);
}

View File

@ -85,11 +85,30 @@ public class Design_lbraryService {
old.setTyperender(data.getTyperender());
old.setTechstack(data.getTechstack());
old.setHtml(data.getHtml());
final Design_lbrary test = designLibraryRepository.save(old);
data.setUpdatedBy(getUser().getUserId());
return test;
}
// delete by range
public String deleteByRange(Long startId, Long endId) {
List<Design_lbrary> all = designLibraryRepository.deleteByIdRange(startId, endId);
int i = 0;
for (Design_lbrary design_lbrary : all) {
designLibraryRepository.delete(design_lbrary);
System.out.println(design_lbrary.getId() + " deleted " + i);
i++;
}
return i + " Deleted";
}
public String generatePreviewHtml(Integer id) {
// 1. Record uthao
Design_lbrary design = designLibraryRepository.findById(id)

View File

@ -15,8 +15,6 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@ -30,7 +28,6 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.realnet.config.EmailService;
import com.realnet.session.Service.TokenBlacklistService;
import com.realnet.userDTO.User;
import com.realnet.users.entity.PasswordResetRequest;
import com.realnet.users.entity.Role;

View File

@ -1,6 +1,9 @@
package com.realnet.vpspack.Controllers;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -20,6 +23,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.realnet.Heplers.FileHelper;
import com.realnet.fnd.response.EntityResponse;
import com.realnet.vpspack.Entity.SiteBuilder;
import com.realnet.vpspack.Services.SiteBuilderService;
@ -34,6 +38,9 @@ public class SiteBuilderController {
@Value("${projectPath}")
private String projectPath;
@Autowired
private FileHelper fileHelper;
@PostMapping("/SiteTree")
public SiteBuilder Savedata(@RequestBody SiteBuilder data) {
SiteBuilder save = Service.Savedata(data);
@ -86,6 +93,21 @@ public class SiteBuilderController {
return new ResponseEntity<>(new EntityResponse("Deleted"), HttpStatus.OK);
}
@PostMapping("/SiteTree/createFile")
public void createHtmlFiles(@RequestParam String siteBuilderName, @RequestBody Map<String, String> pageHtmlMap)
throws IOException {
Service.createHtmlFile(siteBuilderName, pageHtmlMap);
}
@GetMapping("/SiteTree/read")
public ResponseEntity<?> readFile(@RequestParam String siteBuilderName, @RequestParam String filename) {
String filepath = projectPath + File.separator + "Files" + File.separator + siteBuilderName;
ResponseEntity<?> file = fileHelper.readFile(filepath, filename);
return file;
}
}

View File

@ -1,12 +1,17 @@
package com.realnet.vpspack.Services;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
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.Pageable;
import org.springframework.stereotype.Service;
import com.realnet.Heplers.FileHelper;
import com.realnet.realm.Entity.Realm;
import com.realnet.realm.Services.RealmService;
import com.realnet.users.entity1.AppUser;
@ -23,6 +28,12 @@ public class SiteBuilderService {
@Autowired
private RealmService realmService;
@Autowired
private FileHelper fileHelper;
@Value("${projectPath}")
private String projectPath;
public SiteBuilder Savedata(SiteBuilder data) {
data.setUpdatedBy(getUser().getUserId());
@ -82,6 +93,21 @@ public class SiteBuilderService {
return test;
}
public void createHtmlFile(String siteBuilderName, Map<String, String> pageHtmlMap) throws IOException {
String folderPath = projectPath + File.separator + "Files" + File.separator + siteBuilderName;
int i = 0;
for (Map.Entry<String, String> entry : pageHtmlMap.entrySet()) {
String pageName = entry.getKey().trim().replaceAll("\\s+", "_") + ".html"; // remove spaces from name
String htmlContent = entry.getValue();
fileHelper.createFile(folderPath, pageName, htmlContent);
i++;
System.out.println(i + " file created ");
}
}
public AppUser getUser() {
AppUser user = userService.getLoggedInUser();
return user;