Project

General

Profile

1
package eu.dnetlib.repo.manager.service;
2

    
3
import eu.dnetlib.api.functionality.ValidatorService;
4
import eu.dnetlib.api.functionality.ValidatorServiceException;
5
import eu.dnetlib.domain.functionality.validator.JobForValidation;
6
import eu.dnetlib.domain.functionality.validator.RuleSet;
7
import eu.dnetlib.domain.functionality.validator.StoredJob;
8
import eu.dnetlib.repo.manager.shared.Constants;
9
import eu.dnetlib.repo.manager.shared.InterfaceInformation;
10
import eu.dnetlib.repo.manager.shared.ValidationServiceException;
11
import eu.dnetlib.repo.manager.utils.OaiTools;
12
import gr.uoa.di.driver.util.ServiceLocator;
13
import io.swagger.annotations.ApiParam;
14
import org.apache.log4j.Logger;
15
import org.json.JSONException;
16
import org.springframework.beans.factory.annotation.Autowired;
17
import org.springframework.http.HttpStatus;
18
import org.springframework.http.ResponseEntity;
19
import org.springframework.security.access.prepost.PreAuthorize;
20
import org.springframework.security.core.context.SecurityContextHolder;
21
import org.springframework.stereotype.Component;
22
import org.springframework.stereotype.Service;
23
import org.springframework.web.bind.annotation.PathVariable;
24
import org.springframework.web.bind.annotation.RequestBody;
25
import org.springframework.web.bind.annotation.RequestParam;
26

    
27
import javax.annotation.PostConstruct;
28
import javax.annotation.Resource;
29
import java.util.*;
30
import java.util.concurrent.ConcurrentHashMap;
31

    
32

    
33
@Service("validatorService")
34
public class ValidatorApiImpl implements ValidatorApi {
35

    
36
    @Autowired
37
    private MonitorApiImpl monitorApi;
38

    
39
    @Resource(name = "validatorServiceLocator")
40
    private ServiceLocator<ValidatorService> validatorServiceLocator;
41

    
42
    private ValidatorService getValidationService() {
43
        return this.validatorServiceLocator.getService();
44
    }
45

    
46
    public ServiceLocator<ValidatorService> getValidatorServiceLocator() {
47
        return validatorServiceLocator;
48
    }
49

    
50
    public void setValidatorServiceLocator(ServiceLocator<ValidatorService> validatorServiceLocator) {
51
        this.validatorServiceLocator = validatorServiceLocator;
52
    }
53

    
54
    private Map<String, List<RuleSet>> rulesetMap = new ConcurrentHashMap<String, List<RuleSet>>();
55

    
56
    private static final Logger LOGGER = Logger
57
            .getLogger(ValidatorApiImpl.class);
58

    
59
    @Autowired
60
    private EmailUtils emailUtils;
61

    
62
    @PostConstruct
63
    private void loadRules(){
64
        LOGGER.debug("PostConstruct method! Load rules!");
65
        try {
66
            for (RuleSet ruleSet : getValidationService().getRuleSets()) {
67
                if (ruleSet.getVisibility() != null && ruleSet.getVisibility().contains("development")) {
68
                    String key = "";
69
                    if (ruleSet.getGuidelinesAcronym().matches("^openaire[1-9].0_data$"))
70
                        key = Constants.VALIDATION_MODE_DATA;
71
                    else if (ruleSet.getGuidelinesAcronym().matches("^openaire[1-9].0$") || ruleSet.getGuidelinesAcronym().equals("driver"))
72
                        key = Constants.VALIDATION_MODE_LITERATURE;
73
                    else if (ruleSet.getGuidelinesAcronym().matches("^openaire[1-9].0_cris$"))
74
                        key = Constants.VALIDATION_MODE_CRIS;
75

    
76
                    if (rulesetMap.containsKey(key))
77
                        rulesetMap.get(key).add(ruleSet);
78
                    else {
79
                        List<RuleSet> ruleSets = new ArrayList<RuleSet>();
80
                        ruleSets.add(ruleSet);
81
                        rulesetMap.put(key, ruleSets);
82
                    }
83
                }
84
            }
85
        } catch (ValidatorServiceException e) {
86
            e.printStackTrace();
87
        }
88

    
89
    }
90

    
91
    @Override
92
    @PreAuthorize("hasRole('ROLE_USER') and #jobForValidation.userEmail == authentication.userInfo.email")
93
    public JobForValidation submitJobForValidation(@RequestBody JobForValidation jobForValidation) throws ValidatorServiceException {
94
        LOGGER.debug("Submit job for validation with id : " + jobForValidation.getDatasourceId());
95
        try {
96
            emailUtils.sendSubmitJobForValidationEmail(SecurityContextHolder.getContext().getAuthentication(),jobForValidation);
97
            this.getValidationService().submitValidationJob(jobForValidation);
98
        } catch (ValidatorServiceException e) {
99
            LOGGER.debug("Exception on submitJobForValidation" , e);
100
            emailUtils.reportException(e);
101
            throw e;
102
        } catch (Exception e) {
103
            e.printStackTrace();
104
        }
105
        return jobForValidation;
106
    }
107

    
108
    @Override
109
    @PreAuthorize("hasRole('ROLE_USER') and #email == authentication.userInfo.email")
110
    public ResponseEntity<Object> reSubmitJobForValidation(@PathVariable("email") String email,
111
                                                           @PathVariable("jobId") String jobId) throws JSONException, ValidatorServiceException {
112
        LOGGER.debug("Resubmit validation job with id : " + jobId);
113
        StoredJob job = monitorApi.getJobSummary(jobId,"all");
114
        Set<Integer> contentRules = new HashSet<Integer>();
115
        Set<Integer> usageRules = new HashSet<Integer>();
116

    
117
        RuleSet ruleSet = null;
118
        for (List<RuleSet> ruleSets : this.rulesetMap.values()) {
119
            for (RuleSet rSet : ruleSets)
120
                if (rSet.getGuidelinesAcronym().equals(job.getDesiredCompatibilityLevel())) {
121
                    ruleSet = rSet;
122
                    break;
123
                }
124
        }
125

    
126
        for (int ruleId : job.getRules()) {
127
            if (ruleSet.getContentRulesIds().contains(ruleId))
128
                contentRules.add(ruleId);
129
            else if (ruleSet.getUsageRulesIds().contains(ruleId))
130
                usageRules.add(ruleId);
131
        }
132
        if (!contentRules.isEmpty())
133
            job.setSelectedContentRules(contentRules);
134
        if (!usageRules.isEmpty())
135
            job.setSelectedUsageRules(usageRules);
136
        this.submitJobForValidation(job);
137
        return new ResponseEntity<>("OK",HttpStatus.OK);
138
    }
139

    
140
    @Override
141
    public List<RuleSet> getRuleSets(@PathVariable("mode") String mode) {
142
        LOGGER.info("Getting rulesets for mode: " + mode);
143
        return rulesetMap.get(mode);
144
    }
145

    
146
    @Override
147
    public List<String> getSetsOfRepository(@RequestParam(value = "url", required = true) String url) {
148
        LOGGER.debug("Getting sets of repository with url : " + url);
149
        try {
150
            return OaiTools.getSetsOfRepo(url);
151
        } catch (Exception e) {
152
            LOGGER.debug("Exception on getSetsOfRepository" , e);
153
            emailUtils.reportException(e);
154
        }
155
        return null;
156
    }
157

    
158
    @Override
159
    public boolean identifyRepo(@RequestParam(value = "url", required = true) String url) {
160
        LOGGER.debug("Identify repository with url : " + url);
161
        try {
162
            return OaiTools.identifyRepository(url);
163
        } catch (Exception e) {
164
            LOGGER.error("Error while identifying repository with url: " + url, e);
165
            emailUtils.reportException(e);
166
            return false;
167
        }
168
    }
169

    
170
    @Override
171
    public RuleSet getRuleSet(@PathVariable("acronym") String acronym) {
172
        LOGGER.debug("Getting ruleset with acronym : " + acronym);
173
        RuleSet ruleSet = null;
174
        try {
175
            for (List<RuleSet> ruleSets : this.rulesetMap.values()) {
176
                for (RuleSet rSet : ruleSets)
177
                    if (rSet.getGuidelinesAcronym().equals(acronym)) {
178
                        ruleSet = rSet;
179
                        break;
180
                    }
181
            }
182
            return ruleSet;
183
        } catch (Exception e) {
184
            LOGGER.error("Error getting ruleset", e);
185
            emailUtils.reportException(e);
186
            return null;
187
        }
188
    }
189

    
190
    @Override
191
    @PreAuthorize("hasRole('ROLE_USER')")
192
    public List<StoredJob> getStoredJobsNew(@RequestParam("user") @ApiParam(value = "User email", required = true) String user,
193
                                            @RequestParam(value = "jobType", required = false)
194
                                            @ApiParam(value = "Equals to filter job type on validation history page") String jobType,
195
                                            @RequestParam("offset") @ApiParam(value = "Page number", required = true) String offset,
196
                                            @RequestParam(value = "limit", required = false,defaultValue = "10") @ApiParam(value = "Null value") String limit,
197
                                            @RequestParam(value = "dateFrom", required = false) @ApiParam(value = "Null value") String dateFrom,
198
                                            @RequestParam(value = "dateTo", required = false) @ApiParam(value = "Null value") String dateTo,
199
                                            @RequestParam("validationStatus") @ApiParam(value = "Equals to filter validation jobs", required = true) String validationStatus
200
                                            ) throws ValidatorServiceException {
201
        return getValidationService().getStoredJobsNew(user, jobType, Integer.parseInt(offset), Integer.parseInt(limit), dateFrom, dateTo, validationStatus);
202
    }
203

    
204
    @Override
205
    public int getStoredJobsTotalNumberNew(String user, String jobType, String validationStatus) throws  ValidatorServiceException {
206
        return getValidationService().getStoredJobsTotalNumberNew(user, jobType, validationStatus);
207
    }
208

    
209
    @Override
210
    public InterfaceInformation getInterfaceInformation(@RequestParam(value = "baseUrl", required = true) String baseUrl) throws ValidationServiceException {
211
        try {
212
            LOGGER.debug("Getting interface information with url: " + baseUrl);
213
            InterfaceInformation interfaceInformation = new InterfaceInformation();
214
            interfaceInformation.setIdentified(this.identifyRepo(baseUrl));
215
            if (interfaceInformation.isIdentified())
216
                interfaceInformation.setSets(this.getSetsOfRepository(baseUrl));
217

    
218
            return interfaceInformation;
219
        } catch (Exception e) {
220
            LOGGER.error("Error getting interface information with url: " + baseUrl, e);
221
            emailUtils.reportException(e);
222
            throw new ValidationServiceException("login.generalError", ValidationServiceException.ErrorCode.GENERAL_ERROR);
223
        }
224
    }
225

    
226

    
227
}
(19-19/19)