Commit 0ce4516b authored by 0Tyler's avatar 0Tyler

document controller

parent a513b3c8
This diff is collapsed.
package edu.prlab.tyler.iotgateway.cloud.config;
import edu.prlab.tyler.iotgateway.cloud.pojo.Document;
import edu.prlab.tyler.iotgateway.cloud.pojo.device.Device;
import edu.prlab.tyler.iotgateway.cloud.pojo.device.Manufacturer;
import edu.prlab.tyler.iotgateway.cloud.pojo.device.Model;
......@@ -7,10 +8,12 @@ import edu.prlab.tyler.iotgateway.cloud.pojo.privacy.PrivacyPolicy;
import edu.prlab.tyler.iotgateway.cloud.pojo.privacy.PrivacyPolicyReport;
import edu.prlab.tyler.iotgateway.cloud.pojo.privacy.p3p.*;
import edu.prlab.tyler.iotgateway.cloud.services.DeviceService;
import edu.prlab.tyler.iotgateway.cloud.services.DocumentService;
import edu.prlab.tyler.iotgateway.cloud.services.PrivacyPolicyReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import static java.util.Arrays.asList;
......@@ -20,13 +23,15 @@ public class DefaultData implements ApplicationRunner {
private DeviceService deviceService;
private PrivacyPolicyReportService privacyPolicyReportService;
private DocumentService documentService;
@Autowired
public DefaultData(DeviceService deviceService,
PrivacyPolicyReportService privacyPolicyReportService) {
PrivacyPolicyReportService privacyPolicyReportService,
DocumentService documentService) {
this.deviceService = deviceService;
this.privacyPolicyReportService = privacyPolicyReportService;
this.documentService = documentService;
}
@Override
......@@ -102,12 +107,17 @@ public class DefaultData implements ApplicationRunner {
))
.build();
Document document = documentService.add(new MockMultipartFile("file", "test.txt",
"text/plain", "testFileStirng".getBytes()))
.orElse(Document.builder().build());
PrivacyPolicyReport oxygenPrivacyPolicyReport = PrivacyPolicyReport.builder()
.id("0cfb6be3-6f0f-4e63-85b8-e9c936707c0a")
.version("1.0")
.description("本APP會蒐集使用者周遭溫度、濕度及空氣品質作為第三方資料之地區環境分析資料。")
.device(oxygenDevice)
.policies(asList(oxygenPrivacyPolicy))
.document(document)
.build();
privacyPolicyReportService.add(oxygenPrivacyPolicyReport);
......@@ -229,12 +239,17 @@ public class DefaultData implements ApplicationRunner {
.build()))
.build();
document = documentService.add(new MockMultipartFile("file", "test.txt",
"text/plain", "testFileStirng".getBytes()))
.orElse(Document.builder().build());
PrivacyPolicyReport sensorPrivacyPolicyReport = PrivacyPolicyReport.builder()
.id("0cfb6be3-6f0f-4e63-85b8-e9c936707c0a")
.version("1.0")
.description("本APP會蒐集使用者周遭溫度、濕度及空氣品質作為第三方資料之地區環境分析資料。")
.device(sensorDevice)
.policies(asList(sensorPrivacyPolicy1,sensorPrivacyPolicy2,sensorPrivacyPolicy3))
.policies(asList(sensorPrivacyPolicy1, sensorPrivacyPolicy2, sensorPrivacyPolicy3))
.document(document)
.build();
privacyPolicyReportService.add(sensorPrivacyPolicyReport);
......
......@@ -2,7 +2,11 @@ package edu.prlab.tyler.iotgateway.cloud.controllers;
import edu.prlab.tyler.iotgateway.cloud.pojo.Document;
import edu.prlab.tyler.iotgateway.cloud.services.DocumentService;
import org.springframework.core.io.InputStreamResource;
import edu.prlab.tyler.iotgateway.cloud.services.PrivacyPolicyReportService;
import edu.prlab.tyler.iotgateway.cloud.util.CodeTools;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
......@@ -14,21 +18,30 @@ import java.io.IOException;
public class DocumentController {
private DocumentService documentService;
private PrivacyPolicyReportService privacyPolicyReportService;
public DocumentController(DocumentService documentService) {
public DocumentController(DocumentService documentService, PrivacyPolicyReportService privacyPolicyReportService) {
this.documentService = documentService;
this.privacyPolicyReportService = privacyPolicyReportService;
}
@PostMapping
public ResponseEntity<Document> uploadFile(@RequestPart MultipartFile file) throws IOException {
System.out.println(file.getName());
return documentService.add(file)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.noContent().build());
}
// @GetMapping("/{id}")
// public ResponseEntity<InputStreamResource> getFile(@PathVariable(value = "id") Long id) {
// return
// }
@GetMapping("/{udn}")
public ResponseEntity<ByteArrayResource> findFile(@PathVariable String udn) {
return privacyPolicyReportService.readByDevice(udn)
.map(privacyReport->privacyReport.getDocument().getId())
.flatMap(id->documentService.readFile(id))
.map(document -> ResponseEntity.ok()
.contentType(MediaType.parseMediaType(document.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename* = UTF-8''" + CodeTools.encode(document.getFileName()))
.body(new ByteArrayResource(document.getBytes())))
.orElseGet(() -> ResponseEntity.noContent().build());
}
}
......@@ -10,31 +10,31 @@ import java.util.Optional;
@RestController
public class GatewayController {
private PrivacyChoiceService privacyChoiceService;
private PrivacyChoiceService service;
@Autowired
public GatewayController(PrivacyChoiceService privacyChoiceService) {
this.privacyChoiceService = privacyChoiceService;
public GatewayController(PrivacyChoiceService service) {
this.service = service;
}
@PostMapping("/choice")
public ResponseEntity<PrivacyChoice> setPrivacyChoice(@RequestBody PrivacyChoice privacyChoice) {
return privacyChoiceService.add(privacyChoice)
return service.add(privacyChoice)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.noContent().build());
}
@GetMapping("/choice")
public ResponseEntity<Iterable<PrivacyChoice>> readPrivacyChoice() {
return Optional.of(privacyChoiceService.readll())
return Optional.of(service.readll())
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.noContent().build());
}
@GetMapping("/choice/{udn}")
public ResponseEntity<Iterable<PrivacyChoice>> readPrivacyChoiceByDevice(@PathVariable String udn) {
return Optional.ofNullable(privacyChoiceService.readPrivacyChoiceByDevice(udn))
return Optional.ofNullable(service.readPrivacyChoiceByDevice(udn))
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.noContent().build());
}
}
}
\ No newline at end of file
package edu.prlab.tyler.iotgateway.cloud.model;
public class PrivacyChoiceMessage {
}
package edu.prlab.tyler.iotgateway.cloud.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.*;
@Data
@Builder
......@@ -19,6 +16,11 @@ import javax.persistence.Id;
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
private Long id;
private String fileName;
private String fileType;
@Column(length=10000000)
@JsonIgnore
private byte[] bytes;
}
......@@ -6,7 +6,6 @@ import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.util.List;
......@@ -32,7 +31,6 @@ public class PrivacyPolicyReport {
@JoinColumn(name = "policy_id")
@ElementCollection(targetClass = PrivacyPolicy.class)
private List<PrivacyPolicy> policies ;
@OneToOne
@JoinColumn(name = "document_id")
private Document document;
......
......@@ -4,6 +4,8 @@ import edu.prlab.tyler.iotgateway.cloud.pojo.Document;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface DocumentRepository extends CrudRepository<Document, Long> {
}
package edu.prlab.tyler.iotgateway.cloud.repositories;
import edu.prlab.tyler.iotgateway.cloud.pojo.Document;
import edu.prlab.tyler.iotgateway.cloud.pojo.device.Device;
import edu.prlab.tyler.iotgateway.cloud.pojo.privacy.PrivacyPolicyReport;
import org.springframework.data.repository.CrudRepository;
......
......@@ -12,7 +12,7 @@ public abstract class CrudService<T, ID> {
}
public Optional<T> add(T pojo) {
System.out.println("save" + pojo.toString());
System.out.println("save " + pojo.toString());
return Optional.of(repository.save(pojo));
}
......
......@@ -2,28 +2,38 @@ package edu.prlab.tyler.iotgateway.cloud.services;
import edu.prlab.tyler.iotgateway.cloud.pojo.Document;
import edu.prlab.tyler.iotgateway.cloud.repositories.DocumentRepository;
import edu.prlab.tyler.iotgateway.cloud.services.storage.StorageService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Optional;
@Service
public class DocumentService {
private DocumentRepository documentRepository;
private StorageService storageService;
public DocumentService(DocumentRepository repository,
StorageService storageService) {
public DocumentService(DocumentRepository repository) {
this.documentRepository = repository;
this.storageService = storageService;
}
public Optional<Document> add(MultipartFile file) {
return Optional.ofNullable(storageService.store(file))
.map(filename -> Document.builder()
.fileName(filename)
return Optional.of(Document.builder()
.fileName(file.getOriginalFilename())
.fileType(file.getContentType())
.bytes(getBytes(file))
.build())
.map(document->documentRepository.save(document));
}
public Optional<Document> readFile(Long id){
return documentRepository.findById(id);
}
private byte[] getBytes(MultipartFile file) {
try{
return file.getBytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
package edu.prlab.tyler.iotgateway.cloud.services.storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
@Service
public class StorageService {
private final Path rootLocation;
@Autowired
public StorageService(@Value("${storage.location}") String rootLocation) {
this.rootLocation = Paths.get(rootLocation);
}
@PostConstruct
public void init() {
try {
deleteAll();
Files.createDirectories(rootLocation);
} catch (IOException e) {
throw new RuntimeException("Could not initialize storage location", e);
}
}
public String store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (file.isEmpty()) {
throw new RuntimeException("Failed to store empty file " + filename);
}
if (filename.contains("..")) {
// This is a security check
throw new RuntimeException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, this.rootLocation.resolve(filename),
StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
throw new RuntimeException("Failed to store file " + filename, e);
}
return filename;
}
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(this.rootLocation::relativize);
} catch (IOException e) {
throw new RuntimeException("Failed to read stored files", e);
}
}
public Path load(String filename) {
return rootLocation.resolve(filename);
}
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException(
"Could not read file: " + filename);
}
} catch (MalformedURLException e) {
throw new RuntimeException("Could not read file: " + filename, e);
}
}
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
}
package edu.prlab.tyler.iotgateway.cloud.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class CodeTools {
private CodeTools() {
}
public static String encode(String url) {
try {
String encodeURL = URLEncoder.encode(url, "UTF-8");
return encodeURL;
} catch (UnsupportedEncodingException e) {
return "Error: " + e.getMessage();
}
}
}
......@@ -3,6 +3,8 @@ spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.hikari.data-source-properties.useUnicode=true
spring.datasource.hikari.data-source-properties.characterEncoding=UTF-8
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment