com.xlrit.gears.server.rest.DocumentController Maven / Gradle / Ivy
The newest version!
package com.xlrit.gears.server.rest;
import jakarta.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.common.base.Strings;
import com.xlrit.gears.base.content.Content;
import com.xlrit.gears.base.content.ContentRef;
import com.xlrit.gears.base.model.Document;
import com.xlrit.gears.base.repository.DocumentRepository;
import com.xlrit.gears.base.content.ContentStore;
import com.xlrit.gears.base.exception.NotFoundException;
import lombok.RequiredArgsConstructor;
@Controller
@RequiredArgsConstructor
public class DocumentController {
private static final Logger LOG = LoggerFactory.getLogger(DocumentController.class);
private final DocumentRepository documentRepository;
private final ContentStore contentStore;
@GetMapping("/document/{id:.+}")
@ResponseBody
@Transactional
@PreAuthorize("isAuthenticated()")
public ResponseEntity download(
@PathVariable String id,
@RequestParam(required = false, defaultValue = "false") boolean open) {
if (Strings.isNullOrEmpty(id)) throw new RuntimeException("Parameter 'id' is required");
Document document = documentRepository.findById(id);
if (document == null) throw new NotFoundException("document", "id", id);
LOG.info("Document with id '{}': {}", id, document);
ContentRef contentRef = document.getContentRef();
if (contentRef == null) throw new NotFoundException("document content", "id", id);
Content content = contentStore.findContent(contentRef.getId());
if (content == null) throw new NotFoundException("document content", "id", id);
String disposition = open ? null : "attachment; filename=\"" + document.getFilename() + "\"";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, content.getContentType())
.header(HttpHeaders.CONTENT_DISPOSITION, disposition)
.body(content.getData());
}
}