MDES: Upload OHLC CSV Via Curl

From start.spring.io, generate project for web, thymeleaf, and jpa, and add h2 dependencies to it.

Data Model

public class Student {
	private long id;
	private String name;
	private String email;
	public Student() {}
	
	public Student(long id, String name, String email) {
		this.id = id;
		this.name = name;
		this.email = email;
	}
...

DAO Services

@Mapper
public interface StudentsMapper {
	@Select("SELECT * FROM students where id=#{id}")
	public Student find(int id);
	
	@Select("SELECT * FROM students")
	public List<Student> findAll();
	
	@Update("MERGE INTO students KEY(id) VALUES (#{id},#{name},#{email})")
	public Integer insertOrUpdate(Student student);
	
	@Delete("DELETE FROM students WHERE id=#{id}")
	public void delete(int id);
}
public interface StudentService {
	public Student find(int id);
	public Student find(String id);
	public Student saveUpdateStudent(Student student);
	public Student delete(int id);
	public Student delete(String id);
}

Controllers

	@RequestMapping(value="/csv", consumes="text/plain", produces=MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<String> uploadCsv(@RequestBody String input){
		logger.info("input={}", input);
		return ResponseEntity.ok().build();
	}
curl -X POST --data-binary @student.txt -H "Content-Type: text/plain" http://localhost:8080/students/csv
	@PostMapping("/fileupload")
	public ResponseEntity<List<Student>> fileUpload(@RequestPart("file") MultipartFile file){
		List<Student> retval = Lists.newArrayList();
		
		List<String> lines;
		try {
			lines = ByteSource.wrap(file.getBytes()).asCharSource(Charsets.UTF_8).readLines();
			FluentIterable.from(lines).forEach(x->logger.info(x));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			 lines = ByteSource.wrap(file.getBytes()).asCharSource(Charsets.UTF_8).readLines();
			for(String line : lines) {
				retval.add(new Student.Builder().from(line).build());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		//update students
		for(Student item : retval) {
			service.saveUpdateStudent(item);
		}
		if(retval.size()==0) {
			return ResponseEntity.noContent().build();
		}else {
			return ResponseEntity.ok(retval);
		}
	}	
curl -v http://localhost:8080/students/fileupload -X POST -F "file=@student.txt" -H "Content-Type: multipart/form-data"

Published by

wofong

三千娑婆世界,三千难忘遗憾;回头乃是岸,此岸在何方;堪忍不能忍,万般看不穿;何时放得下,始得自在心。 I'm a programmer, a quantitative analyst, a photography hobbyist, a traveler, a runner, and a nature lover.

Leave a comment