Project

General

Profile

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

    
3
import eu.dnetlib.api.functionality.ValidatorServiceException;
4
import eu.dnetlib.domain.data.RepositoryInterface;
5
import eu.dnetlib.domain.functionality.validator.*;
6
import eu.dnetlib.repo.manager.domain.Constants;
7
import eu.dnetlib.repo.manager.domain.InterfaceInformation;
8
import eu.dnetlib.repo.manager.domain.ValidationServiceException;
9
import eu.dnetlib.repo.manager.utils.CrisValidatorUtils;
10
import eu.dnetlib.repo.manager.utils.OaiTools;
11
import gr.uoa.di.driver.util.ServiceLocator;
12
import org.apache.log4j.Logger;
13
import org.eurocris.openaire.cris.validator.model.Job;
14
import org.eurocris.openaire.cris.validator.service.JobExecutor;
15
import org.eurocris.openaire.cris.validator.service.MapJobDao;
16
import org.json.JSONException;
17
import org.springframework.beans.factory.annotation.Autowired;
18
import org.springframework.http.HttpStatus;
19
import org.springframework.http.ResponseEntity;
20
import org.springframework.security.access.prepost.PreAuthorize;
21
import org.springframework.security.core.context.SecurityContextHolder;
22
import org.springframework.stereotype.Service;
23

    
24
import javax.annotation.PostConstruct;
25
import javax.annotation.Resource;
26
import java.util.*;
27
import java.util.concurrent.ConcurrentHashMap;
28
import java.util.stream.Collectors;
29

    
30

    
31
@Service("validatorService")
32
public class ValidatorServiceImpl implements ValidatorService {
33

    
34
    @Autowired
35
    private MonitorServiceImpl monitorApi;
36

    
37
    @Autowired
38
    private RepositoryService repositoryService;
39

    
40
    @Resource(name = "validatorServiceLocator")
41
    private ServiceLocator<eu.dnetlib.api.functionality.ValidatorService> validatorServiceLocator;
42

    
43
    private eu.dnetlib.api.functionality.ValidatorService getValidationService() {
44
        return this.validatorServiceLocator.getService();
45
    }
46

    
47
    public ServiceLocator<eu.dnetlib.api.functionality.ValidatorService> getValidatorServiceLocator() {
48
        return validatorServiceLocator;
49
    }
50

    
51
    public void setValidatorServiceLocator(ServiceLocator<eu.dnetlib.api.functionality.ValidatorService> validatorServiceLocator) {
52
        this.validatorServiceLocator = validatorServiceLocator;
53
    }
54

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

    
57
    private static final Logger LOGGER = Logger
58
            .getLogger(ValidatorServiceImpl.class);
59

    
60
    @Autowired
61
    private EmailUtils emailUtils;
62

    
63
    @Autowired
64
    private JobExecutor crisValidatorExecutor;
65

    
66
    @Autowired
67
    private MapJobDao crisJobs;
68

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

    
83
                    if (rulesetMap.containsKey(key))
84
                        rulesetMap.get(key).add(ruleSet);
85
                    else {
86
                        List<RuleSet> ruleSets = new ArrayList<RuleSet>();
87
                        ruleSets.add(ruleSet);
88
                        rulesetMap.put(key, ruleSets);
89
                    }
90
                }
91
            }
92

    
93
            /////////////////////////////////////////////////////////////////////////////////////////
94
            // FIXME: this is a hack for CRIS Jan Dvorak Validator, should be implemented properly //
95
            /////////////////////////////////////////////////////////////////////////////////////////
96
            int ruleId = -1000;
97
            Rule rule = new Rule();
98
            rule.setType("cris");
99
            rule.setName("CRIS Rules");
100
            rule.setId(ruleId);
101
            rule.setMandatory(true);
102
            RuleSet crisRuleSet = new RuleSet();
103
            crisRuleSet.setContentRulesIds(Collections.singleton(ruleId));
104
            crisRuleSet.setContentRules(Collections.singletonList(rule));
105
            crisRuleSet.setUsageRulesIds(Collections.singleton(ruleId));
106
            crisRuleSet.setUsageRules(Collections.singletonList(rule));
107
            crisRuleSet.setId(-1);
108
            crisRuleSet.setDescription("Validates using the CRIS Validator implementation");
109
            crisRuleSet.setName("CRIS Validation");
110

    
111
            String crisKey = Constants.VALIDATION_MODE_CRIS;
112
            if (rulesetMap.containsKey(crisKey))
113
                rulesetMap.get(crisKey).add(crisRuleSet);
114
            else {
115
                List<RuleSet> ruleSets = new ArrayList<RuleSet>();
116
                ruleSets.add(crisRuleSet);
117
                rulesetMap.put(crisKey, ruleSets);
118
            }
119
            /////////////////////////////////////////////////////////////////////////////////////////
120
            /////////////////////////////////////////////////////////////////////////////////////////
121
        } catch (ValidatorServiceException e) {
122
            LOGGER.error(e);
123
        }
124

    
125
    }
126

    
127
    @Override
128
    @PreAuthorize("hasAuthority('REGISTERED_USER') and #jobForValidation.userEmail == authentication.userInfo.email")
129
    public JobForValidation submitJobForValidation(JobForValidation jobForValidation) throws ValidatorServiceException {
130
        LOGGER.debug("Submit job for validation with id : " + jobForValidation.getDatasourceId());
131
        try {
132
            emailUtils.sendSubmitJobForValidationEmail(SecurityContextHolder.getContext().getAuthentication(),jobForValidation);
133
            /////////////////////////////////////////////////////////////////////////////////////////
134
            // FIXME: this is a hack for CRIS Jan Dvorak Validator, should be implemented properly //
135
            /////////////////////////////////////////////////////////////////////////////////////////
136
            if (jobForValidation.getSelectedContentRules()!=null && jobForValidation.getSelectedContentRules().size() == 1 &&
137
                    jobForValidation.getSelectedContentRules().contains(-1000)) {
138
                crisValidatorExecutor.submit(jobForValidation.getBaseUrl(), jobForValidation.getUserEmail());
139
            } else {
140
                this.getValidationService().submitValidationJob(jobForValidation);
141
            }
142
            /////////////////////////////////////////////////////////////////////////////////////////
143
            /////////////////////////////////////////////////////////////////////////////////////////
144
//            this.getValidationService().submitValidationJob(jobForValidation);
145
        } catch (ValidatorServiceException e) {
146
            LOGGER.debug("Exception on submitJobForValidation" , e);
147
            emailUtils.reportException(e);
148
            throw e;
149
        } catch (Exception e) {
150
            LOGGER.error(e);
151
        }
152
        return jobForValidation;
153
    }
154

    
155
    @Override
156
    @PreAuthorize("hasAuthority('REGISTERED_USER') and #email == authentication.userInfo.email")
157
    public ResponseEntity<Object> reSubmitJobForValidation(String email,
158
                                                           String jobId) throws JSONException, ValidatorServiceException {
159
        LOGGER.debug("Resubmit validation job with id : " + jobId);
160
        StoredJob job = monitorApi.getJobSummary(jobId, "all");
161
        Set<Integer> contentRules = new HashSet<Integer>();
162
        Set<Integer> usageRules = new HashSet<Integer>();
163

    
164
        RuleSet ruleSet = null;
165
        for (List<RuleSet> ruleSets : this.rulesetMap.values()) {
166
            for (RuleSet rSet : ruleSets) {
167
                if (rSet.getName().equalsIgnoreCase("CRIS Validation")) {
168
                    crisValidatorExecutor.submit(job.getBaseUrl(), job.getUserEmail());
169
                    return new ResponseEntity<>("OK",HttpStatus.OK);
170
                } else if(rSet.getGuidelinesAcronym().equals(job.getDesiredCompatibilityLevel())){
171
                    ruleSet = rSet;
172
                    break;
173
                }
174
            }
175
        }
176
        if (ruleSet != null){
177
            for (int ruleId : job.getRules()) {
178
                if (ruleSet.getContentRulesIds().contains(ruleId))
179
                    contentRules.add(ruleId);
180
                else if (ruleSet.getUsageRulesIds().contains(ruleId))
181
                    usageRules.add(ruleId);
182
            }
183
        }
184
        if (!contentRules.isEmpty())
185
            job.setSelectedContentRules(contentRules);
186
        if (!usageRules.isEmpty())
187
            job.setSelectedUsageRules(usageRules);
188
        this.submitJobForValidation(job);
189
        return new ResponseEntity<>("OK",HttpStatus.OK);
190
    }
191

    
192
    @Override
193
    public List<RuleSet> getRuleSets(String mode) {
194
        LOGGER.info("Getting rulesets for mode: " + mode);
195
        return rulesetMap.get(mode);
196
    }
197

    
198
    @Override
199
    public List<String> getSetsOfRepository(String url) {
200
        LOGGER.debug("Getting sets of repository with url : " + url);
201
        try {
202
            return OaiTools.getSetsOfRepo(url);
203
        } catch (Exception e) {
204
            LOGGER.debug("Exception on getSetsOfRepository" , e);
205
            emailUtils.reportException(e);
206
        }
207
        return null;
208
    }
209

    
210
    @Override
211
    public boolean identifyRepo(String url) {
212
        LOGGER.debug("Identify repository with url : " + url);
213
        try {
214
            return OaiTools.identifyRepository(url);
215
        } catch (Exception e) {
216
            LOGGER.error("Error while identifying repository with url: " + url, e);
217
            emailUtils.reportException(e);
218
            return false;
219
        }
220
    }
221

    
222
    @Override
223
    public RuleSet getRuleSet(String acronym) {
224
        LOGGER.debug("Getting ruleset with acronym : " + acronym);
225
        RuleSet ruleSet = null;
226
        try {
227
            for (List<RuleSet> ruleSets : this.rulesetMap.values()) {
228
                for (RuleSet rSet : ruleSets)
229
                    if (rSet.getGuidelinesAcronym().equals(acronym)) {
230
                        ruleSet = rSet;
231
                        break;
232
                    }
233
            }
234
            return ruleSet;
235
        } catch (Exception e) {
236
            LOGGER.error("Error getting ruleset", e);
237
            emailUtils.reportException(e);
238
            return null;
239
        }
240
    }
241

    
242
    @Override
243
    @PreAuthorize("hasAuthority('REGISTERED_USER')")
244
    public List<StoredJob> getStoredJobsNew(String user,
245
                                            String jobType,
246
                                            String offset,
247
                                            String limit,
248
                                            String dateFrom,
249
                                            String dateTo,
250
                                            String validationStatus ) throws ValidatorServiceException {
251
//        return getValidationService().getStoredJobsNew(user, jobType, Integer.parseInt(offset), Integer.parseInt(limit), dateFrom, dateTo, validationStatus);
252
        List<StoredJob> jobs = getValidationService().getStoredJobsNew(user, jobType, Integer.parseInt(offset), Integer.parseInt(limit), dateFrom, dateTo, validationStatus);
253
        /////////////////////////////////////////////////////////////////////////////////////////
254
        // FIXME: this is a hack for CRIS Jan Dvorak Validator, should be implemented properly //
255
        /////////////////////////////////////////////////////////////////////////////////////////
256
        if (jobs == null) {
257
            jobs = new ArrayList<>();
258
        }
259
        List<Job> cj = crisJobs.getJobs(user);
260
        for (Job job : cj) {
261
            jobs.add(CrisValidatorUtils.convertJobToStoredJob(job));
262
        }
263
        /////////////////////////////////////////////////////////////////////////////////////////
264
        /////////////////////////////////////////////////////////////////////////////////////////
265
        return jobs;
266
    }
267

    
268
    @Override
269
    public int getStoredJobsTotalNumberNew(String user, String jobType, String validationStatus) throws  ValidatorServiceException {
270
        return getValidationService().getStoredJobsTotalNumberNew(user, jobType, validationStatus);
271
    }
272

    
273
    @Override
274
    public InterfaceInformation getInterfaceInformation(String baseUrl) throws ValidationServiceException {
275
        try {
276
            LOGGER.debug("Getting interface information with url: " + baseUrl);
277
            InterfaceInformation interfaceInformation = new InterfaceInformation();
278
            interfaceInformation.setIdentified(this.identifyRepo(baseUrl));
279
            if (interfaceInformation.isIdentified())
280
                interfaceInformation.setSets(this.getSetsOfRepository(baseUrl));
281

    
282
            return interfaceInformation;
283
        } catch (Exception e) {
284
            LOGGER.error("Error getting interface information with url: " + baseUrl, e);
285
            emailUtils.reportException(e);
286
            throw new ValidationServiceException("login.generalError", ValidationServiceException.ErrorCode.GENERAL_ERROR);
287
        }
288
    }
289

    
290
    @Override
291
    public List<StoredJob> getJobsSummary(String repoId, int limit) throws JSONException, ValidatorServiceException {
292
        return getValidationService().getJobSummary(repositoryService.getRepositoryInterface(repoId).stream().map(RepositoryInterface::getBaseUrl).collect(Collectors.toList()),limit);
293
    }
294

    
295
}
(20-20/20)