0% found this document useful (0 votes)
14 views7 pages

New Text Document

Uploaded by

gehansoufy6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views7 pages

New Text Document

Uploaded by

gehansoufy6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

package com.template.

RestController;

import com.template.Class.Constants;
import com.template.Class.Util;
import com.template.Controller.BaseController;
import com.template.Exception.InvalidInputException;
import com.template.ImageProcessing.PropImageQualityChecker;
import com.template.Projection.PropIndexProjection;
import com.template.Service.Table.CompanyXmlsService;
import com.template.Service.Table.PropertyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.imageio.ImageIO;

import com.template.Class.ApiResponse;
import com.template.Model.Table.Property;
import com.template.Model.Table.PropertyImages;
import com.template.Repository.Table.PropertyImagesRep;
import com.template.Repository.Table.PropertyRep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.template.Class.Constants;
import com.template.Class.UserInformation;
import com.template.Class.Util;
import com.template.Controller.BaseController;
import com.template.Controller.Table.PropertyController;
import com.template.Exception.InvalidInputException;
import com.template.ImageProcessing.PropImageQualityChecker;
import com.template.Projection.PropIndexProjection;
import com.template.Service.Table.PropertyService;
import jakarta.xml.bind.DatatypeConverter;

@RestController
public class PropertyRestControler extends BaseController {
private static final Logger logger =
LoggerFactory.getLogger(PropertyRestControler.class);
private String name = "property";
@Autowired
PropertyService propertyService;
@Autowired

CompanyXmlsService companyXmlsService;

PropertyRep propertyRep;
@Autowired
PropertyImagesRep propertyImagesRep;

@PostMapping("/quality")
public ResponseEntity<String> checkImageQuality(@RequestParam("file")
MultipartFile file) {
PropImageQualityChecker propImageQualityChecker = null;

propImageQualityChecker = new PropImageQualityChecker();


// Temporarily save the file to check its quality
String fileName = file.getOriginalFilename();
try {
logger.info("Start Checking Image Quality ,file name : {}",
fileName);
Path tempFilePath =
Paths.get(System.getProperty("java.io.tmpdir"), fileName);
file.transferTo(tempFilePath);

File tempFile = tempFilePath.toFile();


boolean qualityCheck =
propImageQualityChecker.checkImageQuality(tempFile);

// Delete the temporary file after checking


tempFile.delete();

if (qualityCheck) {
logger.info("Image quality is acceptable.");

return ResponseEntity.ok("Image quality is acceptable.");


} else {
logger.info("Image does not meet the required quality
standards.");
return ResponseEntity.status(400).body("Image does not meet
the required quality standards.");
}
} catch (IOException ex) {
logger.info("Failed to check image quality: " + ex.getMessage());
return ResponseEntity.status(500).body("Failed to check image
quality: " + ex.getMessage());
}
}

@GetMapping("/property/agentIndex")
public List<PropIndexProjection> index(Model model, @RequestParam("id") int
agentId) {
logger.info("Fetching {} Index for Agent ID - {}- {}", name, agentId,
userInformationService.getLoginUserID());
List<PropIndexProjection> propertyList = new
ArrayList<PropIndexProjection>();
Page<PropIndexProjection> properties = null;
String result = null;
if (Util.isNotZeroNullNumber(agentId)) {
propertyList = propertyService.getAgentProperties(agentId);
// if (properties.getContent() != null &&
properties.getContent().size() > 0) {
// PropertyList = properties.getContent();
// }
model.addAttribute("list", propertyList);
model.addAttribute("flag", Constants.AGENT_FLAG);

// model.addAttribute("page", PropertyList);
} else {
logger.error("Agent ID Is Null OR Zero");
throw new InvalidInputException("Agent ID Is Null OR Zero");
}

result = "/" + name + "/index";


return propertyList;
}

@PostMapping("/property/ddd")
public ResponseEntity<String> deleteRecords(@RequestBody List<Long>
selectedIds) {
System.err.println("******************************************");
try {
selectedIds.forEach(id -> {
System.err.println("Deleting record with ID: " + id);

});

return ResponseEntity.ok("Records deleted successfully.");


} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred while deleting records.");
}
}

@PostMapping("/companyXmls/deleterecords")
public ResponseEntity<String> deleteRecordsCompanyXmls(@RequestBody
List<Long> selectedIds) {
System.err.println("******************************************");
try {
selectedIds.forEach(id -> {
companyXmlsService.deleteCompanyXmls(Math.toIntExact(id));
System.err.println("Deleting record with ID: " + id);

});

return ResponseEntity.ok("Records deleted successfully.");


} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred while deleting records.");
}
}
// @PostMapping("/upload")
// @ResponseBody
// public ResponseEntity<String> handleFileUpload(@RequestParam("file")
MultipartFile file) {
// try {
// // Process the uploaded file and generate a thumbnail
// byte[] thumbnailBytes = generateThumbnail(file.getBytes());
//
// // Convert the thumbnail bytes to a Base64-encoded string
// String thumbnailBase64 =
DatatypeConverter.printBase64Binary(thumbnailBytes);
//
// return ResponseEntity.ok(thumbnailBase64);
// } catch (IOException e) {
// e.printStackTrace();
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
// .body("Error processing the file: " +
e.getMessage());
// }
// }
//
// private byte[] generateThumbnail(byte[] originalBytes) throws IOException {
// ByteArrayInputStream bis = null;
// ByteArrayOutputStream bos = null;
// byte[] result = null;
// try {
// bis = new ByteArrayInputStream(originalBytes);
// BufferedImage originalImage = ImageIO.read(bis);
//
// // Create a thumbnail
// int thumbnailWidth = 100;
// int thumbnailHeight = (int) ((double) originalImage.getHeight() /
originalImage.getWidth()
// * thumbnailWidth);
//
// BufferedImage thumbnail = new BufferedImage(thumbnailWidth,
thumbnailHeight, BufferedImage.TYPE_INT_RGB);
// thumbnail.getGraphics().drawImage(
// originalImage.getScaledInstance(thumbnailWidth,
thumbnailHeight, Image.SCALE_SMOOTH), 0, 0, null);
//
// // Convert the thumbnail to bytes
// bos = new ByteArrayOutputStream();
// ImageIO.write(thumbnail, "jpg", bos);
// result = bos.toByteArray();
//
// } catch (Exception e) {
// }
//
// return result;
// }
@PostMapping("/checkQualityAndUpload")
public ResponseEntity<ApiResponse<List<PropertyImages>>>
checkImageQualityAndUpload(
@RequestParam("file") MultipartFile file,
@RequestParam("id") int id) {

PropImageQualityChecker propImageQualityChecker = new


PropImageQualityChecker();
MultipartFile[] imageFiles = new MultipartFile[1];
imageFiles[0] = file;

String fileName = file.getOriginalFilename();


try {
logger.info("Start Checking Image Quality, file name: {}", fileName);

Path tempFilePath = Paths.get(System.getProperty("java.io.tmpdir"),


fileName);
file.transferTo(tempFilePath);
File tempFile = tempFilePath.toFile();

boolean qualityCheck =
propImageQualityChecker.checkImageQuality(tempFile);

// ‫حذف الملف المؤقت‬


tempFile.delete();

if (qualityCheck) {
logger.info("Image quality is acceptable.");
Property prop = propertyRep.findById(id).orElseThrow(() -> new
RuntimeException("Property not found"));
List<PropertyImages> propertyImages =
propertyService.saveProImages(imageFiles, prop);

return ResponseEntity.ok(new ApiResponse<>(


"success",
"Image uploaded and saved successfully.",
propertyImages
));
} else {
logger.info("Image does not meet the required quality
standards.");
return ResponseEntity.status(400).body(new ApiResponse<>(
"fail",
"Image does not meet the required quality
standards.",
null
));
}
} catch (IOException ex) {
logger.info("Failed to check image quality: {}", ex.getMessage());
return ResponseEntity.status(500).body(new ApiResponse<>(
"error",
"Failed to check image quality: " + ex.getMessage(),
null
));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@PutMapping("/reorderImages")
public ResponseEntity<ApiResponse<String>> reorderImages(
@RequestParam("property_id") int propertyId,
@RequestBody List<Integer> imageIds) {

List<PropertyImages> images =
propertyImagesRep.findByProperty_IDAndIsDeleted(propertyId, 0);
if (images.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ApiResponse<>("error", "No images found for
the property.", null));
}

Map<Integer, PropertyImages> imagesMap = images.stream()


.collect(Collectors.toMap(PropertyImages::getID, image ->
image));

int order = 1;
for (Integer imageId : imageIds) {
if (imagesMap.containsKey(imageId)) {
PropertyImages image = imagesMap.get(imageId);
image.setOrder(order++);
propertyImagesRep.save(image);
}
}

return ResponseEntity.ok(new ApiResponse<>(


"success",
"Images reordered successfully.",
null
));
}
@PutMapping("/deleteImage")
public ResponseEntity<ApiResponse<String>>
deleteImage(@RequestParam("img_id") int id) {

Optional<PropertyImages> propertyImageOpt =
propertyImagesRep.findById(id);

if (propertyImageOpt.isPresent()) {
PropertyImages propertyImage = propertyImageOpt.get();
propertyImage.setIs_deleted(1);

propertyImagesRep.save(propertyImage);
return ResponseEntity.ok(new ApiResponse<>(
"success",
"Image marked as deleted.",
null
));
} else {

return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
new ApiResponse<>(
"error",
"Image not found.",
null
)
);
}
}
@GetMapping("/activeImages")
public ResponseEntity<ApiResponse<List<PropertyImages>>>
getActiveImagesByPropertyId(@RequestParam("property_id") int propertyId) {
List<PropertyImages> activeImages =
propertyImagesRep.findActiveImagesByPropertyId(propertyId);
if (!activeImages.isEmpty()) {
return ResponseEntity.ok(new ApiResponse<>(
"success",
"Active images retrieved successfully.",
activeImages
));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
new ApiResponse<>(
"error",
"No active images found for the specified
property.",
null
)
);
}
}

You might also like