Project

General

Profile

« Previous | Next » 

Revision 61441

merged branch aai_roles_new to trunk

View differences:

modules/uoa-repository-manager-service/trunk/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java
14 14
public interface RepositoryService {
15 15

  
16 16

  
17
    Country[] getCountries() ;
17
    // TODO: move this elsewhere
18
    Country[] getCountries();
18 19

  
20
    List<Repository> getRepositories(List<String> ids) throws JSONException;
21

  
22
    List<Repository> getRepositories(List<String> ids, int page, int size) throws JSONException;
23

  
24
    List<RepositorySnippet> getRepositoriesSnippets(List<String> ids) throws Exception;
25

  
26
    List<RepositorySnippet> getRepositoriesSnippets(List<String> ids, int page, int size) throws Exception;
27

  
19 28
    List<RepositorySnippet> getRepositoriesByCountry(String country, String mode, Boolean managed) throws JSONException, IOException;
20 29

  
30
    // TODO: remove?
31
    List<Repository> getRepositoriesOfUser(String page, String size) throws JSONException, IOException;
32

  
33
    // TODO: remove?
21 34
    List<Repository> getRepositoriesOfUser(String userEmail,
22 35
                                           String page,
23 36
                                           String size) throws JSONException, IOException;
24 37

  
25
    List<RepositorySnippet> getRepositoriesSnippetOfUser(String userEmail, String page, String size) throws IOException, JSONException;
38
    List<RepositorySnippet> getRepositoriesSnippetsOfUser(String page, String size) throws Exception;
26 39

  
40
    List<RepositorySnippet> getRepositoriesSnippetsOfUser(String userEmail, String page, String size) throws Exception;
41

  
42
    RepositorySnippet getRepositorySnippetById(String id) throws JSONException, ResourceNotFoundException;
43

  
27 44
    Repository getRepositoryById(String id) throws JSONException, ResourceNotFoundException;
28 45

  
29 46
    List<AggregationDetails> getRepositoryAggregations(String id, int from, int size) throws JSONException;
30 47

  
31
    Map<String,List<AggregationDetails>> getRepositoryAggregationsByYear(String id) throws JSONException;
48
    Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(String id) throws JSONException;
32 49

  
33 50
    List<Repository> getRepositoriesByName(String name,
34 51
                                           String page,
35 52
                                           String size) throws JSONException;
36 53

  
37 54
    List<RepositorySnippet> searchRegisteredRepositories(String country, String typology, String englishName,
38
                                                                String officialName, String requestSortBy, String order,
39
                                                                int page, int pageSize) throws Exception;
55
                                                         String officialName, String requestSortBy, String order,
56
                                                         int page, int pageSize) throws Exception;
40 57

  
41 58
    List<RepositoryInterface> getRepositoryInterface(String id) throws JSONException;
42 59

  
......
59 76

  
60 77
    List<String> getUrlsOfUserRepos(String user_email,
61 78
                                    String page,
62
                                    String size) throws JSONException;
79
                                    String size);
63 80

  
64 81
    List<String> getDatasourceVocabularies(String mode);
65 82

  
......
71 88

  
72 89
    MetricsInfo getMetricsInfoForRepository(String repoId) throws RepositoryServiceException;
73 90

  
74
    Map<String, String> getListLatestUpdate(String mode) throws RepositoryServiceException, JSONException;
91
    Map<String, String> getListLatestUpdate(String mode) throws JSONException;
75 92

  
76 93
    RepositoryInterface updateRepositoryInterface(String repoId, String registeredBy, String comment, RepositoryInterface repositoryInterface) throws Exception;
77 94

  
modules/uoa-repository-manager-service/trunk/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java
1
package eu.dnetlib.repo.manager.service.aai.registry.utils;
2

  
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonObject;
5
import eu.dnetlib.repo.manager.domain.dto.Role;
6
import org.springframework.beans.factory.annotation.Value;
7
import org.springframework.stereotype.Component;
8

  
9
@Component
10
public class RegistryUtils {
11

  
12
    @Value("1.0")
13
    private String version;
14

  
15
    @Value("2")
16
    private String coid;
17

  
18
    public JsonObject coPersonRoles(Integer coPersonId, Integer couId, String status) {
19
        JsonObject role = new JsonObject();
20
        JsonArray coPersonRoles = new JsonArray();
21
        JsonObject coPersonRole = new JsonObject();
22
        JsonObject person = new JsonObject();
23
        person.addProperty("Type", "CO");
24
        person.addProperty("Id", coPersonId.toString());
25
        coPersonRole.addProperty("Version", version);
26
        coPersonRole.add("Person", person);
27
        coPersonRole.addProperty("CouId", couId.toString());
28
        coPersonRole.addProperty("Affiliation", "member");
29
        coPersonRole.addProperty("Title", "");
30
        coPersonRole.addProperty("O", "Openaire");
31
        coPersonRole.addProperty("Status", status);
32
        coPersonRole.addProperty("ValidFrom", "");
33
        coPersonRole.addProperty("ValidThrough", "");
34
        coPersonRoles.add(coPersonRole);
35
        role.addProperty("RequestType", "CoPersonRoles");
36
        role.addProperty("Version", version);
37
        role.add("CoPersonRoles", coPersonRoles);
38
        return role;
39
    }
40

  
41
    public JsonObject createNewCou(Role role) {
42
        JsonObject cou = new JsonObject();
43
        JsonArray cous = new JsonArray();
44
        JsonObject newCou = new JsonObject();
45
        newCou.addProperty("Version", version);
46
        newCou.addProperty("CoId", coid);
47
        newCou.addProperty("Name", role.getName());
48
        newCou.addProperty("Description", role.getDescription());
49
        cous.add(newCou);
50
        cou.addProperty("RequestType", "Cous");
51
        cou.addProperty("Version", version);
52
        cou.add("Cous", cous);
53
        return cou;
54
    }
55

  
56
    public JsonObject coGroupMembers(Integer coGroupId, Integer coPersonId, boolean member) {
57
        JsonObject coGroup = new JsonObject();
58
        JsonArray coGroupMembers = new JsonArray();
59
        JsonObject coGroupMember = new JsonObject();
60
        JsonObject person = new JsonObject();
61
        person.addProperty("Type", "CO");
62
        person.addProperty("Id", coPersonId.toString());
63
        coGroupMember.addProperty("Version", version);
64
        coGroupMember.add("Person", person);
65
        coGroupMember.addProperty("CoGroupId", coGroupId.toString());
66
        coGroupMember.addProperty("Member", member);
67
        coGroupMember.addProperty("Owner", false);
68
        coGroupMember.addProperty("ValidFrom", "");
69
        coGroupMember.addProperty("ValidThrough", "");
70
        coGroupMembers.add(coGroupMember);
71
        coGroup.addProperty("RequestType", "CoGroupMembers");
72
        coGroup.addProperty("Version", version);
73
        coGroup.add("CoGroupMembers", coGroupMembers);
74
        return coGroup;
75
    }
76
}
modules/uoa-repository-manager-service/trunk/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java
1
package eu.dnetlib.repo.manager.service.aai.registry;
2

  
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonObject;
5
import eu.dnetlib.repo.manager.domain.dto.Role;
6
import eu.dnetlib.repo.manager.domain.dto.User;
7

  
8
import java.util.List;
9
import java.util.Map;
10

  
11
public interface AaiRegistryService {
12

  
13
    /**
14
     * 1.1 Get CoPersonId by authenticated user's Email
15
     *
16
     * @return
17
     */
18
    Integer getCoPersonIdByEmail();
19

  
20
    /**
21
     * 1.2 Get CoPersonId by Email
22
     *
23
     * @param email
24
     * @return
25
     */
26
    Integer getCoPersonIdByEmail(String email);
27

  
28
    /**
29
     * 1. Get CoPersonId List by Email
30
     *
31
     * @param email
32
     * @return
33
     */
34
    List<Integer> getCoPersonIdsByEmail(String email);
35

  
36
    /**
37
     * 2. Get CoPersonId by AAI identifier
38
     *
39
     * @return
40
     */
41
    Integer getCoPersonIdByIdentifier();
42

  
43
    /**
44
     * 3.1 Get OpenAIRE cous with a specific name(or substring)
45
     *
46
     * @param name
47
     * @return
48
     */
49
    JsonArray getCous(String name);
50

  
51
    /**
52
     * 3.2 Get all OpenAIRE cous
53
     *
54
     * @return
55
     */
56
    JsonArray getCous();
57

  
58
    /**
59
     * 4.1 Get a couId by name
60
     *
61
     * @param name
62
     * @return
63
     */
64
    Integer getCouId(String name);
65

  
66
    /**
67
     * 4.2 Get a couId by type.id with/without mapping type
68
     *
69
     * @param type
70
     * @param id
71
     * @return
72
     */
73
    Integer getCouId(String type, String id, boolean communityMap);
74

  
75
    /**
76
     * 4.3 Get a couId by type.id with mapping type
77
     *
78
     * @param type
79
     * @param id
80
     * @return
81
     */
82
    Integer getCouId(String type, String id);
83

  
84
    /**
85
     * 5. Get User non admin roles
86
     *
87
     * @param coPersonId
88
     * @return
89
     */
90
    JsonArray getRoles(Integer coPersonId);
91

  
92
    /**
93
     * 5.2 Get User non admin active roles
94
     *
95
     * @param coPersonId
96
     * @return
97
     */
98
    JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status);
99

  
100
    /**
101
     * 6. Get Role id of User base on couId.
102
     *
103
     * @param coPersonId
104
     * @param couId
105
     * @return
106
     */
107
    Integer getRoleId(Integer coPersonId, Integer couId);
108

  
109
    /**
110
     * 7. Get User Groups
111
     *
112
     * @param coPersonId
113
     * @return
114
     */
115
    JsonArray getUserGroups(Integer coPersonId);
116

  
117
    /**
118
     * 8. Get User Admin Group of a Cou
119
     *
120
     * @param coPersonId
121
     * @param couId
122
     * @return
123
     */
124
    JsonObject getUserAdminGroup(Integer coPersonId, Integer couId);
125

  
126
    /**
127
     * 9. Get Groups of a Cou
128
     *
129
     * @param couId
130
     * @return
131
     */
132
    JsonArray getCouGroups(Integer couId);
133

  
134
    /**
135
     * 10. Get Admin Group of a Cou
136
     *
137
     * @param couId
138
     * @return
139
     */
140
    JsonObject getCouAdminGroup(Integer couId);
141

  
142
    /**
143
     * 11. Get users of a group
144
     *
145
     * @param coGroupId
146
     * @return
147
     */
148
    JsonArray getGroupMembers(Integer coGroupId);
149

  
150

  
151
    /**
152
     * 12. Get Users' email of a Cou
153
     *
154
     * @param couId
155
     * @param admin
156
     * @return
157
     */
158
    JsonArray getUserEmailByCouId(Integer couId, boolean admin);
159

  
160
    /**
161
     * 12.2 Get All Users that have a specific role // TODO: Keep or delete
162
     *
163
     * @param couId
164
     * @return
165
     */
166
    JsonArray getUsersByCouId(Integer couId);
167

  
168
    /**
169
     * 13. Get Users' names of a Cou
170
     *
171
     * @param couId
172
     * @param admin
173
     * @return
174
     */
175
    JsonArray getUserNamesByCouId(Integer couId, boolean admin);
176

  
177
    /**
178
     * 14. Get Users' identifiers of a Cou
179
     *
180
     * @param couId
181
     * @param admin
182
     * @return
183
     */
184
    JsonArray getUserIdByCouId(Integer couId, boolean admin);
185

  
186
    /**
187
     * 15. Assign a member role to a User
188
     *
189
     * @param coPersonId
190
     * @param couId
191
     * @param id
192
     */
193
    void assignMemberRole(Integer coPersonId, Integer couId, Integer id);
194

  
195
    /**
196
     * 16. Remove a member role from a User
197
     *
198
     * @param coPersonId
199
     * @param couId
200
     * @param id
201
     */
202
    void removeMemberRole(Integer coPersonId, Integer couId, Integer id);
203

  
204
    /**
205
     * 17. Create a new role
206
     *
207
     * @param role
208
     * @return
209
     */
210
    Integer createRole(Role role);
211

  
212
    /**
213
     * 18. Get User's email
214
     *
215
     * @param coPersonId
216
     * @return
217
     */
218
    String getUserEmail(Integer coPersonId);
219

  
220
    /**
221
     * 19. Get User's names
222
     *
223
     * @param coPersonId
224
     * @return
225
     */
226
    String getUserNames(Integer coPersonId);
227

  
228
    /**
229
     * 20. Get User's identifier
230
     *
231
     * @param coPersonId
232
     * @return
233
     */
234
    String getUserId(Integer coPersonId);
235

  
236
    /**
237
     * 21. Assign an admin role to a User
238
     *
239
     * @param coPersonId
240
     * @param couId
241
     */
242
    void assignAdminRole(Integer coPersonId, Integer couId);
243

  
244
    /**
245
     * 22. Remove an admin role from a User
246
     *
247
     * @param coPersonId
248
     * @param couId
249
     */
250
    void removeAdminRole(Integer coPersonId, Integer couId);
251

  
252
    /**
253
     * 23. Get a cou Names from couIds.
254
     *
255
     * @param couIds
256
     * @return
257
     */
258
    Map<Integer, String> getCouNames(List<Integer> couIds);
259

  
260
    // TODO: add description
261
    List<User> getUsers(Integer couId);
262

  
263
    enum RoleStatus {
264
        ACTIVE("Active"),
265
        APPROVED("Approved"),
266
        CONFIRMED("Confirmed"),
267
        DECLINED("Declined"),
268
        DELETED("Deleted"),
269
        DENIED("Denied"),
270
        DUPLICATE("Duplicate"),
271
        EXPIRED("Expired"),
272
        GRACE_PERIOD("GracePeriod"),
273
        INVITED("Invited"),
274
        PENDING("Pending"),
275
        PENDING_APPROVAL("PendingApproval"),
276
        PENDING_CONFIRMATION("PendingConfirmation"),
277
        SUSPENDED("Suspended");
278

  
279
        public final String status;
280

  
281
        RoleStatus(String status) {
282
            this.status = status;
283
        }
284
    }
285
}
modules/uoa-repository-manager-service/trunk/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java
1
package eu.dnetlib.repo.manager.service.aai.registry;
2

  
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonElement;
5
import com.google.gson.JsonObject;
6
import eu.dnetlib.repo.manager.domain.dto.Role;
7
import eu.dnetlib.repo.manager.domain.dto.User;
8
import eu.dnetlib.repo.manager.service.aai.registry.utils.RegistryUtils;
9
import eu.dnetlib.repo.manager.utils.HttpUtils;
10
import org.apache.log4j.Logger;
11
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
12
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.beans.factory.annotation.Value;
14
import org.springframework.security.core.context.SecurityContextHolder;
15
import org.springframework.stereotype.Service;
16

  
17
import java.net.URLEncoder;
18
import java.util.ArrayList;
19
import java.util.HashMap;
20
import java.util.List;
21
import java.util.Map;
22

  
23
@Service
24
public class RegistryCalls implements AaiRegistryService {
25

  
26
    private static final Logger logger = Logger.getLogger(RegistryCalls.class);
27

  
28
    private final String coid;
29
    public final HttpUtils httpUtils;
30
    public final RegistryUtils jsonUtils;
31

  
32
    @Autowired
33
    RegistryCalls(@Value("${aai.registry.coid:2}") String coid,
34
                  HttpUtils httpUtils, RegistryUtils registryUtils) {
35
        this.coid = coid;
36
        this.httpUtils = httpUtils;
37
        this.jsonUtils = registryUtils;
38
    }
39

  
40
    private String mapType(String type, boolean communityMap) {
41
        if (type.equals("organization")) {
42
            type = "institution";
43
        } else if (type.equals("ri") && communityMap) {
44
            type = "community";
45
        }
46
        return type;
47
    }
48

  
49
    @Override
50
    public Integer getCoPersonIdByEmail() {
51
        try {
52
            OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
53
            String email = authentication.getUserInfo().getEmail();
54
            Map<String, String> params = new HashMap<>();
55
            params.put("coid", coid);
56
            params.put("mail", email);
57
            JsonElement response = httpUtils.get("co_people.json", params);
58
            return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
59
        } catch (Exception e) {
60
            logger.error("Get User info: An error occurred ", e);
61
            return null;
62
        }
63
    }
64

  
65
    @Override
66
    public Integer getCoPersonIdByEmail(String email) {
67
        Map<String, String> params = new HashMap<>();
68
        params.put("coid", coid);
69
        params.put("mail", email);
70
        JsonElement response = httpUtils.get("co_people.json", params);
71
        if (response != null) {
72
            JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray();
73
            if (coPeople.size() > 0) {
74
                return coPeople.get(0).getAsJsonObject().get("Id").getAsInt();
75
            }
76
        }
77
        return null;
78
    }
79

  
80
    @Override
81
    public List<Integer> getCoPersonIdsByEmail(String email) {
82
        List<Integer> coPersonIds = new ArrayList<>();
83
        Map<String, String> params = new HashMap<>();
84
        params.put("coid", coid);
85
        params.put("mail", email);
86
        JsonElement response = httpUtils.get("co_people.json", params);
87
        if (response != null) {
88
            JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray();
89
            for (int i = 0; i < coPeople.size(); i++) {
90
                coPersonIds.add(coPeople.get(i).getAsJsonObject().get("Id").getAsInt());
91
            }
92
        }
93
        return coPersonIds;
94
    }
95

  
96
    @Override
97
    public Integer getCoPersonIdByIdentifier() {
98
        try {
99
            OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
100
            String sub = authentication.getUserInfo().getSub();
101
            Map<String, String> params = new HashMap<>();
102
            params.put("coid", coid);
103
            params.put("search.identifier", sub);
104
            JsonElement response = httpUtils.get("co_people.json", params);
105
            return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
106
        } catch (Exception e) {
107
            logger.error("Get User info: An error occurred ", e);
108
            return null;
109
        }
110
    }
111

  
112
    public Integer getCoPersonIdByIdentifier(String sub) {
113
        Map<String, String> params = new HashMap<>();
114
        params.put("coid", coid);
115
        params.put("search.identifier", sub);
116
        JsonElement response = httpUtils.get("co_people.json", params);
117
        return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
118
    }
119

  
120
    @Override
121
    public JsonArray getCous(String name) {
122
        Map<String, String> params = new HashMap<>();
123
        params.put("coid", coid);
124
        if (name != null) {
125
            params.put("name", URLEncoder.encode(name).toLowerCase());
126
        }
127
        JsonElement response = httpUtils.get("cous.json", params);
128
        return (response != null) ? response.getAsJsonObject().get("Cous").getAsJsonArray() : new JsonArray();
129
    }
130

  
131
    @Override
132
    public JsonArray getCous() {
133
        return getCous(null);
134
    }
135

  
136
    @Override
137
    public Integer getCouId(String name) {
138
        JsonArray cous = getCous(name);
139
        for (JsonElement cou : cous) {
140
            if (cou.getAsJsonObject().get("Name").getAsString().equalsIgnoreCase(name)) {
141
                return cou.getAsJsonObject().get("Id").getAsInt();
142
            }
143
        }
144
        return null;
145
    }
146

  
147
    @Override
148
    public Integer getCouId(String type, String id, boolean communityMap) {
149
        return getCouId(mapType(type, communityMap) + "." + id);
150
    }
151

  
152
    @Override
153
    public Integer getCouId(String type, String id) {
154
        return getCouId(type, id, true);
155
    }
156

  
157
    @Override
158
    public JsonArray getRoles(Integer coPersonId) {
159
        Map<String, String> params = new HashMap<>();
160
        params.put("copersonid", coPersonId.toString());
161
        JsonElement response = httpUtils.get("co_person_roles.json", params);
162
        return (response != null) ? response.getAsJsonObject().get("CoPersonRoles").getAsJsonArray() : new JsonArray();
163
    }
164

  
165
    @Override
166
    public JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status) {
167
        JsonArray roles = getRoles(coPersonId);
168
        if (status == null) {
169
            return roles;
170
        }
171
        JsonArray activeRoles = new JsonArray();
172
        for (JsonElement role : roles) {
173
            if (role.getAsJsonObject().get("Status").getAsString().equalsIgnoreCase(status.toString())) {
174
                activeRoles.add(role);
175
            }
176
        }
177
        return activeRoles;
178
    }
179

  
180
    @Override
181
    public Integer getRoleId(Integer coPersonId, Integer couId) {
182
        JsonArray roles = getRoles(coPersonId);
183
        for (JsonElement role : roles) {
184
            JsonObject object = role.getAsJsonObject();
185
            if (object.get("CouId").getAsInt() == couId && !object.get("Status").getAsString().equals("Deleted")) {
186
                return object.get("Id").getAsInt();
187
            }
188
        }
189
        return null;
190
    }
191

  
192
    @Override
193
    public JsonArray getUserGroups(Integer coPersonId) {
194
        Map<String, String> params = new HashMap<>();
195
        params.put("copersonid", coPersonId.toString());
196
        JsonElement response = httpUtils.get("co_groups.json", params);
197
        return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
198
    }
199

  
200
    @Override
201
    public JsonObject getUserAdminGroup(Integer coPersonId, Integer couId) {
202
        Map<String, String> params = new HashMap<>();
203
        params.put("copersonid", coPersonId.toString());
204
        JsonElement response = httpUtils.get("co_groups.json", params);
205
        JsonArray roles = (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
206
        for (JsonElement role : roles) {
207
            JsonObject object = role.getAsJsonObject();
208
            if (object.get("CouId") != null && object.get("CouId").getAsInt() == couId) {
209
                if (object.get("Name").getAsString().contains("admins")) {
210
                    return object;
211
                }
212
            }
213
        }
214
        return null;
215
    }
216

  
217
    @Override
218
    public JsonArray getCouGroups(Integer couId) {
219
        Map<String, String> params = new HashMap<>();
220
        params.put("coid", coid);
221
        params.put("couid", couId.toString());
222
        JsonElement response = httpUtils.get("co_groups.json", params);
223
        return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
224
    }
225

  
226
    @Override
227
    public JsonObject getCouAdminGroup(Integer couId) {
228
        JsonArray groups = getCouGroups(couId);
229
        for (JsonElement group : groups) {
230
            if (group.getAsJsonObject().get("Name").getAsString().contains("admins")) {
231
                return group.getAsJsonObject();
232
            }
233
        }
234
        return null;
235
    }
236

  
237
    @Override
238
    public JsonArray getGroupMembers(Integer coGroupId) {
239
        Map<String, String> params = new HashMap<>();
240
        params.put("cogroupid", coGroupId.toString());
241
        JsonElement response = httpUtils.get("co_group_members.json", params);
242
        return (response != null) ? response.getAsJsonObject().get("CoGroupMembers").getAsJsonArray() : new JsonArray();
243
    }
244

  
245

  
246
    @Override
247
    public JsonArray getUserEmailByCouId(Integer couId, boolean admin) {
248
        Map<String, String> params = new HashMap<>();
249
        if (couId == null) {
250
            throw new IllegalArgumentException("Provided 'couId' is null");
251
        }
252
        params.put("couid", couId.toString());
253
        if (admin) {
254
            params.put("admin", "true");
255
        }
256
        JsonElement response = httpUtils.get("email_addresses.json", params);
257
        JsonArray infos = (response != null) ? response.getAsJsonObject().get("EmailAddresses").getAsJsonArray() : new JsonArray();
258
        JsonArray emails = new JsonArray();
259
        infos.forEach(info -> {
260
            JsonObject user = new JsonObject();
261
            boolean add = true;
262
            String email = info.getAsJsonObject().get("Mail").getAsString();
263
            for (JsonElement element : emails) {
264
                if (element.getAsJsonObject().get("email").getAsString().equals(email)) {
265
                    add = false;
266
                }
267
            }
268
            if (add) {
269
                user.addProperty("email", email);
270
                user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
271
                emails.add(user);
272
            }
273
        });
274
        return emails;
275
    }
276

  
277
    @Override
278
    public JsonArray getUsersByCouId(Integer couId) {
279
        Map<String, String> params = new HashMap<>();
280
        params.put("couid", couId.toString());
281
        JsonElement response = httpUtils.get("co_person_roles.json", params);
282
        JsonArray infos = (response != null) ? response.getAsJsonObject().get("CoPersonRoles").getAsJsonArray() : new JsonArray();
283
//        JsonArray users = new JsonArray();
284
//        infos.forEach(info -> {
285
//            JsonObject user = new JsonObject();
286
//            user.addProperty("email", info.getAsJsonObject().get("Mail").getAsString());
287
//            user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
288
//            emails.add(user);
289
//        });
290
        return infos;
291
    }
292

  
293
    @Override
294
    public List<User> getUsers(Integer couId) {
295
        List<User> users = new ArrayList<>();
296
        JsonArray infos = getUserEmailByCouId(couId, false);
297

  
298
        infos.forEach(info -> {
299
            User user = new User();
300
            user.setEmail(info.getAsJsonObject().get("email").getAsString());
301

  
302
            users.add(user);
303
        });
304
        return users;
305
    }
306

  
307
    @Override
308
    public JsonArray getUserNamesByCouId(Integer couId, boolean admin) {
309
        Map<String, String> params = new HashMap<>();
310
        params.put("couid", couId.toString());
311
        if (admin) {
312
            params.put("admin", "true");
313
        }
314
        JsonElement response = httpUtils.get("names.json", params);
315
        JsonArray infos = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray() : new JsonArray();
316
        JsonArray names = new JsonArray();
317
        infos.forEach(info -> {
318
            JsonObject user = new JsonObject();
319
            user.addProperty("name", info.getAsJsonObject().get("Given").getAsString() + " " + info.getAsJsonObject().get("Family").getAsString());
320
            user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
321
            names.add(user);
322
        });
323
        return names;
324
    }
325

  
326
    @Override
327
    public JsonArray getUserIdByCouId(Integer couId, boolean admin) {
328
        Map<String, String> params = new HashMap<>();
329
        params.put("couid", couId.toString());
330
        if (admin) {
331
            params.put("admin", "true");
332
        }
333
        JsonElement response = httpUtils.get("identifiers.json", params);
334
        JsonArray infos = (response != null) ? response.getAsJsonObject().get("Identifiers").getAsJsonArray() : new JsonArray();
335
        JsonArray emails = new JsonArray();
336
        infos.forEach(info -> {
337
            JsonObject user = new JsonObject();
338
            user.addProperty("id", info.getAsJsonObject().get("Identifier").getAsString());
339
            user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
340
            emails.add(user);
341
        });
342
        return emails;
343
    }
344

  
345
    @Override
346
    public void assignMemberRole(Integer coPersonId, Integer couId, Integer id) {
347
        if (id != null) {
348
            httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Active"));
349
        } else {
350
            httpUtils.post("co_person_roles.json", jsonUtils.coPersonRoles(coPersonId, couId, "Active"));
351
        }
352
    }
353

  
354
    @Override
355
    public void removeMemberRole(Integer coPersonId, Integer couId, Integer id) {
356
        if (id != null) {
357
            httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Deleted"));
358
        }
359
    }
360

  
361
    @Override
362
    public Integer createRole(Role role) {
363
        JsonElement element = httpUtils.post("cous.json", jsonUtils.createNewCou(role));
364
        return element.getAsJsonObject().get("Id").getAsInt();
365
    }
366

  
367
    @Override
368
    public String getUserEmail(Integer coPersonId) {
369
        Map<String, String> params = new HashMap<>();
370
        params.put("copersonid", coPersonId.toString());
371
        JsonElement response = httpUtils.get("email_addresses.json", params);
372
        JsonObject info = (response != null) ? response.getAsJsonObject().get("EmailAddresses").getAsJsonArray().get(0).getAsJsonObject() : null;
373
        return (info != null) ? info.getAsJsonObject().get("Mail").getAsString() : null;
374
    }
375

  
376
    @Override
377
    public String getUserNames(Integer coPersonId) {
378
        Map<String, String> params = new HashMap<>();
379
        params.put("copersonid", coPersonId.toString());
380
        JsonElement response = httpUtils.get("names.json", params);
381
        JsonObject info = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray().get(0).getAsJsonObject() : null;
382
        return (info != null) ? info.getAsJsonObject().get("Given").getAsString() + " " + info.getAsJsonObject().get("Family").getAsString() : null;
383
    }
384

  
385
    @Override
386
    public String getUserId(Integer coPersonId) {
387
        Map<String, String> params = new HashMap<>();
388
        params.put("copersonid", coPersonId.toString());
389
        JsonElement response = httpUtils.get("identifiers.json", params);
390
        JsonObject info = (response != null) ? response.getAsJsonObject().get("Identifiers").getAsJsonArray().get(0).getAsJsonObject() : null;
391
        return (info != null) ? info.getAsJsonObject().get("Identifier").getAsString() : null;
392
    }
393

  
394
    @Override
395
    public void assignAdminRole(Integer coPersonId, Integer couId) {
396
        JsonObject group = getCouAdminGroup(couId);
397
        if (group != null) {
398
            httpUtils.post("co_group_members.json", jsonUtils.coGroupMembers(group.get("Id").getAsInt(), coPersonId, true));
399
        }
400
    }
401

  
402
    @Override
403
    public void removeAdminRole(Integer coPersonId, Integer couId) {
404
        JsonObject adminGroup = this.getCouAdminGroup(couId);
405
        JsonArray admins = this.getGroupMembers(adminGroup.get("Id").getAsInt());
406
        Integer id = null;
407
        for (JsonElement admin : admins) {
408
            if (admin.getAsJsonObject().get("Person").getAsJsonObject().get("Id").getAsInt() == coPersonId) {
409
                id = admin.getAsJsonObject().get("Id").getAsInt();
410
            }
411
        }
412
        if (id != null) {
413
            httpUtils.delete("co_group_members/" + id.toString() + ".json");
414
        }
415
    }
416

  
417
    @Override
418
    public Map<Integer, String> getCouNames(List<Integer> couIds) {
419
        Map<Integer, String> idNameMap = new HashMap<>();
420
        for (Integer id : couIds) {
421
            idNameMap.put(id, null);
422
        }
423

  
424
        JsonArray cous = getCous();
425
        int count = 0;
426
        int total = couIds.size();
427
        for (JsonElement cou : cous) {
428
            if (count < total) {
429
                if (idNameMap.containsKey(cou.getAsJsonObject().get("Id").getAsInt())) {
430
                    idNameMap.put(cou.getAsJsonObject().get("Id").getAsInt(), cou.getAsJsonObject().get("Name").getAsString());
431
                    count++;
432
                }
433
            } else {
434
                break;
435
            }
436
        }
437
        return idNameMap;
438
    }
439
}
modules/uoa-repository-manager-service/trunk/src/main/java/eu/dnetlib/repo/manager/service/SushiliteServiceImpl.java
31 31

  
32 32

  
33 33
    @Override
34
    @PreAuthorize("hasRole('ROLE_USER')")
34
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
35 35
    public ReportResponseWrapper getReportResults(String page,
36 36
                                                  String pageSize,
37 37
                                                  String Report,
modules/uoa-repository-manager-service/trunk/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java
1 1
package eu.dnetlib.repo.manager.service;
2 2

  
3 3
import com.fasterxml.jackson.databind.ObjectMapper;
4
import com.google.gson.JsonArray;
5
import com.google.gson.JsonElement;
6
import com.google.gson.JsonObject;
4 7
import eu.dnetlib.api.functionality.ValidatorServiceException;
5 8
import eu.dnetlib.domain.data.Repository;
6 9
import eu.dnetlib.domain.data.RepositoryInterface;
7 10
import eu.dnetlib.domain.enabling.Vocabulary;
8 11
import eu.dnetlib.domain.functionality.validator.JobForValidation;
9 12
import eu.dnetlib.repo.manager.domain.*;
13
import eu.dnetlib.repo.manager.domain.dto.Role;
10 14
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
15
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
16
import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater;
17
import eu.dnetlib.repo.manager.service.security.AuthorizationService;
18
import eu.dnetlib.repo.manager.service.security.RoleMappingService;
11 19
import eu.dnetlib.repo.manager.utils.Converter;
12 20
import gr.uoa.di.driver.enabling.vocabulary.VocabularyLoader;
13 21
import org.apache.commons.codec.digest.DigestUtils;
......
15 23
import org.json.JSONArray;
16 24
import org.json.JSONException;
17 25
import org.json.JSONObject;
26
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
18 27
import org.springframework.beans.factory.annotation.Autowired;
19 28
import org.springframework.beans.factory.annotation.Value;
29
import org.springframework.context.annotation.Lazy;
20 30
import org.springframework.core.ParameterizedTypeReference;
21 31
import org.springframework.http.*;
22 32
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
23 33
import org.springframework.security.core.Authentication;
24 34
import org.springframework.security.core.context.SecurityContextHolder;
25 35
import org.springframework.stereotype.Service;
36
import org.springframework.web.client.HttpClientErrorException;
26 37
import org.springframework.web.client.RestClientException;
27 38
import org.springframework.web.client.RestTemplate;
28 39
import org.springframework.web.util.UriComponents;
......
38 49
@Service("repositoryService")
39 50
public class RepositoryServiceImpl implements RepositoryService {
40 51

  
52
    private static final Logger LOGGER = Logger.getLogger(RepositoryServiceImpl.class);
53

  
54
    private final AuthorizationService authorizationService;
55
    private final RoleMappingService roleMappingService;
56
    private final AaiRegistryService registryCalls;
57
    private final AuthoritiesUpdater authoritiesUpdater;
58
    private final RestTemplate restTemplate;
59
    private final VocabularyLoader vocabularyLoader;
60
    private final PiWikService piWikService;
61
    private final EmailUtils emailUtils;
62
    private final ValidatorService validatorService;
63

  
41 64
    @Value("${api.baseAddress}")
42 65
    private String baseAddress;
43 66

  
44 67
    @Value("${services.repo-manager.adminEmail}")
45 68
    private String adminEmail;
46 69

  
47
    @Autowired
48
    RestTemplate restTemplate;
49

  
50
    private HttpHeaders httpHeaders;
51

  
52
    private final String[] vocabularyNames = {"dnet:countries", "dnet:datasource_typologies", "dnet:compatibilityLevel"};
53

  
54
    private static final Logger LOGGER = Logger.getLogger(RepositoryServiceImpl.class);
55

  
56 70
    @Value("${services.repomanager.usageStatisticsDiagramsBaseURL}")
57 71
    private String usageStatisticsDiagramsBaseURL;
58 72

  
59 73
    @Value("${services.repomanager.usageStatisticsNumbersBaseURL}")
60 74
    private String usageStatisticsNumbersBaseURL;
61 75

  
62
    @Autowired
63
    private VocabularyLoader vocabularyLoader;
64 76

  
65
    @Autowired
66
    private PiWikService piWikService;
77
    private static final Map<String, List<String>> dataSourceClass = new HashMap<>();
78
    private static final Map<String, String> invertedDataSourceClass = new HashMap<>();
67 79

  
68
    @Autowired
69
    private EmailUtils emailUtils;
70 80

  
71
    @Autowired
72
    ValidatorService validatorService;
81
    private final String[] vocabularyNames = {"dnet:countries", "dnet:datasource_typologies", "dnet:compatibilityLevel"};
82
    private final Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<>();
83
    private final Map<String, String> countriesMap = new HashMap<>();
84
    private final Map<String, String> inverseCountriesMap = new HashMap<>();
73 85

  
86
    private HttpHeaders httpHeaders;
74 87

  
75
    private Map<String, Vocabulary> vocabularyMap = new ConcurrentHashMap<>();
88
    @Autowired
89
    public RepositoryServiceImpl(AuthorizationService authorizationService,
90
                                 RoleMappingService roleMappingService,
91
                                 AaiRegistryService registryCalls,
92
                                 AuthoritiesUpdater authoritiesUpdater,
93
                                 VocabularyLoader vocabularyLoader,
94
                                 RestTemplate restTemplate,
95
                                 @Lazy EmailUtils emailUtils,
96
                                 @Lazy ValidatorService validatorService,
97
                                 @Lazy PiWikService piWikService) {
98
        this.authorizationService = authorizationService;
99
        this.roleMappingService = roleMappingService;
100
        this.registryCalls = registryCalls;
101
        this.authoritiesUpdater = authoritiesUpdater;
102
        this.vocabularyLoader = vocabularyLoader;
103
        this.piWikService = piWikService;
104
        this.emailUtils = emailUtils;
105
        this.validatorService = validatorService;
106
        this.restTemplate = restTemplate;
107
    }
76 108

  
77
    private Map<String, String> countriesMap = new HashMap<>();
78
    private Map<String, String> inverseCountriesMap = new HashMap<>();
109
    private String getAuthenticatedUserEmail() {
110
        OIDCAuthenticationToken authenticationToken = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
111
        return authenticationToken.getUserInfo().getEmail();
112
    }
79 113

  
80
    private static Map<String,List<String>> dataSourceClass = new HashMap<>();
81 114

  
82
    private static Map<String,String> invertedDataSourceClass = new HashMap<>();
83

  
84

  
85

  
86 115
    @PostConstruct
87 116
    private void init() {
88 117
        LOGGER.debug("Initialization method of repository api!");
89 118
        LOGGER.debug("Updated version!");
90 119

  
91
        dataSourceClass.put("opendoar",Arrays.asList("pubsrepository::institutional","pubsrepository::thematic","pubsrepository::unknown","pubsrepository::mock"));
120
        dataSourceClass.put("opendoar", Arrays.asList("pubsrepository::institutional", "pubsrepository::thematic", "pubsrepository::unknown", "pubsrepository::mock"));
92 121
        dataSourceClass.put("re3data", Collections.singletonList("datarepository::unknown"));
93 122
        dataSourceClass.put("journal", Collections.singletonList("pubsrepository::journal"));
94
        dataSourceClass.put("aggregator",Arrays.asList("aggregator::pubsrepository::institutional","aggregator::pubsrepository::journals","aggregator::datarepository", "aggregator::pubsrepository::unknown"));
123
        dataSourceClass.put("aggregator", Arrays.asList("aggregator::pubsrepository::institutional", "aggregator::pubsrepository::journals", "aggregator::datarepository", "aggregator::pubsrepository::unknown"));
95 124

  
96
        invertedDataSourceClass.put("pubsrepository::institutional","opendoar");
97
        invertedDataSourceClass.put("pubsrepository::thematic","opendoar");
98
        invertedDataSourceClass.put("pubsrepository::unknown","opendoar");
99
        invertedDataSourceClass.put("pubsrepository::mock","opendoar");
100
        invertedDataSourceClass.put("datarepository::unknown","re3data");
101
        invertedDataSourceClass.put("pubsrepository::journal","journal");
102
        invertedDataSourceClass.put("aggregator::pubsrepository::institutional","aggregator");
103
        invertedDataSourceClass.put("aggregator::pubsrepository::journals","aggregator");
104
        invertedDataSourceClass.put("aggregator::datarepository","aggregator");
105
        invertedDataSourceClass.put("aggregator::pubsrepository::unknown","aggregator");
125
        invertedDataSourceClass.put("pubsrepository::institutional", "opendoar");
126
        invertedDataSourceClass.put("pubsrepository::thematic", "opendoar");
127
        invertedDataSourceClass.put("pubsrepository::unknown", "opendoar");
128
        invertedDataSourceClass.put("pubsrepository::mock", "opendoar");
129
        invertedDataSourceClass.put("datarepository::unknown", "re3data");
130
        invertedDataSourceClass.put("pubsrepository::journal", "journal");
131
        invertedDataSourceClass.put("aggregator::pubsrepository::institutional", "aggregator");
132
        invertedDataSourceClass.put("aggregator::pubsrepository::journals", "aggregator");
133
        invertedDataSourceClass.put("aggregator::datarepository", "aggregator");
134
        invertedDataSourceClass.put("aggregator::pubsrepository::unknown", "aggregator");
106 135

  
107 136

  
108 137
        httpHeaders = new HttpHeaders();
......
128 157
                .build().encode();
129 158
        return restTemplate.getForObject(uriComponents.toUri(), Country[].class);
130 159
    }
160
    
161
    // FIXME: with the new roles of the users the "requestFilter.setRegisteredby(userEmail)" can no longer be used
162
    //  and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
163
    //  another way for paging must be implemented.
164
    @Override
165
    public List<Repository> getRepositories(List<String> ids) throws JSONException {
166
        return getRepositories(ids, 0, 10);
167
    }
131 168

  
169
    // FIXME: with the new roles of the users the "requestFilter.setRegisteredby(userEmail)" can no longer be used
170
    //  and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
171
    //  another way for paging must be implemented.
172
    @Override
173
    public List<Repository> getRepositories(List<String> ids, int page, int size) throws JSONException {
174
        List<Repository> repos = new ArrayList<>();
175
        LOGGER.debug("Retreiving repositories with ids : " + String.join(", ", ids));
176
        UriComponents uriComponents = searchDatasource(Integer.toString(Math.abs(page)), Integer.toString(Math.abs(size)));
177
        RequestFilter requestFilter = new RequestFilter();
132 178

  
179
        try {
180
            for (String repoId : ids) {
181
                requestFilter.setId(repoId);
182
                String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
183

  
184
                repos.addAll(Converter.jsonToRepositoryList(new JSONObject(rs)));
185
            }
186
        } catch (JSONException e) {
187
            LOGGER.debug("Exception on getRepositoriesOfUser", e);
188
            emailUtils.reportException(e);
189
            throw e;
190
        }
191

  
192
        for (Repository r : repos)
193
            r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
194
        return repos;
195
    }
196

  
197
    // FIXME: with the new roles of the users the "requestFilter.setRegisteredby(userEmail)" can no longer be used
198
    //  and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
199
    //  another way for paging must be implemented.
133 200
    @Override
201
    public List<RepositorySnippet> getRepositoriesSnippets(List<String> ids) throws Exception {
202
        return getRepositoriesSnippets(ids, 0, 10);
203
    }
204

  
205
    // FIXME: with the new roles of the users the "requestFilter.setRegisteredby(userEmail)" can no longer be used
206
    //  and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
207
    //  another way for paging must be implemented.
208
    @Override
209
    public List<RepositorySnippet> getRepositoriesSnippets(List<String> ids, int page, int size) throws Exception {
210
        List<RepositorySnippet> resultSet = new ArrayList<>();
211
        ObjectMapper mapper = new ObjectMapper();
212

  
213
        // here page should be 0
214
        UriComponents uriComponents = searchSnipperDatasource(Integer.toString(Math.abs(page)), Integer.toString(Math.abs(size)));
215
        RequestFilter requestFilter = new RequestFilter();
216

  
217
        try {
218
            for (String repoId : ids) {
219
                requestFilter.setId(repoId);
220

  
221
                String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
222
                JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
223
                resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),
224
                        mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
225
            }
226
        } catch (Exception e) {
227
            LOGGER.debug("Exception on getRepositoriesSnippetOfUser", e);
228
            throw e;
229
        }
230

  
231
        LOGGER.debug("resultSet:" + resultSet);
232
        resultSet.parallelStream().forEach(repositorySnippet -> {
233
            repositorySnippet.setPiwikInfo(piWikService.getPiwikSiteForRepo(repositorySnippet.getId()));
234
        });
235
        return resultSet;
236
    }
237

  
238

  
239
    @Override
134 240
    public List<RepositorySnippet> getRepositoriesByCountry(String country,
135 241
                                                            String mode,
136 242
                                                            Boolean managed) throws JSONException, IOException {
......
151 257
        LOGGER.debug("Country code equals : " + country);
152 258
        LOGGER.debug("Filter mode equals : " + filterKey);
153 259

  
154
        UriComponents uriComponents = searchSnipperDatasource(String.valueOf(page),String.valueOf(size));
260
        UriComponents uriComponents = searchSnipperDatasource(String.valueOf(page), String.valueOf(size));
155 261
        RequestFilter requestFilter = new RequestFilter();
156 262
        requestFilter.setCountry(country);
157 263
        requestFilter.setCollectedfrom(filterKey);
158 264

  
159
        try{
160
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
265
        try {
266
            String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
161 267
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
162
            while (jsonArray.length() > 0 ) {
268
            while (jsonArray.length() > 0) {
163 269
                resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),
164 270
                        mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
165 271
                page += 1;
166
                uriComponents = searchSnipperDatasource(String.valueOf(page),String.valueOf(size));
167
                rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
272
                uriComponents = searchSnipperDatasource(String.valueOf(page), String.valueOf(size));
273
                rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
168 274
                jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
169 275
            }
170 276
            return resultSet;
171
        }catch (Exception e){
172
            LOGGER.debug("Exception on getRepositoriesByCountry" , e);
277
        } catch (Exception e) {
278
            LOGGER.debug("Exception on getRepositoriesByCountry", e);
173 279
//            emailUtils.reportException(e);
174 280
            throw e;
175 281
        }
176 282
    }
177 283

  
178 284
    public List<RepositorySnippet> searchRegisteredRepositories(String country, String typology, String englishName,
179
            String officialName, String requestSortBy, String order, int page, int pageSize) throws Exception {
285
                                                                String officialName, String requestSortBy, String order, int page, int pageSize) throws Exception {
180 286

  
181 287
        LOGGER.debug("Searching registered repositories");
182 288

  
......
192 298
        requestFilter.setEnglishname(englishName);
193 299

  
194 300
        try {
195
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
301
            String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
196 302
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
197 303

  
198
            resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),  mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
304
            resultSet.addAll(mapper.readValue(String.valueOf(jsonArray), mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
199 305

  
200
             return resultSet;
201
        }catch (Exception e){
202
            LOGGER.error("Error searching registered datasources" , e);
306
            return resultSet;
307
        } catch (Exception e) {
308
            LOGGER.error("Error searching registered datasources", e);
203 309
            throw e;
204 310
        }
205 311
    }
......
207 313
    private Repository updateRepositoryInfo(Repository r) throws JSONException {
208 314

  
209 315
        /*
210
        * from datasource class
211
        * we get the datasource type form the inverted map
212
        * */
316
         * from datasource class
317
         * we get the datasource type form the inverted map
318
         * */
213 319
        r.setDatasourceType(getRepositoryType(r.getDatasourceClass()));
214 320
        r.setInterfaces(this.getRepositoryInterface(r.getId()));
215 321
        r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
......
230 336
    }
231 337

  
232 338
    @Override
233
    public List<Repository> getRepositoriesOfUser(String userEmail,
234
                                                  String page,
235
                                                  String size) throws JSONException {
339
    public List<Repository> getRepositoriesOfUser(String page, String size) throws JSONException {
340
        String userEmail = ((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail();
341
        LOGGER.debug("Retreiving repositories of authenticated user : " + userEmail);
342
        Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles());
343
        return getRepositories(new ArrayList<>(repoIds));
344
    }
236 345

  
237
        LOGGER.debug("Retreiving repositories of user : " + userEmail );
238
        UriComponents uriComponents = searchDatasource(page,size);
239
        RequestFilter requestFilter = new RequestFilter();
240
        requestFilter.setRegisteredby(userEmail);
346
    @Override
347
    public List<Repository> getRepositoriesOfUser(String userEmail, String page, String size) throws JSONException {
348
        LOGGER.debug("Retreiving repositories of authenticated user : " + userEmail);
349
        Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles(userEmail));
350
        return getRepositories(new ArrayList<>(repoIds));
351
    }
241 352

  
242
        try{
243
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
353
    @Override
354
    public List<RepositorySnippet> getRepositoriesSnippetsOfUser(String page, String size) throws Exception {
355
        Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles());
356
        return getRepositoriesSnippets(new ArrayList<>(repoIds));
357
    }
244 358

  
245
            List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
246
            for (Repository r : repos)
247
                r.setPiwikInfo(piWikService.getPiwikSiteForRepo(r.getId()));
248
            return repos;
249
        }catch (Exception e){
250
            LOGGER.debug("Exception on getRepositoriesOfUser" , e);
251
            emailUtils.reportException(e);
252
            throw e;
253
        }
359
    @Override
360
    public List<RepositorySnippet> getRepositoriesSnippetsOfUser(String userEmail, String page, String size) throws Exception {
361
        Collection<String> repoIds = roleMappingService.getRepoIdsByRoleIds(authorizationService.getUserRoles(userEmail));
362
        return getRepositoriesSnippets(new ArrayList<>(repoIds));
254 363
    }
255 364

  
256 365
    @Override
257
    public List<RepositorySnippet> getRepositoriesSnippetOfUser(String userEmail, String page, String size) throws IOException, JSONException {
258
        List<RepositorySnippet> resultSet = new ArrayList<>();
259
        ObjectMapper mapper = new ObjectMapper();
366
    public RepositorySnippet getRepositorySnippetById(String id) throws JSONException, ResourceNotFoundException {
260 367

  
261
        UriComponents uriComponents = searchSnipperDatasource(page,size);
368
        LOGGER.debug("Retreiving repositories with id : " + id);
369
        RepositorySnippet repo = null;
370
        UriComponents uriComponents = searchSnipperDatasource("0", "100");
262 371
        RequestFilter requestFilter = new RequestFilter();
263
        requestFilter.setRegisteredby(userEmail);
372
        requestFilter.setId(id);
264 373

  
265
        try{
266
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
374
        try {
375
            String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
267 376
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
268
            while (jsonArray.length() > 0 ) {
269
                resultSet.addAll(mapper.readValue(String.valueOf(jsonArray),
270
                        mapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)));
271
                page += 1;
272
                uriComponents = searchSnipperDatasource(page,size);
273
                rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
274
                jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
275
            }
276
            resultSet.parallelStream().forEach(repositorySnippet -> {
277
                repositorySnippet.setPiwikInfo(piWikService.getPiwikSiteForRepo(repositorySnippet.getId()));
278
            });
279
            return resultSet;
280
        }catch (Exception e){
281
            LOGGER.debug("Exception on getRepositoriesByCountry" , e);
377

  
378
            if (jsonArray.length() == 0)
379
                throw new ResourceNotFoundException();
380

  
381
            repo = Converter.jsonToRepositorySnippetObject(jsonArray.getJSONObject(0));
382
            return repo;
383
        } catch (JSONException e) {
384
            LOGGER.debug("Exception on getRepositoryById", e);
385
            emailUtils.reportException(e);
282 386
            throw e;
283 387
        }
388

  
284 389
    }
285 390

  
286 391
    @Override
287
    public Repository getRepositoryById(String id) throws JSONException,ResourceNotFoundException {
392
    public Repository getRepositoryById(String id) throws JSONException, ResourceNotFoundException {
288 393

  
289
        LOGGER.debug("Retreiving repositories with id : " + id );
394
        LOGGER.debug("Retreiving repositories with id : " + id);
290 395
        Repository repo = null;
291
        UriComponents uriComponents = searchDatasource("0","100");
396
        UriComponents uriComponents = searchDatasource("0", "100");
292 397
        RequestFilter requestFilter = new RequestFilter();
293 398
        requestFilter.setId(id);
294 399

  
295
        try{
296
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
400
        try {
401
            String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
297 402
            JSONArray jsonArray = (JSONArray) new JSONObject(rs).get("datasourceInfo");
298 403

  
299
            if(jsonArray.length() == 0)
404
            if (jsonArray.length() == 0)
300 405
                throw new ResourceNotFoundException();
301 406

  
302 407
            repo = Converter.jsonToRepositoryObject(jsonArray.getJSONObject(0));
303 408
            return updateRepositoryInfo(repo);
304
        }catch (JSONException e){
305
            LOGGER.debug("Exception on getRepositoryById" , e);
409
        } catch (JSONException e) {
410
            LOGGER.debug("Exception on getRepositoryById", e);
306 411
            emailUtils.reportException(e);
307 412
            throw e;
308 413
        }
......
313 418
    @Override
314 419
    public List<AggregationDetails> getRepositoryAggregations(String id, int from, int size) throws JSONException {
315 420

  
316
        LOGGER.debug("Retreiving aggregations for repository with id : " + id );
317
        UriComponents uriComponents = searchDatasource(from+"",size+"");
421
        LOGGER.debug("Retreiving aggregations for repository with id : " + id);
422
        UriComponents uriComponents = searchDatasource(from + "", size + "");
318 423
        RequestFilter requestFilter = new RequestFilter();
319 424
        requestFilter.setId(id);
320 425

  
......
322 427

  
323 428
        try {
324 429
            long start = System.currentTimeMillis();
325
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
430
            String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
326 431
            long end = System.currentTimeMillis();
327 432

  
328
            System.out.println("Aggregations request through rest template took " + (end-start)+"ms");
433
            System.out.println("Aggregations request through rest template took " + (end - start) + "ms");
329 434
            JSONObject repository = new JSONObject(rs);
330 435

  
331
            if(repository.getJSONArray("datasourceInfo").length() == 0)
436
            if (repository.getJSONArray("datasourceInfo").length() == 0)
332 437
                return aggregationHistory;
333 438

  
334 439
            start = System.currentTimeMillis();
335 440
            aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
336 441
            end = System.currentTimeMillis();
337 442

  
338
            System.out.println("Getting aggregations history from json " + (end-start)+"ms");
339
            return aggregationHistory.size() == 0? aggregationHistory : aggregationHistory.stream()
340
                                                    .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
341
                                                    .limit(size)
342
                                                    .collect(Collectors.toList());
443
            System.out.println("Getting aggregations history from json " + (end - start) + "ms");
444
            return aggregationHistory.size() == 0 ? aggregationHistory : aggregationHistory.stream()
445
                    .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
446
                    .limit(size)
447
                    .collect(Collectors.toList());
343 448
        } catch (JSONException e) {
344
            LOGGER.debug("Exception on getRepositoryAggregations" , e);
449
            LOGGER.debug("Exception on getRepositoryAggregations", e);
345 450
            emailUtils.reportException(e);
346 451
            throw e;
347 452
        }
......
350 455

  
351 456
    @Override
352 457
    public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(String id) throws JSONException {
353
        LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id );
354
        UriComponents uriComponents = searchDatasource("0","100");
458
        LOGGER.debug("Retreiving aggregations (by year) for repository with id : " + id);
459
        UriComponents uriComponents = searchDatasource("0", "100");
355 460
        RequestFilter requestFilter = new RequestFilter();
356 461
        requestFilter.setId(id);
357 462

  
358 463
        List<AggregationDetails> aggregationHistory = new ArrayList<>();
359 464
        Map<String, List<AggregationDetails>> aggregationByYear = new HashMap<>();
360 465
        try {
361
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
466
            String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
362 467
            JSONObject repository = new JSONObject(rs);
363 468

  
364
            if(repository.getJSONArray("datasourceInfo").length() == 0)
469
            if (repository.getJSONArray("datasourceInfo").length() == 0)
365 470
                return aggregationByYear;
366 471

  
367 472
            aggregationHistory.addAll(Converter.getAggregationHistoryFromJson(repository.getJSONArray("datasourceInfo").getJSONObject(0)));
368
            return aggregationHistory.size() == 0? aggregationByYear:createYearMap(aggregationHistory);
473
            return aggregationHistory.size() == 0 ? aggregationByYear : createYearMap(aggregationHistory);
369 474

  
370 475
        } catch (JSONException e) {
371
            LOGGER.debug("Exception on getRepositoryAggregations" , e);
476
            LOGGER.debug("Exception on getRepositoryAggregations", e);
372 477
            emailUtils.reportException(e);
373 478
            throw e;
374 479
        }
375 480
    }
376 481

  
377
    private Map<String,List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
482
    private Map<String, List<AggregationDetails>> createYearMap(List<AggregationDetails> aggregationHistory) {
378 483
        Map<String, List<AggregationDetails>> aggregationByYear;
379 484
        aggregationHistory = aggregationHistory.stream()
380
                            .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
381
                            .collect(Collectors.toList());
485
                .sorted(Comparator.comparing(AggregationDetails::getDate).reversed())
486
                .collect(Collectors.toList());
382 487

  
383
       return aggregationHistory.stream()
384
                            .collect(Collectors.groupingBy(AggregationDetails::getYear));
488
        return aggregationHistory.stream()
489
                .collect(Collectors.groupingBy(AggregationDetails::getYear));
385 490
    }
386 491

  
387 492

  
......
390 495
                                                  String page,
391 496
                                                  String size) throws JSONException {
392 497

  
393
        LOGGER.debug("Retreiving  repositories with official name : " + name );
394
        UriComponents uriComponents = searchDatasource("0","100");
498
        LOGGER.debug("Retreiving  repositories with official name : " + name);
499
        UriComponents uriComponents = searchDatasource("0", "100");
395 500
        RequestFilter requestFilter = new RequestFilter();
396 501
        requestFilter.setOfficialname(name);
397 502

  
398
        try{
399
            String rs = restTemplate.postForObject(uriComponents.toUri(),requestFilter, String.class);
503
        try {
504
            String rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, String.class);
400 505
            List<Repository> repos = Converter.jsonToRepositoryList(new JSONObject(rs));
401 506
            for (Repository r : repos)
402 507
                updateRepositoryInfo(r);
403 508
            return repos;
404
        }catch (Exception e){
405
            LOGGER.debug("Exception on getRepositoriesByName" , e);
509
        } catch (Exception e) {
510
            LOGGER.debug("Exception on getRepositoriesByName", e);
406 511
            emailUtils.reportException(e);
407 512
            throw e;
408 513
        }
......
417 522
                .path("/{id}")
418 523
                .build().expand(id).encode();
419 524

  
420
        try{
525
        try {
421 526
            String rs = restTemplate.getForObject(uriComponents.toUri(), String.class);
422 527
            return Converter.jsonToRepositoryInterfaceList(new JSONObject(rs));
423
        }catch (Exception e ){
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff