repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/PositConnectProperties.java
src/main/java/org/ohdsi/webapi/shiny/posit/PositConnectProperties.java
package org.ohdsi.webapi.shiny.posit; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "shiny.connect") public class PositConnectProperties { @Value("${shiny.connect.api.key}") private String apiKey; private String url; @Value("${shiny.connect.okhttp.timeout.seconds}") private Integer timeoutSeconds; public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getTimeoutSeconds() { return timeoutSeconds; } public void setTimeoutSeconds(Integer timeoutSeconds) { this.timeoutSeconds = timeoutSeconds; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/PositConnectClientException.java
src/main/java/org/ohdsi/webapi/shiny/posit/PositConnectClientException.java
package org.ohdsi.webapi.shiny.posit; public class PositConnectClientException extends RuntimeException { public PositConnectClientException(String message) { super(message); } public PositConnectClientException(String message, Throwable cause) { super(message, cause); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/PositConnectClient.java
src/main/java/org/ohdsi/webapi/shiny/posit/PositConnectClient.java
package org.ohdsi.webapi.shiny.posit; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.apache.commons.lang3.StringUtils; import org.ohdsi.webapi.service.ShinyService; import org.ohdsi.webapi.shiny.ApplicationBrief; import org.ohdsi.webapi.shiny.ConflictPositConnectException; import org.ohdsi.webapi.shiny.TemporaryFile; import org.ohdsi.webapi.shiny.posit.dto.AddTagRequest; import org.ohdsi.webapi.shiny.posit.dto.BundleDeploymentResponse; import org.ohdsi.webapi.shiny.posit.dto.BundleRequest; import org.ohdsi.webapi.shiny.posit.dto.BundleResponse; import org.ohdsi.webapi.shiny.posit.dto.ContentItem; import org.ohdsi.webapi.shiny.posit.dto.ContentItemResponse; import org.ohdsi.webapi.shiny.posit.dto.TagMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Service; import java.io.IOException; import java.lang.reflect.Type; import java.text.MessageFormat; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; @Service @ConditionalOnBean(ShinyService.class) @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) public class PositConnectClient implements InitializingBean { private static final Logger log = LoggerFactory.getLogger(PositConnectClient.class); private static final int BODY_BYTE_COUNT_TO_LOG = 10_000; private static final MediaType JSON_TYPE = MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE); private static final MediaType OCTET_STREAM_TYPE = MediaType.parse(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE); private static final String HEADER_AUTH = "Authorization"; private static final String AUTH_PREFIX = "Key"; private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); @Autowired(required = false) private PositConnectProperties properties; public UUID createContentItem(ApplicationBrief brief) { ContentItem contentItem = new ContentItem(); contentItem.setAccessType("acl"); contentItem.setName(brief.getName()); contentItem.setTitle(brief.getTitle()); contentItem.setDescription(brief.getDescription()); RequestBody body = RequestBody.create(toJson(contentItem), JSON_TYPE); String url = connect("/v1/content"); ContentItemResponse response = doPost(ContentItemResponse.class, url, body); return response.getGuid(); } public List<ContentItemResponse> listContentItems() { String url = connect("/v1/content"); Request.Builder request = new Request.Builder() .url(url); return doCall(new TypeReference<List<ContentItemResponse>>() { }, request, url); } public List<TagMetadata> listTags() { String url = connect("/v1/tags"); Request.Builder request = new Request.Builder() .url(url); return doCall(new TypeReference<List<TagMetadata>>() { }, request, url); } public void addTagToContent(UUID contentId, AddTagRequest addTagRequest) { String url = connect(MessageFormat.format("/v1/content/{0}/tags", contentId)); RequestBody requestBody = RequestBody.create(toJson(addTagRequest), JSON_TYPE); doPost(Void.class, url, requestBody); } public String uploadBundle(UUID contentId, TemporaryFile bundle) { String url = connect(MessageFormat.format("/v1/content/{0}/bundles", contentId)); BundleResponse response = doPost(BundleResponse.class, url, RequestBody.create(bundle.getFile().toFile(), OCTET_STREAM_TYPE)); return response.getId(); } public String deployBundle(UUID contentId, String bundleId) { String url = connect(MessageFormat.format("/v1/content/{0}/deploy", contentId)); BundleRequest request = new BundleRequest(); request.setBundleId(bundleId); RequestBody requestBody = RequestBody.create(toJson(request), JSON_TYPE); BundleDeploymentResponse response = doPost(BundleDeploymentResponse.class, url, requestBody); return response.getTaskId(); } private <T> T doPost(Class<T> responseClass, String url, RequestBody requestBody) { Request.Builder request = new Request.Builder() .url(url) .post(requestBody); return doCall(responseClass, request, url); } private <T> T doCall(Class<T> responseClass, Request.Builder request, String url) { return doCall(new TypeReference<T>() { @Override public Type getType() { return responseClass; } }, request, url); } private <T> T doCall(TypeReference<T> responseClass, Request.Builder request, String url) { Call call = call(request, properties.getApiKey()); try (Response response = call.execute()) { if (!response.isSuccessful()) { log.error("Request [{}] returned code: [{}], message: [{}], bodyPart: [{}]", url, response.code(), response.message(), response.body() != null ? response.peekBody(BODY_BYTE_COUNT_TO_LOG).string() : ""); String message = MessageFormat.format("Request [{0}] returned code: [{1}], message: [{2}]", url, response.code(), response.message()); if (response.code() == 409) { throw new ConflictPositConnectException(message); } throw new PositConnectClientException(message); } if (responseClass.getType() == Void.class) { return null; } if (response.body() == null) { log.error("Failed to create a content, an empty result returned [{}]", url); throw new PositConnectClientException("Failed to create a content, an empty result returned"); } return objectMapper.readValue(response.body().charStream(), responseClass); } catch (IOException e) { log.error("Failed to execute call [{}]", url, e); throw new PositConnectClientException(MessageFormat.format("Failed to execute call [{0}]: {1}", url, e.getMessage())); } } private <T> String toJson(T value) { try { return objectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { log.error("Failed to execute Connect request", e); throw new PositConnectClientException("Failed to execute Connect request", e); } } private Call call(Request.Builder request, String token) { OkHttpClient client = new OkHttpClient.Builder() .retryOnConnectionFailure(false) .connectTimeout(properties.getTimeoutSeconds(), TimeUnit.SECONDS) .readTimeout(properties.getTimeoutSeconds(), TimeUnit.SECONDS) .writeTimeout(properties.getTimeoutSeconds(), TimeUnit.SECONDS) .build(); return client.newCall(request.header(HEADER_AUTH, AUTH_PREFIX + " " + token).build()); } @Override public void afterPropertiesSet() throws Exception { if (properties != null) { if (StringUtils.isBlank(properties.getApiKey())) { log.error("Set Posit Connect API Key to property \"shiny.connect.api.key\""); throw new BeanInitializationException("Set Posit Connect API Key to property \"shiny.connect.api.key\""); } if (StringUtils.isBlank(properties.getUrl())) { log.error("Set Posit Connect URL to property \"shiny.connect.url\""); throw new BeanInitializationException("Set Posit Connect URL to property \"shiny.connect.url\""); } if (Objects.isNull(properties.getTimeoutSeconds())) { log.error("Set Posit Connect HTTP Connect/Read/Write Timeout to property \"shiny.connect.okhttp.timeout.seconds\""); throw new BeanInitializationException("Set Posit Connect HTTP Connect/Read/Write Timeout to property \"shiny.connect.okhttp.timeout.seconds\""); } } } private String connect(String path) { return StringUtils.removeEnd(properties.getUrl(), "/") + "/__api__/" + StringUtils.removeStart(path, "/"); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/TagMapper.java
src/main/java/org/ohdsi/webapi/shiny/posit/TagMapper.java
package org.ohdsi.webapi.shiny.posit; import com.odysseusinc.arachne.commons.api.v1.dto.CommonAnalysisType; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Service public class TagMapper { @Value("${shiny.tag.name.analysis.cohort:Atlas Cohort}") private String cohortAnalysisTagName; @Value("${shiny.tag.name.analysis.cohort-characterizations:Atlas Cohort Characterization}") private String cohortCharacterizationsAnalysisTagName; @Value("${shiny.tag.name.analysis.cohort-pathways:Atlas Cohort Pathways}") private String cohortPathwaysAnalysisTagName; @Value("${shiny.tag.name.analysis.incidence-rates:Atlas Incidence Rate Analysis}") private String incidenceRatesAnalysisTagName; public String getPositTagNameForAnalysisType(CommonAnalysisType analysisType) { if (analysisType == CommonAnalysisType.COHORT) { return cohortAnalysisTagName; } else if (analysisType == CommonAnalysisType.COHORT_CHARACTERIZATION) { return cohortCharacterizationsAnalysisTagName; } else if (analysisType == CommonAnalysisType.COHORT_PATHWAY) { return cohortPathwaysAnalysisTagName; } else if (analysisType == CommonAnalysisType.INCIDENCE) { return incidenceRatesAnalysisTagName; } else { throw new UnsupportedOperationException("Unsupported analysis mapping requested: " + analysisType.getTitle()); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/dto/AddTagRequest.java
src/main/java/org/ohdsi/webapi/shiny/posit/dto/AddTagRequest.java
package org.ohdsi.webapi.shiny.posit.dto; import com.fasterxml.jackson.annotation.JsonProperty; public class AddTagRequest { @JsonProperty("tag_id") private String tagId; public AddTagRequest(String tagId) { this.tagId = tagId; } public String getTagId() { return tagId; } public void setTagId(String tagId) { this.tagId = tagId; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/dto/BundleDeploymentResponse.java
src/main/java/org/ohdsi/webapi/shiny/posit/dto/BundleDeploymentResponse.java
package org.ohdsi.webapi.shiny.posit.dto; import com.fasterxml.jackson.annotation.JsonProperty; public class BundleDeploymentResponse { @JsonProperty("task_id") private String taskId; public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/dto/TagMetadata.java
src/main/java/org/ohdsi/webapi/shiny/posit/dto/TagMetadata.java
package org.ohdsi.webapi.shiny.posit.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class TagMetadata { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/dto/ContentItem.java
src/main/java/org/ohdsi/webapi/shiny/posit/dto/ContentItem.java
package org.ohdsi.webapi.shiny.posit.dto; import com.fasterxml.jackson.annotation.JsonProperty; public class ContentItem { private String name; private String title; private String description; @JsonProperty("access_type") private String accessType; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAccessType() { return accessType; } public void setAccessType(String accessType) { this.accessType = accessType; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/dto/BundleRequest.java
src/main/java/org/ohdsi/webapi/shiny/posit/dto/BundleRequest.java
package org.ohdsi.webapi.shiny.posit.dto; import com.fasterxml.jackson.annotation.JsonProperty; public class BundleRequest { @JsonProperty("bundle_id") private String bundleId; public String getBundleId() { return bundleId; } public void setBundleId(String bundleId) { this.bundleId = bundleId; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/dto/BundleResponse.java
src/main/java/org/ohdsi/webapi/shiny/posit/dto/BundleResponse.java
package org.ohdsi.webapi.shiny.posit.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.Instant; @JsonIgnoreProperties(ignoreUnknown = true) public class BundleResponse { private String id; @JsonProperty("content_guid") private String contentGuid; @JsonProperty("created_time") private Instant createdTime; @JsonProperty("cluster_name") private String clusterName; @JsonProperty("image_name") private String imageName; @JsonProperty("r_version") private String rVersion; @JsonProperty("r_environment_management") private Boolean rEnvironmentManagement; @JsonProperty("py_version") private String pyVersion; @JsonProperty("py_environment_management") private Boolean pyEnvironmentManagement; @JsonProperty("quarto_version") private String quartoVersion; private Boolean active; private Integer size; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getContentGuid() { return contentGuid; } public void setContentGuid(String contentGuid) { this.contentGuid = contentGuid; } public Instant getCreatedTime() { return createdTime; } public void setCreatedTime(Instant createdTime) { this.createdTime = createdTime; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public String getrVersion() { return rVersion; } public void setrVersion(String rVersion) { this.rVersion = rVersion; } public Boolean getrEnvironmentManagement() { return rEnvironmentManagement; } public void setrEnvironmentManagement(Boolean rEnvironmentManagement) { this.rEnvironmentManagement = rEnvironmentManagement; } public String getPyVersion() { return pyVersion; } public void setPyVersion(String pyVersion) { this.pyVersion = pyVersion; } public Boolean getPyEnvironmentManagement() { return pyEnvironmentManagement; } public void setPyEnvironmentManagement(Boolean pyEnvironmentManagement) { this.pyEnvironmentManagement = pyEnvironmentManagement; } public String getQuartoVersion() { return quartoVersion; } public void setQuartoVersion(String quartoVersion) { this.quartoVersion = quartoVersion; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/posit/dto/ContentItemResponse.java
src/main/java/org/ohdsi/webapi/shiny/posit/dto/ContentItemResponse.java
package org.ohdsi.webapi.shiny.posit.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; @JsonIgnoreProperties(ignoreUnknown = true) public class ContentItemResponse extends ContentItem { private UUID guid; @JsonProperty("owner_guid") private UUID ownerGuid; private String id; public UUID getGuid() { return guid; } public void setGuid(UUID guid) { this.guid = guid; } public UUID getOwnerGuid() { return ownerGuid; } public void setOwnerGuid(UUID ownerGuid) { this.ownerGuid = ownerGuid; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/summary/DataSourceSummary.java
src/main/java/org/ohdsi/webapi/shiny/summary/DataSourceSummary.java
package org.ohdsi.webapi.shiny.summary; public class DataSourceSummary { private String sourceName; private String numberOfPersons; private String female; private String male; private String ageAtFirstObservation; private String cumulativeObservation; private String continuousObservationCoverage; public void setSourceName(String sourceName) { this.sourceName = sourceName; } public void setNumberOfPersons(String numberOfPersons) { this.numberOfPersons = numberOfPersons; } public void setFemale(String female) { this.female = female; } public void setMale(String male) { this.male = male; } public void setAgeAtFirstObservation(String ageAtFirstObservation) { this.ageAtFirstObservation = ageAtFirstObservation; } public void setCumulativeObservation(String cumulativeObservation) { this.cumulativeObservation = cumulativeObservation; } public void setContinuousObservationCoverage(String continuousObservationCoverage) { this.continuousObservationCoverage = continuousObservationCoverage; } public String getSourceName() { return sourceName; } public String getNumberOfPersons() { return numberOfPersons; } public String getFemale() { return female; } public String getMale() { return male; } public String getAgeAtFirstObservation() { return ageAtFirstObservation; } public String getCumulativeObservation() { return cumulativeObservation; } public String getContinuousObservationCoverage() { return continuousObservationCoverage; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/shiny/summary/DataSourceSummaryConverter.java
src/main/java/org/ohdsi/webapi/shiny/summary/DataSourceSummaryConverter.java
package org.ohdsi.webapi.shiny.summary; import org.ohdsi.webapi.report.CDMAttribute; import org.ohdsi.webapi.report.CDMDashboard; import org.ohdsi.webapi.report.ConceptCountRecord; import org.ohdsi.webapi.report.ConceptDistributionRecord; import org.ohdsi.webapi.report.CumulativeObservationRecord; import org.ohdsi.webapi.report.MonthObservationRecord; import org.ohdsi.webapi.service.ShinyService; import org.ohdsi.webapi.shiny.ShinyConstants; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.stereotype.Service; import java.text.DecimalFormat; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @Service @ConditionalOnBean(ShinyService.class) public class DataSourceSummaryConverter { private double calculateVariance(List<Integer> values, double mean) { double variance = 0; for (double value : values) { variance += Math.pow(value - mean, 2); } return variance / values.size(); } public DataSourceSummary convert(CDMDashboard cdmDashboard) { DataSourceSummary dataSourceSummary = new DataSourceSummary(); if (cdmDashboard.getSummary() != null) { for (CDMAttribute attribute : cdmDashboard.getSummary()) { switch (attribute.getAttributeName()) { case "Source name": dataSourceSummary.setSourceName(attribute.getAttributeValue()); break; case "Number of persons": double number = Double.parseDouble(attribute.getAttributeValue()); String formattedNumber = new DecimalFormat("#,###.###M").format(number / 1_000_000); dataSourceSummary.setNumberOfPersons(formattedNumber); break; } } } if (cdmDashboard.getGender() != null) { long maleCount = 0; long femaleCount = 0; for (ConceptCountRecord record : cdmDashboard.getGender()) { if (record.getConceptName().equalsIgnoreCase("MALE")) { maleCount = record.getCountValue(); } else if (record.getConceptName().equalsIgnoreCase("FEMALE")) { femaleCount = record.getCountValue(); } } long totalGenderCount = maleCount + femaleCount; String malePercentage = String.format("%,.1f %%", 100 * (double) maleCount / totalGenderCount); String femalePercentage = String.format("%,.1f %%", 100 * (double) femaleCount / totalGenderCount); dataSourceSummary.setMale(String.format("%,d (%s)", maleCount, malePercentage)); dataSourceSummary.setFemale(String.format("%,d (%s)", femaleCount, femalePercentage)); } if (cdmDashboard.getAgeAtFirstObservation() != null) { List<Integer> ages = cdmDashboard.getAgeAtFirstObservation().stream() .map(ConceptDistributionRecord::getIntervalIndex) .collect(Collectors.toList()); double sum = ages.stream() .mapToInt(Integer::intValue) .sum(); double mean = sum / ages.size(); double variance = calculateVariance(ages, mean); int minYear = cdmDashboard.getAgeAtFirstObservation().stream() .min(Comparator.comparingInt(ConceptDistributionRecord::getIntervalIndex)) .orElse(new ConceptDistributionRecord()).getIntervalIndex(); int maxYear = cdmDashboard.getAgeAtFirstObservation().stream() .max(Comparator.comparingInt(ConceptDistributionRecord::getIntervalIndex)) .orElse(new ConceptDistributionRecord()).getIntervalIndex(); dataSourceSummary.setAgeAtFirstObservation(String.format("[%d - %d] (M = %.1f; SD = %.1f)", minYear, maxYear, mean, Math.sqrt(variance))); } if (cdmDashboard.getCumulativeObservation() != null) { List<Integer> observationLengths = cdmDashboard.getCumulativeObservation().stream() .map(CumulativeObservationRecord::getxLengthOfObservation) .collect(Collectors.toList()); double sum = observationLengths.stream().mapToInt(Integer::intValue).sum(); double mean = sum / observationLengths.size(); double variance = calculateVariance(observationLengths, mean); int minObs = cdmDashboard.getCumulativeObservation().stream() .min(Comparator.comparingInt(CumulativeObservationRecord::getxLengthOfObservation)) .orElse(new CumulativeObservationRecord()).getxLengthOfObservation(); int maxObs = cdmDashboard.getCumulativeObservation().stream() .max(Comparator.comparingInt(CumulativeObservationRecord::getxLengthOfObservation)) .orElse(new CumulativeObservationRecord()).getxLengthOfObservation(); dataSourceSummary.setCumulativeObservation(String.format("[%d - %d] (M = %.1f; SD = %.1f)", minObs, maxObs, mean, Math.sqrt(variance))); } if (cdmDashboard.getObservedByMonth() != null && !cdmDashboard.getObservedByMonth().isEmpty()) { MonthObservationRecord startRecord = cdmDashboard.getObservedByMonth().get(0); MonthObservationRecord endRecord = cdmDashboard.getObservedByMonth() .get(cdmDashboard.getObservedByMonth().size() - 1); dataSourceSummary.setContinuousObservationCoverage(String.format("Start: %02d/%02d, End: %02d/%02d", startRecord.getMonthYear() % 100, startRecord.getMonthYear() / 100, endRecord.getMonthYear() % 100, endRecord.getMonthYear() / 100)); } return dataSourceSummary; } public DataSourceSummary emptySummary(String dataSourceName) { DataSourceSummary dataSourceSummary = new DataSourceSummary(); dataSourceSummary.setSourceName(dataSourceName); dataSourceSummary.setFemale(ShinyConstants.VALUE_NOT_AVAILABLE.getValue()); dataSourceSummary.setMale(ShinyConstants.VALUE_NOT_AVAILABLE.getValue()); dataSourceSummary.setCumulativeObservation(ShinyConstants.VALUE_NOT_AVAILABLE.getValue()); dataSourceSummary.setAgeAtFirstObservation(ShinyConstants.VALUE_NOT_AVAILABLE.getValue()); dataSourceSummary.setContinuousObservationCoverage(ShinyConstants.VALUE_NOT_AVAILABLE.getValue()); dataSourceSummary.setNumberOfPersons(ShinyConstants.VALUE_NOT_AVAILABLE.getValue()); return dataSourceSummary; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/cyclops/specification/PriorImpl.java
src/main/java/org/ohdsi/webapi/cyclops/specification/PriorImpl.java
package org.ohdsi.webapi.cyclops.specification; import com.fasterxml.jackson.annotation.JsonIgnore; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; import org.ohdsi.analysis.cyclops.design.*; import org.ohdsi.webapi.RLangClassImpl; /** * * @author asena5 */ public class PriorImpl extends RLangClassImpl implements Prior { private PriorTypeEnum priorType = PriorTypeEnum.LAPLACE; private List<BigDecimal> variance = null; private List<Integer> exclude = null; private String graph = null; private List<String> neighborhood = null; private Boolean useCrossValidation = false; private Boolean forceIntercept = false; private String priorAttrClass = "cyclopsPrior"; /** * Specifies prior distribution. We specify all priors in terms of their * variance parameters. Similar fitting tools for regularized regression * often parameterize the Laplace distribution in terms of a rate * \&quot;lambda\&quot; per observation. See \&quot;glmnet\&quot;, for * example. variance &#x3D; 2 * / (nobs * lambda)^2 or lambda &#x3D; sqrt(2 * / variance) / nobs * * @return priorType * */ @Override public PriorTypeEnum getPriorType() { return priorType; } /** * * @param priorType */ @JsonIgnore public void setPriorType(PriorTypeEnum priorType) { this.priorType = priorType; } /** * prior distribution variance * * @return variance * */ @Override public List<BigDecimal> getVariance() { return variance; } /** * * @param variance */ public void setVariance(Object variance) { if (variance != null) { if (variance instanceof ArrayList) { this.variance = (ArrayList<BigDecimal>) variance; } else if (variance instanceof Integer) { if (this.variance == null) { this.variance = new ArrayList<>(); } this.variance.add(new BigDecimal((Integer) variance)); } else { throw new InputMismatchException("Expected ArrayList<BigDecimal> or Integer"); } } else { this.variance = null; } } /** * A vector of numbers or covariateId names to exclude from prior * * @return exclude * */ @Override public List<Integer> getExclude() { return exclude; } /** * * @param exclude */ public void setExclude(Object exclude) { if (exclude != null) { if (exclude instanceof ArrayList) { this.exclude = (ArrayList<Integer>) exclude; } else if (exclude instanceof Integer) { this.exclude = new ArrayList<>(Arrays.asList((Integer) exclude)); } else { throw new InputMismatchException("Expected ArrayList<String> or Integer"); } } else { this.exclude = null; } } /** * Child-to-parent mapping for a hierarchical prior * * @return graph * */ @Override public String getGraph() { return graph; } /** * * @param graph */ public void setGraph(String graph) { this.graph = graph; } /** * A list of first-order neighborhoods for a partially fused prior * * @return neighborhood * */ @Override public List<String> getNeighborhood() { return neighborhood; } /** * * @param neighborhood */ public void setNeighborhood(Object neighborhood) { if (neighborhood != null) { if (neighborhood instanceof ArrayList) { this.neighborhood = (ArrayList<String>) neighborhood; } else if (neighborhood instanceof String) { this.neighborhood = new ArrayList<>(Arrays.asList((String) neighborhood)); } else { throw new InputMismatchException("Expected ArrayList<String> or String"); } } else { this.neighborhood = null; } } /** * Perform cross-validation to determine prior variance. * * @return useCrossValidation * */ @Override public Boolean getUseCrossValidation() { return useCrossValidation; } /** * * @param useCrossValidation */ public void setUseCrossValidation(Boolean useCrossValidation) { this.useCrossValidation = useCrossValidation; } /** * Force intercept coefficient into prior * * @return forceIntercept * */ @Override public Boolean getForceIntercept() { return forceIntercept; } /** * * @param forceIntercept */ public void setForceIntercept(Boolean forceIntercept) { this.forceIntercept = forceIntercept; } /** * Get priorAttrClass * * @return priorAttrClass * */ @Override public String getAttrClass() { return priorAttrClass; } /** * * @param attrClass */ @Override public void setAttrClass(String attrClass) { this.priorAttrClass = attrClass; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/cyclops/specification/ControlImpl.java
src/main/java/org/ohdsi/webapi/cyclops/specification/ControlImpl.java
package org.ohdsi.webapi.cyclops.specification; import java.math.BigDecimal; import java.util.InputMismatchException; import org.ohdsi.analysis.cyclops.design.*; import org.ohdsi.webapi.RLangClassImpl; /** * * @author asena5 */ public class ControlImpl extends RLangClassImpl implements Control { private Integer maxIterations = 1000; private BigDecimal tolerance = BigDecimal.valueOf(.000001); private ConvergenceTypeEnum convergenceType = ConvergenceTypeEnum.GRADIENT; private CvTypeEnum cvType = CvTypeEnum.AUTO; private Integer fold = 10; private BigDecimal lowerLimit = BigDecimal.valueOf(0.01); private BigDecimal upperLimit = new BigDecimal(20); private Integer gridSteps = 10; private Integer cvRepetitions = 1; private Integer minCVData = 100; private NoiseLevelEnum noiseLevel = NoiseLevelEnum.SILENT; private Integer threads = 1; private Integer seed = null; private Boolean resetCoefficients = false; private BigDecimal startingVariance = new BigDecimal(-1); private Boolean useKKTSwindle = false; private Integer tuneSwindle = 10; private SelectorTypeEnum selectorType = SelectorTypeEnum.AUTO; private BigDecimal initialBound = new BigDecimal(2); private Integer maxBoundCount = 5; private Boolean autoSearch = true; private AlgorithmTypeEnum algorithm = AlgorithmTypeEnum.CCD; private String controlAttrClass = "cyclopsControl"; /** * maximum iterations of Cyclops to attempt before returning a * failed-to-converge error * * @return maxIterations * */ @Override public Integer getMaxIterations() { return maxIterations; } /** * * @param maxIterations */ public void setMaxIterations(Integer maxIterations) { this.maxIterations = maxIterations; } /** * maximum relative change in convergence criterion from successive * iterations to achieve convergence * * @return tolerance * */ @Override public BigDecimal getTolerance() { return tolerance; } /** * * @param tolerance */ public void setTolerance(BigDecimal tolerance) { this.tolerance = tolerance; } /** * name of convergence criterion to employ * * @return convergenceType * */ @Override public ConvergenceTypeEnum getConvergenceType() { return convergenceType; } /** * * @param convergenceType */ public void setConvergenceType(ConvergenceTypeEnum convergenceType) { this.convergenceType = convergenceType; } /** * name of cross validation search. Option \&quot;auto\&quot; selects an * auto-search following BBR. Option \&quot;grid\&quot; selects a * grid-search cross validation * * @return cvType * */ @Override public CvTypeEnum getCvType() { return cvType; } /** * * @param cvType */ public void setCvType(CvTypeEnum cvType) { this.cvType = cvType; } /** * Number of random folds to employ in cross validation * * @return fold * */ @Override public Integer getFold() { return fold; } /** * * @param fold */ public void setFold(Object fold) { if (fold != null) { if (fold instanceof Integer) { this.fold = (Integer) fold; } else if (fold instanceof BigDecimal) { this.fold = ((BigDecimal) fold).intValue(); } else { throw new InputMismatchException("Expected Integer or BigDecimal"); } } else { this.fold = null; } } /** * Lower prior variance limit for grid-search * * @return lowerLimit * */ @Override public BigDecimal getLowerLimit() { return lowerLimit; } /** * * @param lowerLimit */ public void setLowerLimit(BigDecimal lowerLimit) { this.lowerLimit = lowerLimit; } /** * Upper prior variance limit for grid-search * * @return upperLimit * */ @Override public BigDecimal getUpperLimit() { return upperLimit; } /** * * @param upperLimit */ public void setUpperLimit(BigDecimal upperLimit) { this.upperLimit = upperLimit; } /** * Number of steps in grid-search * * @return gridSteps * */ @Override public Integer getGridSteps() { return gridSteps; } /** * * @param gridSteps */ public void setGridSteps(Object gridSteps) { if (gridSteps != null) { if (gridSteps instanceof Integer) { this.gridSteps = (Integer) gridSteps; } else if (gridSteps instanceof BigDecimal) { this.gridSteps = ((BigDecimal) gridSteps).intValue(); } else { throw new InputMismatchException("Expected Integer or BigDecimal"); } } else { this.gridSteps = null; } } /* public void setGridSteps(BigDecimal gridSteps) { this.gridSteps = gridSteps.intValue(); } */ /** * Number of repetitions of X-fold cross validation * * @return cvRepetitions * */ @Override public Integer getCvRepetitions() { return cvRepetitions; } /** * * @param cvRepetitions */ public void setCvRepetitions(Object cvRepetitions) { if (cvRepetitions != null) { if (cvRepetitions instanceof Integer) { this.cvRepetitions = (Integer) cvRepetitions; } else if (cvRepetitions instanceof BigDecimal) { this.cvRepetitions = ((BigDecimal) cvRepetitions).intValue(); } else { throw new InputMismatchException("Expected Integer or BigDecimal"); } } else { this.cvRepetitions = null; } } /** * Minimum number of data for cross validation * * @return minCVData * */ @Override public Integer getMinCVData() { return minCVData; } /** * * @param minCVData */ public void setMinCVData(Object minCVData) { if (minCVData != null) { if (minCVData instanceof Integer) { this.minCVData = (Integer) minCVData; } else if (minCVData instanceof BigDecimal) { this.minCVData = ((BigDecimal) minCVData).intValue(); } else { throw new InputMismatchException("Expected Integer or BigDecimal"); } } else { this.minCVData = null; } } /** * level of Cyclops screen output (\&quot;silent\&quot;, * \&quot;quiet\&quot;, \&quot;noisy\&quot;) * * @return noiseLevel * */ @Override public NoiseLevelEnum getNoiseLevel() { return noiseLevel; } /** * * @param noiseLevel */ public void setNoiseLevel(NoiseLevelEnum noiseLevel) { this.noiseLevel = noiseLevel; } /** * Specify number of CPU threads to employ in cross-validation; default * &#x3D; 1 (auto &#x3D; -1) * * @return threads * */ @Override public Integer getThreads() { return threads; } /** * * @param threads */ public void setThreads(Object threads) { if (threads != null) { if (threads instanceof Integer) { this.threads = (Integer) threads; } else if (threads instanceof BigDecimal) { this.threads = ((BigDecimal) threads).intValue(); } else { throw new InputMismatchException("Expected Integer or BigDecimal"); } } else { this.threads = null; } } /** * Specify random number generator seed. A null value sets seed via * Sys.time. * * @return seed * */ @Override public Integer getSeed() { return seed; } /** * * @param seed */ public void setSeed(Object seed) { if (seed != null) { if (seed instanceof Integer) { this.seed = (Integer) seed; } else if (seed instanceof BigDecimal) { this.seed = ((BigDecimal) seed).intValue(); } else { throw new InputMismatchException("Expected Integer or BigDecimal"); } } else { this.seed = null; } } /** * Reset all coefficients to 0 between model fits under cross-validation * * @return resetCoefficients * */ @Override public Boolean getResetCoefficients() { return resetCoefficients; } /** * * @param resetCoefficients */ public void setResetCoefficients(Boolean resetCoefficients) { this.resetCoefficients = resetCoefficients; } /** * Starting variance for auto-search cross-validation; default &#x3D; -1 * (use estimate based on data) * * @return startingVariance * */ @Override public BigDecimal getStartingVariance() { return startingVariance; } /** * * @param startingVariance */ public void setStartingVariance(BigDecimal startingVariance) { this.startingVariance = startingVariance; } /** * Use the Karush-Kuhn-Tucker conditions to limit search * * @return useKKTSwindle * */ @Override public Boolean getUseKKTSwindle() { return useKKTSwindle; } /** * * @param useKKTSwindle */ public void setUseKKTSwindle(Boolean useKKTSwindle) { this.useKKTSwindle = useKKTSwindle; } /** * Size multiplier for active set * * @return tuneSwindle * */ @Override public Integer getTuneSwindle() { return tuneSwindle; } /** * * @param tuneSwindle */ public void setTuneSwindle(Integer tuneSwindle) { this.tuneSwindle = tuneSwindle; } /** * name of exchangeable sampling unit. Option \&quot;byPid\&quot; selects * entire strata. Option \&quot;byRow\&quot; selects single rows. If set to * \&quot;auto\&quot;, \&quot;byRow\&quot; will be used for all models * except conditional models where the average number of rows per stratum is * smaller than the number of strata. * * @return selectorType * */ @Override public SelectorTypeEnum getSelectorType() { return selectorType; } /** * * @param selectorType */ public void setSelectorType(SelectorTypeEnum selectorType) { this.selectorType = selectorType; } /** * * @param selectorType */ public void setSelectorType(String selectorType) { this.selectorType = SelectorTypeEnum.fromValue(selectorType); } /** * Starting trust-region size * * @return initialBound * */ @Override public BigDecimal getInitialBound() { return initialBound; } /** * * @param initialBound */ public void setInitialBound(BigDecimal initialBound) { this.initialBound = initialBound; } /** * Maximum number of tries to decrease initial trust-region size * * @return maxBoundCount * */ @Override public Integer getMaxBoundCount() { return maxBoundCount; } /** * * @param maxBoundCount */ public void setMaxBoundCount(Object maxBoundCount) { if (maxBoundCount != null) { if (maxBoundCount instanceof Integer) { this.maxBoundCount = (Integer) maxBoundCount; } else if (maxBoundCount instanceof BigDecimal) { this.maxBoundCount = ((BigDecimal) maxBoundCount).intValue(); } else { throw new InputMismatchException("Expected Integer or BigDecimal"); } } else { this.maxBoundCount = null; } } /** * The auto search setting * * @return autoSearch * */ @Override public Boolean getAutoSearch() { return autoSearch; } /** * * @param autoSearch */ public void setAutoSearch(Boolean autoSearch) { this.autoSearch = autoSearch; } /** * The algorithm setting * * @return algorithm * */ @Override public AlgorithmTypeEnum getAlgorithm() { return algorithm; } /** * * @param algorithm */ public void setAlgorithm(AlgorithmTypeEnum algorithm) { this.algorithm = algorithm; } /** * * @param algorithm */ public void setAlgorithm(String algorithm) { this.algorithm = AlgorithmTypeEnum.fromValue(algorithm); } /** * Get controlAttrClass * * @return controlAttrClass * */ @Override public String getAttrClass() { return controlAttrClass; } /** * * @param attrClass */ @Override public void setAttrClass(String attrClass) { this.controlAttrClass = attrClass; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheRepository.java
src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheRepository.java
package org.ohdsi.webapi.generationcache; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph; import com.cosium.spring.data.jpa.entity.graph.repository.EntityGraphJpaRepository; import org.ohdsi.webapi.source.Source; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.Date; import java.util.List; interface GenerationCacheRepository extends EntityGraphJpaRepository<GenerationCache, Integer> { GenerationCache findByTypeAndAndDesignHashAndSource(CacheableGenerationType type, Integer designHash, Source source, EntityGraph entityGraph); List<GenerationCache> findAllByCreatedDateBefore(Date date, EntityGraph entityGraph); List<GenerationCache> findAllBySourceSourceId(int source); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheServiceImpl.java
src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheServiceImpl.java
package org.ohdsi.webapi.generationcache; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraphUtils; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; @Service public class GenerationCacheServiceImpl implements GenerationCacheService { private static final Logger log = LoggerFactory.getLogger(GenerationCacheServiceImpl.class); private static final String NO_PROVIDER_ERROR = "There is no generation cache provider which supports %s"; private static final String CACHE_CREATED = "Cached results of {} with design hash = {}"; private static final String CACHE_INVALID = "Actual results checksum doesn't match the original checksum for cache with id={}. Invalidating cache"; private static final ConcurrentHashMap<CacheableTypeSource, Integer> maxRequestedResultIds = new ConcurrentHashMap<>(); private final List<GenerationCacheProvider> generationCacheProviderList; private final GenerationCacheRepository generationCacheRepository; private final SourceRepository sourceRepository; public GenerationCacheServiceImpl(List<GenerationCacheProvider> generationCacheProviderList, GenerationCacheRepository generationCacheRepository, SourceRepository sourceRepository) { this.generationCacheProviderList = generationCacheProviderList; this.generationCacheRepository = generationCacheRepository; this.sourceRepository = sourceRepository; } @Override public Integer getDesignHash(CacheableGenerationType type, String design) { return getProvider(type).getDesignHash(design); } @Override public GenerationCache getCacheOrEraseInvalid(CacheableGenerationType type, Integer designHash, Integer sourceId) { Source source = sourceRepository.findBySourceId(sourceId); GenerationCache generationCache = generationCacheRepository.findByTypeAndAndDesignHashAndSource(type, designHash, source, EntityGraphUtils.fromAttributePaths("source")); GenerationCacheProvider provider = getProvider(type); if (generationCache != null) { String checksum = provider.getResultsChecksum(generationCache.getSource(), generationCache.getDesignHash()); if (Objects.equals(generationCache.getResultChecksum(), checksum)) { return generationCache; } else { removeCache(generationCache.getType(), generationCache.getSource(), generationCache.getDesignHash()); log.info(CACHE_INVALID, generationCache.getId()); } } return null; } @Override public String getResultsSql(GenerationCache cache) { return getProvider(cache.getType()).getResultsSql(cache.getDesignHash()); } @Override public GenerationCache cacheResults(CacheableGenerationType type, Integer designHash, Integer sourceId) { Source source = sourceRepository.findBySourceId(sourceId); String checksum = getProvider(type).getResultsChecksum(source, designHash); GenerationCache generationCache = new GenerationCache(); generationCache.setType(type); generationCache.setDesignHash(designHash); generationCache.setSource(source); generationCache.setResultChecksum(checksum); generationCache.setCreatedDate(new Date()); generationCache = generationCacheRepository.saveAndFlush(generationCache); log.info(CACHE_CREATED, type, designHash); return generationCache; } @Override public void removeCache(CacheableGenerationType type, Source source, Integer designHash) { // Cleanup cached results getProvider(type).remove(source, designHash); // Cleanup cache record GenerationCache generationCache = generationCacheRepository.findByTypeAndAndDesignHashAndSource(type, designHash, source, EntityGraphUtils.fromAttributePaths("source")); if (generationCache != null) { generationCacheRepository.delete(generationCache); } } private GenerationCacheProvider getProvider(CacheableGenerationType type) { return generationCacheProviderList.stream() .filter(p -> p.supports(type)) .findFirst() .orElseThrow(() -> new RuntimeException(String.format(NO_PROVIDER_ERROR, type))); } private class CacheableTypeSource { private CacheableGenerationType type; private Integer sourceId; public CacheableTypeSource(CacheableGenerationType type, Integer sourceId) { this.type = type; this.sourceId = sourceId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheableTypeSource that = (CacheableTypeSource) o; return type == that.type && Objects.equals(sourceId, that.sourceId); } @Override public int hashCode() { return Objects.hash(type, sourceId); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheService.java
src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheService.java
package org.ohdsi.webapi.generationcache; import org.ohdsi.webapi.source.Source; public interface GenerationCacheService { Integer getDesignHash(CacheableGenerationType type, String design); GenerationCache getCacheOrEraseInvalid(CacheableGenerationType type, Integer designHash, Integer sourceId); String getResultsSql(GenerationCache cache); GenerationCache cacheResults(CacheableGenerationType type, Integer designHash, Integer sourceId); void removeCache(CacheableGenerationType type, Source source, Integer designHash); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheProvider.java
src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheProvider.java
package org.ohdsi.webapi.generationcache; import org.ohdsi.webapi.source.Source; public interface GenerationCacheProvider { boolean supports(CacheableGenerationType type); Integer getDesignHash(String design); String getResultsChecksum(Source source, Integer designHash); String getResultsSql(Integer designHash); void remove(Source source, Integer designHash); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/GenerationCache.java
src/main/java/org/ohdsi/webapi/generationcache/GenerationCache.java
package org.ohdsi.webapi.generationcache; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.ohdsi.webapi.source.Source; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.util.Date; @Entity @Table(name="generation_cache") public class GenerationCache { @Id @Column(name = "id") @GenericGenerator( name = "generation_cache_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "generation_cache_sequence"), @Parameter(name = "initial_value", value = "1"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "generation_cache_generator") private Integer id; @Column(name = "type") @Enumerated(EnumType.STRING) private CacheableGenerationType type; @Column(name = "design_hash") private Integer designHash; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "source_id") private Source source; @Column(name = "result_checksum") private String resultChecksum; @Column(name = "created_date") private Date createdDate = new Date(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public CacheableGenerationType getType() { return type; } public void setType(CacheableGenerationType type) { this.type = type; } public Integer getDesignHash() { return designHash; } public void setDesignHash(Integer designHash) { this.designHash = designHash; } public Source getSource() { return source; } public void setSource(Source source) { this.source = source; } public String getResultChecksum() { return resultChecksum; } public void setResultChecksum(String resultChecksum) { this.resultChecksum = resultChecksum; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/SourceDeleteListenerConfigurer.java
src/main/java/org/ohdsi/webapi/generationcache/SourceDeleteListenerConfigurer.java
package org.ohdsi.webapi.generationcache; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PreDeleteEventListener; import org.hibernate.internal.SessionFactoryImpl; import org.ohdsi.webapi.source.Source; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.SimpleAsyncTaskExecutor; import javax.annotation.PostConstruct; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import java.util.List; import java.util.concurrent.Future; @Configuration public class SourceDeleteListenerConfigurer { @PersistenceUnit private EntityManagerFactory emf; private final GenerationCacheService generationCacheService; private final GenerationCacheRepository generationCacheRepository; public SourceDeleteListenerConfigurer(GenerationCacheService generationCacheService, GenerationCacheRepository generationCacheRepository) { this.generationCacheService = generationCacheService; this.generationCacheRepository = generationCacheRepository; } @PostConstruct protected void init() { SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class); EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class); registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener((PreDeleteEventListener) event -> { if (event.getEntity() instanceof Source) { Source source = (Source) event.getEntity(); Future future = new SimpleAsyncTaskExecutor().submit(() -> clearSourceRelatedCaches(source)); try { future.get(); } catch (Exception ex) { throw new RuntimeException(ex); } } return false; }); } private void clearSourceRelatedCaches(Source source) { List<GenerationCache> caches = generationCacheRepository.findAllBySourceSourceId(source.getSourceId()); caches.forEach(gc -> generationCacheService.removeCache(gc.getType(), source, gc.getDesignHash())); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/CohortGenerationCacheProvider.java
src/main/java/org/ohdsi/webapi/generationcache/CohortGenerationCacheProvider.java
package org.ohdsi.webapi.generationcache; import org.ohdsi.analysis.Utils; import org.ohdsi.circe.cohortdefinition.CohortExpression; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.SqlRender; import org.ohdsi.sql.SqlSplit; import org.ohdsi.sql.SqlTranslate; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionDetails; import org.ohdsi.webapi.service.AbstractDaoService; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.ohdsi.webapi.util.SessionUtils; import org.ohdsi.webapi.util.SourceUtils; import org.ohdsi.webapi.util.StatementCancel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Objects; import static org.ohdsi.webapi.Constants.Params.DESIGN_HASH; import static org.ohdsi.webapi.Constants.Params.RESULTS_DATABASE_SCHEMA; @Component public class CohortGenerationCacheProvider extends AbstractDaoService implements GenerationCacheProvider { private static final Logger log = LoggerFactory.getLogger(CohortGenerationCacheProvider.class); private static final String CACHE_VALIDATION_TIME = "Checksum of Generation cache for designHash = {} has been calculated in {} milliseconds"; private static final String COHORT_CHECKSUM_SQL_PATH = "/resources/generationcache/cohort/resultsChecksum.sql"; private static final String COHORT_RESULTS_SQL = ResourceHelper.GetResourceAsString("/resources/generationcache/cohort/results.sql"); private static final String CLEANUP_SQL = ResourceHelper.GetResourceAsString("/resources/generationcache/cohort/cleanup.sql"); @Override public boolean supports(CacheableGenerationType type) { return Objects.equals(type, CacheableGenerationType.COHORT); } @Override public Integer getDesignHash(String design) { // remove elements from object that do not determine results output (names, descriptions, etc) CohortExpression cleanExpression = CohortExpression.fromJson(design); cleanExpression.title=null; cleanExpression.inclusionRules.forEach((rule) -> { rule.name = null; rule.description = null; }); CohortDefinitionDetails cohortDetails = new CohortDefinitionDetails(); cohortDetails.setExpression(Utils.serialize(cleanExpression)); return cohortDetails.calculateHashCode(); } @Override public String getResultsChecksum(Source source, Integer designHash) { long startTime = System.currentTimeMillis(); PreparedStatementRenderer psr = new PreparedStatementRenderer( source, COHORT_CHECKSUM_SQL_PATH, "@" + RESULTS_DATABASE_SCHEMA, SourceUtils.getResultsQualifier(source), DESIGN_HASH, designHash, SessionUtils.sessionId() ); String checksum = getSourceJdbcTemplate(source).queryForObject(psr.getSql(), psr.getOrderedParams(), String.class); log.info(CACHE_VALIDATION_TIME, designHash, System.currentTimeMillis() - startTime); return checksum; } @Override public String getResultsSql(Integer designHash) { return SqlRender.renderSql( COHORT_RESULTS_SQL, new String[]{DESIGN_HASH}, new String[]{designHash.toString()} ); } @Override public void remove(Source source, Integer designHash) { String sql = SqlRender.renderSql( CLEANUP_SQL, new String[]{RESULTS_DATABASE_SCHEMA, DESIGN_HASH}, new String[]{SourceUtils.getResultsQualifier(source), designHash.toString()} ); sql = SqlTranslate.translateSql(sql, source.getSourceDialect()); try { // StatementCancel parameter is needed for calling batchUpdate of CancelableJdbcTemplate class // Without StatementCancel parameter JdbcTemplate.batchUpdate will be used. // JdbcTemplate incorrectly determines the support of batch update for impala datasource getSourceJdbcTemplate(source).batchUpdate(new StatementCancel(), SqlSplit.splitSql(sql)); } catch (final Exception e) { // if source is unavailable it throws exception that prevents source from being deleted. // ignore exception and proceed with deletion. log.warn("Cannot remove generation caches from source {}", source.getSourceId()); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheHelper.java
src/main/java/org/ohdsi/webapi/generationcache/GenerationCacheHelper.java
package org.ohdsi.webapi.generationcache; import org.ohdsi.sql.SqlRender; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; import org.ohdsi.webapi.cohortdefinition.CohortGenerationRequest; import org.ohdsi.webapi.cohortdefinition.CohortGenerationRequestBuilder; import org.ohdsi.webapi.cohortdefinition.CohortGenerationUtils; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.util.CancelableJdbcTemplate; import org.ohdsi.webapi.util.SourceUtils; import org.ohdsi.webapi.util.StatementCancel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import org.springframework.transaction.support.TransactionTemplate; import static org.ohdsi.webapi.Constants.Params.RESULTS_DATABASE_SCHEMA; @Component public class GenerationCacheHelper { private static final Logger log = LoggerFactory.getLogger(GenerationCacheHelper.class); private static final String CACHE_USED = "Using cached generation results for %s with id=%s and source=%s"; private static final ConcurrentHashMap<CacheableResource, Object> monitors = new ConcurrentHashMap<>(); private final TransactionTemplate transactionTemplateRequiresNew; private final GenerationCacheService generationCacheService; public GenerationCacheHelper(GenerationCacheService generationCacheService, TransactionTemplate transactionTemplateRequiresNew) { this.generationCacheService = generationCacheService; this.transactionTemplateRequiresNew = transactionTemplateRequiresNew; } public Integer computeHash(String expression) { return generationCacheService.getDesignHash(CacheableGenerationType.COHORT, expression); } public CacheResult computeCacheIfAbsent(CohortDefinition cohortDefinition, Source source, CohortGenerationRequestBuilder requestBuilder, BiConsumer<Integer, String[]> sqlExecutor) { CacheableGenerationType type = CacheableGenerationType.COHORT; Integer designHash = computeHash(cohortDefinition.getDetails().getExpression()); log.info("Computes cache if absent for type = {}, design = {}, source id = {}", type, designHash.toString(), source.getSourceId()); synchronized (monitors.computeIfAbsent(new CacheableResource(type, designHash, source.getSourceId()), cr -> new Object())) { // we execute the synchronized block in a separate transaction to make the cache changes visible immediately to all other threads return transactionTemplateRequiresNew.execute(s -> { log.info("Retrieves or invalidates cache for cohort id = {}", cohortDefinition.getId()); GenerationCache cache = generationCacheService.getCacheOrEraseInvalid(type, designHash, source.getSourceId()); if (cache == null) { log.info("Cache is absent for cohort id = {}. Calculating with design hash = {}", cohortDefinition.getId(), designHash); // Ensure that there are no records in results schema with which we could mess up generationCacheService.removeCache(type, source, designHash); CohortGenerationRequest cohortGenerationRequest = requestBuilder .withExpression(cohortDefinition.getDetails().getExpressionObject()) .withSource(source) .withTargetId(designHash) .build(); String[] sqls = CohortGenerationUtils.buildGenerationSql(cohortGenerationRequest); sqlExecutor.accept(designHash, sqls); cache = generationCacheService.cacheResults(CacheableGenerationType.COHORT, designHash, source.getSourceId()); } else { log.info(String.format(CACHE_USED, type, cohortDefinition.getId(), source.getSourceKey())); } String sql = SqlRender.renderSql( generationCacheService.getResultsSql(cache), new String[]{RESULTS_DATABASE_SCHEMA}, new String[]{SourceUtils.getResultsQualifier(source)} ); log.info("Finished computation cache if absent for cohort id = {}", cohortDefinition.getId()); return new CacheResult(cache.getDesignHash(), sql); }); } } public void runCancelableCohortGeneration(CancelableJdbcTemplate cancelableJdbcTemplate, StatementCancel stmtCancel, String sqls[]) { cancelableJdbcTemplate.batchUpdate(stmtCancel, sqls); // Ensure that no cache created if generation has been cancelled if (stmtCancel.isCanceled()) { throw new RuntimeException("Cohort generation has been cancelled"); } } public class CacheResult { private Integer identifier; private String sql; public CacheResult(Integer identifier, String sql) { this.identifier = identifier; this.sql = sql; } public Integer getIdentifier() { return identifier; } public String getSql() { return sql; } } private static class CacheableResource { private CacheableGenerationType type; private Integer designHash; private Integer sourceId; public CacheableResource(CacheableGenerationType type, Integer designHash, Integer sourceId) { this.type = type; this.designHash = designHash; this.sourceId = sourceId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheableResource that = (CacheableResource) o; return type == that.type && Objects.equals(designHash, that.designHash) && Objects.equals(sourceId, that.sourceId); } @Override public int hashCode() { return Objects.hash(type, designHash, sourceId); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/CacheableGenerationType.java
src/main/java/org/ohdsi/webapi/generationcache/CacheableGenerationType.java
package org.ohdsi.webapi.generationcache; public enum CacheableGenerationType { COHORT }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/generationcache/CleanupScheduler.java
src/main/java/org/ohdsi/webapi/generationcache/CleanupScheduler.java
package org.ohdsi.webapi.generationcache; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraphUtils; import org.apache.commons.lang3.time.DateUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; @Component public class CleanupScheduler { private final GenerationCacheService generationCacheService; private final GenerationCacheRepository generationCacheRepository; @Value("${cache.generation.invalidAfterDays}") private Integer invalidateAfterDays; public CleanupScheduler(GenerationCacheService generationCacheService, GenerationCacheRepository generationCacheRepository) { this.generationCacheService = generationCacheService; this.generationCacheRepository = generationCacheRepository; } @Scheduled(fixedDelayString = "${cache.generation.cleanupInterval}") public void removeOldCache() { List<GenerationCache> caches = generationCacheRepository.findAllByCreatedDateBefore( DateUtils.addDays(new Date(), -1 * invalidateAfterDays), EntityGraphUtils.fromAttributePaths("source", "source.daimons") ); caches.forEach(gc -> generationCacheService.removeCache(gc.getType(), gc.getSource(), gc.getDesignHash())); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/PathwayController.java
src/main/java/org/ohdsi/webapi/pathway/PathwayController.java
package org.ohdsi.webapi.pathway; import com.odysseusinc.arachne.commons.utils.ConverterUtils; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.Pagination; import org.ohdsi.webapi.check.CheckResult; import org.ohdsi.webapi.check.checker.pathway.PathwayChecker; import org.ohdsi.webapi.common.SourceMapKey; import org.ohdsi.webapi.common.generation.CommonGenerationDTO; import org.ohdsi.webapi.common.sensitiveinfo.CommonGenerationSensitiveInfoService; import org.ohdsi.webapi.i18n.I18nService; import org.ohdsi.webapi.job.JobExecutionResource; import org.ohdsi.webapi.pathway.converter.SerializedPathwayAnalysisToPathwayAnalysisConverter; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisGenerationEntity; import org.ohdsi.webapi.pathway.dto.*; import org.ohdsi.webapi.pathway.dto.internal.PathwayAnalysisResult; import org.ohdsi.webapi.security.PermissionService; import org.ohdsi.webapi.source.SourceService; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.tag.TagService; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.ohdsi.webapi.util.ExportUtil; import org.ohdsi.webapi.util.ExceptionUtils; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import javax.transaction.Transactional; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @Path("/pathway-analysis") @Controller public class PathwayController { private ConversionService conversionService; private ConverterUtils converterUtils; private PathwayService pathwayService; private final SourceService sourceService; private final CommonGenerationSensitiveInfoService<CommonGenerationDTO> sensitiveInfoService; private final I18nService i18nService; private PathwayChecker checker; private PermissionService permissionService; @Autowired public PathwayController(ConversionService conversionService, ConverterUtils converterUtils, PathwayService pathwayService, SourceService sourceService, CommonGenerationSensitiveInfoService sensitiveInfoService, PathwayChecker checker, PermissionService permissionService, I18nService i18nService) { this.conversionService = conversionService; this.converterUtils = converterUtils; this.pathwayService = pathwayService; this.sourceService = sourceService; this.sensitiveInfoService = sensitiveInfoService; this.i18nService = i18nService; this.checker = checker; this.permissionService = permissionService; } /** * Create a new pathway analysis design. * * A pathway analysis consists of a set of target cohorts, event cohorts, and * analysis settings for collapsing and repeat events. * * By default, the new design will have the createdBy set to the authenticated * user, and the createdDate to the current time. * * @summary Create Pathway Analysis * @param dto the pathway analysis design * @return the created pathway analysis */ @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public PathwayAnalysisDTO create(final PathwayAnalysisDTO dto) { PathwayAnalysisEntity pathwayAnalysis = conversionService.convert(dto, PathwayAnalysisEntity.class); PathwayAnalysisEntity saved = pathwayService.create(pathwayAnalysis); return reloadAndConvert(saved.getId()); } /** * Creates a copy of a pathway analysis. * * The new pathway will be a copy of the specified pathway analysis id, but * won't contain any tag assignments. * * @summary Copy Pathway Analysis * @param id the analysis to copy * @return The copied pathway analysis. */ @POST @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @Transactional public PathwayAnalysisDTO copy(@PathParam("id") final Integer id) { PathwayAnalysisDTO dto = get(id); dto.setId(null); dto.setName(pathwayService.getNameForCopy(dto.getName())); dto.setTags(null); return create(dto); } /** * Import a pathway analysis * * The imported analysis contains the cohort definitions referenced by the * targets and event cohort paramaters. During import, any cohort definition * not found (by a hash check) will be inserted into the database as a new * cohort definition, and the cohort definition ids that are referenced will * be updated to reflect the new cohort definition ids. * * @param dto * @return */ @POST @Path("/import") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public PathwayAnalysisDTO importAnalysis(final PathwayAnalysisExportDTO dto) { dto.setTags(null); dto.setName(pathwayService.getNameWithSuffix(dto.getName())); PathwayAnalysisEntity pathwayAnalysis = conversionService.convert(dto, PathwayAnalysisEntity.class); PathwayAnalysisEntity imported = pathwayService.importAnalysis(pathwayAnalysis); return reloadAndConvert(imported.getId()); } /** * Get a page of pathway analysis designs for list * * From the selected page, a list of PathwayAnalysisDTOs are returned * containing summary information about the analysis (name, id, modified * dates, etc) * @param pageable indicates how many elements per page to * return, and which page to fetch * * @summary List Designs by Page * @return the list of pathway analysis DTOs. */ @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public Page<PathwayAnalysisDTO> list(@Pagination Pageable pageable) { return pathwayService.getPage(pageable).map(pa -> { PathwayAnalysisDTO dto = conversionService.convert(pa, PathwayAnalysisDTO.class); permissionService.fillWriteAccess(pa, dto); permissionService.fillReadAccess(pa, dto); return dto; }); } /** * Check that a pathway analysis name exists. * * This method checks to see if a pathway analysis name exists. The id * parameter is used to 'ignore' an analysis from checking. This is used when * you have an existing analysis which should be ignored when checking if the * name already exists. * * @Summary Check Pathway Analysis Name Name * @param id the pathway analysis id * @param name the name to check * @return a count of the number of pathway analysis designs with the same * name */ @GET @Path("/{id}/exists") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public int getCountPAWithSameName(@PathParam("id") @DefaultValue("0") final int id, @QueryParam("name") String name) { return pathwayService.getCountPAWithSameName(id, name); } /** * Updates a pathway analysis design. * * The modifiedDate and modifiedValues will be populated automatically. * * @summary Update Pathway Analysis Design * @param id the analysis to update * @param dto the pathway analysis design * @return the updated pathway analysis design. */ @PUT @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public PathwayAnalysisDTO update(@PathParam("id") final Integer id, @RequestBody final PathwayAnalysisDTO dto) { pathwayService.saveVersion(id); PathwayAnalysisEntity pathwayAnalysis = conversionService.convert(dto, PathwayAnalysisEntity.class); pathwayAnalysis.setId(id); pathwayService.update(pathwayAnalysis); return reloadAndConvert(id); } /** * Get the pathway analysis design. * * @summary Get Pathway Analysis Design * @param id the design id * @return a pathway analysis design for the given id */ @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public PathwayAnalysisDTO get(@PathParam("id") final Integer id) { PathwayAnalysisEntity pathwayAnalysis = pathwayService.getById(id); ExceptionUtils.throwNotFoundExceptionIfNull(pathwayAnalysis, String.format(i18nService.translate("pathways.manager.messages.notfound", "There is no pathway analysis with id = %d."), id)); Map<Integer, Integer> eventCodes = pathwayService.getEventCohortCodes(pathwayAnalysis); PathwayAnalysisDTO dto = conversionService.convert(pathwayAnalysis, PathwayAnalysisDTO.class); dto.getEventCohorts().forEach(ec -> ec.setCode(eventCodes.get(ec.getId()))); return dto; } /** * Export the pathway analysis deign as JSON * * @summary Export Pathway Analysis Design * @param id the design id to export * @return a String containing the pathway analysis design as JSON */ @GET @Path("/{id}/export") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public String export(@PathParam("id") final Integer id) { PathwayAnalysisEntity pathwayAnalysis = pathwayService.getById(id); ExportUtil.clearCreateAndUpdateInfo(pathwayAnalysis); return new SerializedPathwayAnalysisToPathwayAnalysisConverter().convertToDatabaseColumn(pathwayAnalysis); } /** * Generate pathway analysis sql * * This method generates the analysis sql for the given design id and * specified source. This means that the pathway design must be saved to the * database, and a valid source key is provided as the sourceKey parameter. * The result is a fully translated and populated query containing the schema * parameters and translation based on the specified source. * * @summary Generate Analysis Sql * @param id the pathway analysis design id * @param sourceKey the source used to find the schema and dialect * @return a String containing the analysis sql */ @GET @Path("/{id}/sql/{sourceKey}") @Produces(MediaType.APPLICATION_OCTET_STREAM) @Consumes(MediaType.APPLICATION_JSON) public String getAnalysisSql(@PathParam("id") final Integer id, @PathParam("sourceKey") final String sourceKey) { Source source = sourceService.findBySourceKey(sourceKey); return pathwayService.buildAnalysisSql(-1L, pathwayService.getById(id), source.getSourceId()); } /** * Delete a pathway analysis design. * * @summary Delete Pathway Analysis Design * @param id */ @DELETE @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public void delete(@PathParam("id") final Integer id) { pathwayService.delete(id); } /** * Generate pathway analysis. * * This method will execute the analysis sql on the specified source. * * @summary Generate Pathway Analysis * @param pathwayAnalysisId * @param sourceKey * @return a job execution reference */ @POST @Path("/{id}/generation/{sourceKey}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public JobExecutionResource generatePathways( @PathParam("id") final Integer pathwayAnalysisId, @PathParam("sourceKey") final String sourceKey ) { PathwayAnalysisEntity pathwayAnalysis = pathwayService.getById(pathwayAnalysisId); ExceptionUtils.throwNotFoundExceptionIfNull(pathwayAnalysis, String.format("There is no pathway analysis with id = %d.", pathwayAnalysisId)); PathwayAnalysisDTO pathwayAnalysisDTO = conversionService.convert(pathwayAnalysis, PathwayAnalysisDTO.class); CheckResult checkResult = runDiagnostics(pathwayAnalysisDTO); if (checkResult.hasCriticalErrors()) { throw new RuntimeException("Cannot be generated due to critical errors in design. Call 'check' service for further details"); } Source source = sourceService.findBySourceKey(sourceKey); return pathwayService.generatePathways(pathwayAnalysisId, source.getSourceId()); } /** * Cancel analysis execution. * * This method will signal the generation job to cancel on the given source * for the specified design. This cancellation is not immediate: the analysis * sql will stop after the current statement has finished execution. * * @summary Cancel Execution * @param pathwayAnalysisId the pathway analysis id * @param sourceKey the key of the source */ @DELETE @Path("/{id}/generation/{sourceKey}") public void cancelPathwaysGeneration( @PathParam("id") final Integer pathwayAnalysisId, @PathParam("sourceKey") final String sourceKey ) { Source source = sourceService.findBySourceKey(sourceKey); pathwayService.cancelGeneration(pathwayAnalysisId, source.getSourceId()); } /** * Returns a list of pathway analysis generation info objects. * * Pathway generation info objects refers to the information related to the * generation on a source. This includes information about the starting time, * duration, and execution status. This method returns the generation * information for any source the user has access to. * * @summary Get pathway generation info * @param pathwayAnalysisId the pathway analysis design id * @return the list of generation info objects for this design */ @GET @Path("/{id}/generation") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public List<CommonGenerationDTO> getPathwayGenerations( @PathParam("id") final Integer pathwayAnalysisId ) { Map<String, Source> sourcesMap = sourceService.getSourcesMap(SourceMapKey.BY_SOURCE_KEY); return sensitiveInfoService.filterSensitiveInfo(converterUtils.convertList(pathwayService.getPathwayGenerations(pathwayAnalysisId), CommonGenerationDTO.class), info -> Collections.singletonMap(Constants.Variables.SOURCE, sourcesMap.get(info.getSourceKey()))); } /** * Return a single generation info for the given generation id. * * @summary Get Generation Info * @param generationId * @return a CommonGenerationDTO for the given generation id */ @GET @Path("/generation/{generationId}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public CommonGenerationDTO getPathwayGenerations( @PathParam("generationId") final Long generationId ) { PathwayAnalysisGenerationEntity generationEntity = pathwayService.getGeneration(generationId); return sensitiveInfoService.filterSensitiveInfo(conversionService.convert(generationEntity, CommonGenerationDTO.class), Collections.singletonMap(Constants.Variables.SOURCE, generationEntity.getSource())); } /** * Get the pathway analysis design for the given generation id * * When a pathway analysis is generated, a snapshot of the design is stored, * and indexed by the hash of the design. This method allows you to fetch the * pathway design given a generation id. * * @summary Get Design for Generation * @param generationId the generation to fetch the design for * @return a JSON representation of the pathway analysis design. */ @GET @Path("/generation/{generationId}/design") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String getGenerationDesign( @PathParam("generationId") final Long generationId ) { return pathwayService.findDesignByGenerationId(generationId); } /** * Get the results for the given generation. * * @summary Get Result for Generation * @param generationId the generation id of the results * @return the pathway analysis results */ @GET @Path("/generation/{generationId}/result") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public PathwayPopulationResultsDTO getGenerationResults( @PathParam("generationId") final Long generationId ) { return pathwayService.getGenerationResults(generationId); } private PathwayAnalysisDTO reloadAndConvert(Integer id) { // Before conversion entity must be refreshed to apply entity graphs PathwayAnalysisEntity analysis = pathwayService.getById(id); return conversionService.convert(analysis, PathwayAnalysisDTO.class); } /** * Checks the pathway analysis for logic issues * * This method runs a series of logical checks on a pathway analysis and * returns the set of warning, info and error messages. * * @summary Check Pathway Analysis Design * @param pathwayAnalysisDTO the pathway analysis design to check * @return the set of checks (warnings, info and errors) */ @POST @Path("/check") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public CheckResult runDiagnostics(PathwayAnalysisDTO pathwayAnalysisDTO) { return new CheckResult(checker.check(pathwayAnalysisDTO)); } /** * Assign tag to Pathway Analysis * * @summary Assign Tag * @param id * @param tagId */ @POST @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/tag/") public void assignTag(@PathParam("id") final int id, final int tagId) { pathwayService.assignTag(id, tagId); } /** * Unassign tag from Pathway Analysis * * @summary Unassign Tag * @param id * @param tagId */ @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/tag/{tagId}") public void unassignTag(@PathParam("id") final int id, @PathParam("tagId") final int tagId) { pathwayService.unassignTag(id, tagId); } /** * Assign protected tag to Pathway Analysis * * @summary Assign Protected Tag * @param id * @param tagId */ @POST @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/protectedtag/") public void assignPermissionProtectedTag(@PathParam("id") final int id, final int tagId) { pathwayService.assignTag(id, tagId); } /** * Unassign protected tag from Pathway Analysis * * @summary Unassign Protected Tag * @param id * @param tagId */ @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/protectedtag/{tagId}") public void unassignPermissionProtectedTag(@PathParam("id") final int id, @PathParam("tagId") final int tagId) { pathwayService.unassignTag(id, tagId); } /** * Get list of versions of Pathway Analysis * * @summary Get Versions * @param id * @return */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/version/") public List<VersionDTO> getVersions(@PathParam("id") final long id) { return pathwayService.getVersions(id); } /** * Get specific version of Pathway Analysis * * @summary Get Version * @param id * @param version * @return */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/version/{version}") public PathwayVersionFullDTO getVersion(@PathParam("id") final int id, @PathParam("version") final int version) { return pathwayService.getVersion(id, version); } /** * Update version of Pathway Analysis * * @summary Update Version * @param id * @param version * @param updateDTO * @return */ @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/version/{version}") public VersionDTO updateVersion(@PathParam("id") final int id, @PathParam("version") final int version, VersionUpdateDTO updateDTO) { return pathwayService.updateVersion(id, version, updateDTO); } /** * Delete version of Pathway Analysis * * @summary Delete Version * @param id * @param version */ @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/version/{version}") public void deleteVersion(@PathParam("id") final int id, @PathParam("version") final int version) { pathwayService.deleteVersion(id, version); } /** * Create a new asset form version of Pathway Analysis * * @Create Asset From Version * @param id * @param version * @return */ @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/version/{version}/createAsset") public PathwayAnalysisDTO copyAssetFromVersion(@PathParam("id") final int id, @PathParam("version") final int version) { return pathwayService.copyAssetFromVersion(id, version); } /** * Get list of pathways with assigned tags * * @summary List By Tags * @param requestDTO * @return */ @POST @Path("/byTags") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public List<PathwayAnalysisDTO> listByTags(TagNameListRequestDTO requestDTO) { if (requestDTO == null || requestDTO.getNames() == null || requestDTO.getNames().isEmpty()) { return Collections.emptyList(); } return pathwayService.listByTags(requestDTO); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/GeneratePathwayAnalysisTasklet.java
src/main/java/org/ohdsi/webapi/pathway/GeneratePathwayAnalysisTasklet.java
package org.ohdsi.webapi.pathway; import org.ohdsi.sql.SqlSplit; import org.ohdsi.webapi.cohortcharacterization.repository.AnalysisGenerationInfoEntityRepository; import org.ohdsi.webapi.common.generation.AnalysisTasklet; import org.ohdsi.webapi.pathway.converter.SerializedPathwayAnalysisToPathwayAnalysisConverter; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.source.SourceService; import org.ohdsi.webapi.shiro.Entities.UserEntity; import org.ohdsi.webapi.shiro.Entities.UserRepository; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.util.CancelableJdbcTemplate; import org.ohdsi.webapi.util.SourceUtils; import org.slf4j.LoggerFactory; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.transaction.support.TransactionTemplate; import java.util.Map; import static org.ohdsi.webapi.Constants.Params.*; public class GeneratePathwayAnalysisTasklet extends AnalysisTasklet { private final PathwayService pathwayService; private final UserRepository userRepository; private final SourceService sourceService; public GeneratePathwayAnalysisTasklet( CancelableJdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate, PathwayService pathwayService, AnalysisGenerationInfoEntityRepository analysisGenerationInfoEntityRepository, UserRepository userRepository, SourceService sourceService ) { super(LoggerFactory.getLogger(GeneratePathwayAnalysisTasklet.class), jdbcTemplate, transactionTemplate, analysisGenerationInfoEntityRepository); this.pathwayService = pathwayService; this.userRepository = userRepository; this.sourceService = sourceService; } @Override protected String[] prepareQueries(ChunkContext chunkContext, CancelableJdbcTemplate jdbcTemplate) { Map<String, Object> jobParams = chunkContext.getStepContext().getJobParameters(); Integer sourceId = Integer.parseInt(jobParams.get(SOURCE_ID).toString()); Source source = sourceService.findBySourceId(sourceId); PathwayAnalysisEntity pathwayAnalysis = pathwayService.getById(Integer.parseInt(jobParams.get(PATHWAY_ANALYSIS_ID).toString())); Long jobId = chunkContext.getStepContext().getStepExecution().getJobExecution().getId(); UserEntity user = userRepository.findByLogin(jobParams.get(JOB_AUTHOR).toString()); String cohortTable = jobParams.get(TARGET_TABLE).toString(); String sessionId = jobParams.get(SESSION_ID).toString(); final String serializedDesign = new SerializedPathwayAnalysisToPathwayAnalysisConverter().convertToDatabaseColumn(pathwayAnalysis); saveInfoWithinTheSeparateTransaction(jobId, serializedDesign, user); String analysisSql = pathwayService.buildAnalysisSql(jobId, pathwayAnalysis, sourceId, SourceUtils.getTempQualifier(source) + "." + cohortTable, sessionId); return SqlSplit.splitSql(analysisSql); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/PathwayStatisticsTasklet.java
src/main/java/org/ohdsi/webapi/pathway/PathwayStatisticsTasklet.java
package org.ohdsi.webapi.pathway; import com.fasterxml.jackson.core.type.TypeReference; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import org.ohdsi.analysis.Utils; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.BigQuerySparkTranslate; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.ohdsi.webapi.pathway.dto.internal.PathwayCode; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.util.CancelableJdbcTemplate; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.slf4j.LoggerFactory; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.ohdsi.sql.SqlRender; import org.ohdsi.webapi.common.generation.CancelableTasklet; import org.ohdsi.webapi.util.PreparedStatementRendererCreator; import org.springframework.jdbc.core.PreparedStatementCreator; import static org.ohdsi.webapi.Constants.Params.GENERATION_ID; public class PathwayStatisticsTasklet extends CancelableTasklet { private static final String SAVE_PATHS_SQL = ResourceHelper.GetResourceAsString("/resources/pathway/savePaths.sql"); private final CancelableJdbcTemplate jdbcTemplate; private final Source source; private Long generationId; private final PathwayService pathwayService; private final GenericConversionService genericConversionService; public PathwayStatisticsTasklet(CancelableJdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate, Source source, PathwayService pathwayService, GenericConversionService genericConversionService) { super(LoggerFactory.getLogger(PathwayStatisticsTasklet.class), jdbcTemplate, transactionTemplate); this.jdbcTemplate = jdbcTemplate; this.source = source; this.pathwayService = pathwayService; this.genericConversionService = genericConversionService; } private List<Integer> intArrayToList(int[] intArray) { return Arrays.stream(intArray).boxed().collect(Collectors.toList()); } @Override protected void doBefore(ChunkContext chunkContext) { initTx(); generationId = chunkContext.getStepContext().getStepExecution().getJobExecution().getId(); } private void initTx() { DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition(); txDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus initStatus = this.transactionTemplate.getTransactionManager().getTransaction(txDefinition); this.transactionTemplate.getTransactionManager().commit(initStatus); } @Override protected int[] doTask(ChunkContext chunkContext) { Callable<int[]> execution; List<Integer> rowsUpdated = new ArrayList<>(); // stores the rows updated from each batch. // roll up patient-level events into pathway counts and save to DB. execution = () -> savePaths(source, generationId); FutureTask<int[]> savePathsTask = new FutureTask<>(execution); taskExecutor.execute(savePathsTask); rowsUpdated.addAll(intArrayToList(waitForFuture(savePathsTask))); if (isStopped()) { return null; } // build comboId -> combo name map final PathwayAnalysisEntity design = genericConversionService .convert(Utils.deserialize(pathwayService.findDesignByGenerationId(generationId), new TypeReference<PathwayAnalysisExportDTO>() { }), PathwayAnalysisEntity.class); List<PathwayCode> pathwayCodes = buildPathwayCodes(design, source); // save combo lookup to DB execution = () -> savePathwayCodes(pathwayCodes); FutureTask<int[]> saveCodesTask = new FutureTask<>(execution); taskExecutor.execute(saveCodesTask); rowsUpdated.addAll(intArrayToList(waitForFuture(saveCodesTask))); return rowsUpdated.stream().mapToInt(Integer::intValue).toArray(); } private List<PathwayCode> buildPathwayCodes(PathwayAnalysisEntity design, Source source) { PreparedStatementRenderer pathwayStatsPsr = new PreparedStatementRenderer( source, "/resources/pathway/getDistinctCodes.sql", "target_database_schema", source.getTableQualifier(SourceDaimon.DaimonType.Results), new String[]{GENERATION_ID}, new Object[]{generationId} ); Map<Integer, Integer> eventCodes = pathwayService.getEventCohortCodes(design); List<PathwayCode> codesFromDb = jdbcTemplate.query(pathwayStatsPsr.getSql(), pathwayStatsPsr.getSetter(), (rs, rowNum) -> { long code = rs.getLong("combo_id"); List<PathwayEventCohort> eventCohorts = getEventCohortsByComboCode(design, eventCodes, code); String names = eventCohorts.stream() .map(PathwayEventCohort::getName) .collect(Collectors.joining(",")); return new PathwayCode(code, names, eventCohorts.size() > 1); }); // need to add any event cohort code that wasn't found in the codes from DB // so that, in the case that only a combo was identified in the pathway analysis, // the event cohorts from the combo are included in the result. List<PathwayCode> codesFromDesign = eventCodes.entrySet() .stream() .mapToLong(ec -> ((long) Math.pow(2, Double.valueOf(ec.getValue())))) .filter(code -> codesFromDb.stream().noneMatch(pc -> pc.getCode() == code)) .mapToObj(code -> { // although we know that the codes we seek are non-combo codes, // there isn't an easy way to get from a code back to the cohort for the code // (the eventCodes goes from cohort_id -> index). Therefore, use getEventCohortsByComboCode // even tho the combo will be for a single event cohort. List<PathwayEventCohort> eventCohorts = getEventCohortsByComboCode(design, eventCodes, code); String names = eventCohorts.stream() .map(PathwayEventCohort::getName) .collect(Collectors.joining(",")); return new PathwayCode(code, names, eventCohorts.size() > 1); }).collect(Collectors.toList()); return Stream.concat(codesFromDb.stream(), codesFromDesign.stream()).collect(Collectors.toList()); } private List<PathwayEventCohort> getEventCohortsByComboCode(PathwayAnalysisEntity pathwayAnalysis, Map<Integer, Integer> eventCodes, long comboCode) { return pathwayAnalysis.getEventCohorts() .stream() .filter(ec -> ((long) Math.pow(2, Double.valueOf(eventCodes.get(ec.getCohortDefinition().getId()))) & comboCode) > 0) .collect(Collectors.toList()); } private int[] savePathwayCodes(List<PathwayCode> pathwayCodes) { String[] codeNames = new String[]{GENERATION_ID, "code", "name", "is_combo"}; List<PreparedStatementCreator> creators = new ArrayList<>(); pathwayCodes.forEach(code -> { Object[] values = new Object[]{generationId, code.getCode(), code.getName(), code.isCombo() ? 1 : 0}; PreparedStatementRenderer psr = new PreparedStatementRenderer(source, "/resources/pathway/saveCodes.sql", "target_database_schema", source.getTableQualifier(SourceDaimon.DaimonType.Results), codeNames, values); creators.add(new PreparedStatementRendererCreator(psr)); }); return jdbcTemplate.batchUpdate(stmtCancel, creators); } private int[] savePaths(Source source, Long generationId) throws SQLException { String sql = SAVE_PATHS_SQL; PreparedStatementRenderer pathwayEventsPsr = new PreparedStatementRenderer( source, sql, new String[]{"target_database_schema"}, new String[]{source.getTableQualifier(SourceDaimon.DaimonType.Results)}, new String[]{GENERATION_ID}, new Object[]{generationId} ); return jdbcTemplate.batchUpdate(stmtCancel, Arrays.asList(new PreparedStatementRendererCreator(pathwayEventsPsr))); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/PathwayServiceImpl.java
src/main/java/org/ohdsi/webapi/pathway/PathwayServiceImpl.java
package org.ohdsi.webapi.pathway; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph; import com.google.common.base.MoreObjects; import com.odysseusinc.arachne.commons.types.DBMSType; import org.hibernate.Hibernate; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.SqlRender; import org.ohdsi.sql.SqlTranslate; import org.ohdsi.sql.StringUtils; import org.ohdsi.webapi.cohortcharacterization.repository.AnalysisGenerationInfoEntityRepository; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; import org.ohdsi.webapi.common.DesignImportService; import org.ohdsi.webapi.common.generation.AnalysisGenerationInfoEntity; import org.ohdsi.webapi.common.generation.GenerationUtils; import org.ohdsi.webapi.common.generation.TransactionalTasklet; import org.ohdsi.webapi.job.GeneratesNotification; import org.ohdsi.webapi.job.JobExecutionResource; import org.ohdsi.webapi.job.JobTemplate; import org.ohdsi.webapi.pathway.converter.SerializedPathwayAnalysisToPathwayAnalysisConverter; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisGenerationEntity; import org.ohdsi.webapi.pathway.domain.PathwayCohort; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import org.ohdsi.webapi.pathway.domain.PathwayTargetCohort; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.dto.PathwayCodeDTO; import org.ohdsi.webapi.pathway.dto.PathwayPopulationEventDTO; import org.ohdsi.webapi.pathway.dto.PathwayPopulationResultsDTO; import org.ohdsi.webapi.pathway.dto.PathwayVersionFullDTO; import org.ohdsi.webapi.pathway.dto.TargetCohortPathwaysDTO; import org.ohdsi.webapi.pathway.dto.internal.CohortPathways; import org.ohdsi.webapi.pathway.dto.internal.PathwayAnalysisResult; import org.ohdsi.webapi.pathway.dto.internal.PathwayCode; import org.ohdsi.webapi.pathway.repository.PathwayAnalysisEntityRepository; import org.ohdsi.webapi.pathway.repository.PathwayAnalysisGenerationRepository; import org.ohdsi.webapi.security.PermissionService; import org.ohdsi.webapi.service.AbstractDaoService; import org.ohdsi.webapi.service.CohortDefinitionService; import org.ohdsi.webapi.service.JobService; import org.ohdsi.webapi.shiro.Entities.UserEntity; import org.ohdsi.webapi.shiro.Entities.UserRepository; import org.ohdsi.webapi.shiro.annotations.DataSourceAccess; import org.ohdsi.webapi.shiro.annotations.PathwayAnalysisGenerationId; import org.ohdsi.webapi.shiro.annotations.SourceId; import org.ohdsi.webapi.shiro.management.Security; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.source.SourceService; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.ohdsi.webapi.util.EntityUtils; import org.ohdsi.webapi.util.ExceptionUtils; import org.ohdsi.webapi.util.NameUtils; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.ohdsi.webapi.util.SessionUtils; import org.ohdsi.webapi.util.SourceUtils; import org.ohdsi.webapi.versioning.domain.PathwayVersion; import org.ohdsi.webapi.versioning.domain.Version; import org.ohdsi.webapi.versioning.domain.VersionBase; import org.ohdsi.webapi.versioning.domain.VersionType; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.ohdsi.webapi.versioning.service.VersionService; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.job.builder.SimpleJobBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.StringJoiner; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.ohdsi.webapi.Constants.GENERATE_PATHWAY_ANALYSIS; import static org.ohdsi.webapi.Constants.Params.GENERATION_ID; import static org.ohdsi.webapi.Constants.Params.JOB_AUTHOR; import static org.ohdsi.webapi.Constants.Params.JOB_NAME; import static org.ohdsi.webapi.Constants.Params.PATHWAY_ANALYSIS_ID; import static org.ohdsi.webapi.Constants.Params.SOURCE_ID; @Service @Transactional public class PathwayServiceImpl extends AbstractDaoService implements PathwayService, GeneratesNotification { private final PathwayAnalysisEntityRepository pathwayAnalysisRepository; private final PathwayAnalysisGenerationRepository pathwayAnalysisGenerationRepository; private final SourceService sourceService; private final JobTemplate jobTemplate; private final EntityManager entityManager; private final DesignImportService designImportService; private final AnalysisGenerationInfoEntityRepository analysisGenerationInfoEntityRepository; private final UserRepository userRepository; private final GenerationUtils generationUtils; private final JobService jobService; private final GenericConversionService genericConversionService; private final StepBuilderFactory stepBuilderFactory; private final CohortDefinitionService cohortDefinitionService; private final VersionService<PathwayVersion> versionService; private PermissionService permissionService; @Value("${security.defaultGlobalReadPermissions}") private boolean defaultGlobalReadPermissions; private final List<String> STEP_COLUMNS = Arrays.asList(new String[]{"step_1", "step_2", "step_3", "step_4", "step_5", "step_6", "step_7", "step_8", "step_9", "step_10"}); private final EntityGraph defaultEntityGraph = EntityUtils.fromAttributePaths( "targetCohorts.cohortDefinition", "eventCohorts.cohortDefinition", "createdBy", "modifiedBy" ); @Autowired public PathwayServiceImpl( PathwayAnalysisEntityRepository pathwayAnalysisRepository, PathwayAnalysisGenerationRepository pathwayAnalysisGenerationRepository, SourceService sourceService, ConversionService conversionService, JobTemplate jobTemplate, EntityManager entityManager, Security security, DesignImportService designImportService, AnalysisGenerationInfoEntityRepository analysisGenerationInfoEntityRepository, UserRepository userRepository, GenerationUtils generationUtils, JobService jobService, @Qualifier("conversionService") GenericConversionService genericConversionService, StepBuilderFactory stepBuilderFactory, CohortDefinitionService cohortDefinitionService, VersionService<PathwayVersion> versionService, PermissionService permissionService) { this.pathwayAnalysisRepository = pathwayAnalysisRepository; this.pathwayAnalysisGenerationRepository = pathwayAnalysisGenerationRepository; this.sourceService = sourceService; this.jobTemplate = jobTemplate; this.entityManager = entityManager; this.jobService = jobService; this.genericConversionService = genericConversionService; this.security = security; this.designImportService = designImportService; this.analysisGenerationInfoEntityRepository = analysisGenerationInfoEntityRepository; this.userRepository = userRepository; this.generationUtils = generationUtils; this.stepBuilderFactory = stepBuilderFactory; this.cohortDefinitionService = cohortDefinitionService; this.versionService = versionService; this.permissionService = permissionService; SerializedPathwayAnalysisToPathwayAnalysisConverter.setConversionService(conversionService); } @Override public PathwayAnalysisEntity create(PathwayAnalysisEntity toSave) { PathwayAnalysisEntity newAnalysis = new PathwayAnalysisEntity(); copyProps(toSave, newAnalysis); toSave.getTargetCohorts().forEach(tc -> { tc.setId(null); tc.setPathwayAnalysis(newAnalysis); newAnalysis.getTargetCohorts().add(tc); }); toSave.getEventCohorts().forEach(ec -> { ec.setId(null); ec.setPathwayAnalysis(newAnalysis); newAnalysis.getEventCohorts().add(ec); }); newAnalysis.setCreatedBy(getCurrentUser()); newAnalysis.setCreatedDate(new Date()); // Fields with information about modifications have to be reseted newAnalysis.setModifiedBy(null); newAnalysis.setModifiedDate(null); return save(newAnalysis); } @Override public PathwayAnalysisEntity importAnalysis(PathwayAnalysisEntity toImport) { PathwayAnalysisEntity newAnalysis = new PathwayAnalysisEntity(); copyProps(toImport, newAnalysis); Stream.concat(toImport.getTargetCohorts().stream(), toImport.getEventCohorts().stream()).forEach(pc -> { CohortDefinition cohortDefinition = designImportService.persistCohortOrGetExisting(pc.getCohortDefinition()); pc.setId(null); pc.setName(cohortDefinition.getName()); pc.setCohortDefinition(cohortDefinition); pc.setPathwayAnalysis(newAnalysis); if (pc instanceof PathwayTargetCohort) { newAnalysis.getTargetCohorts().add((PathwayTargetCohort) pc); } else { newAnalysis.getEventCohorts().add((PathwayEventCohort) pc); } }); newAnalysis.setCreatedBy(getCurrentUser()); newAnalysis.setCreatedDate(new Date()); return save(newAnalysis); } @Override public Page<PathwayAnalysisEntity> getPage(final Pageable pageable) { List<PathwayAnalysisEntity> pathwayList = pathwayAnalysisRepository.findAll(defaultEntityGraph) .stream().filter(!defaultGlobalReadPermissions ? entity -> permissionService.hasReadAccess(entity) : entity -> true) .collect(Collectors.toList()); return getPageFromResults(pageable, pathwayList); } private Page<PathwayAnalysisEntity> getPageFromResults(Pageable pageable, List<PathwayAnalysisEntity> results) { // Calculate the start and end indices for the current page int startIndex = pageable.getPageNumber() * pageable.getPageSize(); int endIndex = Math.min(startIndex + pageable.getPageSize(), results.size()); return new PageImpl<>(results.subList(startIndex, endIndex), pageable, results.size()); } @Override public int getCountPAWithSameName(Integer id, String name) { return pathwayAnalysisRepository.getCountPAWithSameName(id, name); } @Override public PathwayAnalysisEntity getById(Integer id) { PathwayAnalysisEntity entity = pathwayAnalysisRepository.findOne(id, defaultEntityGraph); if (Objects.nonNull(entity)) { entity.getTargetCohorts().forEach(tc -> Hibernate.initialize(tc.getCohortDefinition().getDetails())); entity.getEventCohorts().forEach(ec -> Hibernate.initialize(ec.getCohortDefinition().getDetails())); } return entity; } private List<String> getNamesLike(String name) { return pathwayAnalysisRepository.findAllByNameStartsWith(name).stream().map(PathwayAnalysisEntity::getName).collect(Collectors.toList()); } @Override public String getNameForCopy(String dtoName) { return NameUtils.getNameForCopy(dtoName, this::getNamesLike, pathwayAnalysisRepository.findByName(dtoName)); } @Override public String getNameWithSuffix(String dtoName) { return NameUtils.getNameWithSuffix(dtoName, this::getNamesLike); } @Override public PathwayAnalysisEntity update(PathwayAnalysisEntity forUpdate) { PathwayAnalysisEntity existing = getById(forUpdate.getId()); copyProps(forUpdate, existing); updateCohorts(existing, existing.getTargetCohorts(), forUpdate.getTargetCohorts()); updateCohorts(existing, existing.getEventCohorts(), forUpdate.getEventCohorts()); existing.setModifiedBy(getCurrentUser()); existing.setModifiedDate(new Date()); return save(existing); } private <T extends PathwayCohort> void updateCohorts(PathwayAnalysisEntity analysis, Set<T> existing, Set<T> forUpdate) { Set<PathwayCohort> removedCohorts = existing .stream() .filter(ec -> !forUpdate.contains(ec)) .collect(Collectors.toSet()); existing.removeAll(removedCohorts); forUpdate.forEach(updatedCohort -> existing.stream() .filter(ec -> ec.equals(updatedCohort)) .findFirst() .map(ec -> { ec.setName(updatedCohort.getName()); return ec; }) .orElseGet(() -> { updatedCohort.setId(null); updatedCohort.setPathwayAnalysis(analysis); existing.add(updatedCohort); return updatedCohort; })); } @Override public void delete(Integer id) { pathwayAnalysisRepository.delete(id); } @Override public Map<Integer, Integer> getEventCohortCodes(PathwayAnalysisEntity pathwayAnalysis) { Integer index = 0; List<PathwayEventCohort> sortedEventCohortsCopy = pathwayAnalysis.getEventCohorts() .stream() .sorted(Comparator.comparing(PathwayEventCohort::getName)) .collect(Collectors.toList()); Map<Integer, Integer> cohortDefIdToIndexMap = new HashMap<>(); for (PathwayEventCohort eventCohort : sortedEventCohortsCopy) { cohortDefIdToIndexMap.put(eventCohort.getCohortDefinition().getId(), index++); } return cohortDefIdToIndexMap; } @Override @DataSourceAccess public String buildAnalysisSql(Long generationId, PathwayAnalysisEntity pathwayAnalysis, @SourceId Integer sourceId, String cohortTable, String sessionId) { Map<Integer, Integer> eventCohortCodes = getEventCohortCodes(pathwayAnalysis); Source source = sourceService.findBySourceId(sourceId); final StringJoiner joiner = new StringJoiner("\n\n"); String analysisSql = ResourceHelper.GetResourceAsString("/resources/pathway/runPathwayAnalysis.sql"); String eventCohortInputSql = ResourceHelper.GetResourceAsString("/resources/pathway/eventCohortInput.sql"); String tempTableQualifier = SourceUtils.getTempQualifier(source); String resultsTableQualifier = SourceUtils.getResultsQualifier(source); String eventCohortIdIndexSql = eventCohortCodes.entrySet() .stream() .map(ec -> { String[] params = new String[]{"cohort_definition_id", "event_cohort_index"}; String[] values = new String[]{ec.getKey().toString(), ec.getValue().toString()}; return SqlRender.renderSql(eventCohortInputSql, params, values); }) .collect(Collectors.joining(" UNION ALL ")); pathwayAnalysis.getTargetCohorts().forEach(tc -> { String[] params = new String[]{ GENERATION_ID, "event_cohort_id_index_map", "temp_database_schema", "target_database_schema", "target_cohort_table", "pathway_target_cohort_id", "max_depth", "combo_window", "allow_repeats", "isHive" }; String[] values = new String[]{ generationId.toString(), eventCohortIdIndexSql, tempTableQualifier, resultsTableQualifier, cohortTable, tc.getCohortDefinition().getId().toString(), pathwayAnalysis.getMaxDepth().toString(), MoreObjects.firstNonNull(pathwayAnalysis.getCombinationWindow(), 1).toString(), String.valueOf(pathwayAnalysis.isAllowRepeats()), String.valueOf(Objects.equals(DBMSType.HIVE.getOhdsiDB(), source.getSourceDialect())) }; String renderedSql = SqlRender.renderSql(analysisSql, params, values); String translatedSql = SqlTranslate.translateSql(renderedSql, source.getSourceDialect(), sessionId, SourceUtils.getTempQualifier(source)); joiner.add(translatedSql); }); return joiner.toString(); } @Override public String buildAnalysisSql(Long generationId, PathwayAnalysisEntity pathwayAnalysis, Integer sourceId) { return buildAnalysisSql(generationId, pathwayAnalysis, sourceId, "cohort", SessionUtils.sessionId()); } @Override @DataSourceAccess public JobExecutionResource generatePathways(final Integer pathwayAnalysisId, final @SourceId Integer sourceId) { PathwayService pathwayService = this; PathwayAnalysisEntity pathwayAnalysis = getById(pathwayAnalysisId); Source source = getSourceRepository().findBySourceId(sourceId); JobParametersBuilder builder = new JobParametersBuilder(); builder.addString(JOB_NAME, String.format("Generating Pathway Analysis %d using %s (%s)", pathwayAnalysisId, source.getSourceName(), source.getSourceKey())); builder.addString(SOURCE_ID, String.valueOf(source.getSourceId())); builder.addString(PATHWAY_ANALYSIS_ID, pathwayAnalysis.getId().toString()); builder.addString(JOB_AUTHOR, getCurrentUserLogin()); JdbcTemplate jdbcTemplate = getSourceJdbcTemplate(source); SimpleJobBuilder generateAnalysisJob = generationUtils.buildJobForCohortBasedAnalysisTasklet( GENERATE_PATHWAY_ANALYSIS, source, builder, jdbcTemplate, chunkContext -> { Integer analysisId = Integer.valueOf(chunkContext.getStepContext().getJobParameters().get(PATHWAY_ANALYSIS_ID).toString()); PathwayAnalysisEntity analysis = pathwayService.getById(analysisId); return Stream.concat(analysis.getTargetCohorts().stream(), analysis.getEventCohorts().stream()) .map(PathwayCohort::getCohortDefinition) .collect(Collectors.toList()); }, new GeneratePathwayAnalysisTasklet( getSourceJdbcTemplate(source), getTransactionTemplate(), pathwayService, analysisGenerationInfoEntityRepository, userRepository, sourceService ) ); TransactionalTasklet statisticsTasklet = new PathwayStatisticsTasklet(getSourceJdbcTemplate(source), getTransactionTemplate(), source, this, genericConversionService); Step generateStatistics = stepBuilderFactory.get(GENERATE_PATHWAY_ANALYSIS + ".generateStatistics") .tasklet(statisticsTasklet) .build(); generateAnalysisJob.next(generateStatistics); final JobParameters jobParameters = builder.toJobParameters(); return jobService.runJob(generateAnalysisJob.build(), jobParameters); } @Override @DataSourceAccess public void cancelGeneration(Integer pathwayAnalysisId, @SourceId Integer sourceId) { PathwayAnalysisEntity entity = pathwayAnalysisRepository.findOne(pathwayAnalysisId, defaultEntityGraph); String sourceKey = getSourceRepository().findBySourceId(sourceId).getSourceKey(); entity.getTargetCohorts().forEach(tc -> cohortDefinitionService.cancelGenerateCohort(tc.getId(), sourceKey)); entity.getEventCohorts().forEach(ec -> cohortDefinitionService.cancelGenerateCohort(ec.getId(), sourceKey)); jobService.cancelJobExecution(j -> { JobParameters jobParameters = j.getJobParameters(); String jobName = j.getJobInstance().getJobName(); return Objects.equals(jobParameters.getString(PATHWAY_ANALYSIS_ID), Integer.toString(pathwayAnalysisId)) && Objects.equals(jobParameters.getString(SOURCE_ID), String.valueOf(sourceId)) && Objects.equals(GENERATE_PATHWAY_ANALYSIS, jobName); }); } @Override public List<PathwayAnalysisGenerationEntity> getPathwayGenerations(final Integer pathwayAnalysisId) { return pathwayAnalysisGenerationRepository.findAllByPathwayAnalysisId(pathwayAnalysisId, EntityUtils.fromAttributePaths("source")); } @Override public PathwayAnalysisGenerationEntity getGeneration(Long generationId) { return pathwayAnalysisGenerationRepository.findOne(generationId, EntityUtils.fromAttributePaths("source")); } @Override @DataSourceAccess public PathwayAnalysisResult getResultingPathways(final @PathwayAnalysisGenerationId Long generationId) { PathwayAnalysisGenerationEntity generation = getGeneration(generationId); Source source = generation.getSource(); return queryGenerationResults(source, generationId); } private final RowMapper<PathwayCode> codeRowMapper = (final ResultSet resultSet, final int arg1) -> { return new PathwayCode(resultSet.getLong("code"), resultSet.getString("name"), resultSet.getInt("is_combo") != 0); }; private final RowMapper<CohortPathways> pathwayStatsRowMapper = (final ResultSet rs, final int arg1) -> { CohortPathways cp = new CohortPathways(); cp.setCohortId(rs.getInt("target_cohort_id")); cp.setTargetCohortCount(rs.getInt("target_cohort_count")); cp.setTotalPathwaysCount(rs.getInt("pathways_count")); return cp; }; private final ResultSetExtractor<Map<Integer, Map<String, Integer>>> pathwayExtractor = (final ResultSet rs) -> { Map<Integer, Map<String, Integer>> cohortMap = new HashMap<>(); // maps a cohortId to a list of pathways (which is stored as a Map<String,Integer> while (rs.next()) { int cohortId = rs.getInt("target_cohort_id"); if (!cohortMap.containsKey(cohortId)) { cohortMap.put(cohortId, new HashMap<>()); } Map<String, Integer> pathList = cohortMap.get(cohortId); // build path List<String> path = new ArrayList<>(); for (String stepCol : STEP_COLUMNS) { String step = rs.getString(stepCol); if (step == null) break; // cancel for-loop when we encounter a column with a null value path.add(step); } pathList.put(StringUtils.join(path, "-"), rs.getInt("count_value")); // for a given cohort, a path must be unique, so no need to check } return cohortMap; }; @Override @DataSourceAccess public String findDesignByGenerationId(@PathwayAnalysisGenerationId final Long id) { final AnalysisGenerationInfoEntity entity = analysisGenerationInfoEntityRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("Analysis with id: " + id + " cannot be found")); return entity.getDesign(); } @Override public void assignTag(Integer id, int tagId) { PathwayAnalysisEntity entity = getById(id); assignTag(entity, tagId); } @Override public void unassignTag(Integer id, int tagId) { PathwayAnalysisEntity entity = getById(id); unassignTag(entity, tagId); } @Override public List<VersionDTO> getVersions(long id) { List<VersionBase> versions = versionService.getVersions(VersionType.PATHWAY, id); return versions.stream() .map(v -> genericConversionService.convert(v, VersionDTO.class)) .collect(Collectors.toList()); } @Override public PathwayVersionFullDTO getVersion(int id, int version) { checkVersion(id, version, false); PathwayVersion pathwayVersion = versionService.getById(VersionType.PATHWAY, id, version); return genericConversionService.convert(pathwayVersion, PathwayVersionFullDTO.class); } @Override public VersionDTO updateVersion(int id, int version, VersionUpdateDTO updateDTO) { checkVersion(id, version); updateDTO.setAssetId(id); updateDTO.setVersion(version); PathwayVersion updated = versionService.update(VersionType.PATHWAY, updateDTO); return genericConversionService.convert(updated, VersionDTO.class); } @Override public void deleteVersion(int id, int version) { checkVersion(id, version); versionService.delete(VersionType.PATHWAY, id, version); } @Override public PathwayAnalysisDTO copyAssetFromVersion(int id, int version) { checkVersion(id, version, false); PathwayVersion pathwayVersion = versionService.getById(VersionType.PATHWAY, id, version); PathwayVersionFullDTO fullDTO = genericConversionService.convert(pathwayVersion, PathwayVersionFullDTO.class); PathwayAnalysisDTO dto = fullDTO.getEntityDTO(); dto.setId(null); dto.setTags(null); dto.setName(NameUtils.getNameForCopy(dto.getName(), this::getNamesLike, pathwayAnalysisRepository.findByName(dto.getName()))); PathwayAnalysisEntity pathwayAnalysis = genericConversionService.convert(dto, PathwayAnalysisEntity.class); PathwayAnalysisEntity saved = create(pathwayAnalysis); return genericConversionService.convert(saved, PathwayAnalysisDTO.class); } @Override public List<PathwayAnalysisDTO> listByTags(TagNameListRequestDTO requestDTO) { List<String> names = requestDTO.getNames().stream() .map(name -> name.toLowerCase(Locale.ROOT)) .collect(Collectors.toList()); List<PathwayAnalysisEntity> entities = pathwayAnalysisRepository.findByTags(names); return listByTags(entities, names, PathwayAnalysisDTO.class); } private void checkVersion(int id, int version) { checkVersion(id, version, true); } private void checkVersion(int id, int version, boolean checkOwnerShip) { Version pathwayVersion = versionService.getById(VersionType.PATHWAY, id, version); ExceptionUtils.throwNotFoundExceptionIfNull(pathwayVersion, String.format("There is no pathway analysis version with id = %d.", version)); PathwayAnalysisEntity entity = this.pathwayAnalysisRepository.findOne(id); if (checkOwnerShip) { checkOwnerOrAdminOrGranted(entity); } } public PathwayVersion saveVersion(int id) { PathwayAnalysisEntity def = this.pathwayAnalysisRepository.findOne(id); PathwayVersion version = genericConversionService.convert(def, PathwayVersion.class); UserEntity user = Objects.nonNull(def.getModifiedBy()) ? def.getModifiedBy() : def.getCreatedBy(); Date versionDate = Objects.nonNull(def.getModifiedDate()) ? def.getModifiedDate() : def.getCreatedDate(); version.setCreatedBy(user); version.setCreatedDate(versionDate); return versionService.create(VersionType.PATHWAY, version); } private PathwayAnalysisResult queryGenerationResults(Source source, Long generationId) { // load code lookup PreparedStatementRenderer pathwayCodesPsr = new PreparedStatementRenderer( source, "/resources/pathway/getPathwayCodeLookup.sql", "target_database_schema", source.getTableQualifier(SourceDaimon.DaimonType.Results), new String[]{GENERATION_ID}, new Object[]{generationId} ); List<PathwayCode> pathwayCodes = getSourceJdbcTemplate(source).query(pathwayCodesPsr.getSql(), pathwayCodesPsr.getOrderedParams(), codeRowMapper); // fetch cohort stats, paths will be populated after PreparedStatementRenderer pathwayStatsPsr = new PreparedStatementRenderer( source, "/resources/pathway/getPathwayStats.sql", "target_database_schema", source.getTableQualifier(SourceDaimon.DaimonType.Results), new String[]{GENERATION_ID}, new Object[]{generationId} ); List<CohortPathways> cohortStats = getSourceJdbcTemplate(source).query(pathwayStatsPsr.getSql(), pathwayStatsPsr.getOrderedParams(), pathwayStatsRowMapper); // load cohort paths, and assign back to cohortStats PreparedStatementRenderer pathwayResultsPsr = new PreparedStatementRenderer( source, "/resources/pathway/getPathwayResults.sql", "target_database_schema", source.getTableQualifier(SourceDaimon.DaimonType.Results), new String[]{GENERATION_ID}, new Object[]{generationId} ); Map<Integer, Map<String, Integer>> pathwayResults = getSourceJdbcTemplate(source).query(pathwayResultsPsr.getSql(), pathwayResultsPsr.getOrderedParams(), pathwayExtractor); cohortStats.stream().forEach((cp) -> { cp.setPathwaysCounts(pathwayResults.get(cp.getCohortId())); }); PathwayAnalysisResult result = new PathwayAnalysisResult(); result.setCodes(new HashSet<>(pathwayCodes)); result.setCohortPathwaysList(new HashSet<>(cohortStats)); return result; } private void copyProps(PathwayAnalysisEntity from, PathwayAnalysisEntity to) { to.setName(from.getName()); to.setDescription(from.getDescription()); to.setMaxDepth(from.getMaxDepth()); to.setMinCellCount(from.getMinCellCount()); to.setCombinationWindow(from.getCombinationWindow()); to.setAllowRepeats(from.isAllowRepeats()); } private int getAnalysisHashCode(PathwayAnalysisEntity pathwayAnalysis) { SerializedPathwayAnalysisToPathwayAnalysisConverter designConverter = new SerializedPathwayAnalysisToPathwayAnalysisConverter(); return designConverter.convertToDatabaseColumn(pathwayAnalysis).hashCode(); } private PathwayAnalysisEntity save(PathwayAnalysisEntity pathwayAnalysis) { pathwayAnalysis = pathwayAnalysisRepository.saveAndFlush(pathwayAnalysis); entityManager.refresh(pathwayAnalysis); pathwayAnalysis = getById(pathwayAnalysis.getId()); pathwayAnalysis.setHashCode(getAnalysisHashCode(pathwayAnalysis)); return pathwayAnalysis; } @Override public String getJobName() { return GENERATE_PATHWAY_ANALYSIS; } @Override public String getExecutionFoldingKey() { return PATHWAY_ANALYSIS_ID; } @Override @Transactional public PathwayAnalysisDTO getByGenerationId(final Integer id) { PathwayAnalysisGenerationEntity pathwayAnalysisGenerationEntity = getGeneration(id.longValue()); PathwayAnalysisEntity pathwayAnalysis = pathwayAnalysisGenerationEntity.getPathwayAnalysis(); Map<Integer, Integer> eventCodes = getEventCohortCodes(pathwayAnalysis); PathwayAnalysisDTO dto = genericConversionService.convert(pathwayAnalysis, PathwayAnalysisDTO.class); dto.getEventCohorts().forEach(ec -> ec.setCode(eventCodes.get(ec.getId()))); return dto; } @Override public PathwayPopulationResultsDTO getGenerationResults(Long generationId) { PathwayAnalysisResult resultingPathways = getResultingPathways(generationId); List<PathwayCodeDTO> eventCodeDtos = resultingPathways.getCodes() .stream() .map(entry -> { PathwayCodeDTO dto = new PathwayCodeDTO(); dto.setCode(entry.getCode()); dto.setName(entry.getName()); dto.setIsCombo(entry.isCombo()); return dto; }) .collect(Collectors.toList()); List<TargetCohortPathwaysDTO> pathwayDtos = resultingPathways.getCohortPathwaysList() .stream() .map(cohortResults -> { if (cohortResults.getPathwaysCounts() == null) { return null; } List<PathwayPopulationEventDTO> eventDTOs = cohortResults.getPathwaysCounts() .entrySet() .stream() .map(entry -> new PathwayPopulationEventDTO(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); return new TargetCohortPathwaysDTO(cohortResults.getCohortId(), cohortResults.getTargetCohortCount(), cohortResults.getTotalPathwaysCount(), eventDTOs); }) .filter(Objects::nonNull) .collect(Collectors.toList()); return new PathwayPopulationResultsDTO(eventCodeDtos, pathwayDtos); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/PathwayService.java
src/main/java/org/ohdsi/webapi/pathway/PathwayService.java
package org.ohdsi.webapi.pathway; import org.ohdsi.webapi.job.JobExecutionResource; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisGenerationEntity; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.dto.PathwayPopulationResultsDTO; import org.ohdsi.webapi.pathway.dto.PathwayVersionFullDTO; import org.ohdsi.webapi.pathway.dto.internal.PathwayAnalysisResult; import org.ohdsi.webapi.shiro.annotations.PathwayAnalysisGenerationId; import org.ohdsi.webapi.tag.domain.HasTags; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.ohdsi.webapi.versioning.domain.PathwayVersion; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; import java.util.Map; public interface PathwayService extends HasTags<Integer> { PathwayAnalysisEntity create(PathwayAnalysisEntity pathwayAnalysisEntity); PathwayAnalysisEntity importAnalysis(PathwayAnalysisEntity toImport); String getNameForCopy(String dtoName); String getNameWithSuffix(String dtoName); Page<PathwayAnalysisEntity> getPage(final Pageable pageable); int getCountPAWithSameName(Integer id, String name); PathwayAnalysisEntity getById(Integer id); PathwayAnalysisEntity update(PathwayAnalysisEntity pathwayAnalysisEntity); void delete(Integer id); Map<Integer, Integer> getEventCohortCodes(PathwayAnalysisEntity pathwayAnalysis); String buildAnalysisSql(Long generationId, PathwayAnalysisEntity pathwayAnalysis, Integer sourceId); String buildAnalysisSql(Long generationId, PathwayAnalysisEntity pathwayAnalysis, Integer sourceId, String cohortTable, String sessionId); JobExecutionResource generatePathways(final Integer pathwayAnalysisId, final Integer sourceId); List<PathwayAnalysisGenerationEntity> getPathwayGenerations(final Integer pathwayAnalysisId); PathwayAnalysisGenerationEntity getGeneration(Long generationId); PathwayAnalysisResult getResultingPathways(final Long generationId); void cancelGeneration(Integer pathwayAnalysisId, Integer sourceId); String findDesignByGenerationId(@PathwayAnalysisGenerationId final Long id); List<VersionDTO> getVersions(long id); PathwayVersionFullDTO getVersion(int id, int version); VersionDTO updateVersion(int id, int version, VersionUpdateDTO updateDTO); void deleteVersion(int id, int version); PathwayAnalysisDTO copyAssetFromVersion(int id, int version); PathwayVersion saveVersion(int id); List<PathwayAnalysisDTO> listByTags(TagNameListRequestDTO requestDTO); PathwayAnalysisDTO getByGenerationId(Integer id); PathwayPopulationResultsDTO getGenerationResults(Long generationId); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/PathwayVersionFullDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/PathwayVersionFullDTO.java
package org.ohdsi.webapi.pathway.dto; import org.ohdsi.webapi.versioning.dto.VersionFullDTO; public class PathwayVersionFullDTO extends VersionFullDTO<PathwayAnalysisDTO> { }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/BasePathwayAnalysisDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/BasePathwayAnalysisDTO.java
package org.ohdsi.webapi.pathway.dto; import org.ohdsi.webapi.cohortdefinition.CohortMetadataExt; import org.ohdsi.webapi.service.dto.CommonEntityExtDTO; import java.util.List; public abstract class BasePathwayAnalysisDTO<T extends CohortMetadataExt> extends CommonEntityExtDTO { private Integer id; private String name; private String description; private List<T> targetCohorts; private List<T> eventCohorts; private Integer combinationWindow; private Integer minSegmentLength; private Integer minCellCount; private Integer maxDepth; private boolean allowRepeats; private Integer hashCode; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<T> getTargetCohorts() { return targetCohorts; } public void setTargetCohorts(List<T> targetCohorts) { this.targetCohorts = targetCohorts; } public List<T> getEventCohorts() { return eventCohorts; } public void setEventCohorts(List<T> eventCohorts) { this.eventCohorts = eventCohorts; } public Integer getCombinationWindow() { return combinationWindow; } public void setCombinationWindow(Integer combinationWindow) { this.combinationWindow = combinationWindow; } public Integer getMinSegmentLength() { return minSegmentLength; } public void setMinSegmentLength(Integer minSegmentLength) { this.minSegmentLength = minSegmentLength; } public Integer getMinCellCount() { return minCellCount; } public void setMinCellCount(Integer minCellCount) { this.minCellCount = minCellCount; } public Integer getMaxDepth() { return maxDepth; } public void setMaxDepth(Integer maxDepth) { this.maxDepth = maxDepth; } public boolean isAllowRepeats() { return allowRepeats; } public void setAllowRepeats(boolean allowRepeats) { this.allowRepeats = allowRepeats; } public Integer getHashCode() { return hashCode; } public void setHashCode(Integer hashCode) { this.hashCode = hashCode; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/PathwayAnalysisDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/PathwayAnalysisDTO.java
package org.ohdsi.webapi.pathway.dto; public class PathwayAnalysisDTO extends BasePathwayAnalysisDTO<PathwayCohortDTO> { }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/PathwayCodeDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/PathwayCodeDTO.java
package org.ohdsi.webapi.pathway.dto; public class PathwayCodeDTO { private Long code; private String name; private boolean isCombo = false; public Long getCode() { return code; } public void setCode(Long code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean getIsCombo() { return isCombo; } public void setIsCombo(boolean combo) { isCombo = combo; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/PathwayCohortExportDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/PathwayCohortExportDTO.java
package org.ohdsi.webapi.pathway.dto; import org.ohdsi.analysis.Cohort; import org.ohdsi.circe.cohortdefinition.CohortExpression; import org.ohdsi.webapi.cohortdefinition.ExpressionType; public class PathwayCohortExportDTO extends PathwayCohortDTO implements Cohort { private CohortExpression expression; private ExpressionType expressionType; public CohortExpression getExpression() { return expression; } public void setExpression(final CohortExpression expression) { this.expression = expression; } public ExpressionType getExpressionType() { return expressionType; } public void setExpressionType(final ExpressionType expressionType) { this.expressionType = expressionType; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/TargetCohortPathwaysDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/TargetCohortPathwaysDTO.java
package org.ohdsi.webapi.pathway.dto; import java.util.List; public class TargetCohortPathwaysDTO { private Integer targetCohortId; private Integer targetCohortCount; private Integer totalPathwaysCount; private List<PathwayPopulationEventDTO> pathways; public TargetCohortPathwaysDTO(Integer targetCohortId, Integer targetCohortCount, Integer totalPathwaysCount, List<PathwayPopulationEventDTO> pathways) { this.targetCohortId = targetCohortId; this.targetCohortCount = targetCohortCount; this.totalPathwaysCount = totalPathwaysCount; this.pathways = pathways; } public Integer getTargetCohortId() { return targetCohortId; } public void setTargetCohortId(Integer targetCohortId) { this.targetCohortId = targetCohortId; } public Integer getTargetCohortCount() { return targetCohortCount; } public void setTargetCohortCount(Integer targetCohortCount) { this.targetCohortCount = targetCohortCount; } public Integer getTotalPathwaysCount() { return totalPathwaysCount; } public void setTotalPathwaysCount(Integer totalPathwaysCount) { this.totalPathwaysCount = totalPathwaysCount; } public List<PathwayPopulationEventDTO> getPathways() { return pathways; } public void setPathways(List<PathwayPopulationEventDTO> pathways) { this.pathways = pathways; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/PathwayPopulationEventDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/PathwayPopulationEventDTO.java
package org.ohdsi.webapi.pathway.dto; import org.ohdsi.analysis.pathway.result.PathwayPopulationEvent; public class PathwayPopulationEventDTO implements PathwayPopulationEvent { private String path; private Integer personCount; public PathwayPopulationEventDTO(String path, Integer personCount) { this.path = path; this.personCount = personCount; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Integer getPersonCount() { return personCount; } public void setPersonCount(Integer personCount) { this.personCount = personCount; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/PathwayCohortDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/PathwayCohortDTO.java
package org.ohdsi.webapi.pathway.dto; import org.ohdsi.webapi.cohortdefinition.dto.CohortMetadataDTO; public class PathwayCohortDTO extends CohortMetadataDTO { private Integer code; private Integer pathwayCohortId; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public Integer getPathwayCohortId() { return pathwayCohortId; } public void setPathwayCohortId(Integer pathwayCohortId) { this.pathwayCohortId = pathwayCohortId; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/PathwayAnalysisExportDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/PathwayAnalysisExportDTO.java
package org.ohdsi.webapi.pathway.dto; import org.ohdsi.analysis.pathway.design.PathwayAnalysis; import org.springframework.stereotype.Component; @Component public class PathwayAnalysisExportDTO extends BasePathwayAnalysisDTO<PathwayCohortExportDTO> implements PathwayAnalysis { }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/PathwayPopulationResultsDTO.java
src/main/java/org/ohdsi/webapi/pathway/dto/PathwayPopulationResultsDTO.java
package org.ohdsi.webapi.pathway.dto; import java.util.List; public class PathwayPopulationResultsDTO { private List<PathwayCodeDTO> eventCodes; private List<TargetCohortPathwaysDTO> pathwayGroups; public PathwayPopulationResultsDTO(List<PathwayCodeDTO> eventCodes, List<TargetCohortPathwaysDTO> pathwayGroups) { this.eventCodes = eventCodes; this.pathwayGroups = pathwayGroups; } public List<PathwayCodeDTO> getEventCodes() { return eventCodes; } public void setEventCodes(List<PathwayCodeDTO> eventCodes) { this.eventCodes = eventCodes; } public List<TargetCohortPathwaysDTO> getPathwayGroups() { return pathwayGroups; } public void setPathwayGroups(List<TargetCohortPathwaysDTO> pathwayGroups) { this.pathwayGroups = pathwayGroups; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/internal/PersonPathwayEvent.java
src/main/java/org/ohdsi/webapi/pathway/dto/internal/PersonPathwayEvent.java
package org.ohdsi.webapi.pathway.dto.internal; import java.util.Date; public class PersonPathwayEvent { private Integer comboId; private Integer subjectId; private Date startDate; private Date endDate; public Integer getComboId() { return comboId; } public void setComboId(Integer comboId) { this.comboId = comboId; } public Integer getSubjectId() { return subjectId; } public void setSubjectId(Integer subjectId) { this.subjectId = subjectId; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/internal/PathwayGenerationStats.java
src/main/java/org/ohdsi/webapi/pathway/dto/internal/PathwayGenerationStats.java
package org.ohdsi.webapi.pathway.dto.internal; public class PathwayGenerationStats { private Integer targetCohortId; private Integer targetCohortCount; private Integer pathwaysCount; public Integer getTargetCohortId() { return targetCohortId; } public void setTargetCohortId(Integer targetCohortId) { this.targetCohortId = targetCohortId; } public Integer getTargetCohortCount() { return targetCohortCount; } public void setTargetCohortCount(Integer targetCohortCount) { this.targetCohortCount = targetCohortCount; } public Integer getPathwaysCount() { return pathwaysCount; } public void setPathwaysCount(Integer pathwaysCount) { this.pathwaysCount = pathwaysCount; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/internal/CohortPathways.java
src/main/java/org/ohdsi/webapi/pathway/dto/internal/CohortPathways.java
package org.ohdsi.webapi.pathway.dto.internal; import java.util.Map; import java.util.Objects; public class CohortPathways { private Integer cohortId; private Integer targetCohortCount; private Integer totalPathwaysCount; private Map<String, Integer> pathwaysCounts; public Integer getCohortId() { return cohortId; } public void setCohortId(Integer cohortId) { this.cohortId = cohortId; } public Integer getTargetCohortCount() { return targetCohortCount; } public void setTargetCohortCount(Integer targetCohortCount) { this.targetCohortCount = targetCohortCount; } public Integer getTotalPathwaysCount() { return totalPathwaysCount; } public void setTotalPathwaysCount(Integer totalPathwaysCount) { this.totalPathwaysCount = totalPathwaysCount; } public Map<String, Integer> getPathwaysCounts() { return pathwaysCounts; } public void setPathwaysCounts(Map<String, Integer> pathwaysCounts) { this.pathwaysCounts = pathwaysCounts; } @Override public int hashCode() { return Objects.hash(getCohortId(), getTargetCohortCount(), getTotalPathwaysCount(), getPathwaysCounts()); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CohortPathways)) return false; CohortPathways that = (CohortPathways) o; return Objects.equals(getCohortId(), that.getCohortId()) && Objects.equals(getTargetCohortCount(), that.getTargetCohortCount()) && Objects.equals(getTotalPathwaysCount(), that.getTotalPathwaysCount()) && Objects.equals(getPathwaysCounts(), that.getPathwaysCounts()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/internal/PathwayCode.java
src/main/java/org/ohdsi/webapi/pathway/dto/internal/PathwayCode.java
package org.ohdsi.webapi.pathway.dto.internal; import java.util.Objects; public class PathwayCode { private long code; private String name; private boolean isCombo = false; public PathwayCode(long code, String name, boolean isCombo) { this.code = code; this.name = name; this.isCombo = isCombo; } public long getCode() { return code; } public void setCode(long code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isCombo() { return isCombo; } public void setCombo(boolean combo) { isCombo = combo; } @Override public int hashCode() { return Objects.hash(getCode(), getName(), isCombo()); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PathwayCode)) return false; PathwayCode that = (PathwayCode) o; return Objects.equals(getCode(), that.getCode()) && Objects.equals(getName(), that.getName()) && Objects.equals(isCombo(), that.isCombo()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/dto/internal/PathwayAnalysisResult.java
src/main/java/org/ohdsi/webapi/pathway/dto/internal/PathwayAnalysisResult.java
package org.ohdsi.webapi.pathway.dto.internal; import java.util.HashSet; import java.util.Set; public class PathwayAnalysisResult { private Set<PathwayCode> codes = new HashSet<>(); private Set<CohortPathways> cohortPathwaysList = new HashSet<>(); public Set<PathwayCode> getCodes() { return codes; } public void setCodes(Set<PathwayCode> codes) { this.codes = codes; } public Set<CohortPathways> getCohortPathwaysList() { return cohortPathwaysList; } public void setCohortPathwaysList(Set<CohortPathways> cohortPathwaysList) { this.cohortPathwaysList = cohortPathwaysList; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/domain/PathwayAnalysisEntity.java
src/main/java/org/ohdsi/webapi/pathway/domain/PathwayAnalysisEntity.java
package org.ohdsi.webapi.pathway.domain; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.ohdsi.webapi.model.CommonEntity; import org.ohdsi.webapi.model.CommonEntityExt; import org.ohdsi.webapi.tag.domain.Tag; @Entity(name = "pathway_analysis") public class PathwayAnalysisEntity extends CommonEntityExt<Integer> { @Id @GenericGenerator( name = "pathway_analysis_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "pathway_analysis_sequence"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "pathway_analysis_generator") private Integer id; @Column private String name; @Column private String description; @OneToMany(mappedBy = "pathwayAnalysis", cascade = CascadeType.ALL, orphanRemoval = true) private Set<PathwayTargetCohort> targetCohorts = new HashSet<>(); @OneToMany(mappedBy = "pathwayAnalysis", cascade = CascadeType.ALL, orphanRemoval = true) private Set<PathwayEventCohort> eventCohorts = new HashSet<>(); @Column(name = "combination_window") private Integer combinationWindow; @Column(name = "min_segment_length") private Integer minSegmentLength; @Column(name = "min_cell_count") private Integer minCellCount; @Column(name = "max_depth") private Integer maxDepth; @Column(name = "allow_repeats") private boolean allowRepeats; @Column(name = "hash_code") private Integer hashCode; @ManyToMany(targetEntity = Tag.class, fetch = FetchType.LAZY) @JoinTable(name = "pathway_tag", joinColumns = @JoinColumn(name = "asset_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "tag_id", referencedColumnName = "id")) private Set<Tag> tags; @Override public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Set<PathwayTargetCohort> getTargetCohorts() { return targetCohorts; } public void setTargetCohorts(Set<PathwayTargetCohort> targetCohorts) { this.targetCohorts = targetCohorts; } public Set<PathwayEventCohort> getEventCohorts() { return eventCohorts; } public void setEventCohorts(Set<PathwayEventCohort> eventCohorts) { this.eventCohorts = eventCohorts; } public Integer getCombinationWindow() { return combinationWindow; } public void setCombinationWindow(Integer combinationWindow) { this.combinationWindow = combinationWindow; } public Integer getMinSegmentLength() { return minSegmentLength; } public void setMinSegmentLength(Integer minSegmentLength) { this.minSegmentLength = minSegmentLength; } public Integer getMinCellCount() { return minCellCount; } public void setMinCellCount(Integer minCellCount) { this.minCellCount = minCellCount; } public Integer getMaxDepth() { return maxDepth; } public void setMaxDepth(Integer maxDepth) { this.maxDepth = maxDepth; } public boolean isAllowRepeats() { return allowRepeats; } public void setAllowRepeats(boolean allowRepeats) { this.allowRepeats = allowRepeats; } public Integer getHashCode() { return hashCode; } public void setHashCode(Integer hashCode) { this.hashCode = hashCode; } @Override public Set<Tag> getTags() { return tags; } @Override public void setTags(Set<Tag> tags) { this.tags = tags; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/domain/PathwayEventCohort.java
src/main/java/org/ohdsi/webapi/pathway/domain/PathwayEventCohort.java
package org.ohdsi.webapi.pathway.domain; import javax.persistence.Entity; @Entity(name="pathway_event_cohort") public class PathwayEventCohort extends PathwayCohort { }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/domain/PathwayTargetCohort.java
src/main/java/org/ohdsi/webapi/pathway/domain/PathwayTargetCohort.java
package org.ohdsi.webapi.pathway.domain; import javax.persistence.Entity; @Entity(name="pathway_target_cohort") public class PathwayTargetCohort extends PathwayCohort { }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/domain/PathwayCohort.java
src/main/java/org/ohdsi/webapi/pathway/domain/PathwayCohort.java
package org.ohdsi.webapi.pathway.domain; import java.util.Objects; import javax.persistence.Column; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; @MappedSuperclass public abstract class PathwayCohort { @Id @GenericGenerator( name = "pathway_cohort_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "pathway_cohort_sequence"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "pathway_cohort_generator") protected Integer id; @Column protected String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "cohort_definition_id") protected CohortDefinition cohortDefinition; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "pathway_analysis_id") protected PathwayAnalysisEntity pathwayAnalysis; @Override public int hashCode() { return Objects.hash(this.getCohortDefinition().getId()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof PathwayCohort)) { return false; } final PathwayCohort compare = (PathwayCohort) obj; return Objects.equals(getCohortDefinition().getId(), compare.getCohortDefinition().getId()); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public CohortDefinition getCohortDefinition() { return cohortDefinition; } public void setCohortDefinition(CohortDefinition cohortDefinition) { this.cohortDefinition = cohortDefinition; } public PathwayAnalysisEntity getPathwayAnalysis() { return pathwayAnalysis; } public void setPathwayAnalysis(PathwayAnalysisEntity pathwayAnalysis) { this.pathwayAnalysis = pathwayAnalysis; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/domain/PathwayAnalysisGenerationEntity.java
src/main/java/org/ohdsi/webapi/pathway/domain/PathwayAnalysisGenerationEntity.java
package org.ohdsi.webapi.pathway.domain; import org.ohdsi.webapi.common.generation.CommonGeneration; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "pathway_analysis_generation") public class PathwayAnalysisGenerationEntity extends CommonGeneration { @ManyToOne(targetEntity = PathwayAnalysisEntity.class, fetch = FetchType.LAZY) @JoinColumn(name = "pathway_analysis_id") private PathwayAnalysisEntity pathwayAnalysis; public PathwayAnalysisEntity getPathwayAnalysis() { return pathwayAnalysis; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/repository/PathwayTargetCohortRepository.java
src/main/java/org/ohdsi/webapi/pathway/repository/PathwayTargetCohortRepository.java
package org.ohdsi.webapi.pathway.repository; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph; import com.cosium.spring.data.jpa.entity.graph.repository.EntityGraphJpaRepository; import org.ohdsi.webapi.pathway.domain.PathwayTargetCohort; import java.util.List; public interface PathwayTargetCohortRepository extends EntityGraphJpaRepository<PathwayTargetCohort, Long> { List<PathwayTargetCohort> findAllByPathwayAnalysisId(Integer pathwayAnalysisId, EntityGraph source); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/repository/PathwayEventCohortRepository.java
src/main/java/org/ohdsi/webapi/pathway/repository/PathwayEventCohortRepository.java
package org.ohdsi.webapi.pathway.repository; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph; import com.cosium.spring.data.jpa.entity.graph.repository.EntityGraphJpaRepository; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import java.util.List; public interface PathwayEventCohortRepository extends EntityGraphJpaRepository<PathwayEventCohort, Long> { List<PathwayEventCohort> findAllByPathwayAnalysisId(Integer pathwayAnalysisId, EntityGraph source); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/repository/PathwayAnalysisEntityRepository.java
src/main/java/org/ohdsi/webapi/pathway/repository/PathwayAnalysisEntityRepository.java
package org.ohdsi.webapi.pathway.repository; import com.cosium.spring.data.jpa.entity.graph.repository.EntityGraphJpaRepository; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Optional; public interface PathwayAnalysisEntityRepository extends EntityGraphJpaRepository<PathwayAnalysisEntity, Integer> { @Query("SELECT pa FROM pathway_analysis pa WHERE pa.name LIKE ?1 ESCAPE '\\'") List<PathwayAnalysisEntity> findAllByNameStartsWith(String pattern); Optional<PathwayAnalysisEntity> findByName(String name); @Query("SELECT COUNT(pa) FROM pathway_analysis pa WHERE pa.name = :name and pa.id <> :id") int getCountPAWithSameName(@Param("id") Integer id, @Param("name") String name); @Query("SELECT DISTINCT pa FROM pathway_analysis pa JOIN FETCH pa.tags t WHERE lower(t.name) in :tagNames") List<PathwayAnalysisEntity> findByTags(@Param("tagNames") List<String> tagNames); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/repository/PathwayAnalysisGenerationRepository.java
src/main/java/org/ohdsi/webapi/pathway/repository/PathwayAnalysisGenerationRepository.java
package org.ohdsi.webapi.pathway.repository; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph; import com.cosium.spring.data.jpa.entity.graph.repository.EntityGraphJpaRepository; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisGenerationEntity; import java.util.List; import java.util.Optional; public interface PathwayAnalysisGenerationRepository extends EntityGraphJpaRepository<PathwayAnalysisGenerationEntity, Long> { Optional<PathwayAnalysisGenerationEntity> findById(Long pathwayAnalysisId, EntityGraph entityGraph); List<PathwayAnalysisGenerationEntity> findAllByPathwayAnalysisId(Integer pathwayAnalysisId, EntityGraph entityGraph); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisToPathwayAnalysisDTOConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisToPathwayAnalysisDTOConverter.java
package org.ohdsi.webapi.pathway.converter; import com.odysseusinc.arachne.commons.utils.ConverterUtils; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; @Component public class PathwayAnalysisToPathwayAnalysisDTOConverter extends BasePathwayAnalysisToPathwayAnalysisDTOConverter<PathwayAnalysisDTO> { @Autowired private ConverterUtils converterUtils; @Override public void doConvert(PathwayAnalysisEntity pathwayAnalysis, PathwayAnalysisDTO target) { super.doConvert(pathwayAnalysis, target); target.setEventCohorts(converterUtils.convertList(new ArrayList<>(pathwayAnalysis.getEventCohorts()), PathwayCohortDTO.class)); target.setTargetCohorts(converterUtils.convertList(new ArrayList<>(pathwayAnalysis.getTargetCohorts()), PathwayCohortDTO.class)); } @Override protected PathwayAnalysisDTO createResultObject() { return new PathwayAnalysisDTO(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortExportDTOToCohortDefinitionConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortExportDTOToCohortDefinitionConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.analysis.Cohort; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionDetails; import org.ohdsi.webapi.cohortdefinition.converter.BaseCohortDTOToCohortDefinitionConverter; import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.ohdsi.webapi.pathway.dto.PathwayCohortExportDTO; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Component; @Component public class PathwayCohortExportDTOToCohortDefinitionConverter extends BaseCohortDTOToCohortDefinitionConverter<PathwayCohortExportDTO> { private String convertExpression(final Cohort source) { return Utils.serialize(source.getExpression()); } @Override protected void doConvert(PathwayCohortExportDTO source, CohortDefinition target) { super.doConvert(source, target); if (source.getExpression() != null) { final CohortDefinitionDetails details = new CohortDefinitionDetails(); final String expression = convertExpression(source); details.setExpression(expression); target.setDetails(details); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortDTOToPathwayTargetCohortConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortDTOToPathwayTargetCohortConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.webapi.pathway.domain.PathwayTargetCohort; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Component; @Component public class PathwayCohortDTOToPathwayTargetCohortConverter extends BasePathwayCohortDTOToPathwayCohortConverter<PathwayCohortDTO, PathwayTargetCohort> { public PathwayCohortDTOToPathwayTargetCohortConverter(ConversionService conversionService) { super(conversionService); } @Override protected PathwayTargetCohort getResultObject() { return new PathwayTargetCohort(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortDTOToCohortDefinitionConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortDTOToCohortDefinitionConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.webapi.cohortdefinition.converter.BaseCohortDTOToCohortDefinitionConverter; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.springframework.stereotype.Component; @Component public class PathwayCohortDTOToCohortDefinitionConverter extends BaseCohortDTOToCohortDefinitionConverter<PathwayCohortDTO> { }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayVersionToPathwayVersionFullDTOConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayVersionToPathwayVersionFullDTOConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter; import org.ohdsi.webapi.exception.ConversionAtlasException; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayCohort; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import org.ohdsi.webapi.pathway.domain.PathwayTargetCohort; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.ohdsi.webapi.pathway.dto.PathwayVersionFullDTO; import org.ohdsi.webapi.pathway.repository.PathwayAnalysisEntityRepository; import org.ohdsi.webapi.service.CohortDefinitionService; import org.ohdsi.webapi.util.ExceptionUtils; import org.ohdsi.webapi.versioning.domain.PathwayVersion; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Component public class PathwayVersionToPathwayVersionFullDTOConverter extends BaseConversionServiceAwareConverter<PathwayVersion, PathwayVersionFullDTO> { @Autowired private PathwayAnalysisEntityRepository analysisRepository; @Autowired private CohortDefinitionService cohortService; @Override public PathwayVersionFullDTO convert(PathwayVersion source) { PathwayAnalysisEntity def = this.analysisRepository.findOne(source.getAssetId().intValue()); ExceptionUtils.throwNotFoundExceptionIfNull(def, String.format("There is no pathway analysis with id = %d.", source.getAssetId())); PathwayAnalysisExportDTO exportDTO = Utils.deserialize(source.getAssetJson(), PathwayAnalysisExportDTO.class); PathwayAnalysisEntity entity = conversionService.convert(exportDTO, PathwayAnalysisEntity.class); entity.setId(def.getId()); entity.setTags(def.getTags()); entity.setName(def.getName()); entity.setCreatedBy(def.getCreatedBy()); entity.setCreatedDate(def.getCreatedDate()); entity.setModifiedBy(def.getModifiedBy()); entity.setModifiedDate(def.getModifiedDate()); entity.setEventCohorts(getCohorts(entity.getEventCohorts(), PathwayEventCohort.class)); entity.setTargetCohorts(getCohorts(entity.getTargetCohorts(), PathwayTargetCohort.class)); PathwayVersionFullDTO target = new PathwayVersionFullDTO(); target.setVersionDTO(conversionService.convert(source, VersionDTO.class)); target.setEntityDTO(conversionService.convert(entity, PathwayAnalysisDTO.class)); return target; } private <T extends PathwayCohort> Set<T> getCohorts(Set<T> pathwayCohorts, Class<T> clazz) { List<Integer> cohortIds = pathwayCohorts.stream() .map(c -> c.getCohortDefinition().getId()) .collect(Collectors.toList()); List<CohortDefinition> cohorts = cohortService.getCohorts(cohortIds); if (cohorts.size() != cohortIds.size()) { throw new ConversionAtlasException("Could not load version because it contains deleted cohorts"); } return cohorts.stream() .map(c -> conversionService.convert(c, PathwayCohortDTO.class)) .map(c -> conversionService.convert(c, clazz)) .collect(Collectors.toSet()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisToPathwayAnalysisExportDTOConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisToPathwayAnalysisExportDTOConverter.java
package org.ohdsi.webapi.pathway.converter; import com.odysseusinc.arachne.commons.utils.ConverterUtils; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.ohdsi.webapi.pathway.dto.PathwayCohortExportDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; @Component public class PathwayAnalysisToPathwayAnalysisExportDTOConverter extends BasePathwayAnalysisToPathwayAnalysisDTOConverter<PathwayAnalysisExportDTO> { @Autowired private ConverterUtils converterUtils; @Override public void doConvert(PathwayAnalysisEntity pathwayAnalysis, PathwayAnalysisExportDTO target) { super.doConvert(pathwayAnalysis, target); target.setEventCohorts(converterUtils.convertList(new ArrayList<>(pathwayAnalysis.getEventCohorts()), PathwayCohortExportDTO.class)); target.setTargetCohorts(converterUtils.convertList(new ArrayList<>(pathwayAnalysis.getTargetCohorts()), PathwayCohortExportDTO.class)); } @Override protected PathwayAnalysisExportDTO createResultObject() { return new PathwayAnalysisExportDTO(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortExportDTOToPathwayEventCohortConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortExportDTOToPathwayEventCohortConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import org.ohdsi.webapi.pathway.dto.PathwayCohortExportDTO; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Component; @Component public class PathwayCohortExportDTOToPathwayEventCohortConverter extends BasePathwayCohortDTOToPathwayCohortConverter<PathwayCohortExportDTO, PathwayEventCohort> { public PathwayCohortExportDTOToPathwayEventCohortConverter(ConversionService conversionService) { super(conversionService); } @Override protected PathwayEventCohort getResultObject() { return new PathwayEventCohort(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortDTOToPathwayEventCohortConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortDTOToPathwayEventCohortConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Component; @Component public class PathwayCohortDTOToPathwayEventCohortConverter extends BasePathwayCohortDTOToPathwayCohortConverter<PathwayCohortDTO, PathwayEventCohort> { public PathwayCohortDTOToPathwayEventCohortConverter(ConversionService conversionService) { super(conversionService); } @Override protected PathwayEventCohort getResultObject() { return new PathwayEventCohort(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/BasePathwayCohortToPathwayCohortDTOConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/BasePathwayCohortToPathwayCohortDTOConverter.java
package org.ohdsi.webapi.pathway.converter; import org.apache.commons.lang3.StringUtils; import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter; import org.ohdsi.webapi.pathway.domain.PathwayCohort; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; public abstract class BasePathwayCohortToPathwayCohortDTOConverter<T extends PathwayCohortDTO> extends BaseConversionServiceAwareConverter<PathwayCohort, T> { @Override public T convert(PathwayCohort source) { T result = getResultObject(); result.setId(source.getCohortDefinition().getId()); result.setName(StringUtils.trim(source.getName())); result.setDescription(source.getCohortDefinition().getDescription()); result.setPathwayCohortId(source.getId()); return result; } protected abstract T getResultObject(); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/CohortDefinitionToPathwayCohortDTOConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/CohortDefinitionToPathwayCohortDTOConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.webapi.cohortdefinition.converter.BaseCohortDefinitionToCohortMetadataDTOConverter; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.springframework.stereotype.Component; @Component public class CohortDefinitionToPathwayCohortDTOConverter extends BaseCohortDefinitionToCohortMetadataDTOConverter<PathwayCohortDTO> { @Override protected PathwayCohortDTO createResultObject() { return new PathwayCohortDTO(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortToPathwayCohortExportDTOConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortToPathwayCohortExportDTOConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.webapi.pathway.domain.PathwayCohort; import org.ohdsi.webapi.pathway.dto.PathwayCohortExportDTO; import org.springframework.stereotype.Component; @Component public class PathwayCohortToPathwayCohortExportDTOConverter extends BasePathwayCohortToPathwayCohortDTOConverter<PathwayCohortExportDTO> { @Override public PathwayCohortExportDTO convert(PathwayCohort source) { PathwayCohortExportDTO dto = super.convert(source); dto.setExpressionType(source.getCohortDefinition().getExpressionType()); dto.setExpression(source.getCohortDefinition().getExpression()); return dto; } @Override protected PathwayCohortExportDTO getResultObject() { return new PathwayCohortExportDTO(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortExportDTOToPathwayTargetCohortConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortExportDTOToPathwayTargetCohortConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.webapi.pathway.domain.PathwayTargetCohort; import org.ohdsi.webapi.pathway.dto.PathwayCohortExportDTO; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Component; @Component public class PathwayCohortExportDTOToPathwayTargetCohortConverter extends BasePathwayCohortDTOToPathwayCohortConverter<PathwayCohortExportDTO, PathwayTargetCohort> { public PathwayCohortExportDTOToPathwayTargetCohortConverter(ConversionService conversionService) { super(conversionService); } @Override protected PathwayTargetCohort getResultObject() { return new PathwayTargetCohort(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisExportDTOToPathwayAnalysisEntityConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisExportDTOToPathwayAnalysisEntityConverter.java
package org.ohdsi.webapi.pathway.converter; import com.odysseusinc.arachne.commons.utils.ConverterUtils; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import org.ohdsi.webapi.pathway.domain.PathwayTargetCohort; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashSet; @Component public class PathwayAnalysisExportDTOToPathwayAnalysisEntityConverter extends BasePathwayAnalysisDTOToPathwayAnalysisConverter<PathwayAnalysisExportDTO, PathwayAnalysisEntity> { @Autowired private ConverterUtils converterUtils; @Override public void doConvert(PathwayAnalysisExportDTO source, PathwayAnalysisEntity target) { super.doConvert(source, target); target.setEventCohorts(new HashSet<>(converterUtils.convertList(source.getEventCohorts(), PathwayEventCohort.class))); target.setTargetCohorts(new HashSet<>(converterUtils.convertList(source.getTargetCohorts(), PathwayTargetCohort.class))); } @Override protected PathwayAnalysisEntity createResultObject() { return new PathwayAnalysisEntity(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/SerializedPathwayAnalysisToPathwayAnalysisConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/SerializedPathwayAnalysisToPathwayAnalysisConverter.java
package org.ohdsi.webapi.pathway.converter; import com.fasterxml.jackson.core.type.TypeReference; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.springframework.core.convert.ConversionService; import javax.persistence.AttributeConverter; public class SerializedPathwayAnalysisToPathwayAnalysisConverter implements AttributeConverter<PathwayAnalysisEntity, String> { private static ConversionService conversionService; public static void setConversionService(ConversionService cs) { conversionService = cs; } @Override public String convertToDatabaseColumn(PathwayAnalysisEntity data) { PathwayAnalysisExportDTO exportDTO = conversionService.convert(data, PathwayAnalysisExportDTO.class); return Utils.serialize(exportDTO); } @Override public PathwayAnalysisEntity convertToEntityAttribute(String data) { TypeReference<PathwayAnalysisExportDTO> typeRef = new TypeReference<PathwayAnalysisExportDTO>() {}; return conversionService.convert(Utils.deserialize(data, typeRef), PathwayAnalysisEntity.class); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/BasePathwayAnalysisToPathwayAnalysisDTOConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/BasePathwayAnalysisToPathwayAnalysisDTOConverter.java
package org.ohdsi.webapi.pathway.converter; import org.apache.commons.lang3.StringUtils; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.dto.BasePathwayAnalysisDTO; import org.ohdsi.webapi.service.converters.BaseCommonEntityExtToDTOExtConverter; import org.ohdsi.webapi.tag.dto.TagDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; public abstract class BasePathwayAnalysisToPathwayAnalysisDTOConverter<T extends BasePathwayAnalysisDTO> extends BaseCommonEntityExtToDTOExtConverter<PathwayAnalysisEntity, T> { @Autowired protected ConversionService conversionService; @Override public void doConvert(PathwayAnalysisEntity source, T target) { target.setId(source.getId()); target.setName(StringUtils.trim(source.getName())); target.setCombinationWindow(source.getCombinationWindow()); target.setMinSegmentLength(source.getMinSegmentLength()); target.setMinCellCount(source.getMinCellCount()); target.setDescription(source.getDescription()); target.setMaxDepth(source.getMaxDepth()); target.setAllowRepeats(source.isAllowRepeats()); target.setHashCode(source.getHashCode()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/BasePathwayAnalysisDTOToPathwayAnalysisConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/BasePathwayAnalysisDTOToPathwayAnalysisConverter.java
package org.ohdsi.webapi.pathway.converter; import org.apache.commons.lang3.StringUtils; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.dto.BasePathwayAnalysisDTO; import org.ohdsi.webapi.service.converters.BaseCommonDTOExtToEntityExtConverter; public abstract class BasePathwayAnalysisDTOToPathwayAnalysisConverter<S extends BasePathwayAnalysisDTO, T extends PathwayAnalysisEntity> extends BaseCommonDTOExtToEntityExtConverter<S, T> { @Override protected void doConvert(S source, T target) { target.setId(source.getId()); target.setName(StringUtils.trim(source.getName())); target.setCombinationWindow(source.getCombinationWindow()); target.setMinSegmentLength(source.getMinSegmentLength()); target.setMinCellCount(source.getMinCellCount()); target.setDescription(source.getDescription()); target.setMaxDepth(source.getMaxDepth()); target.setAllowRepeats(source.isAllowRepeats()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/BasePathwayCohortDTOToPathwayCohortConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/BasePathwayCohortDTOToPathwayCohortConverter.java
package org.ohdsi.webapi.pathway.converter; import org.apache.commons.lang3.StringUtils; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter; import org.ohdsi.webapi.pathway.domain.PathwayCohort; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.springframework.core.convert.ConversionService; public abstract class BasePathwayCohortDTOToPathwayCohortConverter<S extends PathwayCohortDTO, R extends PathwayCohort> extends BaseConversionServiceAwareConverter<S, R> { private ConversionService conversionService; public BasePathwayCohortDTOToPathwayCohortConverter(ConversionService conversionService) { this.conversionService = conversionService; } @Override public R convert(S source) { R result = getResultObject(); result.setId(source.getPathwayCohortId()); result.setName(StringUtils.trim(source.getName())); result.setCohortDefinition(convertCohort(source)); return result; } protected abstract R getResultObject(); protected CohortDefinition convertCohort(S source) { return conversionService.convert(source, CohortDefinition.class); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortToPathwayCohortDTOConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayCohortToPathwayCohortDTOConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.webapi.pathway.dto.PathwayCohortDTO; import org.springframework.stereotype.Component; @Component public class PathwayCohortToPathwayCohortDTOConverter extends BasePathwayCohortToPathwayCohortDTOConverter<PathwayCohortDTO> { @Override protected PathwayCohortDTO getResultObject() { return new PathwayCohortDTO(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisDTOToPathwayAnalysisEntityConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisDTOToPathwayAnalysisEntityConverter.java
package org.ohdsi.webapi.pathway.converter; import com.odysseusinc.arachne.commons.utils.ConverterUtils; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayEventCohort; import org.ohdsi.webapi.pathway.domain.PathwayTargetCohort; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashSet; @Component public class PathwayAnalysisDTOToPathwayAnalysisEntityConverter extends BasePathwayAnalysisDTOToPathwayAnalysisConverter<PathwayAnalysisDTO, PathwayAnalysisEntity> { @Autowired private ConverterUtils converterUtils; @Override public void doConvert(PathwayAnalysisDTO source, PathwayAnalysisEntity target) { super.doConvert(source, target); target.setEventCohorts(new HashSet<>(converterUtils.convertList(source.getEventCohorts(), PathwayEventCohort.class))); target.setTargetCohorts(new HashSet<>(converterUtils.convertList(source.getTargetCohorts(), PathwayTargetCohort.class))); } @Override protected PathwayAnalysisEntity createResultObject() { return new PathwayAnalysisEntity(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisToPathwayVersionConverter.java
src/main/java/org/ohdsi/webapi/pathway/converter/PathwayAnalysisToPathwayVersionConverter.java
package org.ohdsi.webapi.pathway.converter; import org.ohdsi.analysis.Utils; import org.ohdsi.analysis.pathway.design.PathwayAnalysis; import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter; import org.ohdsi.webapi.ircalc.IncidenceRateAnalysis; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.ohdsi.webapi.versioning.domain.IRVersion; import org.ohdsi.webapi.versioning.domain.PathwayVersion; import org.springframework.stereotype.Component; @Component public class PathwayAnalysisToPathwayVersionConverter extends BaseConversionServiceAwareConverter<PathwayAnalysisEntity, PathwayVersion> { @Override public PathwayVersion convert(PathwayAnalysisEntity source) { PathwayAnalysisExportDTO exportDTO = conversionService.convert(source, PathwayAnalysisExportDTO.class); String data = Utils.serialize(exportDTO); PathwayVersion target = new PathwayVersion(); target.setAssetId(source.getId()); target.setAssetJson(data); return target; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/Role.java
src/main/java/org/ohdsi/webapi/user/Role.java
package org.ohdsi.webapi.user; import com.fasterxml.jackson.annotation.JsonProperty; import org.eclipse.collections.impl.block.factory.Comparators; import org.ohdsi.webapi.shiro.Entities.RoleEntity; import java.util.Comparator; public class Role implements Comparable<Role> { @JsonProperty("id") public Long id; @JsonProperty("role") public String role; @JsonProperty("defaultImported") public boolean defaultImported; @JsonProperty("systemRole") public boolean systemRole; public Role() {} public Role(String role) { this.role = role; } public Role(RoleEntity roleEntity) { this.id = roleEntity.getId(); this.role = roleEntity.getName(); this.systemRole = roleEntity.isSystemRole(); } public Role(RoleEntity roleEntity, boolean defaultImported) { this(roleEntity); this.defaultImported = defaultImported; } @Override public int compareTo(Role o) { Comparator c = Comparators.naturalOrder(); if (this.id == null && o.id == null) return c.compare(this.role, o.role); else return c.compare(this.id, o.id); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/dto/UserDTO.java
src/main/java/org/ohdsi/webapi/user/dto/UserDTO.java
package org.ohdsi.webapi.user.dto; import java.io.Serializable; public class UserDTO implements Serializable { private Long id; private String name; private String login; public UserDTO() { } // For deserialization of old expressions public UserDTO(String login) { this.login = login; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getLogin() { return login; } public void setLogin(final String login) { this.login = login; } public Long getId() { return id; } public void setId(final Long id) { this.id = id; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/converter/UserEntityToUserDTOConverter.java
src/main/java/org/ohdsi/webapi/user/converter/UserEntityToUserDTOConverter.java
package org.ohdsi.webapi.user.converter; import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter; import org.ohdsi.webapi.shiro.Entities.UserEntity; import org.ohdsi.webapi.user.dto.UserDTO; import org.springframework.stereotype.Component; @Component public class UserEntityToUserDTOConverter extends BaseConversionServiceAwareConverter<UserEntity, UserDTO> { @Override public UserDTO convert(UserEntity userEntity) { if (userEntity == null) { return null; } final UserDTO dto = new UserDTO(); dto.setId(userEntity.getId()); dto.setName(userEntity.getName()); dto.setLogin(userEntity.getLogin()); return dto; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/UserImportController.java
src/main/java/org/ohdsi/webapi/user/importer/UserImportController.java
package org.ohdsi.webapi.user.importer; import com.odysseusinc.scheduler.model.JobExecutingType; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.user.importer.converter.RoleGroupMappingConverter; import org.ohdsi.webapi.user.importer.dto.UserImportJobDTO; import org.ohdsi.webapi.user.importer.exception.JobAlreadyExistException; import org.ohdsi.webapi.user.importer.model.AtlasUserRoles; import org.ohdsi.webapi.user.importer.model.AuthenticationProviders; import org.ohdsi.webapi.user.importer.model.ConnectionInfo; import org.ohdsi.webapi.user.importer.model.LdapGroup; import org.ohdsi.webapi.user.importer.model.LdapProviderType; import org.ohdsi.webapi.user.importer.model.RoleGroupEntity; import org.ohdsi.webapi.user.importer.model.RoleGroupMapping; import org.ohdsi.webapi.user.importer.model.UserImportJob; import org.ohdsi.webapi.user.importer.service.UserImportJobService; import org.ohdsi.webapi.user.importer.service.UserImportService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.stereotype.Controller; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.NotAcceptableException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import static org.ohdsi.webapi.Constants.JOB_IS_ALREADY_SCHEDULED; @Controller @Path("/") public class UserImportController { private static final Logger logger = LoggerFactory.getLogger(UserImportController.class); @Autowired private UserImportService userImportService; @Autowired private UserImportJobService userImportJobService; @Autowired private GenericConversionService conversionService; @Value("${security.ad.url}") private String adUrl; @Value("${security.ldap.url}") private String ldapUrl; @GET @Path("user/providers") @Produces(MediaType.APPLICATION_JSON) public AuthenticationProviders getAuthenticationProviders() { AuthenticationProviders providers = new AuthenticationProviders(); providers.setAdUrl(adUrl); providers.setLdapUrl(ldapUrl); return providers; } @GET @Path("user/import/{type}/test") @Produces(MediaType.APPLICATION_JSON) public Response testConnection(@PathParam("type") String type) { LdapProviderType provider = LdapProviderType.fromValue(type); ConnectionInfo result = new ConnectionInfo(); userImportService.testConnection(provider); result.setState(ConnectionInfo.ConnectionState.SUCCESS); result.setMessage("Connection success"); return Response.ok().entity(result).build(); } @GET @Path("user/import/{type}/groups") @Produces(MediaType.APPLICATION_JSON) public List<LdapGroup> findGroups(@PathParam("type") String type, @QueryParam("search") String searchStr) { LdapProviderType provider = LdapProviderType.fromValue(type); return userImportService.findGroups(provider, searchStr); } @POST @Path("user/import/{type}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public List<AtlasUserRoles> findDirectoryUsers(@PathParam("type") String type, RoleGroupMapping mapping){ LdapProviderType provider = LdapProviderType.fromValue(type); return userImportService.findUsers(provider, mapping); } @POST @Path("user/import") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public UserImportJobDTO importUsers(List<AtlasUserRoles> users, @QueryParam("provider") String provider, @DefaultValue("TRUE") @QueryParam("preserve") Boolean preserveRoles) { LdapProviderType providerType = LdapProviderType.fromValue(provider); UserImportJobDTO jobDto = new UserImportJobDTO(); jobDto.setProviderType(providerType); jobDto.setPreserveRoles(preserveRoles); jobDto.setEnabled(true); jobDto.setStartDate(getJobStartDate()); jobDto.setFrequency(JobExecutingType.ONCE); jobDto.setRecurringTimes(0); if (users != null) { jobDto.setUserRoles(Utils.serialize(users)); } try { UserImportJob job = conversionService.convert(jobDto, UserImportJob.class); UserImportJob created = userImportJobService.createJob(job); return conversionService.convert(created, UserImportJobDTO.class); } catch (JobAlreadyExistException e) { throw new NotAcceptableException(String.format(JOB_IS_ALREADY_SCHEDULED, jobDto.getProviderType())); } } @POST @Path("user/import/{type}/mapping") @Consumes(MediaType.APPLICATION_JSON) public Response saveMapping(@PathParam("type") String type, RoleGroupMapping mapping) { LdapProviderType providerType = LdapProviderType.fromValue(type); List<RoleGroupEntity> mappingEntities = RoleGroupMappingConverter.convertRoleGroupMapping(mapping); userImportService.saveRoleGroupMapping(providerType, mappingEntities); return Response.ok().build(); } @GET @Path("user/import/{type}/mapping") @Produces(MediaType.APPLICATION_JSON) public RoleGroupMapping getMapping(@PathParam("type") String type) { LdapProviderType providerType = LdapProviderType.fromValue(type); List<RoleGroupEntity> mappingEntities = userImportService.getRoleGroupMapping(providerType); return RoleGroupMappingConverter.convertRoleGroupMapping(type, mappingEntities); } private Date getJobStartDate() { Calendar calendar = GregorianCalendar.getInstance(); // Job will be started in five seconds after now calendar.add(Calendar.SECOND, 5); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/UserImportJobController.java
src/main/java/org/ohdsi/webapi/user/importer/UserImportJobController.java
package org.ohdsi.webapi.user.importer; import com.odysseusinc.scheduler.exception.JobNotFoundException; import org.ohdsi.webapi.user.importer.dto.JobHistoryItemDTO; import org.ohdsi.webapi.user.importer.dto.UserImportJobDTO; import org.ohdsi.webapi.user.importer.exception.JobAlreadyExistException; import org.ohdsi.webapi.user.importer.model.UserImportJob; import org.ohdsi.webapi.user.importer.service.UserImportJobService; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RestController; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.NotAcceptableException; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.stream.Collectors; import static org.ohdsi.webapi.Constants.JOB_IS_ALREADY_SCHEDULED; /** * REST Services related to importing user information * from an external source (i.e. Active Directory) * * @summary User Import */ @RestController @Path("/user/import/job") @Transactional public class UserImportJobController { private final UserImportJobService jobService; private final GenericConversionService conversionService; public UserImportJobController(UserImportJobService jobService, GenericConversionService conversionService) { this.jobService = jobService; this.conversionService = conversionService; } /** * Create a user import job * * @summary Create user import job * @param jobDTO The user import information * @return The job information */ @POST @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public UserImportJobDTO createJob(UserImportJobDTO jobDTO) { UserImportJob job = conversionService.convert(jobDTO, UserImportJob.class); try { UserImportJob created = jobService.createJob(job); return conversionService.convert(created, UserImportJobDTO.class); } catch(JobAlreadyExistException e) { throw new NotAcceptableException(String.format(JOB_IS_ALREADY_SCHEDULED, job.getProviderType())); } } /** * Update a user import job * * @summary Update user import job * @param jobId The job ID * @param jobDTO The user import information * @return The job information */ @PUT @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public UserImportJobDTO updateJob(@PathParam("id") Long jobId, UserImportJobDTO jobDTO) { UserImportJob job = conversionService.convert(jobDTO, UserImportJob.class); try { job.setId(jobId); UserImportJob updated = jobService.updateJob(job); return conversionService.convert(updated, UserImportJobDTO.class); } catch (JobNotFoundException e) { throw new NotFoundException(); } } /** * Get the user import job list * * @summary Get user import jobs * @return The list of user import jobs */ @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @Transactional public List<UserImportJobDTO> listJobs() { return jobService.getJobs().stream() .map(job -> conversionService.convert(job, UserImportJobDTO.class)) .peek(job -> jobService.getLatestHistoryItem(job.getId()) .ifPresent(item -> job.setLastExecuted(item.getEndTime()))) .collect(Collectors.toList()); } /** * Get user import job by ID * * @summary Get user import job by ID * @param id The job ID * @return The user import job */ @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public UserImportJobDTO getJob(@PathParam("id") Long id) { return jobService.getJob(id).map(job -> conversionService.convert(job, UserImportJobDTO.class)) .orElseThrow(NotFoundException::new); } /** * Delete user import job by ID * * @summary Delete user import job by ID * @param id The job ID * @return The user import job */ @DELETE @Path("/{id}") public Response deleteJob(@PathParam("id") Long id) { UserImportJob job = jobService.getJob(id).orElseThrow(NotFoundException::new); jobService.delete(job); return Response.ok().build(); } /** * Get the user import job history * * @summary Get import history * @param id The job ID * @return The job history */ @GET @Path("/{id}/history") @Produces(MediaType.APPLICATION_JSON) public List<JobHistoryItemDTO> getImportHistory(@PathParam("id") Long id) { return jobService.getJobHistoryItems(id) .map(item -> conversionService.convert(item, JobHistoryItemDTO.class)) .collect(Collectors.toList()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/dto/JobHistoryItemDTO.java
src/main/java/org/ohdsi/webapi/user/importer/dto/JobHistoryItemDTO.java
package org.ohdsi.webapi.user.importer.dto; import org.ohdsi.webapi.user.importer.model.LdapProviderType; import java.util.Date; public class JobHistoryItemDTO { private Long id; private Date startTime; private Date endTime; private String status; private String exitCode; private String exitMessage; private String author; private LdapProviderType providerType; private String jobTitle; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getExitCode() { return exitCode; } public void setExitCode(String exitCode) { this.exitCode = exitCode; } public String getExitMessage() { return exitMessage; } public void setExitMessage(String exitMessage) { this.exitMessage = exitMessage; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public LdapProviderType getProviderType() { return providerType; } public void setProviderType(LdapProviderType providerType) { this.providerType = providerType; } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/dto/UserImportJobDTO.java
src/main/java/org/ohdsi/webapi/user/importer/dto/UserImportJobDTO.java
package org.ohdsi.webapi.user.importer.dto; import com.odysseusinc.scheduler.api.v1.dto.ArachneJobDTO; import org.ohdsi.webapi.user.importer.model.LdapProviderType; import org.ohdsi.webapi.user.importer.model.RoleGroupMapping; import java.util.Date; public class UserImportJobDTO extends ArachneJobDTO { private LdapProviderType providerType; private Boolean preserveRoles; private String userRoles; private Date lastExecuted; private Date nextExecution; private Date startDate; private RoleGroupMapping roleGroupMapping; public RoleGroupMapping getRoleGroupMapping() { return roleGroupMapping; } public void setRoleGroupMapping(RoleGroupMapping roleGroupMapping) { this.roleGroupMapping = roleGroupMapping; } public LdapProviderType getProviderType() { return providerType; } public void setProviderType(LdapProviderType providerType) { this.providerType = providerType; } public Boolean getPreserveRoles() { return preserveRoles; } public void setPreserveRoles(Boolean preserveRoles) { this.preserveRoles = preserveRoles; } public Date getLastExecuted() { return lastExecuted; } public void setLastExecuted(Date lastExecuted) { this.lastExecuted = lastExecuted; } public Date getNextExecution() { return nextExecution; } public void setNextExecution(Date nextExecution) { this.nextExecution = nextExecution; } @Override public Date getStartDate() { return startDate; } @Override public void setStartDate(Date startDate) { this.startDate = startDate; } public String getUserRoles() { return userRoles; } public void setUserRoles(String userRoles) { this.userRoles = userRoles; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/service/DeleteRoleEventHandler.java
src/main/java/org/ohdsi/webapi/user/importer/service/DeleteRoleEventHandler.java
package org.ohdsi.webapi.user.importer.service; import com.odysseusinc.logging.event.DeleteRoleEvent; import org.ohdsi.webapi.user.importer.repository.RoleGroupRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class DeleteRoleEventHandler implements ApplicationListener<DeleteRoleEvent> { @Autowired private RoleGroupRepository roleGroupRepository; @Override public void onApplicationEvent(final DeleteRoleEvent event) { roleGroupRepository.deleteByRoleId(event.getId()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/service/BaseUserImportTasklet.java
src/main/java/org/ohdsi/webapi/user/importer/service/BaseUserImportTasklet.java
package org.ohdsi.webapi.user.importer.service; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.common.generation.TransactionalTasklet; import org.ohdsi.webapi.user.importer.model.UserImportJob; import org.slf4j.Logger; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.transaction.support.TransactionTemplate; import java.util.Map; public abstract class BaseUserImportTasklet<T> extends TransactionalTasklet<T> { protected final UserImportService userImportService; public BaseUserImportTasklet(Logger log, TransactionTemplate transactionTemplate, UserImportService userImportService) { super(log, transactionTemplate); this.userImportService = userImportService; } @Override protected T doTask(ChunkContext chunkContext) { Map<String,Object> jobParameters = chunkContext.getStepContext().getJobParameters(); Long userImportId = Long.valueOf(jobParameters.get(Constants.Params.USER_IMPORT_ID).toString()); UserImportJob userImportJob = userImportService.getImportUserJob(userImportId); return doUserImportTask(chunkContext, userImportJob); } protected abstract T doUserImportTask(ChunkContext chunkContext, UserImportJob userImportJob); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/service/UserImportService.java
src/main/java/org/ohdsi/webapi/user/importer/service/UserImportService.java
package org.ohdsi.webapi.user.importer.service; import org.ohdsi.webapi.user.importer.model.*; import java.util.List; public interface UserImportService { List<LdapGroup> findGroups(LdapProviderType providerType, String searchStr); List<AtlasUserRoles> findUsers(LdapProviderType providerType, RoleGroupMapping mapping); UserImportResult importUsers(List<AtlasUserRoles> users, LdapProviderType providerType, boolean preserveRoles); void saveRoleGroupMapping(LdapProviderType providerType, List<RoleGroupEntity> mappingEntities); List<RoleGroupEntity> getRoleGroupMapping(LdapProviderType providerType); void testConnection(LdapProviderType provider); UserImportJob getImportUserJob(Long userImportId); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/service/UserImportServiceImpl.java
src/main/java/org/ohdsi/webapi/user/importer/service/UserImportServiceImpl.java
package org.ohdsi.webapi.user.importer.service; import org.apache.commons.collections.CollectionUtils; import org.ohdsi.webapi.shiro.Entities.RoleEntity; import org.ohdsi.webapi.shiro.Entities.UserEntity; import org.ohdsi.webapi.shiro.Entities.UserOrigin; import org.ohdsi.webapi.shiro.Entities.UserRepository; import org.ohdsi.webapi.shiro.PermissionManager; import org.ohdsi.webapi.user.Role; import org.ohdsi.webapi.user.importer.model.AtlasUserRoles; import org.ohdsi.webapi.user.importer.model.LdapGroup; import org.ohdsi.webapi.user.importer.model.LdapProviderType; import org.ohdsi.webapi.user.importer.model.LdapUserImportStatus; import org.ohdsi.webapi.user.importer.model.RoleGroupEntity; import org.ohdsi.webapi.user.importer.model.RoleGroupMapping; import org.ohdsi.webapi.user.importer.model.RoleGroupsMap; import org.ohdsi.webapi.user.importer.model.UserImportJob; import org.ohdsi.webapi.user.importer.model.UserImportResult; import org.ohdsi.webapi.user.importer.providers.ActiveDirectoryProvider; import org.ohdsi.webapi.user.importer.providers.DefaultLdapProvider; import org.ohdsi.webapi.user.importer.providers.LdapProvider; import org.ohdsi.webapi.user.importer.repository.RoleGroupRepository; import org.ohdsi.webapi.user.importer.repository.UserImportJobRepository; import org.ohdsi.webapi.user.importer.utils.RoleGroupUtils; import org.ohdsi.webapi.util.UserUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.filter.AndFilter; import org.springframework.ldap.filter.EqualsFilter; import org.springframework.ldap.support.LdapUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static org.ohdsi.webapi.user.importer.providers.AbstractLdapProvider.OBJECTCLASS_ATTR; import static org.ohdsi.webapi.user.importer.providers.OhdsiLdapUtils.getCriteria; @Service @Transactional(readOnly = true) public class UserImportServiceImpl implements UserImportService { private static final Logger logger = LoggerFactory.getLogger(UserImportService.class); private final Map<LdapProviderType, LdapProvider> providersMap = new HashMap<>(); private final UserRepository userRepository; private final UserImportJobRepository userImportJobRepository; private final PermissionManager userManager; private final RoleGroupRepository roleGroupMappingRepository; @Value("${security.ad.default.import.group}#{T(java.util.Collections).emptyList()}") private List<String> defaultRoles; public UserImportServiceImpl(@Autowired(required = false) ActiveDirectoryProvider activeDirectoryProvider, @Autowired(required = false) DefaultLdapProvider ldapProvider, UserRepository userRepository, UserImportJobRepository userImportJobRepository, PermissionManager userManager, RoleGroupRepository roleGroupMappingRepository) { this.userRepository = userRepository; this.userImportJobRepository = userImportJobRepository; this.userManager = userManager; this.roleGroupMappingRepository = roleGroupMappingRepository; Optional.ofNullable(activeDirectoryProvider).ifPresent(provider -> providersMap.put(LdapProviderType.ACTIVE_DIRECTORY, provider)); Optional.ofNullable(ldapProvider).ifPresent(provider -> providersMap.put(LdapProviderType.LDAP, provider)); } protected Optional<LdapProvider> getProvider(LdapProviderType type) { return Optional.ofNullable(providersMap.get(type)); } @Override public List<LdapGroup> findGroups(LdapProviderType type, String searchStr) { LdapProvider provider = getProvider(type).orElseThrow(IllegalArgumentException::new); return provider.findGroups(searchStr); } @Override public List<AtlasUserRoles> findUsers(LdapProviderType providerType, RoleGroupMapping mapping) { LdapProvider provider = getProvider(providerType).orElseThrow(IllegalArgumentException::new); return provider.findUsers().stream() .map(user -> { AtlasUserRoles atlasUser = new AtlasUserRoles(); atlasUser.setDisplayName(user.getDisplayName()); atlasUser.setLogin(UserUtils.toLowerCase(user.getLogin())); List<Role> roles = user.getGroups().stream() .flatMap(g -> mapping.getRoleGroups() .stream() .filter(m -> m.getGroups().stream().anyMatch(group -> Objects.equals(g.getDistinguishedName(), group.getDistinguishedName()))) .map(RoleGroupsMap::getRole)) .distinct() .collect(Collectors.toList()); atlasUser.setRoles(roles); atlasUser.setStatus(getStatus(atlasUser)); return atlasUser; }) .filter(user -> !LdapUserImportStatus.EXISTS.equals(user.getStatus())) .collect(Collectors.toList()); } @Override @Transactional public UserImportResult importUsers(List<AtlasUserRoles> users, LdapProviderType providerType, boolean preserveRoles) { UserImportResult result = new UserImportResult(); UserOrigin userOrigin = UserOrigin.getFrom(providerType); users.forEach(user -> { String login = UserUtils.toLowerCase(user.getLogin()); Set<String> roles = user.getRoles().stream().map(role -> role.role).collect(Collectors.toSet()); roles.addAll(defaultRoles); try { UserEntity userEntity = userRepository.findByLogin(login); if (Objects.nonNull(userEntity)) { userEntity.setName(user.getDisplayName()); userEntity.setOrigin(userOrigin); if (LdapUserImportStatus.MODIFIED.equals(getStatus(userEntity, user.getRoles()))) { Set<RoleEntity> userRoles = userManager.getUserRoles(userEntity.getId()); if (!preserveRoles) { //Overrides assigned roles userRoles.stream().filter(role -> !role.getName().equalsIgnoreCase(login)).forEach(r -> { try { userManager.removeUserFromRole(r.getName(), userEntity.getLogin(), null); } catch (Exception e) { logger.warn("Failed to remove user {} from role {}", userEntity.getLogin(), r.getName(), e); } }); } else { //Filter roles that is already assigned roles = roles.stream() .filter(role -> userRoles.stream().noneMatch(ur -> Objects.equals(ur.getName(), role))) .collect(Collectors.toSet()); } roles.forEach(r -> { try { userManager.addUserToRole(r, userEntity.getLogin(), userOrigin); } catch (Exception e) { logger.error("Failed to add user {} to role {}", userEntity.getLogin(), r, e); } }); result.incUpdated(); } } else { userManager.registerUser(login, user.getDisplayName(), userOrigin, roles); result.incCreated(); } } catch (Exception e) { logger.error("Failed to register user {}", login, e); } }); userRepository.findByOrigin(userOrigin).stream() .filter(existingUser -> users.stream() .noneMatch(user -> UserUtils.toLowerCase(user.getLogin()).equals(existingUser.getLogin()))) .forEach(deletedUser -> deletedUser.getUserRoles().stream() .filter(role -> !role.getRole().getName().equalsIgnoreCase(deletedUser.getLogin())) .forEach(role -> userManager.removeUserFromRole(role.getRole().getName(), deletedUser.getLogin(), userOrigin))); return result; } @Override @Transactional public void saveRoleGroupMapping(LdapProviderType providerType, List<RoleGroupEntity> mappingEntities) { List<RoleGroupEntity> exists = roleGroupMappingRepository.findByProviderAndUserImportJobNull(providerType); List<RoleGroupEntity> deleted = RoleGroupUtils.findDeleted(exists, mappingEntities); List<RoleGroupEntity> created = RoleGroupUtils.findCreated(exists, mappingEntities); if (!deleted.isEmpty()) { roleGroupMappingRepository.delete(deleted); } if (!created.isEmpty()) { roleGroupMappingRepository.save(created); } } @Override public List<RoleGroupEntity> getRoleGroupMapping(LdapProviderType providerType) { return roleGroupMappingRepository.findByProviderAndUserImportJobNull(providerType); } @Override public void testConnection(LdapProviderType providerType) { LdapProvider provider = getProvider(providerType).orElseThrow(IllegalArgumentException::new); LdapTemplate ldapTemplate = provider.getLdapTemplate(); AndFilter filter = new AndFilter(); filter.and(getCriteria(OBJECTCLASS_ATTR, getProvider(providerType).orElseThrow(IllegalArgumentException::new).getGroupClasses())) .and(new EqualsFilter(provider.getLoginAttributeName(), provider.getPrincipal())); ldapTemplate.authenticate(LdapUtils.emptyLdapName(), filter.toString(), provider.getPassword()); } @Override public UserImportJob getImportUserJob(Long userImportId) { return userImportJobRepository.getOne(userImportId); } private LdapUserImportStatus getStatus(AtlasUserRoles atlasUser) { UserEntity userEntity = userRepository.findByLogin(atlasUser.getLogin()); return getStatus(userEntity, atlasUser.getRoles()); } private LdapUserImportStatus getStatus(UserEntity userEntity, List<Role> atlasUserRoles) { LdapUserImportStatus result = LdapUserImportStatus.NEW_USER; if (Objects.nonNull(userEntity)) { List<Long> atlasRoleIds = userEntity.getUserRoles().stream().map(userRole -> userRole.getRole().getId()).collect(Collectors.toList()); List<Long> mappedRoleIds = atlasUserRoles.stream().map(role -> role.id).collect(Collectors.toList()); result = CollectionUtils.isEqualCollection(atlasRoleIds, mappedRoleIds) ? LdapUserImportStatus.EXISTS : LdapUserImportStatus.MODIFIED; } return result; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/service/UserImportTasklet.java
src/main/java/org/ohdsi/webapi/user/importer/service/UserImportTasklet.java
package org.ohdsi.webapi.user.importer.service; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.user.importer.model.AtlasUserRoles; import org.ohdsi.webapi.user.importer.model.UserImportJob; import org.ohdsi.webapi.user.importer.model.UserImportResult; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.transaction.support.TransactionTemplate; import java.util.List; import java.util.Objects; public class UserImportTasklet extends BaseUserImportTasklet<UserImportResult> implements StepExecutionListener { private List<AtlasUserRoles> users; private UserImportResult result; public UserImportTasklet(TransactionTemplate transactionTemplate, UserImportService userImportService) { super(LoggerFactory.getLogger(UserImportTasklet.class), transactionTemplate, userImportService); } @Override protected UserImportResult doUserImportTask(ChunkContext chunkContext, UserImportJob userImportJob) { if (Objects.isNull(users)) { if (Objects.isNull(userImportJob.getUserRoles())) { throw new IllegalArgumentException("userRoles is required for user import task"); } users = Utils.deserialize(userImportJob.getUserRoles(), factory -> factory.constructCollectionType(List.class, AtlasUserRoles.class)); } return result = userImportService.importUsers(users, userImportJob.getProviderType(), userImportJob.getPreserveRoles()); } @Override protected void doAfter(StepContribution stepContribution, ChunkContext chunkContext) { if (Objects.nonNull(result)) { stepContribution.setExitStatus(new ExitStatus(ExitStatus.COMPLETED.getExitCode(), String.format("Created %d new users, updated %d users", result.getCreated(), result.getUpdated()))); } } @Override public void beforeStep(StepExecution stepExecution) { String userRolesJson = stepExecution.getJobExecution().getExecutionContext().getString(Constants.Params.USER_ROLES, null); if (Objects.nonNull(userRolesJson)){ users = Utils.deserialize(userRolesJson, factory -> factory.constructCollectionType(List.class, AtlasUserRoles.class)); } } @Override public ExitStatus afterStep(StepExecution stepExecution) { return null; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/service/UserImportJobService.java
src/main/java/org/ohdsi/webapi/user/importer/service/UserImportJobService.java
package org.ohdsi.webapi.user.importer.service; import com.odysseusinc.scheduler.service.BaseJobService; import org.ohdsi.webapi.user.importer.model.UserImportJob; import org.ohdsi.webapi.user.importer.model.UserImportJobHistoryItem; import java.util.List; import java.util.Optional; import java.util.stream.Stream; public interface UserImportJobService extends BaseJobService<UserImportJob> { List<UserImportJob> getJobs(); Optional<UserImportJob> getJob(Long id); Stream<UserImportJobHistoryItem> getJobHistoryItems(Long id); Optional<UserImportJobHistoryItem> getLatestHistoryItem(Long id); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/service/FindUsersToImportTasklet.java
src/main/java/org/ohdsi/webapi/user/importer/service/FindUsersToImportTasklet.java
package org.ohdsi.webapi.user.importer.service; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.user.importer.converter.RoleGroupMappingConverter; import org.ohdsi.webapi.user.importer.model.AtlasUserRoles; import org.ohdsi.webapi.user.importer.model.RoleGroupMapping; import org.ohdsi.webapi.user.importer.model.UserImportJob; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.transaction.support.TransactionTemplate; import java.util.List; public class FindUsersToImportTasklet extends BaseUserImportTasklet<List<AtlasUserRoles>> implements StepExecutionListener { private List<AtlasUserRoles> userRoles; public FindUsersToImportTasklet(TransactionTemplate transactionTemplate, UserImportService userImportService) { super(LoggerFactory.getLogger(FindUsersToImportTasklet.class), transactionTemplate, userImportService); } @Override protected List<AtlasUserRoles> doUserImportTask(ChunkContext chunkContext, UserImportJob userImportJob) { RoleGroupMapping roleGroupMapping = RoleGroupMappingConverter.convertRoleGroupMapping( userImportJob.getProviderType().toString(), userImportJob.getRoleGroupMapping()); userRoles = userImportService.findUsers(userImportJob.getProviderType(), roleGroupMapping); return userRoles; } @Override public void beforeStep(StepExecution stepExecution) { } @Override public ExitStatus afterStep(StepExecution stepExecution) { stepExecution.getJobExecution().getExecutionContext().putString(Constants.Params.USER_ROLES, Utils.serialize(userRoles)); return null; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/service/UserImportJobServiceImpl.java
src/main/java/org/ohdsi/webapi/user/importer/service/UserImportJobServiceImpl.java
package org.ohdsi.webapi.user.importer.service; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraphUtils; import com.cronutils.model.definition.CronDefinition; import com.odysseusinc.scheduler.model.ScheduledTask; import com.odysseusinc.scheduler.service.BaseJobServiceImpl; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.job.JobTemplate; import org.ohdsi.webapi.user.importer.model.LdapProviderType; import org.ohdsi.webapi.user.importer.model.RoleGroupEntity; import org.ohdsi.webapi.user.importer.model.UserImportJob; import org.ohdsi.webapi.user.importer.model.UserImportJobHistoryItem; import org.ohdsi.webapi.user.importer.repository.RoleGroupRepository; import org.ohdsi.webapi.user.importer.repository.UserImportJobHistoryItemRepository; import org.ohdsi.webapi.user.importer.repository.UserImportJobRepository; import org.ohdsi.webapi.user.importer.utils.RoleGroupUtils; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.TaskScheduler; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.PostConstruct; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.ohdsi.webapi.Constants.SYSTEM_USER; @Service @Transactional public class UserImportJobServiceImpl extends BaseJobServiceImpl<UserImportJob> implements UserImportJobService { private final UserImportService userImportService; private final UserImportJobRepository jobRepository; private final RoleGroupRepository roleGroupRepository; private final UserImportJobHistoryItemRepository jobHistoryItemRepository; private final TransactionTemplate transactionTemplate; private final StepBuilderFactory stepBuilderFactory; private final JobBuilderFactory jobBuilders; private final JobTemplate jobTemplate; private EntityGraph jobWithMappingEntityGraph = EntityGraphUtils.fromName("jobWithMapping"); public UserImportJobServiceImpl(TaskScheduler taskScheduler, CronDefinition cronDefinition, UserImportJobRepository jobRepository, UserImportService userImportService, RoleGroupRepository roleGroupRepository, UserImportJobHistoryItemRepository jobHistoryItemRepository, @Qualifier("transactionTemplateRequiresNew") TransactionTemplate transactionTemplate, StepBuilderFactory stepBuilderFactory, JobBuilderFactory jobBuilders, JobTemplate jobTemplate) { super(taskScheduler, cronDefinition, jobRepository); this.userImportService = userImportService; this.jobRepository = jobRepository; this.roleGroupRepository = roleGroupRepository; this.jobHistoryItemRepository = jobHistoryItemRepository; this.transactionTemplate = transactionTemplate; this.stepBuilderFactory = stepBuilderFactory; this.jobBuilders = jobBuilders; this.jobTemplate = jobTemplate; } @PostConstruct public void initializeJobs() { transactionTemplate.execute(transactionStatus -> { reassignAllJobs(); return null; }); } @Override protected void saveAdditionalFields(UserImportJob job) { if (job.getRoleGroupMapping() != null && !job.getRoleGroupMapping().isEmpty()) { job.getRoleGroupMapping().forEach(mapping -> mapping.setUserImportJob(job)); roleGroupRepository.save(job.getRoleGroupMapping()); } } @Override protected List<UserImportJob> getActiveJobs() { return jobRepository.findAllByEnabledTrueAndIsClosedFalse(jobWithMappingEntityGraph); } @Override protected void updateAdditionalFields(UserImportJob exists, UserImportJob updated) { exists.setProviderType(updated.getProviderType()); List<RoleGroupEntity> existMapping = exists.getRoleGroupMapping(); List<RoleGroupEntity> updatedMapping = updated.getRoleGroupMapping(); List<RoleGroupEntity> deleted = RoleGroupUtils.findDeleted(existMapping, updatedMapping); List<RoleGroupEntity> created = RoleGroupUtils.findCreated(existMapping, updatedMapping); created.forEach(c -> c.setUserImportJob(exists)); if (!deleted.isEmpty()) { roleGroupRepository.delete(deleted); } if (!created.isEmpty()) { existMapping.addAll(roleGroupRepository.save(created)); } exists.setPreserveRoles(updated.getPreserveRoles()); } @Override protected ScheduledTask<UserImportJob> buildScheduledTask(UserImportJob userImportJob) { return new UserImportScheduledTask(userImportJob); } @Override public List<UserImportJob> getJobs() { return jobRepository.findUserImportJobsBy().map(this::assignNextExecution).collect(Collectors.toList()); } @Override public Optional<UserImportJob> getJob(Long id) { return Optional.ofNullable(jobRepository.findOne(id)).map(this::assignNextExecution); } @Override public Stream<UserImportJobHistoryItem> getJobHistoryItems(Long id) { return jobHistoryItemRepository.findByUserImportId(id); } @Override public Optional<UserImportJobHistoryItem> getLatestHistoryItem(Long id) { return jobHistoryItemRepository.findFirstByUserImportIdOrderByEndTimeDesc(id); } Step userImportStep() { UserImportTasklet userImportTasklet = new UserImportTasklet(transactionTemplate, userImportService); return stepBuilderFactory.get("importUsers") .tasklet(userImportTasklet) .build(); } Job buildJobForUserImportTasklet(UserImportJob job) { FindUsersToImportTasklet findUsersTasklet = new FindUsersToImportTasklet(transactionTemplate, userImportService); Step findUsersStep = stepBuilderFactory.get("findUsersForImport") .tasklet(findUsersTasklet) .build(); if (job.getUserRoles() != null) { // when user roles are already defined then we do not need to look for them return jobBuilders.get(Constants.USERS_IMPORT) .start(userImportStep()) .build(); } else { return jobBuilders.get(Constants.USERS_IMPORT) .start(findUsersStep) .next(userImportStep()) .build(); } } private class UserImportScheduledTask extends ScheduledTask<UserImportJob> { UserImportScheduledTask(UserImportJob job) { super(job); } @Override public void run() { JobParameters jobParameters = new JobParametersBuilder() .addString(Constants.Params.JOB_NAME, String.format("Users import for %s", getProviderName(job.getProviderType()))) .addString(Constants.Params.JOB_AUTHOR, SYSTEM_USER) .addString(Constants.Params.USER_IMPORT_ID, String.valueOf(job.getId())) .toJobParameters(); Job batchJob = buildJobForUserImportTasklet(job); jobTemplate.launch(batchJob, jobParameters); } } private String getProviderName(LdapProviderType providerType) { switch (providerType){ case ACTIVE_DIRECTORY: return "Active Directory"; case LDAP: return "LDAP Server"; default: return "Unknown"; } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/RoleGroupEntity.java
src/main/java/org/ohdsi/webapi/user/importer/model/RoleGroupEntity.java
package org.ohdsi.webapi.user.importer.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.ohdsi.webapi.shiro.Entities.RoleEntity; @Entity @Table(name = "sec_role_group") public class RoleGroupEntity { @Id @GenericGenerator( name = "sec_role_group_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "sec_role_group_seq"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "sec_role_group_generator") @Column(name = "id") private int id; @Column(name = "provider") @Enumerated(EnumType.STRING) private LdapProviderType provider; @Column(name = "group_dn") private String groupDn; @Column(name = "group_name") private String groupName; @ManyToOne @JoinColumn(name = "role_id") private RoleEntity role; @ManyToOne() @JoinColumn(name = "job_id") private UserImportJob userImportJob; public int getId() { return id; } public void setId(int id) { this.id = id; } public LdapProviderType getProvider() { return provider; } public void setProvider(LdapProviderType provider) { this.provider = provider; } public String getGroupDn() { return groupDn; } public void setGroupDn(String groupDn) { this.groupDn = groupDn; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public RoleEntity getRole() { return role; } public void setRole(RoleEntity role) { this.role = role; } public UserImportJob getUserImportJob() { return userImportJob; } public void setUserImportJob(UserImportJob userImportJob) { this.userImportJob = userImportJob; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/AuthenticationProviders.java
src/main/java/org/ohdsi/webapi/user/importer/model/AuthenticationProviders.java
package org.ohdsi.webapi.user.importer.model; public class AuthenticationProviders { private String adUrl; private String ldapUrl; public String getAdUrl() { return adUrl; } public void setAdUrl(String adUrl) { this.adUrl = adUrl; } public String getLdapUrl() { return ldapUrl; } public void setLdapUrl(String ldapUrl) { this.ldapUrl = ldapUrl; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/RoleGroupMapping.java
src/main/java/org/ohdsi/webapi/user/importer/model/RoleGroupMapping.java
package org.ohdsi.webapi.user.importer.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class RoleGroupMapping { @JsonProperty("provider") private String provider; @JsonProperty("roleGroups") private List<RoleGroupsMap> roleGroups; public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public List<RoleGroupsMap> getRoleGroups() { return roleGroups; } public void setRoleGroups(List<RoleGroupsMap> roleGroups) { this.roleGroups = roleGroups; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/UserImportJobHistoryItem.java
src/main/java/org/ohdsi/webapi/user/importer/model/UserImportJobHistoryItem.java
package org.ohdsi.webapi.user.importer.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.util.Date; @Entity @Table(name = "user_import_job_history") public class UserImportJobHistoryItem { @Id @Column private Long id; @Column(name = "start_time") @Temporal(TemporalType.TIMESTAMP) private Date startTime; @Column(name = "end_time") @Temporal(TemporalType.TIMESTAMP) private Date endTime; @Column private String status; @Column(name = "exit_code") private String exitCode; @Column(name = "exit_message") private String exitMessage; @Column(name = "author") private String author; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name="user_import_id") private UserImportJob userImport; @Column(name = "job_name") private String jobName; public Long getId() { return id; } public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public String getStatus() { return status; } public String getExitMessage() { return exitMessage; } public String getAuthor() { return author; } public UserImportJob getUserImport() { return userImport; } public String getJobName() { return jobName; } public String getExitCode() { return exitCode; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/LdapProviderType.java
src/main/java/org/ohdsi/webapi/user/importer/model/LdapProviderType.java
package org.ohdsi.webapi.user.importer.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; public enum LdapProviderType { ACTIVE_DIRECTORY("ad"), LDAP("ldap"); private String value; LdapProviderType(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static LdapProviderType fromValue(String value) { for(LdapProviderType provider : values()) { if (Objects.equals(provider.value, value)) { return provider; } } return null; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/LdapUser.java
src/main/java/org/ohdsi/webapi/user/importer/model/LdapUser.java
package org.ohdsi.webapi.user.importer.model; import java.util.List; public class LdapUser extends LdapObject { private List<LdapGroup> groups; private String login; public LdapUser() { } public LdapUser(String displayName, String distinguishedName) { super(displayName, distinguishedName); } public List<LdapGroup> getGroups() { return groups; } public void setGroups(List<LdapGroup> groups) { this.groups = groups; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/RoleGroupsMap.java
src/main/java/org/ohdsi/webapi/user/importer/model/RoleGroupsMap.java
package org.ohdsi.webapi.user.importer.model; import com.fasterxml.jackson.annotation.JsonProperty; import org.ohdsi.webapi.user.Role; import java.util.List; public class RoleGroupsMap { @JsonProperty("role") private Role role; @JsonProperty("groups") private List<LdapGroup> groups; public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public List<LdapGroup> getGroups() { return groups; } public void setGroups(List<LdapGroup> groups) { this.groups = groups; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/ConnectionInfo.java
src/main/java/org/ohdsi/webapi/user/importer/model/ConnectionInfo.java
package org.ohdsi.webapi.user.importer.model; public class ConnectionInfo { private ConnectionState state; private String message; private String details; public ConnectionState getState() { return state; } public void setState(ConnectionState state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public enum ConnectionState { SUCCESS, FAILED } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/AtlasUserRoles.java
src/main/java/org/ohdsi/webapi/user/importer/model/AtlasUserRoles.java
package org.ohdsi.webapi.user.importer.model; import com.fasterxml.jackson.annotation.JsonProperty; import org.ohdsi.webapi.user.Role; import java.util.List; public class AtlasUserRoles { @JsonProperty("login") private String login; @JsonProperty("displayName") private String displayName; @JsonProperty("roles") private List<Role> roles; @JsonProperty("status") private LdapUserImportStatus status; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public LdapUserImportStatus getStatus() { return status; } public void setStatus(LdapUserImportStatus status) { this.status = status; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/UserImportJob.java
src/main/java/org/ohdsi/webapi/user/importer/model/UserImportJob.java
package org.ohdsi.webapi.user.importer.model; import com.odysseusinc.scheduler.model.ArachneJob; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.NamedAttributeNode; import javax.persistence.NamedEntityGraph; import javax.persistence.OneToMany; import javax.persistence.Table; import java.time.DayOfWeek; import java.util.List; @Entity @Table(name = "user_import_job") @GenericGenerator( name = "arachne_job_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "user_import_job_seq"), @Parameter(name = "increment_size", value = "1") } ) @NamedEntityGraph(name = "jobWithMapping", attributeNodes = @NamedAttributeNode("roleGroupMapping")) public class UserImportJob extends ArachneJob { @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "user_import_job_weekdays", joinColumns = @JoinColumn(name = "user_import_job_id")) @Column(name = "day_of_week") @Enumerated(EnumType.STRING) private List<DayOfWeek> weekDays; @Column(name = "provider_type") @Enumerated(EnumType.STRING) private LdapProviderType providerType; @OneToMany(mappedBy = "userImportJob") private List<RoleGroupEntity> roleGroupMapping; @Column(name = "preserve_roles") private Boolean preserveRoles; @Column(name = "user_roles") private String userRoles; @Override public List<DayOfWeek> getWeekDays() { return weekDays; } @Override public void setWeekDays(List<DayOfWeek> weekDays) { this.weekDays = weekDays; } public LdapProviderType getProviderType() { return providerType; } public void setProviderType(LdapProviderType providerType) { this.providerType = providerType; } public List<RoleGroupEntity> getRoleGroupMapping() { return roleGroupMapping; } public void setRoleGroupMapping(List<RoleGroupEntity> roleGroupMapping) { this.roleGroupMapping = roleGroupMapping; } public Boolean getPreserveRoles() { return preserveRoles; } public void setPreserveRoles(Boolean preserveRoles) { this.preserveRoles = preserveRoles; } public String getUserRoles() { return userRoles; } public void setUserRoles(String userRoles) { this.userRoles = userRoles; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/user/importer/model/LdapGroup.java
src/main/java/org/ohdsi/webapi/user/importer/model/LdapGroup.java
package org.ohdsi.webapi.user.importer.model; public class LdapGroup extends LdapObject { public LdapGroup() { } public LdapGroup(String displayName, String distinguishedName) { super(displayName, distinguishedName); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false