Project

General

Profile

1
package eu.dnetlib.repo.manager.server.services;
2

    
3
import eu.dnetlib.domain.data.Repository;
4
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
5
import eu.dnetlib.repo.manager.client.services.BrokerService;
6
import eu.dnetlib.repo.manager.shared.BrokerException;
7
import eu.dnetlib.repo.manager.shared.RepositoryServiceException;
8
import eu.dnetlib.repo.manager.shared.Tuple;
9
import eu.dnetlib.repo.manager.shared.broker.AdvQueryObject;
10
import eu.dnetlib.repo.manager.shared.broker.BrowseEntry;
11
import eu.dnetlib.repo.manager.shared.broker.DatasourcesBroker;
12
import eu.dnetlib.repo.manager.shared.broker.EventsPage;
13
import eu.dnetlib.repos.RepoApi;
14
import org.apache.log4j.Logger;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.beans.factory.annotation.Value;
17
import org.springframework.core.ParameterizedTypeReference;
18
import org.springframework.http.HttpEntity;
19
import org.springframework.http.HttpMethod;
20
import org.springframework.http.ResponseEntity;
21
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
22
import org.springframework.stereotype.Service;
23
import org.springframework.util.LinkedMultiValueMap;
24
import org.springframework.util.MultiValueMap;
25
import org.springframework.web.client.RestClientException;
26
import org.springframework.web.client.RestTemplate;
27
import org.springframework.web.util.UriComponentsBuilder;
28

    
29
import javax.servlet.ServletConfig;
30
import javax.servlet.ServletException;
31
import java.util.*;
32

    
33
/**
34
 * Created by stefanos on 10/26/16.
35
 */
36
@SuppressWarnings("serial")
37
@Service("brokerService")
38
public class BrokerServiceImpl extends SpringGwtRemoteServiceServlet implements BrokerService {
39

    
40
    private static final Logger LOGGER = Logger
41
            .getLogger(BrokerServiceImpl.class);
42

    
43
    @Autowired
44
    private RepoApi repoAPI;
45

    
46
    @Override
47
    public void init(ServletConfig config) throws ServletException {
48
        super.init(config);
49
        LOGGER.info("broker service init");
50
    }
51

    
52
    @Value("${services.broker.url}:${services.broker.port}/${services.broker.path}")
53
    private String apiPath;
54

    
55
    /**
56
     * @param datasourceName the name of the data source
57
     * @return a list of BrowseEvent entries for that datasource
58
     * @throws BrokerException containing the error code from the server
59
     * @author stefanos
60
     */
61
    @Override
62
    public List<BrowseEntry> getTopicsForDatasource(String datasourceName) throws BrokerException {
63
        final String service = "/topicsForDatasource";
64

    
65
        //build the uri params
66
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiPath + service)
67
                .queryParam("ds", datasourceName);
68

    
69
        //create new template engine
70
        RestTemplate template = new RestTemplate();
71
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
72
        ResponseEntity<List<BrowseEntry>> resp;
73
        try {
74
            //communicate with endpoint
75
            resp = template.exchange(
76
                    builder.build().encode().toUri(),
77
                    HttpMethod.GET,
78
                    null,
79
                    new ParameterizedTypeReference<List<BrowseEntry>>() {
80
                    });
81
        } catch (RestClientException e) {
82
            throw new BrokerException(e);
83
        }
84

    
85
        return resp.getBody();
86
    }
87

    
88
    /**
89
     * @param datasourceName the name of the datasource
90
     * @param topic          the name of the topic to filter
91
     * @param page           the page number
92
     * @return an Events page with a constant 50 max number of entires
93
     * @throws BrokerException containing the error code from the server
94
     */
95
    @Override
96
    public EventsPage showEvents(String datasourceName, String topic, long page) throws BrokerException {
97
        final String service = "/showEvents";
98

    
99
        //build the uri params
100
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiPath + service)
101
                .queryParam("ds", datasourceName)
102
                .queryParam("topic", topic)
103
                .queryParam("page", page);
104

    
105
        //create new template engine
106
        RestTemplate template = new RestTemplate();
107
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
108
        ResponseEntity<EventsPage> resp;
109
        try {
110
            //communicate with endpoint
111
            resp = template.exchange(
112
                    builder.build().encode().toUri(),
113
                    HttpMethod.GET,
114
                    null,
115
                    new ParameterizedTypeReference<EventsPage>() {
116
                    });
117
        } catch (RestClientException e) {
118
            throw new BrokerException(e);
119
        }
120
        return resp.getBody();
121
    }
122

    
123
    /**
124
     * @param advQueryObject a pojo class containing the filter parameters
125
     * @param page           the number of the page
126
     * @param pageSize       the page size
127
     * @return
128
     * @throws BrokerException
129
     */
130
    @Override
131
    public EventsPage advancedShowEvents(AdvQueryObject advQueryObject, long page, long pageSize) throws BrokerException {
132
        final String service = "/advancedShowEvents/{page}/{pageSize}";
133

    
134
        // URI (URL) parameters
135
        Map<String, Long> uriParams = new HashMap<>();
136
        uriParams.put("page", page);
137
        uriParams.put("pageSize", pageSize);
138

    
139
        //build the uri params
140
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiPath + service);
141

    
142
        //Header info
143
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
144
        headers.add("Content-Type", "application/json");
145

    
146
        advQueryObject.setPage(page);
147

    
148
        HttpEntity<AdvQueryObject> entity = new HttpEntity<>(advQueryObject, headers);
149

    
150
        //create new template engine
151
        RestTemplate template = new RestTemplate();
152
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
153
        ResponseEntity<EventsPage> resp;
154
        try {
155
            //communicate with endpoint
156
            resp = template.exchange(
157
                    builder.buildAndExpand(uriParams).encode().toUri(),
158
                    HttpMethod.POST,
159
                    entity,
160
                    new ParameterizedTypeReference<EventsPage>() {
161
                    }
162
            );
163
        } catch (RestClientException e) {
164
            throw new BrokerException(e);
165
        }
166
        return resp.getBody();
167
    }
168

    
169
    @Override
170
    public DatasourcesBroker getDatasourcesOfUser(String userEmail, boolean includeShared, boolean includeByOthers) throws BrokerException {
171
        DatasourcesBroker ret = new DatasourcesBroker();
172
        try {
173
            LOGGER.debug("In getDatasourcesOfUser");
174

    
175
            //set for user
176
            ret.setDatasourcesOfUser(getDatasourcesOfUserType(this.repoAPI.getRepositoriesOfUser(userEmail, false)));
177

    
178
            //set for shared
179
            if (includeShared) {
180
                //TODO whatever nikonas was saying
181
                List<String> sharedDatasourceIds = new ArrayList<String>();
182
                ret.setSharedDatasources(getDatasourcesOfUserType(this.repoAPI.getReposByIds(sharedDatasourceIds)));
183
            }
184

    
185
            //set others
186
            if (includeByOthers) {
187
                ret.setDatasourcesOfOthers(getDatasourcesOfUserType(this.repoAPI.getRepositoriesOfUser(userEmail, true)));
188
            }
189

    
190
        } catch (RepositoryServiceException e) {
191
            e.printStackTrace();
192
            throw new BrokerException(e);
193
        } catch (Exception e) {
194
            e.printStackTrace();
195
        }
196
        return ret;
197
    }
198

    
199
    /**
200
     * Helper class to aggregate the datasources topic sizes by datasource name.
201
     *
202
     * @param repositories to be aggregated
203
     * @return a List of BrowseEntry with the official name and the number of topics for each repo and logo url
204
     * @throws BrokerException
205
     */
206
    private List<Tuple<BrowseEntry, String>> getDatasourcesOfUserType(List<Repository> repositories) throws BrokerException {
207
        //get user entries
208
        LOGGER.debug("getDatasourcesOfUserType : " + repositories.size());
209
        List<Tuple<BrowseEntry, String>> entries = new ArrayList<>();
210
        for (Repository repo : repositories) {
211
            BrowseEntry temp = new BrowseEntry();
212
            temp.setValue(repo.getOfficialName());
213
            temp.setSize(new Long(0));
214
            for (BrowseEntry e : this.getTopicsForDatasource(repo.getOfficialName())) {
215
                temp.setSize(temp.getSize() + e.getSize());
216
            }
217
            Tuple<BrowseEntry, String> tup = new Tuple<>(temp, repo.getLogoUrl());
218
            entries.add(tup);
219
        }
220

    
221
        // sort the collection by the second field of the tuple which is size
222
        Collections.sort(entries, new Comparator<Tuple<BrowseEntry, String>>() {
223
            @Override
224
            public int compare(Tuple<BrowseEntry, String> e1, Tuple<BrowseEntry, String> e2) {
225
                return (int) (e2.getFirst().getSize().longValue() - e1.getFirst().getSize().longValue());
226
            }
227
        });
228

    
229
        return entries;
230
    }
231
}
(2-2/5)