This commit is contained in:
Andreas Wilms
2025-09-08 18:30:35 +02:00
commit f12cc8b2ce
130 changed files with 16911 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
package com.server.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}

View File

@@ -0,0 +1,29 @@
package com.server.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**") // Erlaubt alle Endpunkte
.allowedOrigins(
"http://localhost:3050",
"http://nextjs-app:3050",
"https://erp.wolga-kreativ.de") // Erlaubt Anfragen von Next.js
.allowedMethods(
"GET", "POST", "PUT", "DELETE", "OPTIONS") // Erlaubt spezifische HTTP-Methoden
.allowedHeaders("*") // Erlaubt alle Header
.allowCredentials(true); // Erlaubt Cookies/Authentifizierung
}
};
}
}

View File

@@ -0,0 +1,35 @@
package com.server.api.controller;
import com.server.api.models.User;
import com.server.api.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired private AuthService authService;
@PostMapping("/signup")
public ResponseEntity<String> signup(@RequestBody User user){
if (authService.signUp(user)){
return ResponseEntity.ok("SignUp successful!");
}else{
return ResponseEntity.status(400).body("SignUp failed. Please try again.");
}
}
@PostMapping("/signin")
public ResponseEntity<String> signin(@RequestBody User user){
if (authService.signIn(user)){
return ResponseEntity.ok("SignIn successful!");
}else{
return ResponseEntity.status(400).body("SignIn failed. Please try again.");
}
}
}

View File

@@ -0,0 +1,144 @@
// filepath:
// /Users/andre/Desktop/api/src/main/java/com/server/api/controller/VorlageFlaechendruckController.java
package com.server.api.controller;
import com.server.api.controller.dto.RollendruckGenReqDto;
import com.server.api.models.VorlageFlaechendruck;
import com.server.api.service.flaechendruck.VorlageFlaechendruckService;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import com.server.api.service.flaechendruck.VorlagenFlaechendruckPDFGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/vorlageFlaechendruck")
public class VorlageFlaechendruckController {
@Autowired private VorlageFlaechendruckService vorlageFlaechendruckService;
@Autowired private VorlagenFlaechendruckPDFGeneratorService vorlagenPDFGeneratorService;
@PostMapping("/createWithCoordinates")
public ResponseEntity<String> createVorlageWithCoordinates(
@RequestBody VorlageFlaechendruck vorlage) {
vorlageFlaechendruckService.saveVorlageWithCoordinates(vorlage);
return ResponseEntity.ok("Vorlage successfully created with coordinates.");
}
@PostMapping("/alterVorlage")
public ResponseEntity<?> alterVorlage(@RequestBody VorlageFlaechendruck vorlage){
vorlageFlaechendruckService.alterVorlage(vorlage);
return ResponseEntity.ok("Vorlage successfully created with coordinates.");
}
@GetMapping("/getAllFlaechendruckVorlagen")
public List<VorlageFlaechendruck> getAllFlaechendruckVorlagen() {
return vorlageFlaechendruckService.getAllVorlagen();
}
@DeleteMapping("/delete/{id}")
public void deleteVorlageFlaechendruck(@PathVariable Long id) {
vorlageFlaechendruckService.deleteVorlageFlaechendruck(id);
}
@PostMapping(value = "/generate", consumes = "application/json")
public ResponseEntity<?> uploadFiles(@RequestBody RollendruckGenReqDto rollendruckGenReqDto) {
List<String> vorlageIds = rollendruckGenReqDto.getVorlageIds();
String rootDir = rollendruckGenReqDto.getRootDirectory();
String OUTPUT_DIR = String.valueOf((long) (Math.random() * 9_000_000_000L) + 1_000_000_000L)+"/";
Path output = Paths.get(OUTPUT_DIR);
// Ensure the directory path exists before checking it
if (Files.exists(output)) {
try {
deleteDirectoryRecursively(output);
}catch (Exception e) {
}
}
String sharedFolder = null;
String next_url = null;
try {
sharedFolder = System.getenv("SHARED_FOLDER");
next_url = System.getenv("NEXT_SERVER_URL");
if (sharedFolder == null || sharedFolder.isEmpty()) {
sharedFolder = "../frontend/public";
}
if (next_url == null || next_url.isEmpty()) {
next_url = "http://localhost:3050";
}
String uploadPath = sharedFolder + "/" + rootDir + "/";
File dir = new File(uploadPath);
if (!dir.exists() && !dir.isDirectory()) {
throw new Exception("Ordner "+rootDir+" mit Bildern fehlt!");
}
for (String vorlageId : vorlageIds) {
System.out.println("Wird generiert: " + vorlageId);
vorlagenPDFGeneratorService.generateFlaechendruckPDFs(
Long.parseLong(vorlageId), OUTPUT_DIR, uploadPath);
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
try {
// move final output folder to shared folder
Path outputDir = output;
Path sharedOutputDir = Paths.get(sharedFolder + "/" + rootDir + "/output");
// delete shared output folder if it exists
if (Files.exists(sharedOutputDir)) {
deleteDirectoryRecursively(sharedOutputDir);
}
Files.walk(outputDir)
.forEach(
source -> {
try {
Path destination = sharedOutputDir.resolve(outputDir.relativize(source));
Files.createDirectories(destination.getParent());
Files.copy(source, destination);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
// Output-Ordner löschen
deleteDirectoryRecursively(output);
return ResponseEntity.status(HttpStatus.OK).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
private void deleteDirectoryRecursively(Path path) throws IOException {
if (Files.exists(path)) {
Files.walk(path)
.sorted((a, b) -> b.compareTo(a)) // Dateien zuerst, dann Verzeichnisse
.forEach(
p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
}

View File

@@ -0,0 +1,161 @@
package com.server.api.controller;
import com.server.api.controller.dto.RollendruckGenReqDto;
import com.server.api.models.RollenDruckDupliArtikel;
import com.server.api.models.VorlageRollendruck;
import com.server.api.service.rollendruck.VorlageRollendruckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.server.api.service.rollendruck.VorlageRollendruckPDFGeneratorService;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@RestController
@RequestMapping("/VorlageRollenDruck")
public class VorlageRollendruckController {
@Autowired private VorlageRollendruckService vorlageRollendruckService;
@Autowired private VorlageRollendruckPDFGeneratorService vorlagenPDFGeneratorService;
@PostMapping("/createRollenDruckVorlage")
public ResponseEntity<String> createVorlageWithCoordinates(
@RequestBody VorlageRollendruck vorlage) {
vorlageRollendruckService.createRollendruckVorlage(vorlage);
return ResponseEntity.ok("Vorlage Rollendruck successfully created.");
}
@GetMapping("/getAllRollendruckVorlagen")
public List<VorlageRollendruck> getAllRollendruckVorlagen() {
// Get all rollendruck templates
return vorlageRollendruckService.getAllVorlagen();
}
@PostMapping("/alterVorlage")
public ResponseEntity<?> alterVorlage(@RequestBody VorlageRollendruck vorlage) {
vorlageRollendruckService.alterVorlage(vorlage);
return ResponseEntity.ok("Vorlage successfully created with coordinates.");
}
@DeleteMapping("/delete/{id}")
public void deleteVorlageRollendruck(@PathVariable Long id) {
vorlageRollendruckService.deleteVorlageRollendruck(id);
}
@PostMapping(value = "/generate", consumes = "application/json")
public ResponseEntity<?> uploadFiles(@RequestBody RollendruckGenReqDto rollendruckGenReqDto) {
List<String> vorlageIds = rollendruckGenReqDto.getVorlageIds();
String rootDir = rollendruckGenReqDto.getRootDirectory();
String OUTPUT_DIR = String.valueOf((long) (Math.random() * 9_000_000_000L) + 1_000_000_000L)+"/";
Path output = Paths.get(OUTPUT_DIR);
// Ensure the directory path exists before checking it
if (Files.exists(output)) {
try {
deleteDirectoryRecursively(output);
}catch (Exception e) {
}
}
String sharedFolder = null;
String next_url = null;
try {
sharedFolder = System.getenv("SHARED_FOLDER");
next_url = System.getenv("NEXT_SERVER_URL");
if (sharedFolder == null || sharedFolder.isEmpty()) {
sharedFolder = "../frontend/public";
}
if (next_url == null || next_url.isEmpty()) {
next_url = "http://localhost:3050";
}
String uploadPath = sharedFolder + "/" + rootDir + "/";
File dir = new File(uploadPath);
if (!dir.exists() && !dir.isDirectory()) {
throw new Exception("Ordner "+rootDir+" mit Bildern fehlt!");
}
for (String vorlageId : vorlageIds) {
System.out.println("Wird generiert: " + vorlageId);
vorlagenPDFGeneratorService.generatePdf(
Long.parseLong(vorlageId), OUTPUT_DIR, uploadPath);
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
try {
// move final output folder to shared folder
Path outputDir = output;
Path sharedOutputDir = Paths.get(sharedFolder + "/" + rootDir + "/output");
// delete shared output folder if it exists
if (Files.exists(sharedOutputDir)) {
deleteDirectoryRecursively(sharedOutputDir);
}
Files.walk(outputDir)
.forEach(
source -> {
try {
Path destination = sharedOutputDir.resolve(outputDir.relativize(source));
Files.createDirectories(destination.getParent());
Files.copy(source, destination);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
// Output-Ordner löschen
deleteDirectoryRecursively(output);
return ResponseEntity.status(HttpStatus.OK).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping("/addDupliArtikel")
public ResponseEntity<?> addDupliArtikel(@RequestBody RollenDruckDupliArtikel artikel) {
vorlageRollendruckService.addDupliArtikel(artikel);
return ResponseEntity.ok("Vorlage successfully created with coordinates.");
}
@GetMapping("/getAllDupliArtikel")
public List<RollenDruckDupliArtikel> getAllDupliArtikel() {
return vorlageRollendruckService.getAllDupliArtikel();
}
@DeleteMapping("deleteDupli/{id}")
public void deleteDupli(@PathVariable Long id){
vorlageRollendruckService.deleteDupliArtikel(id);
}
private void deleteDirectoryRecursively(Path path) throws IOException {
if (Files.exists(path)) {
Files.walk(path)
.sorted((a, b) -> b.compareTo(a)) // Dateien zuerst, dann Verzeichnisse
.forEach(
p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
}

View File

@@ -0,0 +1,26 @@
package com.server.api.controller.dto;
import java.util.List;
public class RollendruckGenReqDto {
private List<String> vorlageIds;
private String rootDirectory;
// Getter und Setter
public List<String> getVorlageIds() {
return vorlageIds;
}
public void setVorlageIds(List<String> vorlageIds) {
this.vorlageIds = vorlageIds;
}
public String getRootDirectory() {
return rootDirectory;
}
public void setRootDirectory(String rootDirectory) {
this.rootDirectory = rootDirectory;
}
}

View File

@@ -0,0 +1,68 @@
package com.server.api.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "coordinates")
public class Coordinates {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long coordinate_id;
@ManyToOne
@JoinColumn(name = "flaechendruck_id", nullable = false)
@JsonIgnore
private VorlageFlaechendruck vorlage;
private Double x;
private Double y;
private Double rotation;
// Getter und Setter
public Long getId() {
return coordinate_id;
}
public void setId(Long id) {
this.coordinate_id = id;
}
public VorlageFlaechendruck getVorlage() {
return vorlage;
}
public void setVorlage(VorlageFlaechendruck vorlage) {
this.vorlage = vorlage;
}
public Double getX() {
return x;
}
public void setX(Double x) {
this.x = x;
}
public Double getY() {
return y;
}
public void setY(Double y) {
this.y = y;
}
public Double getRotation() {
return rotation;
}
public void setRotation(Double rotation) {
this.rotation = rotation;
}
}

View File

@@ -0,0 +1,24 @@
package com.server.api.models;
import jakarta.persistence.*;
@Entity
@Table(name = "RollenDruckDupliArtikel")
public class RollenDruckDupliArtikel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String product_type;
public void setProduct_type(String product_type) {
this.product_type = product_type;
}
public String getProduct_type() {
return product_type;
}
public Long getId() {
return id;
}
}

View File

@@ -0,0 +1,31 @@
package com.server.api.models;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
private String name;
private String password;
public void setName(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
}

View File

@@ -0,0 +1,75 @@
package com.server.api.models;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import java.util.List;
@Entity
@Table(name = "vorlageFlaechendruck")
public class VorlageFlaechendruck {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long flaechendruck_id;
private String printer;
private String product_type;
private Float height;
private Float width;
@OneToMany(mappedBy = "coordinate_id")
private List<Coordinates> coordinates;
// Getter und Setter
public String getPrinter() {
return printer;
}
public void setPrinter(String printer) {
this.printer = printer;
}
public Long getId() {
return flaechendruck_id;
}
public void setId(Long id) {
this.flaechendruck_id = id;
}
public String getProduct_type() {
return product_type;
}
public void setProduct_type(String product_type) {
this.product_type = product_type;
}
public Float getHeight() {
return height;
}
public void setHeight(Float height) {
this.height = height;
}
public Float getWidth() {
return width;
}
public void setWidth(Float width) {
this.width = width;
}
public List<Coordinates> getCoordinates() {
return coordinates;
}
public void setCoordinates(List<Coordinates> coordinates) {
this.coordinates = coordinates;
}
}

View File

@@ -0,0 +1,60 @@
package com.server.api.models;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.*;
@Entity
@Table(name = "vorlageRollendruck")
public class VorlageRollendruck {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String printer;
private Float height;
private Float width;
private String articleTypes;
// Getter and Setter
public String getArticleTypes() {
return articleTypes;
}
public void setArticleTypes(String articleTypes) {
this.articleTypes = articleTypes;
}
// Getter und Setter
public String getPrinter() {
return printer;
}
public void setPrinter(String printer) {
this.printer = printer;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Float getHeight() {
return height;
}
public void setHeight(Float height) {
this.height = height;
}
public Float getWidth() {
return width;
}
public void setWidth(Float width) {
this.width = width;
}
}

View File

@@ -0,0 +1,19 @@
package com.server.api.repository;
import com.server.api.models.User;
import com.server.api.models.VorlageRollendruck;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AuthRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.name = :name")
User findByName(@Param("name") String name);
}

View File

@@ -0,0 +1,15 @@
// filepath:
// /Users/andre/Desktop/PrintAuftrag/api/src/main/java/com/server/api/repository/CoordinatesRepository.java
package com.server.api.repository;
import com.server.api.models.Coordinates;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CoordinatesRepository extends JpaRepository<Coordinates, Long> {
void deleteByVorlageId(Long vorlageId); // Diese Methode hinzufügen
List<Coordinates> findAllByVorlageId(Long vorlageId);
}

View File

@@ -0,0 +1,10 @@
package com.server.api.repository;
import com.server.api.models.RollenDruckDupliArtikel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RollenDruckDupliRepository extends JpaRepository<RollenDruckDupliArtikel, Long> {
}

View File

@@ -0,0 +1,10 @@
// filepath:
// /Users/andre/Desktop/api/src/main/java/com/server/api/repository/VorlagenFlaechendruckRepository.java
package com.server.api.repository;
import com.server.api.models.VorlageFlaechendruck;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface VorlageFlaechendruckRepository extends JpaRepository<VorlageFlaechendruck, Long> {}

View File

@@ -0,0 +1,15 @@
package com.server.api.repository;
import com.server.api.models.VorlageRollendruck;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface VorlageRollendruckRepository extends JpaRepository<VorlageRollendruck, Long> {
@Query("SELECT v FROM VorlageRollendruck v")
List<VorlageRollendruck> getAllVorlagenRollendruck();
}

View File

@@ -0,0 +1,61 @@
package com.server.api.service;
import com.server.api.models.User;
import com.server.api.repository.AuthRepository;
import com.server.api.utils.HashUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class AuthService {
private static final Logger logger = LoggerFactory.getLogger(AuthService.class);
@Autowired
private AuthRepository authRepository;
public boolean signUp(User user) {
try {
// Validate user object (you can implement your own validation logic)
if (user == null || user.getName() == null || user.getPassword() == null) {
throw new IllegalArgumentException("User or required fields cannot be null");
}
// Hash password
user.setPassword(HashUtil.hash(user.getPassword()));
// Save the user to the repository
authRepository.save(user);
return true;
} catch (Exception e) {
logger.error("Error during sign up: ", e); // Log the exception
return false;
}
}
public boolean signIn(User user) {
if (user == null || user.getName() == null || user.getPassword() == null) {
return false;
}
try {
Optional<User> maybe = Optional.ofNullable(authRepository.findByName(user.getName()));
if (maybe.isEmpty()) return false;
User stored = maybe.get();
// Hash das eingegebene Passwort und vergleiche mit gespeichertem Hash
String hashedInput = HashUtil.hash(user.getPassword());
return hashedInput.equals(stored.getPassword());
} catch (Exception e) {
logger.error("Error during sign in: ", e);
return false;
}
}
}

View File

@@ -0,0 +1,102 @@
package com.server.api.service.flaechendruck;
import com.server.api.models.Coordinates;
import com.server.api.models.VorlageFlaechendruck;
import com.server.api.repository.CoordinatesRepository;
import com.server.api.repository.VorlageFlaechendruckRepository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class VorlageFlaechendruckService {
@Autowired private VorlageFlaechendruckRepository vorlageFlaechendruckRepository;
@Autowired private CoordinatesRepository coordinatesRepository;
@Transactional
public void deleteVorlageFlaechendruck(Long id) {
coordinatesRepository.deleteByVorlageId(id);
vorlageFlaechendruckRepository.deleteById(id);
}
public void saveVorlageWithCoordinates(VorlageFlaechendruck vorlageDTO) {
// Erstellen der VorlageFlaechendruck-Entität
VorlageFlaechendruck vorlage = new VorlageFlaechendruck();
vorlage.setPrinter(vorlageDTO.getPrinter());
vorlage.setProduct_type(vorlageDTO.getProduct_type());
vorlage.setHeight(vorlageDTO.getHeight());
vorlage.setWidth(vorlageDTO.getWidth());
// Speichern der VorlageFlaechendruck-Entität
VorlageFlaechendruck savedVorlage = vorlageFlaechendruckRepository.save(vorlage);
// Speichern der zugehörigen Coordinates
for (Coordinates coordinate : vorlageDTO.getCoordinates()) {
coordinate.setVorlage(savedVorlage); // Fremdschlüssel setzen
coordinatesRepository.save(coordinate);
}
}
public void alterVorlage(VorlageFlaechendruck vorlage){
VorlageFlaechendruck vorlageInDB = vorlageFlaechendruckRepository.findById(vorlage.getId()).get();
vorlageInDB.setPrinter(vorlage.getPrinter());
vorlageInDB.setProduct_type(vorlage.getProduct_type());
vorlageInDB.setHeight(vorlage.getHeight());
vorlageInDB.setWidth(vorlage.getWidth());
List<Coordinates> coordinates = coordinatesRepository.findAll();
List<Coordinates> coordinatesToDelete = new ArrayList<>();
for (Coordinates coordinate : coordinates) {
if (coordinate.getVorlage().getId() == vorlageInDB.getId()) {
coordinatesToDelete.add(coordinate);
}
}
coordinatesRepository.deleteAll(coordinatesToDelete);
for (Coordinates coordinate : vorlage.getCoordinates()) {
coordinate.setVorlage(vorlageInDB); // Fremdschlüssel setzen
coordinatesRepository.save(coordinate);
}
vorlageFlaechendruckRepository.save(vorlageInDB);
}
public List<VorlageFlaechendruck> getAllVorlagen() {
List<VorlageFlaechendruck> vorlagen = vorlageFlaechendruckRepository.findAll();
List<Coordinates> coordinates = coordinatesRepository.findAll();
List<VorlageFlaechendruck> vorlagenWithCoordinates = new ArrayList<>();
for (VorlageFlaechendruck vorlage : vorlagen) {
List<Coordinates> vorlageCoordinates = new ArrayList<>();
for (Coordinates coordinate : coordinates) {
if (coordinate.getVorlage().getId() == vorlage.getId()) {
vorlageCoordinates.add(coordinate);
}
}
vorlage.setCoordinates(vorlageCoordinates);
vorlagenWithCoordinates.add(vorlage);
}
return vorlagenWithCoordinates;
}
public VorlageFlaechendruck getVorlageById(long id) {
VorlageFlaechendruck vorlage = vorlageFlaechendruckRepository.findById(id).get();
List<Coordinates> coordinates = coordinatesRepository.findAll();
List<Coordinates> vorlageCoordinates = new ArrayList<>();
for (Coordinates coordinate : coordinates) {
if (coordinate.getVorlage().getId() == vorlage.getId()) {
vorlageCoordinates.add(coordinate);
}
}
vorlage.setCoordinates(vorlageCoordinates);
return vorlage;
}
}

View File

@@ -0,0 +1,330 @@
package com.server.api.service.flaechendruck;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.server.api.models.Coordinates;
import com.server.api.models.VorlageFlaechendruck;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class VorlagenFlaechendruckPDFGeneratorService {
@Autowired
private VorlageFlaechendruckService vorlageFlaechendruckService;
public void generateFlaechendruckPDFs(long vorlageId, String outputDir, String uploadDir)
throws Exception {
VorlageFlaechendruck vorlage = vorlageFlaechendruckService.getVorlageById(vorlageId);
String imagePath = uploadDir;
Path outputFolder = Paths.get(outputDir);
if (!Files.exists(outputFolder)) {
Files.createDirectories(outputFolder);
}
PdfGenerator pdfGenerator = new PdfGenerator(imagePath, outputDir);
pdfGenerator.generatePdf(vorlage);
}
public class PdfGenerator {
private String imagePath;
private String pdfPath;
public class Article {
private String imagePath;
private String color;
private String productType;
public Article(String imagePath, String color, String productType) {
this.imagePath = imagePath;
this.color = color;
this.productType = productType;
}
public String getImagePath() {
return imagePath;
}
public String getColor() {
return color;
}
public String getProductType() {
return productType;
}
}
public class ColorCount {
private String color;
private int count;
public ColorCount(String color, int count) {
this.color = color;
this.count = count;
}
public String getColor() {
return color;
}
public int getCount() {
return count;
}
public void incrementCount() {
this.count++;
}
public void decrementCount() {
this.count--;
}
}
public PdfGenerator(String imagePath, String pdfPath) {
this.imagePath = imagePath;
this.pdfPath = pdfPath;
}
public void generatePdf(VorlageFlaechendruck vorlage) throws Exception {
// Bild hinzufügen
File folder = new File(imagePath);
File[] files = folder.listFiles();
files = getAllFilePaths(imagePath);
// delete hidden files beginning with .
files = Arrays.stream(files).filter(file -> !file.getName().startsWith(".")).toArray(File[]::new);
// only keep files with the correct product type
files = Arrays.stream(files)
.filter(file -> file.getName().startsWith(vorlage.getProduct_type().toLowerCase()))
.toArray(File[]::new);
// Sort files by color
Article[] articles = createArticlesOrder(files, vorlage.getCoordinates().size());
Coordinates[] coordinates = vorlage.getCoordinates().toArray(new Coordinates[0]);
float height = vorlage.getHeight();
float width = vorlage.getWidth();
int count = 0;
for (int i = 0; i < articles.length; i += coordinates.length) {
count++;
ArrayList<ColorCount> colorCounts = new ArrayList<>();
float pointsPerMm = 2.83465f;
try (PdfWriter writer = new PdfWriter(pdfPath + count + ".pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(
pdf, new PageSize(width * pointsPerMm, height * pointsPerMm))) {
for (int j = 0; j < coordinates.length; j++) {
if (i + j >= articles.length) {
break;
}
boolean found = false;
for (ColorCount colorCount : colorCounts) {
if (colorCount.getColor().equals(articles[i + j].getColor())) {
colorCount.incrementCount();
found = true;
break;
}
}
if (!found) {
colorCounts.add(new ColorCount(articles[i + j].getColor(), 1));
}
String imagePathTemp = articles[i + j].getImagePath();
ImageData imageData = ImageDataFactory.create(imagePathTemp);
Image image = new Image(imageData);
double x = coordinates[j].getX() * pointsPerMm;
double y = coordinates[j].getY() * pointsPerMm;
double rotation = coordinates[j].getRotation();
float[] imageSize = getImageSize(imagePathTemp);
float imageWidth = pixelsToMm(imageSize[0]);
float imageHeight = pixelsToMm(imageSize[1]);
if (rotation != 0) {
image.setRotationAngle(Math.toRadians(rotation));
// Swap width and height if the image is rotated
}
image.scaleToFit(imageWidth * pointsPerMm, imageHeight * pointsPerMm);
// Adjust x and y to center the image at the given coordinates
if (rotation != 0) {
float temp = imageWidth;
imageWidth = imageHeight;
imageHeight = temp;
}
double adjustedX = x - (imageWidth * pointsPerMm) / 2;
double adjustedY = y - (imageHeight * pointsPerMm) / 2;
image.setFixedPosition((float) adjustedX, (float) adjustedY);
document.add(image);
}
}
String saveName = compressString(colorCounts, articles[0].getProductType());
// Datei umbenennen
String tempFileName = pdfPath + count + ".pdf";
File tempFile = new File(tempFileName);
File renamedFile = new File(pdfPath + count + ". " + saveName + ".pdf");
if (!tempFile.renameTo(renamedFile)) {
throw new Exception("Internal Server Error");
}
}
}
private Article[] createArticlesOrder(File[] files, int cors_len) throws Exception {
ArrayList<Article> articles = new ArrayList<>();
ArrayList<ColorCount> colorCounts = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
articles.add(getArticleProperties(files[i].getAbsolutePath()));
boolean found = false;
for (ColorCount colorCount : colorCounts) {
if (colorCount.getColor().equals(articles.get(i).getColor())) {
colorCount.incrementCount();
found = true;
break;
}
}
if (!found) {
colorCounts.add(new ColorCount(articles.get(i).getColor(), 1));
}
}
ArrayList<Article> sortedArticles = new ArrayList<>();
int index = 0;
while (index < colorCounts.size()) {
if (colorCounts.get(index).getCount() >= cors_len) {
int num_added = 0;
ArrayList<Article> removeArticles = new ArrayList<>();
for (Article artc : articles) {
if (artc.getColor().equals(colorCounts.get(index).getColor())) {
sortedArticles.add(artc);
removeArticles.add(artc);
colorCounts.get(index).decrementCount();
num_added++;
}
if (num_added >= cors_len) {
break;
}
}
articles.removeAll(removeArticles);
} else {
index++;
}
}
// sort articles by color
articles.sort((a, b) -> a.getColor().compareTo(b.getColor()));
for (Article artc : articles) {
sortedArticles.add(artc);
}
// transform ArrayList to Array
Article[] sortedArticlesArray = new Article[sortedArticles.size()];
for (int i = 0; i < sortedArticles.size(); i++) {
sortedArticlesArray[i] = sortedArticles.get(i);
}
return sortedArticlesArray;
}
private File[] getAllFilePaths(String directoryPath) throws Exception {
try (Stream<Path> paths = Files.walk(Paths.get(directoryPath))) {
return paths
.filter(Files::isRegularFile) // Behalte nur reguläre Dateien (keine Verzeichnisse)
.map(Path::toFile) // Konvertiere Path zu File
.toArray(File[]::new); // Sammle die Ergebnisse in ein Array
}
}
private String compressString(ArrayList<ColorCount> colorCounts, String productType) {
StringBuilder result = new StringBuilder();
for (ColorCount colorCount : colorCounts) {
result.append(colorCount.getCount()); // Häufigkeit
result.append(productType); // Produkttyp
result.append(" ");
result.append(colorCount.getColor()); // Farbe
result.append(" ");
}
// Entferne das letzte Leerzeichen
if (result.length() > 0) {
result.setLength(result.length() - 1);
}
return result.toString();
}
private Article getArticleProperties(String imagePath) throws Exception {
String filename = new File(imagePath).getName();
String farben = "abcdefghijklmnopqrstuvwxyz";
String productType = "";
int i = 0;
while (true) {
if (Character.isDigit(filename.charAt(i))) {
break;
}
productType += filename.charAt(i);
i++;
}
while (true) {
if (!Character.isDigit(filename.charAt(i))) {
break;
}
i++;
}
String color = String.valueOf(filename.charAt(i));
// for colors with two letters
if (farben.indexOf(filename.charAt(i + 1)) != -1) {
color += String.valueOf(filename.charAt(i + 1));
}
// Prüfe, ob der Buchstabe in der Liste der Farben enthalten ist
if (farben.indexOf(color) == -1 && color.length() != 2) {
throw new Exception("Nicht alle Bilder enthalten Farbbuchstaben!");
}
return new Article(imagePath, color, productType);
}
private float[] getImageSize(String imagePath) {
try {
BufferedImage image = ImageIO.read(new File(imagePath));
return new float[] { image.getWidth(), image.getHeight() };
} catch (Exception e) {
return new float[] { 0, 0 };
}
}
private float pixelsToMm(float pixels) {
float dpi = 300;
return pixels / dpi * 25.4f;
}
}
}

View File

@@ -0,0 +1,398 @@
package com.server.api.service.rollendruck;
import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.element.Paragraph;
import com.server.api.models.VorlageRollendruck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import java.util.List;
import java.awt.image.BufferedImage;
@Service
public class VorlageRollendruckPDFGeneratorService {
final float pointsPerMm = 2.83464567f;
final float numberPointsForMm = 28.3465f;
@Autowired VorlageRollendruckService vorlageRollendruckService;
private static class ImageObject {
float x1;
float y1;
float x2;
float y2;
String imageGroup;
boolean isRotated;
String imagePath;
public ImageObject(float x1, float y1, float x2, float y2, String imageGroup, boolean isRotated,
String imagePath) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.imageGroup = imageGroup;
this.isRotated = isRotated;
this.imagePath = imagePath;
}
public float getX1() {
return x1;
}
public float getY1() {
return y1;
}
public float getX2() {
return x2;
}
public float getY2() {
return y2;
}
public boolean isRotated() {
return isRotated;
}
public String getImagePath() {
return imagePath;
}
}
private static class ImageGroup {
String name;
List<String> images;
float size;
public ImageGroup(String name) {
this.name = name;
this.images = new ArrayList<>();
}
public String getName() {
return name;
}
public List<String> getImages() {
return images;
}
public float getSize() {
return size;
}
public void setSize(float size) {
this.size = size;
}
}
private class Surface {
float height;
float width;
List<ImageObject> placedImages;
public Surface(float height, float width) {
this.height = height;
this.width = width;
this.placedImages = new ArrayList<>();
}
private List<String> placeImageGroup(List<String> imagePaths, float width, float height, String imageGroupName) throws MalformedURLException {
List<String> notPlacedImages = new ArrayList<>();
float cursor_x = 0;
float cursor_y = height * pointsPerMm;
for (String singleImagePath : imagePaths) {
ImageData imageData = ImageDataFactory.create(singleImagePath);
Image image = new Image(imageData);
float[] imageSize = getImageSize(singleImagePath);
float imageWidth = pixelsToMm(imageSize[0]);
float imageHeight = pixelsToMm(imageSize[1]);
image.scaleToFit(imageWidth * pointsPerMm, imageHeight * pointsPerMm);
boolean foundFreePos = false;
boolean isRotated = false;
float abstand = numberPointsForMm * pointsPerMm;
float updated_x = 0;
float updated_y = 0;
boolean isEndOfPage = false;
while (!foundFreePos) {
// cursor runs through the whole page
if (cursor_x + 1 > width * pointsPerMm) {
cursor_x = 0;
if (cursor_y - 1 < 0) {
isEndOfPage = true;
break;
} else {
cursor_y -= 1;
}
} else {
cursor_x += 1;
}
// check if cursor is not on an image
if (isOverlap(cursor_x, imageWidth, cursor_y - imageHeight * pointsPerMm, imageHeight)) {
continue;
}
updated_x = cursor_x + abstand;
updated_y = cursor_y - imageHeight * pointsPerMm - abstand;
boolean isLeftNeighbourOverlap = false;
for (ImageObject placedImage : placedImages) {
if(placedImage.y1 < cursor_y && placedImage.y2 > updated_y && placedImage.x2 >= cursor_x - 30 && placedImage.x1 < cursor_x - 30){
isLeftNeighbourOverlap = true;
break;
}
}
if (isLeftNeighbourOverlap) {
continue;
}
if (isOverlap(updated_x, imageWidth, updated_y, imageHeight)) {
continue;
}
if (updated_x + imageWidth * pointsPerMm < width * pointsPerMm
&& updated_y> 0) {
foundFreePos = true;
}
}
if (isEndOfPage) {
notPlacedImages.add(singleImagePath);
continue;
}
if (isRotated) {
placedImages.add(new ImageObject(updated_x, updated_y,
updated_x + imageHeight * pointsPerMm,
updated_y + imageWidth * pointsPerMm, imageGroupName, true, singleImagePath));
image.setFixedPosition(updated_x, updated_y);
image.setRotationAngle(Math.toRadians(90));
} else {
placedImages.add(new ImageObject(updated_x, updated_y,
updated_x + imageWidth * pointsPerMm,
updated_y + imageHeight * pointsPerMm, imageGroupName, false, singleImagePath));
image.setFixedPosition(updated_x, updated_y);
}
}
return notPlacedImages;
}
private boolean isOverlap(float cursor_x, float imageWidth, float cursor_y, float imageHeight) {
for (ImageObject imageObject : placedImages) {
if (imageObject.getX1() < cursor_x + imageWidth * pointsPerMm
&& imageObject.getX2() > cursor_x
&& imageObject.getY1() < cursor_y + imageHeight * pointsPerMm
&& imageObject.getY2() > cursor_y) {
return true;
}
}
return false;
}
}
public void generatePdf(long vorlageId, String outputDir, String uploadPath) throws Exception {
// get width and height from vorlage
VorlageRollendruck vorlage = vorlageRollendruckService.getVorlageById(vorlageId);
float width = vorlage.getWidth();
float height = vorlage.getHeight();
List<String> articleTypes = splitArticleTypes(vorlage.getArticleTypes());
List<String> dupliStrings = vorlageRollendruckService.getAllDupliStrings();
Path outputFolder = Paths.get(outputDir);
if (!Files.exists(outputFolder)) {
Files.createDirectories(outputFolder);
}
String imagePath = uploadPath;
File folder = new File(imagePath);
File[] files = folder.listFiles();
files = getAllFilePaths(imagePath);
// delete hidden files beginning with .
files = Arrays.stream(getAllFilePaths(imagePath)).filter(file -> !file.getName().startsWith(".")).toArray(File[]::new);
// create subgroups
List<ImageGroup> imageGroups = new ArrayList<>();
for (File file : files) {
String name = file.getName();
int i = 0;
while (i < name.length() && !Character.isDigit(name.charAt(i)) && name.charAt(i) != ' ') {
i++;
}
boolean isGroup = false;
for (ImageGroup imageGroup : imageGroups) {
if (imageGroup.getName().equals(name.substring(0, i).trim())) {
imageGroup.images.add(file.getAbsolutePath());
isGroup = true;
break;
}
}
if (!isGroup) {
String groupName = name.substring(0, i).trim();
ImageGroup imageGroup = new ImageGroup(groupName);
imageGroup.images.add(file.getAbsolutePath());
float[] imageSizes = getImageSize(file.getAbsolutePath());
float imageSize = pixelsToMm(imageSizes[0]) * pixelsToMm(imageSizes[1]);
imageGroup.setSize(imageSize);
imageGroups.add(imageGroup);
}
}
// delete imageGroups that are not in articleTypes
imageGroups.removeIf(imageGroup -> !articleTypes.contains(imageGroup.getName()));
// sort groups by size
imageGroups.sort((g1, g2) -> Float.compare(g2.getSize(), g1.getSize()));
// if imageGroup contains dupliStrings double the entries
for (ImageGroup imageGroup : imageGroups) {
if (dupliStrings.contains(imageGroup.getName())) {
List<String> images = new ArrayList<>(imageGroup.getImages());
for (String image : images) {
imageGroup.getImages().add(image);
}
}
}
List<Surface> surfaces = new ArrayList<>();
surfaces.add(new Surface(height, width));
int surfaceIndex = 0;
for (ImageGroup imageGroup : imageGroups) {
List<String> notPlacedImages = surfaces.get(surfaceIndex).placeImageGroup(imageGroup.getImages(), width, height, imageGroup.getName());
while (!notPlacedImages.isEmpty()) {
surfaces.add(new Surface(height, width));
surfaceIndex++;
notPlacedImages = surfaces.get(surfaceIndex).placeImageGroup(notPlacedImages, width, height, imageGroup.getName());
}
}
int count = 1;
for (Surface surface: surfaces){
try (PdfWriter writer = new PdfWriter(outputDir + count + ". " + vorlage.getPrinter() + " Rollendruck.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(
pdf, new PageSize(width * pointsPerMm, height * pointsPerMm))) {
for (ImageObject imageObject : surface.placedImages) {
ImageData imageData = ImageDataFactory.create(imageObject.getImagePath());
Image image = getImage(imageObject, imageData);
// Add image at fixed position
image.setFixedPosition(imageObject.getX1(), imageObject.getY1());
document.add(image);
// Add text under image
String caption = imageObject.getImagePath().substring(imageObject.getImagePath().lastIndexOf("/") + 1);
float textX = ((imageObject.getX2() - imageObject.getX1())/2) + imageObject.getX1() + caption.length()*2; // Centered
float textY = imageObject.getY1() - numberPointsForMm - 10; // Adjust to place below image
PdfDocument pdfDocument = document.getPdfDocument();
PdfCanvas pdfCanvas = new PdfCanvas(pdfDocument.getLastPage());
pdfCanvas.saveState();
// Apply a horizontal mirroring transformation
pdfCanvas.concatMatrix(-1, 0, 0, 1, textX * 2, 0);
Paragraph paragraph = new Paragraph(caption)
.setFontSize(11)
.setFixedPosition(textX, textY, 200);
// Add the mirrored paragraph to the document
document.add(paragraph);
pdfCanvas.restoreState();
}
}
count++;
}
}
private static List<String> splitArticleTypes(String articleTypes) {
if (articleTypes == null || articleTypes.isEmpty()) {
return new ArrayList<>();
}
// Split the string by commas and trim whitespace from each part
articleTypes = articleTypes.replaceAll(" ", ""); // Remove all whitespace
return Arrays.asList(articleTypes.split(","));
}
private static Image getImage(ImageObject imageObject, ImageData imageData) {
Image image = new Image(imageData);
if (imageObject.isRotated()) {
image.setRotationAngle(Math.toRadians(90));
image.setFixedPosition(imageObject.getX1(), imageObject.getY1());
image.scaleToFit(imageObject.getY2() - imageObject.getY1(),
imageObject.getX2() - imageObject.getX1());
} else {
image.setFixedPosition(imageObject.getX1(), imageObject.getY1());
image.scaleToFit(imageObject.getX2() - imageObject.getX1(),
imageObject.getY2() - imageObject.getY1());
}
return image;
}
private File[] getAllFilePaths(String directoryPath) throws Exception {
try (Stream<Path> paths = Files.walk(Paths.get(directoryPath))) {
return paths
.filter(Files::isRegularFile) // Behalte nur reguläre Dateien (keine Verzeichnisse)
.map(Path::toFile) // Konvertiere Path zu File
.toArray(File[]::new); // Sammle die Ergebnisse in ein Array
}
}
private float[] getImageSize(String imagePath) {
try {
BufferedImage image = ImageIO.read(new File(imagePath));
return new float[] { image.getWidth(), image.getHeight() };
} catch (Exception e) {
System.out.println("Error reading image: " + e.getMessage());
}
return new float[] { 0, 0 };
}
private float pixelsToMm(float pixels) {
float dpi = 300;
return pixels / dpi * 25.4f;
}
}

View File

@@ -0,0 +1,79 @@
package com.server.api.service.rollendruck;
import com.server.api.models.RollenDruckDupliArtikel;
import com.server.api.models.VorlageRollendruck;
import com.server.api.repository.RollenDruckDupliRepository;
import com.server.api.repository.VorlageRollendruckRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class VorlageRollendruckService {
@Autowired
private VorlageRollendruckRepository vorlageRollendruckRepository;
@Autowired
private RollenDruckDupliRepository rollenDruckDupliRepository;
public void createRollendruckVorlage(VorlageRollendruck vorlage) {
System.out.println("Das sie die Artiekl "+ vorlage.getArticleTypes());
vorlageRollendruckRepository.save(vorlage);
}
public List<VorlageRollendruck> getAllVorlagen() {
return vorlageRollendruckRepository.getAllVorlagenRollendruck();
}
public void alterVorlage(VorlageRollendruck vorlage) {
VorlageRollendruck vorlageInDB = vorlageRollendruckRepository.findById(vorlage.getId()).orElseThrow(() -> new RuntimeException("Vorlage not found"));
vorlageInDB.setPrinter(vorlage.getPrinter());
vorlageInDB.setHeight(vorlage.getHeight());
vorlageInDB.setWidth(vorlage.getWidth());
vorlageInDB.setArticleTypes(vorlage.getArticleTypes());
vorlageRollendruckRepository.save(vorlageInDB);
}
public void deleteVorlageRollendruck(Long id) {
VorlageRollendruck vorlage = vorlageRollendruckRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Vorlage not found"));
vorlageRollendruckRepository.delete(vorlage);
}
public void addDupliArtikel(RollenDruckDupliArtikel artikel) {
// save the article
rollenDruckDupliRepository.save(artikel);
}
public List<RollenDruckDupliArtikel> getAllDupliArtikel() {
// print all articles
for (RollenDruckDupliArtikel artikel : rollenDruckDupliRepository.findAll()) {
System.out.println(artikel);
}
return rollenDruckDupliRepository.findAll();
}
public void deleteDupliArtikel(Long id) {
RollenDruckDupliArtikel artikel = rollenDruckDupliRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Artikel not found"));
rollenDruckDupliRepository.delete(artikel);
}
public VorlageRollendruck getVorlageById(Long id) {
return vorlageRollendruckRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Vorlage not found"));
}
public List<String> getAllDupliStrings(){
List<RollenDruckDupliArtikel> dupliArtikelList = rollenDruckDupliRepository.findAll();
return dupliArtikelList.stream()
.map(RollenDruckDupliArtikel::getProduct_type)
.toList();
}
}

View File

@@ -0,0 +1,25 @@
package com.server.api.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashUtil {
public static String hash(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Hashing algorithm not found", e);
}
}
}

View File

@@ -0,0 +1,16 @@
spring.application.name=api
spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5432/postgres}
spring.datasource.username=${DB_USERNAME:postgres}
spring.datasource.password=${DB_PASSWORD:mysecretpassword}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=HikariPool-1
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.servlet.multipart.enabled=false
spring.profiles.active=development

View File

@@ -0,0 +1,13 @@
package com.server.api;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApiApplicationTests {
@Test
void contextLoads() {
}
}

View File

@@ -0,0 +1,12 @@
package com.server.api;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class FlaechendruckTests {
@Test
void testRightColorOrdering() {
}
}