Skip to content
Snippets Groups Projects
TsvService.java 1.53 KiB
package com.smartharvester.service;

import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;
import org.bson.BsonBinarySubType;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.webjars.NotFoundException;

import com.smartharvester.dao.TsvDaoRepository;
import com.smartharvester.model.TsvModel;

@Service
public class TsvService {
	
	@Autowired
	private TsvDaoRepository daoRepository;
	
	public String addTsv(MultipartFile file, String catalogId) throws IOException {
		
		TsvModel tsv = new TsvModel(new Binary(BsonBinarySubType.BINARY, file.getBytes()), catalogId, file.getContentType().toString());
		 
		 
//		FileUtils.writeByteArrayToFile(new File("./test.tsv"), tsv.getFile().getData());
//		System.out.println( Base64.getEncoder().encodeToString(tsv.getFile().getData()));
		
		if (this.daoRepository.findByCatalogId(catalogId) != null) {
			this.daoRepository.deleteByCatalogId(catalogId);
		}
		
		this.daoRepository.save(tsv);
		
		return tsv.getId();
		
	}
	
	public TsvModel getFileById(String catalogId) { 
		
		return this.daoRepository.findByCatalogId(catalogId).orElseThrow(() -> new NotFoundException("File not found")); 
		
		
    }
	
	public List<Binary> getAll() {
		return this.daoRepository.findAll().stream().map(e -> e.getFile()).collect(Collectors.toList());
	}

}