-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathValidationService.java
202 lines (180 loc) · 7.45 KB
/
ValidationService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
* Copyright (c) 2019. Ontario Institute for Cancer Research
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package bio.overture.song.server.service;
import static bio.overture.song.core.exceptions.ServerErrors.MALFORMED_PARAMETER;
import static bio.overture.song.core.exceptions.ServerException.checkServer;
import static bio.overture.song.core.utils.JsonUtils.fromJson;
import static bio.overture.song.core.utils.JsonUtils.mapper;
import static bio.overture.song.core.utils.Separators.COMMA;
import static bio.overture.song.server.utils.JsonParser.extractAnalysisTypeFromPayload;
import static bio.overture.song.server.utils.JsonSchemas.buildSchema;
import static bio.overture.song.server.utils.JsonSchemas.validateWithSchema;
import static java.lang.String.format;
import static java.util.Objects.isNull;
import static org.apache.commons.lang.StringUtils.isBlank;
import bio.overture.song.core.model.AnalysisTypeId;
import bio.overture.song.core.model.FileData;
import bio.overture.song.server.model.enums.UploadStates;
import bio.overture.song.server.repository.UploadRepository;
import bio.overture.song.server.validation.SchemaValidator;
import bio.overture.song.server.validation.ValidationResponse;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.collections.CollectionUtils;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class ValidationService {
private static final String FILE_DATA_SCHEMA_ID = "fileData";
private static final String STORAGE_DOWNLOAD_RESPONSE_SCHEMA_ID = "storageDownloadResponse";
private final SchemaValidator validator;
private final AnalysisTypeService analysisTypeService;
private final UploadRepository uploadRepository;
private final boolean enforceLatest;
private final Schema analysisTypeIdSchema;
@Autowired
public ValidationService(
@Value("${schemas.enforceLatest}") boolean enforceLatest,
@NonNull SchemaValidator validator,
@NonNull AnalysisTypeService analysisTypeService,
@NonNull Supplier<Schema> analysisTypeIdSchemaSupplier,
@NonNull UploadRepository uploadRepository) {
this.validator = validator;
this.analysisTypeService = analysisTypeService;
this.uploadRepository = uploadRepository;
this.enforceLatest = enforceLatest;
this.analysisTypeIdSchema = analysisTypeIdSchemaSupplier.get();
}
@SneakyThrows
public Optional<String> validate(@NonNull JsonNode payload) {
String errors = null;
try {
validateWithSchema(analysisTypeIdSchema, payload);
val analysisTypeResult = extractAnalysisTypeFromPayload(payload);
val analysisTypeId = fromJson(analysisTypeResult.get(), AnalysisTypeId.class);
val analysisType = analysisTypeService.getAnalysisType(analysisTypeId, false);
log.info(
format(
"Found Analysis type: name=%s version=%s",
analysisType.getName(), analysisType.getVersion()));
List<String> fileTypes = new ArrayList<>();
if (analysisType.getOptions() != null && analysisType.getOptions().getFileTypes() != null) {
fileTypes = analysisType.getOptions().getFileTypes();
}
validateFileType(fileTypes, payload);
val schema = buildSchema(analysisType.getSchema());
validateWithSchema(schema, payload);
} catch (ValidationException e) {
errors = COMMA.join(e.getAllMessages());
log.error(errors);
}
return Optional.ofNullable(errors);
}
private void validateFileType(List<String> fileTypes, @NonNull JsonNode payload) {
if (CollectionUtils.isNotEmpty(fileTypes)) {
JsonNode files = payload.get("files");
if (files.isArray()) {
for (JsonNode file : files) {
log.info("file is " + file);
String fileType = file.get("fileType").asText();
String fileName = file.get("fileName").asText();
if (!fileTypes.contains(fileType)) {
throw new ValidationException(
String.format(
"%s name is not supported, supported formats are %s",
fileName, String.join(", ", fileTypes)));
}
}
}
}
}
public void update(@NonNull String uploadId, String errorMessages) {
if (isNull(errorMessages)) {
updateAsValid(uploadId);
} else {
updateAsInvalid(uploadId, errorMessages);
}
}
// TODO: transition to everit json schema library
public Optional<String> validate(FileData fileData) {
val json = mapper().valueToTree(fileData);
val resp = validator.validate(FILE_DATA_SCHEMA_ID, json);
return processResponse(resp);
}
// TODO: transition to everit json schema library
public Optional<String> validateStorageDownloadResponse(JsonNode response) {
return processResponse(validator.validate(STORAGE_DOWNLOAD_RESPONSE_SCHEMA_ID, response));
}
public String validateAnalysisTypeVersion(AnalysisTypeId a) {
checkServer(
!isBlank(a.getName()),
getClass(),
MALFORMED_PARAMETER,
"The analysisType name cannot be null");
return validateAnalysisTypeVersion(a.getName(), a.getVersion());
}
public String validateAnalysisTypeVersion(@NonNull String name, Integer version) {
if (enforceLatest && !isNull(version)) {
val latestVersion = analysisTypeService.getLatestVersionNumber(name);
if (!version.equals(latestVersion)) {
val message =
format(
"Must use the latest version '%s' while enforceLatest=true, but using version '%s' of analysisType '%s' instead",
latestVersion, version, name);
log.error(message);
return message;
}
}
return null;
}
private void updateState(
@NonNull String uploadId, @NonNull UploadStates state, @NonNull String errors) {
uploadRepository
.findById(uploadId)
.map(
x -> {
x.setState(state);
x.setErrors(errors);
return x;
})
.ifPresent(uploadRepository::save);
}
private void updateAsValid(@NonNull String uploadId) {
updateState(uploadId, UploadStates.VALIDATED, "");
}
public void updateAsInvalid(@NonNull String uploadId, @NonNull String errorMessages) {
updateState(uploadId, UploadStates.VALIDATION_ERROR, errorMessages);
}
private static Optional<String> processResponse(ValidationResponse response) {
if (response.isValid()) {
return Optional.empty();
} else {
return Optional.of(response.getValidationErrors());
}
}
}