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.Tuple;
13
import eu.dnetlib.repo.manager.shared.broker.*;
14
import eu.dnetlib.repos.RepoApi;
15
import org.apache.log4j.Logger;
16
import org.json.JSONArray;
17
import org.json.JSONException;
18
import org.json.JSONObject;
19
import org.springframework.beans.factory.annotation.Autowired;
20
import org.springframework.beans.factory.annotation.Value;
21
import org.springframework.core.ParameterizedTypeReference;
22
import org.springframework.http.HttpEntity;
23
import org.springframework.http.HttpMethod;
24
import org.springframework.http.ResponseEntity;
25
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
26
import org.springframework.stereotype.Service;
27
import org.springframework.util.LinkedMultiValueMap;
28
import org.springframework.util.MultiValueMap;
29
import org.springframework.web.client.RestClientException;
30
import org.springframework.web.client.RestTemplate;
31
import org.springframework.web.util.UriComponentsBuilder;
32

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

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

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

    
48
    @Autowired
49
    private RepoApi repoAPI;
50

    
51

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

    
57

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
194
    /**
195
     * Helper class to aggregate the datasources topic sizes by datasource name.
196
     *
197
     * @param repositories to be aggregated
198
     * @return a List of BrowseEntry with the official name and the number of topics for each repo and logo url
199
     * @throws BrokerException
200
     */
201
    private List<Tuple<BrowseEntry, String>> getDatasourcesOfUserType(List<Repository> repositories) throws BrokerException {
202

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

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

    
225
        return entries;
226
    }
227
}
(2-2/6)