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/cohortsample/CohortSamplingService.java | src/main/java/org/ohdsi/webapi/cohortsample/CohortSamplingService.java | package org.ohdsi.webapi.cohortsample;
import org.ohdsi.webapi.cohortsample.dto.CohortSampleDTO;
import org.ohdsi.webapi.cohortsample.dto.SampleElementDTO;
import org.ohdsi.webapi.cohortsample.dto.SampleParametersDTO;
import org.ohdsi.webapi.job.JobTemplate;
import org.ohdsi.webapi.service.AbstractDaoService;
import org.ohdsi.webapi.shiro.Entities.UserEntity;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.source.SourceDaimon;
import org.ohdsi.webapi.user.dto.UserDTO;
import org.ohdsi.webapi.util.PreparedStatementRenderer;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionCallback;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.ohdsi.sql.SqlTranslate;
import static org.ohdsi.webapi.cohortsample.dto.SampleParametersDTO.GenderDTO.GENDER_FEMALE_CONCEPT_ID;
import static org.ohdsi.webapi.cohortsample.dto.SampleParametersDTO.GenderDTO.GENDER_MALE_CONCEPT_ID;
import org.ohdsi.webapi.util.SourceUtils;
/**
* Service to do manage samples of a cohort definition.
*/
@Component
public class CohortSamplingService extends AbstractDaoService {
private final CohortSampleRepository sampleRepository;
private final JobBuilderFactory jobBuilders;
private final StepBuilderFactory stepBuilders;
private final JobTemplate jobTemplate;
@Autowired
public CohortSamplingService(
CohortSampleRepository sampleRepository,
JobBuilderFactory jobBuilders,
StepBuilderFactory stepBuilders,
JobTemplate jobTemplate) {
this.sampleRepository = sampleRepository;
this.jobBuilders = jobBuilders;
this.stepBuilders = stepBuilders;
this.jobTemplate = jobTemplate;
}
public List<CohortSampleDTO> listSamples(int cohortDefinitionId, int sourceId) {
return sampleRepository.findByCohortDefinitionIdAndSourceId(cohortDefinitionId, sourceId).stream()
.map(sample -> sampleToSampleDTO(sample, null, false))
.collect(Collectors.toList());
}
public CohortSampleDTO getSample(int sampleId, boolean withRecordCounts) {
CohortSample sample = sampleRepository.findById(sampleId);
if (sample == null) {
throw new NotFoundException("Cohort sample with ID " + sampleId + " not found");
}
Source source = getSourceRepository().findBySourceId(sample.getSourceId());
List<SampleElement> sampleElements = findSampleElements(source, sample.getId(), withRecordCounts);
return sampleToSampleDTO(sample, sampleElements, true);
}
public int countSamples(int cohortDefinitionId) {
return sampleRepository.countSamples(cohortDefinitionId);
}
public int countSamples(int cohortDefinitionId, int sourceId) {
return sampleRepository.countSamples(cohortDefinitionId, sourceId);
}
/**
* Find all sample elements of a sample.
* @param source Source to use
* @param cohortSampleId sample ID of the elements.
* @param withRecordCounts whether to return record counts. This makes the query much slower.
* @return list of elements.
*/
private List<SampleElement> findSampleElements(Source source, int cohortSampleId, boolean withRecordCounts) {
JdbcTemplate jdbcTemplate = getSourceJdbcTemplate(source);
PreparedStatementRenderer renderer;
Collection<String> optionalFields;
if (withRecordCounts) {
renderer = new PreparedStatementRenderer(source, "/resources/cohortsample/sql/findElementsByCohortSampleIdWithCounts.sql",
new String[]{"results_schema", "CDM_schema"},
new String[]{source.getTableQualifier(SourceDaimon.DaimonType.Results), source.getTableQualifier(SourceDaimon.DaimonType.CDM)},
"cohortSampleId", cohortSampleId);
optionalFields = Collections.singleton("record_count");
} else {
renderer = new PreparedStatementRenderer(source, "/resources/cohortsample/sql/findElementsByCohortSampleId.sql",
"results_schema",
source.getTableQualifier(SourceDaimon.DaimonType.Results),
"cohortSampleId", cohortSampleId);
optionalFields = Collections.emptySet();
}
return jdbcTemplate.query(renderer.getSql(), renderer.getOrderedParams(), new CohortSampleElementRowMapper(optionalFields));
}
/**
* Create a new sample in given source and cohort definition, using sample parameters.
* @param source Source to use
* @param cohortDefinitionId cohort definition ID to sample
* @param sampleParameters parameters to define the sample
* @return list of elements.
*/
public CohortSampleDTO createSample(Source source, int cohortDefinitionId, SampleParametersDTO sampleParameters) {
JdbcTemplate jdbcTemplate = getSourceJdbcTemplate(source);
CohortSample sample = new CohortSample();
sample.setName(sampleParameters.getName());
sample.setCohortDefinitionId(cohortDefinitionId);
sample.setSourceId(source.getId());
sample.setSize(sampleParameters.getSize());
SampleParametersDTO.AgeDTO age = sampleParameters.getAge();
if (age != null) {
switch (age.getMode()) {
case LESS_THAN:
case LESS_THAN_OR_EQUAL:
sample.setAgeMax(age.getValue());
break;
case GREATER_THAN:
case GREATER_THAN_OR_EQUAL:
sample.setAgeMin(age.getValue());
break;
case EQUAL_TO:
sample.setAgeMin(age.getValue());
sample.setAgeMax(age.getValue());
break;
case BETWEEN:
case NOT_BETWEEN:
sample.setAgeMin(age.getMin());
sample.setAgeMax(age.getMax());
break;
}
sample.setAgeMode(age.getMode().getSerialName());
}
SampleParametersDTO.GenderDTO gender = sampleParameters.getGender();
if (gender != null) {
StringBuilder sb = new StringBuilder(12);
for (Integer conceptId : gender.getConceptIds()) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(conceptId);
}
if (gender.isOtherNonBinary()) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(-1);
}
sample.setGenderConceptIds(sb.toString());
}
sample.setCreatedBy(getCurrentUser());
sample.setCreatedDate(new Date());
log.info("Sampling {} elements for cohort {}", sampleParameters.getSize(), cohortDefinitionId);
final List<SampleElement> elements = sampleElements(sampleParameters, sample, jdbcTemplate, source);
if (elements.size() < sample.getSize()) {
sample.setSize(elements.size());
}
getTransactionTemplate().execute((TransactionCallback<Void>) transactionStatus -> {
log.debug("Saving {} sample elements for cohort {}", sample.getSize(), cohortDefinitionId);
CohortSample updatedSample = sampleRepository.save(sample);
insertSampledElements(source, jdbcTemplate, updatedSample.getId(), elements);
return null;
});
return sampleToSampleDTO(sample, elements, true);
}
/**
* Create a new sample in given source and cohort definition, using sample parameters.
* @param sampleId The sample to refresh
*/
public void refreshSample(Integer sampleId) {
CohortSample sample = sampleRepository.findById(sampleId);
if (sample == null) {
throw new NotFoundException("Cohort sample with ID " + sampleId + " not found");
}
Source source = getSourceRepository().findBySourceId(sample.getSourceId());
CohortSampleDTO sampleDto = sampleToSampleDTO(sample, null, true);
SampleParametersDTO sampleParamaters = new SampleParametersDTO();
sampleParamaters.setAge(sampleDto.getAge());
sampleParamaters.setGender(sampleDto.getGender());
sampleParamaters.setSize(sampleDto.getSize());
log.info("Sampling {} elements for cohort {}", sampleParamaters.getSize(), sample.getCohortDefinitionId());
JdbcTemplate jdbcTemplate = getSourceJdbcTemplate(source);
final List<SampleElement> elements = sampleElements(sampleParamaters, sample, jdbcTemplate, source);
getTransactionTemplate().execute((TransactionCallback<Void>) transactionStatus -> {
String deleteSql = String.format(
"DELETE FROM %s.cohort_sample_element WHERE cohort_sample_id = %d;",
source.getTableQualifier(SourceDaimon.DaimonType.Results),
sample.getId());
String translatedDeleteSql = SqlTranslate.translateSql(deleteSql, source.getSourceDialect(), null, null);
jdbcTemplate.update(translatedDeleteSql);
insertSampledElements(source, jdbcTemplate, sample.getId(), elements);
return null;
});
}
/** Convert a given sample with given elements to a DTO. */
private CohortSampleDTO sampleToSampleDTO(CohortSample sample, List<SampleElement> elements, boolean includeIds) {
CohortSampleDTO sampleDTO = new CohortSampleDTO();
sampleDTO.setId(sample.getId());
sampleDTO.setName(sample.getName());
sampleDTO.setSize(sample.getSize());
if (includeIds) {
sampleDTO.setCohortDefinitionId(sample.getCohortDefinitionId());
sampleDTO.setSourceId(sample.getSourceId());
}
sampleDTO.setCreatedDate(sample.getCreatedDate());
UserEntity createdBy = sample.getCreatedBy();
if (createdBy != null) {
UserDTO userDto = new UserDTO();
userDto.setId(createdBy.getId());
userDto.setLogin(createdBy.getLogin());
userDto.setName(createdBy.getName());
sampleDTO.setCreatedBy(userDto);
}
SampleParametersDTO.AgeMode ageMode = SampleParametersDTO.AgeMode.fromSerialName(sample.getAgeMode());
if (ageMode != null) {
SampleParametersDTO.AgeDTO age = new SampleParametersDTO.AgeDTO();
age.setMode(ageMode);
switch (ageMode) {
case LESS_THAN:
case LESS_THAN_OR_EQUAL:
case EQUAL_TO:
age.setValue(sample.getAgeMax());
break;
case GREATER_THAN:
case GREATER_THAN_OR_EQUAL:
age.setValue(sample.getAgeMin());
break;
case BETWEEN:
case NOT_BETWEEN:
age.setMin(sample.getAgeMin());
age.setMax(sample.getAgeMax());
break;
}
sampleDTO.setAge(age);
}
if (sample.getGenderConceptIds() != null && !sample.getGenderConceptIds().isEmpty()) {
List<Integer> conceptIds = Arrays.stream(sample.getGenderConceptIds().split(","))
.map(Integer::valueOf)
.collect(Collectors.toList());
SampleParametersDTO.GenderDTO genderDto = new SampleParametersDTO.GenderDTO();
if (conceptIds.remove(Integer.valueOf(-1))) {
genderDto.setOtherNonBinary(true);
}
genderDto.setConceptIds(conceptIds);
sampleDTO.setGender(genderDto);
}
sampleDTO.setElements(sampleElementToDTO(elements));
return sampleDTO;
}
/** Convert given sample elements DTOs. */
private List<SampleElementDTO> sampleElementToDTO(List<SampleElement> elements) {
if (elements == null) {
return null;
}
return elements.stream()
.map(el -> {
SampleElementDTO elementDTO = new SampleElementDTO();
elementDTO.setRank(el.getRank());
elementDTO.setPersonId(String.valueOf(el.getPersonId()));
elementDTO.setAge(el.getAge());
elementDTO.setGenderConceptId(el.getGenderConceptId());
elementDTO.setRecordCount(el.getRecordCount());
return elementDTO;
})
.collect(Collectors.toList());
}
/** Insert elements that have been sampled. */
private void insertSampledElements(Source source, JdbcTemplate jdbcTemplate, int sampleId, List<SampleElement> elements) {
if (elements.isEmpty()) {
return;
}
String[] parameters = new String[] { "results_schema" };
String[] parameterValues = new String[] { source.getTableQualifier(SourceDaimon.DaimonType.Results) };
String[] sqlParameters = new String[] { "cohortSampleId", "rank", "personId", "age", "genderConceptId" };
String statement = null;
List<Object[]> variables = new ArrayList<>(elements.size());
for (SampleElement element : elements) {
Object[] sqlValues = new Object[] {
sampleId,
element.getRank(),
element.getPersonId(),
element.getAge(),
element.getGenderConceptId() };
PreparedStatementRenderer renderer = new PreparedStatementRenderer(source, "/resources/cohortsample/sql/insertSampleElement.sql", parameters, parameterValues, sqlParameters, sqlValues);
if (statement == null) {
statement = renderer.getSql();
}
variables.add(renderer.getOrderedParams());
}
jdbcTemplate.batchUpdate(statement, variables);
}
/** Sample elements based on parameters. */
private List<SampleElement> sampleElements(SampleParametersDTO sampleParametersDTO, CohortSample sample, JdbcTemplate jdbcTemplate, Source source) {
StringBuilder expressionBuilder = new StringBuilder();
Map<String, Object> sqlVariables = new LinkedHashMap<>();
sqlVariables.put("cohort_definition_id", sample.getCohortDefinitionId());
SampleParametersDTO.AgeMode ageMode = SampleParametersDTO.AgeMode.fromSerialName(sample.getAgeMode());
if (ageMode != null) {
switch (ageMode) {
case LESS_THAN:
expressionBuilder.append(" AND age < @age_max");
sqlVariables.put("age_max", sample.getAgeMax());
break;
case LESS_THAN_OR_EQUAL:
expressionBuilder.append(" AND age <= @age_max");
sqlVariables.put("age_max", sample.getAgeMax());
break;
case GREATER_THAN:
expressionBuilder.append(" AND age > @age_min");
sqlVariables.put("age_min", sample.getAgeMin());
break;
case GREATER_THAN_OR_EQUAL:
expressionBuilder.append(" AND age >= @age_min");
sqlVariables.put("age_min", sample.getAgeMin());
break;
case EQUAL_TO:
expressionBuilder.append(" AND age = @age_equal");
sqlVariables.put("age_equal", sample.getAgeMin());
break;
case BETWEEN:
expressionBuilder.append(" AND age <= @age_max AND age >= @age_min");
sqlVariables.put("age_min", sample.getAgeMin());
sqlVariables.put("age_max", sample.getAgeMax());
break;
case NOT_BETWEEN:
expressionBuilder.append(" AND age > @age_max OR age < @age_min");
sqlVariables.put("age_min", sample.getAgeMin());
sqlVariables.put("age_max", sample.getAgeMax());
break;
}
}
SampleParametersDTO.GenderDTO gender = sampleParametersDTO.getGender();
if (gender != null) {
List<Integer> conceptIds = gender.getConceptIds();
if (gender.isOtherNonBinary()) {
if (conceptIds.size() == 0) {
expressionBuilder.append(" AND gender_concept_id NOT IN (")
.append(GENDER_MALE_CONCEPT_ID)
.append(',')
.append(GENDER_FEMALE_CONCEPT_ID)
.append(')');
} else if (conceptIds.size() == 1) {
if (conceptIds.get(0) == GENDER_FEMALE_CONCEPT_ID) {
expressionBuilder.append(" AND gender_concept_id <> ")
.append(GENDER_MALE_CONCEPT_ID);
} else {
expressionBuilder.append(" AND gender_concept_id <> ")
.append(GENDER_FEMALE_CONCEPT_ID);
}
}
// else: all genders are selected, no where statement needed
} else if (!conceptIds.isEmpty()) {
expressionBuilder.append(" AND gender_concept_id IN (");
for (int i = 0; i < conceptIds.size(); i++) {
if (i > 0) {
expressionBuilder.append(',');
}
expressionBuilder.append(conceptIds.get(i));
}
expressionBuilder.append(')');
}
// else: all genders are selected, no where statement needed
}
String[] parameterKeys = new String[] { "results_schema", "CDM_schema", "expression"};
String[] parameterValues = new String[] {
source.getTableQualifier(SourceDaimon.DaimonType.Results),
source.getTableQualifier(SourceDaimon.DaimonType.CDM),
expressionBuilder.toString() };
String[] sqlVariableKeys = sqlVariables.keySet().toArray(new String[0]);
Object[] sqlVariableValues = Stream.of(sqlVariableKeys)
.map(sqlVariables::get)
.toArray(Object[]::new);
PreparedStatementRenderer renderer = new PreparedStatementRenderer(source, "/resources/cohortsample/sql/generateSample.sql",
parameterKeys,
parameterValues,
sqlVariableKeys,
sqlVariableValues);
jdbcTemplate.setMaxRows(sample.getSize());
return jdbcTemplate.query(renderer.getSql(), renderer.getOrderedParams(), (rs, rowNum) -> {
SampleElement element = new SampleElement();
element.setRank(rowNum);
element.setAge(rs.getInt("age"));
element.setGenderConceptId(rs.getInt("gender_concept_id"));
element.setPersonId(rs.getLong("person_id"));
return element;
});
}
/** Delete a sample and its elements. */
public void deleteSample(int cohortDefinitionId, Source source, int sampleId) {
JdbcTemplate jdbcTemplate = getSourceJdbcTemplate(source);
String resultsSchema = source.getTableQualifier(SourceDaimon.DaimonType.Results);
String sql = new PreparedStatementRenderer(
source,
"/resources/cohortsample/sql/deleteSampleElementsById.sql",
"results_schema",
resultsSchema,
"cohortSampleId",
sampleId).getSql();
CohortSample sample = sampleRepository.findOne(sampleId);
if (sample == null) {
throw new NotFoundException("Sample with ID " + sampleId + " does not exist");
}
if (sample.getCohortDefinitionId() != cohortDefinitionId) {
throw new BadRequestException("Cohort definition ID " + sample.getCohortDefinitionId() + " does not match provided cohort definition id " + cohortDefinitionId);
}
if (sample.getSourceId() != source.getId()) {
throw new BadRequestException("Source " + sample.getSourceId() + " does not match provided source " + source.getId());
}
getTransactionTemplate().execute((TransactionCallback<Void>) transactionStatus -> {
sampleRepository.delete(sampleId);
jdbcTemplate.update(sql, sampleId);
return null;
});
}
public void launchDeleteSamplesTasklet(int cohortDefinitionId) {
CleanupCohortSamplesTasklet tasklet = createDeleteSamplesTasklet();
tasklet.launch(jobBuilders, stepBuilders, jobTemplate, cohortDefinitionId);
}
public void launchDeleteSamplesTasklet(int cohortDefinitionId, int sourceId) {
CleanupCohortSamplesTasklet tasklet = createDeleteSamplesTasklet();
tasklet.launch(jobBuilders, stepBuilders, jobTemplate, cohortDefinitionId, sourceId);
}
public CleanupCohortSamplesTasklet createDeleteSamplesTasklet() {
return new CleanupCohortSamplesTasklet(getTransactionTemplate(), getSourceRepository(), this, sampleRepository);
}
/** Maps a SQL result to a sample element. */
private static class CohortSampleElementRowMapper implements RowMapper<SampleElement> {
private final Collection<String> optionalFields;
CohortSampleElementRowMapper(Collection<String> optionalFields) {
this.optionalFields = optionalFields;
}
@Override
public SampleElement mapRow(ResultSet rs, int rowNum) throws SQLException {
SampleElement sample = new SampleElement();
sample.setRank(rs.getInt("rank_value"));
sample.setSampleId(rs.getInt("cohort_sample_id"));
sample.setPersonId(rs.getLong("person_id"));
sample.setGenderConceptId(rs.getInt("gender_concept_id"));
sample.setAge(rs.getInt("age"));
if (optionalFields.contains("record_count")) {
sample.setRecordCount(rs.getInt("record_count"));
}
return sample;
}
}
}
| 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/cohortsample/SampleElement.java | src/main/java/org/ohdsi/webapi/cohortsample/SampleElement.java | package org.ohdsi.webapi.cohortsample;
/** A single person that is part of a given sample. */
public class SampleElement {
private int sampleId;
private int rank;
private long personId;
private long genderConceptId;
private int age;
private Integer recordCount;
public int getSampleId() {
return sampleId;
}
public void setSampleId(int sampleId) {
this.sampleId = sampleId;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
public long getGenderConceptId() {
return genderConceptId;
}
public void setGenderConceptId(long genderConceptId) {
this.genderConceptId = genderConceptId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Integer getRecordCount() {
return recordCount;
}
public void setRecordCount(Integer recordCount) {
this.recordCount = recordCount;
}
}
| 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/cohortsample/CohortSample.java | src/main/java/org/ohdsi/webapi/cohortsample/CohortSample.java | package org.ohdsi.webapi.cohortsample;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.ohdsi.webapi.model.CommonEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.List;
/**
* Cohort sample details.
*/
@Entity(name = "CohortSample")
@Table(name = "cohort_sample")
public class CohortSample extends CommonEntity<Integer> {
@Id
@GenericGenerator(
name = "cohort_sample_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "cohort_sample_sequence"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "cohort_sample_generator")
private Integer id;
@Column
private String name;
@Column(name = "cohort_definition_id")
private int cohortDefinitionId;
@Column(name = "source_id")
private int sourceId;
@Column(name = "age_mode")
private String ageMode;
@Column(name = "age_min")
private Integer ageMin;
@Column(name = "age_max")
private Integer ageMax;
@Column(name = "gender_concept_ids")
private String genderConceptIds;
@Column(name = "\"size\"")
private int size;
@Transient
private List<SampleElement> elements;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public int getCohortDefinitionId() {
return cohortDefinitionId;
}
public void setCohortDefinitionId(int cohortDefinitionId) {
this.cohortDefinitionId = cohortDefinitionId;
}
public List<SampleElement> getElements() {
return elements;
}
public void setElements(List<SampleElement> elements) {
this.elements = elements;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public Integer getAgeMin() {
return ageMin;
}
public void setAgeMin(Integer ageMin) {
this.ageMin = ageMin;
}
public Integer getAgeMax() {
return ageMax;
}
public void setAgeMax(Integer ageMax) {
this.ageMax = ageMax;
}
public String getGenderConceptIds() {
return genderConceptIds;
}
public void setGenderConceptIds(String genderConceptIds) {
this.genderConceptIds = genderConceptIds;
}
public int getSourceId() {
return sourceId;
}
public void setSourceId(int sourceId) {
this.sourceId = sourceId;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getAgeMode() {
return ageMode;
}
public void setAgeMode(String ageMode) {
this.ageMode = ageMode;
}
}
| 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/cohortsample/dto/SampleParametersDTO.java | src/main/java/org/ohdsi/webapi/cohortsample/dto/SampleParametersDTO.java | package org.ohdsi.webapi.cohortsample.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonValue;
import javax.ws.rs.BadRequestException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
public class SampleParametersDTO {
private static final int SIZE_MAX = 500;
private static final int AGE_MAX = 500;
/** Sample size. */
private int size;
/** Sample name. */
private String name;
/** Gender criteria. */
private GenderDTO gender;
/** Age criteria. */
private AgeDTO age;
/**
* Validate this DTO.
* @throws BadRequestException if the DTO is not valid.
*/
public void validate() {
if (name == null) {
throw new BadRequestException("Sample must have a name");
}
if (size <= 0) {
throw new BadRequestException("sample parameter size must fall in the range (1, " + SIZE_MAX + ")");
}
if (size > SIZE_MAX) {
throw new BadRequestException("sample parameter size must fall in the range (1, " + SIZE_MAX + ")");
}
if (age != null && !age.validate()) {
age = null;
}
if (gender != null && !gender.validate()) {
gender = null;
}
}
public AgeDTO getAge() {
return age;
}
public void setAge(AgeDTO age) {
this.age = age;
}
public GenderDTO getGender() {
return gender;
}
public void setGender(GenderDTO gender) {
this.gender = gender;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public enum AgeMode {
LESS_THAN("lessThan"),
LESS_THAN_OR_EQUAL("lessThanOrEqual"),
GREATER_THAN("greaterThan"),
GREATER_THAN_OR_EQUAL("greaterThanOrEqual"),
EQUAL_TO("equalTo"),
BETWEEN("between"),
NOT_BETWEEN("notBetween");
private final String serialName;
AgeMode(String serialName) {
this.serialName = serialName;
}
@JsonValue
public String getSerialName() {
return serialName;
}
public static AgeMode fromSerialName(String name) {
return Stream.of(SampleParametersDTO.AgeMode.values())
.filter(mode -> mode.getSerialName().equals(name))
.findFirst()
.orElse(null);
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class GenderDTO {
public final static int GENDER_MALE_CONCEPT_ID = 8507;
public final static int GENDER_FEMALE_CONCEPT_ID = 8532;
private Integer conceptId;
private List<Integer> conceptIds;
private boolean otherNonBinary = false;
/**
* Validate this DTO.
* @return true if this DTO contains any information, false otherwise.
*/
public boolean validate() {
if (conceptIds == null) {
conceptIds = new ArrayList<>();
} else if (conceptIds.contains(null)) {
conceptIds.removeIf(Objects::isNull);
}
if (conceptId != null) {
conceptIds.add(conceptId);
conceptId = null;
}
if (!isOtherNonBinary() && conceptIds.isEmpty()) {
return false;
}
if (isOtherNonBinary()) {
conceptIds.removeIf(i -> i != GENDER_MALE_CONCEPT_ID && i != GENDER_FEMALE_CONCEPT_ID);
}
return true;
}
public Integer getConceptId() {
return conceptId;
}
public void setConceptId(Integer conceptId) {
this.conceptId = conceptId;
}
public List<Integer> getConceptIds() {
return conceptIds;
}
public void setConceptIds(List<Integer> conceptIds) {
this.conceptIds = conceptIds;
}
public boolean isOtherNonBinary() {
return otherNonBinary;
}
public void setOtherNonBinary(boolean otherNonBinary) {
this.otherNonBinary = otherNonBinary;
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class AgeDTO {
private Integer min;
private Integer max;
private Integer value;
private AgeMode mode;
/**
* Validate this DTO.
* @return true if this DTO contains any information, false otherwise.
* @throws BadRequestException if the DTO is not valid.
*/
public boolean validate() {
if (mode == null) {
if (min != null || max != null || value != null) {
throw new BadRequestException("Cannot specify age without a mode to use age with.");
} else {
return false;
}
}
switch (mode) {
case LESS_THAN:
case LESS_THAN_OR_EQUAL:
case GREATER_THAN:
case GREATER_THAN_OR_EQUAL:
case EQUAL_TO:
if (value == null) {
throw new BadRequestException("Cannot use single age comparison mode " + mode.getSerialName() + " without age property.");
}
if (min != null || max != null) {
throw new BadRequestException("Cannot use age range property with comparison mode " + mode.getSerialName() + ".");
}
break;
case BETWEEN:
case NOT_BETWEEN:
if (min == null || max == null) {
throw new BadRequestException("Cannot use age range comparison mode " + mode.getSerialName() + " without ageMin and ageMax properties.");
}
if (value != null) {
throw new BadRequestException("Cannot use single age property with comparison mode " + mode.getSerialName() + ".");
}
if (min < 0) {
throw new BadRequestException("Minimum age may not be less than 0");
}
if (max >= AGE_MAX) {
throw new BadRequestException("Maximum age must be smaller than " + AGE_MAX);
}
if (min > max) {
throw new BadRequestException("Maximum age " + max + " may not be less than minimum age " + min);
}
break;
}
return true;
}
public Integer getMin() {
return min;
}
public void setMin(Integer min) {
this.min = min;
}
public Integer getMax() {
return max;
}
public void setMax(Integer max) {
this.max = max;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public AgeMode getMode() {
return mode;
}
public void setMode(AgeMode mode) {
this.mode = mode;
}
}
}
| 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/cohortsample/dto/CohortSampleDTO.java | src/main/java/org/ohdsi/webapi/cohortsample/dto/CohortSampleDTO.java | package org.ohdsi.webapi.cohortsample.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.ohdsi.webapi.user.dto.UserDTO;
import java.util.Date;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CohortSampleDTO {
/** Cohort sample ID. */
private int id;
/** Cohort sample name. */
private String name;
/**
* Actual sample size. This may be different from the size specified by the user if not enough
* persons could be found matching the criteria.
*/
private int size;
/**
* Date that the sample was created.
*/
private Date createdDate;
/**
* User that created the sample. If no login system is used, this is null.
*/
private UserDTO createdBy;
/**
* Cohort definition ID that was sampled.
*/
private Integer cohortDefinitionId;
/**
* Source ID that was sampled.
*/
private Integer sourceId;
/**
* Age criteria used to create the sample.
*/
private SampleParametersDTO.AgeDTO age;
/**
* Gender criteria used to create the sample.
*/
private SampleParametersDTO.GenderDTO gender;
/**
* Actually sampled elements.
*/
private List<SampleElementDTO> elements;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public UserDTO getCreatedBy() {
return createdBy;
}
public void setCreatedBy(UserDTO createdBy) {
this.createdBy = createdBy;
}
public Integer getCohortDefinitionId() {
return cohortDefinitionId;
}
public void setCohortDefinitionId(Integer cohortDefinitionId) {
this.cohortDefinitionId = cohortDefinitionId;
}
public Integer getSourceId() {
return sourceId;
}
public void setSourceId(Integer sourceId) {
this.sourceId = sourceId;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<SampleElementDTO> getElements() {
return elements;
}
public void setElements(List<SampleElementDTO> elements) {
this.elements = elements;
}
public SampleParametersDTO.AgeDTO getAge() {
return age;
}
public void setAge(SampleParametersDTO.AgeDTO age) {
this.age = age;
}
public SampleParametersDTO.GenderDTO getGender() {
return gender;
}
public void setGender(SampleParametersDTO.GenderDTO gender) {
this.gender = gender;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return 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/cohortsample/dto/SampleElementDTO.java | src/main/java/org/ohdsi/webapi/cohortsample/dto/SampleElementDTO.java | package org.ohdsi.webapi.cohortsample.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SampleElementDTO {
/**
* Sample ID that this element belongs to. May be null if this object is part of a
* {@link CohortSampleDTO} object.
*/
private Integer sampleId;
/**
* Rank of the object within the sample. This establishes order between elements.
*/
private int rank;
/**
* Person ID of the element.
*/
private String personId;
/**
* Gender ID of the person.
*/
private long genderConceptId;
/**
* Age of the person.
*/
private int age;
private Integer recordCount;
public Integer getSampleId() {
return sampleId;
}
public void setSampleId(Integer sampleId) {
this.sampleId = sampleId;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public long getGenderConceptId() {
return genderConceptId;
}
public void setGenderConceptId(long genderConceptId) {
this.genderConceptId = genderConceptId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Integer getRecordCount() {
return recordCount;
}
public void setRecordCount(Integer recordCount) {
this.recordCount = recordCount;
}
}
| 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/cohortsample/dto/CohortSampleListDTO.java | src/main/java/org/ohdsi/webapi/cohortsample/dto/CohortSampleListDTO.java | package org.ohdsi.webapi.cohortsample.dto;
import org.ohdsi.webapi.GenerationStatus;
import java.util.List;
public class CohortSampleListDTO {
private int cohortDefinitionId;
private int sourceId;
private GenerationStatus generationStatus;
private boolean isValid;
private List<CohortSampleDTO> samples;
public int getCohortDefinitionId() {
return cohortDefinitionId;
}
public void setCohortDefinitionId(int cohortDefinitionId) {
this.cohortDefinitionId = cohortDefinitionId;
}
public int getSourceId() {
return sourceId;
}
public void setSourceId(int sourceId) {
this.sourceId = sourceId;
}
public GenerationStatus getGenerationStatus() {
return generationStatus;
}
public void setGenerationStatus(GenerationStatus generationStatus) {
this.generationStatus = generationStatus;
}
public boolean isValid() {
return isValid;
}
public void setIsValid(boolean valid) {
isValid = valid;
}
public List<CohortSampleDTO> getSamples() {
return samples;
}
public void setSamples(List<CohortSampleDTO> samples) {
this.samples = samples;
}
}
| 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/helper/Guard.java | src/main/java/org/ohdsi/webapi/helper/Guard.java | package org.ohdsi.webapi.helper;
/**
*
* @author gennadiy.anisimov
*/
public class Guard {
public static Boolean isNullOrEmpty(String value) {
return value == null || value.isEmpty();
}
public static void checkNotEmpty(String value) {
if (isNullOrEmpty(value))
throw new IllegalArgumentException("Value should not be empty");
}
}
| 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/security/AccessType.java | src/main/java/org/ohdsi/webapi/security/AccessType.java | package org.ohdsi.webapi.security;
public enum AccessType {
READ,
WRITE
}
| 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/security/PermissionService.java | src/main/java/org/ohdsi/webapi/security/PermissionService.java | package org.ohdsi.webapi.security;
import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph;
import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraphUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.ohdsi.webapi.model.CommonEntity;
import org.ohdsi.webapi.security.model.EntityPermissionSchema;
import org.ohdsi.webapi.security.model.EntityPermissionSchemaResolver;
import org.ohdsi.webapi.security.model.EntityType;
import org.ohdsi.webapi.security.model.SourcePermissionSchema;
import org.ohdsi.webapi.security.model.UserSimpleAuthorizationInfo;
import org.ohdsi.webapi.service.dto.CommonEntityDTO;
import org.ohdsi.webapi.shiro.Entities.PermissionEntity;
import org.ohdsi.webapi.shiro.Entities.PermissionRepository;
import org.ohdsi.webapi.shiro.Entities.RoleEntity;
import org.ohdsi.webapi.shiro.Entities.RolePermissionEntity;
import org.ohdsi.webapi.shiro.Entities.RolePermissionRepository;
import org.ohdsi.webapi.shiro.Entities.RoleRepository;
import org.ohdsi.webapi.shiro.Entities.UserEntity;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.source.SourceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.support.Repositories;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.subject.Subject;
@Service
public class PermissionService {
private final Logger logger = LoggerFactory.getLogger(PermissionService.class);
private final WebApplicationContext appContext;
private final PermissionManager permissionManager;
private final EntityPermissionSchemaResolver entityPermissionSchemaResolver;
private final SourcePermissionSchema sourcePermissionSchema;
private final RoleRepository roleRepository;
private final SourceRepository sourceRepository;
private final PermissionRepository permissionRepository;
private final RolePermissionRepository rolePermissionRepository;
private final ConversionService conversionService;
private Repositories repositories;
@Value("#{!'${security.provider}'.equals('DisabledSecurity')}")
private boolean securityEnabled;
@Value("${security.defaultGlobalReadPermissions}")
private boolean defaultGlobalReadPermissions;
private final EntityGraph PERMISSION_ENTITY_GRAPH = EntityGraphUtils.fromAttributePaths("rolePermissions", "rolePermissions.role");
public PermissionService(
WebApplicationContext appContext,
PermissionManager permissionManager,
EntityPermissionSchemaResolver entityPermissionSchemaResolver,
SourcePermissionSchema sourcePermissionSchema,
RoleRepository roleRepository,
SourceRepository sourceRepository,
PermissionRepository permissionRepository,
RolePermissionRepository rolePermissionRepository,
ConversionService conversionService
) {
this.appContext = appContext;
this.permissionManager = permissionManager;
this.entityPermissionSchemaResolver = entityPermissionSchemaResolver;
this.sourcePermissionSchema = sourcePermissionSchema;
this.roleRepository = roleRepository;
this.sourceRepository = sourceRepository;
this.permissionRepository = permissionRepository;
this.rolePermissionRepository = rolePermissionRepository;
this.conversionService = conversionService;
}
@PostConstruct
private void postConstruct() {
this.repositories = new Repositories(appContext);
// Migrated from Atlas security. Is it still required?
for (Source source : sourceRepository.findAll()) {
sourcePermissionSchema.addSourceUserRole(source);
}
}
public List<RoleEntity> suggestRoles(String roleSearch) {
return roleRepository.findByNameIgnoreCaseContaining(roleSearch);
}
public Map<String, String> getTemplatesForType(EntityType entityType, AccessType accessType) {
EntityPermissionSchema entityPermissionSchema = entityPermissionSchemaResolver.getForType(entityType);
return getPermissionTemplates(entityPermissionSchema, accessType);
}
public void checkCommonEntityOwnership(EntityType entityType, Integer entityId) throws Exception {
JpaRepository entityRepository = (JpaRepository) (((Advised) repositories.getRepositoryFor(entityType.getEntityClass())).getTargetSource().getTarget());
Class idClazz = Arrays.stream(entityType.getEntityClass().getMethods())
// Overriden methods from parameterized interface are "bridges" and should be ignored.
// For more information see https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html
.filter(m -> m.getName().equals("getId") && !m.isBridge())
.findFirst()
.orElseThrow(() -> new RuntimeException("Cannot retrieve common entity"))
.getReturnType();
CommonEntity entity = (CommonEntity) entityRepository.getOne((Serializable) conversionService.convert(entityId, idClazz));
if (!isCurrentUserOwnerOf(entity)) {
throw new UnauthorizedException();
}
}
public Map<String, String> getPermissionTemplates(EntityPermissionSchema permissionSchema, AccessType accessType) {
switch (accessType) {
case WRITE:
return permissionSchema.getWritePermissions();
case READ:
return permissionSchema.getReadPermissions();
default:
throw new UnsupportedOperationException();
}
}
public List<RoleEntity> finaAllRolesHavingPermissions(List<String> permissions) {
return roleRepository.finaAllRolesHavingPermissions(permissions, (long) permissions.size());
}
public void removePermissionsFromRole(Map<String, String> permissionTemplates, Integer entityId, Long roleId) {
RoleEntity role = roleRepository.findById(roleId);
permissionTemplates.keySet()
.forEach(pt -> {
String permission = getPermission(pt, entityId);
PermissionEntity permissionEntity = permissionRepository.findByValueIgnoreCase(permission);
if (permissionEntity != null) {
RolePermissionEntity rp = rolePermissionRepository.findByRoleAndPermission(role, permissionEntity);
rolePermissionRepository.delete(rp.getId());
}
});
}
public String getPermission(String template, Object entityId) {
return String.format(template, entityId);
}
public String getPermissionSqlTemplate(String template) {
return String.format(template, "%%");
}
private boolean isCurrentUserOwnerOf(CommonEntity entity) {
UserEntity owner = entity.getCreatedBy();
String loggedInUsername = permissionManager.getSubjectName();
return Objects.equals(owner.getLogin(), loggedInUsername);
}
public List<Permission> getEntityPermissions(EntityType entityType, Number id, AccessType accessType) {
Set<String> permissionTemplates = getTemplatesForType(entityType, accessType).keySet();
List<Permission> permissions = permissionTemplates.stream()
.map(pt -> new WildcardPermission(getPermission(pt, id)))
.collect(Collectors.toList());
return permissions;
}
public boolean hasAccess(CommonEntity entity, AccessType accessType) {
boolean hasAccess = false;
if (securityEnabled && entity.getCreatedBy() != null) {
try {
Subject subject = SecurityUtils.getSubject();
String login = this.permissionManager.getSubjectName();
UserSimpleAuthorizationInfo authorizationInfo = this.permissionManager.getAuthorizationInfo(login);
if (Objects.equals(authorizationInfo.getUserId(), entity.getCreatedBy().getId())) {
hasAccess = true; // the role is the one that created the artifact
} else {
EntityType entityType = entityPermissionSchemaResolver.getEntityType(entity.getClass());
List<Permission> permsToCheck = getEntityPermissions(entityType, entity.getId(), accessType);
hasAccess = permsToCheck.stream().allMatch(p -> subject.isPermitted(p));
}
} catch (Exception e) {
logger.error("Error getting user roles and permissions", e);
throw new RuntimeException(e);
}
}
return hasAccess;
}
public boolean hasWriteAccess(CommonEntity entity) {
return hasAccess(entity, AccessType.WRITE);
}
public boolean hasReadAccess(CommonEntity entity) {
return hasAccess(entity, AccessType.READ);
}
public void fillWriteAccess(CommonEntity entity, CommonEntityDTO entityDTO) {
if (securityEnabled && entity.getCreatedBy() != null) {
entityDTO.setHasWriteAccess(hasAccess(entity, AccessType.WRITE));
}
}
public void fillReadAccess(CommonEntity entity, CommonEntityDTO entityDTO) {
if (securityEnabled && entity.getCreatedBy() != null) {
entityDTO.setHasReadAccess(hasAccess(entity, AccessType.READ));
}
}
public boolean isSecurityEnabled() {
return this.securityEnabled;
}
// Use this key for cache (asset lists) that may be associated to a user or shared across users.
public String getAssetListCacheKey() {
if (this.isSecurityEnabled() && !defaultGlobalReadPermissions)
return permissionManager.getSubjectName();
else
return "ALL_USERS";
}
// use this cache key when the cache is associated to a user
public String getSubjectCacheKey() {
return this.isSecurityEnabled() ? permissionManager.getSubjectName() : "ALL_USERS";
}
}
| 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/security/SecurityConfigurationInfo.java | src/main/java/org/ohdsi/webapi/security/SecurityConfigurationInfo.java | package org.ohdsi.webapi.security;
import org.ohdsi.info.ConfigurationInfo;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.shiro.management.AtlasRegularSecurity;
import org.ohdsi.webapi.shiro.management.Security;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class SecurityConfigurationInfo extends ConfigurationInfo {
private static final String KEY = "security";
public SecurityConfigurationInfo(@Value("${security.provider}") String securityProvider,
@Value("${security.saml.enabled}") Boolean samlEnabled,
Security atlasSecurity) {
boolean enabled = !Objects.equals(securityProvider, Constants.SecurityProviders.DISABLED);
properties.put("enabled", enabled);
properties.put("samlEnabled", samlEnabled);
boolean samlActivated = false;
if (atlasSecurity instanceof AtlasRegularSecurity) {
samlActivated = ((AtlasRegularSecurity) atlasSecurity).isSamlEnabled();
}
properties.put("samlActivated", samlActivated);
}
@Override
public String getKey() {
return KEY;
}
}
| 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/security/SSOController.java | src/main/java/org/ohdsi/webapi/security/SSOController.java | /*
*
* Copyright 2018 Odysseus Data Services, inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Company: Odysseus Data Services, Inc.
* Product Owner/Architecture: Gregory Klebanov
* Authors: Pavel Grafkin, Vitaly Koulakov, Maria Pozhidaeva
* Created: April 4, 2018
*
*/
package org.ohdsi.webapi.security;
import com.google.common.net.HttpHeaders;
import org.apache.commons.io.IOUtils;
import org.pac4j.core.context.HttpConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
/**
* REST Services related to working with Single Sign-On and SAML-based
* Services
*
* @summary Single Sign On
*/
@Controller
@Path("/saml/")
public class SSOController {
@Value("${security.saml.metadataLocation}")
private String metadataLocation;
@Value("${security.saml.sloUrl}")
private String sloUri;
@Value("${security.origin}")
private String origin;
/**
* Get the SAML metadata
*
* @summary Get metadata
* @param response The response context
* @throws IOException
*/
@GET
@Path("/saml-metadata")
public void samlMetadata(@Context HttpServletResponse response) throws IOException {
ClassPathResource resource = new ClassPathResource(metadataLocation);
final InputStream is = resource.getInputStream();
response.setContentType(MediaType.APPLICATION_XML);
response.setHeader(HttpHeaders.CONTENT_TYPE, "application/xml");
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
response.setHeader(HttpHeaders.PRAGMA, "no-cache");
response.setHeader(HttpHeaders.EXPIRES, "0");
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}
/**
* Log out of the service
*
* @summary Log out
* @return Response
* @throws URISyntaxException
*/
@GET
@Path("/slo")
public Response logout() throws URISyntaxException {
return Response.status(HttpConstants.TEMPORARY_REDIRECT)
.header(HttpConstants.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, this.origin)
.location(new URI(sloUri))
.build();
}
}
| 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/security/PermissionController.java | src/main/java/org/ohdsi/webapi/security/PermissionController.java | package org.ohdsi.webapi.security;
import org.ohdsi.webapi.security.dto.AccessRequestDTO;
import org.ohdsi.webapi.security.dto.RoleDTO;
import org.ohdsi.webapi.security.model.EntityType;
import org.ohdsi.webapi.service.UserService;
import org.ohdsi.webapi.shiro.Entities.PermissionEntity;
import org.ohdsi.webapi.shiro.Entities.RoleEntity;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/**
* REST Services related to working with security permissions
*
* @summary Notifications
*/
@Controller
@Path(value = "/permission")
@Transactional
public class PermissionController {
private final PermissionService permissionService;
private final PermissionManager permissionManager;
private final ConversionService conversionService;
public PermissionController(PermissionService permissionService, PermissionManager permissionManager, ConversionService conversionService) {
this.permissionService = permissionService;
this.permissionManager = permissionManager;
this.conversionService = conversionService;
}
/**
* Get the list of permissions for a user
*
* @return A list of permissions
*/
@GET
@Path("")
@Produces(MediaType.APPLICATION_JSON)
public List<UserService.Permission> getPermissions() {
Iterable<PermissionEntity> permissionEntities = this.permissionManager.getPermissions();
return StreamSupport.stream(permissionEntities.spliterator(), false)
.map(UserService.Permission::new)
.collect(Collectors.toList());
}
/**
* Get the roles matching the roleSearch value
*
* @summary Role search
* @param roleSearch The role to search
* @return The list of roles
*/
@GET
@Path("/access/suggest")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<RoleDTO> listAccessesForEntity(@QueryParam("roleSearch") String roleSearch) {
List<RoleEntity> roles = permissionService.suggestRoles(roleSearch);
return roles.stream().map(re -> conversionService.convert(re, RoleDTO.class)).collect(Collectors.toList());
}
/**
* Get roles that have a permission type (READ/WRITE) to entity
*
* @summary Get roles that have a specific permission (READ/WRITE) for the
* entity
* @param entityType The entity type
* @param entityId The entity ID
* @return The list of permissions for the permission type
* @throws Exception
*/
@GET
@Path("/access/{entityType}/{entityId}/{permType}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<RoleDTO> listAccessesForEntityByPermType(
@PathParam("entityType") EntityType entityType,
@PathParam("entityId") Integer entityId,
@PathParam("permType") AccessType permType
) throws Exception {
permissionService.checkCommonEntityOwnership(entityType, entityId);
Set<String> permissionTemplates = null;
permissionTemplates = permissionService.getTemplatesForType(entityType, permType).keySet();
List<String> permissions = permissionTemplates
.stream()
.map(pt -> permissionService.getPermission(pt, entityId))
.collect(Collectors.toList());
List<RoleEntity> roles = permissionService.finaAllRolesHavingPermissions(permissions);
return roles.stream().map(re -> conversionService.convert(re, RoleDTO.class)).collect(Collectors.toList());
}
/**
* Get roles that have a permission type (READ/WRITE) to entity
*
* @summary Get roles that have a specific permission (READ/WRITE) for the
* entity
* @param entityType The entity type
* @param entityId The entity ID
* @return The list of permissions for the permission type
* @throws Exception
*/
@GET
@Path("/access/{entityType}/{entityId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<RoleDTO> listAccessesForEntity(
@PathParam("entityType") EntityType entityType,
@PathParam("entityId") Integer entityId
) throws Exception {
return listAccessesForEntityByPermType(entityType, entityId, AccessType.WRITE);
}
/**
* Grant group of permissions (READ / WRITE / ...) for the specified entity to the given role.
* Only owner of the entity can do that.
*
* @summary Grant permissions
* @param entityType The entity type
* @param entityId The entity ID
* @param roleId The role ID
* @param accessRequestDTO The access request object
* @throws Exception
*/
@POST
@Path("/access/{entityType}/{entityId}/role/{roleId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void grantEntityPermissionsForRole(
@PathParam("entityType") EntityType entityType,
@PathParam("entityId") Integer entityId,
@PathParam("roleId") Long roleId,
AccessRequestDTO accessRequestDTO
) throws Exception {
permissionService.checkCommonEntityOwnership(entityType, entityId);
Map<String, String> permissionTemplates = permissionService.getTemplatesForType(entityType, accessRequestDTO.getAccessType());
RoleEntity role = permissionManager.getRole(roleId);
permissionManager.addPermissionsFromTemplate(role, permissionTemplates, entityId.toString());
}
/**
* Remove group of permissions for the specified entity to the given role.
*
* @summary Remove permissions
* @param entityType The entity type
* @param entityId The entity ID
* @param roleId The role ID
* @param accessRequestDTO The access request object
* @throws Exception
*/
@DELETE
@Path("/access/{entityType}/{entityId}/role/{roleId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void revokeEntityPermissionsFromRole(
@PathParam("entityType") EntityType entityType,
@PathParam("entityId") Integer entityId,
@PathParam("roleId") Long roleId,
AccessRequestDTO accessRequestDTO
) throws Exception {
permissionService.checkCommonEntityOwnership(entityType, entityId);
Map<String, String> permissionTemplates = permissionService.getTemplatesForType(entityType, accessRequestDTO.getAccessType());
permissionService.removePermissionsFromRole(permissionTemplates, entityId, roleId);
}
}
| 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/security/dto/AccessRequestDTO.java | src/main/java/org/ohdsi/webapi/security/dto/AccessRequestDTO.java | package org.ohdsi.webapi.security.dto;
import org.ohdsi.webapi.security.AccessType;
public class AccessRequestDTO {
private AccessType accessType;
public AccessType getAccessType() {
return accessType;
}
public void setAccessType(AccessType 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/security/dto/RoleDTO.java | src/main/java/org/ohdsi/webapi/security/dto/RoleDTO.java | package org.ohdsi.webapi.security.dto;
public class RoleDTO {
private Long id;
private String name;
public RoleDTO() {
}
public RoleDTO(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long 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/security/model/CohortCharacterizationPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/CohortCharacterizationPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class CohortCharacterizationPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("cohort-characterization:%s:put", "Update Cohort Characterization with ID = %s");
put("cohort-characterization:%s:delete", "Delete Cohort Characterization with ID = %s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("cohort-characterization:%s:get", "Get cohort characterization");
put("cohort-characterization:%s:generation:get", "Get cohort characterization generations");
put("cohort-characterization:%s:design:get", "Get cohort characterization design");
put("cohort-characterization:design:%s:get", "view cohort characterization with id %s");
put("cohort-characterization:%s:version:get", "Get list of characterization versions");
put("cohort-characterization:%s:version:*:get", "Get list of characterization version");
}};
public CohortCharacterizationPermissionSchema() {
super(EntityType.COHORT_CHARACTERIZATION, readPermissions, writePermissions);
}
}
| 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/security/model/EntityPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/EntityPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.ohdsi.webapi.model.CommonEntity;
import org.ohdsi.webapi.shiro.Entities.RoleEntity;
import org.ohdsi.webapi.shiro.PermissionManager;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public abstract class EntityPermissionSchema {
private final EntityType entityType;
private final Map<String, String> readPermissions;
private final Map<String, String> writePermissions;
@Autowired
protected PermissionManager permissionManager;
public EntityPermissionSchema(EntityType entityType, Map<String, String> readPermissions, Map<String, String> writePermissions) {
this.entityType = entityType;
this.readPermissions = readPermissions;
this.writePermissions = Collections.unmodifiableMap(writePermissions);
}
public EntityType getEntityType() {
return entityType;
}
public Map<String, String> getReadPermissions() {
return readPermissions;
}
public Map<String, String> getWritePermissions() {
return writePermissions;
}
public Map<String, String> getAllPermissions() {
Map<String, String> permissions = new HashMap<>();
permissions.putAll(getReadPermissions());
permissions.putAll(getWritePermissions());
return permissions;
}
public void onInsert(CommonEntity commonEntity) {
addPermissionsToCurrentUserFromTemplate(commonEntity, getAllPermissions());
}
public void onDelete(CommonEntity commonEntity) {
Map<String, String> permissionTemplates = getAllPermissions();
permissionManager.removePermissionsFromTemplate(permissionTemplates, commonEntity.getId().toString());
}
protected void addPermissionsToCurrentUserFromTemplate(CommonEntity commonEntity, Map<String, String> template) {
String login = permissionManager.getSubjectName();
RoleEntity role = permissionManager.getUserPersonalRole(login);
permissionManager.addPermissionsFromTemplate(role, template, commonEntity.getId().toString());
}
}
| 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/security/model/PathwayAnalysisPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/PathwayAnalysisPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class PathwayAnalysisPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("pathway-analysis:%s:put", "Update Pathway Analysis with ID = %s");
put("pathway-analysis:%s:sql:*:get", "Get analysis sql for Pathway Analysis with ID = %s");
put("pathway-analysis:%s:delete", "Delete Pathway Analysis with ID = %s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("pathway-analysis:%s:get", "Get Pathways Analysis instance");
put("pathway-analysis:%s:generation:get", "Get Pathways Analysis generations list");
put("pathway-analysis:%s:version:get", "Get list of pathway analysis versions");
put("pathway-analysis:%s:version:*:get", "Get pathway analysis version");
}
};
public PathwayAnalysisPermissionSchema() {
super(EntityType.PATHWAY_ANALYSIS, readPermissions, writePermissions);
}
}
| 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/security/model/CohortDefinitionPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/CohortDefinitionPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class CohortDefinitionPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("cohortdefinition:%s:put", "Update Cohort Definition with ID = %s");
put("cohortdefinition:%s:delete", "Delete Cohort Definition with ID = %s");
put("cohortdefinition:%s:check:post", "Fix Cohort Definition with ID = %s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("cohortdefinition:%s:get", "Get Cohort Definition by ID");
put("cohortdefinition:%s:info:get","");
put("cohortdefinition:%s:version:get", "Get list of cohort versions");
put("cohortdefinition:%s:version:*:get", "Get cohort version");
}
};
public CohortDefinitionPermissionSchema() {
super(EntityType.COHORT_DEFINITION, readPermissions, writePermissions);
}
}
| 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/security/model/TagPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/TagPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class TagPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("tag:%s:delete", "Delete tag");
put("tag:%s:put", "Update tag");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("tag:get", "view tag with id %s");
put("tag:search:get", "Resolve tag %s expression");
}
};
public TagPermissionSchema() {
super(EntityType.TAG, new HashMap<>(), writePermissions);
}
}
| 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/security/model/UserSimpleAuthorizationInfo.java | src/main/java/org/ohdsi/webapi/security/model/UserSimpleAuthorizationInfo.java | package org.ohdsi.webapi.security.model;
import java.util.List;
import java.util.Map;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
public class UserSimpleAuthorizationInfo extends SimpleAuthorizationInfo {
private Long userId;
private String login;
private Map<String,List<Permission>> permissionIdx;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Map<String, List<Permission>> getPermissionIdx() {
return permissionIdx;
}
public void setPermissionIdx(Map<String, List<Permission>> permissionIdx) {
this.permissionIdx = permissionIdx;
}
}
| 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/security/model/IncidenceRatePermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/IncidenceRatePermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class IncidenceRatePermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("ir:%s:get", "Read Incidence Rate with ID=%s"); // TODO
put("ir:%s:export:get", "Export Incidence Rate with ID=%s");
put("ir:%s:put", "Edit Incidence Rate with ID=%s");
put("ir:%s:delete", "Delete Incidence Rate with ID=%s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("ir:%s:get", "view list of incident rates");
put("ir:%s:version:get", "Get list of IR analsis versions");
put("ir:%s:version:*:get", "Get IR analysis version");
put("ir:%s:copy:get","Copy incidence rate");
put("ir:%s:info:get","Get IR info");
put("ir:%s:design:get","Export Incidence Rates design");
}
};
public IncidenceRatePermissionSchema() {
super(EntityType.INCIDENCE_RATE, readPermissions, writePermissions);
}
}
| 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/security/model/ReusablePermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/ReusablePermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class ReusablePermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("reusable:%s:delete", "Delete reusable");
put("reusable:%s:put", "Update reusable");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("reusable:%s:get", "view reusable with id %s");
put("reusable:%s:expression:get", "Resolve reusable %s expression");
put("reusable:%s:version:*:get", "Get expression for reusable %s items for default source");
}
};
public ReusablePermissionSchema() {
super(EntityType.REUSABLE, new HashMap<>(), writePermissions);
}
}
| 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/security/model/EstimationPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/EstimationPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class EstimationPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("estimation:%s:put", "Edit Estimation with ID=%s");
put("estimation:%s:delete", "Delete Estimation with ID=%s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("estimation:%s:get", "Get Estimation instance");
put("estimation:%s:generation:get", "View Estimation Generations");
put("estimation:%s:copy:get", "Copy Estimation instance");
put("estimation:%s:download:get", "Download Estimation package");
put("estimation:%s:export:get", "Export Estimation");
put("estimation:%s:generation:get", "View Estimation Generations");
put("comparativecohortanalysis:%s:get","Get estimation");
}
};
public EstimationPermissionSchema() {
super(EntityType.ESTIMATION, readPermissions, writePermissions);
}
}
| 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/security/model/EntityPermissionSchemaResolver.java | src/main/java/org/ohdsi/webapi/security/model/EntityPermissionSchemaResolver.java | package org.ohdsi.webapi.security.model;
import org.ohdsi.webapi.model.CommonEntity;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class EntityPermissionSchemaResolver {
private static Map<EntityType, EntityPermissionSchema> entityPermissionSchemas = new HashMap<>();
public EntityPermissionSchemaResolver(List<EntityPermissionSchema> entityPermissionSchemaList) {
entityPermissionSchemaList.forEach(s -> entityPermissionSchemas.put(s.getEntityType(), s));
}
public EntityPermissionSchema getForType(EntityType entityType) {
return entityPermissionSchemas.get(entityType);
}
public EntityPermissionSchema getForClass(Class<? extends CommonEntity> clazz) {
return getForType(getEntityType(clazz));
}
public EntityType getEntityType(Class<? extends CommonEntity> clazz) {
return Arrays.stream(EntityType.values())
.filter(e -> e.getEntityClass().isAssignableFrom(clazz))
.findFirst()
.orElse(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/security/model/ConceptSetPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/ConceptSetPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class ConceptSetPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("conceptset:%s:put", "Update Concept Set with ID = %s");
put("conceptset:%s:items:put", "Update Items of Concept Set with ID = %s");
put("conceptset:%s:annotation:*:delete", "Delete Annotations of Concept Set with ID = %s");
put("conceptset:%s:delete", "Delete Concept Set with ID = %s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("conceptset:%s:get", "view conceptset definition with id %s");
put("conceptset:%s:expression:get", "Resolve concept set %s expression");
put("conceptset:%s:annotation:get", "Resolve concept set annotations");
put("conceptset:%s:version:*:expression:get", "Get expression for concept set %s items for default source");
}};
public ConceptSetPermissionSchema() {
super(EntityType.CONCEPT_SET, readPermissions, writePermissions);
}
}
| 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/security/model/EntityType.java | src/main/java/org/ohdsi/webapi/security/model/EntityType.java | package org.ohdsi.webapi.security.model;
import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity;
import org.ohdsi.webapi.cohortdefinition.CohortDefinition;
import org.ohdsi.webapi.cohortsample.CohortSample;
import org.ohdsi.webapi.conceptset.ConceptSet;
import org.ohdsi.webapi.estimation.Estimation;
import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity;
import org.ohdsi.webapi.ircalc.IncidenceRateAnalysis;
import org.ohdsi.webapi.model.CommonEntity;
import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity;
import org.ohdsi.webapi.prediction.PredictionAnalysis;
import org.ohdsi.webapi.reusable.domain.Reusable;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.tag.domain.Tag;
import org.ohdsi.webapi.tool.Tool;
public enum EntityType {
COHORT_DEFINITION(CohortDefinition.class),
CONCEPT_SET(ConceptSet.class),
COHORT_CHARACTERIZATION(CohortCharacterizationEntity.class),
PATHWAY_ANALYSIS(PathwayAnalysisEntity.class),
FE_ANALYSIS(FeAnalysisEntity.class),
INCIDENCE_RATE(IncidenceRateAnalysis.class),
SOURCE(Source.class),
ESTIMATION(Estimation.class),
PREDICTION(PredictionAnalysis.class),
COHORT_SAMPLE(CohortSample.class),
TAG(Tag.class),
TOOL(Tool.class),
REUSABLE(Reusable.class);
private final Class<? extends CommonEntity> entityClass;
EntityType(Class<? extends CommonEntity> entityClass) {
this.entityClass = entityClass;
}
public Class<? extends CommonEntity> getEntityClass() {
return entityClass;
}
}
| 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/security/model/ToolPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/ToolPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class ToolPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("tool:%s:delete", "Delete Tool with id = %s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {
{
put("tool:%s:get", "View Tool with id = %s");
}
};
public ToolPermissionSchema() {
super(EntityType.TOOL, readPermissions, writePermissions);
}
} | 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/security/model/CohortSamplePermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/CohortSamplePermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class CohortSamplePermissionSchema extends EntityPermissionSchema {
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("cohortsample:*:*:%s:get", "Get Cohort Sample with ID = %s");
}};
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("cohortsample:*:*:%s:delete", "Delete Cohort Sample with ID = %s");
}};
public CohortSamplePermissionSchema() {
super(EntityType.COHORT_SAMPLE, readPermissions, writePermissions);
}
}
| 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/security/model/SourcePermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/SourcePermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.ohdsi.webapi.model.CommonEntity;
import org.ohdsi.webapi.shiro.Entities.RoleEntity;
import org.ohdsi.webapi.source.Source;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import static org.ohdsi.webapi.shiro.management.Security.SOURCE_ACCESS_PERMISSION;
@Component
public class SourcePermissionSchema extends EntityPermissionSchema {
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("cohortdefinition:*:report:%s:get", "Get Inclusion Rule Report for Source with SourceKey = %s");
put("cohortdefinition:*:generate:%s:get", "Generate Cohort on Source with SourceKey = %s");
put("cohortdefinition:*:cancel:%s:get", "Cancel Cohort Generation on Source with SourceKey = %s");
put("vocabulary:%s:*:get", "Get vocabulary info on Source with SourceKey = %s");
put("vocabulary:%s:included-concepts:count:post", "Get vocab concept counts on Source with SourceKey = %s");
put("vocabulary:%s:resolveConceptSetExpression:post", "Resolve concept set expression on Source with SourceKey = %s");
put("vocabulary:%s:lookup:identifiers:post", "Lookup identifiers on Source with SourceKey = %s");
put("vocabulary:%s:lookup:identifiers:ancestors:post", "Lookup identifiers ancestors on Source with SourceKey = %s");
put("vocabulary:%s:lookup:mapped:post", "Lookup mapped identifiers on Source with SourceKey = %s");
put("vocabulary:%s:lookup:recommended:post", "Lookup recommendations on Source with SourceKey = %s");
put("vocabulary:%s:compare:post", "Compare concept sets on Source with SourceKey = %s");
put("vocabulary:%s:optimize:post", "Optimize concept sets on Source with SourceKey = %s");
put("vocabulary:%s:concept:*:get", "Get concept on Source with SourceKey = %s");
put("vocabulary:%s:concept:*:related:get", "Get related concepts on Source with SourceKey = %s");
put("vocabulary:%s:search:post", "Search vocab on Source with SourceKey = %s");
put("vocabulary:%s:search:*:get", "Search vocab on Source with SourceKey = %s");
put("cdmresults:%s:*:get", "Get Achilles reports on Source with SourceKey = %s");
put("cdmresults:%s:conceptRecordCount:post", "Get Achilles concept counts on Source with SourceKey = %s");
put("cdmresults:%s:*:*:get", "Get Achilles reports details on Source with SourceKey = %s");
put("cdmresults:%s:clearcache:post", "Clear the Achilles and CDM results caches on Source with SourceKey = %s");
put("cohortresults:%s:*:*:get", "Get cohort results on Source with SourceKey = %s");
put("cohortresults:%s:*:*:*:get", "Get cohort results details on Source with SourceKey = %s");
put("cohortresults:%s:*:healthcareutilization:*:*:get", "Get cohort results baseline on period for Source with SourceKey = %s");
put("cohortresults:%s:*:healthcareutilization:*:*:*:get", "Get cohort results baseline on occurrence for Source with SourceKey = %s");
put("ir:*:execute:%s:get", "Generate IR on Source with SourceKey = %s");
put("ir:*:execute:%s:delete", "Cancel IR generation on Source with SourceKey = %s");
put("ir:*:info:%s:get", "Get IR execution info on Source with SourceKey = %s");
put("ir:*:report:%s:get", "Get IR generation report with SourceKey = %s");
put("ir:%s:info:*:delete", "Delete IR generation report with ID=%s");
put("%s:person:*:get", "Get person's profile on Source with SourceKey = %s");
put("vocabulary:%s:lookup:sourcecodes:post", "Lookup source codes in Source with SourceKey = %s");
put("cohort-characterization:*:generation:%s:post", "Generate Cohort Characterization on Source with SourceKey = %s");
put("cohort-characterization:*:generation:%s:delete", "Cancel Generation of Cohort Characterization on Source with SourceKey = %s");
put("pathway-analysis:*:generation:%s:post", "Generate Pathway Analysis on Source with SourceKey = %s");
put("pathway-analysis:*:generation:%s:delete", "Cancel Generation of Pathway Analysis on Source with SourceKey = %s");
put("vocabulary:%s:concept:*:ancestorAndDescendant:get", "Get ancestor and descendants on Source with SourceKey = %s");
put(SOURCE_ACCESS_PERMISSION, "Access to Source with SourceKey = %s");
}};
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("source:%s:put", "Edit Source with sourceKey=%s");
put("source:%s:get", "Read Source with sourceKey=%s");
put("source:%s:delete", "Delete Source with sourceKey=%s");
}};
public SourcePermissionSchema() {
super(EntityType.SOURCE, readPermissions, writePermissions);
}
@Override
public void onInsert(CommonEntity commonEntity) {
addSourceUserRole(commonEntity);
addPermissionsToCurrentUserFromTemplate(commonEntity, getWritePermissions());
}
@Override
public void onDelete(CommonEntity commonEntity) {
super.onDelete(commonEntity);
dropSourceUserRole(commonEntity);
}
public void addSourceUserRole(CommonEntity commonEntity) {
Source source = (Source) commonEntity;
final String roleName = getSourceRoleName(source.getSourceKey());
final RoleEntity role;
if (permissionManager.roleExists(roleName)) {
role = permissionManager.getSystemRoleByName(roleName);
} else {
role = permissionManager.addRole(roleName, true);
}
permissionManager.addPermissionsFromTemplate(role, getReadPermissions(), source.getSourceKey());
}
private void dropSourceUserRole(CommonEntity commonEntity) {
Source source = (Source) commonEntity;
final String roleName = getSourceRoleName(source.getSourceKey());
if (permissionManager.roleExists(roleName)) {
RoleEntity role = permissionManager.getSystemRoleByName(roleName);
permissionManager.removePermissionsFromTemplate(getReadPermissions(), source.getSourceKey());
permissionManager.removeRole(role.getId());
}
}
private String getSourceRoleName(String sourceKey) {
return String.format("Source user (%s)", sourceKey);
}
}
| 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/security/model/PredictionPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/PredictionPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class PredictionPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("prediction:%s:put", "Edit Estimation with ID=%s");
put("prediction:%s:delete", "Delete Estimation with ID=%s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("prediction:%s:get", "Get Prediction instance");
put("prediction:%s:copy:get", "Copy Prediction instance");
put("prediction:%s:download:get", "Download Prediction package");
put("prediction:%s:export:get", "Export Prediction");
put("prediction:%s:generation:get", "View Prediction Generations");
put("prediction:%s:exists:get", "Check name uniqueness of prediction");
put("plp:%s:get", "Get population level prediction");
}
};
public PredictionPermissionSchema() {
super(EntityType.PREDICTION, readPermissions, writePermissions);
}
}
| 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/security/model/FeatureAnalysisPermissionSchema.java | src/main/java/org/ohdsi/webapi/security/model/FeatureAnalysisPermissionSchema.java | package org.ohdsi.webapi.security.model;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class FeatureAnalysisPermissionSchema extends EntityPermissionSchema {
private static Map<String, String> writePermissions = new HashMap<String, String>() {{
put("feature-analysis:%s:put", "Update Feature Analysis with ID = %s");
put("feature-analysis:%s:delete", "Delete Feature Analysis with ID = %s");
}};
private static Map<String, String> readPermissions = new HashMap<String, String>() {{
put("feature-analysis:%s:get", "get feature analysis");
put("feature-analysis:aggregates:get", "feature-analysis:aggregates:get");
}
};
public FeatureAnalysisPermissionSchema() {
super(EntityType.FE_ANALYSIS, readPermissions, writePermissions);
}
}
| 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/security/converter/RoleEntityToRoleDTOConverter.java | src/main/java/org/ohdsi/webapi/security/converter/RoleEntityToRoleDTOConverter.java | package org.ohdsi.webapi.security.converter;
import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter;
import org.ohdsi.webapi.security.dto.RoleDTO;
import org.ohdsi.webapi.shiro.Entities.RoleEntity;
import org.springframework.stereotype.Component;
@Component
public class RoleEntityToRoleDTOConverter extends BaseConversionServiceAwareConverter<RoleEntity, RoleDTO> {
@Override
public RoleDTO convert(RoleEntity roleEntity) {
return new RoleDTO(roleEntity.getId(), roleEntity.getName());
}
}
| 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/security/config/HibernateListenerConfigurer.java | src/main/java/org/ohdsi/webapi/security/config/HibernateListenerConfigurer.java | package org.ohdsi.webapi.security.config;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;
import org.ohdsi.webapi.security.listener.EntityDeleteEventListener;
import org.ohdsi.webapi.security.listener.EntityInsertEventListener;
import org.ohdsi.webapi.security.model.EntityPermissionSchemaResolver;
import org.ohdsi.webapi.shiro.management.DisabledSecurity;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
@Configuration
@ConditionalOnMissingBean(value = DisabledSecurity.class)
public class HibernateListenerConfigurer {
@PersistenceUnit
private EntityManagerFactory emf;
private final EntityPermissionSchemaResolver entityPermissionSchemaResolver;
public HibernateListenerConfigurer(EntityPermissionSchemaResolver entityPermissionSchemaResolver) {
this.entityPermissionSchemaResolver = entityPermissionSchemaResolver;
}
@PostConstruct
protected void init() {
SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(new EntityInsertEventListener(entityPermissionSchemaResolver));
registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(new EntityDeleteEventListener(entityPermissionSchemaResolver));
}
}
| 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/security/listener/EntityInsertEventListener.java | src/main/java/org/ohdsi/webapi/security/listener/EntityInsertEventListener.java | package org.ohdsi.webapi.security.listener;
import org.hibernate.event.spi.PreInsertEvent;
import org.hibernate.event.spi.PreInsertEventListener;
import org.ohdsi.webapi.model.CommonEntity;
import org.ohdsi.webapi.security.model.EntityPermissionSchema;
import org.ohdsi.webapi.security.model.EntityPermissionSchemaResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class EntityInsertEventListener implements PreInsertEventListener {
private static final Logger LOG = LoggerFactory.getLogger(EntityInsertEventListener.class);
private final EntityPermissionSchemaResolver entityPermissionSchemaResolver;
public EntityInsertEventListener(EntityPermissionSchemaResolver entityPermissionSchemaResolver) {
this.entityPermissionSchemaResolver = entityPermissionSchemaResolver;
}
@Override
public boolean onPreInsert(PreInsertEvent event) {
Object entity = event.getEntity();
if (CommonEntity.class.isAssignableFrom(entity.getClass())) {
CommonEntity commonEntity = (CommonEntity) entity;
EntityPermissionSchema permissionSchema = entityPermissionSchemaResolver.getForClass(commonEntity.getClass());
if (permissionSchema != null) {
// NOTE:
// Fails if executed within the same thread
// http://anshuiitk.blogspot.com/2010/11/hibernate-pre-database-opertaion-event.html
Future<Boolean> future = new SimpleAsyncTaskExecutor().submit(() -> {
permissionSchema.onInsert(commonEntity);
return true;
});
try {
if (future.get()) {
return false;
}
} catch (InterruptedException | ExecutionException ex) {
LOG.error(ex.getMessage(), ex);
}
}
throw new RuntimeException();
}
return false;
}
}
| 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/security/listener/EntityDeleteEventListener.java | src/main/java/org/ohdsi/webapi/security/listener/EntityDeleteEventListener.java | package org.ohdsi.webapi.security.listener;
import org.hibernate.event.spi.PostDeleteEvent;
import org.hibernate.event.spi.PostDeleteEventListener;
import org.hibernate.persister.entity.EntityPersister;
import org.ohdsi.webapi.model.CommonEntity;
import org.ohdsi.webapi.security.model.EntityPermissionSchema;
import org.ohdsi.webapi.security.model.EntityPermissionSchemaResolver;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
public class EntityDeleteEventListener implements PostDeleteEventListener {
private final EntityPermissionSchemaResolver entityPermissionSchemaResolver;
public EntityDeleteEventListener(EntityPermissionSchemaResolver entityPermissionSchemaResolver) {
this.entityPermissionSchemaResolver = entityPermissionSchemaResolver;
}
@Override
public void onPostDelete(PostDeleteEvent postDeleteEvent) {
final Object entity = postDeleteEvent.getEntity();
if (CommonEntity.class.isAssignableFrom(entity.getClass())) {
CommonEntity commonEntity = (CommonEntity) entity;
EntityPermissionSchema permissionSchema = entityPermissionSchemaResolver.getForClass(commonEntity.getClass());
if (permissionSchema != null) {
new SimpleAsyncTaskExecutor().execute(() -> permissionSchema.onDelete(commonEntity));
}
}
}
@Override
public boolean requiresPostCommitHanding(EntityPersister entityPersister) {
return false;
}
}
| 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/conceptset/ConceptSetComparison.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetComparison.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohdsi.webapi.conceptset;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.sql.Date;
/**
*
* @author Anthony Sena <https://github.com/ohdsi>
*/
@JsonInclude(JsonInclude.Include.ALWAYS)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConceptSetComparison {
@JsonProperty("conceptId")
public Long conceptId;
@JsonProperty("conceptIn1Only")
public Long conceptIn1Only;
@JsonProperty("conceptIn2Only")
public Long conceptIn2Only;
@JsonProperty("conceptIn1And2")
public Long conceptIn1And2;
@JsonProperty("conceptName")
public String conceptName;
@JsonProperty("standardConcept")
public String standardConcept;
@JsonProperty("invalidReason")
public String invalidReason;
@JsonProperty("conceptCode")
public String conceptCode;
@JsonProperty("domainId")
public String domainId;
@JsonProperty("vocabularyId")
public String vocabularyId;
@JsonProperty("validStartDate")
public Date validStartDate;
@JsonProperty("validEndDate")
public Date validEndDate;
@JsonProperty("conceptClassId")
public String conceptClassId;
@JsonProperty("nameMismatch")
public boolean nameMismatch;
}
| 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/conceptset/ConceptSetOptimizationResult.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetOptimizationResult.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohdsi.webapi.conceptset;
import org.ohdsi.circe.vocabulary.ConceptSetExpression;
/**
*
* @author Anthony Sena <https://github.com/ohdsi>
*/
public class ConceptSetOptimizationResult {
public ConceptSetExpression optimizedConceptSet;
public ConceptSetExpression removedConceptSet;
public ConceptSetOptimizationResult(){
this.optimizedConceptSet = new ConceptSetExpression();
this.removedConceptSet = new ConceptSetExpression();
}
}
| 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/conceptset/ConceptSetItemRepository.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetItemRepository.java | /*
* Copyright 2015 fdefalco.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ohdsi.webapi.conceptset;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
/**
*
* @author fdefalco
*/
public interface ConceptSetItemRepository extends CrudRepository<ConceptSetItem, Integer> {
List<ConceptSetItem> findAllByConceptSetId(Integer conceptSetId);
void deleteByConceptSetId(Integer conceptSetId);
}
| 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/conceptset/ConceptSetGenerationInfoRepository.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetGenerationInfoRepository.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohdsi.webapi.conceptset;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
/**
*
* @author Anthony Sena <https://github.com/ohdsi>
*/
public interface ConceptSetGenerationInfoRepository extends CrudRepository<ConceptSetGenerationInfo, Integer> {
@Query("from ConceptSetGenerationInfo where concept_set_id = ?1")
List<ConceptSetGenerationInfo> findAllByConceptSetId(Integer conceptSetId);
void deleteByConceptSetId(Integer conceptSetId);
}
| 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/conceptset/ConceptSetItem.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetItem.java | /*
* Copyright 2015 fdefalco.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ohdsi.webapi.conceptset;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
*
* @author fdefalco
*/
@Entity(name = "ConceptSetItem")
@Table(name="concept_set_item")
public class ConceptSetItem implements Serializable{
@Id
@GenericGenerator(
name = "concept_set_item_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "concept_set_item_sequence"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "concept_set_item_generator")
@Column(name="concept_set_item_id")
private int id;
@Column(name="concept_set_id")
private int conceptSetId;
@Column(name="concept_id")
private long conceptId;
@Column(name="is_excluded")
private int isExcluded;
@Column(name="include_descendants")
private int includeDescendants;
@Column(name="include_mapped")
private int includeMapped;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getConceptSetId() {
return conceptSetId;
}
public void setConceptSetId(int conceptSetId) {
this.conceptSetId = conceptSetId;
}
public long getConceptId() {
return conceptId;
}
public void setConceptId(long conceptId) {
this.conceptId = conceptId;
}
public int getIsExcluded() {
return isExcluded;
}
public void setIsExcluded(int isExcluded) {
this.isExcluded = isExcluded;
}
public int getIncludeDescendants() {
return includeDescendants;
}
public void setIncludeDescendants(int includeDescendants) {
this.includeDescendants = includeDescendants;
}
public int getIncludeMapped() {
return includeMapped;
}
public void setIncludeMapped(int includeMapped) {
this.includeMapped = includeMapped;
}
}
| 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/conceptset/ConceptSetGenerationInfoKey.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetGenerationInfoKey.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohdsi.webapi.conceptset;
import java.io.Serializable;
/**
*
* @author Anthony Sena <https://github.com/ohdsi>
*/
public class ConceptSetGenerationInfoKey implements Serializable {
private int conceptSetId;
private int 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/conceptset/ConceptSetGenerationInfo.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetGenerationInfo.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohdsi.webapi.conceptset;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Lob;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.ohdsi.webapi.GenerationStatus;
/**
*
* @author Anthony Sena <https://github.com/ohdsi>
*/
@Entity(name = "ConceptSetGenerationInfo")
@Table(name = "concept_set_generation_info")
@IdClass(ConceptSetGenerationInfoKey.class)
public class ConceptSetGenerationInfo implements Serializable {
private static long serialVersionUID = 1L;
public ConceptSetGenerationInfo() {
}
public ConceptSetGenerationInfo(ConceptSet conceptSet, Integer sourceId, Integer generationType) {
}
@Id
@Column(name = "concept_set_id")
private Integer conceptSetId;
@Id
@Column(name = "source_id")
private Integer sourceId;
@Column(name = "generation_type")
private ConceptSetGenerationType generationType;
@Column(name = "start_time")
private Date startTime;
@Column(name = "execution_duration")
private Integer executionDuration;
@Column(name = "status")
private GenerationStatus status;
@Column(name = "is_valid")
private boolean isValid;
@Column(name = "is_canceled")
private boolean isCanceled;
@Lob
@Type(type = "org.hibernate.type.TextType")
private String params;
/**
* @return the conceptSetId
*/
public Integer getConceptSetId() {
return conceptSetId;
}
/**
* @return the executionDuration
*/
public Integer getExecutionDuration() {
return executionDuration;
}
/**
* @return the sourceId
*/
public Integer getSourceId() {
return sourceId;
}
/**
* @return the startTime
*/
public Date getStartTime() {
return startTime;
}
/**
* @return the status
*/
public GenerationStatus getStatus() {
return status;
}
/**
* @return the isValid
*/
public boolean isIsValid() {
return isValid;
}
public boolean isCanceled() {
return isCanceled;
}
public void setCanceled(boolean canceled) {
isCanceled = canceled;
}
/**
* @param conceptSetId the conceptSetId to set
*/
public void setConceptSetId(Integer conceptSetId) {
this.conceptSetId = conceptSetId;
}
/**
* @param executionDuration the executionDuration to set
*/
public void setExecutionDuration(Integer executionDuration) {
this.executionDuration = executionDuration;
}
/**
* @param isValid the isValid to set
*/
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
/**
* @param sourceId the sourceId to set
*/
public void setSourceId(Integer sourceId) {
this.sourceId = sourceId;
}
/**
* @param startTime the startTime to set
*/
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
/**
* @param status the status to set
*/
public void setStatus(GenerationStatus status) {
this.status = status;
}
/**
* @return the generationType
*/
public ConceptSetGenerationType getGenerationType() {
return generationType;
}
/**
* @param generationType the generationType to set
*/
public void setGenerationType(ConceptSetGenerationType generationType) {
this.generationType = generationType;
}
/**
* @return the params
*/
public String getParams() {
return params;
}
/**
* @param params the params to set
*/
public void setParams(String params) {
this.params = params;
}
}
| 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/conceptset/ConceptSetExport.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetExport.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohdsi.webapi.conceptset;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Collection;
import org.ohdsi.circe.vocabulary.ConceptSetExpression;
import org.ohdsi.vocabulary.Concept;
/**
*
* @author Anthony Sena <https://github.com/ohdsi>
*/
public class ConceptSetExport {
@JsonProperty("ConceptSetId")
public int ConceptSetId;
@JsonProperty("ConceptSetName")
public String ConceptSetName;
@JsonProperty("ConceptSetExpression")
public ConceptSetExpression csExpression;
@JsonProperty("IdentifierConcepts")
public Collection<Concept> identifierConcepts;
@JsonProperty("MappedConcepts")
public Collection<Concept> mappedConcepts;
}
| 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/conceptset/ConceptSetGenerationTypeConverter.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetGenerationTypeConverter.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohdsi.webapi.conceptset;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
*
* @author Anthony Sena <https://github.com/ohdsi>
*/
@Converter(autoApply = true)
public class ConceptSetGenerationTypeConverter implements AttributeConverter<ConceptSetGenerationType, Integer>{
@Override
public Integer convertToDatabaseColumn(ConceptSetGenerationType status) {
switch (status) {
case NEGATIVE_CONTROLS:
return 0;
default:
throw new IllegalArgumentException("Unknown value: " + status);
}
}
@Override
public ConceptSetGenerationType convertToEntityAttribute(Integer statusValue) {
switch (statusValue) {
case 0: return ConceptSetGenerationType.NEGATIVE_CONTROLS;
default: throw new IllegalArgumentException("Unknown status value: " + statusValue);
}
}
}
| 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/conceptset/ConceptSetCrossReferenceImpl.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetCrossReferenceImpl.java | package org.ohdsi.webapi.conceptset;
import org.ohdsi.analysis.ConceptSetCrossReference;
public class ConceptSetCrossReferenceImpl implements ConceptSetCrossReference {
private Integer conceptSetId = null;
private String targetName = null;
private Integer targetIndex = 0;
private String propertyName = null;
/**
* The concept set ID
* @return conceptSetId
**/
@Override
public Integer getConceptSetId() {
return conceptSetId;
}
public void setConceptSetId(Integer conceptSetId) {
this.conceptSetId = conceptSetId;
}
/**
* The target object name that will utilize the concept set
* @return targetName
**/
@Override
public String getTargetName() {
return targetName;
}
public void setTargetName(String targetName) {
this.targetName = targetName;
}
/**
* The index of the target object
* @return targetIndex
**/
@Override
public Integer getTargetIndex() {
return targetIndex;
}
public void setTargetIndex(Integer targetIndex) {
this.targetIndex = targetIndex;
}
/**
* The property that will hold the list of concept IDs from the resolved concept set
* @return propertyName
**/
@Override
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
}
| 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/conceptset/ConceptSet.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSet.java | /*
* Copyright 2015 fdefalco.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ohdsi.webapi.conceptset;
import java.io.Serializable;
import java.util.Set;
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.Table;
import javax.persistence.OneToOne;
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;
/**
*
* @author fdefalco
*/
@Entity(name = "ConceptSet")
@Table(name="concept_set")
public class ConceptSet extends CommonEntityExt<Integer> implements Serializable {
@Id
@GenericGenerator(
name = "concept_set_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "concept_set_sequence"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "concept_set_generator")
@Column(name="concept_set_id")
private Integer id;
@Column(name="concept_set_name")
private String name;
@Column(name="description")
private String description;
@ManyToMany(targetEntity = Tag.class, fetch = FetchType.LAZY)
@JoinTable(name = "concept_set_tag",
joinColumns = @JoinColumn(name = "asset_id", referencedColumnName = "concept_set_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 Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 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/conceptset/ConceptSetGenerationType.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetGenerationType.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohdsi.webapi.conceptset;
/**
*
* @author Anthony Sena <https://github.com/ohdsi>
*/
public enum ConceptSetGenerationType {
NEGATIVE_CONTROLS
} | 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/conceptset/ConceptSetRepository.java | src/main/java/org/ohdsi/webapi/conceptset/ConceptSetRepository.java | /*
* Copyright 2015 fdefalco.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ohdsi.webapi.conceptset;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
/**
*
* @author fdefalco
*/
public interface ConceptSetRepository extends CrudRepository<ConceptSet, Integer> {
ConceptSet findById(Integer conceptSetId);
@Deprecated
@Query("SELECT cs FROM ConceptSet cs WHERE cs.name = :conceptSetName and cs.id <> :conceptSetId")
Collection<ConceptSet> conceptSetExists(@Param("conceptSetId") Integer conceptSetId, @Param("conceptSetName") String conceptSetName);
@Query("SELECT COUNT(cs) FROM ConceptSet cs WHERE cs.name = :conceptSetName and cs.id <> :conceptSetId")
int getCountCSetWithSameName(@Param("conceptSetId") Integer conceptSetId, @Param("conceptSetName") String conceptSetName);
@Query("SELECT cs FROM ConceptSet cs WHERE cs.name LIKE ?1 ESCAPE '\\'")
List<ConceptSet> findAllByNameStartsWith(String pattern);
Optional<ConceptSet> findByName(String name);
@Query("SELECT DISTINCT cs FROM ConceptSet cs JOIN FETCH cs.tags t WHERE lower(t.name) in :tagNames")
List<ConceptSet> 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/conceptset/dto/ConceptSetVersionFullDTO.java | src/main/java/org/ohdsi/webapi/conceptset/dto/ConceptSetVersionFullDTO.java | package org.ohdsi.webapi.conceptset.dto;
import org.ohdsi.webapi.conceptset.ConceptSetItem;
import org.ohdsi.webapi.service.dto.ConceptSetDTO;
import org.ohdsi.webapi.versioning.dto.VersionFullDTO;
import java.util.List;
public class ConceptSetVersionFullDTO extends VersionFullDTO<ConceptSetDTO> {
private List<ConceptSetItem> items;
public List<ConceptSetItem> getItems() {
return items;
}
public void setItems(List<ConceptSetItem> items) {
this.items = items;
}
}
| 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/conceptset/converter/CirceConceptSetToConceptSetItemConverter.java | src/main/java/org/ohdsi/webapi/conceptset/converter/CirceConceptSetToConceptSetItemConverter.java | package org.ohdsi.webapi.conceptset.converter;
import org.ohdsi.webapi.conceptset.ConceptSetItem;
import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter;
import org.springframework.stereotype.Component;
@Component
public class CirceConceptSetToConceptSetItemConverter<T extends org.ohdsi.circe.vocabulary.ConceptSetExpression.ConceptSetItem> extends BaseConversionServiceAwareConverter<T, ConceptSetItem> {
@Override
public ConceptSetItem convert(T source) {
ConceptSetItem csi = new ConceptSetItem();
csi.setConceptId(source.concept.conceptId);
csi.setIncludeDescendants(source.includeDescendants ? 1 : 0);
csi.setIncludeMapped(source.includeMapped ? 1 :0);
csi.setIsExcluded(source.isExcluded ? 1 : 0);
return csi;
}
}
| 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/conceptset/converter/ConceptSetToConceptSetVersionConverter.java | src/main/java/org/ohdsi/webapi/conceptset/converter/ConceptSetToConceptSetVersionConverter.java | package org.ohdsi.webapi.conceptset.converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ohdsi.webapi.conceptset.ConceptSet;
import org.ohdsi.webapi.conceptset.ConceptSetItem;
import org.ohdsi.webapi.conceptset.ConceptSetItemRepository;
import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter;
import org.ohdsi.webapi.versioning.domain.ConceptSetVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ConceptSetToConceptSetVersionConverter
extends BaseConversionServiceAwareConverter<ConceptSet, ConceptSetVersion> {
@Autowired
private ConceptSetItemRepository conceptSetItemRepository;
@Autowired
private ObjectMapper mapper;
@Override
public ConceptSetVersion convert(ConceptSet source) {
List<ConceptSetItem> items = conceptSetItemRepository.findAllByConceptSetId(source.getId());
String itemString;
try {
itemString = mapper.writeValueAsString(items);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
ConceptSetVersion target = new ConceptSetVersion();
target.setAssetId(source.getId());
target.setAssetJson(itemString);
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/conceptset/converter/ConceptSetVersionToConceptSetVersionFullDTOConverter.java | src/main/java/org/ohdsi/webapi/conceptset/converter/ConceptSetVersionToConceptSetVersionFullDTOConverter.java | package org.ohdsi.webapi.conceptset.converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ohdsi.webapi.conceptset.ConceptSet;
import org.ohdsi.webapi.conceptset.ConceptSetItem;
import org.ohdsi.webapi.conceptset.ConceptSetRepository;
import org.ohdsi.webapi.conceptset.dto.ConceptSetVersionFullDTO;
import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter;
import org.ohdsi.webapi.service.dto.ConceptSetDTO;
import org.ohdsi.webapi.util.ExceptionUtils;
import org.ohdsi.webapi.versioning.domain.ConceptSetVersion;
import org.ohdsi.webapi.versioning.dto.VersionDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ConceptSetVersionToConceptSetVersionFullDTOConverter
extends BaseConversionServiceAwareConverter<ConceptSetVersion, ConceptSetVersionFullDTO> {
@Autowired
private ConceptSetRepository conceptSetRepository;
@Autowired
private ObjectMapper mapper;
@Override
public ConceptSetVersionFullDTO convert(ConceptSetVersion source) {
List<ConceptSetItem> items;
try {
items = mapper.readValue(source.getAssetJson(),
new TypeReference<List<ConceptSetItem>>() {
});
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
ConceptSet conceptSet = conceptSetRepository.findById(source.getAssetId().intValue());
ExceptionUtils.throwNotFoundExceptionIfNull(conceptSet,
String.format("There is no concept set with id = %d.", source.getAssetId()));
ConceptSetVersionFullDTO target = new ConceptSetVersionFullDTO();
target.setItems(items);
target.setVersionDTO(conversionService.convert(source, VersionDTO.class));
target.setEntityDTO(conversionService.convert(conceptSet, ConceptSetDTO.class));
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/conceptset/converter/ConceptSetToExportConverter.java | src/main/java/org/ohdsi/webapi/conceptset/converter/ConceptSetToExportConverter.java | package org.ohdsi.webapi.conceptset.converter;
import com.odysseusinc.arachne.commons.converter.BaseConvertionServiceAwareConverter;
import org.ohdsi.circe.cohortdefinition.ConceptSet;
import org.ohdsi.webapi.conceptset.ConceptSetExport;
import org.springframework.stereotype.Component;
@Component
public class ConceptSetToExportConverter extends BaseConvertionServiceAwareConverter<ConceptSet, ConceptSetExport> {
@Override
protected ConceptSetExport createResultObject(ConceptSet conceptSet) {
return new ConceptSetExport();
}
@Override
protected void convert(ConceptSet conceptSet, ConceptSetExport export) {
export.ConceptSetId = conceptSet.id;
export.ConceptSetName = conceptSet.name;
export.csExpression = conceptSet.expression;
}
}
| 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/conceptset/annotation/ConceptSetAnnotationRepository.java | src/main/java/org/ohdsi/webapi/conceptset/annotation/ConceptSetAnnotationRepository.java | package org.ohdsi.webapi.conceptset.annotation;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface ConceptSetAnnotationRepository extends JpaRepository<ConceptSetAnnotation, Integer> {
@Query("DELETE FROM ConceptSetAnnotation cc WHERE cc.conceptSetId = :conceptSetId and cc.conceptId in :conceptId")
void deleteAnnotationByConceptSetIdAndInConceptId(int conceptSetId, List<Integer> conceptId);
void deleteAnnotationByConceptSetIdAndConceptId(int conceptSetId, int conceptId);
List<ConceptSetAnnotation> findByConceptSetId(int conceptSetId);
ConceptSetAnnotation findById(int id);
void deleteById(int id);
Optional<ConceptSetAnnotation> findConceptSetAnnotationByConceptIdAndConceptId(int conceptSetId, int conceptId);
}
| 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/conceptset/annotation/ConceptSetAnnotation.java | src/main/java/org/ohdsi/webapi/conceptset/annotation/ConceptSetAnnotation.java | package org.ohdsi.webapi.conceptset.annotation;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.ohdsi.webapi.model.CommonEntity;
import org.ohdsi.webapi.shiro.Entities.UserEntity;
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.ManyToOne;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
@Entity(name = "ConceptSetAnnotation")
@Table(name = "concept_set_annotation")
public class ConceptSetAnnotation implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GenericGenerator(
name = "concept_set_annotation_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "concept_set_annotation_sequence"),
@Parameter(name = "increment_size", value = "1")
}
)
@GeneratedValue(generator = "concept_set_annotation_generator")
@Column(name = "concept_set_annotation_id")
private Integer id;
@Column(name = "concept_set_id", nullable = false)
private Integer conceptSetId;
@Column(name = "concept_id")
private Integer conceptId;
@Column(name = "annotation_details")
private String annotationDetails;
@Column(name = "vocabulary_version")
private String vocabularyVersion;
@Column(name = "concept_set_version")
private Integer conceptSetVersion;
@Column(name = "copied_from_concept_set_ids")
private String copiedFromConceptSetIds;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "created_by_id", updatable = false)
private UserEntity createdBy;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "modified_by_id")
private UserEntity modifiedBy;
@Column(name = "created_date", updatable = false)
private Date createdDate;
@Column(name = "modified_date")
private Date modifiedDate;
public UserEntity getCreatedBy() {
return createdBy;
}
public void setCreatedBy(UserEntity createdBy) {
this.createdBy = createdBy;
}
public UserEntity getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(UserEntity modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getConceptSetId() {
return conceptSetId;
}
public void setConceptSetId(Integer conceptSetId) {
this.conceptSetId = conceptSetId;
}
public Integer getConceptId() {
return conceptId;
}
public void setConceptId(Integer conceptId) {
this.conceptId = conceptId;
}
public String getAnnotationDetails() {
return annotationDetails;
}
public void setAnnotationDetails(String annotationDetails) {
this.annotationDetails = annotationDetails;
}
public String getVocabularyVersion() {
return vocabularyVersion;
}
public void setVocabularyVersion(String vocabularyVersion) {
this.vocabularyVersion = vocabularyVersion;
}
public Integer getConceptSetVersion() {
return conceptSetVersion;
}
public void setConceptSetVersion(Integer conceptSetVersion) {
this.conceptSetVersion = conceptSetVersion;
}
public String getCopiedFromConceptSetIds() {
return copiedFromConceptSetIds;
}
public void setCopiedFromConceptSetIds(String copiedFromConceptSetIds) {
this.copiedFromConceptSetIds = copiedFromConceptSetIds;
}
}
| 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/audittrail/AuditTrailAspect.java | src/main/java/org/ohdsi/webapi/audittrail/AuditTrailAspect.java | package org.ohdsi.webapi.audittrail;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.shiro.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Component
@Aspect
@ConditionalOnProperty(value = "audit.trail.enabled", havingValue = "true")
public class AuditTrailAspect {
@Autowired
private AuditTrailService auditTrailService;
@Pointcut("@annotation(javax.ws.rs.GET)")
public void restGetPointcut() {
}
@Pointcut("@annotation(javax.ws.rs.POST)")
public void restPostPointcut() {
}
@Pointcut("@annotation(javax.ws.rs.PUT)")
public void restPutPointcut() {
}
@Pointcut("@annotation(javax.ws.rs.DELETE)")
public void restDeletePointcut() {
}
@Pointcut("execution(public * org.ohdsi.webapi.service.IRAnalysisResource+.*(..))")
public void irResource() {
}
@Pointcut("execution(public * org.ohdsi.webapi.job.NotificationController.*(..))")
public void notificationsPointcut() {
}
@Pointcut("execution(public * org.ohdsi.webapi.executionengine.controller.ScriptExecutionController.*(..))")
public void executionenginePointcut() {
}
@Pointcut("execution(public * org.ohdsi.webapi.service.VocabularyService.getInfo(..))")
public void vocabularyServiceGetInfoPointcut() {
}
@Pointcut("execution(public * org.ohdsi.webapi.info.InfoService.getInfo(..))")
public void webapiGetInfoPointcut() {
}
@Around("(restGetPointcut() || restPostPointcut() || restPutPointcut() || restDeletePointcut() || irResource())" +
" && " +
// exclude system calls
"!notificationsPointcut() && " +
"!executionenginePointcut() && " +
"!vocabularyServiceGetInfoPointcut() && " +
"!webapiGetInfoPointcut()")
public Object auditLog(final ProceedingJoinPoint joinPoint) throws Throwable {
final HttpServletRequest request = getHttpServletRequest();
if (request == null) { // system call
return joinPoint.proceed();
}
final AuditTrailEntry entry = new AuditTrailEntry();
entry.setRemoteHost(request.getRemoteHost());
final String token = TokenManager.extractToken(request);
if (token != null) {
try {
final String user = TokenManager.getSubject(token);
final String sessionId = (String) TokenManager.getBody(token).get(Constants.SESSION_ID);
entry.setCurrentUser(user);
entry.setSessionId(sessionId);
} catch (final ExpiredJwtException | SignatureException e ) {
// ignore expired or invalid token. let the application create a new one
}
}
entry.setActionLocation(request.getHeader(Constants.Headers.ACTION_LOCATION));
entry.setRequestMethod(request.getMethod());
entry.setRequestUri(request.getRequestURI());
entry.setQueryString(request.getQueryString());
try {
final Object returnedObject = joinPoint.proceed();
entry.setReturnedObject(returnedObject);
auditTrailService.logRestCall(entry, true);
return returnedObject;
} catch (final Throwable t) {
auditTrailService.logRestCall(entry, false);
throw t;
}
}
private HttpServletRequest getHttpServletRequest() {
try {
return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
} catch (final Exception e) {
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/audittrail/AuditTrailServiceImpl.java | src/main/java/org/ohdsi/webapi/audittrail/AuditTrailServiceImpl.java | package org.ohdsi.webapi.audittrail;
import com.cloudbees.syslog.Facility;
import com.cloudbees.syslog.Severity;
import com.cloudbees.syslog.SyslogMessage;
import org.apache.commons.lang3.StringUtils;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.cohortsample.dto.CohortSampleDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import javax.ws.rs.core.Response;
import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Component
class AuditTrailServiceImpl implements AuditTrailService {
private final Logger AUDIT_LOGGER = LoggerFactory.getLogger("audit");
private final Logger AUDIT_EXTRA_LOGGER = LoggerFactory.getLogger("audit-extra");
private static final int MAX_ENTRY_LENGTH = 2048;
private static final String EXTRA_LOG_REFERENCE_MESSAGE =
"... Log entry exceeds 2048 chars length. Please see the whole message in extra log file, entry id = %s";
private static final String USER_LOGIN_SUCCESS_TEMPLATE = "User successfully logged in: %s, sessionId = %s, remote-host = %s";
private static final String USER_LOGIN_FAILURE_TEMPLATE = "User login failed: %s, remote-host = %s";
private static final String USER_LOGOUT_SUCCESS_TEMPLATE = "User successfully logged out: %s";
private static final String USER_LOGOUT_FAILURE_TEMPLATE = "User logout failed: %s";
private static final String JOB_STARTED_TEMPLATE = "%s - Job %s execution started: %s";
private static final String JOB_COMPLETED_TEMPLATE = "%s - Job %s execution completed successfully: %s";
private static final String JOB_FAILED_TEMPLATE = "%s - Job %s execution failed: %s";
private static final String LIST_OF_TEMPLATE = "list of %s objects %s";
private static final String MAP_OF_TEMPLATE = "map (key: %s) of %s objects %s";
private static final String FILE_TEMPLATE = "file %s (%s bytes)";
private static final String PATIENT_IDS_TEMPLATE = " Patient IDs (%s): ";
private static final String FIELD_DIVIDER = " - ";
private static final String SPACE = " ";
private static final String FAILURE = "FAILURE (see application log for details)";
private static final String ANONYMOUS = "anonymous";
private static final String NO_SESSION = "NO_SESSION";
private static final String NO_LOCATION = "NO_LOCATION";
private static final String EMPTY_LIST = "empty list";
private static final String EMPTY_MAP = "empty map";
private final AtomicInteger extraLogIdSuffix = new AtomicInteger();
@Override
public void logSuccessfulLogin(final String login, final String sessionId, final String remoteHost) {
log(String.format(USER_LOGIN_SUCCESS_TEMPLATE, login, sessionId, remoteHost));
}
@Override
public void logFailedLogin(final String login, final String remoteHost) {
log(String.format(USER_LOGIN_FAILURE_TEMPLATE, login, remoteHost));
}
@Override
public void logSuccessfulLogout(final String login) {
log(String.format(USER_LOGOUT_SUCCESS_TEMPLATE, login));
}
@Override
public void logFailedLogout(final String login) {
log(String.format(USER_LOGOUT_FAILURE_TEMPLATE, login));
}
@Override
public void logRestCall(final AuditTrailEntry entry, final boolean success) {
final StringBuilder logEntry = new StringBuilder();
final String currentUserField = getCurrentUserField(entry);
logEntry.append(currentUserField).append(SPACE)
.append(entry.getRemoteHost()).append(SPACE)
.append(getSessionIdField(entry))
.append(FIELD_DIVIDER)
.append(getActionLocationField(entry))
.append(FIELD_DIVIDER)
.append(getRestCallField(entry));
if (success) {
final String additionalInfo = getAdditionalInfo(entry);
if (!StringUtils.isBlank(additionalInfo)) {
logEntry.append(FIELD_DIVIDER).append(additionalInfo);
}
} else {
logEntry.append(FIELD_DIVIDER).append(FAILURE);
}
log(logEntry.toString());
}
@Override
public void logJobStart(final JobExecution jobExecution) {
logJob(jobExecution, JOB_STARTED_TEMPLATE);
}
@Override
public void logJobCompleted(final JobExecution jobExecution) {
logJob(jobExecution, JOB_COMPLETED_TEMPLATE);
}
@Override
public void logJobFailed(JobExecution jobExecution) {
logJob(jobExecution, JOB_FAILED_TEMPLATE);
}
private void log(final String message) {
final SyslogMessage syslogMessage = new SyslogMessage()
.withFacility(Facility.AUDIT)
.withSeverity(Severity.INFORMATIONAL)
.withAppName("Atlas")
.withMsg(message);
final StringBuilder logEntry = new StringBuilder(syslogMessage.toRfc5424SyslogMessage());
if (logEntry.length() >= MAX_ENTRY_LENGTH) {
final String currentExtraSuffix = String.format("%02d", this.extraLogIdSuffix.getAndIncrement());
final String entryId = System.currentTimeMillis() + "_" + currentExtraSuffix;
AUDIT_EXTRA_LOGGER.info(entryId + FIELD_DIVIDER + message);
final String extraLogReferenceMessage = String.format(EXTRA_LOG_REFERENCE_MESSAGE, entryId);
logEntry.setLength(MAX_ENTRY_LENGTH - extraLogReferenceMessage.length() - 1);
logEntry.append(extraLogReferenceMessage);
AUDIT_LOGGER.info(logEntry.toString());
if (this.extraLogIdSuffix.get() > 99) {
this.extraLogIdSuffix.set(0);
}
} else {
AUDIT_LOGGER.info(logEntry.toString());
}
}
private String getSessionIdField(final AuditTrailEntry entry) {
return entry.getSessionId() != null ? entry.getSessionId() : NO_SESSION;
}
private String getCurrentUserField(final AuditTrailEntry entry) {
return (entry.getCurrentUser() != null ? String.valueOf(entry.getCurrentUser()) : ANONYMOUS);
}
private String getActionLocationField(final AuditTrailEntry entry) {
return entry.getActionLocation() != null ? entry.getActionLocation() : NO_LOCATION;
}
private String getRestCallField(final AuditTrailEntry entry) {
final StringBuilder sb = new StringBuilder();
sb.append(entry.getRequestMethod())
.append(" ")
.append(entry.getRequestUri());
if (!StringUtils.isBlank(entry.getQueryString())) {
sb.append("?").append(entry.getQueryString());
}
return sb.toString();
}
private String getAdditionalInfo(final AuditTrailEntry entry) {
final StringBuilder additionalInfo = new StringBuilder();
final String returnedObjectFields = getReturnedObjectFields(entry.getReturnedObject());
if (!StringUtils.isBlank(returnedObjectFields)) {
additionalInfo.append(returnedObjectFields);
}
// File entry log
if (entry.getReturnedObject() instanceof Response) {
try {
final Object entity = ((Response) entry.getReturnedObject()).getEntity();
if (entity instanceof File) {
final File file = (File) entity;
return String.format(FILE_TEMPLATE, file.getName(), file.length());
}
return null;
} catch (final Exception e) {
return null;
}
}
// Patient IDs log
if (entry.getReturnedObject() instanceof CohortSampleDTO) {
final CohortSampleDTO sampleDto = (CohortSampleDTO) entry.getReturnedObject();
if (sampleDto.getElements().isEmpty()) {
additionalInfo.append(String.format(PATIENT_IDS_TEMPLATE, 0)).append("none");
} else {
additionalInfo.append(String.format(PATIENT_IDS_TEMPLATE, sampleDto.getElements().size()));
sampleDto.getElements().forEach((e) -> {
additionalInfo.append(e.getPersonId()).append(" ");
});
}
}
return additionalInfo.toString();
}
private String getReturnedObjectFields(final Object returnedObject) {
if (returnedObject == null) {
return null;
}
if (returnedObject instanceof Collection) {
final Collection<?> c = (Collection<?>) returnedObject;
if (!c.isEmpty()) {
final String fields = collectClassFieldNames(c.iterator().next().getClass());
return fields != null ? String.format(LIST_OF_TEMPLATE, c.size(), fields) : null;
}
return EMPTY_LIST;
} if (returnedObject instanceof Map) {
final Map<?, ?> map = (Map<?, ?>) returnedObject;
if (!map.isEmpty()) {
final Map.Entry<?, ?> entry = map.entrySet().iterator().next();
final Class<?> keyClass = entry.getKey().getClass();
final Class<?> valueClass = entry.getValue().getClass();
final String valueFields = collectClassFieldNames(valueClass);
return valueFields != null ?
String.format(MAP_OF_TEMPLATE, keyClass.getSimpleName(), map.size(), valueFields) : null;
}
return EMPTY_MAP;
} else {
return collectClassFieldNames(returnedObject.getClass());
}
}
private String collectClassFieldNames(final Class<?> klass) {
if (!klass.getPackage().getName().startsWith("org.ohdsi.")) {
return null;
}
// collect only first level field names
final StringBuilder sb = new StringBuilder();
sb.append("{");
ReflectionUtils.doWithFields(klass,
field -> sb.append(field.getName()).append("::").append(field.getType().getSimpleName()).append(","));
if (sb.length() > 1) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("}");
return sb.toString();
}
private void logJob(final JobExecution jobExecution, final String template) {
final JobParameters jobParameters = jobExecution.getJobParameters();
final String author = jobParameters.getString(Constants.Params.JOB_AUTHOR);
if (author.equals("anonymous")) { // system jobs
return;
}
final String jobName = jobParameters.getString(Constants.Params.JOB_NAME);
log(String.format(template, author, jobExecution.getJobId(), jobName));
}
}
| 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/audittrail/AuditTrailEntry.java | src/main/java/org/ohdsi/webapi/audittrail/AuditTrailEntry.java | package org.ohdsi.webapi.audittrail;
import org.ohdsi.webapi.shiro.Entities.UserEntity;
public class AuditTrailEntry {
private String currentUser;
private String remoteHost;
private String actionLocation;
private String sessionId;
private String requestMethod;
private String requestUri;
private String queryString;
private Object returnedObject;
public String getCurrentUser() {
return currentUser;
}
public void setCurrentUser(String currentUser) {
this.currentUser = currentUser;
}
public String getActionLocation() {
return actionLocation;
}
public void setActionLocation(String actionLocation) {
this.actionLocation = actionLocation;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
public String getRequestUri() {
return requestUri;
}
public void setRequestUri(String requestUri) {
this.requestUri = requestUri;
}
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public Object getReturnedObject() {
return returnedObject;
}
public void setReturnedObject(Object returnedObject) {
this.returnedObject = returnedObject;
}
public String getRemoteHost() {
return remoteHost;
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
}
| 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/audittrail/AuditTrailService.java | src/main/java/org/ohdsi/webapi/audittrail/AuditTrailService.java | package org.ohdsi.webapi.audittrail;
import org.springframework.batch.core.JobExecution;
public interface AuditTrailService {
void logSuccessfulLogin(String login, String sessionId, String remoteHost);
void logFailedLogin(String login, String remoteHost);
void logSuccessfulLogout(String login);
void logFailedLogout(String login);
void logRestCall(AuditTrailEntry entry, boolean success);
void logJobStart(JobExecution jobExecution);
void logJobCompleted(JobExecution jobExecution);
void logJobFailed(JobExecution jobExecution);
}
| 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/audittrail/events/AuditTrailLoginFailedEvent.java | src/main/java/org/ohdsi/webapi/audittrail/events/AuditTrailLoginFailedEvent.java | package org.ohdsi.webapi.audittrail.events;
import org.springframework.context.ApplicationEvent;
public class AuditTrailLoginFailedEvent extends ApplicationEvent {
private final String login;
private final String remoteHost;
public AuditTrailLoginFailedEvent(final Object source,
final String login,
final String remoteHost) {
super(source);
this.login = login;
this.remoteHost = remoteHost;
}
public String getLogin() {
return this.login;
}
public String getRemoteHost() {
return remoteHost;
}
}
| 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/audittrail/events/AuditTrailSessionCreatedEvent.java | src/main/java/org/ohdsi/webapi/audittrail/events/AuditTrailSessionCreatedEvent.java | package org.ohdsi.webapi.audittrail.events;
import com.odysseusinc.logging.LogLevel;
import org.springframework.context.ApplicationEvent;
public class AuditTrailSessionCreatedEvent extends ApplicationEvent {
private final String login;
private final String sessionId;
private final String remoteHost;
public AuditTrailSessionCreatedEvent(final Object source,
final String login,
final String sessionId,
final String remoteHost) {
super(source);
this.login = login;
this.sessionId = sessionId;
this.remoteHost = remoteHost;
}
public String getLogin() {
return this.login;
}
public String getSessionId() {
return sessionId;
}
public String getRemoteHost() {
return remoteHost;
}
}
| 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/audittrail/listeners/AuditTrailFailedLogoutListener.java | src/main/java/org/ohdsi/webapi/audittrail/listeners/AuditTrailFailedLogoutListener.java | package org.ohdsi.webapi.audittrail.listeners;
import com.odysseusinc.logging.event.FailedLogoutEvent;
import org.ohdsi.webapi.audittrail.AuditTrailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class AuditTrailFailedLogoutListener implements ApplicationListener<FailedLogoutEvent> {
@Autowired
private AuditTrailService auditTrailService;
@Override
public void onApplicationEvent(final FailedLogoutEvent event) {
auditTrailService.logFailedLogout(event.getLogin());
}
}
| 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/audittrail/listeners/AuditTrailSuccessLogoutListener.java | src/main/java/org/ohdsi/webapi/audittrail/listeners/AuditTrailSuccessLogoutListener.java | package org.ohdsi.webapi.audittrail.listeners;
import com.odysseusinc.logging.event.SuccessLogoutEvent;
import org.ohdsi.webapi.audittrail.AuditTrailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class AuditTrailSuccessLogoutListener implements ApplicationListener<SuccessLogoutEvent> {
@Autowired
private AuditTrailService auditTrailService;
@Override
public void onApplicationEvent(final SuccessLogoutEvent event) {
auditTrailService.logSuccessfulLogout(event.getLogin());
}
}
| 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/audittrail/listeners/AuditTrailFailedLoginListener.java | src/main/java/org/ohdsi/webapi/audittrail/listeners/AuditTrailFailedLoginListener.java | package org.ohdsi.webapi.audittrail.listeners;
import com.odysseusinc.logging.event.FailedLoginEvent;
import org.ohdsi.webapi.audittrail.AuditTrailService;
import org.ohdsi.webapi.audittrail.events.AuditTrailLoginFailedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class AuditTrailFailedLoginListener implements ApplicationListener<AuditTrailLoginFailedEvent> {
@Autowired
private AuditTrailService auditTrailService;
@Override
public void onApplicationEvent(final AuditTrailLoginFailedEvent event) {
auditTrailService.logFailedLogin(event.getLogin(), event.getRemoteHost());
}
}
| 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/audittrail/listeners/AuditTrailSuccessLoginListener.java | src/main/java/org/ohdsi/webapi/audittrail/listeners/AuditTrailSuccessLoginListener.java | package org.ohdsi.webapi.audittrail.listeners;
import com.odysseusinc.logging.event.SuccessLoginEvent;
import org.ohdsi.webapi.audittrail.AuditTrailService;
import org.ohdsi.webapi.audittrail.events.AuditTrailSessionCreatedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class AuditTrailSuccessLoginListener implements ApplicationListener<AuditTrailSessionCreatedEvent> {
@Autowired
private AuditTrailService auditTrailService;
@Override
public void onApplicationEvent(final AuditTrailSessionCreatedEvent event) {
auditTrailService.logSuccessfulLogin(event.getLogin(), event.getSessionId(), event.getRemoteHost());
}
}
| 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/audittrail/listeners/AuditTrailJobListener.java | src/main/java/org/ohdsi/webapi/audittrail/listeners/AuditTrailJobListener.java | package org.ohdsi.webapi.audittrail.listeners;
import org.ohdsi.webapi.audittrail.AuditTrailService;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AuditTrailJobListener implements JobExecutionListener {
@Autowired
private AuditTrailService auditTrailService;
@Override
public void beforeJob(final JobExecution jobExecution) {
auditTrailService.logJobStart(jobExecution);
}
@Override
public void afterJob(final JobExecution jobExecution) {
if (jobExecution.getStatus() == BatchStatus.COMPLETED ) {
auditTrailService.logJobCompleted(jobExecution);
} else if (jobExecution.getStatus() == BatchStatus.FAILED) {
auditTrailService.logJobFailed(jobExecution);
}
}
}
| 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/cohortanalysis/CohortSummary.java | src/main/java/org/ohdsi/webapi/cohortanalysis/CohortSummary.java | package org.ohdsi.webapi.cohortanalysis;
import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO;
import java.util.List;
public class CohortSummary {
private CohortDTO cohortDefinition;
private String totalPatients;
private String meanAge;
private String meanObsPeriod;
private List<?> genderDistribution;
private List<?> ageDistribution;
private List<CohortAnalysis> analyses;
/**
* @return the definition
*/
public CohortDTO getCohortDefinition() {
return cohortDefinition;
}
/**
* @param definition the definition to set
*/
public void setCohortDefinition(CohortDTO definition) {
this.cohortDefinition = definition;
}
/**
* @return the totalPatients
*/
public String getTotalPatients() {
return totalPatients;
}
/**
* @param totalPatients the totalPatients to set
*/
public void setTotalPatients(String totalPatients) {
this.totalPatients = totalPatients;
}
/**
* @return the meanAge
*/
public String getMeanAge() {
return meanAge;
}
/**
* @param meanAge the meanAge to set
*/
public void setMeanAge(String meanAge) {
this.meanAge = meanAge;
}
/**
* @return the meanObsPeriod
*/
public String getMeanObsPeriod() {
return meanObsPeriod;
}
/**
* @param meanObsPeriod the meanObsPeriod to set
*/
public void setMeanObsPeriod(String meanObsPeriod) {
this.meanObsPeriod = meanObsPeriod;
}
/**
* @return the genderDistribution
*/
public List<?> getGenderDistribution() {
return genderDistribution;
}
/**
* @param genderDistribution the genderDistribution to set
*/
public void setGenderDistribution(List<?> genderDistribution) {
this.genderDistribution = genderDistribution;
}
/**
* @return the ageDistribution
*/
public List<?> getAgeDistribution() {
return ageDistribution;
}
/**
* @param ageDistribution the ageDistribution to set
*/
public void setAgeDistribution(List<?> ageDistribution) {
this.ageDistribution = ageDistribution;
}
/**
* @return the analyses
*/
public List<CohortAnalysis> getAnalyses() {
return analyses;
}
/**
* @param analyses the analyses to set
*/
public void setAnalyses(List<CohortAnalysis> analyses) {
this.analyses = analyses;
}
}
| 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/cohortanalysis/package-info.java | src/main/java/org/ohdsi/webapi/cohortanalysis/package-info.java | /**
* Model specific classes used by for running Heracles analyses (cohort analyses)
*/
package org.ohdsi.webapi.cohortanalysis; | 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/cohortanalysis/CohortAnalysisGenerationInfoPK.java | src/main/java/org/ohdsi/webapi/cohortanalysis/CohortAnalysisGenerationInfoPK.java | //
// This file was generated by the Jeddict
//
package org.ohdsi.webapi.cohortanalysis;
import java.io.Serializable;
public class CohortAnalysisGenerationInfoPK implements Serializable {
private Integer sourceId;
private Integer cohortDefinition;
public CohortAnalysisGenerationInfoPK(){
}
public CohortAnalysisGenerationInfoPK(Integer sourceId,Integer cohortDefinition){
this.sourceId=sourceId;
this.cohortDefinition=cohortDefinition;
}
public Integer getSourceId() {
return this.sourceId;
}
public void setSourceId (Integer sourceId) {
this.sourceId = sourceId;
}
public Integer getCohortDefinition() {
return this.cohortDefinition;
}
public void setCohortDefinition (Integer cohortDefinition) {
this.cohortDefinition = cohortDefinition;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {return false;}
if (!java.util.Objects.equals(getClass(), obj.getClass())) {return false;}
final CohortAnalysisGenerationInfoPK other = (CohortAnalysisGenerationInfoPK) obj;
if (!java.util.Objects.equals(this.getSourceId(), other.getSourceId())) { return false; }
if (!java.util.Objects.equals(this.getCohortDefinition(), other.getCohortDefinition())) { return false; }
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (this.getSourceId() != null ? this.getSourceId().hashCode() : 0);
hash = 59 * hash + (this.getCohortDefinition() != null ? this.getCohortDefinition().hashCode() : 0);
return hash;
}
@Override
public String toString() {
return "CohortAnalysisGenerationInfoPK{" + " sourceId=" + sourceId + ", cohortDefinition=" + cohortDefinition + '}';
}
}
| 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/cohortanalysis/CohortAnalysisUtilities.java | src/main/java/org/ohdsi/webapi/cohortanalysis/CohortAnalysisUtilities.java | package org.ohdsi.webapi.cohortanalysis;
public class CohortAnalysisUtilities {
private String cdmSchema;
private String ohdsiSchema;
private String sourceName;
private String cdmVersion;
private String sourceDialect;
private String dialect;
/**
* @return the cdmSchema
*/
public String getCdmSchema() {
return cdmSchema;
}
/**
* @param cdmSchema the cdmSchema to set
*/
public void setCdmSchema(String cdmSchema) {
this.cdmSchema = cdmSchema;
}
/**
* @return the ohdsiSchema
*/
public String getOhdsiSchema() {
return ohdsiSchema;
}
/**
* @param ohdsiSchema the ohdsiSchema to set
*/
public void setOhdsiSchema(String ohdsiSchema) {
this.ohdsiSchema = ohdsiSchema;
}
/**
* @return the sourceName
*/
public String getSourceName() {
return sourceName;
}
/**
* @param sourceName the sourceName to set
*/
public void setSourceName(String sourceName) {
this.sourceName = sourceName;
}
/**
* @return the cdmVersion
*/
public String getCdmVersion() {
return cdmVersion;
}
/**
* @param cdmVersion the cdmVersion to set
*/
public void setCdmVersion(String cdmVersion) {
this.cdmVersion = cdmVersion;
}
/**
* @return the sourceDialect
*/
public String getSourceDialect() {
return sourceDialect;
}
/**
* @param sourceDialect the sourceDialect to set
*/
public void setSourceDialect(String sourceDialect) {
this.sourceDialect = sourceDialect;
}
/**
* @return the dialect
*/
public String getDialect() {
return dialect;
}
/**
* @param dialect the dialect to set
*/
public void setDialect(String dialect) {
this.dialect = dialect;
}
}
| 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/cohortanalysis/CohortAnalysis.java | src/main/java/org/ohdsi/webapi/cohortanalysis/CohortAnalysis.java | package org.ohdsi.webapi.cohortanalysis;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import org.ohdsi.webapi.model.results.Analysis;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CohortAnalysis extends Analysis {
public static final String COHORT_DEFINITION_ID = "COHORT_DEFINITION_ID";
public static final String ANALYSIS_COMPLETE = "ANALYSIS_COMPLETE";
public static final String LAST_UPDATE_TIME = "LAST_UPDATE_TIME";
public static final String LAST_UPDATE_TIME_FORMATTED = "LAST_UPDATE_TIME_FORMATTED";
private int cohortDefinitionId;
private boolean analysisComplete;
private Timestamp lastUpdateTime;
private String lastUpdateTimeFormatted;
private SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy hh:mm aaa");
public int getCohortDefinitionId() {
return cohortDefinitionId;
}
public void setCohortDefinitionId(int cohortDefinitionId) {
this.cohortDefinitionId = cohortDefinitionId;
}
public boolean isAnalysisComplete() {
return analysisComplete;
}
public void setAnalysisComplete(boolean analysisComplete) {
this.analysisComplete = analysisComplete;
}
/**
* @return the lastUpdateTime
*/
public Timestamp getLastUpdateTime() {
return lastUpdateTime;
}
/**
* @param lastUpdateTime the lastUpdateTime to set
*/
public void setLastUpdateTime(Timestamp lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
/**
* @return the lastUpdateTimeFormatted
*/
public String getLastUpdateTimeFormatted() {
if (this.lastUpdateTime != null) {
this.lastUpdateTimeFormatted = formatter.format(lastUpdateTime);
}
return lastUpdateTimeFormatted;
}
}
| 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/cohortanalysis/CohortAnalysisTasklet.java | src/main/java/org/ohdsi/webapi/cohortanalysis/CohortAnalysisTasklet.java | package org.ohdsi.webapi.cohortanalysis;
import java.util.Calendar;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import static org.ohdsi.webapi.util.SecurityUtils.whitelist;
import org.ohdsi.sql.SqlSplit;
import org.ohdsi.webapi.cohortdefinition.CohortDefinition;
import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository;
import org.ohdsi.webapi.cohortresults.CohortResultsAnalysisRunner;
import org.ohdsi.webapi.cohortresults.VisualizationDataRepository;
import org.ohdsi.webapi.service.CohortAnalysisService;
import org.ohdsi.webapi.util.BatchStatementExecutorWithProgress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.TransactionTemplate;
import javax.ws.rs.NotFoundException;
public class CohortAnalysisTasklet implements Tasklet {
private static final Logger log = LoggerFactory.getLogger(CohortAnalysisTasklet.class);
private final CohortAnalysisTask task;
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
private final TransactionTemplate transactionTemplateRequiresNew;
private final CohortResultsAnalysisRunner analysisRunner;
private final CohortDefinitionRepository cohortDefinitionRepository;
private final HeraclesQueryBuilder heraclesQueryBuilder;
public CohortAnalysisTasklet(CohortAnalysisTask task
, final JdbcTemplate jdbcTemplate
, final TransactionTemplate transactionTemplate
, final TransactionTemplate transactionTemplateRequiresNew
, String sourceDialect
, VisualizationDataRepository visualizationDataRepository
, CohortDefinitionRepository cohortDefinitionRepository
, final ObjectMapper objectMapper
, HeraclesQueryBuilder heraclesQueryBuilder) {
this.task = task;
this.jdbcTemplate = jdbcTemplate;
this.transactionTemplate = transactionTemplate;
this.transactionTemplateRequiresNew = transactionTemplateRequiresNew;
this.heraclesQueryBuilder = heraclesQueryBuilder;
this.analysisRunner = new CohortResultsAnalysisRunner(sourceDialect, visualizationDataRepository, objectMapper);
this.cohortDefinitionRepository = cohortDefinitionRepository;
}
@Override
public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext) throws Exception {
boolean successful = false;
String failMessage = null;
Integer cohortDefinitionId = Integer.parseInt(task.getCohortDefinitionIds().get(0));
this.transactionTemplate.execute(status -> {
CohortDefinition cohortDef = cohortDefinitionRepository.findOne(cohortDefinitionId);
CohortAnalysisGenerationInfo gi = cohortDef.getCohortAnalysisGenerationInfoList().stream()
.filter(a -> a.getSourceId() == task.getSource().getSourceId())
.findFirst()
.orElseGet(() -> {
CohortAnalysisGenerationInfo genInfo = new CohortAnalysisGenerationInfo();
genInfo.setSourceId(task.getSource().getSourceId());
genInfo.setCohortDefinition(cohortDef);
cohortDef.getCohortAnalysisGenerationInfoList().add(genInfo);
return genInfo;
});
gi.setProgress(0);
cohortDefinitionRepository.save(cohortDef);
return gi;
});
try {
final String cohortSql = heraclesQueryBuilder.buildHeraclesAnalysisQuery(task);
BatchStatementExecutorWithProgress executor = new BatchStatementExecutorWithProgress(
SqlSplit.splitSql(cohortSql),
transactionTemplate,
jdbcTemplate);
int[] ret = executor.execute(progress -> {
transactionTemplateRequiresNew.execute(status -> {
CohortDefinition cohortDef = cohortDefinitionRepository.findOne(cohortDefinitionId);
CohortAnalysisGenerationInfo info = cohortDef.getCohortAnalysisGenerationInfoList().stream()
.filter(a -> a.getSourceId() == task.getSource().getSourceId())
.findFirst().orElseThrow(NotFoundException::new);
info.setProgress(progress);
cohortDefinitionRepository.save(cohortDef);
return null;
});
});
if (log.isDebugEnabled()) {
log.debug("Update count: {}", ret.length);
log.debug("Warming up visualizations");
}
final int count = this.analysisRunner.warmupData(jdbcTemplate, task);
if (log.isDebugEnabled()) {
log.debug("Warmed up {} visualizations", count);
}
successful = true;
} catch (final TransactionException | DataAccessException e) {
log.error(whitelist(e));
failMessage = StringUtils.left(e.getMessage(),2000);
throw e;//FAIL job status
} finally {
// add generated analysis IDs to cohort analysis generation info
final String f_failMessage = failMessage; // assign final var to pass into lambda
final boolean f_successful = successful; // assign final var to pass into lambda
this.transactionTemplateRequiresNew.execute(status -> {
CohortDefinition cohortDef = cohortDefinitionRepository.findOne(cohortDefinitionId);
CohortAnalysisGenerationInfo info = cohortDef.getCohortAnalysisGenerationInfoList().stream()
.filter(a -> a.getSourceId() == task.getSource().getSourceId())
.findFirst().orElseThrow(NotFoundException::new);
info.setExecutionDuration((int)(Calendar.getInstance().getTime().getTime()- info.getLastExecution().getTime()));
if (f_successful) {
// merge existing analysisIds with analysis Ids generated.
Set<Integer> generatedIds = Stream.concat(
task.getAnalysisIds().stream().map(Integer::parseInt),
info.getAnalysisIds().stream())
.collect(Collectors.toSet());
info.setAnalysisIds(generatedIds);
} else {
info.setFailMessage(f_failMessage);
}
this.cohortDefinitionRepository.save(cohortDef);
return null;
});
}
return RepeatStatus.FINISHED;
}
}
| 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/cohortanalysis/HeraclesConfigurationInfo.java | src/main/java/org/ohdsi/webapi/cohortanalysis/HeraclesConfigurationInfo.java | package org.ohdsi.webapi.cohortanalysis;
import org.ohdsi.info.ConfigurationInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class HeraclesConfigurationInfo extends ConfigurationInfo {
private static final String KEY = "heracles";
public HeraclesConfigurationInfo(@Value("${heracles.smallcellcount}") String smallCellCount) {
properties.put("smallCellCount", smallCellCount);
}
@Override
public String getKey() {
return KEY;
}
}
| 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/cohortanalysis/HeraclesQueryBuilder.java | src/main/java/org/ohdsi/webapi/cohortanalysis/HeraclesQueryBuilder.java | package org.ohdsi.webapi.cohortanalysis;
import com.odysseusinc.arachne.commons.types.DBMSType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.ArrayUtils;
import org.ohdsi.circe.helper.ResourceHelper;
import org.ohdsi.sql.SqlRender;
import org.ohdsi.sql.SqlTranslate;
import org.ohdsi.webapi.cohortresults.PeriodType;
import org.ohdsi.webapi.util.CSVRecordMapper;
import org.ohdsi.webapi.util.JoinUtils;
import org.ohdsi.webapi.util.SessionUtils;
import org.ohdsi.webapi.util.SourceUtils;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.*;
import java.util.stream.Collectors;
@Component
public class HeraclesQueryBuilder {
private final static String INIT_QUERY = ResourceHelper.GetResourceAsString("/resources/cohortanalysis/sql/initHeraclesAnalyses.sql");
private final static String FINALIZE_QUERY = ResourceHelper.GetResourceAsString("/resources/cohortanalysis/sql/finalizeHeraclesAnalyses.sql");
private final static String HERACLES_ANALYSES_TABLE = ResourceHelper.GetResourceAsString("/resources/cohortanalysis/heraclesanalyses/csv/heraclesAnalyses.csv");
private final static String HERACLES_ANALYSES_PARAMS = ResourceHelper.GetResourceAsString("/resources/cohortanalysis/heraclesanalyses/csv/heraclesAnalysesParams.csv");
private final static String ANALYSES_QUERY_PREFIX = "/resources/cohortanalysis/heraclesanalyses/sql/";
private final static String INSERT_RESULT_STATEMENT = "insert into @results_schema.heracles_results (cohort_definition_id, analysis_id, stratum_1, stratum_2, stratum_3, stratum_4, stratum_5, count_value, last_update_time)\n";
private final static String INSERT_DIST_RESULT_STATEMENT = "insert into @results_schema.heracles_results_dist (cohort_definition_id, analysis_id, stratum_1, stratum_2, stratum_3, stratum_4, stratum_5, count_value, min_value, max_value, avg_value, stdev_value, median_value, p10_value, p25_value, p75_value, p90_value, last_update_time)\n";
private final static String SELECT_RESULT_STATEMENT = ResourceHelper.GetResourceAsString("/resources/cohortanalysis/sql/selectHeraclesResults.sql");
private final static String SELECT_DIST_RESULT_STATEMENT = ResourceHelper.GetResourceAsString("/resources/cohortanalysis/sql/selectHeraclesDistResults.sql");
private final static String[] PARAM_NAMES = new String[]{"CDM_schema", "results_schema", "refreshStats", "source_name",
"smallcellcount", "runHERACLESHeel", "CDM_version", "cohort_definition_id", "list_of_analysis_ids",
"condition_concept_ids", "drug_concept_ids", "procedure_concept_ids", "observation_concept_ids",
"measurement_concept_ids", "cohort_period_only", "source_id", "periods", "rollupUtilizationVisit", "rollupUtilizationDrug",
"includeVisitTypeUtilization", "includeDrugTypeUtilization", "includeCostConcepts", "includeCurrency"};
private static final String UNION_ALL = "\nUNION ALL\n";
//Columns
private static final String COL_ANALYSIS_ID = "analysisId";
private static final String COL_ANALYSIS_NAME = "analysisName";
private static final String COL_SQL_FILE_NAME = "sqlFileName";
private static final String COL_RESULTS = "results";
private static final String COL_DIST_RESULTS = "distResults";
private static final String COL_PARAM_NAME = "paramName";
private static final String COL_PARAM_VALUE = "paramValue";
//Defaults
private static final String includeVisitTypeUtilization = "32025, 32028, 32022";
private static final String includeDrugTypeUtilization = "38000175,38000176";
private static final String includeCostConcepts = "31978, 31973, 31980";
private static final String includeCurrency = "44818668";
private Map<Integer, HeraclesAnalysis> heraclesAnalysisMap;
private Map<Integer, Set<HeraclesAnalysisParameter>> analysesParamsMap = new HashMap<>();
@PostConstruct
public void init() {
initHeraclesAnalyses();
initAnalysesParams();
}
private void initHeraclesAnalyses() {
heraclesAnalysisMap = parseCSV(HERACLES_ANALYSES_TABLE, record -> new HeraclesAnalysis(Integer.parseInt(record.get(COL_ANALYSIS_ID)),
record.get(COL_ANALYSIS_NAME), record.get(COL_SQL_FILE_NAME),
Boolean.parseBoolean(record.get(COL_RESULTS)), Boolean.parseBoolean(record.get(COL_DIST_RESULTS))))
.stream()
.collect(Collectors.toMap(HeraclesAnalysis::getId, analysis -> analysis));
}
private void initAnalysesParams() {
parseCSV(HERACLES_ANALYSES_PARAMS, record -> new HeraclesAnalysisParameter(Integer.parseInt(record.get(COL_ANALYSIS_ID)),
record.get(COL_PARAM_NAME), record.get(COL_PARAM_VALUE)))
.forEach(p -> {
Set<HeraclesAnalysisParameter> params = analysesParamsMap.getOrDefault(p.getAnalysisId(), new HashSet<>());
params.add(p);
analysesParamsMap.put(p.getAnalysisId(), params);
});
heraclesAnalysisMap.values().forEach(analysis -> {
Integer id = analysis.getId();
Set<HeraclesAnalysisParameter> params = analysesParamsMap.getOrDefault(id, new HashSet<>());
params.add(new HeraclesAnalysisParameter(id, COL_ANALYSIS_ID, id.toString()));
params.add(new HeraclesAnalysisParameter(id, COL_ANALYSIS_NAME, analysis.getName()));
analysesParamsMap.put(id, params);
});
}
private <T> List<T> parseCSV(String source, CSVRecordMapper<T> mapper) {
List<T> result = new ArrayList<>();
try(Reader in = new StringReader(source)) {
CSVParser parser = new CSVParser(in, CSVFormat.RFC4180.withFirstRecordAsHeader());
for(final CSVRecord record : parser.getRecords()) {
result.add(mapper.mapRecord(record));
}
} catch (IOException e) {
throw new BeanInitializationException("Failed to read heracles analyses");
}
return result;
}
public String buildHeraclesAnalysisQuery(CohortAnalysisTask task) {
return new Builder(task).buildQuery();
}
private String[] buildAnalysisParams(CohortAnalysisTask task) {
String resultsTableQualifier = SourceUtils.getResultsQualifier(task.getSource());
String cdmTableQualifier = SourceUtils.getCdmQualifier(task.getSource());
String cohortDefinitionIds = JoinUtils.join(task.getCohortDefinitionIds());
String analysisIds = JoinUtils.join(task.getAnalysisIds());
String conditionIds = JoinUtils.join(task.getConditionConceptIds());
String drugIds = JoinUtils.join(task.getDrugConceptIds());
String procedureIds = JoinUtils.join(task.getProcedureConceptIds());
String observationIds = JoinUtils.join(task.getObservationConceptIds());
String measurementIds = JoinUtils.join(task.getMeasurementConceptIds());
String concatenatedPeriods = "";
if (CollectionUtils.isEmpty(task.getPeriods())) {
// In this case summary stats will be calculated
concatenatedPeriods = "''";
} else {
List<PeriodType> periods = CollectionUtils.isEmpty(task.getPeriods()) ? Arrays.asList(PeriodType.values()) : task.getPeriods();
concatenatedPeriods = periods.stream()
.map(PeriodType::getValue)
.map(StringUtils::quote)
.collect(Collectors.joining(","));
}
boolean refreshStats = Arrays.asList(DBMSType.POSTGRESQL.getOhdsiDB()).contains(task.getSource().getSourceDialect());
return new String[]{
cdmTableQualifier, resultsTableQualifier, String.valueOf(refreshStats).toUpperCase(), task.getSource().getSourceName(),
String.valueOf(task.getSmallCellCount()), String.valueOf(task.runHeraclesHeel()).toUpperCase(),
task.getCdmVersion(), cohortDefinitionIds, analysisIds, conditionIds, drugIds, procedureIds,
observationIds, measurementIds,String.valueOf(task.isCohortPeriodOnly()),
String.valueOf(task.getSource().getSourceId()), concatenatedPeriods,
String.valueOf(task.getRollupUtilizationVisit()).toUpperCase(), String.valueOf(task.getRollupUtilizationDrug()).toUpperCase(),
includeVisitTypeUtilization, includeDrugTypeUtilization, includeCostConcepts, includeCurrency
};
}
private class Builder {
private CohortAnalysisTask analysisTask;
private String[] values;
private List<Integer> analysesIds;
private List<String> resultSql = new ArrayList<>();
private String sessionId;
Builder(CohortAnalysisTask analysisTask) {
this.analysisTask = analysisTask;
this.values = buildAnalysisParams(this.analysisTask);
this.analysesIds = analysisTask.getAnalysisIds().stream().map(Integer::parseInt).collect(Collectors.toList());
this.sessionId = SessionUtils.sessionId();
}
String buildQuery() {
return buildQuery(INIT_QUERY)
.buildAnalysesQueries()
.buildSelectResultQuery()
.buildQuery(FINALIZE_QUERY)
.toSql();
}
private String translateSql(String query) {
return SqlTranslate.translateSql(query, analysisTask.getSource().getSourceDialect(), sessionId,
SourceUtils.getTempQualifier(analysisTask.getSource()));
}
private Builder buildQuery(String query) {
resultSql.add(translateSql(SqlRender.renderSql(query, PARAM_NAMES, values)));
return this;
}
private Builder buildAnalysesQueries() {
resultSql.add(analysesIds.stream().map(this::getAnalysisQuery).collect(Collectors.joining("\n")));
return this;
}
private Builder buildSelectResultQuery() {
StringBuilder result = new StringBuilder();
List<String> resultsQuery = new ArrayList<>();
List<String> distResultsQuery = new ArrayList<>();
analysesIds.forEach(id -> {
HeraclesAnalysis analysis = heraclesAnalysisMap.get(id);
if (Objects.nonNull(analysis)) {
Pair<String[], String[]> params = getAnalysisParams(id);
if (analysis.isHasResults()) {
resultsQuery.add(SqlRender.renderSql(SELECT_RESULT_STATEMENT, params.getFirst(), params.getSecond()));
}
if (analysis.isHasDistResults()) {
distResultsQuery.add(SqlRender.renderSql(SELECT_DIST_RESULT_STATEMENT, params.getFirst(), params.getSecond()));
}
}
});
if (!resultsQuery.isEmpty()) {
result.append(SqlRender.renderSql(INSERT_RESULT_STATEMENT, PARAM_NAMES, values))
.append(resultsQuery.stream().collect(Collectors.joining(UNION_ALL)))
.append(";")
.append("\n");
}
if (!distResultsQuery.isEmpty()) {
result.append(SqlRender.renderSql(INSERT_DIST_RESULT_STATEMENT, PARAM_NAMES, values))
.append(distResultsQuery.stream().collect(Collectors.joining(UNION_ALL)))
.append(";")
.append("\n");
}
resultSql.add(translateSql(result.toString()));
return this;
}
private String toSql() {
return resultSql.stream().collect(Collectors.joining("\n"));
}
private String getAnalysisQuery(Integer id) {
HeraclesAnalysis analysis = heraclesAnalysisMap.get(id);
if (Objects.nonNull(analysis)) {
String query = ResourceHelper.GetResourceAsString(ANALYSES_QUERY_PREFIX + analysis.getFilename());
Pair<String[], String[]> params = getAnalysisParams(id);
return translateSql(SqlRender.renderSql(query, params.getFirst(), params.getSecond()));
} else {
return "";
}
}
private Pair<String[], String[]> getAnalysisParams(Integer id) {
List<HeraclesAnalysisParameter> params = new ArrayList<>(analysesParamsMap.getOrDefault(id, new HashSet<>()));
int size = params.size();
String[] analysisParamNames = new String[size];
String[] analysisParamValues = new String[size];
for(int i = 0; i < size; i++) {
analysisParamNames[i] = params.get(i).getParamName();
analysisParamValues[i] = params.get(i).getValue();
}
String[] paramNames = ArrayUtils.addAll(PARAM_NAMES, analysisParamNames);
String[] paramValues = ArrayUtils.addAll(values, analysisParamValues);
return Pair.of(paramNames, paramValues);
}
}
static class HeraclesAnalysis {
private Integer id;
private String name;
private String filename;
private boolean hasResults;
private boolean hasDistResults;
public HeraclesAnalysis(Integer id, String name, String filename, boolean hasResults, boolean hasDistResults) {
this.id = id;
this.name = name;
this.filename = filename;
this.hasResults = hasResults;
this.hasDistResults = hasDistResults;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getFilename() {
return filename;
}
public boolean isHasResults() {
return hasResults;
}
public boolean isHasDistResults() {
return hasDistResults;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HeraclesAnalysis)) return false;
HeraclesAnalysis analysis = (HeraclesAnalysis) o;
return Objects.equals(id, analysis.id) &&
Objects.equals(name, analysis.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
static class HeraclesAnalysisParameter {
private Integer analysisId;
private String paramName;
private String value;
public HeraclesAnalysisParameter(Integer analysisId, String paramName, String value) {
this.analysisId = analysisId;
this.paramName = paramName;
this.value = value;
}
public Integer getAnalysisId() {
return analysisId;
}
public String getParamName() {
return paramName;
}
public String getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HeraclesAnalysisParameter)) return false;
HeraclesAnalysisParameter that = (HeraclesAnalysisParameter) o;
return Objects.equals(analysisId, that.analysisId) &&
Objects.equals(paramName, that.paramName) &&
Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(analysisId, paramName, value);
}
}
}
| 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/cohortanalysis/CohortAnalysisGenerationInfo.java | src/main/java/org/ohdsi/webapi/cohortanalysis/CohortAnalysisGenerationInfo.java | /**
* This file was generated by the Jeddict
*/
package org.ohdsi.webapi.cohortanalysis;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.ohdsi.webapi.cohortdefinition.CohortDefinition;
/**
* @author cknoll1
*/
@Entity(name="CohortAnalysisGenerationInfo")
@Table(name="cohort_analysis_gen_info")
@IdClass(CohortAnalysisGenerationInfoPK.class)
public class CohortAnalysisGenerationInfo {
@Column(name="source_id")
@Id
private Integer sourceId;
@Id
@ManyToOne(targetEntity = CohortDefinition.class)
@JoinColumn(name="cohort_id",referencedColumnName="id")
private CohortDefinition cohortDefinition;
@Column(name="last_execution")
@Basic
@Temporal(TemporalType.TIMESTAMP)
private Date lastExecution;
@Column(name="execution_duration")
@Basic
private Integer executionDuration;
@Column(name="fail_message")
@Basic
private String failMessage;
@Column(name = "progress")
private Integer progress;
@Column(name = "analysis_id")
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "cohort_analysis_list_xref", joinColumns = {
@JoinColumn(name = "cohort_id", referencedColumnName = "cohort_id")
,@JoinColumn(name = "source_id", referencedColumnName = "source_id")})
private Set<Integer> analysisIds = new HashSet<>();
public Integer getSourceId() {
return this.sourceId;
}
public void setSourceId(Integer sourceId) {
this.sourceId = sourceId;
}
public Date getLastExecution() {
return this.lastExecution;
}
public void setLastExecution(Date lastExecution) {
this.lastExecution = lastExecution;
}
public Integer getExecutionDuration() {
return this.executionDuration;
}
public void setExecutionDuration(Integer executionDuration) {
this.executionDuration = executionDuration;
}
public String getFailMessage() {
return this.failMessage;
}
public void setFailMessage(String failMessage) {
this.failMessage = failMessage;
}
public Set<Integer> getAnalysisIds() {
return this.analysisIds;
}
public void setAnalysisIds(Set<Integer> analysisIds) {
this.analysisIds = analysisIds;
}
public CohortDefinition getCohortDefinition() {
return this.cohortDefinition;
}
public void setCohortDefinition(CohortDefinition cohortDefinition) {
this.cohortDefinition = cohortDefinition;
}
public Integer getProgress() {
return progress;
}
public void setProgress(Integer progress) {
this.progress = progress;
}
}
| 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/cohortanalysis/CohortAnalysisTask.java | src/main/java/org/ohdsi/webapi/cohortanalysis/CohortAnalysisTask.java | package org.ohdsi.webapi.cohortanalysis;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ohdsi.webapi.cohortresults.PeriodType;
import org.ohdsi.webapi.source.Source;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static org.ohdsi.webapi.util.SecurityUtils.whitelist;
public class CohortAnalysisTask {
private static final Logger log = LoggerFactory.getLogger(CohortAnalysisTasklet.class);
private String jobName;
private Source source;
private String sourceKey;
private int smallCellCount;
private boolean runHeraclesHeel;
private boolean cohortPeriodOnly;
private String cdmVersion = "5"; // Default to CDM V5
private List<String> visualizations;
private List<String> cohortDefinitionIds;
private List<String> analysisIds;
private List<String> conditionConceptIds;
private List<String> drugConceptIds;
private List<String> procedureConceptIds;
private List<String> observationConceptIds;
private List<String> measurementConceptIds;
private List<PeriodType> periods;
private boolean rollupUtilizationVisit;
private boolean rollupUtilizationDrug;
public String getSourceKey() {
return sourceKey;
}
public void setSourceKey(String sourceKey) {
this.sourceKey = sourceKey;
}
public Source getSource() {
return source;
}
public void setSource(Source source) {
this.source = source;
}
/**
* @return the smallCellCount
*/
public int getSmallCellCount() {
return smallCellCount;
}
/**
* @return the jobName
*/
public String getJobName() {
return jobName;
}
/**
* @param jobName the jobName to set
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
/**
* @param smallCellCount the smallCellCount to set
*/
public void setSmallCellCount(int smallCellCount) {
this.smallCellCount = smallCellCount;
}
/**
* @return the runHeraclesHeel
*/
public boolean runHeraclesHeel() {
return runHeraclesHeel;
}
/**
* @param runHeraclesHeel the runHeraclesHeel to set
*/
public void setRunHeraclesHeel(boolean runHeraclesHeel) {
this.runHeraclesHeel = runHeraclesHeel;
}
/**
* @return the cohortDefinitionId
*/
public List<String> getCohortDefinitionIds() {
return cohortDefinitionIds;
}
/**
* @param cohortDefinitionIds the cohortDefinitionIds to set
*/
public void setCohortDefinitionIds(List<String> cohortDefinitionIds) {
this.cohortDefinitionIds = cohortDefinitionIds;
}
/**
* @return the analysisId
*/
public List<String> getAnalysisIds() {
return analysisIds;
}
/**
* @param analysisIds the analysisIds to set
*/
public void setAnalysisIds(List<String> analysisIds) {
this.analysisIds = analysisIds;
}
/**
* @return the conditionConceptIds
*/
public List<String> getConditionConceptIds() {
return conditionConceptIds;
}
/**
* @param conditionConceptIds the conditionConceptIds to set
*/
public void setConditionConceptIds(List<String> conditionConceptIds) {
this.conditionConceptIds = conditionConceptIds;
}
/**
* @return the drugConceptIds
*/
public List<String> getDrugConceptIds() {
return drugConceptIds;
}
/**
* @param drugConceptIds the drugConceptIds to set
*/
public void setDrugConceptIds(List<String> drugConceptIds) {
this.drugConceptIds = drugConceptIds;
}
/**
* @return the procedureConceptIds
*/
public List<String> getProcedureConceptIds() {
return procedureConceptIds;
}
/**
* @param procedureConceptIds the procedureConceptIds to set
*/
public void setProcedureConceptIds(List<String> procedureConceptIds) {
this.procedureConceptIds = procedureConceptIds;
}
/**
* @return the observationConceptIds
*/
public List<String> getObservationConceptIds() {
return observationConceptIds;
}
/**
* @param observationConceptIds the observationConceptIds to set
*/
public void setObservationConceptIds(List<String> observationConceptIds) {
this.observationConceptIds = observationConceptIds;
}
/**
* @return the measurementConceptIds
*/
public List<String> getMeasurementConceptIds() {
return measurementConceptIds;
}
/**
* @param measurementConceptIds the measurementConceptIds to set
*/
public void setMeasurementConceptIds(List<String> measurementConceptIds) {
this.measurementConceptIds = measurementConceptIds;
}
/**
* @return the runHeraclesHeel
*/
public boolean isRunHeraclesHeel() {
return runHeraclesHeel;
}
/**
* @return the cohortPeriodOnly
*/
public boolean isCohortPeriodOnly() {
return cohortPeriodOnly;
}
/**
* @param cohortPeriodOnly the cohortPeriodOnly to set
*/
public void setCohortPeriodOnly(boolean cohortPeriodOnly) {
this.cohortPeriodOnly = cohortPeriodOnly;
}
/**
* @return the cdmVersion
*/
public String getCdmVersion() {
return cdmVersion;
}
/**
* @param cdmVersion the cdmVersion to set
*/
public void setCdmVersion(String cdmVersion) {
this.cdmVersion = cdmVersion;
}
/**
* @return the visualizations
*/
public List<String> getVisualizations() {
return visualizations;
}
/**
* @param visualizations the visualizations to set
*/
public void setVisualizations(List<String> visualizations) {
this.visualizations = visualizations;
}
/**
* @return the periods
*/
public List<PeriodType> getPeriods() {
return periods;
}
/**
* @param periods the periods to set
*/
public void setPeriods(final List<PeriodType> periods) {
this.periods = periods;
}
public boolean getRollupUtilizationVisit() {
return rollupUtilizationVisit;
}
public void setRollupUtilizationVisit(boolean rollupUtilizationVisit) {
this.rollupUtilizationVisit = rollupUtilizationVisit;
}
public boolean getRollupUtilizationDrug() {
return rollupUtilizationDrug;
}
public void setRollupUtilizationDrug(boolean rollupUtilizationDrug) {
this.rollupUtilizationDrug = rollupUtilizationDrug;
}
@Override
public String toString() {
return String.format("jobName = %s, source = %s, smallCellCount = %d, runHeraclesHeel = %s, " +
"cohortPeriodOnly = %s, cdmVersion = %s, visualizations = %s, cohortDefinitionIds = %s, " +
"analysisIds = %s, conditionConceptIds = %s, drugConceptIds = %s, procedureConceptIds = %s, " +
"observationConceptIds = %s, measurementConceptIds = %s, periods = %s",
jobName, source, smallCellCount, runHeraclesHeel, cohortPeriodOnly, cdmVersion,
visualizations, cohortDefinitionIds, analysisIds, conditionConceptIds, drugConceptIds,
procedureConceptIds, observationConceptIds, measurementConceptIds, periods);
}
}
| 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/cohortcharacterization/CreateCohortTableTasklet.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/CreateCohortTableTasklet.java | package org.ohdsi.webapi.cohortcharacterization;
import org.ohdsi.circe.helper.ResourceHelper;
import org.ohdsi.sql.SqlSplit;
import org.ohdsi.sql.SqlTranslate;
import org.ohdsi.webapi.source.SourceService;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.sqlrender.SourceAwareSqlRender;
import org.ohdsi.webapi.util.SourceUtils;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.Arrays;
import java.util.Map;
import static org.ohdsi.webapi.Constants.Params.SOURCE_ID;
import static org.ohdsi.webapi.Constants.Params.TARGET_TABLE;
public class CreateCohortTableTasklet implements Tasklet {
private final String CREATE_COHORT_SQL = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/createCohortTable.sql");
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
private final SourceService sourceService;
private final SourceAwareSqlRender sourceAwareSqlRender;
public CreateCohortTableTasklet(JdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate, SourceService sourceService, SourceAwareSqlRender sourceAwareSqlRender) {
this.jdbcTemplate = jdbcTemplate;
this.transactionTemplate = transactionTemplate;
this.sourceService = sourceService;
this.sourceAwareSqlRender = sourceAwareSqlRender;
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
transactionTemplate.execute(transactionStatus -> doTask(chunkContext));
return RepeatStatus.FINISHED;
}
private Object doTask(ChunkContext chunkContext) {
final Map<String, Object> jobParameters = chunkContext.getStepContext().getJobParameters();
final Integer sourceId = Integer.valueOf(jobParameters.get(SOURCE_ID).toString());
final String targetTable = jobParameters.get(TARGET_TABLE).toString();
final String sql = sourceAwareSqlRender.renderSql(sourceId, CREATE_COHORT_SQL, TARGET_TABLE, targetTable );
final Source source = sourceService.findBySourceId(sourceId);
final String resultsQualifier = SourceUtils.getResultsQualifier(source);
final String tempQualifier = SourceUtils.getTempQualifier(source, resultsQualifier);
final String translatedSql = SqlTranslate.translateSql(sql, source.getSourceDialect(), null, tempQualifier);
Arrays.stream(SqlSplit.splitSql(translatedSql)).forEach(jdbcTemplate::execute);
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/cohortcharacterization/DropCohortTableListener.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/DropCohortTableListener.java | package org.ohdsi.webapi.cohortcharacterization;
import com.odysseusinc.arachne.commons.types.DBMSType;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.ohdsi.circe.helper.ResourceHelper;
import org.ohdsi.sql.SqlTranslate;
import org.ohdsi.webapi.source.SourceService;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.sqlrender.SourceAwareSqlRender;
import org.ohdsi.webapi.util.SourceUtils;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.Map;
import static org.ohdsi.webapi.Constants.Params.SOURCE_ID;
import static org.ohdsi.webapi.Constants.Params.TARGET_TABLE;
public class DropCohortTableListener extends JobExecutionListenerSupport {
private final String DROP_TABLE_SQL = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/dropCohortTable.sql");
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
private final SourceService sourceService;
private final SourceAwareSqlRender sourceAwareSqlRender;
public DropCohortTableListener(JdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate, SourceService sourceService, SourceAwareSqlRender sourceAwareSqlRender) {
this.jdbcTemplate = jdbcTemplate;
this.transactionTemplate = transactionTemplate;
this.sourceService = sourceService;
this.sourceAwareSqlRender = sourceAwareSqlRender;
}
private Object doTask(JobParameters parameters) {
final Map<String, JobParameter> jobParameters = parameters.getParameters();
final Integer sourceId = Integer.valueOf(jobParameters.get(SOURCE_ID).toString());
final String targetTable = jobParameters.get(TARGET_TABLE).getValue().toString();
final String sql = sourceAwareSqlRender.renderSql(sourceId, DROP_TABLE_SQL, TARGET_TABLE, targetTable );
final Source source = sourceService.findBySourceId(sourceId);
final String resultsQualifier = SourceUtils.getResultsQualifier(source);
final String tempQualifier = SourceUtils.getTempQualifier(source, resultsQualifier);
String toRemove = SqlTranslate.translateSql(sql, source.getSourceDialect(), null, tempQualifier);
if (Objects.equals(DBMSType.SPARK.getOhdsiDB(), source.getSourceDialect()) ||
Objects.equals(DBMSType.HIVE.getOhdsiDB(), source.getSourceDialect())) {
toRemove = StringUtils.remove(toRemove, ';');
}
jdbcTemplate.execute(toRemove);
return null;
}
@Override
public void afterJob(JobExecution jobExecution) {
transactionTemplate.execute(transactionStatus -> doTask(jobExecution.getJobParameters()));
}
}
| 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/cohortcharacterization/CcServiceImpl.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/CcServiceImpl.java | package org.ohdsi.webapi.cohortcharacterization;
import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableList;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.ohdsi.analysis.Utils;
import org.ohdsi.analysis.WithId;
import org.ohdsi.analysis.cohortcharacterization.design.CohortCharacterization;
import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType;
import org.ohdsi.circe.helper.ResourceHelper;
import org.ohdsi.featureExtraction.FeatureExtraction;
import org.ohdsi.hydra.Hydra;
import org.ohdsi.sql.SqlSplit;
import org.ohdsi.sql.SqlTranslate;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.JobInvalidator;
import org.ohdsi.webapi.cohortcharacterization.converter.SerializedCcToCcConverter;
import org.ohdsi.webapi.cohortcharacterization.domain.CcFeAnalysisEntity;
import org.ohdsi.webapi.cohortcharacterization.domain.CcGenerationEntity;
import org.ohdsi.webapi.cohortcharacterization.domain.CcParamEntity;
import org.ohdsi.webapi.cohortcharacterization.domain.CcStrataConceptSetEntity;
import org.ohdsi.webapi.cohortcharacterization.domain.CcStrataEntity;
import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity;
import org.ohdsi.webapi.cohortcharacterization.dto.AbstractTemporalResult;
import org.ohdsi.webapi.cohortcharacterization.dto.CcDistributionStat;
import org.ohdsi.webapi.cohortcharacterization.dto.CcExportDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CcPrevalenceStat;
import org.ohdsi.webapi.cohortcharacterization.dto.CcResult;
import org.ohdsi.webapi.cohortcharacterization.dto.CcShortDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CcTemporalAnnualResult;
import org.ohdsi.webapi.cohortcharacterization.dto.CcTemporalResult;
import org.ohdsi.webapi.cohortcharacterization.dto.CcVersionFullDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.ExecutionResultRequest;
import org.ohdsi.webapi.cohortcharacterization.dto.ExportExecutionResultRequest;
import org.ohdsi.webapi.cohortcharacterization.dto.GenerationResults;
import org.ohdsi.webapi.cohortcharacterization.report.AnalysisItem;
import org.ohdsi.webapi.cohortcharacterization.report.AnalysisResultItem;
import org.ohdsi.webapi.cohortcharacterization.report.ComparativeItem;
import org.ohdsi.webapi.cohortcharacterization.report.ExportItem;
import org.ohdsi.webapi.cohortcharacterization.report.PrevalenceItem;
import org.ohdsi.webapi.cohortcharacterization.report.Report;
import org.ohdsi.webapi.cohortcharacterization.report.TemporalAnnualItem;
import org.ohdsi.webapi.cohortcharacterization.report.TemporalItem;
import org.ohdsi.webapi.cohortcharacterization.repository.AnalysisGenerationInfoEntityRepository;
import org.ohdsi.webapi.cohortcharacterization.repository.CcConceptSetRepository;
import org.ohdsi.webapi.cohortcharacterization.repository.CcFeAnalysisRepository;
import org.ohdsi.webapi.cohortcharacterization.repository.CcGenerationEntityRepository;
import org.ohdsi.webapi.cohortcharacterization.repository.CcParamRepository;
import org.ohdsi.webapi.cohortcharacterization.repository.CcRepository;
import org.ohdsi.webapi.cohortcharacterization.repository.CcStrataRepository;
import org.ohdsi.webapi.cohortcharacterization.specification.CohortCharacterizationImpl;
import org.ohdsi.webapi.cohortdefinition.CohortDefinition;
import org.ohdsi.webapi.cohortdefinition.event.CohortDefinitionChangedEvent;
import org.ohdsi.webapi.common.DesignImportService;
import org.ohdsi.webapi.common.generation.AnalysisGenerationInfoEntity;
import org.ohdsi.webapi.common.generation.GenerationUtils;
import org.ohdsi.webapi.conceptset.ConceptSetExport;
import org.ohdsi.webapi.feanalysis.FeAnalysisService;
import org.ohdsi.webapi.feanalysis.domain.FeAnalysisCriteriaEntity;
import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity;
import org.ohdsi.webapi.feanalysis.domain.FeAnalysisWithCriteriaEntity;
import org.ohdsi.webapi.feanalysis.domain.FeAnalysisWithStringEntity;
import org.ohdsi.webapi.feanalysis.event.FeAnalysisChangedEvent;
import org.ohdsi.webapi.job.GeneratesNotification;
import org.ohdsi.webapi.job.JobExecutionResource;
import org.ohdsi.webapi.service.AbstractDaoService;
import org.ohdsi.webapi.service.FeatureExtractionService;
import org.ohdsi.webapi.service.JobService;
import org.ohdsi.webapi.service.VocabularyService;
import org.ohdsi.webapi.shiro.Entities.UserEntity;
import org.ohdsi.webapi.shiro.annotations.CcGenerationId;
import org.ohdsi.webapi.shiro.annotations.DataSourceAccess;
import org.ohdsi.webapi.shiro.annotations.SourceKey;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.source.SourceInfo;
import org.ohdsi.webapi.source.SourceService;
import org.ohdsi.webapi.sqlrender.SourceAwareSqlRender;
import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO;
import org.ohdsi.webapi.util.CancelableJdbcTemplate;
import org.ohdsi.webapi.util.EntityUtils;
import org.ohdsi.webapi.util.ExceptionUtils;
import org.ohdsi.webapi.util.ExportUtil;
import org.ohdsi.webapi.util.NameUtils;
import org.ohdsi.webapi.util.SessionUtils;
import org.ohdsi.webapi.util.SourceUtils;
import org.ohdsi.webapi.util.TempFileUtils;
import org.ohdsi.webapi.versioning.domain.CharacterizationVersion;
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.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.job.builder.SimpleJobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.event.EventListener;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
import static org.ohdsi.analysis.cohortcharacterization.design.CcResultType.DISTRIBUTION;
import static org.ohdsi.analysis.cohortcharacterization.design.CcResultType.PREVALENCE;
import static org.ohdsi.webapi.Constants.GENERATE_COHORT_CHARACTERIZATION;
import static org.ohdsi.webapi.Constants.Params.COHORT_CHARACTERIZATION_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.SOURCE_ID;
import org.ohdsi.webapi.security.PermissionService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageImpl;
@Service
@Transactional
@DependsOn({"ccExportDTOToCcEntityConverter", "cohortDTOToCohortDefinitionConverter", "feAnalysisDTOToFeAnalysisConverter"})
public class CcServiceImpl extends AbstractDaoService implements CcService, GeneratesNotification {
private static final String GENERATION_NOT_FOUND_ERROR = "generation cannot be found by id %d";
private static final String[] PARAMETERS_RESULTS = {"cohort_characterization_generation_id", "threshold_level", "vocabulary_schema"};
private static final String[] PARAMETERS_RESULTS_FILTERED = {"cohort_characterization_generation_id", "threshold_level",
"analysis_ids", "cohort_ids", "vocabulary_schema"};
private static final String[] PARAMETERS_COUNT = {"cohort_characterization_generation_id", "vocabulary_schema"};
private static final String[] PREVALENCE_STATS_PARAMS = {"cdm_database_schema", "cdm_results_schema", "cc_generation_id", "analysis_id", "cohort_id", "covariate_id"};
private final String QUERY_RESULTS = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/queryResults.sql");
private final String QUERY_TEMPORAL_RESULTS = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/queryTemporalResults.sql");
private final String QUERY_TEMPORAL_ANNUAL_RESULTS = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/queryTemporalAnnualResults.sql");
private final String QUERY_COUNT = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/queryCountWithoutThreshold.sql");
private final String DELETE_RESULTS = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/deleteResults.sql");
private final String DELETE_EXECUTION = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/deleteExecution.sql");
private final String QUERY_PREVALENCE_STATS = ResourceHelper.GetResourceAsString("/resources/cohortcharacterizations/sql/queryCovariateStatsVocab.sql");
private final String HYDRA_PACKAGE = "/resources/cohortcharacterizations/hydra/CohortCharacterization_v0.0.1.zip";
private final static List<String> INCOMPLETE_STATUSES = ImmutableList.of(BatchStatus.STARTED, BatchStatus.STARTING, BatchStatus.STOPPING, BatchStatus.UNKNOWN)
.stream().map(BatchStatus::name).collect(Collectors.toList());
private Map<String, FeatureExtraction.PrespecAnalysis> prespecAnalysisMap = FeatureExtraction.getNameToPrespecAnalysis();
private final EntityGraph defaultEntityGraph = EntityUtils.fromAttributePaths(
"cohortDefinitions",
"featureAnalyses",
"stratas",
"parameters",
"createdBy",
"modifiedBy"
);
private final List<String[]> executionPrevalenceHeaderLines = new ArrayList<String[]>() {{
add(new String[]{"Analysis ID", "Analysis name", "Strata ID",
"Strata name", "Cohort ID", "Cohort name", "Covariate ID", "Covariate name", "Covariate short name",
"Count", "Percent"});
}};
private final List<String[]> executionDistributionHeaderLines = new ArrayList<String[]>() {{
add(new String[]{"Analysis ID", "Analysis name", "Strata ID",
"Strata name", "Cohort ID", "Cohort name", "Covariate ID", "Covariate name", "Covariate short name", "Value field","Missing Means Zero",
"Count", "Avg", "StdDev", "Min", "P10", "P25", "Median", "P75", "P90", "Max"});
}};
private final List<String[]> executionComparativeHeaderLines = new ArrayList<String[]>() {{
add(new String[]{"Analysis ID", "Analysis name", "Strata ID",
"Strata name", "Target cohort ID", "Target cohort name", "Comparator cohort ID", "Comparator cohort name",
"Covariate ID", "Covariate name", "Covariate short name", "Target count", "Target percent",
"Comparator count", "Comparator percent", "Std. Diff Of Mean"});
}};
private final CcRepository repository;
private final CcParamRepository paramRepository;
private final CcStrataRepository strataRepository;
private final CcConceptSetRepository conceptSetRepository;
private final FeAnalysisService analysisService;
private final CcGenerationEntityRepository ccGenerationRepository;
private final FeatureExtractionService featureExtractionService;
private final DesignImportService designImportService;
private final AnalysisGenerationInfoEntityRepository analysisGenerationInfoEntityRepository;
private final SourceService sourceService;
private final GenerationUtils generationUtils;
private final EntityManager entityManager;
private final ApplicationEventPublisher eventPublisher;
private final JobRepository jobRepository;
private final SourceAwareSqlRender sourceAwareSqlRender;
private final JobService jobService;
private final JobInvalidator jobInvalidator;
private final GenericConversionService genericConversionService;
private final VocabularyService vocabularyService;
private final CcFeAnalysisRepository ccFeAnalysisRepository;
private VersionService<CharacterizationVersion> versionService;
private PermissionService permissionService;
@Value("${security.defaultGlobalReadPermissions}")
private boolean defaultGlobalReadPermissions;
private final Environment env;
public CcServiceImpl(
final CcRepository ccRepository,
final CcParamRepository paramRepository,
final CcStrataRepository strataRepository,
final CcConceptSetRepository conceptSetRepository,
final FeAnalysisService analysisService,
final CcGenerationEntityRepository ccGenerationRepository,
final FeatureExtractionService featureExtractionService,
final ConversionService conversionService,
final DesignImportService designImportService,
final JobRepository jobRepository,
final AnalysisGenerationInfoEntityRepository analysisGenerationInfoEntityRepository,
final SourceService sourceService,
final GenerationUtils generationUtils,
final SourceAwareSqlRender sourceAwareSqlRender,
final EntityManager entityManager,
final JobService jobService,
final ApplicationEventPublisher eventPublisher,
final JobInvalidator jobInvalidator,
final VocabularyService vocabularyService,
CcFeAnalysisRepository ccFeAnalysisRepository, final VersionService<CharacterizationVersion> versionService,
final PermissionService permissionService,
@Qualifier("conversionService") final GenericConversionService genericConversionService,
Environment env) {
this.repository = ccRepository;
this.paramRepository = paramRepository;
this.strataRepository = strataRepository;
this.conceptSetRepository = conceptSetRepository;
this.analysisService = analysisService;
this.ccGenerationRepository = ccGenerationRepository;
this.featureExtractionService = featureExtractionService;
this.designImportService = designImportService;
this.jobRepository = jobRepository;
this.analysisGenerationInfoEntityRepository = analysisGenerationInfoEntityRepository;
this.sourceService = sourceService;
this.generationUtils = generationUtils;
this.sourceAwareSqlRender = sourceAwareSqlRender;
this.entityManager = entityManager;
this.jobService = jobService;
this.eventPublisher = eventPublisher;
this.jobInvalidator = jobInvalidator;
this.vocabularyService = vocabularyService;
this.ccFeAnalysisRepository = ccFeAnalysisRepository;
this.permissionService = permissionService;
this.genericConversionService = genericConversionService;
this.versionService = versionService;
this.env = env;
SerializedCcToCcConverter.setConversionService(conversionService);
}
@Override
public CohortCharacterizationEntity createCc(final CohortCharacterizationEntity entity) {
entity.setCreatedBy(getCurrentUser());
entity.setCreatedDate(new Date());
return saveCc(entity);
}
private CohortCharacterizationEntity saveCc(final CohortCharacterizationEntity entity) {
CohortCharacterizationEntity savedEntity = repository.save(entity);
for(CcStrataEntity strata: entity.getStratas()){
strata.setCohortCharacterization(savedEntity);
strataRepository.save(strata);
}
for(CcParamEntity param: entity.getParameters()){
param.setCohortCharacterization(savedEntity);
paramRepository.save(param);
}
for(CcFeAnalysisEntity analysis : entity.getCcFeatureAnalyses()) {
analysis.setCohortCharacterization(savedEntity);
ccFeAnalysisRepository.save(analysis);
}
entityManager.flush();
entityManager.refresh(savedEntity);
savedEntity = findByIdWithLinkedEntities(savedEntity.getId());
Date modifiedDate = savedEntity.getModifiedDate();
savedEntity.setModifiedDate(null);
final String serialized = this.serializeCc(savedEntity);
savedEntity.setHashCode(serialized.hashCode());
savedEntity.setModifiedDate(modifiedDate);
return repository.save(savedEntity);
}
@EventListener
@Transactional
@Override
public void onCohortDefinitionChanged(CohortDefinitionChangedEvent event) {
List<CohortCharacterizationEntity> ccList = repository.findByCohortDefinition(event.getCohortDefinition());
ccList.forEach(this::saveCc);
}
@EventListener
@Transactional
public void onFeAnalysisChanged(FeAnalysisChangedEvent event) {
List<CohortCharacterizationEntity> ccList = repository.findByFeatureAnalysis(event.getFeAnalysis());
ccList.forEach(this::saveCc);
}
@Override
@Transactional
public void assignTag(Long id, int tagId) {
CohortCharacterizationEntity entity = findById(id);
assignTag(entity, tagId);
}
@Override
@Transactional
public void unassignTag(Long id, int tagId) {
CohortCharacterizationEntity entity = findById(id);
unassignTag(entity, tagId);
}
@Override
public int getCountCcWithSameName(Long id, String name) {
return repository.getCountCcWithSameName(id, name);
}
@Override
public void deleteCc(Long ccId) {
repository.delete(ccId);
}
@Override
public CohortCharacterizationEntity updateCc(final CohortCharacterizationEntity entity) {
final CohortCharacterizationEntity foundEntity = repository.findById(entity.getId())
.orElseThrow(() -> new NotFoundException("CC entity isn't found"));
updateLinkedFields(entity, foundEntity);
if (StringUtils.isNotEmpty(entity.getName())) {
foundEntity.setName(entity.getName());
}
foundEntity.setDescription(entity.getDescription());
foundEntity.setStratifiedBy(entity.getStratifiedBy());
if (Objects.nonNull(entity.getStrataOnly())) {
foundEntity.setStrataOnly(entity.getStrataOnly());
}
foundEntity.setModifiedDate(new Date());
foundEntity.setModifiedBy(getCurrentUser());
return saveCc(foundEntity);
}
private void updateLinkedFields(final CohortCharacterizationEntity entity, final CohortCharacterizationEntity foundEntity) {
updateConceptSet(entity, foundEntity);
updateParams(entity, foundEntity);
updateAnalyses(entity, foundEntity);
updateCohorts(entity, foundEntity);
updateStratas(entity, foundEntity);
}
private void updateConceptSet(CohortCharacterizationEntity entity, CohortCharacterizationEntity foundEntity) {
if (Objects.nonNull(foundEntity.getConceptSetEntity()) && Objects.nonNull(entity.getConceptSetEntity())) {
foundEntity.getConceptSetEntity().setRawExpression(entity.getConceptSetEntity().getRawExpression());
} else if (Objects.nonNull(entity.getConceptSetEntity())) {
CcStrataConceptSetEntity cse = new CcStrataConceptSetEntity();
cse.setCohortCharacterization(foundEntity);
cse.setRawExpression(entity.getConceptSetEntity().getRawExpression());
foundEntity.setConceptSetEntity(cse);
} else {
foundEntity.setConceptSetEntity(null);
}
}
private void updateStratas(CohortCharacterizationEntity entity, CohortCharacterizationEntity foundEntity) {
final List<CcStrataEntity> stratasToDelete = getLinksToDelete(foundEntity,
existingLink -> entity.getStratas().stream().noneMatch(newLink -> Objects.equals(newLink.getId(), existingLink.getId())),
CohortCharacterizationEntity::getStratas);
foundEntity.getStratas().removeAll(stratasToDelete);
strataRepository.delete(stratasToDelete);
Map<Long, CcStrataEntity> strataEntityMap = foundEntity.getStratas().stream()
.collect(Collectors.toMap(CcStrataEntity::getId, s -> s));
List<CcStrataEntity> updatedStratas = entity.getStratas().stream().map(updated -> {
updated.setCohortCharacterization(foundEntity);
if (Objects.nonNull(updated.getId())) {
CcStrataEntity strata = strataEntityMap.get(updated.getId());
// strata will be null in case of importing new characterization
if (strata == null) {
return updated;
}
if (StringUtils.isNotBlank(updated.getName())) {
strata.setName(updated.getName());
}
strata.setExpressionString(updated.getExpressionString());
return strata;
} else {
return updated;
}
}).collect(Collectors.toList());
entity.setStratas(new HashSet<>(strataRepository.save(updatedStratas)));
}
private void updateCohorts(final CohortCharacterizationEntity entity, final CohortCharacterizationEntity foundEntity) {
foundEntity.getCohortDefinitions().clear();
foundEntity.getCohortDefinitions().addAll(entity.getCohortDefinitions());
}
private void updateAnalyses(final CohortCharacterizationEntity entity, final CohortCharacterizationEntity foundEntity) {
ccFeAnalysisRepository.delete(foundEntity.getCcFeatureAnalyses());
foundEntity.getCcFeatureAnalyses().clear();
foundEntity.getCcFeatureAnalyses().addAll(entity.getCcFeatureAnalyses());
ccFeAnalysisRepository.save(foundEntity.getCcFeatureAnalyses());
}
private <T extends WithId> List<T> getLinksToDelete(final CohortCharacterizationEntity foundEntity,
Predicate<? super T> filterPredicate,
Function<CohortCharacterizationEntity, Set<T>> getter) {
return getter.apply(foundEntity)
.stream()
.filter(filterPredicate)
.collect(Collectors.toList());
}
private void updateParams(final CohortCharacterizationEntity entity, final CohortCharacterizationEntity foundEntity) {
updateOrCreateParams(entity, foundEntity);
deleteParams(entity, foundEntity);
}
private void deleteParams(final CohortCharacterizationEntity entity, final CohortCharacterizationEntity foundEntity) {
final Map<String, CcParamEntity> nameToParamFromInputMap = buildParamNameToParamMap(entity);
List<CcParamEntity> paramsForDelete = getLinksToDelete(foundEntity,
parameter -> !nameToParamFromInputMap.containsKey(parameter.getName()),
CohortCharacterizationEntity::getParameters);
foundEntity.getParameters().removeAll(paramsForDelete);
paramRepository.delete(paramsForDelete);
}
private void updateOrCreateParams(final CohortCharacterizationEntity entity, final CohortCharacterizationEntity foundEntity) {
final Map<String, CcParamEntity> nameToParamFromDbMap = buildParamNameToParamMap(foundEntity);
final List<CcParamEntity> paramsForCreateOrUpdate = new ArrayList<>();
for (final CcParamEntity parameter : entity.getParameters()) {
final CcParamEntity entityFromMap = nameToParamFromDbMap.get(parameter.getName());
parameter.setCohortCharacterization(foundEntity);
if (entityFromMap == null) {
paramsForCreateOrUpdate.add(parameter);
} else if (!StringUtils.equals(entityFromMap.getValue(), parameter.getValue())) {
entityFromMap.setValue(parameter.getValue());
paramsForCreateOrUpdate.add(entityFromMap);
}
}
paramRepository.save(paramsForCreateOrUpdate);
}
@Override
public CohortCharacterizationEntity importCc(final CohortCharacterizationEntity entity) {
cleanIds(entity);
final CohortCharacterizationEntity newCohortCharacterization = new CohortCharacterizationEntity();
newCohortCharacterization.setName(entity.getName());
final CohortCharacterizationEntity persistedCohortCharacterization = this.createCc(newCohortCharacterization);
updateParams(entity, persistedCohortCharacterization);
updateStratas(entity, persistedCohortCharacterization);
updateConceptSet(entity, persistedCohortCharacterization);
importCohorts(entity, persistedCohortCharacterization);
final CohortCharacterizationEntity savedEntity = saveCc(persistedCohortCharacterization);
List<Integer> savedAnalysesIds = importAnalyses(entity, savedEntity);
eventPublisher.publishEvent(new CcImportEvent(savedAnalysesIds));
return savedEntity;
}
@Override
public String getNameForCopy(String dtoName) {
return NameUtils.getNameForCopy(dtoName, this::getNamesLike, repository.findByName(dtoName));
}
@Override
public String getNameWithSuffix(String dtoName) {
return NameUtils.getNameWithSuffix(dtoName, this::getNamesLike);
}
@Override
public String serializeCc(final Long id) {
return Utils.serialize(exportCc(id), true);
}
@Override
public String serializeCc(final CohortCharacterizationEntity cohortCharacterizationEntity) {
return new SerializedCcToCcConverter().convertToDatabaseColumn(cohortCharacterizationEntity);
}
private CohortCharacterizationImpl exportCc(final Long id) {
final CohortCharacterizationEntity cohortCharacterizationEntity = repository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Cohort characterization cannot be found by id: " + id));
CohortCharacterizationImpl cc = genericConversionService.convert(cohortCharacterizationEntity, CohortCharacterizationImpl.class);
ExportUtil.clearCreateAndUpdateInfo(cc);
cc.getFeatureAnalyses().forEach(ExportUtil::clearCreateAndUpdateInfo);
cc.getCohorts().forEach(ExportUtil::clearCreateAndUpdateInfo);
cc.setOrganizationName(env.getRequiredProperty("organization.name"));
return cc;
}
@Override
public CohortCharacterizationEntity findById(final Long id) {
return repository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Cohort characterization with id: " + id + " cannot be found"));
}
@Override
public CohortCharacterizationEntity findByIdWithLinkedEntities(final Long id) {
return repository.findOne(id, defaultEntityGraph);
}
@Override
@DataSourceAccess
public CohortCharacterization findDesignByGenerationId(@CcGenerationId final Long id) {
final AnalysisGenerationInfoEntity entity = analysisGenerationInfoEntityRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Analysis with id: " + id + " cannot be found"));
return genericConversionService.convert(Utils.deserialize(entity.getDesign(),
new TypeReference<CcExportDTO>() {}), CohortCharacterizationEntity.class);
}
@Override
public Page<CohortCharacterizationEntity> getPageWithLinkedEntities(final Pageable pageable) {
return repository.findAll(pageable, defaultEntityGraph);
}
@Override
public Page<CohortCharacterizationEntity> getPage(final Pageable pageable) {
List<CohortCharacterizationEntity> ccList = repository.findAll()
.stream().filter(!defaultGlobalReadPermissions ? entity -> permissionService.hasReadAccess(entity) : entity -> true)
.collect(Collectors.toList());
return getPageFromResults(pageable, ccList);
}
private Page<CohortCharacterizationEntity> getPageFromResults(Pageable pageable, List<CohortCharacterizationEntity> 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 void hydrateAnalysis(Long analysisId, String packageName, OutputStream out) {
if (packageName == null || !Utils.isAlphaNumeric(packageName)) {
throw new IllegalArgumentException("The package name must be alphanumeric only.");
}
CohortCharacterizationImpl analysis = exportCc(analysisId);
analysis.setPackageName(packageName);
String studySpecs = Utils.serialize(analysis, true);
Hydra hydra = new Hydra(studySpecs);
File skeletonFile = null;
try {
skeletonFile = TempFileUtils.copyResourceToTempFile(HYDRA_PACKAGE, "cc-", ".zip");
hydra.setExternalSkeletonFileName(skeletonFile.getAbsolutePath());
hydra.hydrate(out);
} catch (IOException e) {
log.error("Failed to hydrate cohort characterization", e);
throw new InternalServerErrorException(e);
} finally {
FileUtils.deleteQuietly(skeletonFile);
}
}
@Override
@DataSourceAccess
public JobExecutionResource generateCc(final Long id, @SourceKey final String sourceKey) {
CcService ccService = this;
Source source = getSourceRepository().findBySourceKey(sourceKey);
JobParametersBuilder builder = new JobParametersBuilder();
builder.addString(JOB_NAME, String.format("Generating cohort characterization %d : %s (%s)", id, source.getSourceName(), source.getSourceKey()));
builder.addString(COHORT_CHARACTERIZATION_ID, String.valueOf(id));
builder.addString(SOURCE_ID, String.valueOf(source.getSourceId()));
builder.addString(JOB_AUTHOR, getCurrentUserLogin());
CancelableJdbcTemplate jdbcTemplate = getSourceJdbcTemplate(source);
SimpleJobBuilder generateCohortJob = generationUtils.buildJobForCohortBasedAnalysisTasklet(
GENERATE_COHORT_CHARACTERIZATION,
source,
builder,
jdbcTemplate,
chunkContext -> {
Long ccId = Long.valueOf(chunkContext.getStepContext().getJobParameters().get(COHORT_CHARACTERIZATION_ID).toString());
return ccService.findById(ccId).getCohortDefinitions();
},
new GenerateCohortCharacterizationTasklet(
jdbcTemplate,
getTransactionTemplate(),
ccService,
analysisGenerationInfoEntityRepository,
sourceService,
userRepository
)
);
final JobParameters jobParameters = builder.toJobParameters();
return jobService.runJob(generateCohortJob.build(), jobParameters);
}
@Override
public List<CcGenerationEntity> findGenerationsByCcId(final Long id) {
return ccGenerationRepository.findByCohortCharacterizationIdOrderByIdDesc(id, EntityUtils.fromAttributePaths("source"));
}
@Override
public CcGenerationEntity findGenerationById(final Long id) {
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | true |
OHDSI/WebAPI | https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/cohortcharacterization/GenerateLocalCohortTasklet.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/GenerateLocalCohortTasklet.java | package org.ohdsi.webapi.cohortcharacterization;
import org.ohdsi.webapi.cohortdefinition.CohortDefinition;
import org.ohdsi.webapi.cohortdefinition.CohortDefinitionDetails;
import org.ohdsi.webapi.cohortdefinition.CohortGenerationRequestBuilder;
import org.ohdsi.webapi.cohortdefinition.CohortGenerationUtils;
import org.ohdsi.webapi.generationcache.GenerationCacheHelper;
import org.ohdsi.webapi.service.CohortGenerationService;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.source.SourceService;
import org.ohdsi.webapi.util.CancelableJdbcTemplate;
import org.ohdsi.webapi.util.SessionUtils;
import org.ohdsi.webapi.util.SourceUtils;
import org.ohdsi.webapi.util.StatementCancel;
import org.ohdsi.webapi.util.StatementCancelException;
import org.ohdsi.webapi.util.TempTableCleanupManager;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.StoppableTasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.transaction.support.TransactionTemplate;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.ohdsi.webapi.Constants.Params.SOURCE_ID;
import static org.ohdsi.webapi.Constants.Params.TARGET_TABLE;
import static org.ohdsi.webapi.Constants.Params.DEMOGRAPHIC_STATS;
public class GenerateLocalCohortTasklet implements StoppableTasklet {
private static final String COPY_CACHED_RESULTS = "INSERT INTO %s.%s (cohort_definition_id, subject_id, cohort_start_date, cohort_end_date) SELECT %s as cohort_definition_id, subject_id, cohort_start_date, cohort_end_date FROM (%s) r";
protected TransactionTemplate transactionTemplate;
private final CancelableJdbcTemplate cancelableJdbcTemplate;
protected final CohortGenerationService cohortGenerationService;
protected final SourceService sourceService;
protected final Function<ChunkContext, Collection<CohortDefinition>> cohortGetter;
private final GenerationCacheHelper generationCacheHelper;
private boolean useAsyncCohortGeneration;
private Set<StatementCancel> statementCancels = ConcurrentHashMap.newKeySet();
private volatile boolean stopped = false;
public GenerateLocalCohortTasklet(TransactionTemplate transactionTemplate,
CancelableJdbcTemplate cancelableJdbcTemplate,
CohortGenerationService cohortGenerationService,
SourceService sourceService,
Function<ChunkContext, Collection<CohortDefinition>> cohortGetter,
GenerationCacheHelper generationCacheHelper,
boolean useAsyncCohortGeneration) {
this.transactionTemplate = transactionTemplate;
this.cancelableJdbcTemplate = cancelableJdbcTemplate;
this.cohortGenerationService = cohortGenerationService;
this.sourceService = sourceService;
this.cohortGetter = cohortGetter;
this.generationCacheHelper = generationCacheHelper;
this.useAsyncCohortGeneration = useAsyncCohortGeneration;
}
@Override
public void stop() {
try {
stopped = true;
for (StatementCancel statementCancel: statementCancels) {
statementCancel.cancel();
}
} catch (SQLException ignored) {
}
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
Map<String, Object> jobParameters = chunkContext.getStepContext().getJobParameters();
Source source = sourceService.findBySourceId(Integer.valueOf(jobParameters.get(SOURCE_ID).toString()));
String resultSchema = SourceUtils.getResultsQualifier(source);
String targetTable = jobParameters.get(TARGET_TABLE).toString();
Collection<CohortDefinition> cohortDefinitions = cohortGetter.apply(chunkContext);
if (useAsyncCohortGeneration) {
List<CompletableFuture> executions = cohortDefinitions.stream()
.map(cd ->
CompletableFuture.supplyAsync(() -> generateCohort(cd, source, resultSchema, targetTable),
Executors.newSingleThreadExecutor()
)
).collect(Collectors.toList());
CompletableFuture.allOf(executions.toArray(new CompletableFuture[]{})).join();
} else {
CompletableFuture.runAsync(() ->
cohortDefinitions.stream().forEach(cd -> generateCohort(cd, source, resultSchema, targetTable)),
Executors.newSingleThreadExecutor()
).join();
}
return RepeatStatus.FINISHED;
}
private Object generateCohort(CohortDefinition cd, Source source, String resultSchema, String targetTable) {
if (stopped) {
return null;
}
String sessionId = SessionUtils.sessionId();
CohortGenerationRequestBuilder generationRequestBuilder = new CohortGenerationRequestBuilder(
sessionId,
resultSchema
);
CohortDefinitionDetails details = cd.getDetails();
int designHash = this.generationCacheHelper.computeHash(details.getExpression());
CohortGenerationUtils.insertInclusionRules(cd, source, designHash, resultSchema, sessionId, cancelableJdbcTemplate);
try {
StatementCancel stmtCancel = new StatementCancel();
statementCancels.add(stmtCancel);
GenerationCacheHelper.CacheResult res = generationCacheHelper.computeCacheIfAbsent(cd, source, generationRequestBuilder, (resId, sqls) -> {
try {
generationCacheHelper.runCancelableCohortGeneration(cancelableJdbcTemplate, stmtCancel, sqls);
} finally {
// Usage of the same sessionId for all cohorts would cause issues in databases w/o real temp tables support
// And we cannot postfix existing sessionId with some index because SqlRender requires sessionId to be only 8 symbols long
// So, relying on TempTableCleanupManager.removeTempTables from GenerationTaskExceptionHandler is not an option
// That's why explicit TempTableCleanupManager call is defined
TempTableCleanupManager cleanupManager = new TempTableCleanupManager(
cancelableJdbcTemplate,
transactionTemplate,
source.getSourceDialect(),
sessionId,
SourceUtils.getTempQualifier(source)
);
cleanupManager.cleanupTempTables();
}
});
String sql = String.format(COPY_CACHED_RESULTS, SourceUtils.getTempQualifier(source), targetTable, cd.getId(), res.getSql());
cancelableJdbcTemplate.batchUpdate(stmtCancel, sql);
statementCancels.remove(stmtCancel);
} catch (StatementCancelException ignored) {
// this exception must be caught to prevent "FAIL" status of the job
}
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/cohortcharacterization/CcConst.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/CcConst.java | package org.ohdsi.webapi.cohortcharacterization;
public interface CcConst {
String dateFormat = "yyyy-MM-dd HH:mm:ss";
}
| 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/cohortcharacterization/CcImportEvent.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/CcImportEvent.java | package org.ohdsi.webapi.cohortcharacterization;
import java.util.List;
public class CcImportEvent {
// should keep list of ids to prevent error for duplication of permissions
private List<Integer> savedAnalysesIds;
public CcImportEvent(List<Integer> savedAnalysesIds) {
this.savedAnalysesIds = savedAnalysesIds;
}
public List<Integer> getSavedAnalysesIds() {
return savedAnalysesIds;
}
}
| 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/cohortcharacterization/GenerateCohortCharacterizationTasklet.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/GenerateCohortCharacterizationTasklet.java | /*
* Copyright 2017 Observational Health Data Sciences and Informatics <OHDSI.org>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ohdsi.webapi.cohortcharacterization;
import com.google.common.collect.ImmutableList;
import com.odysseusinc.arachne.commons.types.DBMSType;
import org.ohdsi.cohortcharacterization.CCQueryBuilder;
import org.ohdsi.sql.BigQuerySparkTranslate;
import org.ohdsi.sql.SqlSplit;
import org.ohdsi.sql.SqlTranslate;
import org.ohdsi.webapi.cohortcharacterization.converter.SerializedCcToCcConverter;
import org.ohdsi.webapi.cohortcharacterization.domain.CcFeAnalysisEntity;
import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity;
import org.ohdsi.webapi.cohortcharacterization.repository.AnalysisGenerationInfoEntityRepository;
import org.ohdsi.webapi.common.generation.AnalysisTasklet;
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.sql.SQLException;
import java.util.Map;
import java.util.Optional;
import static org.ohdsi.webapi.Constants.Params.*;
public class GenerateCohortCharacterizationTasklet extends AnalysisTasklet {
private final CcService ccService;
private final SourceService sourceService;
private final UserRepository userRepository;
public GenerateCohortCharacterizationTasklet(
final CancelableJdbcTemplate jdbcTemplate,
final TransactionTemplate transactionTemplate,
final CcService ccService,
final AnalysisGenerationInfoEntityRepository analysisGenerationInfoEntityRepository,
final SourceService sourceService,
final UserRepository userRepository
) {
super(LoggerFactory.getLogger(GenerateCohortCharacterizationTasklet.class), jdbcTemplate, transactionTemplate, analysisGenerationInfoEntityRepository);
this.ccService = ccService;
this.sourceService = sourceService;
this.userRepository = userRepository;
}
@Override
protected String[] prepareQueries(ChunkContext chunkContext, CancelableJdbcTemplate jdbcTemplate) {
Map<String, Object> jobParams = chunkContext.getStepContext().getJobParameters();
CohortCharacterizationEntity cohortCharacterization = ccService.findByIdWithLinkedEntities(
Long.valueOf(jobParams.get(COHORT_CHARACTERIZATION_ID).toString())
);
final Long jobId = chunkContext.getStepContext().getStepExecution().getJobExecution().getId();
final UserEntity userEntity = userRepository.findByLogin(jobParams.get(JOB_AUTHOR).toString());
String serializedDesign = new SerializedCcToCcConverter().convertToDatabaseColumn(cohortCharacterization);
saveInfoWithinTheSeparateTransaction(jobId, serializedDesign, userEntity);
final Integer sourceId = Integer.valueOf(jobParams.get(SOURCE_ID).toString());
final Source source = sourceService.findBySourceId(sourceId);
final String cohortTable = String.format("%s.%s", SourceUtils.getTempQualifier(source), jobParams.get(TARGET_TABLE).toString());
final String sessionId = jobParams.get(SESSION_ID).toString();
final String tempSchema = SourceUtils.getTempQualifier(source);
boolean includeAnnual = cohortCharacterization.getCcFeatureAnalyses().stream()
.anyMatch(fe -> Optional.ofNullable(fe.getIncludeAnnual()).orElse(false));
boolean includeTemporal = cohortCharacterization.getCcFeatureAnalyses().stream()
.anyMatch(fe -> Optional.ofNullable(fe.getIncludeTemporal()).orElse(false));
CCQueryBuilder ccQueryBuilder = new CCQueryBuilder(cohortCharacterization, cohortTable, sessionId,
SourceUtils.getCdmQualifier(source), SourceUtils.getResultsQualifier(source),
SourceUtils.getVocabularyQualifier(source), tempSchema, jobId, includeAnnual, includeTemporal);
String sql = ccQueryBuilder.build();
/*
* There is an issue with temp tables on sql server: Temp tables scope is session or stored procedure.
* To execute PreparedStatement sql server uses stored procedure <i>sp_executesql</i>
* and this is the reason why multiple PreparedStatements cannot share the same local temporary table.
*
* On the other side, temp tables cannot be re-used in the same PreparedStatement, e.g. temp table cannot be created, used, dropped
* and created again in the same PreparedStatement because sql optimizator detects object already exists and fails.
* When is required to re-use temp table it should be separated to several PreparedStatements.
*
* An option to use global temp tables also doesn't work since such tables can be not supported / disabled.
*
* Therefore, there are two ways:
* - either precisely group SQLs into statements so that temp tables aren't re-used in a single statement,
* - or use ‘permanent temporary tables’
*
* The second option looks better since such SQL could be exported and executed manually,
* which is not the case with the first option.
*/
if (ImmutableList.of(DBMSType.MS_SQL_SERVER.getOhdsiDB(), DBMSType.PDW.getOhdsiDB()).contains(source.getSourceDialect())) {
sql = sql
.replaceAll("#", tempSchema + "." + sessionId + "_")
.replaceAll("tempdb\\.\\.", "");
}
final String translatedSql = SqlTranslate.translateSql(sql, source.getSourceDialect(), sessionId, tempSchema);
return SqlSplit.splitSql(translatedSql);
}
}
| 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/cohortcharacterization/CcService.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/CcService.java | package org.ohdsi.webapi.cohortcharacterization;
import org.ohdsi.analysis.cohortcharacterization.design.CohortCharacterization;
import org.ohdsi.webapi.cohortcharacterization.domain.CcGenerationEntity;
import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity;
import org.ohdsi.webapi.cohortcharacterization.dto.CcPrevalenceStat;
import org.ohdsi.webapi.cohortcharacterization.dto.CcResult;
import org.ohdsi.webapi.cohortcharacterization.dto.CcShortDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CcTemporalResult;
import org.ohdsi.webapi.cohortcharacterization.dto.CcVersionFullDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.ExecutionResultRequest;
import org.ohdsi.webapi.cohortcharacterization.dto.ExportExecutionResultRequest;
import org.ohdsi.webapi.cohortcharacterization.dto.GenerationResults;
import org.ohdsi.webapi.conceptset.ConceptSetExport;
import org.ohdsi.webapi.cohortdefinition.event.CohortDefinitionChangedEvent;
import org.ohdsi.webapi.feanalysis.event.FeAnalysisChangedEvent;
import org.ohdsi.webapi.job.JobExecutionResource;
import org.ohdsi.webapi.shiro.annotations.CcGenerationId;
import org.ohdsi.webapi.shiro.annotations.DataSourceAccess;
import org.ohdsi.webapi.tag.domain.HasTags;
import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO;
import org.ohdsi.webapi.versioning.domain.CharacterizationVersion;
import org.ohdsi.webapi.versioning.dto.VersionDTO;
import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.io.OutputStream;
import java.util.List;
public interface CcService extends HasTags<Long> {
CohortCharacterizationEntity createCc(CohortCharacterizationEntity entity);
CohortCharacterizationEntity updateCc(CohortCharacterizationEntity entity);
int getCountCcWithSameName(Long id, String name);
void deleteCc(Long ccId);
CohortCharacterizationEntity importCc(CohortCharacterizationEntity entity);
String getNameForCopy(String dtoName);
String getNameWithSuffix(String dtoName);
String serializeCc(Long id);
String serializeCc(CohortCharacterizationEntity cohortCharacterizationEntity);
CohortCharacterizationEntity findById(Long id);
CohortCharacterizationEntity findByIdWithLinkedEntities(Long id);
CohortCharacterization findDesignByGenerationId(final Long id);
Page<CohortCharacterizationEntity> getPageWithLinkedEntities(Pageable pageable);
Page<CohortCharacterizationEntity> getPage(Pageable pageable);
JobExecutionResource generateCc(Long id, final String sourceKey);
List<CcGenerationEntity> findGenerationsByCcId(Long id);
CcGenerationEntity findGenerationById(final Long id);
List<CcGenerationEntity> findGenerationsByCcIdAndSource(Long id, String sourceKey);
@DataSourceAccess
List<CcTemporalResult> findTemporalResultAsList(@CcGenerationId Long generationId);
GenerationResults findResult(Long generationId, ExecutionResultRequest params);
List<CcResult> findResultAsList(Long generationId, float thresholdLevel);
List<CcPrevalenceStat> getPrevalenceStatsByGenerationId(final Long id, Long analysisId, final Long cohortId, final Long covariateId);
void hydrateAnalysis(Long analysisId, String packageName, OutputStream out);
void deleteCcGeneration(Long generationId);
void cancelGeneration(Long id, String sourceKey);
Long getCCResultsTotalCount(Long id);
List<ConceptSetExport> exportConceptSets(CohortCharacterization cohortCharacterization);
GenerationResults exportExecutionResult(Long generationId, ExportExecutionResultRequest params);
GenerationResults findData(final Long generationId, ExecutionResultRequest params);
@EventListener
void onCohortDefinitionChanged(CohortDefinitionChangedEvent event);
@EventListener
void onFeAnalysisChanged(FeAnalysisChangedEvent event);
List<VersionDTO> getVersions(long id);
CcVersionFullDTO getVersion(long id, int version);
VersionDTO updateVersion(long id, int version, VersionUpdateDTO updateDTO);
void deleteVersion(long id, int version);
CohortCharacterizationDTO copyAssetFromVersion(long id, int version);
CharacterizationVersion saveVersion(long id);
List<CcShortDTO> listByTags(TagNameListRequestDTO 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/cohortcharacterization/CcController.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/CcController.java | package org.ohdsi.webapi.cohortcharacterization;
import com.odysseusinc.arachne.commons.utils.CommonFilenameUtils;
import com.odysseusinc.arachne.commons.utils.ConverterUtils;
import com.opencsv.CSVWriter;
import com.qmino.miredot.annotations.ReturnType;
import org.ohdsi.analysis.Utils;
import org.ohdsi.analysis.cohortcharacterization.design.CohortCharacterization;
import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType;
import org.ohdsi.featureExtraction.FeatureExtraction;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.Pagination;
import org.ohdsi.webapi.check.CheckResult;
import org.ohdsi.webapi.check.checker.characterization.CharacterizationChecker;
import org.ohdsi.webapi.cohortcharacterization.domain.CcGenerationEntity;
import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity;
import org.ohdsi.webapi.cohortcharacterization.dto.CcExportDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CcPrevalenceStat;
import org.ohdsi.webapi.cohortcharacterization.dto.CcResult;
import org.ohdsi.webapi.cohortcharacterization.dto.CcShortDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CcTemporalResult;
import org.ohdsi.webapi.cohortcharacterization.dto.CcVersionFullDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.ExportExecutionResultRequest;
import org.ohdsi.webapi.cohortcharacterization.dto.GenerationResults;
import org.ohdsi.webapi.cohortcharacterization.report.Report;
import org.ohdsi.webapi.common.SourceMapKey;
import org.ohdsi.webapi.common.generation.CommonGenerationDTO;
import org.ohdsi.webapi.common.sensitiveinfo.CommonGenerationSensitiveInfoService;
import org.ohdsi.webapi.conceptset.ConceptSetExport;
import org.ohdsi.webapi.feanalysis.FeAnalysisService;
import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity;
import org.ohdsi.webapi.feanalysis.domain.FeAnalysisWithStringEntity;
import org.ohdsi.webapi.job.JobExecutionResource;
import org.ohdsi.webapi.security.PermissionService;
import org.ohdsi.webapi.source.Source;
import org.ohdsi.webapi.source.SourceService;
import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO;
import org.ohdsi.webapi.util.ExceptionUtils;
import org.ohdsi.webapi.util.ExportUtil;
import org.ohdsi.webapi.util.HttpUtils;
import org.ohdsi.webapi.versioning.dto.VersionDTO;
import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO;
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.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
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.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Path("/cohort-characterization")
@Controller
@Transactional
public class CcController {
private CcService service;
private FeAnalysisService feAnalysisService;
private ConversionService conversionService;
private ConverterUtils converterUtils;
private final CommonGenerationSensitiveInfoService<CommonGenerationDTO> sensitiveInfoService;
private final SourceService sourceService;
private CharacterizationChecker checker;
private PermissionService permissionService;
public CcController(
final CcService service,
final FeAnalysisService feAnalysisService,
final ConversionService conversionService,
final ConverterUtils converterUtils,
CommonGenerationSensitiveInfoService sensitiveInfoService,
SourceService sourceService, CharacterizationChecker checker,
PermissionService permissionService) {
this.service = service;
this.feAnalysisService = feAnalysisService;
this.conversionService = conversionService;
this.converterUtils = converterUtils;
this.sensitiveInfoService = sensitiveInfoService;
this.sourceService = sourceService;
this.checker = checker;
this.permissionService = permissionService;
FeatureExtraction.init(null);
}
/**
* Create a new cohort characterization
*
* @param dto A cohort characterization JSON definition (name, cohorts, featureAnalyses, etc.)
* @return The cohort characterization definition passed in as input
* with additional fields (createdDate, hasWriteAccess, tags, id, hashcode).
*/
@POST
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Transactional
public CohortCharacterizationDTO create(final CohortCharacterizationDTO dto) {
final CohortCharacterizationEntity createdEntity = service.createCc(conversionService.convert(dto, CohortCharacterizationEntity.class));
return conversionService.convert(createdEntity, CohortCharacterizationDTO.class);
}
/**
* Create a copy of an existing cohort characterization
*
* @param id An existing cohort characterization id
* @return The cohort characterization definition of the newly created copy
*/
@POST
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public CohortCharacterizationDTO copy(@PathParam("id") final Long id) {
CohortCharacterizationDTO dto = getDesign(id);
dto.setName(service.getNameForCopy(dto.getName()));
dto.setId(null);
dto.setTags(null);
dto.getStratas().forEach(s -> s.setId(null));
dto.getParameters().forEach(p -> p.setId(null));
return create(dto);
}
/**
* Get information about the cohort characterization analyses in WebAPI
*
* @return A json object with information about the characterization analyses in WebAPI.
*/
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Page<CcShortDTO> list(@Pagination Pageable pageable) {
return service.getPage(pageable).map(entity -> {
CcShortDTO dto = convertCcToShortDto(entity);
permissionService.fillWriteAccess(entity, dto);
permissionService.fillReadAccess(entity, dto);
return dto;
});
}
/**
* Get the design specification for every cohort-characterization analysis in WebAPI.
*
* @return A json object with all characterization design specifications.
*/
@GET
@Path("/design")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Page<CohortCharacterizationDTO> listDesign(@Pagination Pageable pageable) {
return service.getPageWithLinkedEntities(pageable).map(entity -> {
CohortCharacterizationDTO dto = convertCcToDto(entity);
permissionService.fillWriteAccess(entity, dto);
permissionService.fillReadAccess(entity, dto);
return dto;
});
}
/**
* Get metadata about a cohort characterization.
*
* @param id The id for an existing cohort characterization
* @return name, createdDate, tags, etc for a single cohort characterization.
*/
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CcShortDTO get(@PathParam("id") final Long id) {
return convertCcToShortDto(service.findById(id));
}
/**
* Get the complete design specification for a single cohort characterization.
*
* @param id The id for an existing cohort characterization
* @return JSON containing the cohort characterization specification
*/
@GET
@Path("/{id}/design")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CohortCharacterizationDTO getDesign(@PathParam("id") final Long id) {
CohortCharacterizationEntity cc = service.findByIdWithLinkedEntities(id);
ExceptionUtils.throwNotFoundExceptionIfNull(cc, String.format("There is no cohort characterization with id = %d.", id));
return convertCcToDto(cc);
}
/**
* Check if a cohort characterization with the same name exists
*
* <p>This endpoint is used to check that a desired name for a characterization does not already exist in WebAPI</p>
*
* @param id The id for a new characterization that does not currently exist in WebAPI
* @param name The desired name for the new cohort characterization
* @return The number of existing characterizations with the same name that was passed as a query parameter
*/
@GET
@Path("/{id}/exists")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public int getCountCcWithSameName(@PathParam("id") @DefaultValue("0") final long id, @QueryParam("name") String name) {
return service.getCountCcWithSameName(id, name);
}
/**
* Remove a characterization from WebAPI
*
* @param id The id for a characterization that currently exists in WebAPI
*/
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void deleteCc(@PathParam("id") final Long id) {
service.deleteCc(id);
}
private CohortCharacterizationDTO convertCcToDto(final CohortCharacterizationEntity entity) {
return conversionService.convert(entity, CohortCharacterizationDTO.class);
}
private CcShortDTO convertCcToShortDto(final CohortCharacterizationEntity entity) {
return conversionService.convert(entity, CcShortDTO.class);
}
@PUT
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CohortCharacterizationDTO update(@PathParam("id") final Long id, final CohortCharacterizationDTO dto) {
service.saveVersion(dto.getId());
final CohortCharacterizationEntity entity = conversionService.convert(dto, CohortCharacterizationEntity.class);
entity.setId(id);
final CohortCharacterizationEntity updatedEntity = service.updateCc(entity);
return convertCcToDto(updatedEntity);
}
/**
* Add a new cohort characterization analysis to WebAPI
*
* @chrisknoll this endpoint did not work when I tried it.
*
* @param dto A cohort characterization definition
* @return The same cohort characterization definition that was passed as input
*/
@POST
@Path("/import")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CohortCharacterizationDTO doImport(final CcExportDTO dto) {
dto.setName(service.getNameWithSuffix(dto.getName()));
dto.setTags(null);
final CohortCharacterizationEntity entity = conversionService.convert(dto, CohortCharacterizationEntity.class);
return conversionService.convert(service.importCc(entity), CohortCharacterizationDTO.class);
}
/**
* Get a cohort characterization definition
*
* @param id The id of an existing cohort characterization definition
* @return JSON containing the cohort characterization definition
*/
@GET
@Path("/{id}/export")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String export(@PathParam("id") final Long id) {
return service.serializeCc(id);
}
/**
* Get csv files containing concept sets used in a characterization analysis
* @param id The id for a cohort characterization analysis
* @return A zip file containing three csv files (mappedConcepts, includedConcepts, conceptSetExpression)
*/
@GET
@Path("/{id}/export/conceptset")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response exportConceptSets(@PathParam("id") final Long id) {
CohortCharacterizationEntity cc = service.findById(id);
Optional.ofNullable(cc).orElseThrow(NotFoundException::new);
List<ConceptSetExport> exportList = service.exportConceptSets(cc);
ByteArrayOutputStream stream = ExportUtil.writeConceptSetExportToCSVAndZip(exportList);
return HttpUtils.respondBinary(stream, String.format("cc_%d_export.zip", id));
}
/**
* Check that a cohort characterization definition is correct
* @summary Check a cohort characterization definition
* @param characterizationDTO A cohort characterization definition object
* @return A list of warnings that is possibly empty
*/
@POST
@Path("/check")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CheckResult runDiagnostics(CohortCharacterizationDTO characterizationDTO){
return new CheckResult(checker.check(characterizationDTO));
}
/**
* Generate a cohort characterization on a single data source
* @param id The id of an existing cohort characterization in WebAPI
* @param sourceKey The identifier for the data source to generate against
* @return A json object with information about the generation job included the status and execution id.
*/
@POST
@Path("/{id}/generation/{sourceKey}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JobExecutionResource generate(@PathParam("id") final Long id, @PathParam("sourceKey") final String sourceKey) {
CohortCharacterizationEntity cc = service.findByIdWithLinkedEntities(id);
ExceptionUtils.throwNotFoundExceptionIfNull(cc, String.format("There is no cohort characterization with id = %d.", id));
CheckResult checkResult = runDiagnostics(convertCcToDto(cc));
if (checkResult.hasCriticalErrors()) {
throw new RuntimeException("Cannot be generated due to critical errors in design. Call 'check' service for further details");
}
return service.generateCc(id, sourceKey);
}
/**
* Cancel a cohort characterization generation
* @param id The id of an existing cohort characterization
* @param sourceKey The sourceKey for the data source to generate against
* @return Status code
*/
@DELETE
@Path("/{id}/generation/{sourceKey}")
public Response cancelGeneration(@PathParam("id") final Long id, @PathParam("sourceKey") final String sourceKey) {
service.cancelGeneration(id, sourceKey);
return Response.ok().build();
}
/**
* Get all generations for a cohort characterization
* @param id The id for an existing cohort characterization
* @return An array of all generations that includes the generation id, sourceKey, start and end times
*/
@GET
@Path("/{id}/generation")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<CommonGenerationDTO> getGenerationList(@PathParam("id") final Long id) {
Map<String, Source> sourcesMap = sourceService.getSourcesMap(SourceMapKey.BY_SOURCE_KEY);
return sensitiveInfoService.filterSensitiveInfo(converterUtils.convertList(service.findGenerationsByCcId(id), CommonGenerationDTO.class),
info -> Collections.singletonMap(Constants.Variables.SOURCE, sourcesMap.get(info.getSourceKey())));
}
/**
* Get generation information by generation id
* @param generationId The generation id to look up
* @return Data about the generation including the generation id, sourceKey, hashcode, start and end times
*/
@GET
@Path("/generation/{generationId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CommonGenerationDTO getGeneration(@PathParam("generationId") final Long generationId) {
CcGenerationEntity generationEntity = service.findGenerationById(generationId);
return sensitiveInfoService.filterSensitiveInfo(conversionService.convert(generationEntity, CommonGenerationDTO.class),
Collections.singletonMap(Constants.Variables.SOURCE, generationEntity.getSource()));
}
/**
* Delete a cohort characterization generation
* @param generationId
*/
@DELETE
@Path("/generation/{generationId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void deleteGeneration(@PathParam("generationId") final Long generationId) {
service.deleteCcGeneration(generationId);
}
/**
* Get the definition of a cohort characterization for a given generation id
* @param generationId
* @return A cohort characterization definition
*/
@GET
@Path("/generation/{generationId}/design")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CcExportDTO getGenerationDesign(
@PathParam("generationId") final Long generationId) {
return conversionService.convert(service.findDesignByGenerationId(generationId), CcExportDTO.class);
}
/**
* Get the total number of analyses in a cohort characterization
*
* @param generationId
* @return The total number of analyses in the given cohort characterization
*/
@GET
@Path("/generation/{generationId}/result/count")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Long getGenerationsResultsCount( @PathParam("generationId") final Long generationId) {
return service.getCCResultsTotalCount(generationId);
}
/**
* Get cohort characterization results
* @param generationId id for generation
* @param thresholdLevel The max prevelance for a covariate. Covariates that occur in less than {threholdLevel}%
* of the cohort will not be returned. Default is 0.01 = 1%
* @return The complete set of characterization analyses filtered by the thresholdLevel parameter
*/
@GET
@Path("/generation/{generationId}/result")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<CcResult> getGenerationsResults(
@PathParam("generationId") final Long generationId, @DefaultValue("0.01") @QueryParam("thresholdLevel") final float thresholdLevel) {
return service.findResultAsList(generationId, thresholdLevel);
}
@GET
@Path("/generation/{generationId}/temporalresult")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<CcTemporalResult> getGenerationTemporalResults(@PathParam("generationId") final Long generationId) {
return service.findTemporalResultAsList(generationId);
}
@POST
@Path("/generation/{generationId}/result")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ReturnType("java.lang.Object")
public GenerationResults getGenerationsResults(
@PathParam("generationId") final Long generationId, @RequestBody ExportExecutionResultRequest params) {
return service.findData(generationId, params);
}
@POST
@Path("/generation/{generationId}/result/export")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
public Response exportGenerationsResults(
@PathParam("generationId") final Long generationId, ExportExecutionResultRequest params) {
GenerationResults res = service.exportExecutionResult(generationId, params);
return prepareExecutionResultResponse(res.getReports());
}
private Response prepareExecutionResultResponse(List<Report> reports) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Report report : reports) {
createZipEntry(zos, report);
}
zos.closeEntry();
baos.flush();
return Response
.ok(baos)
.type(MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", String.format("attachment; filename=\"%s\"", "reports.zip"))
.build();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void createZipEntry(ZipOutputStream zos, Report report) throws IOException {
StringWriter sw = new StringWriter();
CSVWriter csvWriter = new CSVWriter(sw, ',', CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER);
csvWriter.writeAll(report.header);
csvWriter.writeAll(report.getResultArray());
csvWriter.flush();
String filename = report.analysisName;
if (report.isComparative) {
filename = "Export comparison (" + filename + ")";
} else {
filename = "Export (" + filename + ")";
}
// trim the name so it can be opened by archiver,
// -1 is for dot character
if (filename.length() >= 64) {
filename = filename.substring(0, 63);
}
filename = CommonFilenameUtils.sanitizeFilename(filename);
ZipEntry resultsEntry = new ZipEntry(filename + ".csv");
zos.putNextEntry(resultsEntry);
zos.write(sw.getBuffer().toString().getBytes());
}
@GET
@Path("/generation/{generationId}/explore/prevalence/{analysisId}/{cohortId}/{covariateId}")
@Produces(MediaType.APPLICATION_JSON)
public List<CcPrevalenceStat> getPrevalenceStat(@PathParam("generationId") Long generationId,
@PathParam("analysisId") Long analysisId,
@PathParam("cohortId") Long cohortId,
@PathParam("covariateId") Long covariateId) {
Integer presetId = convertPresetAnalysisIdToSystem(Math.toIntExact(analysisId));
List<CcPrevalenceStat> stats = service.getPrevalenceStatsByGenerationId(generationId, Long.valueOf(presetId), cohortId, covariateId);
convertPresetAnalysesToLocal(stats);
return stats;
}
/**
* Download a cohort characterization R study package that can be used to run the characterization on an OMOP CDM from R
* @summary Download a cohort characterization R package
* @param analysisId id of the cohort characterization to convert to an R study package
* @param packageName The name of the R study package
* @return A zip file containing the cohort characterization R study package
*/
@GET
@Path("{id}/download")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadPackage(@PathParam("id") Long analysisId, @QueryParam("packageName") String packageName) {
if (packageName == null) {
packageName = "CohortCharacterization" + String.valueOf(analysisId);
}
if (!Utils.isAlphaNumeric(packageName)) {
throw new IllegalArgumentException("The package name must be alphanumeric only.");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
service.hydrateAnalysis(analysisId, packageName, baos);
return Response
.ok(baos)
.type(MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", String.format("attachment; filename=\"cohort_characterization_study_%d_export.zip\"", analysisId))
.build();
}
/**
* Assign tag to Cohort Characterization
*
* @param id
* @param tagId
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/tag/")
@javax.transaction.Transactional
public void assignTag(@PathParam("id") final long id, final int tagId) {
service.assignTag(id, tagId);
}
/**
* Unassign tag from Cohort Characterization
*
* @param id
* @param tagId
*/
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/tag/{tagId}")
@javax.transaction.Transactional
public void unassignTag(@PathParam("id") final long id, @PathParam("tagId") final int tagId) {
service.unassignTag(id, tagId);
}
/**
* Assign protected tag to Cohort Characterization
*
* @param id
* @param tagId
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/protectedtag/")
@javax.transaction.Transactional
public void assignPermissionProtectedTag(@PathParam("id") final long id, final int tagId) {
service.assignTag(id, tagId);
}
/**
* Unassign protected tag from Cohort Characterization
*
* @param id
* @param tagId
*/
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/protectedtag/{tagId}")
@javax.transaction.Transactional
public void unassignPermissionProtectedTag(@PathParam("id") final long id, @PathParam("tagId") final int tagId) {
service.unassignTag(id, tagId);
}
/**
* Get list of versions of Cohort Characterization
*
* @param id
* @return
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/version/")
public List<VersionDTO> getVersions(@PathParam("id") final long id) {
return service.getVersions(id);
}
/**
* Get version of Cohort Characterization
*
* @param id
* @param version
* @return
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/version/{version}")
public CcVersionFullDTO getVersion(@PathParam("id") final long id, @PathParam("version") final int version) {
return service.getVersion(id, version);
}
/**
* Update version of Cohort Characterization
*
* @param id
* @param version
* @param updateDTO
* @return
*/
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/version/{version}")
public VersionDTO updateVersion(@PathParam("id") final long id, @PathParam("version") final int version,
VersionUpdateDTO updateDTO) {
return service.updateVersion(id, version, updateDTO);
}
/**
* Delete version of Cohort Characterization
*
* @param id
* @param version
*/
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/version/{version}")
public void deleteVersion(@PathParam("id") final long id, @PathParam("version") final int version) {
service.deleteVersion(id, version);
}
/**
* Create a new asset form version of Cohort Characterization
*
* @param id
* @param version
* @return
*/
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/version/{version}/createAsset")
public CohortCharacterizationDTO copyAssetFromVersion(@PathParam("id") final long id,
@PathParam("version") final int version) {
return service.copyAssetFromVersion(id, version);
}
/**
* Get list of cohort characterizations with assigned tags
*
* @param requestDTO
* @return
*/
@POST
@Path("/byTags")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<CcShortDTO> listByTags(TagNameListRequestDTO requestDTO) {
if (requestDTO == null || requestDTO.getNames() == null || requestDTO.getNames().isEmpty()) {
return Collections.emptyList();
}
return service.listByTags(requestDTO);
}
private void convertPresetAnalysesToLocal(List<? extends CcResult> ccResults) {
List<FeAnalysisWithStringEntity> presetFeAnalyses = feAnalysisService.findPresetAnalysesBySystemNames(ccResults.stream().map(CcResult::getAnalysisName).distinct().collect(Collectors.toList()));
ccResults.stream().filter(res -> Objects.equals(res.getFaType(), StandardFeatureAnalysisType.PRESET.name()))
.forEach(res -> {
presetFeAnalyses.stream().filter(fa -> fa.getDesign().equals(res.getAnalysisName())).findFirst().ifPresent(fa -> {
res.setAnalysisId(fa.getId());
res.setAnalysisName(fa.getName());
});
});
}
private Integer convertPresetAnalysisIdToSystem(Integer analysisId) {
FeAnalysisEntity fe = feAnalysisService.findById(analysisId).orElse(null);
if (fe instanceof FeAnalysisWithStringEntity && fe.isPreset()) {
FeatureExtraction.PrespecAnalysis prespecAnalysis = FeatureExtraction.getNameToPrespecAnalysis().get(((FeAnalysisWithStringEntity) fe).getDesign());
return prespecAnalysis.analysisId;
}
return analysisId;
}
}
| 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/cohortcharacterization/dto/BaseCcDTO.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/BaseCcDTO.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.ohdsi.analysis.CohortMetadata;
import org.ohdsi.circe.cohortdefinition.ConceptSet;
import org.ohdsi.webapi.cohortdefinition.CohortMetadataExt;
import org.ohdsi.webapi.cohortdefinition.dto.CohortMetadataImplDTO;
import org.ohdsi.webapi.feanalysis.dto.FeAnalysisShortDTO;
import java.util.ArrayList;
import java.util.Collection;
public class BaseCcDTO<T extends CohortMetadataImplDTO, F extends FeAnalysisShortDTO> extends CcShortDTO {
private Collection<T> cohorts = new ArrayList<>();
private Collection<F> featureAnalyses = new ArrayList<>();
private Collection<CcParameterDTO> parameters = new ArrayList<>();
@JsonProperty("stratifiedBy")
private String stratifiedBy;
@JsonProperty("strataOnly")
private Boolean strataOnly;
private Collection<CcStrataDTO> stratas = new ArrayList<>();
@JsonProperty("strataConceptSets")
private Collection<ConceptSet> strataConceptSets = new ArrayList<>();
public Collection<T> getCohorts() {
return cohorts;
}
public void setCohorts(Collection<T> cohorts) {
this.cohorts = cohorts;
}
public Collection<CcParameterDTO> getParameters() {
return parameters;
}
public void setParameters(final Collection<CcParameterDTO> parameters) {
this.parameters = parameters;
}
public Collection<F> getFeatureAnalyses() {
return featureAnalyses;
}
public void setFeatureAnalyses(final Collection<F> featureAnalyses) {
this.featureAnalyses = featureAnalyses;
}
public Collection<CcStrataDTO> getStratas() {
return stratas;
}
public void setStratas(Collection<CcStrataDTO> stratas) {
this.stratas = stratas;
}
public String getStratifiedBy() {
return stratifiedBy;
}
public void setStratifiedBy(String stratifiedBy) {
this.stratifiedBy = stratifiedBy;
}
public Boolean getStrataOnly() {
return strataOnly;
}
public void setStrataOnly(Boolean strataOnly) {
this.strataOnly = strataOnly;
}
public Collection<ConceptSet> getStrataConceptSets() {
return strataConceptSets;
}
public void setStrataConceptSets(Collection<ConceptSet> strataConceptSets) {
this.strataConceptSets = strataConceptSets;
}
}
| 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/cohortcharacterization/dto/CcVersionFullDTO.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/CcVersionFullDTO.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import org.ohdsi.webapi.versioning.dto.VersionFullDTO;
public class CcVersionFullDTO extends VersionFullDTO<CohortCharacterizationDTO> {
}
| 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/cohortcharacterization/dto/CcTemporalAnnualResult.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/CcTemporalAnnualResult.java | package org.ohdsi.webapi.cohortcharacterization.dto;
public class CcTemporalAnnualResult extends AbstractTemporalResult{
private Integer year;
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
}
| 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/cohortcharacterization/dto/ExportExecutionResultRequest.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/ExportExecutionResultRequest.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ExportExecutionResultRequest extends ExecutionResultRequest{
@JsonProperty("isComparative")
private Boolean isComparative;
public Boolean isComparative() {
return isComparative;
}
public void setComparative(Boolean comparative) {
isComparative = comparative;
}
}
| 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/cohortcharacterization/dto/CcShortDTO.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/CcShortDTO.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import org.ohdsi.webapi.service.dto.CommonEntityExtDTO;
public class CcShortDTO extends CommonEntityExtDTO {
private Long id;
private Integer hashCode;
private String name;
private String description;
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public Integer getHashCode() {
return hashCode;
}
public void setHashCode(final Integer hashCode) {
this.hashCode = hashCode;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 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/cohortcharacterization/dto/GenerationResults.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/GenerationResults.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import org.ohdsi.webapi.cohortcharacterization.report.Report;
import java.util.List;
public class GenerationResults {
private List<Report> reports;
private Float prevalenceThreshold;
private Boolean showEmptyResults;
private int count;
public List<Report> getReports() {
return reports;
}
public void setReports(List<Report> reports) {
this.reports = reports;
}
public Float getPrevalenceThreshold() {
return prevalenceThreshold;
}
public void setPrevalenceThreshold(Float prevalenceThreshold) {
this.prevalenceThreshold = prevalenceThreshold;
}
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return count;
}
public Boolean getShowEmptyResults() {
return showEmptyResults;
}
public void setShowEmptyResults(Boolean showEmptyResults) {
this.showEmptyResults = showEmptyResults;
}
}
| 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/cohortcharacterization/dto/UserDTO.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/UserDTO.java | package org.ohdsi.webapi.cohortcharacterization.dto;
public class UserDTO {
private Long id;
private String name;
private String 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/cohortcharacterization/dto/CcStrataDTO.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/CcStrataDTO.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import org.ohdsi.analysis.cohortcharacterization.design.CohortCharacterizationStrata;
import org.ohdsi.circe.cohortdefinition.CriteriaGroup;
public class CcStrataDTO implements CohortCharacterizationStrata {
private Long id;
private String name;
private CriteriaGroup criteria;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CriteriaGroup getCriteria() {
return criteria;
}
public void setCriteria(CriteriaGroup criteria) {
this.criteria = criteria;
}
}
| 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/cohortcharacterization/dto/AbstractTemporalResult.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/AbstractTemporalResult.java | package org.ohdsi.webapi.cohortcharacterization.dto;
public abstract class AbstractTemporalResult {
protected Integer analysisId;
protected String analysisName;
protected Long covariateId;
protected String covariateName;
protected Integer strataId;
protected String strataName;
protected Integer conceptId;
protected Integer cohortId;
protected Long count;
protected Double avg;
public Integer getAnalysisId() {
return analysisId;
}
public void setAnalysisId(Integer analysisId) {
this.analysisId = analysisId;
}
public String getAnalysisName() {
return analysisName;
}
public void setAnalysisName(String analysisName) {
this.analysisName = analysisName;
}
public Long getCovariateId() {
return covariateId;
}
public void setCovariateId(Long covariateId) {
this.covariateId = covariateId;
}
public String getCovariateName() {
return covariateName;
}
public void setCovariateName(String covariateName) {
this.covariateName = covariateName;
}
public Integer getStrataId() {
return strataId;
}
public void setStrataId(Integer strataId) {
this.strataId = strataId;
}
public String getStrataName() {
return strataName;
}
public void setStrataName(String strataName) {
this.strataName = strataName;
}
public Integer getConceptId() {
return conceptId;
}
public void setConceptId(Integer conceptId) {
this.conceptId = conceptId;
}
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
public Double getAvg() {
return avg;
}
public void setAvg(Double avg) {
this.avg = avg;
}
public Integer getCohortId() {
return cohortId;
}
public void setCohortId(Integer cohortId) {
this.cohortId = cohortId;
}
}
| 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/cohortcharacterization/dto/CcParameterDTO.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/CcParameterDTO.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import org.ohdsi.analysis.cohortcharacterization.design.CohortCharacterizationParam;
public class CcParameterDTO implements CohortCharacterizationParam {
private Long id;
private String name;
private String value;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
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/cohortcharacterization/dto/CcTemporalResult.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/CcTemporalResult.java | package org.ohdsi.webapi.cohortcharacterization.dto;
public class CcTemporalResult extends AbstractTemporalResult {
private Integer timeId;
private Integer startDay;
private Integer endDay;
public Integer getTimeId() {
return timeId;
}
public void setTimeId(Integer timeId) {
this.timeId = timeId;
}
public Integer getStartDay() {
return startDay;
}
public void setStartDay(Integer startDay) {
this.startDay = startDay;
}
public Integer getEndDay() {
return endDay;
}
public void setEndDay(Integer endDay) {
this.endDay = endDay;
}
}
| 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/cohortcharacterization/dto/CohortCharacterizationDTO.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/CohortCharacterizationDTO.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import org.ohdsi.webapi.cohortdefinition.dto.CohortMetadataImplDTO;
import org.ohdsi.webapi.feanalysis.dto.FeAnalysisShortDTO;
public class CohortCharacterizationDTO extends BaseCcDTO<CohortMetadataImplDTO, FeAnalysisShortDTO> {
}
| 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/cohortcharacterization/dto/ExecutionResultRequest.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/ExecutionResultRequest.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.ohdsi.webapi.Constants;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class ExecutionResultRequest {
@JsonProperty("cohortIds")
private List<Integer> cohortIds;
@JsonProperty("analysisIds")
private List<Integer> analysisIds;
@JsonProperty("domainIds")
private List<String> domainIds;
@JsonProperty("thresholdValuePct")
private Float thresholdValuePct;
@JsonProperty("isSummary")
private Boolean isSummary;
@JsonProperty("showEmptyResults")
private Boolean isShowEmptyResults = false;
public List<Integer> getCohortIds() {
if(cohortIds == null) {
return Collections.emptyList();
}
return cohortIds;
}
public void setCohortIds(List<Integer> cohortIds) {
this.cohortIds = cohortIds;
}
public List<Integer> getAnalysisIds() {
if(analysisIds == null) {
return Collections.emptyList();
}
return analysisIds;
}
public void setAnalysisIds(List<Integer> analysisIds) {
this.analysisIds = analysisIds;
}
public List<String> getDomainIds() {
if(domainIds == null) {
return Collections.emptyList();
}
return domainIds;
}
public void setDomainIds(List<String> domainIds) {
this.domainIds = domainIds;
}
public boolean isFilterUsed() {
return !(getAnalysisIds().isEmpty() && getDomainIds().isEmpty() && getCohortIds().isEmpty());
}
public Float getThresholdValuePct() {
return thresholdValuePct != null ? thresholdValuePct : Constants.DEFAULT_THRESHOLD;
}
public void setThresholdValuePct(Float thresholdValuePct) {
this.thresholdValuePct = thresholdValuePct;
}
public Boolean isSummary() {
return isSummary;
}
public void setSummary(Boolean summary) {
isSummary = summary;
}
public Boolean getShowEmptyResults() {
return Boolean.TRUE.equals(isShowEmptyResults);
}
public void setShowEmptyResults(Boolean showEmptyResults) {
isShowEmptyResults = showEmptyResults;
}
}
| 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/cohortcharacterization/dto/CcExportDTO.java | src/main/java/org/ohdsi/webapi/cohortcharacterization/dto/CcExportDTO.java | package org.ohdsi.webapi.cohortcharacterization.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.ohdsi.analysis.cohortcharacterization.design.CohortCharacterization;
import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO;
import org.ohdsi.webapi.feanalysis.dto.FeAnalysisDTO;
@JsonIgnoreProperties(ignoreUnknown = true)
public class CcExportDTO extends BaseCcDTO<CohortDTO, FeAnalysisDTO> implements CohortCharacterization {
}
| java | Apache-2.0 | b22d7bf02d98c0cf78c46801877368d6ecad2245 | 2026-01-05T02:37:20.475642Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.