1.1.34.1. fejezet, RestApi szerver és JPA (Postgresql)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.4</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>hu.infokristaly</groupId>
	<artifactId>HomeworkRestService</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>HomeworkRestService</name>
	<description>Spring and Rest project</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
 
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-rest</artifactId>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
 
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
 
</project>

FileInfo.java

package hu.infokristaly.homework4rest;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
@Entity
public class FileInfo {
	@Id 
	@GeneratedValue(strategy=GenerationType.AUTO)
	Long id;
	String fileName;
	String filePath;
	Long size;
 
	public FileInfo() {
 
	}
 
	public FileInfo(String fileName, String filePath, Long size) {
		this.fileName = fileName;
		this.filePath = filePath;
		this.size = size;
	}
 
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getFilePath() {
		return filePath;
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	public Long getSize() {
		return size;
	}
	public void setSize(Long size) {
		this.size = size;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((fileName == null) ? 0 : fileName.hashCode());
		result = prime * result + ((filePath == null) ? 0 : filePath.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((size == null) ? 0 : size.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		FileInfo other = (FileInfo) obj;
		if (fileName == null) {
			if (other.fileName != null)
				return false;
		} else if (!fileName.equals(other.fileName))
			return false;
		if (filePath == null) {
			if (other.filePath != null)
				return false;
		} else if (!filePath.equals(other.filePath))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (size == null) {
			if (other.size != null)
				return false;
		} else if (!size.equals(other.size))
			return false;
		return true;
	}
}

FileInfoRepository.java

package hu.infokristaly.homework4rest;
 
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
 
@Repository
public interface FileInfoRepository extends CrudRepository<FileInfo, Long>  { 
 
}

FileInfoService.java

package hu.infokristaly.homework4rest;
 
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class FileInfoService {
 
    @Autowired
    private FileInfoRepository fileInfoRepository;
 
    public List<FileInfo> findAll() {
    	List<FileInfo> result = new ArrayList<FileInfo>();
    	fileInfoRepository.findAll().forEach(fileInfo -> result.add(fileInfo));
    	return result;
    }
 
    public FileInfo save(FileInfo fileInfo) {
    	return fileInfoRepository.save(fileInfo);
    }
 
	public FileInfo findById(Long id) {
		return fileInfoRepository.findById(id).get();
	}
}

FileInfoController.java

package hu.infokristaly.homework4rest;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class FileInfoController {
 
	@Autowired
	private FileInfoService fileInfoService;
 
	@GetMapping("/findAll")
	List<FileInfo> findAll() {
		List<FileInfo> result = fileInfoService.findAll();
		return result;
	}
 
	@GetMapping("/getById/{id}")
	byte[] getById(@PathVariable Long id) {
		FileInfo result = fileInfoService.findById(id);
		File file = new File(result.filePath+File.separatorChar+result.fileName);
		if (file.exists()) {
			byte[] array = new byte[(int) file.length()];
			try {
				array = Files.readAllBytes(file.toPath());
			} catch (IOException e) {
				array = new byte[0];
				e.printStackTrace();
			}
			return array;
		} else {
			return new byte[0];
		}
	}
 
	@GetMapping("/findById/{id}")
	FileInfo findById(@PathVariable Long id) {
		FileInfo result = fileInfoService.findById(id);
		return result;
	}
 
	@PostMapping("/")
	FileInfo save(@RequestBody FileInfo fileInfo) {
		return fileInfoService.save(fileInfo);
	}
 
	@RequestMapping(value = "fileupload", method = { RequestMethod.POST, RequestMethod.PUT }, consumes = { "multipart/form-data;charset=UTF-8" })
	ResponseEntity<?> fileUpload(@RequestParam("field1") String field1,@RequestParam("file") MultipartFile file) {
		File localFile = new File("/home/pzoli/temp.jar");
		System.out.println(field1);
		try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(localFile)) {
			FileCopyUtils.copy(in, out);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
 
		URI location = fromCurrentRequest().buildAndExpand().toUri();
 
		return ResponseEntity.created(location).build();
	}
 
 
}

application.properties

## default connection pool
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5
 
## PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.username=[username]
spring.datasource.password=[password]
 
#drop n create table again, good for testing, comment this in production
spring.jpa.hibernate.ddl-auto=update
 
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB

Kapcsolódó hivatkozások: