Project

General

Profile

« Previous | Next » 

Revision 62271

banching to fix aggregations

View differences:

modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/broker/AdvQueryObject.java
1
package eu.dnetlib.repo.manager.domain.broker;
2

  
3

  
4

  
5
import java.util.ArrayList;
6
import java.util.List;
7

  
8
public class AdvQueryObject   {
9

  
10
    private String datasource = "";
11
    private String topic = "";
12
    private List<String> titles = new ArrayList<>();
13
    private List<String> subjects = new ArrayList<>();
14
    private List<String> authors = new ArrayList<>();
15
    private List<Range> dates = new ArrayList<>();
16
    private Range trust = new Range("0", "1");
17

  
18
    private long page = 0;
19

  
20
    public AdvQueryObject() {
21
    }
22

  
23
    public AdvQueryObject(String datasource, String topic, List<String> titles, List<String> subjects, List<String> authors,
24
                          List<Range> dates, Range trust, long page) {
25
        this.datasource = datasource;
26
        this.topic = topic;
27
        this.titles = titles;
28
        this.subjects = subjects;
29
        this.authors = authors;
30
        this.dates = dates;
31
        this.trust = trust;
32
        this.page = page;
33
    }
34

  
35
    public String getDatasource() {
36
        return datasource;
37
    }
38

  
39
    public void setDatasource(String datasource) {
40
        this.datasource = datasource;
41
    }
42

  
43
    public String getTopic() {
44
        return topic;
45
    }
46

  
47
    public void setTopic(String topic) {
48
        this.topic = topic;
49
    }
50

  
51
    public List<String> getTitles() {
52
        return titles;
53
    }
54

  
55
    public void setTitles(List<String> titles) {
56
        this.titles = titles;
57
    }
58

  
59
    public List<String> getSubjects() {
60
        return subjects;
61
    }
62

  
63
    public void setSubjects(List<String> subjects) {
64
        this.subjects = subjects;
65
    }
66

  
67
    public List<String> getAuthors() {
68
        return authors;
69
    }
70

  
71
    public void setAuthors(List<String> authors) {
72
        this.authors = authors;
73
    }
74

  
75
    public List<Range> getDates() {
76
        return dates;
77
    }
78

  
79
    public void setDates(List<Range> dates) {
80
        this.dates = dates;
81
    }
82

  
83
    public Range getTrust() {
84
        return trust;
85
    }
86

  
87
    public void setTrust(Range trust) {
88
        this.trust = trust;
89
    }
90

  
91
    public long getPage() {
92
        return page;
93
    }
94

  
95
    public void setPage(long page) {
96
        this.page = page;
97
    }
98
}
99

  
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/Organization.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3

  
4

  
5
public class Organization{
6
    private String country;
7
    private String legalname;
8
    private String websiteurl;
9
    private String legalshortname;
10
    private String logourl;
11

  
12
    public String getCountry() {
13
        return country;
14
    }
15

  
16
    public void setCountry(String country) {
17
        this.country = country;
18
    }
19

  
20
    public String getLegalname() {
21
        return legalname;
22
    }
23

  
24
    public void setLegalname(String legalname) {
25
        this.legalname = legalname;
26
    }
27

  
28
    public String getWebsiteurl() {
29
        return websiteurl;
30
    }
31

  
32
    public void setWebsiteurl(String websiteurl) {
33
        this.websiteurl = websiteurl;
34
    }
35

  
36
    public String getLegalshortname() {
37
        return legalshortname;
38
    }
39

  
40
    public void setLegalshortname(String legalshortname) {
41
        this.legalshortname = legalshortname;
42
    }
43

  
44
    public String getLogourl() {
45
        return logourl;
46
    }
47

  
48
    public void setLogourl(String logourl) {
49
        this.logourl = logourl;
50
    }
51
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/broker/ConditionParams.java
1
package eu.dnetlib.repo.manager.domain.broker;
2

  
3
/**
4
 * Created by stefanos on 17/3/2017.
5
 */
6
public class ConditionParams {
7

  
8
    private String value;
9
    private String otherValue;
10

  
11
    public ConditionParams() {
12
    }
13

  
14
    public ConditionParams(final String value, final String otherValue) {
15
        this.value = value;
16
        this.otherValue = otherValue;
17
    }
18

  
19
    public String getValue() {
20
        return this.value;
21
    }
22

  
23
    public void setValue(final String value) {
24
        this.value = value;
25
    }
26

  
27
    public String getOtherValue() {
28
        return this.otherValue;
29
    }
30

  
31
    public void setOtherValue(final String otherValue) {
32
        this.otherValue = otherValue;
33
    }
34
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/broker/MapValueType.java
1
package eu.dnetlib.repo.manager.domain.broker;
2

  
3

  
4
/**
5
 * Created by stefanos on 17/3/2017.
6
 */
7
public enum MapValueType {
8
    STRING, INTEGER, FLOAT, DATE, BOOLEAN, LIST_STRING, LIST_INTEGER, LIST_FLOAT, LIST_DATE, LIST_BOOLEAN;
9
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/RepositorySummaryInfo.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3

  
4

  
5
import java.util.Date;
6

  
7
public class RepositorySummaryInfo{
8

  
9
    String id;
10
    String repositoryName;
11
    String logoURL;
12
    int recordsCollected;
13
    Date lastIndexedVersion;
14
    long enrichmentEvents;
15
    String totalViews;
16
    String totalDownloads;
17

  
18
    public RepositorySummaryInfo() {
19
    }
20

  
21
    public String getId() {
22
        return id;
23
    }
24

  
25
    public void setId(String id) {
26
        this.id = id;
27
    }
28

  
29
    public String getRepositoryName() {
30
        return repositoryName;
31
    }
32

  
33
    public void setRepositoryName(String repositoryName) {
34
        this.repositoryName = repositoryName;
35
    }
36

  
37
    public String getLogoURL() {
38
        return logoURL;
39
    }
40

  
41
    public void setLogoURL(String logoURL) {
42
        this.logoURL = logoURL;
43
    }
44

  
45
    public int getRecordsCollected() {
46
        return recordsCollected;
47
    }
48

  
49
    public void setRecordsCollected(int recordsCollected) {
50
        this.recordsCollected = recordsCollected;
51
    }
52

  
53
    public Date getLastIndexedVersion() {
54
        return lastIndexedVersion;
55
    }
56

  
57
    public void setLastIndexedVersion(Date lastIndexedVersion) {
58
        this.lastIndexedVersion = lastIndexedVersion;
59
    }
60

  
61
    public long getEnrichmentEvents() {
62
        return enrichmentEvents;
63
    }
64

  
65
    public void setEnrichmentEvents(long enrichmentEvents) {
66
        this.enrichmentEvents = enrichmentEvents;
67
    }
68

  
69
    public String getTotalViews() {
70
        return totalViews;
71
    }
72

  
73
    public void setTotalViews(String totalViews) {
74
        this.totalViews = totalViews;
75
    }
76

  
77
    public String getTotalDownloads() {
78
        return totalDownloads;
79
    }
80

  
81
    public void setTotalDownloads(String totalDownloads) {
82
        this.totalDownloads = totalDownloads;
83
    }
84
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/broker/SimpleSubscriptionDesc.java
1
package eu.dnetlib.repo.manager.domain.broker;
2

  
3

  
4

  
5
import java.util.Date;
6

  
7
/**
8
 * Created by stefanos on 10-Mar-17.
9
 */
10
public class SimpleSubscriptionDesc   {
11

  
12
    private String id;
13
    private String datasource;
14
    private String topic;
15
    private long count;
16
    private Date creationDate;
17
    private Date lastNotificationDate;
18

  
19
    public SimpleSubscriptionDesc() {
20
    }
21

  
22
    public SimpleSubscriptionDesc(final String id, final String datasource, final String topic, final long count) {
23
        this.id = id;
24
        this.datasource = datasource;
25
        this.topic = topic;
26
        this.count = count;
27
    }
28

  
29
    public String getId() {
30
        return this.id;
31
    }
32

  
33
    public void setId(final String id) {
34
        this.id = id;
35
    }
36

  
37
    public String getDatasource() {
38
        return this.datasource;
39
    }
40

  
41
    public void setDatasource(final String datasource) {
42
        this.datasource = datasource;
43
    }
44

  
45
    public String getTopic() {
46
        return this.topic;
47
    }
48

  
49
    public void setTopic(final String topic) {
50
        this.topic = topic;
51
    }
52

  
53
    public long getCount() {
54
        return this.count;
55
    }
56

  
57
    public void setCount(final long count) {
58
        this.count = count;
59
    }
60

  
61
    public Date getCreationDate() {
62
        return creationDate;
63
    }
64

  
65
    public void setCreationDate(Date creationDate) {
66
        this.creationDate = creationDate;
67
    }
68

  
69
    public Date getLastNotificationDate() {
70
        return lastNotificationDate;
71
    }
72

  
73
    public void setLastNotificationDate(Date lastNotificationDate) {
74
        this.lastNotificationDate = lastNotificationDate;
75
    }
76
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/Timezone.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3

  
4
public class Timezone{
5
	private String name;
6
	private double offset;
7

  
8
	public Timezone(){
9
	}
10

  
11
	public Timezone(String name, double offset) {
12
		super();
13
		this.name = name;
14
		this.offset = offset;
15
	}
16
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/BrokerException.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3

  
4
/**
5
 * Created by stefanos on 27-Oct-16.
6
 */
7
public class BrokerException extends Exception {
8

  
9
    public BrokerException(Throwable th) {
10
        super(th);
11
    }
12

  
13
    public BrokerException() {
14
    }
15

  
16

  
17
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/Triple.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3

  
4

  
5
/**
6
 * Created by stefania on 3/8/16.
7
 */
8
public class Triple<K, V, L> extends Tuple<K, V>   {
9

  
10
    private L third;
11

  
12
    public Triple() {
13
    }
14

  
15
    public Triple(K first, V second, L third) {
16
        super(first, second);
17
        this.third = third;
18
    }
19

  
20
    public L getThird() {
21
        return third;
22
    }
23

  
24
    public void setThird(L third) {
25
        this.third = third;
26
    }
27
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/Vocabulary.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3

  
4

  
5
/**
6
 * Created by stefania on 3/8/16.
7
 */
8
public class Vocabulary   {
9

  
10
    private String id;
11
    private String name;
12

  
13
    public Vocabulary() {
14
    }
15

  
16
    public Vocabulary(String id, String name) {
17
        this.id = id;
18
        this.name = name;
19
    }
20

  
21
    public String getId() {
22
        return id;
23
    }
24

  
25
    public void setId(String id) {
26
        this.id = id;
27
    }
28

  
29
    public String getName() {
30
        return name;
31
    }
32

  
33
    public void setName(String name) {
34
        this.name = name;
35
    }
36
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/JobsOfUser.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3

  
4
import eu.dnetlib.domain.functionality.validator.StoredJob;
5

  
6
import java.util.List;
7

  
8
/**
9
 * Created by nikonas on 29/3/16.
10
 */
11
public class JobsOfUser   {
12

  
13
    private int totalJobs;
14
    private int totalJobsSuccessful;
15
    private int totalJobsFailed;
16
    private int totalJobsOngoing;
17

  
18
    private List<StoredJob> jobs;
19

  
20
    public int getTotalJobs() {
21
        return totalJobs;
22
    }
23

  
24
    public void setTotalJobs(int totalJobs) {
25
        this.totalJobs = totalJobs;
26
    }
27

  
28
    public int getTotalJobsSuccessful() {
29
        return totalJobsSuccessful;
30
    }
31

  
32
    public void setTotalJobsSuccessful(int totalJobsSuccessful) {
33
        this.totalJobsSuccessful = totalJobsSuccessful;
34
    }
35

  
36
    public int getTotalJobsFailed() {
37
        return totalJobsFailed;
38
    }
39

  
40
    public void setTotalJobsFailed(int totalJobsFailed) {
41
        this.totalJobsFailed = totalJobsFailed;
42
    }
43

  
44
    public int getTotalJobsOngoing() {
45
        return totalJobsOngoing;
46
    }
47

  
48
    public void setTotalJobsOngoing(int totalJobsOngoing) {
49
        this.totalJobsOngoing = totalJobsOngoing;
50
    }
51

  
52
    public List<StoredJob> getJobs() {
53
        return jobs;
54
    }
55

  
56
    public void setJobs(List<StoredJob> jobs) {
57
        this.jobs = jobs;
58
    }
59
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/AggregationDetails.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3
import java.util.Calendar;
4
import java.util.Date;
5

  
6
public class AggregationDetails{
7

  
8

  
9
    private String aggregationStage;
10
    private Date date;
11
    private int numberOfRecords;
12
    private String collectionMode;
13
    private Boolean indexedVersion;
14

  
15
    public AggregationDetails() {
16
    }
17

  
18
    public String getAggregationStage() {
19
        return aggregationStage;
20
    }
21

  
22
    public String getCollectionMode() {
23
        return collectionMode;
24
    }
25

  
26
    public void setCollectionMode(String collectionMode) {
27
        this.collectionMode = collectionMode;
28
    }
29

  
30
    public void setAggregationStage(String aggregationStage) {
31
        this.aggregationStage = aggregationStage;
32
    }
33

  
34
    public Date getDate() {
35
        return date;
36
    }
37

  
38
    public void setDate(Date date) {
39
        this.date = date;
40
    }
41

  
42
    public int getNumberOfRecords() {
43
        return numberOfRecords;
44
    }
45

  
46
    public void setNumberOfRecords(int numberOfRecords) {
47
        this.numberOfRecords = numberOfRecords;
48
    }
49

  
50
    public String getYear() {
51
        Calendar calendar = Calendar.getInstance();
52
        calendar.setTime(getDate());
53
        return String.valueOf(calendar.get(Calendar.YEAR));
54
    }
55

  
56
    public Boolean getIndexedVersion() {
57
        return indexedVersion;
58
    }
59

  
60
    public void setIndexedVersion(Boolean indexedVersion) {
61
        this.indexedVersion = indexedVersion;
62
    }
63
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/BrokerSummary.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3
import eu.dnetlib.repo.manager.domain.broker.BrowseEntry;
4
import eu.dnetlib.repo.manager.domain.broker.SimpleSubscriptionDesc;
5

  
6
import java.util.List;
7
import java.util.Map;
8

  
9
public class BrokerSummary {
10
    private Map<String, List<SimpleSubscriptionDesc>> userSubs;
11

  
12
    private List<BrowseEntry> topicsForDatasource;
13

  
14
    public BrokerSummary(){}
15

  
16
    public BrokerSummary(Map<String, List<SimpleSubscriptionDesc>> userSubs, List<BrowseEntry> topicsForDatasource) {
17
        this.userSubs = userSubs;
18
        this.topicsForDatasource = topicsForDatasource;
19
    }
20

  
21
    public Map<String, List<SimpleSubscriptionDesc>> getUserSubs() {
22
        return userSubs;
23
    }
24

  
25
    public void setUserSubs(Map<String, List<SimpleSubscriptionDesc>> userSubs) {
26
        this.userSubs = userSubs;
27
    }
28

  
29
    public List<BrowseEntry> getTopicsForDatasource() {
30
        return topicsForDatasource;
31
    }
32

  
33
    public void setTopicsForDatasource(List<BrowseEntry> topicsForDatasource) {
34
        this.topicsForDatasource = topicsForDatasource;
35
    }
36
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/controllers/RepositoryController.java
1
package eu.dnetlib.repo.manager.controllers;
2

  
3
import eu.dnetlib.domain.data.Repository;
4
import eu.dnetlib.domain.data.RepositoryInterface;
5
import eu.dnetlib.repo.manager.domain.*;
6
import eu.dnetlib.repo.manager.domain.dto.RepositoryTerms;
7
import eu.dnetlib.repo.manager.domain.dto.User;
8
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
9
import eu.dnetlib.repo.manager.service.RepositoryService;
10
import eu.dnetlib.repo.manager.service.security.AuthorizationService;
11
import eu.dnetlib.repo.manager.utils.JsonUtils;
12
import io.swagger.annotations.Api;
13
import org.apache.log4j.Logger;
14
import org.json.JSONException;
15
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
16
import org.springframework.beans.factory.annotation.Autowired;
17
import org.springframework.http.HttpStatus;
18
import org.springframework.http.MediaType;
19
import org.springframework.http.ResponseEntity;
20
import org.springframework.security.access.prepost.PostAuthorize;
21
import org.springframework.security.access.prepost.PreAuthorize;
22
import org.springframework.security.core.Authentication;
23
import org.springframework.security.core.context.SecurityContextHolder;
24
import org.springframework.web.bind.annotation.*;
25

  
26
import javax.ws.rs.core.Response;
27
import java.io.IOException;
28
import java.util.Date;
29
import java.util.List;
30
import java.util.Map;
31

  
32
@RestController
33
@RequestMapping(value = "/repositories")
34
@Api(description = "Repository API", tags = {"repositories"})
35
public class RepositoryController {
36

  
37
    private static final Logger logger = Logger.getLogger(RepositoryController.class);
38

  
39
    private final RepositoryService repositoryService;
40
    private final AuthorizationService authorizationService;
41

  
42
    @Autowired
43
    RepositoryController(RepositoryService repositoryService,
44
                         AuthorizationService authorizationService) {
45
        this.repositoryService = repositoryService;
46
        this.authorizationService = authorizationService;
47
    }
48

  
49
    @RequestMapping(value = "/countries", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
50
    @ResponseBody
51
    public Country[] getCountries() {
52
        return repositoryService.getCountries();
53
    }
54

  
55
    @RequestMapping(value = "/getRepositoriesByCountry/{country}/{mode}", method = RequestMethod.GET,
56
            produces = MediaType.APPLICATION_JSON_VALUE)
57
    @ResponseBody
58
    public List<RepositorySnippet> getRepositoriesByCountry(@PathVariable("country") String country,
59
                                                            @PathVariable("mode") String mode,
60
                                                            @RequestParam(value = "managed", required = false) Boolean managed) throws JSONException, IOException {
61
        return repositoryService.getRepositoriesByCountry(country, mode, managed);
62
    }
63

  
64
    @RequestMapping(value = "/snippets/user", method = RequestMethod.GET,
65
            produces = MediaType.APPLICATION_JSON_VALUE)
66
    @ResponseBody
67
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
68
    public List<RepositorySnippet> getRepositoriesSnippetsOfUser() throws Exception {
69
        return repositoryService.getRepositoriesSnippetsOfUser("0", "100"); // FIXME
70
    }
71

  
72
    @RequestMapping(value = "/terms", method = RequestMethod.POST,
73
            produces = MediaType.APPLICATION_JSON_VALUE)
74
    @ResponseBody
75
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
76
    public void updateRepositoriesTerms(@RequestBody List<RepositoryTerms> repositoriesTerms) throws Exception {
77
        Date date = new Date();
78
        if (repositoriesTerms != null) {
79
        for (RepositoryTerms terms : repositoriesTerms) {
80
                Repository repository = repositoryService.getRepositoryById(terms.getId());
81
                repository.setConsentTermsOfUse(terms.getConsentTermsOfUse());
82
                repository.setFullTextDownload(terms.getFullTextDownload());
83
                repository.setLastConsentTermsOfUseDate(date);
84
                repositoryService.updateRepository(repository, SecurityContextHolder.getContext().getAuthentication());
85
            }
86
        }
87
    }
88

  
89
    @RequestMapping(value = "/searchRegisteredRepositories/{page}/{size}", method = RequestMethod.GET,
90
            produces = MediaType.APPLICATION_JSON_VALUE)
91
    @ResponseBody
92
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
93
    public List<RepositorySnippet> searchRegisteredRepositories(@RequestParam(name = "country", required = false) String country,
94
                                                                @RequestParam(name = "typology", required = false) String typology,
95
                                                                @RequestParam(name = "englishName", required = false) String englishName,
96
                                                                @RequestParam(name = "officialName", required = false) String officialName,
97
                                                                @RequestParam("requestSortBy") String requestSortBy,
98
                                                                @RequestParam("order") String order,
99
                                                                @PathVariable("page") int page,
100
                                                                @PathVariable("size") int pageSize) throws Exception {
101

  
102
        return repositoryService.searchRegisteredRepositories(country, typology, englishName, officialName, requestSortBy, order, page, pageSize);
103
    }
104

  
105
    @RequestMapping(value = "/getRepositoryById/{id}", method = RequestMethod.GET,
106
            produces = MediaType.APPLICATION_JSON_VALUE)
107
    @ResponseBody
108
    @PostAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (returnObject.registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
109
    public Repository getRepositoryById(@PathVariable("id") String id) throws JSONException, ResourceNotFoundException {
110
        Repository repo = repositoryService.getRepositoryById(id);
111

  
112
        if (repo != null)
113
            logger.info("Returning repository " + repo.getId() + " registered by " + repo.getRegisteredBy());
114
        else
115
            logger.info("Requested repository " + id + " not found");
116
        return repo;
117
    }
118

  
119
    @RequestMapping(value = "/getRepositoryAggregations/{id}", method = RequestMethod.GET,
120
            produces = MediaType.APPLICATION_JSON_VALUE)
121
    @ResponseBody
122
    public List<AggregationDetails> getRepositoryAggregations(@PathVariable("id") String id) throws JSONException {
123
        return repositoryService.getRepositoryAggregations(id, 0, 20);
124
    }
125

  
126
    @RequestMapping(value = "/getRepositoryAggregationsByYear/{id}", method = RequestMethod.GET,
127
            produces = MediaType.APPLICATION_JSON_VALUE)
128
    @ResponseBody
129
    public Map<String, List<AggregationDetails>> getRepositoryAggregationsByYear(@PathVariable("id") String id) throws JSONException {
130
        return repositoryService.getRepositoryAggregationsByYear(id);
131
    }
132

  
133
    @RequestMapping(value = "/getRepositoriesByName/{name:.+}/{page}/{size}/", method = RequestMethod.GET,
134
            produces = MediaType.APPLICATION_JSON_VALUE)
135
    @ResponseBody
136
    public List<Repository> getRepositoriesByName(@PathVariable("name") String name,
137
                                                  @PathVariable("page") String page,
138
                                                  @PathVariable("size") String size) throws JSONException {
139
        return repositoryService.getRepositoriesByName(name, page, size);
140
    }
141

  
142
    @RequestMapping(value = "/getRepositoryInterface/{id}", method = RequestMethod.GET,
143
            produces = MediaType.APPLICATION_JSON_VALUE)
144
    @ResponseBody
145
    @PostAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id) or (@repositoryService.getRepositoryById(#id).registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
146
    public List<RepositoryInterface> getRepositoryInterface(@PathVariable("id") String id) throws JSONException {
147
        return repositoryService.getRepositoryInterface(id);
148
    }
149

  
150
    @RequestMapping(value = "/addRepository", method = RequestMethod.POST,
151
            consumes = MediaType.APPLICATION_JSON_VALUE)
152
    @ResponseBody
153
//    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or (hasAuthority(@authorizationService.convertRepoIdToRoleId(#repository.id)) or hasAuthority(@authorizationService.convertRepoIdToRoleId(returnObject.id)))")
154
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER')")
155
    public Repository addRepository(@RequestParam("datatype") String datatype,
156
                                    @RequestBody Repository repository) throws Exception {
157

  
158
        return repositoryService.addRepository(datatype, repository);
159
    }
160

  
161
    @RequestMapping(value = "/getDnetCountries", method = RequestMethod.GET,
162
            produces = MediaType.APPLICATION_JSON_VALUE)
163
    @ResponseBody
164
    public List<String> getDnetCountries() {
165
        return repositoryService.getDnetCountries();
166
    }
167

  
168
    @RequestMapping(value = "/getTypologies", method = RequestMethod.GET,
169
            produces = MediaType.APPLICATION_JSON_VALUE)
170
    @ResponseBody
171
    public List<String> getTypologies() {
172
        return repositoryService.getTypologies();
173
    }
174

  
175
    @RequestMapping(value = "/getTimezones", method = RequestMethod.GET,
176
            produces = MediaType.APPLICATION_JSON_VALUE)
177
    @ResponseBody
178
    public List<Timezone> getTimezones() {
179
        return repositoryService.getTimezones();
180
    }
181

  
182
    @RequestMapping(value = "/updateRepository", method = RequestMethod.POST,
183
            consumes = MediaType.APPLICATION_JSON_VALUE)
184
    @ResponseBody
185
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOfInterface(#repository.id)")
186
    public Repository updateRepository(@RequestBody Repository repository, Authentication authentication) throws Exception {
187
        return repositoryService.updateRepository(repository, authentication);
188
    }
189

  
190
    @RequestMapping(value = "/deleteInterface/", method = RequestMethod.DELETE)
191
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOfInterface(#id)")
192
    public void deleteRepositoryInterface(@RequestParam("id") String id,
193
                                          @RequestParam("registeredBy") String registeredBy) {
194
        repositoryService.deleteRepositoryInterface(id, registeredBy);
195
    }
196

  
197
    @RequestMapping(value = "/addInterface", method = RequestMethod.POST,
198
            consumes = MediaType.APPLICATION_JSON_VALUE)
199
    @ResponseBody
200
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
201
    public RepositoryInterface addRepositoryInterface(@RequestParam("datatype") String datatype,
202
                                                      @RequestParam("repoId") String id,
203
                                                      @RequestParam("registeredBy") String registeredBy,
204
                                                      @RequestParam(value = "comment", required = false) String comment,
205
                                                      @RequestBody RepositoryInterface repositoryInterface) throws Exception {
206
        return repositoryService.addRepositoryInterface(datatype, id, registeredBy, comment, repositoryInterface);
207
    }
208

  
209
    @RequestMapping(value = "/updateRepositoryInterface", method = RequestMethod.POST,
210
            consumes = MediaType.APPLICATION_JSON_VALUE)
211
    @ResponseBody
212
    @PreAuthorize("hasAuthority('SUPER_ADMINISTRATOR') or hasAuthority('CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
213
    public RepositoryInterface updateRepositoryInterface(@RequestParam("repoId") String id,
214
                                                         @RequestParam("registeredBy") String registeredBy,
215
                                                         @RequestParam(value = "comment", required = false) String comment,
216
                                                         @RequestBody RepositoryInterface repositoryInterface) throws Exception {
217
        return repositoryService.updateRepositoryInterface(id, registeredBy, comment, repositoryInterface);
218
    }
219

  
220
    @RequestMapping(value = "/getUrlsOfUserRepos/{page}/{size}/", method = RequestMethod.GET,
221
            produces = MediaType.APPLICATION_JSON_VALUE)
222
    @ResponseBody
223
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
224
    public List<String> getUrlsOfUserRepos(@PathVariable("page") String page, @PathVariable("size") String size) {
225
        return repositoryService.getUrlsOfUserRepos(((OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication()).getUserInfo().getEmail(), page, size);
226
    }
227

  
228
    @RequestMapping(value = "/getDatasourceVocabularies/{mode}", method = RequestMethod.GET,
229
            produces = MediaType.APPLICATION_JSON_VALUE)
230
    @ResponseBody
231
    public List<String> getDatasourceVocabularies(@PathVariable("mode") String mode) {
232
        return repositoryService.getDatasourceVocabularies(mode);
233
    }
234

  
235
    @RequestMapping(value = "/getCompatibilityClasses/{mode}", method = RequestMethod.GET,
236
            produces = MediaType.APPLICATION_JSON_VALUE)
237
    @ResponseBody
238
    public Map<String, String> getCompatibilityClasses(@PathVariable("mode") String mode) {
239

  
240
        return repositoryService.getCompatibilityClasses(mode);
241
    }
242

  
243
    @RequestMapping(value = "/getDatasourceClasses/{mode}", method = RequestMethod.GET,
244
            produces = MediaType.APPLICATION_JSON_VALUE)
245
    @ResponseBody
246
    public Map<String, String> getDatasourceClasses(@PathVariable("mode") String mode) {
247
        return repositoryService.getDatasourceClasses(mode);
248
    }
249

  
250
    @RequestMapping(value = "/getMetricsInfoForRepository/{id}", method = RequestMethod.GET,
251
            produces = MediaType.APPLICATION_JSON_VALUE)
252
    @ResponseBody
253
    public MetricsInfo getMetricsInfoForRepository(@PathVariable("id") String id) throws RepositoryServiceException {
254
        return repositoryService.getMetricsInfoForRepository(id);
255
    }
256

  
257
    @RequestMapping(value = "/getListLatestUpdate/{mode}", method = RequestMethod.GET,
258
            produces = MediaType.APPLICATION_JSON_VALUE)
259
    @ResponseBody
260
    public Map<String, String> getListLatestUpdate(@PathVariable("mode") String mode) throws JSONException {
261
        return repositoryService.getListLatestUpdate(mode);
262
    }
263

  
264
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
265
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
266

  
267
    /**
268
     * Get all the admins of the repository
269
     */
270
    @RequestMapping(method = RequestMethod.GET, path = "{id}/admins")
271
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
272
    public ResponseEntity<List<User>> getAdminsOfARepo(@PathVariable("id") String id) {
273
        return new ResponseEntity<>(authorizationService.getAdminsOfRepo(id), HttpStatus.OK);
274
    }
275

  
276
    /**
277
     * Subscribe to repo by email
278
     */
279
    @RequestMapping(method = RequestMethod.POST, path = "{id}/admins")
280
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
281
    public Response subscribeByEmail(@PathVariable("id") String id, @RequestBody String email) throws ResourceNotFoundException {
282
        authorizationService.addAdmin(id, email);
283
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(javax.ws.rs.core.MediaType.APPLICATION_JSON).build();
284
    }
285

  
286
    /**
287
     * Unsubscribe from repo by email
288
     */
289
    @RequestMapping(method = RequestMethod.DELETE, path = "{id}/admins/{email:.+}")
290
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#id)")
291
    public ResponseEntity<Void> unsubscribeByEmail(@PathVariable("id") String id, @PathVariable("email") String email) throws ResourceNotFoundException {
292
        authorizationService.removeAdmin(id, email);
293
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
294
    }
295
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/Aggregations.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3
import java.util.ArrayList;
4
import java.util.List;
5

  
6
public class Aggregations{
7

  
8
    private List<AggregationDetails> aggregationHistory = new ArrayList<>();
9
    private AggregationDetails lastCollection;
10
    private AggregationDetails lastTransformation;
11

  
12
    public Aggregations() {
13
    }
14

  
15
    public List<AggregationDetails> getAggregationHistory() {
16
        return aggregationHistory;
17
    }
18

  
19
    public void setAggregationHistory(List<AggregationDetails> aggregationHistory) {
20
        this.aggregationHistory = aggregationHistory;
21
    }
22

  
23
    public AggregationDetails getLastCollection() {
24
        return lastCollection;
25
    }
26

  
27
    public void setLastCollection(AggregationDetails lastCollection) {
28
        this.lastCollection = lastCollection;
29
    }
30

  
31
    public AggregationDetails getLastTransformation() {
32
        return lastTransformation;
33
    }
34

  
35
    public void setLastTransformation(AggregationDetails lastTransformation) {
36
        this.lastTransformation = lastTransformation;
37
    }
38
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/UsageSummary.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3
import eu.dnetlib.domain.data.PiwikInfo;
4

  
5
public class UsageSummary {
6
    private MetricsInfo metricsInfo;
7

  
8
    private PiwikInfo piwikInfo;
9

  
10
    public UsageSummary() {
11
    }
12

  
13
    public UsageSummary(MetricsInfo metricsInfo, PiwikInfo piwikInfo) {
14
        this.metricsInfo = metricsInfo;
15
        this.piwikInfo = piwikInfo;
16
    }
17

  
18
    public MetricsInfo getMetricsInfo() {
19
        return metricsInfo;
20
    }
21

  
22
    public void setMetricsInfo(MetricsInfo metricsInfo) {
23
        this.metricsInfo = metricsInfo;
24
    }
25

  
26
    public PiwikInfo getPiwikInfo() {
27
        return piwikInfo;
28
    }
29

  
30
    public void setPiwikInfo(PiwikInfo piwikInfo) {
31
        this.piwikInfo = piwikInfo;
32
    }
33
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java
1
package eu.dnetlib.repo.manager.controllers;
2

  
3
import eu.dnetlib.repo.manager.domain.dto.Role;
4
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
5
import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater;
6
import eu.dnetlib.repo.manager.service.security.AuthorizationService;
7
import eu.dnetlib.repo.manager.service.security.RoleMappingService;
8
import eu.dnetlib.repo.manager.utils.JsonUtils;
9
import io.swagger.annotations.Api;
10
import io.swagger.annotations.ApiOperation;
11
import org.springframework.beans.factory.annotation.Autowired;
12
import org.springframework.http.HttpStatus;
13
import org.springframework.http.ResponseEntity;
14
import org.springframework.security.access.prepost.PreAuthorize;
15
import org.springframework.web.bind.annotation.*;
16

  
17
import javax.ws.rs.core.MediaType;
18
import javax.ws.rs.core.Response;
19
import java.util.Collection;
20

  
21
//@RestController
22
//@RequestMapping(value = "/role-management")
23
//@Api(description = "Role Management", value = "role-management")
24
public class UserRoleController {
25

  
26
    private final AaiRegistryService aaiRegistryService;
27
    private final AuthoritiesUpdater authoritiesUpdater;
28
    private final RoleMappingService roleMappingService;
29
    private final AuthorizationService authorizationService;
30

  
31
    @Autowired
32
    UserRoleController(AaiRegistryService aaiRegistryService,
33
                       AuthoritiesUpdater authoritiesUpdater,
34
                       RoleMappingService roleMappingService,
35
                       AuthorizationService authorizationService) {
36
        this.aaiRegistryService = aaiRegistryService;
37
        this.authoritiesUpdater = authoritiesUpdater;
38
        this.roleMappingService = roleMappingService;
39
        this.authorizationService = authorizationService;
40
    }
41

  
42
    /**
43
     * Get the role with the given id.
44
     **/
45
    @RequestMapping(method = RequestMethod.GET, path = "/role/{id}")
46
//    @PreAuthorize("hasAnyAuthority('REGISTERED_USER', 'SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
47
    public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @PathVariable("id") String id) {
48
        int roleId = aaiRegistryService.getCouId(type, id);
49
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role id is: " + roleId).toString()).type(MediaType.APPLICATION_JSON).build();
50
    }
51

  
52
    /**
53
     * Create a new role with the given name and description.
54
     **/
55
    @RequestMapping(method = RequestMethod.POST, path = "/role")
56
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR')")
57
    public Response createRole(@RequestBody Role role) {
58
        aaiRegistryService.createRole(role);
59
        return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
60
    }
61

  
62
    /**
63
     * Subscribe to a type(Community, etc.) with id(ee, egi, etc.)
64
     */
65
    @ApiOperation(value = "subscribe")
66
    @RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}")
67
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
68
    public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) {
69
        Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier();
70
        if (coPersonId == null) {
71
            coPersonId = aaiRegistryService.getCoPersonIdByEmail();
72
        }
73
        Integer couId = aaiRegistryService.getCouId(type, id);
74
        if (couId != null) {
75
            Integer role = aaiRegistryService.getRoleId(coPersonId, couId);
76
            aaiRegistryService.assignMemberRole(coPersonId, couId, role);
77

  
78
            // Add role to current authorities
79
            authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id));
80

  
81
            return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
82
        } else {
83
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
84
        }
85
    }
86
    /////////////////////////////////////////////////////////////////////////////////////////////
87
    /////////////////////////////////////////////////////////////////////////////////////////////
88

  
89
    @RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}")
90
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
91
    public ResponseEntity<String> getUsersByCouId(@PathVariable("id") Integer id) {
92
//        calls.getUserByCoId()
93
        return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString());
94
    }
95

  
96

  
97
    @RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles")
98
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER') and authentication.userInfo.email==#email")
99
    public ResponseEntity<Collection<String>> getRolesByEmail(@PathVariable("email") String email) {
100
        return ResponseEntity.ok(authorizationService.getUserRoles(email));
101
    }
102

  
103

  
104
    @RequestMapping(method = RequestMethod.GET, path = "/user/roles/my")
105
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
106
    public ResponseEntity<Collection<String>> getRoleNames() {
107
        return ResponseEntity.ok(authorizationService.getUserRoles());
108
    }
109

  
110
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/CollectionMonitorSummary.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3
import java.util.List;
4

  
5
public class CollectionMonitorSummary {
6
    private List<AggregationDetails> aggregationDetails;
7

  
8
    private AggregationDetails lastIndexedVersion;
9

  
10
    public CollectionMonitorSummary(){}
11

  
12
    public CollectionMonitorSummary(List<AggregationDetails> aggregationDetails, AggregationDetails lastIndexedVersion) {
13
        this.aggregationDetails = aggregationDetails;
14
        this.lastIndexedVersion = lastIndexedVersion;
15
    }
16

  
17
    public List<AggregationDetails> getAggregationDetails() {
18
        return aggregationDetails;
19
    }
20

  
21
    public void setAggregationDetails(List<AggregationDetails> aggregationDetails) {
22
        this.aggregationDetails = aggregationDetails;
23
    }
24

  
25
    public AggregationDetails getLastIndexedVersion() {
26
        return lastIndexedVersion;
27
    }
28

  
29
    public void setLastIndexedVersion(AggregationDetails lastIndexedVersion) {
30
        this.lastIndexedVersion = lastIndexedVersion;
31
    }
32
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/controllers/PrometheusController.java
1
package eu.dnetlib.repo.manager.controllers;
2

  
3
import eu.dnetlib.repo.manager.service.PiWikService;
4
import eu.dnetlib.repo.manager.service.RepositoryService;
5
import eu.dnetlib.repo.manager.service.RepositoryServiceImpl;
6
import io.micrometer.core.instrument.binder.jvm.DiskSpaceMetrics;
7
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics;
8
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
9
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
10
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
11
import io.micrometer.core.instrument.binder.system.UptimeMetrics;
12
import io.micrometer.prometheus.PrometheusConfig;
13
import io.micrometer.prometheus.PrometheusMeterRegistry;
14
import io.prometheus.client.exporter.common.TextFormat;
15
import org.apache.log4j.Logger;
16
import org.json.JSONException;
17
import org.springframework.beans.factory.annotation.Autowired;
18
import org.springframework.http.MediaType;
19
import org.springframework.web.bind.annotation.RequestMapping;
20
import org.springframework.web.bind.annotation.RequestMethod;
21
import org.springframework.web.bind.annotation.RestController;
22

  
23
import java.io.File;
24

  
25

  
26
@RestController
27
@RequestMapping("/actuator/prometheus")
28
public class PrometheusController { // TODO: remove this with migration to Spring Boot 2
29
    private static final Logger LOGGER = Logger.getLogger(PrometheusController.class);
30

  
31
    private final PiWikService piWikService;
32
    private final RepositoryService repositoryService;
33

  
34
    @Autowired
35
    public PrometheusController(PiWikService piWikService, RepositoryService repositoryService) {
36
        this.piWikService = piWikService;
37
        this.repositoryService = repositoryService;
38
    }
39

  
40
    @RequestMapping(method = RequestMethod.GET, path = "", produces = MediaType.TEXT_PLAIN_VALUE)
41
    public String getPiwikMetrics() {
42
        PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
43
        registry.counter("provide_repositories_registered").increment(repositoryService.getTotalRegisteredRepositories());
44
        registry.counter("provide_usagecounts_repositories_registered").increment(piWikService.getTotal());
45
        registry.counter("provide_usagecounts_repositories_validated").increment(piWikService.getValidated(true));
46

  
47
        return registry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100);
48
    }
49

  
50
    @RequestMapping(method = RequestMethod.GET, path = "metrics", produces = MediaType.TEXT_PLAIN_VALUE)
51
    public String getMetrics() {
52
        PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
53
        new JvmThreadMetrics().bindTo(registry);
54
        new JvmGcMetrics().bindTo(registry);
55
        new JvmMemoryMetrics().bindTo(registry);
56
        new DiskSpaceMetrics(new File("/")).bindTo(registry);
57
        new ProcessorMetrics().bindTo(registry); // metrics related to the CPU stats
58
        new UptimeMetrics().bindTo(registry);
59

  
60
        return registry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100);
61
    }
62

  
63
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/ValidationServiceException.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3
/**
4
 * Created by nikonas on 7/12/15.
5
 */
6
public class ValidationServiceException extends Exception{
7

  
8
    public enum ErrorCode{
9
        NO_ADMIN_EMAILS,
10
        NOT_VALID_BASEURL,
11
        GENERAL_ERROR, NOT_VALID_SET
12
    }
13

  
14
    private ErrorCode errorCode = null;
15

  
16
    public ValidationServiceException() {
17
    }
18

  
19
    public ValidationServiceException(ErrorCode errorCode) {
20
        this.errorCode = errorCode;
21
    }
22

  
23
    public ValidationServiceException(String message, Throwable cause, ErrorCode errorCode) {
24
        super(message, cause);
25

  
26
        this.errorCode = errorCode;
27
    }
28

  
29
    public ValidationServiceException(String message, ErrorCode errorCode) {
30
        super(message);
31

  
32
        this.errorCode = errorCode;
33
    }
34

  
35
    public ValidationServiceException(Throwable cause, ErrorCode errorCode) {
36
        super(cause);
37

  
38
        this.errorCode = errorCode;
39
    }
40

  
41
    public ErrorCode getErrorCode() {
42
        return errorCode;
43
    }
44
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/domain/Tuple.java
1
package eu.dnetlib.repo.manager.domain;
2

  
3

  
4

  
5
/**
6
 * Created by stefania on 12/18/15.
7
 */
8
public class Tuple<K, V>   {
9

  
10
    private K first;
11
    private V second;
12

  
13
    public Tuple() {
14
    }
15

  
16
    public Tuple(K first, V second) {
17
        this.first = first;
18
        this.second = second;
19
    }
20

  
21
    public K getFirst() {
22
        return first;
23
    }
24

  
25
    public void setFirst(K first) {
26
        this.first = first;
27
    }
28

  
29
    public V getSecond() {
30
        return second;
31
    }
32

  
33
    public void setSecond(V second) {
34
        this.second = second;
35
    }
36
}
modules/uoa-repository-manager-service/branches/aggregations/src/main/java/eu/dnetlib/repo/manager/controllers/PiWikController.java
1
package eu.dnetlib.repo.manager.controllers;
2

  
3
import eu.dnetlib.domain.data.PiwikInfo;
4
import eu.dnetlib.repo.manager.domain.OrderByField;
5
import eu.dnetlib.repo.manager.domain.OrderByType;
6
import eu.dnetlib.repo.manager.domain.Paging;
7
import eu.dnetlib.repo.manager.domain.RepositoryServiceException;
8
import eu.dnetlib.repo.manager.service.PiWikServiceImpl;
9
import io.swagger.annotations.Api;
10
import io.swagger.annotations.ApiImplicitParam;
11
import io.swagger.annotations.ApiImplicitParams;
12
import org.apache.log4j.Logger;
13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.core.io.FileSystemResource;
15
import org.springframework.http.MediaType;
16
import org.springframework.http.ResponseEntity;
17
import org.springframework.security.access.prepost.PreAuthorize;
18
import org.springframework.web.bind.annotation.*;
19

  
20
import javax.servlet.http.HttpServletRequest;
21
import javax.servlet.http.HttpServletResponse;
22
import java.io.FileNotFoundException;
23
import java.io.IOException;
24
import java.io.PrintWriter;
25
import java.nio.file.Files;
26
import java.nio.file.Path;
27
import java.text.SimpleDateFormat;
28
import java.util.Date;
29
import java.util.List;
30

  
31
@RestController
32
@RequestMapping(value = "/piwik")
33
@Api(description = "Piwik API",  tags = {"piwik"})
34
public class PiWikController {
35

  
36
    private static final Logger LOGGER = Logger
37
            .getLogger(PiWikController.class);
38

  
39
    @Autowired
40
    private PiWikServiceImpl piWikService;
41

  
42
    @RequestMapping(value = "/getPiwikSiteForRepo/{repositoryId}" , method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
43
    @ResponseBody
44
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#repositoryId) or (@repositoryService.getRepositoryById(#repositoryId).registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
45
    public PiwikInfo getPiwikSiteForRepo(@PathVariable("repositoryId") String repositoryId) {
46
        return piWikService.getPiwikSiteForRepo(repositoryId);
47
    }
48

  
49
    @RequestMapping(value = "/savePiwikInfo" , method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
50
    @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or @authorizationService.isMemberOf(#piwikInfo.repositoryId) or (@repositoryService.getRepositoryById(#piwikInfo.repositoryId).registeredBy=='null' and hasAuthority('REGISTERED_USER'))")
51
    public PiwikInfo savePiwikInfo(@RequestBody PiwikInfo piwikInfo) {
52
        return piWikService.savePiwikInfo(piwikInfo);
53
    }
54

  
55
    @RequestMapping(value = "/getPiwikSitesForRepos" , method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
56
    @ApiImplicitParams({
57
            @ApiImplicitParam(name = "from", dataType = "number", paramType = "query"),
58
            @ApiImplicitParam(name = "quantity", dataType = "number", paramType = "query"),
59
            @ApiImplicitParam(name = "order", dataType = "eu.dnetlib.repo.manager.domain.OrderByType", paramType = "query"),
60
            @ApiImplicitParam(name = "orderField", dataType = "eu.dnetlib.repo.manager.domain.OrderByField", paramType = "query"),
61
            @ApiImplicitParam(name = "searchField", dataType = "string", paramType = "query"),
62
    })
63
    public Paging<PiwikInfo> getPiwikSitesForRepos(
64
            @RequestParam(value = "from",required=false,defaultValue = "0") int from,
65
            @RequestParam(value = "quantity",required=false,defaultValue = "100") int quantity,
66
            @RequestParam(value = "order",required=false,defaultValue = "DSC") OrderByType orderType,
67
            @RequestParam(value = "orderField", required = false, defaultValue = "REPOSITORY_NAME") OrderByField orderField,
68
            @RequestParam(value = "searchField", required = false, defaultValue = "") String searchField
69

  
70
    ){
71
        Paging<PiwikInfo> results = new Paging<>();
72
        List<PiwikInfo> returning = piWikService.getPiwikSitesForRepos(orderField,orderType,from,quantity,searchField);
73
        results.setFrom(from);
74
        results.setTo(from + returning.size());
75
        results.setTotal(piWikService.getPiwikSitesTotals(searchField));
76
        results.setResults(returning);
77
        return results;
78
    }
79
    @ApiImplicitParams({
80
            @ApiImplicitParam(name = "from", dataType = "number", paramType = "query"),
81
            @ApiImplicitParam(name = "quantity", dataType = "number", paramType = "query"),
82
            @ApiImplicitParam(name = "order", dataType = "eu.dnetlib.repo.manager.domain.OrderByType", paramType = "query"),
83
            @ApiImplicitParam(name = "searchField", dataType = "eu.dnetlib.repo.manager.domain.OrderByField", paramType = "query"),
84
            @ApiImplicitParam(name = "orderField", dataType = "string", paramType = "query"),
85
    })
86
    @RequestMapping(value = "/getPiwikSitesForRepos/csv" , method = RequestMethod.GET,produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
87
    @ResponseBody
88
    public FileSystemResource getPiwikSitesForReposToCsv(
89
            @RequestParam(value = "from",required=false,defaultValue = "0") int from,
90
            @RequestParam(value = "quantity",required=false,defaultValue = "10000") int quantity,
91
            @RequestParam(value = "order",required=false,defaultValue = "DSC") OrderByType orderType,
92
            @RequestParam(value = "orderField", required = false, defaultValue = "REPOSITORY_NAME") OrderByField orderField,
93
            @RequestParam(value = "searchField", required = false, defaultValue = "") String searchField,
94
            HttpServletResponse response,
95
            HttpServletRequest request
96
    ) throws IOException {
97

  
98
        Path p = Files.createTempFile("exportingCsv-", new Date().toString());
99
        List<PiwikInfo> returning = piWikService.getPiwikSitesForRepos(orderField,orderType,0,10000,searchField);
100
        try (PrintWriter writer = new PrintWriter(p.toFile())) {
101

  
102
            StringBuilder sb = new StringBuilder();
103
            sb.append(" Repository ID , Repository name, Country, Site ID, Authentication token, Creation date, Requestor full name, Requestor email, Validated, Validation date, Comment \n");
104

  
105
            for(PiwikInfo piwikInfo : returning){
106
                sb.append(
107
                        (piwikInfo.getRepositoryId() == null ? "," : piwikInfo.getRepositoryId()+ ",")+
108
                                (piwikInfo.getRepositoryName() == null ? "," : piwikInfo.getRepositoryName()+ ",")+
109
                                (piwikInfo.getCountry() == null ? "," : piwikInfo.getCountry()+ ",")+
110
                                (piwikInfo.getSiteId() == null ? "," : piwikInfo.getSiteId()+ ",") +
111
                                (piwikInfo.getAuthenticationToken() == null ? "," : piwikInfo.getAuthenticationToken()+ ",")+
112
                                (piwikInfo.getCreationDate() == null ? "," : piwikInfo.getCreationDate().toString()+ ",") +
113
                                (piwikInfo.getRequestorName() == null ? "," : piwikInfo.getRequestorName()+ ",") +
114
                                (piwikInfo.getRequestorEmail() == null ? "," : piwikInfo.getRequestorEmail()+ ",")+
115
                                piwikInfo.isValidated() + "," +
116
                                (piwikInfo.getValidationDate() == null ? "," : piwikInfo.getValidationDate().toString()+ ",") +
117
                                (piwikInfo.getComment() == null ? "\n" : piwikInfo.getComment()+ "\n")
118

  
119
                );
120
            }
121
            writer.write(sb.toString());
122

  
123
        } catch (FileNotFoundException e) {
124
            LOGGER.error(e.getMessage());
125
        }
126

  
127

  
128
        String mimeType = request.getServletContext().getMimeType(p.toFile().getAbsolutePath());
129
        if (mimeType == null) {
130
            mimeType = "application/octet-stream";
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff