package cc.fascinated.backend.service; import cc.fascinated.backend.exception.impl.BadRequestException; import cc.fascinated.backend.exception.impl.ResourceNotFoundException; import cc.fascinated.backend.model.Paste; import cc.fascinated.backend.repository.PasteRepository; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.Optional; @Service @Log4j2(topic = "Paste Service") public class PasteService { /** * The {@link PasteRepository} instance. */ private final PasteRepository pasteRepository; /** * The length of the paste id. */ @Value("${paste.id-length}") private int idLength; /** * The maximum size of the paste content. */ @Value("${paste.upload-size-limit}") private int uploadSizeLimit; @Autowired public PasteService(PasteRepository pasteRepository) { this.pasteRepository = pasteRepository; } /** * Creates a new paste with the specified content. * * @param content The content of the paste. * @return The id of the paste. */ public String createPaste(String content) { int length = content.length(); log.info("Creating a new paste. (characters: {})", length); // Check if the content is too large. if (length > uploadSizeLimit && uploadSizeLimit != -1) { log.info("Paste didn't meet the size requirements. (characters: {})", length); throw new BadRequestException("The paste content is too large, the limit is " + uploadSizeLimit + " characters"); } // Save the paste to the database. Paste paste = pasteRepository.save(new Paste( RandomStringUtils.randomAlphabetic(idLength), System.currentTimeMillis(), content )); log.info("Created a new paste with the id '{}'", paste.getId()); return paste.getId(); } /** * Gets the content of the paste with the specified id. * * @param id The id of the paste. * @return The content of the paste. */ public Paste getPaste(String id) { log.info("Getting paste with the id '{}'", id); Optional paste = pasteRepository.findById(id); // The paste does not exist. if (paste.isEmpty()) { log.info("Paste with the id '{}' not found", id); throw new ResourceNotFoundException("Paste '%s' not found".formatted(id)); } log.info("Got paste with the id '{}'", id); return paste.get(); } }