Project

General

Profile

« Previous | Next » 

Revision 48362

reimplementing project exporters using spring data repositories

View differences:

modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/DNetConfig.java
1
package eu.dnetlib;
2

  
3
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
4
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
5
import org.springframework.beans.factory.annotation.Value;
6
import org.springframework.context.annotation.Bean;
7
import org.springframework.context.annotation.Configuration;
8

  
9
/**
10
 * Created by claudio on 04/07/2017.
11
 */
12
@Configuration
13
public class DNetConfig {
14

  
15
	@Value("${services.is.lookup.url}")
16
	private String isLookupUrl;
17

  
18
	@Bean
19
	public ISLookUpService getLookUpService() {
20
		final JaxWsProxyFactoryBean jaxWsProxyFactory = new JaxWsProxyFactoryBean();
21
		jaxWsProxyFactory.setServiceClass(ISLookUpService.class);
22
		jaxWsProxyFactory.setAddress(isLookupUrl);
23
		return (ISLookUpService) jaxWsProxyFactory.create();
24
	}
25

  
26
}
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/model/project/ProjectDetail.java
1
package eu.dnetlib.openaire.exporter.model.project;
2

  
3
import java.io.IOException;
4
import java.io.StringReader;
5
import java.io.StringWriter;
6
import java.util.List;
7

  
8
import com.google.gson.Gson;
9
import org.supercsv.cellprocessor.Optional;
10
import org.supercsv.cellprocessor.ift.CellProcessor;
11
import org.supercsv.cellprocessor.ift.StringCellProcessor;
12
import org.supercsv.io.CsvBeanReader;
13
import org.supercsv.io.CsvBeanWriter;
14
import org.supercsv.io.ICsvBeanReader;
15
import org.supercsv.io.ICsvBeanWriter;
16
import org.supercsv.prefs.CsvPreference;
17
import org.supercsv.util.CsvContext;
18

  
19
/**
20
 * Created by claudio on 22/09/16.
21
 */
22
public class ProjectDetail {
23

  
24
	private static final String[] NAMEMAPPING = { "projectId", "acronym", "code", "jsonextrainfo", "fundingPath" };
25

  
26
	private String projectId;
27
	private String acronym;
28
	private String code;
29
	private String jsonextrainfo;
30
	private List<String> fundingPath;
31

  
32
	public ProjectDetail() {}
33

  
34
	public static ProjectDetail fromJson(final String json) {
35
		return new Gson().fromJson(json, ProjectDetail.class);
36
	}
37

  
38
	public static ProjectDetail fromCSV(final String csv) throws IOException {
39
		ICsvBeanReader beanReader = null;
40
		try {
41
			beanReader = new CsvBeanReader(new StringReader(csv), CsvPreference.STANDARD_PREFERENCE);
42
			return beanReader.read(ProjectDetail.class, NAMEMAPPING, getProcessors(new StringCellProcessor() {
43
				@Override
44
				public Object execute(final Object value, final CsvContext context) {
45
					return new Gson().fromJson(value.toString(), List.class);
46
				}
47
			}));
48
		} finally {
49
			if (beanReader != null) {
50
				beanReader.close();
51
			}
52
		}
53
	}
54

  
55
	/**
56
	 * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. Empty
57
	 * columns are read as null (hence the NotNull() for mandatory columns).
58
	 *
59
	 * @return the cell processors
60
	 */
61
	private static CellProcessor[] getProcessors(final CellProcessor fundingPathProcessor) {
62
		return new CellProcessor[] {
63
				new Optional(), // projectId
64
				new Optional(), // acronym
65
				new Optional(), // code
66
				new Optional(), // jsonextrainfo
67
				fundingPathProcessor
68
		};
69
	}
70

  
71
	public String asJson() {
72
		return new Gson().toJson(this) + '\n';
73
	}
74

  
75
	public String asCSV() throws IOException {
76
		final StringWriter sb = new StringWriter();
77
		try (ICsvBeanWriter beanWriter = new CsvBeanWriter(sb, CsvPreference.STANDARD_PREFERENCE)) {
78
			beanWriter.write(this, NAMEMAPPING, getProcessors(new StringCellProcessor() {
79
				@Override
80
				public Object execute(final Object value, final CsvContext context) {
81
					return new Gson().toJson(value);
82
				}
83
			}));
84
			beanWriter.flush();
85
		}
86

  
87
		return sb.toString();
88
	}
89

  
90
	public String getProjectId() {
91
		return projectId;
92
	}
93

  
94
	public ProjectDetail setProjectId(final String projectId) {
95
		this.projectId = projectId;
96
		return this;
97
	}
98

  
99
	public String getAcronym() {
100
		return acronym;
101
	}
102

  
103
	public ProjectDetail setAcronym(final String acronym) {
104
		this.acronym = acronym;
105
		return this;
106
	}
107

  
108
	public String getCode() {
109
		return code;
110
	}
111

  
112
	public ProjectDetail setCode(final String code) {
113
		this.code = code;
114
		return this;
115
	}
116

  
117
	public String getJsonextrainfo() {
118
		return jsonextrainfo;
119
	}
120

  
121
	public ProjectDetail setJsonextrainfo(final String jsonextrainfo) {
122
		this.jsonextrainfo = jsonextrainfo;
123
		return this;
124
	}
125

  
126
	public List<String> getFundingPath() {
127
		return fundingPath;
128
	}
129

  
130
	public ProjectDetail setFundingPath(final List<String> fundingPath) {
131
		this.fundingPath = fundingPath;
132
		return this;
133
	}
134

  
135
}
modules/dnet-openaire-exporter/trunk/src/main/resources/eu/dnetlib/openaire/exporter/sql/projects_details.sql
1
SELECT * FROM projects_details;
modules/dnet-openaire-exporter/trunk/src/test/java/eu/dnetlib/openaire/exporter/model/project/ProjectDetailsTest.java
1
package eu.dnetlib.openaire.exporter.model.project;
2

  
3
import java.io.IOException;
4

  
5
import org.junit.Test;
6

  
7
/**
8
 * Created by claudio on 05/07/2017.
9
 */
10
public class ProjectDetailsTest {
11

  
12
	@Test
13
	public void testCSV() throws IOException {
14

  
15
		final ProjectDetails p = ProjectDetails.fromCSV(
16
				"arc_________::ANZCCART,,ANZCCART,{},\"[\"\"\\u003cfundingtree\\u003e\\n      \\u003cfunder\\u003e\\n         \\u003cid\\u003earc_________::ARC\\u003c/id\\u003e\\n         \\u003cshortname\\u003eARC\\u003c/shortname\\u003e\\n         \\u003cname\\u003eAustralian Research Council (ARC)\\u003c/name\\u003e\\n         \\u003cjurisdiction\\u003eAU\\u003c/jurisdiction\\u003e\\n      \\u003c/funder\\u003e\\n      \\u003cfunding_level_0\\u003e\\n         \\u003cid\\u003earc_________::ARC::Special Research initiative (Australian and New Zealand Council for the Care of Animals in Research and Teaching)\\u003c/id\\u003e\\n         \\u003cname\\u003eSpecial Research initiative (Australian and New Zealand Council for the Care of Animals in Research and Teaching)\\u003c/name\\u003e\\n         \\u003cdescription\\u003eSpecial Research initiative (Australian and New Zealand Council for the Care of Animals in Research and Teaching)\\u003c/description\\u003e\\n         \\u003cparent/\\u003e\\n         \\u003cclass\\u003earc:fundingStream\\u003c/class\\u003e\\n      \\u003c/funding_level_0\\u003e\\n   \\u003c/fundingtree\\u003e\"\"]\"");
17

  
18
		System.out.println(p.asJson());
19

  
20
		System.out.println(p.asCSV());
21

  
22

  
23
	}
24

  
25
}
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/OpenaireExporterConfig.java
3 3
import com.mongodb.MongoClient;
4 4
import com.mongodb.MongoClientOptions;
5 5
import com.mongodb.ServerAddress;
6
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
6 7
import org.apache.commons.dbcp2.BasicDataSource;
8
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
7 9
import org.springframework.beans.factory.annotation.Value;
8 10
import org.springframework.context.annotation.Bean;
9 11
import org.springframework.context.annotation.Configuration;
......
38 40
	@Value("${openaire.datasource.publisher.mongodb.connectionsPerHost}")
39 41
	private int connectionsPerHost;
40 42

  
43
	@Value("${services.is.lookup.url}")
44
	private String isLookupUrl;
45

  
41 46
	@Bean
47
	public ISLookUpService getLookUpService() {
48
		final JaxWsProxyFactoryBean jaxWsProxyFactory = new JaxWsProxyFactoryBean();
49
		jaxWsProxyFactory.setServiceClass(ISLookUpService.class);
50
		jaxWsProxyFactory.setAddress(isLookupUrl);
51
		return (ISLookUpService) jaxWsProxyFactory.create();
52
	}
53

  
54
	@Bean
42 55
	public BasicDataSource getProjectDataSource() {
43 56
		return getDatasource(driverClassName, jdbcUrl, jdbcUser, jdbcPwd, jdbcMinIdle, jdbcMaxidle);
44 57
	}
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/model/project/ProjectTsv.java
1
package eu.dnetlib.openaire.exporter.model.project;
2

  
3
import java.sql.Date;
4
import java.util.List;
5
import javax.persistence.Column;
6
import javax.persistence.Entity;
7
import javax.persistence.Id;
8
import javax.persistence.Table;
9

  
10
import com.fasterxml.jackson.annotation.JsonIgnore;
11
import com.google.common.collect.Lists;
12
import io.swagger.annotations.ApiModel;
13
import org.apache.commons.lang3.StringUtils;
14

  
15
/**
16
 * Created by claudio on 05/07/2017.
17
 */
18
@Entity
19
@Table(name = "projects_tsv")
20
@ApiModel(value = "Project TSV model", description = "project TSV model description")
21
public class ProjectTsv {
22

  
23
	@Id
24
	@JsonIgnore
25
	private int id;
26
	private String code;
27
	private String acronym;
28
	private String title;
29
	@Column(name = "call_identifier")
30
	private String callIdentifier;
31
	private Date startdate;
32
	private Date enddate;
33
	@Column(name = "ec_sc39")
34
	private Boolean ecSc39;
35
	@Column(name = "oa_mandate_for_publications")
36
	private Boolean oaMandateForPublications;
37
	@Column(name = "oa_mandate_for_datasets")
38
	private Boolean oaMandateForDatasets;
39
	@JsonIgnore
40
	private String fundingpathid;
41
	private String description;
42
	@Column(name = "legalname")
43
	private String orgLegalname;
44
	@Column(name = "country")
45
	private String orgCountry;
46
	@Column(name = "role")
47
	private String orgRole;
48
	private String firstname;
49
	private String secondnames;
50
	private String email;
51

  
52
	public ProjectTsv() {}
53

  
54
	public List<String> asList() {
55
		return Lists.newArrayList(
56
				clean(getCode()),
57
				clean(getAcronym()),
58
				clean(getTitle()),
59
				clean(getCallIdentifier()),
60
				clean(getStartdate() != null ? getStartdate().toString() : ""),
61
				clean(getEnddate() != null ? getEnddate().toString() : ""),
62
				clean(String.valueOf(isOaMandateForPublications())),
63
				clean(String.valueOf(isOaMandateForDatasets())),
64
				clean(getDescription()),
65
				clean(getOrgLegalname()),
66
				clean(getOrgCountry()),
67
				clean(getOrgRole()),
68
				clean(getFirstname()),
69
				clean(getSecondnames()),
70
				clean(getEmail()));
71
	}
72

  
73
	private String clean(final String s) {
74
		return StringUtils.isNotBlank(s) ? "\"" + s.replaceAll("\\n|\\t|\\s+", " ").replace("\"","\"\"").trim() + "\"" : "";
75
	}
76

  
77
	public int getId() {
78
		return id;
79
	}
80

  
81
	public void setId(final int id) {
82
		this.id = id;
83
	}
84

  
85
	public String getCode() {
86
		return code;
87
	}
88

  
89
	public void setCode(final String code) {
90
		this.code = code;
91
	}
92

  
93
	public String getAcronym() {
94
		return acronym;
95
	}
96

  
97
	public void setAcronym(final String acronym) {
98
		this.acronym = acronym;
99
	}
100

  
101
	public String getTitle() {
102
		return title;
103
	}
104

  
105
	public void setTitle(final String title) {
106
		this.title = title;
107
	}
108

  
109
	public String getCallIdentifier() {
110
		return callIdentifier;
111
	}
112

  
113
	public void setCallIdentifier(final String callIdentifier) {
114
		this.callIdentifier = callIdentifier;
115
	}
116

  
117
	public Date getStartdate() {
118
		return startdate;
119
	}
120

  
121
	public void setStartdate(final Date startdate) {
122
		this.startdate = startdate;
123
	}
124

  
125
	public Date getEnddate() {
126
		return enddate;
127
	}
128

  
129
	public void setEnddate(final Date enddate) {
130
		this.enddate = enddate;
131
	}
132

  
133
	public Boolean isEcSc39() {
134
		return ecSc39;
135
	}
136

  
137
	public void setEcSc39(final Boolean ecSc39) {
138
		this.ecSc39 = ecSc39;
139
	}
140

  
141
	public Boolean isOaMandateForPublications() {
142
		return oaMandateForPublications;
143
	}
144

  
145
	public void setOaMandateForPublications(final Boolean oaMandateForPublications) {
146
		this.oaMandateForPublications = oaMandateForPublications;
147
	}
148

  
149
	public Boolean isOaMandateForDatasets() {
150
		return oaMandateForDatasets;
151
	}
152

  
153
	public void setOaMandateForDatasets(final Boolean oaMandateForDatasets) {
154
		this.oaMandateForDatasets = oaMandateForDatasets;
155
	}
156

  
157
	public String getFundingpathid() {
158
		return fundingpathid;
159
	}
160

  
161
	public void setFundingpathid(final String fundingpathid) {
162
		this.fundingpathid = fundingpathid;
163
	}
164

  
165
	public String getDescription() {
166
		return description;
167
	}
168

  
169
	public void setDescription(final String description) {
170
		this.description = description;
171
	}
172

  
173
	public String getOrgLegalname() {
174
		return orgLegalname;
175
	}
176

  
177
	public void setOrgLegalname(final String orgLegalname) {
178
		this.orgLegalname = orgLegalname;
179
	}
180

  
181
	public String getOrgCountry() {
182
		return orgCountry;
183
	}
184

  
185
	public void setOrgCountry(final String orgCountry) {
186
		this.orgCountry = orgCountry;
187
	}
188

  
189
	public String getOrgRole() {
190
		return orgRole;
191
	}
192

  
193
	public void setOrgRole(final String orgRole) {
194
		this.orgRole = orgRole;
195
	}
196

  
197
	public String getFirstname() {
198
		return firstname;
199
	}
200

  
201
	public void setFirstname(final String firstname) {
202
		this.firstname = firstname;
203
	}
204

  
205
	public String getSecondnames() {
206
		return secondnames;
207
	}
208

  
209
	public void setSecondnames(final String secondnames) {
210
		this.secondnames = secondnames;
211
	}
212

  
213
	public String getEmail() {
214
		return email;
215
	}
216

  
217
	public void setEmail(final String email) {
218
		this.email = email;
219
	}
220
}
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/model/project/ProjectDetails.java
1 1
package eu.dnetlib.openaire.exporter.model.project;
2 2

  
3 3
import java.io.IOException;
4
import java.io.StringReader;
4 5
import java.io.StringWriter;
6
import java.util.Arrays;
7
import java.util.List;
8
import javax.persistence.*;
5 9

  
10
import com.fasterxml.jackson.annotation.JsonIgnore;
6 11
import com.google.gson.Gson;
12
import io.swagger.annotations.ApiModel;
13
import org.hibernate.annotations.Type;
7 14
import org.supercsv.cellprocessor.Optional;
8 15
import org.supercsv.cellprocessor.ift.CellProcessor;
9 16
import org.supercsv.cellprocessor.ift.StringCellProcessor;
17
import org.supercsv.io.CsvBeanReader;
10 18
import org.supercsv.io.CsvBeanWriter;
19
import org.supercsv.io.ICsvBeanReader;
11 20
import org.supercsv.io.ICsvBeanWriter;
12 21
import org.supercsv.prefs.CsvPreference;
13 22
import org.supercsv.util.CsvContext;
......
15 24
/**
16 25
 * Created by claudio on 04/07/2017.
17 26
 */
18
//@Entity
19
//@Table(name = "project_details")
20
//@ApiModel(value = "Project details model", description = "provides project details")
27
@Entity
28
@Table(name = "project_details")
29
@ApiModel(value = "Project details model", description = "provides project details")
21 30
public class ProjectDetails {
22 31

  
23
	private static final String[] NAMEMAPPING = { "projectid", "acronym", "code", "jsonextrainfo", "fundingpath" };
32
	@Transient
33
	@JsonIgnore
34
	private transient static final String[] FIELDS = Arrays.stream(ProjectDetails.class.getDeclaredFields())
35
			.map(f -> f.getName())
36
			.filter(s -> !s.equals("FIELDS"))
37
			.filter(s -> !s.startsWith("optional"))
38
			.toArray(String[]::new);
24 39

  
25
	//@Id
26
	private String projectid;
40
	@Id
41
	@Column(name = "projectid")
42
	private String projectId;
27 43
	private String acronym;
28 44
	private String code;
29
	private String optional1;
30
	private String optional2;
45

  
46
	@Transient
47
	@JsonIgnore
48
	private transient String optional1;
49

  
50
	@Transient
51
	@JsonIgnore
52
	private transient String optional2;
53

  
31 54
	private String jsonextrainfo;
32
	private String[] fundingpath;
33 55

  
56
	@Type(type = "eu.dnetlib.openaire.exporter.model.GenericArrayUserType")
57
	@Column(name = "fundingpath", columnDefinition = "text[]")
58
	private String[] fundingPath;
59

  
34 60
	public ProjectDetails() {
35 61
	}
36 62

  
37
	public String getProjectid() {
38
		return projectid;
63
	public String getProjectId() {
64
		return projectId;
39 65
	}
40 66

  
41
	public void setProjectid(final String projectid) {
42
		this.projectid = projectid;
67
	public void setProjectId(final String projectId) {
68
		this.projectId = projectId;
43 69
	}
44 70

  
45 71
	public String getAcronym() {
......
82 108
		this.jsonextrainfo = jsonextrainfo;
83 109
	}
84 110

  
85
	public String[] getFundingpath() {
86
		return fundingpath;
111
	public String[] getFundingPath() {
112
		return fundingPath;
87 113
	}
88 114

  
89
	public void setFundingpath(final String[] fundingpath) {
90
		this.fundingpath = fundingpath;
115
	public void setFundingPath(final String[] fundingPath) {
116
		this.fundingPath = fundingPath;
91 117
	}
92 118

  
119
	public static ProjectDetails fromJson(final String json) {
120
		return new Gson().fromJson(json, ProjectDetails.class);
121
	}
122

  
123
	public static ProjectDetails fromCSV(final String csv) throws IOException {
124
		ICsvBeanReader beanReader = null;
125
		try {
126
			beanReader = new CsvBeanReader(new StringReader(csv), CsvPreference.STANDARD_PREFERENCE);
127
			return beanReader.read(ProjectDetails.class, FIELDS, getProcessors(new StringCellProcessor() {
128
				@Override
129
				public Object execute(final Object value, final CsvContext context) {
130
					return new Gson().fromJson(value.toString(), List.class);
131
				}
132
			}));
133
		} finally {
134
			if (beanReader != null) {
135
				beanReader.close();
136
			}
137
		}
138
	}
139

  
93 140
	/**
94 141
	 * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. Empty
95 142
	 * columns are read as null (hence the NotNull() for mandatory columns).
......
113 160
	public String asCSV() throws IOException {
114 161
		final StringWriter sb = new StringWriter();
115 162
		try (ICsvBeanWriter beanWriter = new CsvBeanWriter(sb, CsvPreference.STANDARD_PREFERENCE)) {
116
			beanWriter.write(this, NAMEMAPPING, getProcessors(new StringCellProcessor() {
163
			beanWriter.write(this, FIELDS, getProcessors(new StringCellProcessor() {
117 164
				@Override
118 165
				public Object execute(final Object value, final CsvContext context) {
119 166
					return new Gson().toJson(value);
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/model/ConverterTextArray.java
1
package eu.dnetlib.openaire.exporter.model;
2

  
3
import java.sql.Array;
4
import java.sql.Connection;
5
import java.sql.SQLException;
6
import java.util.Arrays;
7
import java.util.List;
8
import java.util.Map;
9
import java.util.stream.Collectors;
10
import javax.persistence.AttributeConverter;
11
import javax.persistence.Converter;
12
import javax.sql.DataSource;
13

  
14
import org.springframework.beans.BeansException;
15
import org.springframework.context.ApplicationContext;
16
import org.springframework.context.ApplicationContextAware;
17

  
18
/**
19
 * Created by claudio on 05/07/2017.
20
 */
21
@Converter
22
public class ConverterTextArray implements AttributeConverter<List<String>, Array>, ApplicationContextAware {
23

  
24
	private ApplicationContext applicationContext;
25

  
26
	@Override
27
	public Array convertToDatabaseColumn(List<String> attribute) {
28

  
29
		final Map<String, DataSource> datasources = applicationContext.getBeansOfType(DataSource.class);
30
		DataSource source = datasources.values().stream().findFirst().get();
31

  
32
		try {
33
			Connection conn = source.getConnection();
34
			Array array = conn.createArrayOf("text", attribute.toArray());
35
			return  array;
36

  
37
		} catch (SQLException e) {
38
			e.printStackTrace();
39
		}
40

  
41
		return null;
42

  
43
	}
44

  
45
	@Override
46
	public List<String> convertToEntityAttribute(Array dbData) {
47
		try {
48
			return Arrays.stream((Object[]) dbData.getArray()).map(d -> (String) d).collect(Collectors.toList());
49
		} catch (SQLException e) {
50
			e.printStackTrace();
51
			return null;
52
		}
53
	}
54

  
55
	@Override
56
	public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
57
		this.applicationContext = applicationContext;
58
	}
59
}
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/model/GenericArrayUserType.java
1
package eu.dnetlib.openaire.exporter.model;
2

  
3
import java.io.Serializable;
4
import java.sql.*;
5

  
6
import org.hibernate.HibernateException;
7
import org.hibernate.engine.spi.SessionImplementor;
8
import org.hibernate.usertype.UserType;
9

  
10
/**
11
 * Created by claudio on 05/07/2017.
12
 */
13
public class GenericArrayUserType<T extends Serializable> implements UserType {
14

  
15
	protected static final int[] SQL_TYPES = { Types.ARRAY };
16

  
17
	private  Class<T> typeParameterClass;
18

  
19
	@Override
20
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
21
		return this.deepCopy(cached);
22
	}
23

  
24
	@Override
25
	public Object deepCopy(Object value) throws HibernateException {
26
		return value;
27
	}
28

  
29
	@SuppressWarnings("unchecked")
30
	@Override
31
	public Serializable disassemble(Object value) throws HibernateException {
32
		return (T) this.deepCopy(value);
33
	}
34

  
35
	@Override
36
	public boolean equals(Object x, Object y) throws HibernateException {
37

  
38
		if (x == null) {
39
			return y == null;
40
		}
41
		return x.equals(y);
42
	}
43

  
44
	@Override
45
	public int hashCode(Object x) throws HibernateException {
46
		return x.hashCode();
47
	}
48

  
49
	@Override
50
	public boolean isMutable() {
51
		return true;
52
	}
53

  
54
	@Override
55
	public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner)
56
			throws HibernateException, SQLException {
57
		if (resultSet.wasNull()) {
58
			return null;
59
		}
60
		if (resultSet.getArray(names[0]) == null) {
61
			return new Integer[0];
62
		}
63

  
64
		Array array = resultSet.getArray(names[0]);
65
		@SuppressWarnings("unchecked")
66
		T javaArray = (T) array.getArray();
67
		return javaArray;
68
	}
69

  
70
	@Override
71
	public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor session)
72
			throws HibernateException, SQLException {
73
		Connection connection = statement.getConnection();
74
		if (value == null) {
75
			statement.setNull(index, SQL_TYPES[0]);
76
		} else {
77
			@SuppressWarnings("unchecked")
78
			T castObject = (T) value;
79
			Array array = connection.createArrayOf("integer", (Object[]) castObject);
80
			statement.setArray(index, array);
81
		}
82
	}
83

  
84
	@Override
85
	public Object replace(Object original, Object target, Object owner) throws HibernateException {
86
		return original;
87
	}
88

  
89
	@Override
90
	public Class<T> returnedClass() {
91
		return typeParameterClass;
92
	}
93

  
94
	@Override
95
	public int[] sqlTypes() {
96
		return new int[] { Types.ARRAY };
97
	}
98

  
99

  
100
}
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/project/repository/ProjectTsvRepository.java
1
package eu.dnetlib.openaire.exporter.project.repository;
2

  
3
import eu.dnetlib.openaire.exporter.model.project.ProjectTsv;
4
import org.springframework.data.repository.PagingAndSortingRepository;
5
import org.springframework.stereotype.Repository;
6

  
7
/**
8
 * Created by claudio on 04/07/2017.
9
 */
10
@Repository
11
public interface ProjectTsvRepository extends PagingAndSortingRepository<ProjectTsv, String> {
12

  
13
	Iterable<ProjectTsv> findByFundingpathidStartingWithOrderByAcronym(String fundingpathid);
14

  
15
	Iterable<ProjectTsv> findByFundingpathidStartingWithAndOaMandateForDatasetsOrderByAcronym(String fundingpathid, boolean article293);
16

  
17
}
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/project/repository/ProjectDetailsRepository.java
1 1
package eu.dnetlib.openaire.exporter.project.repository;
2 2

  
3
import eu.dnetlib.openaire.exporter.model.project.ProjectDetails;
4
import org.springframework.data.repository.PagingAndSortingRepository;
5
import org.springframework.stereotype.Repository;
6

  
3 7
/**
4 8
 * Created by claudio on 04/07/2017.
5 9
 */
6
//@Repository
7
public interface ProjectDetailsRepository /*extends PagingAndSortingRepository<ProjectDetails, String>*/ {
10
@Repository
11
public interface ProjectDetailsRepository extends PagingAndSortingRepository<ProjectDetails, String> {
8 12

  
9 13
}
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/project/JdbcApiDao.java
8 8
import java.time.LocalDateTime;
9 9
import java.util.Arrays;
10 10
import java.util.List;
11
import java.util.zip.GZIPOutputStream;
12 11
import java.util.zip.ZipOutputStream;
13 12

  
14 13
import com.google.common.base.Function;
......
17 16
import com.google.common.collect.Iterables;
18 17
import com.google.common.collect.Lists;
19 18
import eu.dnetlib.openaire.exporter.model.project.Project;
20
import eu.dnetlib.openaire.exporter.model.project.ProjectDetail;
21 19
import org.antlr.stringtemplate.StringTemplate;
22 20
import org.apache.commons.dbcp2.BasicDataSource;
23 21
import org.apache.commons.lang3.StringUtils;
......
133 131
	}
134 132

  
135 133

  
136
	public void streamProjectDetails(final String sql, final OutputStream out, final String format) throws SQLException, IOException {
137
		if (log.isDebugEnabled()) {
138
			log.debug("Thread " + Thread.currentThread().getId() + " begin");
139
		}
140
		final LocalDateTime start = LocalDateTime.now();
141
		int i = 0;
142
		try(final Connection con = getConn(); final PreparedStatement stm = getStm(sql, con); final ResultSet rs = stm.executeQuery()) {
143
			while (rs.next()) {
144
				final ProjectDetail p = getProjectDetail(rs);
145

  
146
				switch (format) {
147
				case "csv":
148
					out.write(p.asCSV().getBytes(UTF8));
149
					break;
150
				case "json":
151
					out.write(p.asJson().getBytes(UTF8));
152
					break;
153
				}
154
				if (++i % gzipFlushSize == 0) {
155
					log.debug("flushing output stream");
156
					out.flush();
157
				}
158
			}
159
			final LocalDateTime end = LocalDateTime.now();
160
			if (log.isDebugEnabled()) {
161
				log.debug("Thread " + Thread.currentThread().getId() + " ends, took: " + Duration.between(start, end));
162
			}
163
		} finally {
164
			if (out instanceof GZIPOutputStream) {
165
				((GZIPOutputStream) out).finish();
166
			}
167
			out.close();
168
		}
169
	}
170

  
171 134
	private Connection getConn() throws SQLException {
172 135
		final Connection conn = projectApiDataSource.getConnection();
173 136
		conn.setAutoCommit(false);
......
180 143
		return stm;
181 144
	}
182 145

  
183
	private ProjectDetail getProjectDetail(final ResultSet rs) throws SQLException {
184
		return new ProjectDetail()
185
				.setProjectId(rs.getString("projectid"))
186
				.setAcronym(rs.getString("acronym"))
187
				.setCode(rs.getString("code"))
188
				.setJsonextrainfo(rs.getString("jsonextrainfo"))
189
				.setFundingPath(asList(rs.getArray("fundingpath")));
190
	}
191

  
192 146
	private List<String> asList(final Array value) throws SQLException {
193 147
		if (value != null) {
194 148
			final List<Object> list = Arrays.asList((Object[]) value.getArray());
modules/dnet-openaire-exporter/trunk/src/main/java/eu/dnetlib/openaire/exporter/project/ProjectsController.java
8 8
import java.util.Arrays;
9 9
import java.util.Date;
10 10
import java.util.Map;
11
import java.util.concurrent.atomic.AtomicInteger;
11 12
import java.util.zip.GZIPOutputStream;
12 13
import java.util.zip.ZipEntry;
13 14
import java.util.zip.ZipOutputStream;
......
16 17
import javax.servlet.http.HttpServletRequest;
17 18
import javax.servlet.http.HttpServletResponse;
18 19

  
20
import com.google.common.base.Joiner;
19 21
import com.google.common.collect.Maps;
20 22
import com.google.common.xml.XmlEscapers;
21 23
import eu.dnetlib.common.rmi.DNetRestDocumentation;
24
import eu.dnetlib.openaire.exporter.datasource.ApiException;
25
import eu.dnetlib.openaire.exporter.model.project.ProjectTsv;
26
import eu.dnetlib.openaire.exporter.project.repository.ProjectDetailsRepository;
27
import eu.dnetlib.openaire.exporter.project.repository.ProjectTsvRepository;
22 28
import org.antlr.stringtemplate.StringTemplate;
23 29
import org.apache.commons.io.IOUtils;
24 30
import org.apache.commons.lang3.StringUtils;
......
70 76
	@Autowired
71 77
	private ProjectQueryParamsFactory projectQueryParamsFactory;
72 78

  
73
	//@Autowired
74
	//private ProjectDetailsRepository projectDetailsRepository;
79
	@Autowired
80
	private ProjectDetailsRepository projectDetailsRepository;
75 81

  
82
	@Autowired
83
	private ProjectTsvRepository projectTsvRepository;
84

  
76 85
	@Deprecated
77 86
	/**
78 87
	 * @deprecated  we should use the codes returned by the yet to come service
......
150 159
		dao.streamProjectsTSV(st.toString(), out);
151 160
	}
152 161

  
153
	@RequestMapping(value = "/openaire/export/streamProjectDetails.do", method = RequestMethod.GET)
154
	void streamProjectDetails(final HttpServletResponse response,
155
			@RequestParam(value = "format", required = true) final String format,
156
			@RequestParam(value = "compress", required = false) final Boolean compress) throws IOException, SQLException {
157
		final String sql = IOUtils.toString(projectDetailsSql.getInputStream(), UTF8);
162
	@RequestMapping(value = "/openaire/export/project2tsv2.do", method = RequestMethod.GET)
163
	void processTsv2(final HttpServletRequest request, final HttpServletResponse response,
164
			@RequestParam(value = "funding", required = true) final String funding,
165
			@RequestParam(value = "article293", required = false) final Boolean article293) throws Exception {
158 166

  
159
		if (compress != null && compress) {
160
			response.setHeader("Content-Encoding", "gzip");
167
		final Funding requestedFunding = Funding.valueOf(funding.toUpperCase());
168
		final String fundingPrefix = getFundingPrefix(requestedFunding, null);
169

  
170
		final String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
171
		final String filename = "projects_" + funding + "_" + date + ".tsv";
172
		response.setContentType("text/tab-separated-values");
173
		response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".zip\"");
174

  
175
		try(final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()))) {
176
			out.putNextEntry(new ZipEntry(filename));
177
			queryForTsv(fundingPrefix, article293).forEach(p -> {
178
				try {
179
					out.write(Joiner.on('\t').useForNull("").join(p.asList()).getBytes(UTF8));
180
					out.write('\n');
181
				} catch (IOException e) {
182
					throw new RuntimeException(e);
183
				}
184
			});
185
		} catch (Throwable e) {
186
			throw new ApiException(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error processing the request", e);
161 187
		}
162
		switch (format) {
163
		case "csv":
164
			response.setContentType("text/csv");
165
			break;
166
		case "json":
167
			response.setContentType("text/plain");
168
			break;
169
		default: throw new IllegalArgumentException("unsupported format: " + format);
188
	}
189

  
190
	private Iterable<ProjectTsv> queryForTsv(final String fundingPrefix, final Boolean article293) {
191
		log.debug(String.format("fundingPrefix:'%s' and article293:'%s'", fundingPrefix, article293));
192
		if (article293 != null) {
193
			return projectTsvRepository.findByFundingpathidStartingWithAndOaMandateForDatasetsOrderByAcronym(fundingPrefix, article293);
194
		} else {
195
			return projectTsvRepository.findByFundingpathidStartingWithOrderByAcronym(fundingPrefix);
170 196
		}
171

  
172
		final OutputStream outputStream = getOutputStream(response.getOutputStream(), compress);
173
		dao.streamProjectDetails(sql, outputStream, format);
174 197
	}
175 198

  
176
	@RequestMapping(value = "/openaire/export/streamProjectDetails2.do", method = RequestMethod.GET)
177
	void streamProjectDetails2(final HttpServletResponse response,
199
	@RequestMapping(value = "/openaire/export/streamProjectDetails.do", method = RequestMethod.GET)
200
	void streamProjectDetails(final HttpServletResponse response,
178 201
			@RequestParam(value = "format", required = true) final String format,
179 202
			@RequestParam(value = "compress", required = false) final Boolean compress) throws IOException, SQLException {
180
	/*
203

  
181 204
		if (compress != null && compress) {
182 205
			response.setHeader("Content-Encoding", "gzip");
183 206
		}
184

  
185 207
		switch (format) {
186 208
			case "csv":
187 209
				response.setContentType("text/csv");
......
211 233
							out.flush();
212 234
						}
213 235
					} catch (IOException e) {
214
						log.error("Unable to write to OutputStream", e);
236
						throw new RuntimeException(e);
215 237
					}
216 238
				}
217 239
			);
......
221 243
			}
222 244
			out.close();
223 245
		}
224
	*/
225 246
	}
226 247

  
227 248
	private OutputStream getOutputStream(final ServletOutputStream outputStream, final Boolean compress) throws IOException {
......
234 255
	@ExceptionHandler({Exception.class, Throwable.class})
235 256
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
236 257
	public @ResponseBody ErrorMessage handleSqlException(final Exception e) {
237
		log.error(e.getMessage());
238
		return new ErrorMessage(e);
258
		log.debug(e.getMessage(), e);
259
		if (StringUtils.containsIgnoreCase(ExceptionUtils.getRootCauseMessage(e), "Broken pipe")) {
260
			return null;        //socket is closed, cannot return any response
261
		} else {
262
			return new ErrorMessage(e);
263
		}
239 264
	}
240 265

  
241 266
	public class ErrorMessage {
modules/dnet-openaire-exporter/trunk/src/main/resources/logback-spring.xml
10 10
	<logger name="eu.dnetlib" level="INFO" additivity="false">
11 11
		<appender-ref ref="CONSOLE" />
12 12
	</logger>
13
	<logger name="eu.dnetlib.openaire.exporter.project.ProjectsController" level="DEBUG" additivity="false">
14
		<appender-ref ref="CONSOLE" />
15
	</logger>
13 16
</configuration>
modules/dnet-openaire-exporter/trunk/src/main/resources/application.properties
7 7

  
8 8
spring.datasource.driverClassName=org.postgresql.Driver
9 9
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
10
spring.jpa.show-sql=false
10
spring.jpa.show-sql=true
11 11
spring.jpa.hibernate.ddl-auto=validate
12 12

  
13 13
openaire.exporter.jdbc.url=jdbc:postgresql://localhost:5432/dnet_openaire

Also available in: Unified diff