1
|
package eu.dnetlib.goldoa.service.dao;
|
2
|
|
3
|
import eu.dnetlib.goldoa.domain.File;
|
4
|
import eu.dnetlib.goldoa.domain.Invoice;
|
5
|
import org.apache.commons.io.IOUtils;
|
6
|
import org.apache.commons.logging.Log;
|
7
|
import org.apache.commons.logging.LogFactory;
|
8
|
import org.hibernate.criterion.Restrictions;
|
9
|
import org.hibernate.type.StringType;
|
10
|
import org.springframework.stereotype.Repository;
|
11
|
|
12
|
import java.io.ByteArrayOutputStream;
|
13
|
import java.io.IOException;
|
14
|
import java.io.InputStream;
|
15
|
import java.util.List;
|
16
|
|
17
|
/**
|
18
|
* Created by panagiotis on 28/1/2017.
|
19
|
*/
|
20
|
@Repository
|
21
|
public class InvoiceDAO extends AbstractDao<String, Invoice>{
|
22
|
|
23
|
private Log logger = LogFactory.getLog(InvoiceDAO.class);
|
24
|
|
25
|
public Invoice saveInvoice(Invoice invoice) {
|
26
|
|
27
|
Invoice i = getByKey(invoice.getId());
|
28
|
Invoice i_merged = null;
|
29
|
|
30
|
if(i!=null) {
|
31
|
logger.debug("Merge invoice with id " + i.getId());
|
32
|
|
33
|
if(i.getFile()!=null)
|
34
|
invoice.setFile(i.getFile());
|
35
|
|
36
|
logger.debug("Invoice file " + invoice.getFile());
|
37
|
|
38
|
i_merged = (Invoice) getSession().merge(invoice);
|
39
|
}else
|
40
|
persist(invoice);
|
41
|
|
42
|
return invoice;
|
43
|
}
|
44
|
|
45
|
@SuppressWarnings("unchecked")
|
46
|
public Invoice getByKey(String invoiceId){
|
47
|
List<Invoice> inv = createEntityCriteria()
|
48
|
.add(Restrictions.eq("id",invoiceId)).list();
|
49
|
if(inv.size() > 0)
|
50
|
return inv.get(0);
|
51
|
return null;
|
52
|
}
|
53
|
|
54
|
public Invoice uploadInvoice(String invoiceId, String mimetype, InputStream inputStream) throws IOException {
|
55
|
Invoice inv = getByKey(invoiceId);
|
56
|
|
57
|
ByteArrayOutputStream baos = null;
|
58
|
baos = new ByteArrayOutputStream();
|
59
|
IOUtils.copy(inputStream, baos);
|
60
|
IOUtils.closeQuietly(baos);
|
61
|
|
62
|
|
63
|
File file = new File();
|
64
|
file.setId(getFileId());
|
65
|
file.setMimetype(mimetype);
|
66
|
file.setFile(baos.toByteArray());
|
67
|
|
68
|
inv.setFile(file);
|
69
|
return inv;
|
70
|
}
|
71
|
|
72
|
private String getFileId(){
|
73
|
return (String) getSession().createSQLQuery("select nextval('file_id_seq') as id").addScalar("id",StringType.INSTANCE)
|
74
|
.list().get(0);
|
75
|
}
|
76
|
}
|