-
Notifications
You must be signed in to change notification settings - Fork 5
/
OclFhirUtil.java
322 lines (273 loc) · 13.3 KB
/
OclFhirUtil.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package org.openconceptlab.fhir.util;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import com.google.gson.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.*;
import org.openconceptlab.fhir.model.*;
import org.openconceptlab.fhir.repository.SourceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static org.openconceptlab.fhir.util.OclFhirConstants.*;
@Component
public class OclFhirUtil {
@Value("${server.port}")
private String port;
private static FhirContext context;
private SourceRepository sourceRepository;
@Autowired
public OclFhirUtil(SourceRepository sourceRepository) {
this.sourceRepository = sourceRepository;
}
static {
context = FhirContext.forR4();
}
private String serverBase = "";
IParser parser = context.newJsonParser();
public static JsonParser jsonParser = new JsonParser();
public static Gson gson = new Gson();
public static final List<String> allowedFilterOperators = Arrays.asList(CodeSystem.FilterOperator.ISA.toCode(),
CodeSystem.FilterOperator.ISNOTA.toCode(), CodeSystem.FilterOperator.IN.toCode(),
CodeSystem.FilterOperator.NOTIN.toCode());
@PostConstruct
private void init() {
serverBase = String.format("http://localhost:%s/fhir",port);
}
public static FhirContext getFhirContext() {
return context;
}
public static <T extends Resource> Bundle getBundle(List<T> resource, String fhirBase, String requestPath) {
Bundle bundle = new Bundle();
bundle.setType(Bundle.BundleType.SEARCHSET);
bundle.setTotal(resource.size());
resource.stream().forEach(r -> {
Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent();
component.setResource(r);
//component.setFullUrl(getCompleteUrl(fhirBase, requestPath, r.getId()));
bundle.addEntry(component);
});
return bundle;
}
private static String getCompleteUrl(final String fhirBase, final String requestPath, final String id) {
return fhirBase + "/" + Paths.get(requestPath, id).toString();
}
public Source getSourceVersion(String id, String version, List<String> access, String ownerType, String owner) {
return getSourceVersion(new StringType(id), new StringType(version), access, ownerType, owner);
}
public Source getSourceVersion(StringType id, StringType version, List<String> access, String ownerType, String owner) {
final Source source;
if (!isValid(version)) {
// get most recent released version
source = getMostRecentReleasedSourceByOwner(id.getValue(), owner, ownerType, access);
} else {
// get a given version
if (ORG.equals(ownerType)) {
source = sourceRepository.findFirstByMnemonicAndVersionAndOrganizationMnemonicAndPublicAccessIn(
id.getValue(), version.getValue(), owner, access);
} else {
source = sourceRepository.findFirstByMnemonicAndVersionAndUserIdUsernameAndPublicAccessIn(
id.getValue(), version.getValue(), owner, access);
}
}
return source;
}
public Source getMostRecentReleasedSourceByOwner(String id, String owner, String ownerType, List<String> access) {
if (ORG.equals(ownerType)) {
return sourceRepository.findFirstByMnemonicAndReleasedAndPublicAccessInAndOrganizationMnemonicOrderByCreatedAtDesc(
id, true, access, owner);
}
return sourceRepository.findFirstByMnemonicAndReleasedAndPublicAccessInAndUserIdUsernameOrderByCreatedAtDesc(
id, true, access, owner);
}
public IGenericClient getClient() {
return context.newRestfulGenericClient(serverBase);
}
public String getResourceAsString(Resource resource) {
return parser.encodeResourceToString(resource);
}
public static IBaseResource getResource(String resource) {
return getFhirContext().newJsonParser().parseResource(resource);
}
public OperationOutcome getNotFoundOutcome(IdType id) {
OperationOutcome o = new OperationOutcome();
o.getIssueFirstRep()
.setSeverity(OperationOutcome.IssueSeverity.ERROR)
.setCode(OperationOutcome.IssueType.NOTFOUND)
.setDiagnostics("Resource " + id + " does not exist.");
return o;
}
public static OperationOutcome getError(OperationOutcome.IssueType errorType, final String error) {
OperationOutcome o = new OperationOutcome();
o.getIssueFirstRep()
.setSeverity(OperationOutcome.IssueSeverity.ERROR)
.setCode(errorType)
.setDiagnostics(error);
return o;
}
public static OperationOutcome getError(OperationOutcome.IssueType errorType) {
OperationOutcome o = new OperationOutcome();
o.getIssueFirstRep()
.setSeverity(OperationOutcome.IssueSeverity.ERROR)
.setCode(errorType);
return o;
}
public static boolean isValid(final String value) {
return StringUtils.isNotBlank(value);
}
public static boolean isValid(final StringType value) {
return value != null && StringUtils.isNotBlank(value.getValue());
}
public static boolean isValid(final PrimitiveType type) {
return type != null && !type.isEmpty();
}
public static StringType getOwnerProperty(final List<CodeType> type) {
StringType owner = new StringType();
if (type == null || type.isEmpty()) return owner;
type.parallelStream()
.filter(c -> c.getCode().startsWith(ORG_) || c.getCode().startsWith(USER_))
.map(CodeType::getCode)
.findFirst()
.ifPresent(owner::setValue);
return owner;
}
public static JsonObject parseExtras(String extras) {
return jsonParser.parse(extras).getAsJsonObject();
}
public static List<Identifier> getIdentifiers(JsonArray jsonArray) {
List<Identifier> identifiers = new ArrayList<>();
if (jsonArray != null && jsonArray.isJsonArray()) {
for(JsonElement je : jsonArray) {
JsonObject identifier = je.getAsJsonObject();
if(identifier.get(SYSTEM) != null && identifier.get(VALUE) != null) {
Identifier i = new Identifier();
i.setSystem(identifier.get(SYSTEM).getAsString());
i.setValue(identifier.get(VALUE).getAsString());
JsonElement use = identifier.get(USE);
if(use != null && Identifier.IdentifierUse.fromCode(use.getAsString()) != null)
i.setUse(Identifier.IdentifierUse.fromCode(use.getAsString()));
identifiers.add(i);
}
}
}
return identifiers;
}
public static boolean isValidElement(JsonElement element) {
return element != null && element.getAsString() != null;
}
public static void validatePublisher(String publisher) {
if (!isValidPublisher(publisher)) {
throw new InvalidRequestException("", getError(OperationOutcome.IssueType.INVALID,
String.format("Invalid publisher '%s' provided. Correct format is 'user:<username>' or 'org:<organizationId>'", publisher)));
}
}
public static boolean isValidPublisher(final String publisher) {
return isValid(publisher)
&& publisher.matches(PUBLISHER_REGEX)
&& publisher.split(SEP).length >= 2;
}
public static String getOwnerType(String owner) {
return owner.split(SEP)[0];
}
public static String getOwner(String owner) {
String[] arr = owner.split(SEP);
return String.join(SEP, ArrayUtils.subarray(arr, 1, arr.length));
}
public static <T extends MetadataResource> String toFhirString(final T resource) {
String fhirString = getFhirContext().newJsonParser().encodeResourceToString(resource);
JsonObject object = new JsonObject();
object.add("__fhir", jsonParser.parse(fhirString));
return gson.toJson(object);
}
public static Optional<Identifier> getIdentifier(String value) {
Identifier identifier = new Identifier();
identifier.setSystem("http://fhir.openconceptlab.org");
identifier.setValue(value.replace("sources", "CodeSystem").replace("collections", "ValueSet"));
identifier.getType().setText("Accession ID");
identifier.getType().getCodingFirstRep().setSystem("http://hl7.org/fhir/v2/0203").setCode("ACSN").setDisplay("Accession ID");
return isValid(value) ? Optional.of(identifier) : Optional.empty();
}
public static void addConceptDesignation(Concept concept, CodeSystem.ConceptDefinitionComponent definitionComponent) {
concept.getConceptsNames().parallelStream().forEach(name -> {
CodeSystem.ConceptDefinitionDesignationComponent designation = new CodeSystem.ConceptDefinitionDesignationComponent();
LocalizedText lt = name.getLocalizedText();
if(lt != null) {
designation.setLanguage(lt.getLocale());
if (isValid(lt.getType()))
designation.getUse().setCode(lt.getType());
designation.setValue(lt.getName());
definitionComponent.getDesignation().add(designation);
}
});
}
public static void addStatus(MetadataResource resource, boolean active, boolean retired, boolean released) {
if(active || released) {
resource.setStatus(Enumerations.PublicationStatus.ACTIVE);
} else if(retired) {
resource.setStatus(Enumerations.PublicationStatus.RETIRED);
} else {
resource.setStatus(Enumerations.PublicationStatus.UNKNOWN);
}
}
public String getDefinition(List<LocalizedText> definitions, String defaultLocale) {
if (definitions == null || definitions.isEmpty()) return "";
if (definitions.size() > 1) {
// match with dict default locale
Stream<LocalizedText> dlMatch = definitions.stream().filter(d -> defaultLocale.equals(d.getLocale()));
Optional<LocalizedText> dlPreferred = getPreferred(dlMatch);
if (dlPreferred.isPresent()) return dlPreferred.get().getName();
Optional<LocalizedText> dlNonPreferred = getNonPreferred(dlMatch);
if (dlNonPreferred.isPresent()) return dlNonPreferred.get().getName();
// match with dict supported locales
Stream<LocalizedText> slMatch = definitions.stream().filter(d -> defaultLocale.contains(d.getLocale()));
Optional<LocalizedText> slPreferred = getPreferred(slMatch);
if (slPreferred.isPresent()) return slPreferred.get().getName();
Optional<LocalizedText> slNonPreferred = getNonPreferred(slMatch);
if (slNonPreferred.isPresent()) return slNonPreferred.get().getName();
// Any locale preferred
Optional<LocalizedText> anyPreferred = getPreferred(definitions.stream());
if (anyPreferred.isPresent()) return anyPreferred.get().getName();
}
return definitions.get(0).getName();
}
private Optional<LocalizedText> getPreferred(Stream<LocalizedText> texts) {
return texts.filter(LocalizedText::getLocalePreferred).findFirst();
}
private Optional<LocalizedText> getNonPreferred(Stream<LocalizedText> texts) {
return texts.filter(f -> !f.getLocalePreferred()).findFirst();
}
public static String notFound(Class<? extends MetadataResource> cls, StringType url, StringType version) {
return String.format("Resource of type %s with URL %s%s is not known",
cls.getSimpleName(),
url,
isValid(version) ? " and version "+version : "");
}
public static String notFound(Class<? extends MetadataResource> cls, StringType owner, StringType id, StringType version) {
return String.format("Resource of type %s with owner %s and ID %s/%s is not known",
cls.getSimpleName(),
getOwner(owner.getValue()),
id,
isValid(version) ? VERSION + "/" + version : "");
}
public static boolean isVersionAll(StringType version) {
return isValid(version) && version.getValue().equals("*");
}
public static ResponseEntity<String> badRequest() {
return ResponseEntity.badRequest().body("{\"exception\":\"Could not process the request.\"}");
}
public static ResponseEntity<String> notFound(int status, String body) {
return ResponseEntity.status(status).body(body);
}
}