Project

General

Profile

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

    
3
import com.fasterxml.jackson.core.JsonProcessingException;
4
import com.fasterxml.jackson.databind.ObjectMapper;
5
import eu.dnetlib.domain.data.Repository;
6
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
7
import eu.dnetlib.repo.manager.client.services.BrokerService;
8
import eu.dnetlib.repo.manager.service.controllers.BrokerApi;
9
import eu.dnetlib.repo.manager.service.controllers.RepositoryApi;
10
import eu.dnetlib.repo.manager.shared.BrokerException;
11
import eu.dnetlib.repo.manager.shared.RepositoryServiceException;
12
import eu.dnetlib.repo.manager.shared.Term;
13
import eu.dnetlib.repo.manager.shared.Tuple;
14
import eu.dnetlib.repo.manager.shared.broker.*;
15
import eu.dnetlib.repos.RepoApi;
16
import org.apache.log4j.Logger;
17
import org.json.JSONArray;
18
import org.json.JSONException;
19
import org.json.JSONObject;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.beans.factory.annotation.Value;
22
import org.springframework.core.ParameterizedTypeReference;
23
import org.springframework.http.HttpEntity;
24
import org.springframework.http.HttpMethod;
25
import org.springframework.http.ResponseEntity;
26
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
27
import org.springframework.stereotype.Service;
28
import org.springframework.util.LinkedMultiValueMap;
29
import org.springframework.util.MultiValueMap;
30
import org.springframework.web.client.RestClientException;
31
import org.springframework.web.client.RestTemplate;
32
import org.springframework.web.util.UriComponentsBuilder;
33

    
34
import javax.servlet.ServletConfig;
35
import javax.servlet.ServletException;
36
import java.io.IOException;
37
import java.util.*;
38

    
39
/**
40
 * Created by stefanos on 10/26/16.
41
 */
42
@SuppressWarnings("serial")
43
@Service("brokerService")
44
public class BrokerServiceImpl extends SpringGwtRemoteServiceServlet implements BrokerService {
45

    
46
    private static final Logger LOGGER = Logger
47
            .getLogger(BrokerServiceImpl.class);
48

    
49
    @Autowired
50
    private RepoApi repoAPI;
51

    
52

    
53
    @Autowired
54
    private RepositoryApi repositoryApi;
55
    @Autowired
56
    private BrokerApi brokerApi;
57

    
58

    
59
    @Override
60
    public void init(ServletConfig config) throws ServletException {
61
        super.init(config);
62
        LOGGER.info("broker service init");
63
    }
64

    
65
    @Value("${services.broker.url}:${services.broker.port}/${services.broker.api}${services.broker.openaire}")
66
    private String openairePath;
67
    @Value("${services.broker.url}:${services.broker.port}/${services.broker.api}")
68
    private String apiPath;
69

    
70
    /**
71
     * @param datasourceName the name of the data source
72
     * @return a list of BrowseEvent entries for that datasource
73
     * @throws BrokerException containing the error code from the server
74
     * @author stefanos
75
     */
76
    @Override
77
    public List<BrowseEntry> getTopicsForDatasource(String datasourceName) throws BrokerException {
78
        return brokerApi.getTopicsForDatasource(datasourceName);
79
    }
80

    
81
    /**
82
     * @param datasourceName the name of the datasource
83
     * @param topic          the name of the topic to filter
84
     * @param page           the page number
85
     * @return an Events page with a constant 50 max number of entires
86
     * @throws BrokerException containing the error code from the server
87
     */
88
    @Override
89
    public EventsPage showEvents(String datasourceName, String topic, long page) throws BrokerException{
90
        JSONObject params = new JSONObject();
91
        try {
92
            params.put("datasourceName",datasourceName);
93
            params.put("topic",topic);
94
            params.put("page",String.valueOf(page));
95
            return brokerApi.showEvents(params.toString());
96
        } catch (JSONException e) {
97
            LOGGER.debug("Error on show events",e);
98
        }
99
        return null;
100
    }
101

    
102
    /**
103
     * @param advQueryObject a pojo class containing the filter parameters
104
     * @param page           the number of the page
105
     * @param pageSize       the page size
106
     * @return
107
     * @throws BrokerException
108
     */
109
    @Override
110
    public EventsPage advancedShowEvents(AdvQueryObject advQueryObject, long page, long pageSize) throws BrokerException {
111

    
112
        JSONObject jsonObject = new JSONObject();
113
        try {
114
            jsonObject.put("page",String.valueOf(page));
115
            jsonObject.put("pagesize",String.valueOf(pageSize));
116
            ObjectMapper mapper = new ObjectMapper();
117
            String json_advQueryObject = mapper.writeValueAsString(advQueryObject);
118
            jsonObject.put("advQueryObject",json_advQueryObject);
119
            return brokerApi.advancedShowEvents(jsonObject.toString());
120
        } catch (Exception e) {
121
            LOGGER.debug("Error on advanced show events",e);
122
        }
123
        return null;
124
    }
125

    
126
    @Override
127
    public DatasourcesBroker getDatasourcesOfUser(String userEmail, boolean includeShared, boolean includeByOthers)
128
            throws BrokerException {
129

    
130
        JSONObject params = new JSONObject();
131
        try {
132
            params.put("userEmail",userEmail);
133
            params.put("includeShared",includeShared);
134
            params.put("includeByOthers",includeByOthers);
135
            return brokerApi.getDatasourcesOfUser(params.toString());
136
        } catch (JSONException e) {
137
            LOGGER.debug("Error on get datasources of user",e);
138
        }
139
        return null;
140
      /*  DatasourcesBroker ret = new DatasourcesBroker();
141
        try {
142
            LOGGER.debug("In getDatasourcesOfUser");
143

    
144
            //set for user
145
            ret.setDatasourcesOfUser(getDatasourcesOfUserType(this.repoAPI.getRepositoriesOfUser(userEmail, false)));
146

    
147
            //set for shared
148
            if (includeShared) {
149
                //TODO whatever nikonas was saying
150
                List<String> sharedDatasourceIds = new ArrayList<String>();
151
                ret.setSharedDatasources(getDatasourcesOfUserType(this.repoAPI.getReposByIds(sharedDatasourceIds)));
152
            }
153

    
154
            //set others
155
            if (includeByOthers) {
156
                ret.setDatasourcesOfOthers(getDatasourcesOfUserType(this.repoAPI.getRepositoriesOfUser(userEmail, true)));
157
            }
158

    
159
        } catch (RepositoryServiceException e) {
160
            e.printStackTrace();
161
            throw new BrokerException(e);
162
        } catch (Exception e) {
163
            e.printStackTrace();
164
        }
165
        return ret;*/
166
    }
167

    
168
    @Override
169
    public Map<String, List<SimpleSubscriptionDesc>> getSubscriptionsOfUser(String userEmail) throws BrokerException {
170
        return brokerApi.getSubscriptionsOfUser(userEmail);
171
    }
172

    
173
    @Override
174
    public Subscription subscribe(OpenaireSubscription obj) throws BrokerException {
175
        return brokerApi.subscribe(obj);
176
    }
177

    
178
    @Override
179
    public void unsubscribe(String subscriptionId) throws BrokerException {
180
        brokerApi.unsubscribe(subscriptionId);
181
    }
182

    
183
    @Override
184
    public Subscription getSubscription(String subscriptionId) throws BrokerException {
185
        return brokerApi.getSubscription(subscriptionId);
186
    }
187

    
188
    @Override
189
    public void unsubscribe(List<String> subscriptionIds) throws BrokerException {
190
        for (String subscriptionId : subscriptionIds) {
191
            unsubscribe(subscriptionId);
192
        }
193
    }
194

    
195
    public Map<String,Term> getDnetTopics() throws BrokerException {
196
        return brokerApi.getDnetTopics();
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

    
208
        //get user entries
209
        LOGGER.debug("getDatasourcesOfUserType : " + repositories.size());
210
        List<Tuple<BrowseEntry, String>> entries = new ArrayList<>();
211
        for (Repository repo : repositories) {
212
            BrowseEntry temp = new BrowseEntry();
213
            temp.setValue(repo.getOfficialName());
214
            temp.setSize(new Long(0));
215
            for (BrowseEntry e : this.getTopicsForDatasource(repo.getOfficialName())) {
216
                temp.setSize(temp.getSize() + e.getSize());
217
            }
218
            Tuple<BrowseEntry, String> tup = new Tuple<>(temp, repo.getLogoUrl());
219
            entries.add(tup);
220
        }
221

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

    
230
        return entries;
231
    }
232

    
233
}
(2-2/6)