1
|
package eu.dnetlib.repo.manager.service;
|
2
|
|
3
|
import com.fasterxml.jackson.databind.JsonNode;
|
4
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
5
|
import eu.dnetlib.domain.data.Repository;
|
6
|
import eu.dnetlib.repo.manager.domain.BrokerException;
|
7
|
import eu.dnetlib.repo.manager.domain.RepositorySnippet;
|
8
|
import eu.dnetlib.repo.manager.domain.Term;
|
9
|
import eu.dnetlib.repo.manager.domain.Tuple;
|
10
|
import eu.dnetlib.repo.manager.domain.broker.*;
|
11
|
import org.json.JSONException;
|
12
|
import org.springframework.beans.factory.annotation.Autowired;
|
13
|
import org.springframework.beans.factory.annotation.Value;
|
14
|
import org.springframework.core.ParameterizedTypeReference;
|
15
|
import org.springframework.http.*;
|
16
|
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
17
|
import org.springframework.stereotype.Service;
|
18
|
import org.springframework.util.LinkedMultiValueMap;
|
19
|
import org.springframework.util.MultiValueMap;
|
20
|
import org.springframework.web.client.RestClientException;
|
21
|
import org.springframework.web.client.RestTemplate;
|
22
|
import org.springframework.web.util.UriComponents;
|
23
|
import org.springframework.web.util.UriComponentsBuilder;
|
24
|
|
25
|
import javax.annotation.PostConstruct;
|
26
|
import java.io.IOException;
|
27
|
import java.io.InputStream;
|
28
|
import java.net.URL;
|
29
|
import java.util.*;
|
30
|
|
31
|
@Service("brokerService")
|
32
|
public class BrokerServiceImpl implements BrokerService {
|
33
|
|
34
|
@Autowired
|
35
|
private RepositoryServiceImpl repoAPI;
|
36
|
@Value("${services.broker.url}:${services.broker.port}/${services.broker.api}${services.broker.openaire}")
|
37
|
private String openairePath;
|
38
|
@Value("${services.broker.url}:${services.broker.port}/${services.broker.api}")
|
39
|
private String apiPath;
|
40
|
@Value("${topic_types.url}")
|
41
|
private String topicsURL;
|
42
|
|
43
|
private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger
|
44
|
.getLogger(BrokerServiceImpl.class);
|
45
|
|
46
|
@Autowired
|
47
|
RestTemplate restTemplate ;
|
48
|
|
49
|
private HttpHeaders httpHeaders;
|
50
|
|
51
|
private HashMap<String,Term> topics = new HashMap<String, Term>();
|
52
|
|
53
|
@Autowired
|
54
|
private EmailUtils emailUtils;
|
55
|
|
56
|
@PostConstruct
|
57
|
private void initDnetTopicsMap() {
|
58
|
|
59
|
httpHeaders = new HttpHeaders();
|
60
|
httpHeaders.set("Content-Type", "application/json");
|
61
|
|
62
|
LOGGER.debug("Init dnet topics!");
|
63
|
try (InputStream is = new URL(topicsURL).openStream() ){
|
64
|
ObjectMapper mapper = new ObjectMapper();
|
65
|
JsonNode root = mapper.readTree(is);
|
66
|
for (JsonNode term : root.path("terms") )
|
67
|
topics.put(term.path("code").textValue(), parseTerm(term));
|
68
|
} catch (IOException e) {
|
69
|
LOGGER.debug("Exception on initDnetTopicsMap" , e);
|
70
|
emailUtils.reportException(e);
|
71
|
}
|
72
|
}
|
73
|
|
74
|
private Term parseTerm(JsonNode term) {
|
75
|
return new Term(term.path("englishName").textValue(),term.path("nativeName").textValue(),
|
76
|
term.path("encoding").textValue(),term.path("code").textValue());
|
77
|
}
|
78
|
|
79
|
|
80
|
@Override
|
81
|
public DatasourcesBroker getDatasourcesOfUser(String user,String includeShared,String includeByOthers) throws JSONException {
|
82
|
long start = System.currentTimeMillis();
|
83
|
DatasourcesBroker ret = new DatasourcesBroker();
|
84
|
try {
|
85
|
ret.setDatasourcesOfUser(getDatasourcesOfUserType(repoAPI.getRepositoriesSnippetOfUser(user,"0","100")));
|
86
|
//TODO fix bug when values are true
|
87
|
// if (Boolean.parseBoolean(includeShared)) {
|
88
|
// List<String> sharedDatasourceIds = new ArrayList<String>();
|
89
|
// ret.setSharedDatasources(getDatasourcesOfUserType(getRepositoriesByIds(sharedDatasourceIds)));
|
90
|
// }
|
91
|
|
92
|
// if (Boolean.parseBoolean(includeByOthers)) {
|
93
|
// ret.setDatasourcesOfOthers(getDatasourcesOfUserType(getRepositoriesOfUser(user)));
|
94
|
// }
|
95
|
} catch (BrokerException | IOException e) {
|
96
|
LOGGER.debug("Exception on getDatasourcesOfUser" , e);
|
97
|
emailUtils.reportException(e);
|
98
|
}
|
99
|
long end = System.currentTimeMillis();
|
100
|
System.out.println("Getting datasources of user in " + (end-start)+"ms");
|
101
|
return ret;
|
102
|
}
|
103
|
|
104
|
@Override
|
105
|
public List<BrowseEntry> getTopicsForDatasource(String datasourceName) throws BrokerException {
|
106
|
final String service = "/topicsForDatasource";
|
107
|
|
108
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service)
|
109
|
.queryParam("ds", datasourceName);
|
110
|
|
111
|
ResponseEntity<List<BrowseEntry>> resp;
|
112
|
try {
|
113
|
resp = restTemplate.exchange(
|
114
|
builder.build().encode().toUri(),
|
115
|
HttpMethod.GET,
|
116
|
null,
|
117
|
new ParameterizedTypeReference<List<BrowseEntry>>() {
|
118
|
});
|
119
|
} catch (RestClientException e) {
|
120
|
LOGGER.debug("Exception on getTopicsForDatasource" , e);
|
121
|
emailUtils.reportException(e);
|
122
|
throw new BrokerException(e);
|
123
|
}
|
124
|
|
125
|
return resp.getBody();
|
126
|
}
|
127
|
|
128
|
@Override
|
129
|
public EventsPage advancedShowEvents(String page,
|
130
|
String size,
|
131
|
AdvQueryObject advQueryObject) throws BrokerException, JSONException ,IOException {
|
132
|
|
133
|
final String service = "/events/{page}/{pageSize}";
|
134
|
|
135
|
Map<String, Long> uriParams = new HashMap<>();
|
136
|
uriParams.put("page", Long.parseLong(page));
|
137
|
uriParams.put("pageSize", Long.parseLong(size));
|
138
|
|
139
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service);
|
140
|
|
141
|
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
|
142
|
advQueryObject.setPage(Long.parseLong(page));
|
143
|
HttpEntity<AdvQueryObject> entity = new HttpEntity<>(advQueryObject, httpHeaders);
|
144
|
ResponseEntity<EventsPage> resp;
|
145
|
try {
|
146
|
resp = restTemplate.exchange(
|
147
|
builder.buildAndExpand(uriParams).encode().toUri(),
|
148
|
HttpMethod.POST,
|
149
|
entity,
|
150
|
new ParameterizedTypeReference<EventsPage>() {
|
151
|
}
|
152
|
);
|
153
|
} catch (RestClientException e) {
|
154
|
LOGGER.debug("Exception on advancedShowEvents" , e);
|
155
|
emailUtils.reportException(e);
|
156
|
throw new BrokerException(e);
|
157
|
}
|
158
|
return resp.getBody();
|
159
|
|
160
|
|
161
|
}
|
162
|
|
163
|
|
164
|
private List<Tuple<BrowseEntry, String>> getDatasourcesOfUserType(List<RepositorySnippet> repositories) throws BrokerException {
|
165
|
long start = System.currentTimeMillis();
|
166
|
List<Tuple<BrowseEntry, String>> entries = new ArrayList<>();
|
167
|
for (RepositorySnippet repo : repositories) {
|
168
|
BrowseEntry temp = new BrowseEntry();
|
169
|
temp.setValue(repo.getOfficialname());
|
170
|
temp.setSize(new Long(0));
|
171
|
for (BrowseEntry e : getTopicsForDatasource(repo.getOfficialname())) {
|
172
|
temp.setSize(temp.getSize() + e.getSize());
|
173
|
}
|
174
|
Tuple<BrowseEntry, String> tup = new Tuple<>(temp, repo.getLogoUrl());
|
175
|
entries.add(tup);
|
176
|
}
|
177
|
|
178
|
// sort the collection by the second field of the tuple which is size
|
179
|
Collections.sort(entries, new Comparator<Tuple<BrowseEntry, String>>() {
|
180
|
@Override
|
181
|
public int compare(Tuple<BrowseEntry, String> e1, Tuple<BrowseEntry, String> e2) {
|
182
|
return (int) (e2.getFirst().getSize().longValue() - e1.getFirst().getSize().longValue());
|
183
|
}
|
184
|
});
|
185
|
long stop = System.currentTimeMillis();
|
186
|
System.out.println("getDatasourcesOfUserType returned in " + (stop-start) + "ms ");
|
187
|
|
188
|
return entries;
|
189
|
}
|
190
|
|
191
|
private List<Repository> getRepositoriesOfUser(String userEmail) throws JSONException {
|
192
|
|
193
|
int page = 0;
|
194
|
int size = 50;
|
195
|
List<Repository> rs ;
|
196
|
List<Repository> resultSet = new ArrayList<>();
|
197
|
|
198
|
while (true){
|
199
|
rs = repoAPI.getRepositoriesOfUser(userEmail, String.valueOf(page), String.valueOf(size));
|
200
|
resultSet.addAll(rs);
|
201
|
page+=1;
|
202
|
if(rs.size() == 0) break;
|
203
|
}
|
204
|
return resultSet;
|
205
|
}
|
206
|
|
207
|
private List<Repository> getRepositoriesByIds(List<String> sharedDatasourceIds) {
|
208
|
return null;
|
209
|
}
|
210
|
|
211
|
@Override
|
212
|
public EventsPage showEvents(String datasourceName,
|
213
|
String topic,
|
214
|
String page,
|
215
|
String size) throws BrokerException, JSONException {
|
216
|
|
217
|
final String service = "/events";
|
218
|
|
219
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service)
|
220
|
.queryParam("ds", datasourceName)
|
221
|
.queryParam("topic", topic)
|
222
|
.path("/{page}/{size}/");
|
223
|
|
224
|
ResponseEntity<EventsPage> resp;
|
225
|
try {
|
226
|
resp = restTemplate.exchange(
|
227
|
builder.build().expand(page, size).encode().toUri(),
|
228
|
HttpMethod.GET,
|
229
|
null,
|
230
|
new ParameterizedTypeReference<EventsPage>() {
|
231
|
});
|
232
|
} catch (RestClientException e) {
|
233
|
LOGGER.debug("Exception on showEvents" , e);
|
234
|
emailUtils.reportException(e);
|
235
|
throw new BrokerException(e);
|
236
|
}
|
237
|
return resp.getBody();
|
238
|
}
|
239
|
|
240
|
@Override
|
241
|
public Map<String, List<SimpleSubscriptionDesc>> getSimpleSubscriptionsOfUser(String userEmail)
|
242
|
throws BrokerException {
|
243
|
|
244
|
final String service = "/subscriptions";
|
245
|
|
246
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service)
|
247
|
.queryParam("email", userEmail);
|
248
|
|
249
|
LOGGER.debug(builder.build().encode().toUri());
|
250
|
ResponseEntity<Map<String, List<SimpleSubscriptionDesc>>> resp;
|
251
|
try {
|
252
|
resp = restTemplate.exchange(
|
253
|
builder.build().encode().toUri(),
|
254
|
HttpMethod.GET,
|
255
|
null,
|
256
|
new ParameterizedTypeReference<Map<String, List<SimpleSubscriptionDesc>>>() {
|
257
|
});
|
258
|
} catch (RestClientException e) {
|
259
|
LOGGER.debug("Exception on getSimpleSubscriptionsOfUser" , e);
|
260
|
emailUtils.reportException(e);
|
261
|
throw new BrokerException(e);
|
262
|
}
|
263
|
return resp.getBody();
|
264
|
}
|
265
|
|
266
|
@Override
|
267
|
public Map<String, List<SimpleSubscriptionDesc>> getSimpleSubscriptionsOfUserByRepoId(String userEmail, String repoId) throws BrokerException {
|
268
|
Map<String, List<SimpleSubscriptionDesc>> subscriptionsOfUser = getSimpleSubscriptionsOfUser(userEmail);
|
269
|
|
270
|
return null;
|
271
|
}
|
272
|
|
273
|
@Override
|
274
|
public Subscription subscribe(OpenaireSubscription obj) throws BrokerException {
|
275
|
final String service = "/subscribe";
|
276
|
|
277
|
//build the uri params
|
278
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openairePath + service);
|
279
|
|
280
|
HttpEntity<OpenaireSubscription> entity = new HttpEntity<>(obj, httpHeaders);
|
281
|
|
282
|
//create new template engine
|
283
|
RestTemplate template = new RestTemplate();
|
284
|
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
|
285
|
ResponseEntity<Subscription> resp;
|
286
|
try {
|
287
|
//communicate with endpoint
|
288
|
resp = restTemplate.exchange(
|
289
|
builder.build().encode().toUri(),
|
290
|
HttpMethod.POST,
|
291
|
entity,
|
292
|
new ParameterizedTypeReference<Subscription>() {
|
293
|
});
|
294
|
} catch (RestClientException e) {
|
295
|
LOGGER.debug("Exception on OpenaireSubscription" , e);
|
296
|
emailUtils.reportException(e);
|
297
|
throw new BrokerException(e);
|
298
|
}
|
299
|
|
300
|
return resp.getBody();
|
301
|
}
|
302
|
|
303
|
@Override
|
304
|
public ResponseEntity<Object> unsubscribe(String subscriptionId) throws BrokerException {
|
305
|
final String service = "/subscriptions/" + subscriptionId;
|
306
|
|
307
|
//build the uri params
|
308
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiPath + service);
|
309
|
|
310
|
try {
|
311
|
//communicate with endpoint
|
312
|
restTemplate.exchange(
|
313
|
builder.build().encode().toUri(),
|
314
|
HttpMethod.DELETE,
|
315
|
null,
|
316
|
new ParameterizedTypeReference<Void>() {
|
317
|
});
|
318
|
} catch (RestClientException e) {
|
319
|
LOGGER.debug("Exception on unsubscribe" , e);
|
320
|
emailUtils.reportException(e);
|
321
|
throw new BrokerException(e);
|
322
|
}
|
323
|
return new ResponseEntity<>("OK",HttpStatus.OK);
|
324
|
}
|
325
|
|
326
|
@Override
|
327
|
public Subscription getSubscription( String subscriptionId) throws BrokerException {
|
328
|
final String service = "/subscriptions/" + subscriptionId;
|
329
|
|
330
|
//build the uri params
|
331
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiPath + service);
|
332
|
|
333
|
ResponseEntity<Subscription> resp;
|
334
|
try {
|
335
|
//communicate with endpoint
|
336
|
resp = restTemplate.exchange(
|
337
|
builder.build().encode().toUri(),
|
338
|
HttpMethod.GET,
|
339
|
null,
|
340
|
new ParameterizedTypeReference<Subscription>() {
|
341
|
});
|
342
|
} catch (RestClientException e) {
|
343
|
LOGGER.debug("Exception on getSubscription" , e);
|
344
|
emailUtils.reportException(e);
|
345
|
throw new BrokerException(e);
|
346
|
}
|
347
|
return resp.getBody();
|
348
|
}
|
349
|
|
350
|
@Override
|
351
|
public Map<String, Term> getDnetTopics() throws BrokerException {
|
352
|
return topics;
|
353
|
}
|
354
|
|
355
|
@Override
|
356
|
public EventsPage getNotificationsBySubscriptionId(String subscriptionId,
|
357
|
String page,
|
358
|
String size) throws BrokerException {
|
359
|
|
360
|
UriComponents uriComponents = UriComponentsBuilder
|
361
|
.fromHttpUrl(openairePath + "/notifications/")
|
362
|
.path("/{id}/{page}/{size}/")
|
363
|
.build().expand(subscriptionId,page, size).encode();
|
364
|
|
365
|
ResponseEntity<EventsPage> resp;
|
366
|
try {
|
367
|
resp = restTemplate.exchange(
|
368
|
uriComponents.toUri(),
|
369
|
HttpMethod.GET,
|
370
|
null,
|
371
|
new ParameterizedTypeReference<EventsPage>() {
|
372
|
});
|
373
|
} catch (RestClientException e) {
|
374
|
LOGGER.debug("Exception on getNotificationsBySubscriptionId" , e);
|
375
|
emailUtils.reportException(e);
|
376
|
throw new BrokerException(e);
|
377
|
}
|
378
|
return resp.getBody();
|
379
|
}
|
380
|
|
381
|
//@Override
|
382
|
public Map<String, List<Subscription>> getSubscriptionsOfUser(String userEmail)
|
383
|
throws BrokerException {
|
384
|
|
385
|
Map<String, List<SimpleSubscriptionDesc>> simpleSubs = getSimpleSubscriptionsOfUser(userEmail);
|
386
|
Map<String,List<Subscription>> subs = new HashMap<>();
|
387
|
List<Subscription> subscriptions = null;
|
388
|
|
389
|
for(String s:simpleSubs.keySet()){
|
390
|
List<SimpleSubscriptionDesc> simpleSubscriptionDescs = simpleSubs.get(s);
|
391
|
for(SimpleSubscriptionDesc simpleSubscriptionDesc : simpleSubscriptionDescs) {
|
392
|
subscriptions = new ArrayList<>();
|
393
|
subscriptions.add(getSubscription(simpleSubscriptionDesc.getId()));
|
394
|
}
|
395
|
subs.put(s,subscriptions);
|
396
|
}
|
397
|
return subs;
|
398
|
}
|
399
|
|
400
|
|
401
|
}
|