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/test/java/org/ohdsi/webapi/util/DataSourceDTOParserTest.java
src/test/java/org/ohdsi/webapi/util/DataSourceDTOParserTest.java
package org.ohdsi.webapi.util; import com.odysseusinc.arachne.commons.types.DBMSType; import com.odysseusinc.arachne.execution_engine_common.api.v1.dto.DataSourceUnsecuredDTO; import org.junit.Test; import org.ohdsi.webapi.source.Source; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.*; public class DataSourceDTOParserTest { public static final String PGSQL_CONN_STR = "jdbc:postgresql://localhost:5432/ohdsi?ssl=true&user=user&password=secret"; public static final String PGSQL_WO_PWD_CONN_STR = "jdbc:postgresql://localhost:5432/ohdsi?ssl=true"; public static final String MSSQL_CONN_STR = "jdbc:sqlserver://localhost:1433;databaseName=ohdsi;user=msuser;password=password"; public static final String PDW_CONN_STR = "jdbc:sqlserver://yourserver.database.windows.net:1433;database=yourdatabase;user=pdw_user;password=pdw_password;" + "encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"; public static final String REDSHIFT_CONN_STR = "jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/" + "dev?ssl=true&UID=your_username&PWD=your_password"; public static final String NETEZZA_CONN_STR = "jdbc:netezza://main:5490/sales;user=admin;password=password;loglevel=2;logdirpath=C:\\"; public static final String IMPALA_AUTH3_CONN_STR = "jdbc:impala://node1.example.com:18000/default2;AuthMech=3;UID=cloudera;PWD=cloudera"; public static final String IMPALA_AUTH0_CONN_STR = "jdbc:impala://localhost:21050;AuthMech=0;"; public static final String IMPALA_AUTH1_CONN_STR = "jdbc:impala://node1.example.com:21050;AuthMech=1;" + "KrbRealm=EXAMPLE.COM;KrbHostFQDN=node1.example.com;KrbServiceName=impala"; private static final String BIGQUERY_CONN_STR = "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + "ProjectId=MyBigQueryProject;OAuthType=0;OAuthServiceAcctEmail==bqtest1@data-driver-testing.iam.gserviceaccount.com;" + "OAuthPvtKeyPath=C:\\SecureFiles\\ServiceKeyFile.p12;"; public static final String ORACLE_WO_PWD_CONN_STR = "jdbc:oracle:thin:@myhost:1521:orcl"; public static final String ORACLE_WITH_PWD_CONN_STR = "jdbc:oracle:thin:scott/tiger@myhost:1521:orcl"; public static final String HIVE_CONN_STR = "jdbc:hive2://sandbox-hdp.hortonworks.com:2181/synpuf_531_orc;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2"; public static final String IRIS_CONN_STR = "jdbc:IRIS://localhost:1972/USER"; @Test public void parseDTO() { DataSourceUnsecuredDTO dto; dto = DataSourceDTOParser.parseDTO(getPostgreSQLSource()); assertThat(dto.getType(), is(DBMSType.POSTGRESQL)); assertThat(dto.getConnectionString(), is(PGSQL_CONN_STR)); assertThat(dto.getUsername(), is("user")); assertThat(dto.getPassword(), is("secret")); dto = DataSourceDTOParser.parseDTO(getPostgreSQLPasswordSource()); assertThat(dto.getType(), is(DBMSType.POSTGRESQL)); assertThat(dto.getConnectionString(), is(PGSQL_WO_PWD_CONN_STR)); assertThat(dto.getUsername(), is("user")); assertThat(dto.getPassword(), is("password")); dto = DataSourceDTOParser.parseDTO(getMSSQLSource()); assertThat(dto.getType(), is(DBMSType.MS_SQL_SERVER)); assertThat(dto.getConnectionString(), is((MSSQL_CONN_STR))); assertThat(dto.getUsername(), is("msuser")); assertThat(dto.getPassword(), is("password")); dto = DataSourceDTOParser.parseDTO(getPDWSource()); assertThat(dto.getType(), is(DBMSType.PDW)); assertThat(dto.getConnectionString(), is(PDW_CONN_STR)); assertThat(dto.getUsername(), is("pdw_user")); assertThat(dto.getPassword(), is("pdw_password")); dto = DataSourceDTOParser.parseDTO(getRedshiftSource()); assertThat(dto.getType(), is(DBMSType.REDSHIFT)); assertThat(dto.getConnectionString(), is(REDSHIFT_CONN_STR)); assertThat(dto.getUsername(), is("your_username")); assertThat(dto.getPassword(), is("your_password")); dto = DataSourceDTOParser.parseDTO(getNetezzaSource()); assertThat(dto.getType(), is(DBMSType.NETEZZA)); assertThat(dto.getConnectionString(), is(NETEZZA_CONN_STR)); assertThat(dto.getUsername(), is("admin")); assertThat(dto.getPassword(), is("password")); dto = DataSourceDTOParser.parseDTO(getImpalaAuth3Source()); assertThat(dto.getType(), is(DBMSType.IMPALA)); assertThat(dto.getConnectionString(), is(IMPALA_AUTH3_CONN_STR)); assertThat(dto.getUsername(), is("cloudera")); assertThat(dto.getPassword(), is("cloudera")); dto = DataSourceDTOParser.parseDTO(getImpalaAuth0Source()); assertThat(dto.getType(), is(DBMSType.IMPALA)); assertThat(dto.getConnectionString(), is(IMPALA_AUTH0_CONN_STR)); assertThat(dto.getUsername(), is(nullValue())); assertThat(dto.getPassword(), is(nullValue())); dto = DataSourceDTOParser.parseDTO(getImpalaAuth1Source()); assertThat(dto.getType(), is(DBMSType.IMPALA)); assertThat(dto.getConnectionString(), is(IMPALA_AUTH1_CONN_STR)); assertThat(dto.getUsername(), is(nullValue())); assertThat(dto.getPassword(), is(nullValue())); dto = DataSourceDTOParser.parseDTO(getBigQuerySource()); assertThat(dto.getType(), is(DBMSType.BIGQUERY)); assertThat(dto.getConnectionString(), is(BIGQUERY_CONN_STR)); assertThat(dto.getUsername(), is(nullValue())); assertThat(dto.getPassword(), is(nullValue())); dto = DataSourceDTOParser.parseDTO(getOracleWOPwdSource()); assertThat(dto.getType(), is(DBMSType.ORACLE)); assertThat(dto.getConnectionString(), is(ORACLE_WO_PWD_CONN_STR)); assertThat(dto.getUsername(), is(nullValue())); assertThat(dto.getPassword(), is(nullValue())); dto = DataSourceDTOParser.parseDTO(getOracleWithPwdSource()); assertThat(dto.getType(), is(DBMSType.ORACLE)); assertThat(dto.getConnectionString(), is(ORACLE_WITH_PWD_CONN_STR)); assertThat(dto.getUsername(), is("scott")); assertThat(dto.getPassword(), is("tiger")); dto = DataSourceDTOParser.parseDTO(getHiveSource()); assertThat(dto.getType(), is(DBMSType.HIVE)); assertThat(dto.getConnectionString(), is(HIVE_CONN_STR)); assertThat(dto.getUsername(), is(nullValue())); assertThat(dto.getPassword(), is(nullValue())); dto = DataSourceDTOParser.parseDTO(getIRISSource()); assertThat(dto.getType(), is(DBMSType.IRIS)); assertThat(dto.getConnectionString(), is(IRIS_CONN_STR)); assertThat(dto.getUsername(), is(nullValue())); assertThat(dto.getPassword(), is(nullValue())); } private Source getPostgreSQLPasswordSource() { Source source = new Source(); source.setSourceDialect("postgresql"); source.setSourceConnection(PGSQL_WO_PWD_CONN_STR); source.setUsername("user"); source.setPassword("password"); return source; } private Source getOracleWithPwdSource() { Source source = new Source(); source.setSourceDialect("oracle"); source.setSourceConnection(ORACLE_WITH_PWD_CONN_STR); return source; } private Source getOracleWOPwdSource() { Source source = new Source(); source.setSourceDialect("oracle"); source.setSourceConnection(ORACLE_WO_PWD_CONN_STR); return source; } private Source getBigQuerySource() { Source source = new Source(); source.setSourceDialect("bigquery"); source.setSourceConnection(BIGQUERY_CONN_STR); return source; } private Source getImpalaAuth1Source() { Source source = new Source(); source.setSourceDialect("impala"); source.setSourceConnection(IMPALA_AUTH1_CONN_STR); return source; } private Source getImpalaAuth0Source() { Source source = new Source(); source.setSourceDialect("impala"); source.setSourceConnection(IMPALA_AUTH0_CONN_STR); return source; } private Source getImpalaAuth3Source() { Source source = new Source(); source.setSourceDialect("impala"); source.setSourceConnection(IMPALA_AUTH3_CONN_STR); return source; } private Source getNetezzaSource() { Source source = new Source(); source.setSourceDialect("netezza"); source.setSourceConnection(NETEZZA_CONN_STR); return source; } private Source getRedshiftSource() { Source source = new Source(); source.setSourceDialect("redshift"); source.setSourceConnection(REDSHIFT_CONN_STR); return source; } private Source getPDWSource() { Source source = new Source(); source.setSourceDialect("pdw"); source.setSourceConnection(PDW_CONN_STR); return source; } private Source getMSSQLSource() { Source source = new Source(); source.setSourceDialect("sql server"); source.setSourceConnection(MSSQL_CONN_STR); return source; } private Source getPostgreSQLSource() { Source source = new Source(); source.setSourceDialect("postgresql"); source.setSourceConnection(PGSQL_CONN_STR); return source; } private Source getHiveSource() { Source source = new Source(); source.setSourceDialect("hive"); source.setSourceConnection(HIVE_CONN_STR); return source; } private Source getIRISSource() { Source source = new Source(); source.setSourceDialect("iris"); source.setSourceConnection(IRIS_CONN_STR); return source; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/util/JsonMappingTest.java
src/test/java/org/ohdsi/webapi/util/JsonMappingTest.java
package org.ohdsi.webapi.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import org.aspectj.lang.JoinPoint; import org.junit.Test; public class JsonMappingTest { @Test public void testJsonMapping() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); Exception e = new Exception("some exception"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String s = sw.toString(); Result r = new Result(); r.setStatus("success"); r.setErrorString(s); r.setReturnedValueType(null); r.setInvocationDate(new Date().toString()); s = mapper.writeValueAsString(r); System.out.println(s); } class Result { private String status; private String returnedValueType; private String signature; private String signatureName; private String invocationDate; private String errorString; public Result() { super(); } public void Result(JoinPoint joinPoint, Throwable returnedThrowable, Date invocationDate) { setState(joinPoint, returnedThrowable, invocationDate); } protected void setState(JoinPoint joinPoint, Throwable returnedThrowable, Date invocationDate) { this.signatureName = joinPoint.getSignature().getName(); this.signature = joinPoint.getSignature().toLongString(); this.status = "failed"; this.returnedValueType = "no return value since operation failed"; /// set error string StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); returnedThrowable.printStackTrace(pw); errorString = sw.toString(); setInvocationDate(invocationDate.toString()); } protected void setState(JoinPoint joinPoint, Object returnedValue, Date invocationDate) { this.signatureName = joinPoint.getSignature().getName(); this.signature = joinPoint.getSignature().toLongString(); this.status = "succeeded"; if (returnedValue == null) { this.returnedValueType = "null"; } else { this.returnedValueType = returnedValue.getClass().getName(); } errorString = ""; setInvocationDate(invocationDate.toString()); } public String getInvocationDate() { return invocationDate; } public void setInvocationDate(String date) { this.invocationDate = date; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getErrorString() { return errorString; } public void setErrorString(String stringException) { this.errorString = stringException; } public String getReturnedValueType() { return returnedValueType; } public void setReturnedValueType(String returnedValueType) { this.returnedValueType = returnedValueType; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public String getSignatureName() { return signatureName; } public void setSignatureName(String signatureName) { this.signatureName = signatureName; } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/VocabularyServiceTest.java
src/test/java/org/ohdsi/webapi/service/VocabularyServiceTest.java
package org.ohdsi.webapi.service; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.ohdsi.webapi.vocabulary.ConceptSearch; import org.ohdsi.webapi.vocabulary.DescendentOfAncestorSearch; import org.ohdsi.webapi.vocabulary.RelatedConceptSearch; import org.springframework.beans.factory.annotation.Autowired; public class VocabularyServiceTest extends AbstractServiceTest { @Autowired private VocabularyService vocabularyService; @Before public void before() { if (vocabularyService == null) { vocabularyService = new VocabularyService(); } } @Test public void prepareExecuteSearch() throws IOException { Source mockSource = mock(Source.class); when(mockSource.getTableQualifier(SourceDaimon.DaimonType.Vocabulary)).thenReturn("omop_v5"); when(mockSource.getSourceDialect()).thenReturn("sql server"); ConceptSearch search = new ConceptSearch(); search.query = "conceptABC"; int domainIdCount = 5; search.domainId = new String[domainIdCount]; for (int i = 0; i < domainIdCount; i++) { search.domainId[i] = "domainId" + i; } int vocabularyIdCount = 10; search.vocabularyId = new String[vocabularyIdCount]; for (int i = 0; i < vocabularyIdCount; i++) { search.vocabularyId[i] = "vocabularyId" + i; } int conceptClassIdCount = 15; search.conceptClassId = new String[conceptClassIdCount]; for (int i = 0; i < conceptClassIdCount; i++) { search.conceptClassId[i] = "conceptClassId" + i; } search.invalidReason = "V"; search.standardConcept = "Y"; PreparedStatementRenderer psr = vocabularyService.prepareExecuteSearch(search, mockSource); assertSqlEquals("/vocabulary/sql/search-expected-2.sql", psr); } @Test public void prepareExecuteSearchWithQuery() throws IOException { String query = "ConceptXYZ"; Source mockSource = mock(Source.class); when(mockSource.getTableQualifier(SourceDaimon.DaimonType.Vocabulary)).thenReturn("omop_v5"); when(mockSource.getSourceDialect()).thenReturn("sql server"); PreparedStatementRenderer psr = vocabularyService.prepareExecuteSearchWithQuery(query, mockSource); assertSqlEquals("/vocabulary/sql/search-expected.sql", psr); assertEquals("%" + query.toLowerCase() + "%", psr.getOrderedParamsList().get(0)); assertEquals("%" + query.toLowerCase() + "%", psr.getOrderedParamsList().get(1)); } @Test public void prepareExecuteSearchWithQueryOptionalConceptId() throws IOException { String query = "12345"; // this looks like a conceptID so add it to the query Source mockSource = mock(Source.class); when(mockSource.getTableQualifier(SourceDaimon.DaimonType.Vocabulary)).thenReturn("omop_v5"); when(mockSource.getSourceDialect()).thenReturn("sql server"); PreparedStatementRenderer psr = vocabularyService.prepareExecuteSearchWithQuery(query, mockSource); assertSqlEquals("/vocabulary/sql/search-expected-3.sql", psr); assertEquals("%" + query.toLowerCase() + "%", psr.getOrderedParamsList().get(0)); assertEquals("%" + query.toLowerCase() + "%", psr.getOrderedParamsList().get(1)); assertEquals(query, psr.getOrderedParamsList().get(2)); } @Test public void prepareGetRelatedConcepts2() throws IOException { RelatedConceptSearch search = new RelatedConceptSearch(); search.vocabularyId = null; // new String[]{"0","1","2"};//null; was search.conceptClassId = new String[]{"4", "5"}; search.conceptId = new long[]{(long) 0}; PreparedStatementRenderer psr = vocabularyService.prepareGetRelatedConcepts(search, getSource()); assertSqlEquals("/vocabulary/sql/getRelatedConceptsFiltered-expected-2.sql", psr); assertEquals(6, psr.getOrderedParamsList().size()); /// the first 4 arguments are the conceptId repeated for (int i = 0; i < 4; i++) { long expectedValue = search.conceptId[0]; assertEquals(expectedValue, psr.getOrderedParamsList().get(i)); } /// the next two arguments are the conceptClassId id for (int i = 0; i < 2; i++) { String expectedValue = "" + (i + 4); assertEquals(expectedValue, psr.getOrderedParamsList().get(i + 4)); } } @Test public void prepareGetRelatedConcepts() throws IOException { RelatedConceptSearch search = new RelatedConceptSearch(); search.vocabularyId = new String[]{"0", "1", "2"}; search.conceptClassId = new String[]{"4", "5", "6"}; search.conceptId = new long[]{0, 1, 2, 3, 4}; PreparedStatementRenderer psr = vocabularyService.prepareGetRelatedConcepts(search, getSource()); assertSqlEquals("/vocabulary/sql/getRelatedConceptsFiltered-expected-1.sql", psr); assertEquals(26, psr.getOrderedParamsList().size()); /// the first 20 arguments are the conceptId repeated for (int i = 0; i < 20; i++) { int expectedIndex = i % 5; long expectedValue = search.conceptId[expectedIndex]; assertEquals(expectedValue, psr.getOrderedParamsList().get(i)); } /// the next three arguments are the vocabulary id for (int i = 20; i < 23; i++) { int expectedIndex = i - 20; String expectedValue = search.vocabularyId[expectedIndex]; assertEquals(expectedValue, psr.getOrderedParamsList().get(i)); } /// the next three arguments are the vocabulary id for (int i = 23; i < 26; i++) { int expectedIndex = i - 23; String expectedValue = search.conceptClassId[expectedIndex]; assertEquals(expectedValue, psr.getOrderedParamsList().get(i)); } } @Test public void prepareGetCommonAncestors() throws IOException { Object[] identifiers = {"1"}; PreparedStatementRenderer psr = vocabularyService.prepareGetCommonAncestors(identifiers, getSource()); assertSqlEquals("/vocabulary/sql/getCommonAncestors-expected.sql", psr); assertEquals(identifiers[0], psr.getOrderedParamsList().get(0)); } @Test public void prepareExecuteMappedLookup() throws IOException { long[] identifiers = new long[]{0L, 1L, 2L, 3L, 4L, 5L, 6L}; PreparedStatementRenderer psr = vocabularyService.prepareExecuteMappedLookup(identifiers, getSource()); assertSqlEquals("/vocabulary/sql/getMappedSourcecodes-expected.sql", psr); for (int i = 0; i < identifiers.length * 3; i++) { assertEquals((long) (i % 7), psr.getOrderedParamsList().get(i)); } } @Test public void prepareExecuteSourcecodeLookup() throws IOException { String[] sourcecodes = new String[]{"a", "b", "c", "d", "e"}; PreparedStatementRenderer psr = vocabularyService.prepareExecuteSourcecodeLookup(sourcecodes, getSource()); assertSqlEquals("/vocabulary/sql/lookupSourcecodes-expected.sql", psr); assertEquals("a", psr.getOrderedParamsList().get(0)); assertEquals("b", psr.getOrderedParamsList().get(1)); assertEquals("c", psr.getOrderedParamsList().get(2)); assertEquals("d", psr.getOrderedParamsList().get(3)); assertEquals("e", psr.getOrderedParamsList().get(4)); } @Test public void prepareExecuteIdentifierLookup() throws IOException { long[] identifiers = {(long) 11, (long) 5, (long) 8}; PreparedStatementRenderer psr = vocabularyService.prepareExecuteIdentifierLookup(identifiers, getSource()); assertSqlEquals("/vocabulary/sql/lookupIdentifiers-expected.sql", psr); assertEquals(11L, psr.getOrderedParamsList().get(0)); assertEquals(5L, psr.getOrderedParamsList().get(1)); assertEquals(8L, psr.getOrderedParamsList().get(2)); } @Test public void prepareGetDescendantOfAncestorConcepts() throws IOException { DescendentOfAncestorSearch search = new DescendentOfAncestorSearch(); search.conceptId = "1"; search.ancestorVocabularyId = "2"; search.ancestorClassId = "3"; search.siblingVocabularyId = "4"; search.siblingClassId = "5"; PreparedStatementRenderer psr = vocabularyService.prepareGetDescendantOfAncestorConcepts(search, getSource()); assertSqlEquals("/vocabulary/sql/getDescendentOfAncestorConcepts-expected.sql", psr); assertEquals(1, psr.getOrderedParamsList().get(0)); assertEquals("2", psr.getOrderedParamsList().get(1)); assertEquals("3", psr.getOrderedParamsList().get(2)); assertEquals("4", psr.getOrderedParamsList().get(3)); assertEquals("5", psr.getOrderedParamsList().get(4)); } @Test public void prepareGetDescendantConceptsByList() throws IOException { String[] conceptList = new String[]{"0", "1", "2", "3", "4"}; PreparedStatementRenderer psr = vocabularyService.prepareGetDescendantConceptsByList(conceptList, getSource()); assertSqlEquals("/vocabulary/sql/getDescendantConceptsMultipleConcepts-expected.sql", psr); /// verify that the params are ordered correctly for (int i = 0; i < psr.getOrderedParamsList().size(); i++) { assertEquals(i, psr.getOrderedParamsList().get(i)); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/EvidenceServiceTest.java
src/test/java/org/ohdsi/webapi/service/EvidenceServiceTest.java
package org.ohdsi.webapi.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.evidence.EvidenceSearch; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.springframework.beans.factory.annotation.Autowired; public class EvidenceServiceTest extends AbstractServiceTest { @Autowired EvidenceService evidenceService; @Before public void before() { if (evidenceService == null) evidenceService = new EvidenceService(); } @Test public void prepareGetDrugHoiEvidence() throws IOException { String drugId = "4444"; String hoiId = "5555"; String key = drugId + "-" + hoiId; PreparedStatementRenderer psr = evidenceService.prepareGetDrugHoiEvidence(key, getSource()); assertSqlEquals("/evidence/sql/getDrugHoiEvidence-expected.sql", psr); assertTrue(psr.getOrderedParamsList().contains(4444)); assertTrue(psr.getOrderedParamsList().contains(5555)); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/TherapyPathResultsServiceTest.java
src/test/java/org/ohdsi/webapi/service/TherapyPathResultsServiceTest.java
package org.ohdsi.webapi.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.springframework.beans.factory.annotation.Autowired; public class TherapyPathResultsServiceTest extends AbstractServiceTest { @Autowired private TherapyPathResultsService therapyPathResultsService; @Before public void before() { if (therapyPathResultsService == null) { therapyPathResultsService = new TherapyPathResultsService(); } } @Test public void prepareGetReports() throws IOException { PreparedStatementRenderer psr = therapyPathResultsService.prepareGetReports(getSource()); assertSqlEquals("/therapypathresults/sql/getTherapyPathReports-expected.sql", psr); } @Test public void prepareGetTherapyVectors() throws IOException { String id = "5555"; PreparedStatementRenderer psr = therapyPathResultsService.prepareGetTherapyVectors(id, getSource()); assertSqlEquals("/therapypathresults/sql/getTherapyPathVectors-expected.sql", psr); assertEquals(5555, psr.getOrderedParamsList().get(0)); assertEquals(1, psr.getOrderedParamsList().size()); } @Test public void prepareGetSummaries() throws IOException { String[] identifiers = new String[]{"1111"}; PreparedStatementRenderer psr = therapyPathResultsService.prepareGetSummaries(identifiers, getSource()); assertSqlEquals("/therapypathresults/sql/getTherapySummaries-expected.sql", psr); assertNotNull(psr.getSetter()); assertEquals(1111, psr.getOrderedParamsList().get(0)); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/CohortResultsServiceTest.java
src/test/java/org/ohdsi/webapi/service/CohortResultsServiceTest.java
package org.ohdsi.webapi.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.regex.Pattern; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.cohortresults.ExposureCohortSearch; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.springframework.beans.factory.annotation.Autowired; public class CohortResultsServiceTest extends AbstractSpringBootServiceTest { @Autowired private CohortResultsService cohortResultsService; @Before public void before() { if (cohortResultsService == null) { cohortResultsService = new CohortResultsService(); } } @Test(expected = Exception.class) public void getCohortSpecificResultsRefreshIsTrue() { cohortResultsService.getCohortSpecificResults(-1, null, null, null, true); } @Test(expected = Exception.class) public void getCohortSpecificResultsRefreshIsFalse() { cohortResultsService.getCohortSpecificResults(-1, null, null, null, false); } @Test(expected = Exception.class) public void getDashboardRefreshIsTrue() { cohortResultsService.getDashboard(-1, null, null, true, null, true); } @Test(expected = Exception.class) public void getDashboardRefreshIsFalse() { cohortResultsService.getDashboard(-1, null, null, true, null, false); } @Test public void prepareGetRawDistinctPersonCount() throws IOException { String id = "1230"; PreparedStatementRenderer psr = cohortResultsService.prepareGetRawDistinctPersonCount(id, getSource()); assertSqlEquals("/cohortresults/sql/raw/getTotalDistinctPeople-expected.sql", psr); assertEquals(Integer.parseInt(id), psr.getOrderedParamsList().get(0)); } @Test public void prepareGetCompletedAnalyses() throws IOException { String id = "1230"; PreparedStatementRenderer psr = cohortResultsService.prepareGetCompletedAnalysis(id, getSource().getSourceId()); assertSqlEquals("/cohortresults/sql/raw/getCompletedAnalyses-expected.sql", psr); assertEquals(2, psr.getOrderedParamsList().size()); } @Test public void prepareGetExposureOutcomeCohortPredictors() throws IOException { ExposureCohortSearch search = new ExposureCohortSearch(); search.minCellCount = 5; search.exposureCohortList = new String[]{"1"}; search.outcomeCohortList = new String[]{"2"}; PreparedStatementRenderer psr = cohortResultsService.prepareGetExposureOutcomeCohortPredictors(search, getSource()); assertSqlEquals("/cohortresults/sql/cohortSpecific/getExposureOutcomePredictors-expected.sql", psr); } @Test public void prepareGetTimeToEventDrilldown() throws IOException { ExposureCohortSearch search = new ExposureCohortSearch(); search.exposureCohortList = new String[]{"1"}; search.outcomeCohortList = new String[]{"2"}; PreparedStatementRenderer psr = cohortResultsService.prepareGetTimeToEventDrilldown(search, getSource()); assertSqlEquals("/cohortresults/sql/cohortSpecific/getTimeToEventDrilldown-expected.sql", psr); for (Object param : psr.getOrderedParamsList()) { assertTrue("1".equals(param) || "2".equals(param)); } } @Test public void prepareGetExposureOutcomeCohortRates() throws IOException { ExposureCohortSearch search = new ExposureCohortSearch(); search.exposureCohortList = new String[]{"1"}; search.outcomeCohortList = new String[]{"1"}; PreparedStatementRenderer psr = cohortResultsService.prepareGetExposureOutcomeCohortRates(search, getSource()); assertSqlEquals("/cohortresults/sql/cohortSpecific/getExposureOutcomeCohortRates-expected.sql", psr); for (Object object : psr.getOrderedParamsList()) { assertTrue("1".equals(object)); } } @Test public void prepareGetCohortMembers() throws IOException { int id = 111998; String gender = "M"; String age = "15"; String conditions = "2,3,4"; String drugs = "45,61"; int rows = 5; PreparedStatementRenderer psr = cohortResultsService.prepareGetCohortMembers(id, gender, age, conditions, drugs, rows, getSource()); assertSqlEquals("/cohortresults/sql/raw/getCohortBreakdownPeople-expected.sql", psr); assertEquals(id, psr.getOrderedParamsList().get(0)); assertEquals(gender, psr.getOrderedParamsList().get(1)); assertEquals(age, psr.getOrderedParamsList().get(2)); assertEquals(2, psr.getOrderedParamsList().get(3)); assertEquals(3, psr.getOrderedParamsList().get(4)); assertEquals(4, psr.getOrderedParamsList().get(5)); assertEquals(45, psr.getOrderedParamsList().get(6)); assertEquals(61, psr.getOrderedParamsList().get(7)); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/SqlRenderServiceTest.java
src/test/java/org/ohdsi/webapi/service/SqlRenderServiceTest.java
package org.ohdsi.webapi.service; import static org.junit.Assert.*; import static org.mockito.Mockito.verify; import static org.ohdsi.webapi.Constants.SqlSchemaPlaceholders.TEMP_DATABASE_SCHEMA_PLACEHOLDER; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.sqlrender.SourceStatement; import org.ohdsi.webapi.sqlrender.TranslatedStatement; @RunWith(MockitoJUnitRunner.class) public class SqlRenderServiceTest { public static final String TEST_SQL = "select cast(field as int) from table; "; @Spy private SqlRenderService sqlRenderService; @Captor private ArgumentCaptor<SourceStatement> sourceStatementCaptor; @Test public void translateSQLFromSourceStatement() { SourceStatement statement = createSourceStatement(TEST_SQL, "oracle"); statement.setOracleTempSchema(null); sqlRenderService.translateSQLFromSourceStatement(statement); verify(sqlRenderService).translatedStatement(sourceStatementCaptor.capture()); assertEquals(TEMP_DATABASE_SCHEMA_PLACEHOLDER, sourceStatementCaptor.getValue().getOracleTempSchema()); } @Test public void translateSQL_sourceStatementIsNull() { assertEquals(new TranslatedStatement(), SqlRenderService.translateSQL(null)); } @Test public void translateSQL() { SourceStatement statement = createSourceStatement(TEST_SQL, "oracle"); TranslatedStatement translatedStatement = SqlRenderService.translateSQL(statement); assertNotNull(translatedStatement.getTargetSQL()); assertNotEquals(TEST_SQL, translatedStatement.getTargetSQL()); } @Test public void translateSQL_defaultDialect() { SourceStatement statement = createSourceStatement(TEST_SQL, Constants.DEFAULT_DIALECT); TranslatedStatement translatedStatement = SqlRenderService.translateSQL(statement); assertEquals(TEST_SQL, translatedStatement.getTargetSQL()); } private SourceStatement createSourceStatement(String testExpression, String dialect) { SourceStatement statement = new SourceStatement(); statement.setTargetDialect(dialect) ; statement.setOracleTempSchema("schema"); statement.setSql(testExpression); statement.getParameters().putAll(Collections.emptyMap()); return statement; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/AbstractSpringBootServiceTest.java
src/test/java/org/ohdsi/webapi/service/AbstractSpringBootServiceTest.java
package org.ohdsi.webapi.service; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) @TestPropertySource(locations = "/application-test.properties") public abstract class AbstractSpringBootServiceTest extends AbstractServiceTest { }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/AbstractServiceTest.java
src/test/java/org/ohdsi/webapi/service/AbstractServiceTest.java
package org.ohdsi.webapi.service; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import org.junit.Before; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.springframework.util.StringUtils; public abstract class AbstractServiceTest { private Source source; @Before public void setupMockedSource() { source = mock(Source.class); when(getSource().getSourceDialect()).thenReturn("sql server"); when(getSource().getTableQualifier(SourceDaimon.DaimonType.Results)).thenReturn("result_schema"); when(getSource().getTableQualifier(SourceDaimon.DaimonType.Vocabulary)).thenReturn("vocab_schema"); when(getSource().getTableQualifier(SourceDaimon.DaimonType.CDM)).thenReturn("cdm_schema"); when(getSource().getTableQualifier(SourceDaimon.DaimonType.CEM)).thenReturn("evidence_schema"); } public static void assertSqlEquals(String expectedPath, PreparedStatementRenderer psr) throws IOException { String expectedSql = StringUtils.trimAllWhitespace(ResourceHelper.GetResourceAsString(expectedPath)).toLowerCase(); assertEquals(expectedSql, StringUtils.trimAllWhitespace(psr.getSql()).toLowerCase()); } public Source getSource() { return source; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/CohortDefinitionServiceTest.java
src/test/java/org/ohdsi/webapi/service/CohortDefinitionServiceTest.java
package org.ohdsi.webapi.service; import java.util.Arrays; import java.util.List; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.management.CacheStatisticsMXBean; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.ThreadContext; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO; import org.ohdsi.webapi.cohortdefinition.dto.CohortMetadataDTO; import org.springframework.beans.factory.annotation.Autowired; import org.ohdsi.webapi.util.CacheHelper; public class CohortDefinitionServiceTest extends AbstractDatabaseTest { @Autowired private CohortDefinitionService cdService; @Autowired protected CohortDefinitionRepository cdRepository; @Autowired(required = false) private CacheManager cacheManager ; @Autowired private DefaultWebSecurityManager securityManager; // in JUnit 4 it's impossible to mark methods inside interface with annotations, it was implemented in JUnit 5. After upgrade it's needed // to mark interface methods with @Test, @Before, @After and to remove them from this class @After public void tearDownDB() { cdRepository.deleteAll(); } @Before public void setup() { // Set the SecurityManager for the current thread SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(); principalCollection.addAll(Arrays.asList("permsTest"), "testRealm"); Subject subject = new Subject.Builder(securityManager) .authenticated(true) .principals(principalCollection) .buildSubject(); ThreadContext.bind(subject); } private CohortDTO createEntity(String name) { CohortDTO dto = new CohortDTO(); dto.setName(name); return cdService.createCohortDefinition(dto); } @Test public void cohortDefinitionListCacheTest() throws Exception { if (cacheManager == null) return; // cache is disabled, so nothing to test CacheStatisticsMXBean cacheStatistics = CacheHelper.getCacheStats(cacheManager , CohortDefinitionService.CachingSetup.COHORT_DEFINITION_LIST_CACHE); Cache cohortListCache = cacheManager.getCache(CohortDefinitionService.CachingSetup.COHORT_DEFINITION_LIST_CACHE); // reset the cache and statistics for this test cacheStatistics.clear(); cohortListCache.clear(); int cacheHits = 0; int cacheMisses = 0; List<CohortMetadataDTO> cohortDefList; cohortDefList = cdService.getCohortDefinitionList(); cacheMisses++; assertThat(cacheStatistics.getCacheMisses()).isEqualTo(cacheMisses); assertThat(cacheStatistics.getCacheHits()).isEqualTo(cacheHits); cohortDefList = cdService.getCohortDefinitionList(); cacheHits++; assertThat(cacheStatistics.getCacheMisses()).isEqualTo(cacheMisses); assertThat(cacheStatistics.getCacheHits()).isEqualTo(cacheHits); } @Test public void cohortDefinitionListEvictTest() throws Exception { if (cacheManager == null) return; // cache is disabled, so nothing to test CacheStatisticsMXBean cacheStatistics = CacheHelper.getCacheStats(cacheManager , CohortDefinitionService.CachingSetup.COHORT_DEFINITION_LIST_CACHE); Cache cohortListCache = cacheManager.getCache(CohortDefinitionService.CachingSetup.COHORT_DEFINITION_LIST_CACHE); // reset the cache and statistics for this test cacheStatistics.clear(); cohortListCache.clear(); int cacheHits = 0; int cacheMisses = 0; List<CohortMetadataDTO> cohortDefList; cohortDefList = cdService.getCohortDefinitionList(); cacheMisses++; assertThat(cacheStatistics.getCacheMisses()).isEqualTo(cacheMisses); assertThat(cacheStatistics.getCacheHits()).isEqualTo(cacheHits); CohortDTO c = createEntity("Cohort 1"); cohortDefList = cdService.getCohortDefinitionList(); cacheMisses++; assertThat(cacheStatistics.getCacheMisses()).isEqualTo(cacheMisses); assertThat(cacheStatistics.getCacheHits()).isEqualTo(cacheHits); c = cdService.saveCohortDefinition(c.getId(), c); cohortDefList = cdService.getCohortDefinitionList(); cacheMisses++; assertThat(cacheStatistics.getCacheMisses()).isEqualTo(cacheMisses); assertThat(cacheStatistics.getCacheHits()).isEqualTo(cacheHits); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/PersonServiceTest.java
src/test/java/org/ohdsi/webapi/service/PersonServiceTest.java
package org.ohdsi.webapi.service; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.springframework.beans.factory.annotation.Autowired; public class PersonServiceTest extends AbstractServiceTest { @Autowired private PersonService personService; @Before public void before() { if (personService == null) { personService = new PersonService(); } } @Test public void prepareGetPersonProfile() throws IOException { String personId = "5555"; PreparedStatementRenderer psr = personService.prepareGetPersonProfile(personId, getSource()); String actualSql = psr.getSql(); Assert.assertNotNull(actualSql); Assert.assertNotNull(psr.getSetter()); assertSqlEquals("/person/sql/getRecords-expected.sql", psr); //// count the number of question marks in the sql, make sure it matches the orderedParamsList size int qmarkCount = 0; int startIndex = 0; while ((startIndex = actualSql.indexOf("?", startIndex)) != -1) { qmarkCount++; startIndex++; } Assert.assertEquals(qmarkCount, psr.getOrderedParamsList().size()); /// make sure that all of the parameters are equivalent to personId value for (Object param : psr.getOrderedParamsList()) { Assert.assertEquals(param, 5555L); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/CDMResultsServiceTest.java
src/test/java/org/ohdsi/webapi/service/CDMResultsServiceTest.java
package org.ohdsi.webapi.service; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.springframework.beans.factory.annotation.Autowired; public class CDMResultsServiceTest extends AbstractServiceTest { @Autowired private CDMResultsService cdmResultsService; @Before public void before() { if (cdmResultsService == null) cdmResultsService = new CDMResultsService(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/service/annotations/SearchDataTransformerTest.java
src/test/java/org/ohdsi/webapi/service/annotations/SearchDataTransformerTest.java
package org.ohdsi.webapi.service.annotations; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyString; public class SearchDataTransformerTest { private SearchDataTransformer sut; @Before public void setUp() { sut = new SearchDataTransformer(); } @Test public void shouldReturnEmptyStringWhenInputIsEmpty() { JSONObject emptyJson = new JSONObject(); String transformed = sut.convertJsonToReadableFormat(emptyJson.toString()); assertThat(transformed, isEmptyString()); } @Test public void shouldHandleSearchText() { String input = "{\"filterData\":{\"searchText\":\"testSearch\"}}"; String result = sut.convertJsonToReadableFormat(input); assertThat(result, is("Search, \"testSearch\"")); } @Test public void shouldHandleFilterSource() { String input = "{\"filterSource\":\"Search\"}"; String result = sut.convertJsonToReadableFormat(input); assertThat(result, is("Search")); } @Test public void shouldHandleFilterColumns() { String input = "{\"filterData\":{\"filterColumns\":[{\"title\":\"Domain\",\"key\":\"Drug\"}]} }"; String result = sut.convertJsonToReadableFormat(input); assertThat(result, is("Search, \"\", Filtered By: \"Domain: \"Drug\"\"")); } @Test public void shouldCombineFilterDataAndFilterSource() { String input = "{\"filterData\":{\"searchText\":\"testSearch\",\"filterColumns\":[{\"title\":\"Domain\",\"key\":\"Drug\"}]},\"filterSource\":\"Search\"}"; String result = sut.convertJsonToReadableFormat(input); String expected = "Search, \"testSearch\", Filtered By: \"Domain: \"Drug\"\""; assertThat(result, is(expected)); } @Test public void shouldHandleMultipleFilterColumns() { String input = "{\"filterData\":{\"filterColumns\":[{\"title\":\"Domain\",\"key\":\"Drug\"},{\"title\":\"Class\",\"key\":\"Medication\"}]}}"; String result = sut.convertJsonToReadableFormat(input); String expected = "Search, \"\", Filtered By: \"Domain: \"Drug\"" + ", Class: \"Medication\"\""; assertThat(result, is(expected)); } @Test public void shouldHandleNullValuesGracefully() { String input = "{\"filterData\":{\"filterColumns\":[{\"title\":null,\"key\":null}], \"searchText\":null}, \"filterSource\":null}"; String result = sut.convertJsonToReadableFormat(input); assertThat(result, is("Search, \"\", Filtered By: \": \"\"\"")); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/shiny/CohortPathwaysShinyPackagingServiceTest.java
src/test/java/org/ohdsi/webapi/shiny/CohortPathwaysShinyPackagingServiceTest.java
package org.ohdsi.webapi.shiny; import com.odysseusinc.arachne.commons.api.v1.dto.CommonAnalysisType; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.ohdsi.webapi.pathway.PathwayService; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisGenerationEntity; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.dto.PathwayPopulationResultsDTO; import org.ohdsi.webapi.pathway.dto.internal.PathwayAnalysisResult; import java.util.Collections; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class CohortPathwaysShinyPackagingServiceTest { private static final int GENERATION_ID = 1; private static final String SOURCE_KEY = "SynPuf110k"; @Mock private PathwayService pathwayService; @Spy private ManifestUtils manifestUtils; @Spy private FileWriter fileWriter; @InjectMocks private CohortPathwaysShinyPackagingService sut; @Test public void shouldGetBrief() { when(pathwayService.getByGenerationId(eq(GENERATION_ID))).thenReturn(createPathwayAnalysisDTO()); when(pathwayService.getResultingPathways(eq((long) GENERATION_ID))).thenReturn(createPathwayAnalysisResult()); ApplicationBrief brief = sut.getBrief(GENERATION_ID, SOURCE_KEY); assertEquals(brief.getName(), "txp_" + GENERATION_ID + "_" + SOURCE_KEY); assertEquals(brief.getTitle(), "Pathway_8_gv1x_SynPuf110k"); assertEquals(brief.getDescription(), "desc"); } @Test public void shouldPopulateAppData() { when(pathwayService.findDesignByGenerationId(eq((long) GENERATION_ID))).thenReturn("design json"); when(pathwayService.getGenerationResults(eq((long) GENERATION_ID))).thenReturn(createPathwayGenerationResults()); PathwayAnalysisDTO pathwayAnalysisDTO = Mockito.mock(PathwayAnalysisDTO.class); PathwayAnalysisGenerationEntity generationEntity = Mockito.mock(PathwayAnalysisGenerationEntity.class); when(pathwayService.getByGenerationId(eq(GENERATION_ID))).thenReturn(pathwayAnalysisDTO); when(pathwayService.getGeneration(eq((long) GENERATION_ID))).thenReturn(generationEntity); CommonShinyPackagingService.ShinyAppDataConsumers dataConsumers = Mockito.mock(CommonShinyPackagingService.ShinyAppDataConsumers.class, Answers.RETURNS_DEEP_STUBS.get()); sut.populateAppData(GENERATION_ID, SOURCE_KEY, dataConsumers); verify(dataConsumers.getTextFiles(), times(1)).accept(eq("design.json"), anyString()); verify(dataConsumers.getJsonObjects(), times(1)).accept(eq("chartData.json"), any(PathwayPopulationResultsDTO.class)); } private PathwayPopulationResultsDTO createPathwayGenerationResults() { return new PathwayPopulationResultsDTO(Collections.emptyList(), Collections.emptyList()); } @Test public void shouldReturnIncidenceType() { assertEquals(sut.getType(), CommonAnalysisType.COHORT_PATHWAY); } private PathwayAnalysisResult createPathwayAnalysisResult() { return new PathwayAnalysisResult(); } private PathwayAnalysisDTO createPathwayAnalysisDTO() { PathwayAnalysisDTO pathwayAnalysisDTO = new PathwayAnalysisDTO(); pathwayAnalysisDTO.setId(8); pathwayAnalysisDTO.setName("pathwayAnalysis"); pathwayAnalysisDTO.setDescription("desc"); return pathwayAnalysisDTO; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/shiny/IncidenceRatesShinyPackagingServiceTest.java
src/test/java/org/ohdsi/webapi/shiny/IncidenceRatesShinyPackagingServiceTest.java
package org.ohdsi.webapi.shiny; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.odysseusinc.arachne.commons.api.v1.dto.CommonAnalysisType; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO; import org.ohdsi.webapi.ircalc.AnalysisReport; import org.ohdsi.webapi.ircalc.IncidenceRateAnalysis; import org.ohdsi.webapi.ircalc.IncidenceRateAnalysisDetails; import org.ohdsi.webapi.ircalc.IncidenceRateAnalysisExportExpression; import org.ohdsi.webapi.ircalc.IncidenceRateAnalysisRepository; import org.ohdsi.webapi.service.IRAnalysisResource; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceRepository; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class IncidenceRatesShinyPackagingServiceTest { @Mock private IncidenceRateAnalysisRepository repository; @Spy private ManifestUtils manifestUtils; @Spy private FileWriter fileWriter; @Mock private IRAnalysisResource irAnalysisResource; @Mock private SourceRepository sourceRepository; @Spy private ObjectMapper objectMapper; @InjectMocks private IncidenceRatesShinyPackagingService sut; private final Integer analysisId = 1; private final String sourceKey = "sourceKey"; @Test public void shouldGetBrief() { IncidenceRateAnalysis incidenceRateAnalysis = createIncidenceRateAnalysis(); when(repository.findOne(analysisId)).thenReturn(incidenceRateAnalysis); Source source = new Source(); source.setSourceId(3); when(sourceRepository.findBySourceKey("sourceKey")).thenReturn(source); ApplicationBrief brief = sut.getBrief(analysisId, sourceKey); assertEquals(brief.getName(), "ir_" + analysisId + "_" + sourceKey); assertEquals(brief.getTitle(), "Incidence_1_gv1x3_sourceKey"); assertEquals(brief.getDescription(), incidenceRateAnalysis.getDescription()); } @Test public void shouldPopulateAppDataWithValidData() throws JsonProcessingException { Integer generationId = 1; String sourceKey = "source"; Source source = new Source(); source.setSourceId(3); when(sourceRepository.findBySourceKey("source")).thenReturn(source); IncidenceRateAnalysis analysis = Mockito.mock(IncidenceRateAnalysis.class, Answers.RETURNS_DEEP_STUBS.get()); when(analysis.getDetails().getExpression()).thenReturn("{}"); when(repository.findOne(generationId)).thenReturn(analysis); CohortDTO targetCohort = new CohortDTO(); targetCohort.setId(101); targetCohort.setName("Target Cohort"); CohortDTO outcomeCohort = new CohortDTO(); outcomeCohort.setId(201); outcomeCohort.setName("Outcome Cohort"); IncidenceRateAnalysisExportExpression expression = new IncidenceRateAnalysisExportExpression(); expression.outcomeCohorts.add(outcomeCohort); expression.targetCohorts.add(targetCohort); when(objectMapper.readValue("{}", IncidenceRateAnalysisExportExpression.class)).thenReturn(expression); AnalysisReport analysisReport = new AnalysisReport(); analysisReport.summary = new AnalysisReport.Summary(); when(irAnalysisResource.getAnalysisReport(1, "source", 101, 201)).thenReturn(analysisReport); CommonShinyPackagingService.ShinyAppDataConsumers dataConsumers = mock(CommonShinyPackagingService.ShinyAppDataConsumers.class, Answers.RETURNS_DEEP_STUBS.get()); sut.populateAppData(generationId, sourceKey, dataConsumers); verify(dataConsumers.getAppProperties(), times(11)).accept(anyString(), anyString()); verify(dataConsumers.getTextFiles(), times(1)).accept(anyString(), anyString()); verify(dataConsumers.getJsonObjects(), times(1)).accept(anyString(), any()); } @Test public void shouldReturnIncidenceType() { assertEquals(sut.getType(), CommonAnalysisType.INCIDENCE); } private IncidenceRateAnalysis createIncidenceRateAnalysis() { IncidenceRateAnalysis incidenceRateAnalysis = new IncidenceRateAnalysis(); IncidenceRateAnalysisDetails incidenceRateAnalysisDetails = new IncidenceRateAnalysisDetails(incidenceRateAnalysis); incidenceRateAnalysisDetails.setExpression("{\"ConceptSets\":[],\"targetIds\":[11,7],\"outcomeIds\":[12,6],\"timeAtRisk\":{\"start\":{\"DateField\":\"StartDate\",\"Offset\":0},\"end\":{\"DateField\":\"EndDate\",\"Offset\":0}},\"studyWindow\":null,\"strata\":[{\"name\":\"Male\",\"description\":null,\"expression\":{\"Type\":\"ALL\",\"Count\":null,\"CriteriaList\":[],\"DemographicCriteriaList\":[{\"Age\":null,\"Gender\":[{\"CONCEPT_ID\":8507,\"CONCEPT_NAME\":\"MALE\",\"STANDARD_CONCEPT\":null,\"STANDARD_CONCEPT_CAPTION\":\"Unknown\",\"INVALID_REASON\":null,\"INVALID_REASON_CAPTION\":\"Unknown\",\"CONCEPT_CODE\":\"M\",\"DOMAIN_ID\":\"Gender\",\"VOCABULARY_ID\":\"Gender\",\"CONCEPT_CLASS_ID\":null}],\"Race\":null,\"Ethnicity\":null,\"OccurrenceStartDate\":null,\"OccurrenceEndDate\":null}],\"Groups\":[]}},{\"name\":\"Female\",\"description\":null,\"expression\":{\"Type\":\"ALL\",\"Count\":null,\"CriteriaList\":[],\"DemographicCriteriaList\":[{\"Age\":null,\"Gender\":[{\"CONCEPT_ID\":8532,\"CONCEPT_NAME\":\"FEMALE\",\"STANDARD_CONCEPT\":null,\"STANDARD_CONCEPT_CAPTION\":\"Unknown\",\"INVALID_REASON\":null,\"INVALID_REASON_CAPTION\":\"Unknown\",\"CONCEPT_CODE\":\"F\",\"DOMAIN_ID\":\"Gender\",\"VOCABULARY_ID\":\"Gender\",\"CONCEPT_CLASS_ID\":null}],\"Race\":null,\"Ethnicity\":null,\"OccurrenceStartDate\":null,\"OccurrenceEndDate\":null}],\"Groups\":[]}}],\"targetCohorts\":[{\"id\":11,\"name\":\"All population-IR\",\"hasWriteAccess\":false,\"hasReadAccess\":false,\"expression\":{\"cdmVersionRange\":\">=5.0.0\",\"PrimaryCriteria\":{\"CriteriaList\":[{\"ConditionOccurrence\":{\"ConditionTypeExclude\":false}},{\"DrugExposure\":{\"DrugTypeExclude\":false}}],\"ObservationWindow\":{\"PriorDays\":0,\"PostDays\":0},\"PrimaryCriteriaLimit\":{\"Type\":\"First\"}},\"ConceptSets\":[],\"QualifiedLimit\":{\"Type\":\"First\"},\"ExpressionLimit\":{\"Type\":\"First\"},\"InclusionRules\":[],\"CensoringCriteria\":[],\"CollapseSettings\":{\"CollapseType\":\"ERA\",\"EraPad\":0},\"CensorWindow\":{}}},{\"id\":7,\"name\":\"Test Cohort 4\",\"hasWriteAccess\":false,\"hasReadAccess\":false,\"expressionType\":\"SIMPLE_EXPRESSION\",\"expression\":{\"cdmVersionRange\":\">=5.0.0\",\"PrimaryCriteria\":{\"CriteriaList\":[{\"DrugExposure\":{\"CodesetId\":0,\"DrugTypeExclude\":false}}],\"ObservationWindow\":{\"PriorDays\":30,\"PostDays\":0},\"PrimaryCriteriaLimit\":{\"Type\":\"First\"}},\"ConceptSets\":[{\"id\":0,\"name\":\"celecoxib\",\"expression\":{\"items\":[{\"concept\":{\"CONCEPT_ID\":1118084,\"CONCEPT_NAME\":\"celecoxib\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"140587\",\"DOMAIN_ID\":\"Drug\",\"VOCABULARY_ID\":\"RxNorm\",\"CONCEPT_CLASS_ID\":\"Ingredient\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":true}]}},{\"id\":1,\"name\":\"Major gastrointestinal (GI) bleeding\",\"expression\":{\"items\":[{\"concept\":{\"CONCEPT_ID\":4280942,\"CONCEPT_NAME\":\"Acute gastrojejunal ulcer with perforation\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"66636001\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false},{\"concept\":{\"CONCEPT_ID\":28779,\"CONCEPT_NAME\":\"Bleeding esophageal varices\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"17709002\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false},{\"concept\":{\"CONCEPT_ID\":198798,\"CONCEPT_NAME\":\"Dieulafoy's vascular malformation\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"109558001\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false},{\"concept\":{\"CONCEPT_ID\":4112183,\"CONCEPT_NAME\":\"Esophageal varices with bleeding, associated with another disorder\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"195475003\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false},{\"concept\":{\"CONCEPT_ID\":194382,\"CONCEPT_NAME\":\"External hemorrhoids\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"23913003\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":false,\"includeMapped\":false},{\"concept\":{\"CONCEPT_ID\":192671,\"CONCEPT_NAME\":\"Gastrointestinal hemorrhage\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"74474003\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false},{\"concept\":{\"CONCEPT_ID\":196436,\"CONCEPT_NAME\":\"Internal hemorrhoids\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"90458007\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":false,\"includeMapped\":false},{\"concept\":{\"CONCEPT_ID\":4338225,\"CONCEPT_NAME\":\"Peptic ulcer with perforation\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"88169003\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false},{\"concept\":{\"CONCEPT_ID\":194158,\"CONCEPT_NAME\":\"Perinatal gastrointestinal hemorrhage\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"48729005\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false}]}}],\"QualifiedLimit\":{\"Type\":\"All\"},\"ExpressionLimit\":{\"Type\":\"First\"},\"InclusionRules\":[{\"name\":\"No prior GI\",\"expression\":{\"Type\":\"ALL\",\"CriteriaList\":[{\"Criteria\":{\"ConditionOccurrence\":{\"CodesetId\":1}},\"StartWindow\":{\"Start\":{\"Coeff\":-1},\"End\":{\"Days\":0,\"Coeff\":1},\"UseIndexEnd\":false,\"UseEventEnd\":false},\"RestrictVisit\":false,\"IgnoreObservationPeriod\":false,\"Occurrence\":{\"Type\":1,\"Count\":0,\"IsDistinct\":false}}],\"DemographicCriteriaList\":[],\"Groups\":[]}}],\"CensoringCriteria\":[],\"CollapseSettings\":{\"CollapseType\":\"ERA\",\"EraPad\":0},\"CensorWindow\":{\"StartDate\":\"2010-04-01\",\"EndDate\":\"2010-12-01\"}}}],\"outcomeCohorts\":[{\"id\":12,\"name\":\"Diabetes-IR\",\"hasWriteAccess\":false,\"hasReadAccess\":false,\"expression\":{\"cdmVersionRange\":\">=5.0.0\",\"PrimaryCriteria\":{\"CriteriaList\":[{\"ConditionOccurrence\":{\"CodesetId\":0,\"First\":true,\"ConditionTypeExclude\":false}}],\"ObservationWindow\":{\"PriorDays\":365,\"PostDays\":0},\"PrimaryCriteriaLimit\":{\"Type\":\"First\"}},\"ConceptSets\":[{\"id\":0,\"name\":\"Diabetes-IR\",\"expression\":{\"items\":[{\"concept\":{\"CONCEPT_ID\":201826,\"CONCEPT_NAME\":\"Type 2 diabetes mellitus\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"44054006\",\"DOMAIN_ID\":\"Condition\",\"VOCABULARY_ID\":\"SNOMED\",\"CONCEPT_CLASS_ID\":\"Clinical Finding\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false}]}}],\"QualifiedLimit\":{\"Type\":\"First\"},\"ExpressionLimit\":{\"Type\":\"First\"},\"InclusionRules\":[{\"name\":\"Age over 18\",\"expression\":{\"Type\":\"ALL\",\"CriteriaList\":[],\"DemographicCriteriaList\":[{\"Age\":{\"Value\":18,\"Op\":\"gte\"}}],\"Groups\":[]}}],\"CensoringCriteria\":[],\"CollapseSettings\":{\"CollapseType\":\"ERA\",\"EraPad\":0},\"CensorWindow\":{}}},{\"id\":6,\"name\":\"TEST COHORT 2\",\"hasWriteAccess\":false,\"hasReadAccess\":false,\"expressionType\":\"SIMPLE_EXPRESSION\",\"expression\":{\"cdmVersionRange\":\">=5.0.0\",\"PrimaryCriteria\":{\"CriteriaList\":[{\"DrugEra\":{\"CodesetId\":0}}],\"ObservationWindow\":{\"PriorDays\":0,\"PostDays\":0},\"PrimaryCriteriaLimit\":{\"Type\":\"All\"}},\"ConceptSets\":[{\"id\":0,\"name\":\"Simvastatin1\",\"expression\":{\"items\":[{\"concept\":{\"CONCEPT_ID\":1539403,\"CONCEPT_NAME\":\"Simvastatin\",\"STANDARD_CONCEPT\":\"S\",\"STANDARD_CONCEPT_CAPTION\":\"Standard\",\"INVALID_REASON\":\"V\",\"INVALID_REASON_CAPTION\":\"Valid\",\"CONCEPT_CODE\":\"36567\",\"DOMAIN_ID\":\"Drug\",\"VOCABULARY_ID\":\"RxNorm\",\"CONCEPT_CLASS_ID\":\"Ingredient\"},\"isExcluded\":false,\"includeDescendants\":true,\"includeMapped\":false}]}}],\"QualifiedLimit\":{\"Type\":\"First\"},\"ExpressionLimit\":{\"Type\":\"All\"},\"InclusionRules\":[],\"EndStrategy\":{\"DateOffset\":{\"DateField\":\"EndDate\",\"Offset\":0}},\"CensoringCriteria\":[],\"CollapseSettings\":{\"CollapseType\":\"ERA\",\"EraPad\":0},\"CensorWindow\":{}}}]}"); incidenceRateAnalysis.setId(analysisId); incidenceRateAnalysis.setName("Analysis Name"); incidenceRateAnalysis.setDescription("Analysis Description"); incidenceRateAnalysis.setDetails(incidenceRateAnalysisDetails); return incidenceRateAnalysis; } private AnalysisReport createAnalysisReport(int targetId, int outcomeId) { AnalysisReport analysisReport = new AnalysisReport(); analysisReport.summary = new AnalysisReport.Summary(); analysisReport.summary.targetId = targetId; analysisReport.summary.outcomeId = outcomeId; return analysisReport; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/generationcache/GenerationCacheTest.java
src/test/java/org/ohdsi/webapi/generationcache/GenerationCacheTest.java
package org.ohdsi.webapi.generationcache; import com.odysseusinc.arachne.commons.types.DBMSType; import com.odysseusinc.arachne.execution_engine_common.api.v1.dto.KerberosAuthMechanism; import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ohdsi.analysis.Utils; import org.ohdsi.circe.cohortdefinition.CohortExpression; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.SqlRender; import org.ohdsi.sql.SqlSplit; import org.ohdsi.sql.SqlTranslate; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionDetails; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.cohortdefinition.CohortGenerationRequestBuilder; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.source.SourceRepository; import org.ohdsi.webapi.util.SessionUtils; import org.ohdsi.webapi.util.SourceUtils; import org.springframework.beans.factory.annotation.Autowired; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static org.ohdsi.webapi.Constants.Params.DESIGN_HASH; import static org.ohdsi.webapi.Constants.Params.RESULTS_DATABASE_SCHEMA; import org.springframework.beans.factory.annotation.Value; public class GenerationCacheTest extends AbstractDatabaseTest { private static final String CDM_SQL = ResourceHelper.GetResourceAsString("/cdm-postgresql-ddl.sql"); private static final String COHORT_JSON = ResourceHelper.GetResourceAsString("/generationcache/cohort/cohortIbuprofenOlder50.json"); private static final String INSERT_COHORT_RESULTS_SQL = ResourceHelper.GetResourceAsString("/generationcache/cohort/insertCohortResults.sql"); private static final String COHORT_COUNTS_SQL = ResourceHelper.GetResourceAsString("/generationcache/cohort/queryCohortCounts.sql"); private static final String EUNOMIA_CSV_ZIP = "/eunomia.csv.zip"; private static final String CDM_SCHEMA_NAME = "cdm"; private static final String RESULT_SCHEMA_NAME = "results"; private static final String SOURCE_KEY = "Embedded_PG"; private static boolean isSetup = false; private int cohortId; // will be set to the test cohort for each test excution @Autowired private GenerationCacheService generationCacheService; @Autowired private GenerationCacheRepository generationCacheRepository; @Autowired private GenerationCacheHelper generationCacheHelper; @Autowired private SourceRepository sourceRepository; @Autowired private CohortDefinitionRepository cohortDefinitionRepository; @Value("${datasource.ohdsi.schema}") private String ohdsiSchema; private static final Collection<String> COHORT_DDL_FILE_PATHS = Arrays.asList( // cohort generation results "/ddl/results/cohort.sql", "/ddl/results/cohort_censor_stats.sql", "/ddl/results/cohort_inclusion.sql", "/ddl/results/cohort_inclusion_result.sql", "/ddl/results/cohort_inclusion_stats.sql", "/ddl/results/cohort_summary_stats.sql", // cohort generation cache "/ddl/results/cohort_cache.sql", "/ddl/results/cohort_censor_stats_cache.sql", "/ddl/results/cohort_inclusion_result_cache.sql", "/ddl/results/cohort_inclusion_stats_cache.sql", "/ddl/results/cohort_summary_stats_cache.sql" ); private CohortGenerationRequestBuilder cohortGenerationRequestBuilder; @Before public void setUp() throws SQLException { if (!isSetup) { // one-time setup per class here truncateTable(String.format("%s.%s", ohdsiSchema, "source")); resetSequence(String.format("%s.%s", ohdsiSchema,"source_sequence")); sourceRepository.saveAndFlush(getCdmSource()); isSetup = true; } // reset cohort tables truncateTable(String.format("%s.%s", ohdsiSchema, "cohort_definition_details")); truncateTable(String.format("%s.%s", ohdsiSchema, "cohort_definition")); resetSequence(String.format("%s.%s", ohdsiSchema, "cohort_definition_sequence")); cohortId = cohortDefinitionRepository.save(getCohortDefinition()).getId(); cohortGenerationRequestBuilder = getCohortGenerationRequestBuilder(sourceRepository.findBySourceKey(SOURCE_KEY)); generationCacheRepository.deleteAll(); prepareResultSchema(); } @Test public void generateCohort() { AtomicBoolean isSqlExecuted = new AtomicBoolean(); CohortDefinition cohortDefinition = cohortDefinitionRepository.findOneWithDetail(cohortId); Source source = sourceRepository.findBySourceKey(SOURCE_KEY); // Run first-time generation GenerationCacheHelper.CacheResult res = generationCacheHelper.computeCacheIfAbsent( cohortDefinition, source, cohortGenerationRequestBuilder, (resId, sqls) -> executeCohort(isSqlExecuted, resId) ); Assert.assertTrue("Cohort SQL is executed in case of empty cache", isSqlExecuted.get()); Map<String, Long> counts = retrieveCohortGenerationCounts(res.getIdentifier()); Assert.assertTrue("Cohort generation properly fills tables", checkCohortCounts(counts)); // Second time generation. Cached results isSqlExecuted.set(false); res = generationCacheHelper.computeCacheIfAbsent( cohortDefinition, source, cohortGenerationRequestBuilder, (resId, sqls) -> isSqlExecuted.set(true) ); Assert.assertFalse("Cohort results are retrieved from cache", isSqlExecuted.get()); // Generation after results were corrupted jdbcTemplate.execute(String.format("DELETE FROM %s.cohort_cache;", RESULT_SCHEMA_NAME)); isSqlExecuted.set(false); res = generationCacheHelper.computeCacheIfAbsent( cohortDefinition, source, cohortGenerationRequestBuilder, (resId, sqls) -> executeCohort(isSqlExecuted, resId) ); Assert.assertTrue("Cohort SQL is executed in case of invalid cache", isSqlExecuted.get()); counts = retrieveCohortGenerationCounts(res.getIdentifier()); Assert.assertTrue("Cohort generation properly fills tables after invalid cache", checkCohortCounts(counts)); } @Test public void checkCachingWithEmptyResultSet() { CacheableGenerationType type = CacheableGenerationType.COHORT; CohortDefinition cohortDefinition = cohortDefinitionRepository.findOneWithDetail(cohortId); Source source = sourceRepository.findBySourceKey(SOURCE_KEY); generationCacheHelper.computeCacheIfAbsent( cohortDefinition, source, cohortGenerationRequestBuilder, (resId, sqls) -> {} ); GenerationCache generationCache = generationCacheService.getCacheOrEraseInvalid(type, generationCacheService.getDesignHash(type, cohortDefinition.getDetails().getExpression()), source.getSourceId()); Assert.assertNotNull("Empty result set is cached", generationCache); } @Test public void checkHashEquivalence() { CohortDefinition cohortDefinition = cohortDefinitionRepository.findOneWithDetail(cohortId); Integer originalHash = generationCacheHelper.computeHash(cohortDefinition.getDetails().getExpression()); // modify the inclusion rule name/description, but should lead to same hash result CohortExpression expression = CohortExpression.fromJson(cohortDefinition.getDetails().getExpression()); expression.inclusionRules.get(0).name += "...updated name"; expression.inclusionRules.get(0).description += "..updated description"; Integer updatedHash = generationCacheHelper.computeHash(Utils.serialize(expression)); Assert.assertEquals("Expression with different name and descritpion results in same hash", originalHash,updatedHash); } private void executeCohort(AtomicBoolean isSqlExecuted, Integer resId) { String mockSqlList = SqlRender.renderSql( INSERT_COHORT_RESULTS_SQL, new String[]{RESULTS_DATABASE_SCHEMA, DESIGN_HASH}, new String[]{RESULT_SCHEMA_NAME, resId.toString()} ); String[] mockSqls = SqlSplit.splitSql(mockSqlList); jdbcTemplate.batchUpdate(mockSqls); isSqlExecuted.set(true); } private Map<String, Long> retrieveCohortGenerationCounts(Integer generationId) { String cohortCountsSql = SqlRender.renderSql( COHORT_COUNTS_SQL, new String[]{RESULTS_DATABASE_SCHEMA, DESIGN_HASH}, new String[]{RESULT_SCHEMA_NAME, generationId.toString()} ); return jdbcTemplate.queryForMap(cohortCountsSql) .entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> (Long) e.getValue())); } private boolean checkCohortCounts(Map<String, Long> counts) { return counts.get("cohort_record_count") == 1 && counts.get("cohort_inclusion_result_count") == 1 && counts.get("cohort_inclusion_stats_count") == 1 && counts.get("cohort_summary_stats_count") == 1 && counts.get("cohort_censor_stats_count") == 0; } private CohortDefinition getCohortDefinition() { CohortDefinitionDetails cohortDefinitionDetails = new CohortDefinitionDetails(); cohortDefinitionDetails.setExpression(COHORT_JSON); CohortDefinition cohortDefinition = new CohortDefinition(); cohortDefinition.setName("Unit test"); cohortDefinition.setDetails(cohortDefinitionDetails); cohortDefinitionDetails.setCohortDefinition(cohortDefinition); return cohortDefinition; } private Source getCdmSource() throws SQLException { Source source = new Source(); source.setSourceName("Embedded PG"); source.setSourceKey(SOURCE_KEY); source.setSourceDialect(DBMSType.POSTGRESQL.getOhdsiDB()); source.setSourceConnection(getDataSource().getConnection().getMetaData().getURL()); source.setUsername("postgres"); source.setPassword("postgres"); source.setKrbAuthMethod(KerberosAuthMechanism.PASSWORD); SourceDaimon cdmDaimon = new SourceDaimon(); cdmDaimon.setPriority(1); cdmDaimon.setDaimonType(SourceDaimon.DaimonType.CDM); cdmDaimon.setTableQualifier(CDM_SCHEMA_NAME); cdmDaimon.setSource(source); SourceDaimon vocabDaimon = new SourceDaimon(); vocabDaimon.setPriority(1); vocabDaimon.setDaimonType(SourceDaimon.DaimonType.Vocabulary); vocabDaimon.setTableQualifier(CDM_SCHEMA_NAME); vocabDaimon.setSource(source); SourceDaimon resultsDaimon = new SourceDaimon(); resultsDaimon.setPriority(1); resultsDaimon.setDaimonType(SourceDaimon.DaimonType.Results); resultsDaimon.setTableQualifier(RESULT_SCHEMA_NAME); resultsDaimon.setSource(source); source.setDaimons(Arrays.asList(cdmDaimon, vocabDaimon, resultsDaimon)); return source; } private CohortGenerationRequestBuilder getCohortGenerationRequestBuilder(Source source) { return new CohortGenerationRequestBuilder( SessionUtils.sessionId(), SourceUtils.getResultsQualifier(source) ); } // NOTE: // Not used in the current test set. Will be utilized for cohort generation testing private static void prepareCdmSchema() throws IOException, ZipException { String cdmSql = getCdmSql(); jdbcTemplate.batchUpdate("CREATE SCHEMA cdm;", cdmSql); } private static void prepareResultSchema() { String resultSql = getResultTablesSql(); jdbcTemplate.batchUpdate(SqlSplit.splitSql(resultSql)); } private static String getCdmSql() throws IOException, ZipException { StringBuilder cdmSqlBuilder = new StringBuilder(CDM_SQL); cdmSqlBuilder.append("ALTER TABLE @cdm_database_schema.vocabulary ALTER COLUMN vocabulary_reference DROP NOT NULL;\n"); cdmSqlBuilder.append("ALTER TABLE @cdm_database_schema.vocabulary ALTER COLUMN vocabulary_version DROP NOT NULL;\n"); Path tempDir = Files.createTempDirectory(""); tempDir.toFile().deleteOnExit(); // Direct Files.copy into new file in the temp folder throws Access Denied File eunomiaZip = File.createTempFile("eunomia", "", tempDir.toFile()); try (InputStream is = GenerationCacheTest.class.getResourceAsStream(EUNOMIA_CSV_ZIP)) { Files.copy(is, eunomiaZip.toPath(), REPLACE_EXISTING); } ZipFile zipFile = new ZipFile(eunomiaZip); zipFile.extractAll(tempDir.toAbsolutePath().toString()); for (final File file : tempDir.toFile().listFiles()) { if (file.getName().endsWith(".csv")) { String tableName = file.getName().replace(".csv", ""); String sql = String.format("INSERT INTO @cdm_database_schema.%s SELECT * FROM CSVREAD('%s');", tableName, file.getAbsolutePath()); cdmSqlBuilder.append(sql).append("\n\n"); } } return cdmSqlBuilder.toString().replaceAll(Constants.SqlSchemaPlaceholders.CDM_DATABASE_SCHEMA_PLACEHOLDER, CDM_SCHEMA_NAME); } private static String getResultTablesSql() { StringBuilder ddl = new StringBuilder(); ddl.append(String.format("DROP SCHEMA IF EXISTS %s CASCADE;", RESULT_SCHEMA_NAME)).append("\n"); ddl.append(String.format("CREATE SCHEMA %s;", RESULT_SCHEMA_NAME)).append("\n"); COHORT_DDL_FILE_PATHS.forEach(sqlPath -> ddl.append(ResourceHelper.GetResourceAsString(sqlPath)).append("\n")); String resultSql = SqlRender.renderSql(ddl.toString(), new String[]{"results_schema"}, new String[]{RESULT_SCHEMA_NAME}); return SqlTranslate.translateSql(resultSql, DBMSType.POSTGRESQL.getOhdsiDB()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/pathway/PathwayAnalysisTest.java
src/test/java/org/ohdsi/webapi/pathway/PathwayAnalysisTest.java
/* * Copyright 2020 cknoll1. * * 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.pathway; import com.github.mjeanroy.dbunit.core.dataset.DataSetFactory; import com.odysseusinc.arachne.commons.types.DBMSType; import com.odysseusinc.arachne.execution_engine_common.api.v1.dto.KerberosAuthMechanism; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import org.dbunit.Assertion; import org.dbunit.DatabaseUnitException; import org.dbunit.database.IDatabaseConnection; import org.dbunit.dataset.CompositeDataSet; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; import org.dbunit.operation.DatabaseOperation; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.SqlRender; import org.ohdsi.sql.SqlSplit; import org.ohdsi.sql.SqlTranslate; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.job.JobExecutionResource; import org.ohdsi.webapi.pathway.converter.PathwayAnalysisToPathwayVersionConverter; import org.ohdsi.webapi.pathway.converter.PathwayVersionToPathwayVersionFullDTOConverter; import org.ohdsi.webapi.pathway.converter.SerializedPathwayAnalysisToPathwayAnalysisConverter; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisGenerationEntity; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.source.SourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; /** * * @author cknoll1 */ public class PathwayAnalysisTest extends AbstractDatabaseTest { private static final Collection<String> CDM_DDL_FILE_PATHS = Arrays.asList("/cdm-postgresql-ddl.sql"); private static final String CDM_SCHEMA_NAME = "cdm"; private static boolean isSourceInitialized = false; private static final String SOURCE_KEY = "Embedded_PG"; private static Integer SOURCE_ID; private static final String RESULT_SCHEMA_NAME = "results"; private static final Collection<String> RESULTS_DDL_FILE_PATHS = Arrays.asList( "/ddl/results/cohort.sql", "/ddl/results/cohort_cache.sql", "/ddl/results/cohort_inclusion.sql", "/ddl/results/cohort_inclusion_result.sql", "/ddl/results/cohort_inclusion_stats.sql", "/ddl/results/cohort_inclusion_result_cache.sql", "/ddl/results/cohort_inclusion_stats_cache.sql", "/ddl/results/cohort_summary_stats.sql", "/ddl/results/cohort_summary_stats_cache.sql", "/ddl/results/cohort_censor_stats.sql", "/ddl/results/cohort_censor_stats_cache.sql", "/ddl/results/pathway_analysis_codes.sql", "/ddl/results/pathway_analysis_events.sql", "/ddl/results/pathway_analysis_paths.sql", "/ddl/results/pathway_analysis_stats.sql" ); @Autowired private SourceRepository sourceRepository; @Autowired private PathwayService pathwayService; @Autowired private ConversionService conversionService; @Value("${datasource.ohdsi.schema}") private String ohdsiSchema; private static SerializedPathwayAnalysisToPathwayAnalysisConverter converter = new SerializedPathwayAnalysisToPathwayAnalysisConverter(); @Before public void setUp() throws Exception { if (!isSourceInitialized) { // one-time setup of CDM source truncateTable(String.format("%s.%s", ohdsiSchema, "source")); resetSequence(String.format("%s.%s", ohdsiSchema, "source_sequence")); Source s = sourceRepository.saveAndFlush(getCdmSource()); SOURCE_ID = s.getSourceId(); isSourceInitialized = true; } // perform the following before each test truncateTable(String.format("%s.%s", ohdsiSchema, "cohort_definition")); resetSequence(String.format("%s.%s", ohdsiSchema, "cohort_definition_sequence")); truncateTable(String.format("%s.%s", ohdsiSchema, "pathway_analysis")); resetSequence(String.format("%s.%s", ohdsiSchema, "pathway_analysis_sequence")); truncateTable(String.format("%s.%s", ohdsiSchema, "generation_cache")); prepareCdmSchema(); prepareResultSchema(); SerializedPathwayAnalysisToPathwayAnalysisConverter.setConversionService(conversionService); } @After public void tearDownDB() { truncateTable(String.format("%s.%s", ohdsiSchema, "cohort_definition")); resetSequence(String.format("%s.%s", ohdsiSchema, "cohort_definition_sequence")); truncateTable(String.format("%s.%s", ohdsiSchema, "pathway_analysis")); resetSequence(String.format("%s.%s", ohdsiSchema, "pathway_analysis_sequence")); } private static void prepareResultSchema() { prepareSchema(RESULT_SCHEMA_NAME, "results_schema", RESULTS_DDL_FILE_PATHS); } private static void prepareCdmSchema() { prepareSchema(CDM_SCHEMA_NAME, "cdm_database_schema", CDM_DDL_FILE_PATHS); } private static void prepareSchema(final String schemaName, final String schemaToken, final Collection<String> schemaPaths) { StringBuilder ddl = new StringBuilder(); ddl.append(String.format("DROP SCHEMA IF EXISTS %s CASCADE;", schemaName)); ddl.append(String.format("CREATE SCHEMA %s;", schemaName)); schemaPaths.forEach(sqlPath -> ddl.append(ResourceHelper.GetResourceAsString(sqlPath)).append("\n")); String resultSql = SqlRender.renderSql(ddl.toString(), new String[]{schemaToken}, new String[]{schemaName}); String ddlSql = SqlTranslate.translateSql(resultSql, DBMSType.POSTGRESQL.getOhdsiDB()); jdbcTemplate.batchUpdate(SqlSplit.splitSql(ddlSql)); } private Source getCdmSource() throws SQLException { Source source = new Source(); source.setSourceName("Embedded PG"); source.setSourceKey(SOURCE_KEY); source.setSourceDialect(DBMSType.POSTGRESQL.getOhdsiDB()); source.setSourceConnection(getDataSource().getConnection().getMetaData().getURL()); source.setUsername("postgres"); source.setPassword("postgres"); source.setKrbAuthMethod(KerberosAuthMechanism.PASSWORD); SourceDaimon cdmDaimon = new SourceDaimon(); cdmDaimon.setPriority(1); cdmDaimon.setDaimonType(SourceDaimon.DaimonType.CDM); cdmDaimon.setTableQualifier(CDM_SCHEMA_NAME); cdmDaimon.setSource(source); SourceDaimon vocabDaimon = new SourceDaimon(); vocabDaimon.setPriority(1); vocabDaimon.setDaimonType(SourceDaimon.DaimonType.Vocabulary); vocabDaimon.setTableQualifier(CDM_SCHEMA_NAME); vocabDaimon.setSource(source); SourceDaimon resultsDaimon = new SourceDaimon(); resultsDaimon.setPriority(1); resultsDaimon.setDaimonType(SourceDaimon.DaimonType.Results); resultsDaimon.setTableQualifier(RESULT_SCHEMA_NAME); resultsDaimon.setSource(source); source.setDaimons(Arrays.asList(cdmDaimon, vocabDaimon, resultsDaimon)); return source; } private void generateAnalysis(PathwayAnalysisEntity entity) throws Exception { JobExecutionResource executionResource = pathwayService.generatePathways(entity.getId(), SOURCE_ID); PathwayAnalysisGenerationEntity generationEntity; while (true) { generationEntity = pathwayService.getGeneration(executionResource.getExecutionId()); if (generationEntity.getStatus().equals("FAILED") || generationEntity.getStatus().equals("COMPLETED")) { break; } Thread.sleep(2000L); } assertEquals("COMPLETED", generationEntity.getStatus()); } /** * Basic test that defines a pathway analysis with a Target cohort of the observation period start-end, * and 2 event cohorts that are constructed from the drug eras of 2 distinct drug concepts: * Child 1 [Parent 1] (ID=2) and Child 2 [Parent 1] (ID=3) creating the following overlapping periods: * <pre>{@code * Target: |-------------------------------------------------| * EC1: |---| |------| * EC2: |-----------| |---| |-------| * * Final pathway: EC1 -> EC1+EC2 -> EC2 * combo_id: 1 3 2 * * }</pre> * * References: * /pathway/vocabulary.json: simple vocabulary with 1 parent, 5 children (of parent 1) * /pathway/simpleTest_PREP.json: the person, drug_era, and observation_period data needed to produce the above cohorts. * * @throws Exception */ @Test public void test01_simplePathway() throws Exception { final String[] testDataSetsPaths = new String[] { "/pathway/vocabulary.json", "/pathway/simpleTest_PREP.json" }; loadPrepData(testDataSetsPaths); // CDM data loaded, generate pathways PathwayAnalysisEntity entity = converter.convertToEntityAttribute(ResourceHelper.GetResourceAsString("/pathway/simpleTest_design.json")); entity = pathwayService.importAnalysis(entity); generateAnalysis(entity); // Validate results // Load actual records from cohort table final IDatabaseConnection dbUnitCon = getConnection(); final ITable pathwayCodes = dbUnitCon.createQueryTable(RESULT_SCHEMA_NAME + ".pathway_analysis_codes", String.format("SELECT code, name, is_combo from %s ORDER BY code, name, is_combo", RESULT_SCHEMA_NAME + ".pathway_analysis_codes")); final ITable pathwayPaths = dbUnitCon.createQueryTable(RESULT_SCHEMA_NAME + ".pathway_analysis_paths", String.format("SELECT target_cohort_id, step_1, step_2, step_3, step_4, step_5, step_6, step_7, step_8, step_9, step_10, count_value from %s ORDER BY target_cohort_id, step_1, step_2, step_3, step_4, step_5", RESULT_SCHEMA_NAME + ".pathway_analysis_paths")); final ITable pathwayStats = dbUnitCon.createQueryTable(RESULT_SCHEMA_NAME + ".pathway_analysis_stats", String.format("SELECT target_cohort_id, target_cohort_count, pathways_count from %s ORDER BY target_cohort_id", RESULT_SCHEMA_NAME + ".pathway_analysis_stats")); final IDataSet actualDataSet = new CompositeDataSet(new ITable[] {pathwayCodes, pathwayPaths, pathwayStats}); // Load expected data from an XML dataset final String[] testDataSetsVerify = new String[] {"/pathway/simpleTest_VERIFY.json"}; final IDataSet expectedDataSet = DataSetFactory.createDataSet(testDataSetsVerify); // Assert actual database table match expected table Assertion.assertEquals(expectedDataSet, actualDataSet); } /** * A more advanced test that defines a pathway analysis with a Target cohort of the observation period start-end, * and 2 event cohorts that are constructed from the drug eras of 2 distinct drug concepts, with a gap window of 15d: * Child 1 [Parent 1] (ID=2) and Child 2 [Parent 1] (ID=3) creating the following overlapping periods: * <pre>{@code * Target: |-------------------------------------------------| * EC1: |---| |------| * EC2: |-----------| |---| |-------| * * With 15d collapse (and re-arranged to show the overlapping periods: * Target: |-------------------------------------------------| * EC1: |---| * EC1: |-------------| * EC2: |-------------| * EC2: |---| * EC2: |----------| * * Note: EC1 gets collapse to cause an overlap between the first EC1 episode and second EC2 Episode * Final pathway: EC1+EC2 -> EC2 * combo_id: 3 2 * * }</pre> * * References: * /pathway/vocabulary.json: simple vocabulary with 1 parent, 5 children (of parent 1) * /pathway/collapseTest_PREP.json: the person, drug_era, and observation_period data needed to produce the above cohorts. * * @throws Exception */ @Test public void test02_collapseWindow() throws Exception { final String[] testDataSetsPaths = new String[] { "/pathway/vocabulary.json", "/pathway/collapseTest_PREP.json" }; loadPrepData(testDataSetsPaths); // CDM data loaded, generate pathways PathwayAnalysisEntity entity = converter.convertToEntityAttribute(ResourceHelper.GetResourceAsString("/pathway/collapseTest_design.json")); entity = pathwayService.importAnalysis(entity); generateAnalysis(entity); // Validate results // Load actual records from cohort table final IDatabaseConnection dbUnitCon = getConnection(); final ITable pathwayCodes = dbUnitCon.createQueryTable(RESULT_SCHEMA_NAME + ".pathway_analysis_codes", String.format("SELECT code, name, is_combo from %s ORDER BY code, name, is_combo", RESULT_SCHEMA_NAME + ".pathway_analysis_codes")); final ITable pathwayPaths = dbUnitCon.createQueryTable(RESULT_SCHEMA_NAME + ".pathway_analysis_paths", String.format("SELECT target_cohort_id, step_1, step_2, step_3, step_4, step_5, step_6, step_7, step_8, step_9, step_10, count_value from %s ORDER BY target_cohort_id, step_1, step_2, step_3, step_4, step_5", RESULT_SCHEMA_NAME + ".pathway_analysis_paths")); final ITable pathwayStats = dbUnitCon.createQueryTable(RESULT_SCHEMA_NAME + ".pathway_analysis_stats", String.format("SELECT target_cohort_id, target_cohort_count, pathways_count from %s ORDER BY target_cohort_id", RESULT_SCHEMA_NAME + ".pathway_analysis_stats")); final IDataSet actualDataSet = new CompositeDataSet(new ITable[] {pathwayCodes, pathwayPaths, pathwayStats}); // Load expected data from an XML dataset final String[] testDataSetsVerify = new String[] {"/pathway/collapseTest_VERIFY.json"}; final IDataSet expectedDataSet = DataSetFactory.createDataSet(testDataSetsVerify); // Assert actual database table match expected table Assertion.assertEquals(expectedDataSet, actualDataSet); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/pathway/PathwayServiceTest.java
src/test/java/org/ohdsi/webapi/pathway/PathwayServiceTest.java
package org.ohdsi.webapi.pathway; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisEntity; import org.ohdsi.webapi.pathway.domain.PathwayAnalysisGenerationEntity; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.repository.PathwayAnalysisGenerationRepository; import org.springframework.core.convert.support.GenericConversionService; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class PathwayServiceTest { @Mock private PathwayAnalysisGenerationRepository pathwayAnalysisGenerationRepository; @Mock private GenericConversionService genericConversionService; @Mock private PathwayAnalysisGenerationEntity pathwayAnalysisGenerationEntity; @Mock(answer = Answers.RETURNS_DEEP_STUBS) private PathwayAnalysisDTO pathwayAnalysisDTO; @Mock private PathwayAnalysisEntity pathwayAnalysisEntity; @InjectMocks private PathwayServiceImpl sut; @Test public void shouldGetByGenerationId() { when(pathwayAnalysisGenerationRepository.findOne(anyLong(), any())).thenReturn(pathwayAnalysisGenerationEntity); when(pathwayAnalysisGenerationEntity.getPathwayAnalysis()).thenReturn(pathwayAnalysisEntity); when(genericConversionService.convert(eq(pathwayAnalysisEntity), eq(PathwayAnalysisDTO.class))).thenReturn(pathwayAnalysisDTO); PathwayAnalysisDTO result = sut.getByGenerationId(1); assertEquals(result, pathwayAnalysisDTO); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/versioning/ConceptSetVersioningTest.java
src/test/java/org/ohdsi/webapi/versioning/ConceptSetVersioningTest.java
package org.ohdsi.webapi.versioning; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.ohdsi.circe.vocabulary.ConceptSetExpression; import org.ohdsi.webapi.conceptset.ConceptSetItem; import org.ohdsi.webapi.conceptset.ConceptSetRepository; import org.ohdsi.webapi.conceptset.dto.ConceptSetVersionFullDTO; import org.ohdsi.webapi.service.ConceptSetService; import org.ohdsi.webapi.service.dto.ConceptSetDTO; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; public class ConceptSetVersioningTest extends BaseVersioningTest<ConceptSetDTO, ConceptSetVersionFullDTO, Integer> { private static final String JSON_PATH = "/versioning/conceptset.json"; @Autowired private ConceptSetService service; @Autowired private ConceptSetRepository repository; @Autowired private ObjectMapper mapper; @Override public void doCreateInitialData() throws IOException { ConceptSetDTO dto = new ConceptSetDTO(); dto.setName("test dto name"); initialDTO = service.createConceptSet(dto); String expression = getExpression(getExpressionPath()); ConceptSetExpression.ConceptSetItem[] expressionItems; try { ConceptSetExpression conceptSetExpression = mapper.readValue(expression, ConceptSetExpression.class); expressionItems = conceptSetExpression.items; } catch (JsonProcessingException e) { throw new RuntimeException(e); } ConceptSetItem[] items = Arrays.stream(expressionItems) .map(i -> conversionService.convert(i, ConceptSetItem.class)) .toArray(ConceptSetItem[]::new); service.saveConceptSetItems(initialDTO.getId(), items); } protected void checkClientDTOEquality(ConceptSetVersionFullDTO fullDTO) { ConceptSetDTO dto = fullDTO.getEntityDTO(); checkEquality(dto); assertEquals(dto.getTags().size(), 0); } protected void checkServerDTOEquality(ConceptSetDTO dto) { checkEquality(dto); assertNull(dto.getTags()); } private void checkEquality(ConceptSetDTO dto) { assertNotEquals(dto.getName(), initialDTO.getName()); Iterable<ConceptSetItem> initialItems = service.getConceptSetItems(initialDTO.getId()); long initialSize = StreamSupport.stream(initialItems.spliterator(), false).count(); Iterable<ConceptSetItem> newItems = service.getConceptSetItems(dto.getId()); long newSize = StreamSupport.stream(newItems.spliterator(), false).count(); assertEquals(newSize, initialSize); } @Override protected ConceptSetDTO getEntity(Integer id) { return service.getConceptSet(id); } @Override protected ConceptSetDTO updateEntity(ConceptSetDTO dto) throws Exception { return service.updateConceptSet(dto.getId(), dto); } @Override protected ConceptSetDTO copyAssetFromVersion(Integer id, int version) { return service.copyAssetFromVersion(id, version); } @Override protected Integer getId(ConceptSetDTO dto) { return dto.getId(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected List<VersionDTO> getVersions(Integer id) { return service.getVersions(id); } @Override protected ConceptSetVersionFullDTO getVersion(Integer id, int version) { return service.getVersion(id, version); } @Override protected void updateVersion(Integer id, int version, VersionUpdateDTO updateDTO) { service.updateVersion(id, version, updateDTO); } @Override protected void deleteVersion(Integer id, int version) { service.deleteVersion(id, version); } @Override public void doClear() { repository.deleteAll(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/versioning/ReusableVersioningTest.java
src/test/java/org/ohdsi/webapi/versioning/ReusableVersioningTest.java
package org.ohdsi.webapi.versioning; import org.ohdsi.webapi.reusable.ReusableService; import org.ohdsi.webapi.reusable.dto.ReusableDTO; import org.ohdsi.webapi.reusable.dto.ReusableVersionFullDTO; import org.ohdsi.webapi.reusable.repository.ReusableRepository; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class ReusableVersioningTest extends BaseVersioningTest<ReusableDTO, ReusableVersionFullDTO, Integer> { @Autowired private ReusableService service; @Autowired private ReusableRepository repository; @Override public void doCreateInitialData() throws IOException { ReusableDTO dto = new ReusableDTO(); dto.setData("test data"); dto.setName("test name"); dto.setDescription("test description"); initialDTO = service.create(dto); } protected void checkClientDTOEquality(ReusableVersionFullDTO fullDTO) { ReusableDTO dto = fullDTO.getEntityDTO(); checkEquality(dto); } protected void checkServerDTOEquality(ReusableDTO dto) { checkEquality(dto); } private void checkEquality(ReusableDTO dto) { assertNotEquals(dto.getName(), initialDTO.getName()); assertEquals(dto.getTags().size(), 0); } @Override protected ReusableDTO getEntity(Integer id) { return service.getDTOById(id); } @Override protected ReusableDTO updateEntity(ReusableDTO dto) { return service.update(dto.getId(), dto); } @Override protected ReusableDTO copyAssetFromVersion(Integer id, int version) { return service.copyAssetFromVersion(id, version); } @Override protected Integer getId(ReusableDTO dto) { return dto.getId(); } @Override protected String getExpressionPath() { return null; } @Override protected List<VersionDTO> getVersions(Integer id) { return service.getVersions(id); } @Override protected ReusableVersionFullDTO getVersion(Integer id, int version) { return service.getVersion(id, version); } @Override protected void updateVersion(Integer id, int version, VersionUpdateDTO updateDTO) { service.updateVersion(id, version, updateDTO); } @Override protected void deleteVersion(Integer id, int version) { service.deleteVersion(id, version); } @Override public void doClear() { repository.deleteAll(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/versioning/BaseVersioningTest.java
src/test/java/org/ohdsi/webapi/versioning/BaseVersioningTest.java
package org.ohdsi.webapi.versioning; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.service.dto.CommonEntityExtDTO; import org.ohdsi.webapi.shiro.Entities.UserEntity; import org.ohdsi.webapi.shiro.Entities.UserRepository; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionFullDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Objects; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public abstract class BaseVersioningTest<S extends CommonEntityExtDTO, T extends VersionFullDTO<?>, ID extends Number> extends AbstractDatabaseTest { protected S initialDTO; @Autowired protected UserRepository userRepository; @Autowired protected ConversionService conversionService; protected String getExpression(String path) throws IOException { File ple_spec = ResourceUtils.getFile(Objects.requireNonNull(this.getClass().getResource(path))); return FileUtils.readFileToString(ple_spec, StandardCharsets.UTF_8); } @Before public void createInitialData() throws IOException { UserEntity user = new UserEntity(); user.setLogin("anonymous"); userRepository.save(user); doCreateInitialData(); } protected abstract void doCreateInitialData() throws IOException; @After public void clear() { doClear(); userRepository.deleteAll(); } @Test public void createAndGetVersion() throws Exception { S dto = getEntity(getId(initialDTO)); dto.setName(dto.getName() + "__copy"); updateEntity(dto); List<VersionDTO> versions = getVersions(getId(dto)); assertEquals(1, versions.size()); VersionDTO version = versions.get(0); T fullDTO = getVersion(getId(dto), version.getVersion()); assertNotNull(fullDTO); checkClientDTOEquality(fullDTO); } @Test public void deleteVersion() throws Exception { S dto = getEntity(getId(initialDTO)); dto.setName(dto.getName() + "__copy"); updateEntity(dto); List<VersionDTO> versions = getVersions(getId(dto)); assertEquals(1, versions.size()); VersionDTO version = versions.get(0); deleteVersion(getId(dto), version.getVersion()); versions = getVersions(getId(dto)); assertTrue(versions.get(0).isArchived()); } @Test public void createAndGetMultipleVersions() throws Exception { S dto = getEntity(getId(initialDTO)); int count = 3; for (int i = 0; i < count; i++) { updateEntity(dto); } List<VersionDTO> versions = getVersions(getId(dto)); assertEquals(count, versions.size()); } @Test public void updateVersion() throws Exception { S dto = getEntity(getId(initialDTO)); dto.setName(dto.getName() + "__copy"); updateEntity(dto); List<VersionDTO> versions = getVersions(getId(dto)); VersionDTO version = versions.get(0); VersionUpdateDTO updateDTO = new VersionUpdateDTO(); updateDTO.setVersion(version.getVersion()); updateDTO.setArchived(true); updateDTO.setComment("test comment"); updateVersion(getId(dto), version.getVersion(), updateDTO); T fullDTO = getVersion(getId(dto), version.getVersion()); version = fullDTO.getVersionDTO(); assertEquals(version.getComment(), updateDTO.getComment()); assertEquals(version.isArchived(), updateDTO.isArchived()); } @Test public void copyAssetFromVersion() throws Exception { S dto = getEntity(getId(initialDTO)); dto.setName(dto.getName() + "__copy"); updateEntity(dto); List<VersionDTO> versions = getVersions(getId(dto)); VersionDTO version = versions.get(0); S newDTO = copyAssetFromVersion(getId(dto), version.getVersion()); checkServerDTOEquality(newDTO); } protected abstract void doClear(); protected abstract void checkServerDTOEquality(S dto); protected abstract void checkClientDTOEquality(T dto); protected abstract List<VersionDTO> getVersions(ID id); protected abstract T getVersion(ID id, int version); protected abstract String getExpressionPath(); protected abstract S getEntity(ID id); protected abstract S updateEntity(S dto) throws Exception; protected abstract S copyAssetFromVersion(ID id, int version); protected abstract void updateVersion(ID id, int version, VersionUpdateDTO updateDTO); protected abstract void deleteVersion(ID id, int version); protected abstract ID getId(S dto); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/versioning/CohortVersioningTest.java
src/test/java/org/ohdsi/webapi/versioning/CohortVersioningTest.java
package org.ohdsi.webapi.versioning; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO; import org.ohdsi.webapi.cohortdefinition.dto.CohortMetadataDTO; import org.ohdsi.webapi.cohortdefinition.dto.CohortRawDTO; import org.ohdsi.webapi.cohortdefinition.dto.CohortVersionFullDTO; import org.ohdsi.webapi.service.CohortDefinitionService; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; public class CohortVersioningTest extends BaseVersioningTest<CohortDTO, CohortVersionFullDTO, Integer> { private static final String JSON_PATH = "/versioning/cohort.json"; @Autowired private CohortDefinitionService service; @Autowired private CohortDefinitionRepository repository; private CohortDTO deserializeExpression(String expression) { CohortRawDTO rawDTO = new CohortRawDTO(); rawDTO.setExpression(expression); CohortDTO dto = conversionService.convert(rawDTO, CohortDTO.class); dto.setName("test dto name"); dto.setDescription("test dto description"); return dto; } @Override public void doCreateInitialData() throws IOException { String expression = getExpression(getExpressionPath()); CohortDTO dto = deserializeExpression(expression); initialDTO = service.createCohortDefinition(dto); } protected void checkClientDTOEquality(CohortVersionFullDTO fullDTO) { CohortRawDTO dto = fullDTO.getEntityDTO(); checkEquality(dto); assertEquals(dto.getTags().size(), 0); CohortDefinition def = conversionService.convert(initialDTO, CohortDefinition.class); CohortRawDTO rawDTO = conversionService.convert(def, CohortRawDTO.class); assertEquals(dto.getExpression(), rawDTO.getExpression()); } protected void checkServerDTOEquality(CohortDTO dto) { checkEquality(dto); assertNull(dto.getTags()); CohortDefinition def = conversionService.convert(initialDTO, CohortDefinition.class); CohortRawDTO rawDTO = conversionService.convert(def, CohortRawDTO.class); CohortDefinition newDef = conversionService.convert(dto, CohortDefinition.class); CohortRawDTO newRawDTO = conversionService.convert(newDef, CohortRawDTO.class); assertEquals(newRawDTO.getExpression(), rawDTO.getExpression()); } private void checkEquality(CohortMetadataDTO dto) { assertNotEquals(dto.getName(), initialDTO.getName()); assertEquals(dto.getDescription(), initialDTO.getDescription()); } @Override protected CohortDTO getEntity(Integer id) { return service.getCohortDefinition(id); } @Override protected CohortDTO updateEntity(CohortDTO dto) { return service.saveCohortDefinition(dto.getId(), dto); } @Override protected CohortDTO copyAssetFromVersion(Integer id, int version) { return service.copyAssetFromVersion(id, version); } @Override protected Integer getId(CohortDTO dto) { return dto.getId(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected List<VersionDTO> getVersions(Integer id) { return service.getVersions(id); } @Override protected CohortVersionFullDTO getVersion(Integer id, int version) { return service.getVersion(id, version); } @Override protected void updateVersion(Integer id, int version, VersionUpdateDTO updateDTO) { service.updateVersion(id, version, updateDTO); } @Override protected void deleteVersion(Integer id, int version) { service.deleteVersion(id, version); } @Override public void doClear() { repository.deleteAll(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/versioning/CcVersioningTest.java
src/test/java/org/ohdsi/webapi/versioning/CcVersioningTest.java
package org.ohdsi.webapi.versioning; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.cohortcharacterization.CcController; import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity; import org.ohdsi.webapi.cohortcharacterization.dto.CcExportDTO; import org.ohdsi.webapi.cohortcharacterization.dto.CcVersionFullDTO; import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO; import org.ohdsi.webapi.cohortcharacterization.repository.CcRepository; import org.ohdsi.webapi.cohortcharacterization.specification.CohortCharacterizationImpl; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class CcVersioningTest extends BaseVersioningTest<CohortCharacterizationDTO, CcVersionFullDTO, Long> { private static final String JSON_PATH = "/versioning/characterization.json"; @Autowired private CcController service; @Autowired private CcRepository repository; @Autowired private CohortDefinitionRepository cohortRepository; @Override public void doCreateInitialData() throws IOException { String expression = getExpression(getExpressionPath()); CohortCharacterizationImpl characterizationImpl = Utils.deserialize(expression, CohortCharacterizationImpl.class); CohortCharacterizationEntity entity = conversionService.convert(characterizationImpl, CohortCharacterizationEntity.class); CcExportDTO exportDTO = conversionService.convert(entity, CcExportDTO.class); exportDTO.setName("test dto name"); initialDTO = service.doImport(exportDTO); } protected void checkClientDTOEquality(CcVersionFullDTO fullDTO) { CohortCharacterizationDTO dto = fullDTO.getEntityDTO(); checkEquality(dto); assertEquals(dto.getCohorts().size(), initialDTO.getCohorts().size()); assertEquals(dto.getParameters().size(), initialDTO.getParameters().size()); assertEquals(dto.getFeatureAnalyses().size(), initialDTO.getFeatureAnalyses().size()); } protected void checkServerDTOEquality(CohortCharacterizationDTO dto) { checkEquality(dto); } private void checkEquality(CohortCharacterizationDTO dto) { assertNotEquals(dto.getName(), initialDTO.getName()); assertEquals(dto.getCohorts().size(), initialDTO.getCohorts().size()); assertEquals(dto.getParameters().size(), initialDTO.getParameters().size()); assertEquals(dto.getFeatureAnalyses().size(), initialDTO.getFeatureAnalyses().size()); assertEquals(dto.getTags().size(), 0); } @Override protected CohortCharacterizationDTO getEntity(Long id) { return service.getDesign(id); } @Override protected CohortCharacterizationDTO updateEntity(CohortCharacterizationDTO dto) { return service.update(dto.getId(), dto); } @Override protected CohortCharacterizationDTO copyAssetFromVersion(Long id, int version) { return service.copyAssetFromVersion(id, version); } @Override protected Long getId(CohortCharacterizationDTO dto) { return dto.getId(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected List<VersionDTO> getVersions(Long id) { return service.getVersions(id); } @Override protected CcVersionFullDTO getVersion(Long id, int version) { return service.getVersion(id, version); } @Override protected void updateVersion(Long id, int version, VersionUpdateDTO updateDTO) { service.updateVersion(id, version, updateDTO); } @Override protected void deleteVersion(Long id, int version) { service.deleteVersion(id, version); } @Override public void doClear() { repository.deleteAll(); cohortRepository.deleteAll(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/versioning/IRVersioningTest.java
src/test/java/org/ohdsi/webapi/versioning/IRVersioningTest.java
package org.ohdsi.webapi.versioning; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.ircalc.IncidenceRateAnalysisRepository; import org.ohdsi.webapi.ircalc.dto.IRVersionFullDTO; import org.ohdsi.webapi.service.IRAnalysisService; import org.ohdsi.webapi.service.dto.IRAnalysisDTO; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; public class IRVersioningTest extends BaseVersioningTest<IRAnalysisDTO, IRVersionFullDTO, Integer> { private static final String JSON_PATH = "/versioning/ir.json"; @Autowired private IRAnalysisService service; @Autowired private IncidenceRateAnalysisRepository repository; @Autowired private CohortDefinitionRepository cohortRepository; private IRAnalysisDTO deserializeExpression(String expression) { IRAnalysisDTO dto = Utils.deserialize(expression, IRAnalysisDTO.class); dto.setName("test dto name"); dto.setDescription("test dto description"); return dto; } @Override public void doCreateInitialData() throws IOException { String expression = getExpression(getExpressionPath()); IRAnalysisDTO dto = deserializeExpression(expression); initialDTO = service.doImport(dto); } protected void checkClientDTOEquality(IRVersionFullDTO fullDTO) { IRAnalysisDTO dto = fullDTO.getEntityDTO(); checkEquality(dto); assertEquals(dto.getTags().size(), 0); } protected void checkServerDTOEquality(IRAnalysisDTO dto) { checkEquality(dto); assertNull(dto.getTags()); } private void checkEquality(IRAnalysisDTO dto) { assertNotEquals(dto.getName(), initialDTO.getName()); assertEquals(dto.getDescription(), initialDTO.getDescription()); assertEquals(dto.getExpression(), initialDTO.getExpression()); } @Override protected IRAnalysisDTO getEntity(Integer id) { return service.getAnalysis(id); } @Override protected IRAnalysisDTO updateEntity(IRAnalysisDTO dto) { return service.saveAnalysis(dto.getId(), dto); } @Override protected IRAnalysisDTO copyAssetFromVersion(Integer id, int version) { return service.copyAssetFromVersion(id, version); } @Override protected Integer getId(IRAnalysisDTO dto) { return dto.getId(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected List<VersionDTO> getVersions(Integer id) { return service.getVersions(id); } @Override protected IRVersionFullDTO getVersion(Integer id, int version) { return service.getVersion(id, version); } @Override protected void updateVersion(Integer id, int version, VersionUpdateDTO updateDTO) { service.updateVersion(id, version, updateDTO); } @Override protected void deleteVersion(Integer id, int version) { service.deleteVersion(id, version); } @Override public void doClear() { repository.deleteAll(); cohortRepository.deleteAll(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/versioning/PathwayVersioningTest.java
src/test/java/org/ohdsi/webapi/versioning/PathwayVersioningTest.java
package org.ohdsi.webapi.versioning; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.pathway.PathwayController; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.ohdsi.webapi.pathway.dto.PathwayVersionFullDTO; import org.ohdsi.webapi.pathway.repository.PathwayAnalysisEntityRepository; import org.ohdsi.webapi.versioning.dto.VersionDTO; import org.ohdsi.webapi.versioning.dto.VersionUpdateDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class PathwayVersioningTest extends BaseVersioningTest<PathwayAnalysisDTO, PathwayVersionFullDTO, Integer> { private static final String JSON_PATH = "/versioning/pathway.json"; @Autowired private PathwayController service; @Autowired private PathwayAnalysisEntityRepository repository; @Autowired private CohortDefinitionRepository cohortRepository; @Override public void doCreateInitialData() throws IOException { String expression = getExpression(getExpressionPath()); PathwayAnalysisExportDTO dto = Utils.deserialize(expression, PathwayAnalysisExportDTO.class); dto.setName("test dto name"); initialDTO = service.importAnalysis(dto); } protected void checkClientDTOEquality(PathwayVersionFullDTO fullDTO) { PathwayAnalysisDTO dto = fullDTO.getEntityDTO(); checkEquality(dto); } protected void checkServerDTOEquality(PathwayAnalysisDTO dto) { checkEquality(dto); } private void checkEquality(PathwayAnalysisDTO dto) { assertNotEquals(dto.getName(), initialDTO.getName()); assertEquals(dto.getEventCohorts().size(), initialDTO.getEventCohorts().size()); assertEquals(dto.getTargetCohorts().size(), initialDTO.getTargetCohorts().size()); assertEquals(dto.getTags().size(), 0); } @Override protected PathwayAnalysisDTO getEntity(Integer id) { return service.get(id); } @Override protected PathwayAnalysisDTO updateEntity(PathwayAnalysisDTO dto) { return service.update(dto.getId(), dto); } @Override protected PathwayAnalysisDTO copyAssetFromVersion(Integer id, int version) { return service.copyAssetFromVersion(id, version); } @Override protected Integer getId(PathwayAnalysisDTO dto) { return dto.getId(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected List<VersionDTO> getVersions(Integer id) { return service.getVersions(id); } @Override protected PathwayVersionFullDTO getVersion(Integer id, int version) { return service.getVersion(id, version); } @Override protected void updateVersion(Integer id, int version, VersionUpdateDTO updateDTO) { service.updateVersion(id, version, updateDTO); } @Override protected void deleteVersion(Integer id, int version) { service.deleteVersion(id, version); } @Override public void doClear() { repository.deleteAll(); cohortRepository.deleteAll(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/SecurityIT.java
src/test/java/org/ohdsi/webapi/test/SecurityIT.java
package org.ohdsi.webapi.test; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.annotation.DbUnitConfiguration; import com.google.common.collect.ImmutableMap; import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.model.Resource; import org.glassfish.jersey.server.model.ResourceMethod; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; import org.junit.runner.RunWith; import org.ohdsi.webapi.JerseyConfig; import org.ohdsi.webapi.WebApi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.*; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.util.UriComponentsBuilder; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.net.URI; import java.util.*; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.springframework.test.context.TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS; @RunWith(SpringRunner.class) @SpringBootTest(classes = {WebApi.class, WebApiIT.DbUnitConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @DbUnitConfiguration(databaseConnection = "dbUnitDatabaseConnection") @TestExecutionListeners(value = {DbUnitTestExecutionListener.class}, mergeMode = MERGE_WITH_DEFAULTS) @DatabaseTearDown(value = "/database/empty.xml", type = DatabaseOperation.DELETE_ALL) @TestPropertySource(properties = {"security.provider=AtlasRegularSecurity"}) public class SecurityIT { private final Map<String, HttpStatus> EXPECTED_RESPONSE_CODES = ImmutableMap.<String, HttpStatus>builder() .put("/info/", HttpStatus.OK) .put("/i18n/", HttpStatus.OK) .put("/i18n/locales", HttpStatus.OK) .put("/ddl/results", HttpStatus.OK) .put("/ddl/cemresults", HttpStatus.OK) .put("/ddl/achilles", HttpStatus.OK) .put("/saml/saml-metadata", HttpStatus.OK) .put("/saml/slo", HttpStatus.TEMPORARY_REDIRECT) .build(); @Autowired private TestRestTemplate restTemplate; @Autowired private JerseyConfig jerseyConfig; @Value("${baseUri}") private String baseUri; @Rule public ErrorCollector collector = new ErrorCollector(); private final Logger LOG = LoggerFactory.getLogger(SecurityIT.class); @BeforeClass public static void before() throws IOException { TomcatURLStreamHandlerFactory.disable(); ITStarter.before(); } @AfterClass public static void after() { ITStarter.tearDownSubject(); } @Test public void testServiceSecurity() { Map<String, List<ServiceInfo>> serviceMap = getServiceMap(); for (String servicePrefix : serviceMap.keySet()) { List<ServiceInfo> serviceInfos = serviceMap.get(servicePrefix); for (ServiceInfo serviceInfo : serviceInfos) { if (!serviceInfo.pathPrefix.startsWith("/")) { serviceInfo.pathPrefix = "/" + serviceInfo.pathPrefix; } serviceInfo.pathPrefix = serviceInfo.pathPrefix.replaceAll("//", "/"); String rawUrl = baseUri + serviceInfo.pathPrefix; URI uri = null; try { Map<String, String> parametersMap = prepareParameters(serviceInfo.parameters); HttpEntity<?> entity = new HttpEntity<>(new HttpHeaders()); uri = UriComponentsBuilder.fromUriString(rawUrl) .buildAndExpand(parametersMap).encode().toUri(); LOG.info("testing service {}:{}", serviceInfo.httpMethod, uri); ResponseEntity<?> response = this.restTemplate.exchange(uri, serviceInfo.httpMethod, entity, getResponseType(serviceInfo)); LOG.info("tested service {}:{} with code {}", serviceInfo.httpMethod, uri, response.getStatusCode()); HttpStatus expectedStatus = EXPECTED_RESPONSE_CODES.getOrDefault(serviceInfo.pathPrefix, HttpStatus.UNAUTHORIZED); assertThat(response.getStatusCode()).isEqualTo(expectedStatus); } catch (Throwable t) { LOG.info("failed service {}:{}", serviceInfo.httpMethod, uri); collector.addError(new ThrowableEx(t, rawUrl)); } } } } private Class<?> getResponseType(ServiceInfo serviceInfo) { if (serviceInfo.mediaTypes.contains(MediaType.TEXT_PLAIN_TYPE)) { return String.class; } else if (serviceInfo.pathPrefix.equalsIgnoreCase("/saml/saml-metadata")) { return Void.class; } return Object.class; } private Map<String, String> prepareParameters(List<Parameter> parameters) { Map<String, String> parametersMap = new HashMap<>(); if (parameters != null && !parameters.isEmpty()) { for (Parameter parameter : parameters) { String value = "0"; // if parameter has classloader then it is of object type, else it is primitive type if (parameter.getRawType().getClassLoader() != null) { value = null; } parametersMap.put(parameter.getSourceName(), value); } } return parametersMap; } /* * Retrieve information about rest services (path prefixes, http methods, parameters) */ private Map<String, List<ServiceInfo>> getServiceMap() { // Set<Class<?>> classes = this.jerseyConfig.getClasses(); Map<String, List<ServiceInfo>> serviceMap = new HashMap<>(); for (Class<?> clazz : classes) { Map<String, List<ServiceInfo>> map = scan(clazz); if (map != null) { serviceMap.putAll(map); } } return serviceMap; } private Map<String, List<ServiceInfo>> scan(Class<?> baseClass) { Resource.Builder builder = Resource.builder(baseClass); if (null == builder) return null; Resource resource = builder.build(); String uriPrefix = ""; Map<String, List<ServiceInfo>> info = new TreeMap<>(); return process(uriPrefix, resource, info); } private Map<String, List<ServiceInfo>> process(String uriPrefix, Resource resource, Map<String, List<ServiceInfo>> info) { String pathPrefix = uriPrefix; List<Resource> resources = new ArrayList<>(resource.getChildResources()); if (resource.getPath() != null) { pathPrefix = pathPrefix + resource.getPath(); } for (ResourceMethod method : resource.getAllMethods()) { List<ServiceInfo> serviceInfos = info.computeIfAbsent(pathPrefix, k -> new ArrayList<>()); ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.pathPrefix = pathPrefix; serviceInfo.httpMethod = HttpMethod.resolve(method.getHttpMethod()); serviceInfo.parameters = method.getInvocable().getParameters(); serviceInfo.mediaTypes = method.getProducedTypes(); serviceInfos.add(serviceInfo); } for (Resource childResource : resources) { process(pathPrefix, childResource, info); } return info; } private static class ServiceInfo { public String pathPrefix; public HttpMethod httpMethod; public List<Parameter> parameters; public List<MediaType> mediaTypes; } private static class ThrowableEx extends Throwable { private final String serviceName; public ThrowableEx(Throwable throwable, String serviceName) { super(throwable); this.serviceName = serviceName; } @Override public String getMessage() { return serviceName + ": " + super.getMessage(); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/TestConstants.java
src/test/java/org/ohdsi/webapi/test/TestConstants.java
package org.ohdsi.webapi.test; public class TestConstants { public final static String COPY_PREFIX = "COPY OF "; public final static String NEW_TEST_ENTITY = "New test entity"; public final static String SOME_UNIQUE_TEST_NAME = "Some unique test name"; }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/WebApiIT.java
src/test/java/org/ohdsi/webapi/test/WebApiIT.java
package org.ohdsi.webapi.test; import static org.junit.Assert.assertEquals; import static org.springframework.test.context.TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DbUnitConfiguration; import java.io.IOException; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBean; import com.odysseusinc.arachne.commons.types.DBMSType; import com.odysseusinc.arachne.execution_engine_common.api.v1.dto.KerberosAuthMechanism; import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.SqlRender; import org.ohdsi.sql.SqlSplit; import org.ohdsi.sql.SqlTranslate; import org.ohdsi.webapi.WebApi; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.boot.test.web.client.TestRestTemplate; import javax.sql.DataSource; @RunWith(SpringRunner.class) @SpringBootTest(classes = {WebApi.class, WebApiIT.DbUnitConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @DbUnitConfiguration(databaseConnection = "dbUnitDatabaseConnection") @TestExecutionListeners(value = {DbUnitTestExecutionListener.class}, mergeMode = MERGE_WITH_DEFAULTS) public abstract class WebApiIT { protected final Logger log = LoggerFactory.getLogger(getClass()); protected final String SOURCE_KEY = "Embedded_PG"; protected static final String CDM_SCHEMA_NAME = "cdm"; protected static final String RESULT_SCHEMA_NAME = "results"; private static final Collection<String> CDM_DDL_FILE_PATHS = Arrays.asList("/cdm-postgresql-ddl.sql"); private static final Collection<String> RESULTS_DDL_FILE_PATHS = Arrays.asList( "/ddl/results/cohort.sql", "/ddl/results/cohort_cache.sql", "/ddl/results/cohort_inclusion.sql", "/ddl/results/cohort_inclusion_result.sql", "/ddl/results/cohort_inclusion_stats.sql", "/ddl/results/cohort_inclusion_result_cache.sql", "/ddl/results/cohort_inclusion_stats_cache.sql", "/ddl/results/cohort_summary_stats.sql", "/ddl/results/cohort_summary_stats_cache.sql", "/ddl/results/cohort_censor_stats.sql", "/ddl/results/cohort_censor_stats_cache.sql", "/ddl/results/pathway_analysis_codes.sql", "/ddl/results/pathway_analysis_events.sql", "/ddl/results/pathway_analysis_paths.sql", "/ddl/results/pathway_analysis_stats.sql", "/ddl/results/achilles_result_concept_count.sql" ); @TestConfiguration public static class DbUnitConfiguration { @Bean DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection(DataSource primaryDataSource) { DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection = new DatabaseDataSourceConnectionFactoryBean(primaryDataSource); dbUnitDatabaseConnection.setSchema("public"); return dbUnitDatabaseConnection; } } @Value("${baseUri}") private String baseUri; private final TestRestTemplate restTemplate = new TestRestTemplate(); protected static JdbcTemplate jdbcTemplate; @BeforeClass public static void before() throws IOException { TomcatURLStreamHandlerFactory.disable(); ITStarter.before(); jdbcTemplate = new JdbcTemplate(ITStarter.getDataSource()); } @AfterClass public static void after() { ITStarter.tearDownSubject(); } public TestRestTemplate getRestTemplate() { return this.restTemplate; } public String getBaseUri() { return this.baseUri; } public void setBaseUri(final String baseUri) { this.baseUri = baseUri; } public void assertOK(ResponseEntity<?> entity) { assertEquals(HttpStatus.OK, entity.getStatusCode()); if (log.isDebugEnabled()) { log.debug("Body: {}", entity.getBody()); } } protected void truncateTable(final String tableName) { jdbcTemplate.execute(String.format("TRUNCATE %s CASCADE",tableName)); } protected void resetSequence(final String sequenceName) { jdbcTemplate.execute(String.format("ALTER SEQUENCE %s RESTART WITH 1", sequenceName)); } protected Source getCdmSource() throws SQLException { Source source = new Source(); source.setSourceName("Embedded PG"); source.setSourceKey(SOURCE_KEY); source.setSourceDialect(DBMSType.POSTGRESQL.getOhdsiDB()); source.setSourceConnection(ITStarter.getDataSource().getConnection().getMetaData().getURL()); source.setUsername("postgres"); source.setPassword("postgres"); source.setKrbAuthMethod(KerberosAuthMechanism.PASSWORD); SourceDaimon cdmDaimon = new SourceDaimon(); cdmDaimon.setPriority(1); cdmDaimon.setDaimonType(SourceDaimon.DaimonType.CDM); cdmDaimon.setTableQualifier(CDM_SCHEMA_NAME); cdmDaimon.setSource(source); SourceDaimon vocabDaimon = new SourceDaimon(); vocabDaimon.setPriority(1); vocabDaimon.setDaimonType(SourceDaimon.DaimonType.Vocabulary); vocabDaimon.setTableQualifier(CDM_SCHEMA_NAME); vocabDaimon.setSource(source); SourceDaimon resultsDaimon = new SourceDaimon(); resultsDaimon.setPriority(1); resultsDaimon.setDaimonType(SourceDaimon.DaimonType.Results); resultsDaimon.setTableQualifier(RESULT_SCHEMA_NAME); resultsDaimon.setSource(source); source.setDaimons(Arrays.asList(cdmDaimon, vocabDaimon, resultsDaimon)); return source; } protected void prepareResultSchema() { prepareSchema(RESULT_SCHEMA_NAME, "results_schema", RESULTS_DDL_FILE_PATHS); } protected void prepareCdmSchema() { prepareSchema(CDM_SCHEMA_NAME, "cdm_database_schema", CDM_DDL_FILE_PATHS); } private void prepareSchema(final String schemaName, final String schemaToken, final Collection<String> schemaPaths) { StringBuilder ddl = new StringBuilder(); ddl.append(String.format("DROP SCHEMA IF EXISTS %s CASCADE;", schemaName)); ddl.append(String.format("CREATE SCHEMA %s;", schemaName)); schemaPaths.forEach(sqlPath -> ddl.append(ResourceHelper.GetResourceAsString(sqlPath)).append("\n")); String resultSql = SqlRender.renderSql(ddl.toString(), new String[]{schemaToken}, new String[]{schemaName}); String ddlSql = SqlTranslate.translateSql(resultSql, DBMSType.POSTGRESQL.getOhdsiDB()); jdbcTemplate.batchUpdate(SqlSplit.splitSql(ddlSql)); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/AbstractShiro.java
src/test/java/org/ohdsi/webapi/test/AbstractShiro.java
package org.ohdsi.webapi.test; import org.apache.shiro.SecurityUtils; import org.apache.shiro.UnavailableSecurityManagerException; import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.support.SubjectThreadState; import org.apache.shiro.util.LifecycleUtils; import org.apache.shiro.util.ThreadState; import org.apache.shiro.mgt.SecurityManager; import org.junit.AfterClass; /** * Abstract test case enabling Shiro in test environments. */ public abstract class AbstractShiro { private static ThreadState subjectThreadState; public AbstractShiro() { } /** * Allows subclasses to set the currently executing {@link Subject} instance. * * @param subject the Subject instance */ protected static void setSubject(Subject subject) { clearSubject(); subjectThreadState = createThreadState(subject); subjectThreadState.bind(); } protected Subject getSubject() { return SecurityUtils.getSubject(); } protected static ThreadState createThreadState(Subject subject) { return new SubjectThreadState(subject); } /** * Clears Shiro's thread state, ensuring the thread remains clean for future test execution. */ protected static void clearSubject() { doClearSubject(); } private static void doClearSubject() { if (subjectThreadState != null) { subjectThreadState.clear(); subjectThreadState = null; } } protected static void setSecurityManager(SecurityManager securityManager) { SecurityUtils.setSecurityManager(securityManager); } protected static SecurityManager getSecurityManager() { return SecurityUtils.getSecurityManager(); } @AfterClass public static void tearDownShiro() { doClearSubject(); try { SecurityManager securityManager = getSecurityManager(); LifecycleUtils.destroy(securityManager); } catch (UnavailableSecurityManagerException e) { //we don't care about this when cleaning up the test environment //(for example, maybe the subclass is a unit test and it didn't // need a SecurityManager instance because it was using only // mock Subject instances) } setSecurityManager(null); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/JobServiceIT.java
src/test/java/org/ohdsi/webapi/test/JobServiceIT.java
package org.ohdsi.webapi.test; import static org.junit.Assert.assertEquals; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.ohdsi.webapi.exampleapplication.ExampleApplicationWithJobService; import org.ohdsi.webapi.job.JobExecutionResource; import org.ohdsi.webapi.job.JobInstanceResource; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.policy.TimeoutRetryPolicy; import org.springframework.retry.support.RetryTemplate; @DatabaseTearDown(value = "/database/empty.xml", type = DatabaseOperation.DELETE_ALL) public class JobServiceIT extends WebApiIT { @Value("${exampleservice.endpoint}") private String endpointExample; @Value("${jobservice.endpoint.job}") private String endpointJob; @Value("${jobservice.endpoint.jobexecution}") private String endpointJobExecution; @Value("${jobservice.endpoint.jobexecution.alt}") private String endpointJobExecutionAlternative; /* The test is ignored, because it is failing with current xstream version com.thoughtworks.xstream:xstream:1.4.19. * see https://github.com/OHDSI/WebAPI/issues/2109 for details. */ @Test @Ignore public void createAndFindJob() { //create/queue job final ResponseEntity<JobExecutionResource> postEntity = getRestTemplate().postForEntity(this.endpointExample, null, JobExecutionResource.class); assertOk(postEntity); final JobExecutionResource postExecution = postEntity.getBody(); assertJobExecution(postExecution); //check on status of job final Map<String, Object> params = new HashMap<String, Object>(); params.put("instanceId", postExecution.getJobInstanceResource().getInstanceId()); params.put("executionId", postExecution.getExecutionId()); //retry until asynchronous job is complete final RetryTemplate template = new RetryTemplate(); final TimeoutRetryPolicy policy = new TimeoutRetryPolicy(); policy.setTimeout(30000L); template.setRetryPolicy(policy); final ResponseEntity<JobExecutionResource> getEntityExecution = template .execute((RetryCallback<ResponseEntity<JobExecutionResource>, IllegalStateException>) context -> { // Do stuff that might fail, e.g. webservice operation final ResponseEntity<JobExecutionResource> getEntityExecution1 = getRestTemplate().getForEntity( JobServiceIT.this.endpointJobExecution, JobExecutionResource.class, params); final JobExecutionResource getExecution = getEntityExecution1.getBody(); assertJobExecution(getExecution); if (!"COMPLETED".equals(getExecution.getStatus())) { JobServiceIT.this.log.debug("Incomplete job, trying again..."); throw new IllegalStateException("Incomplete job"); } return getEntityExecution1; }); //end retry final JobExecutionResource getExecution = getEntityExecution.getBody(); assertJobExecution(getExecution); final ResponseEntity<JobInstanceResource> getEntityInstance = getRestTemplate().getForEntity(this.endpointJob, JobInstanceResource.class, params); assertOk(getEntityInstance); assertJobInstance(getEntityInstance.getBody()); assertEquals(postExecution.getExecutionId(), getExecution.getExecutionId()); //Check alternate endpoint final ResponseEntity<JobExecutionResource> getEntityExecutionAlt = getRestTemplate().getForEntity( this.endpointJobExecutionAlternative, JobExecutionResource.class, params); final JobExecutionResource getExecutionAlt = getEntityExecutionAlt.getBody(); assertJobExecution(getExecution); assertEquals(postExecution.getExecutionId(), getExecutionAlt.getExecutionId()); } private void assertJobInstance(final JobInstanceResource instance) { Assert.assertNotNull(instance.getInstanceId()); assertEquals(ExampleApplicationWithJobService.EXAMPLE_JOB_NAME, instance.getName()); } private void assertOk(final ResponseEntity<?> entity) { assertEquals(entity.getStatusCode(), HttpStatus.OK); } private void assertJobExecution(final JobExecutionResource execution) { Assert.assertNotNull(execution); Assert.assertNotNull(execution.getExecutionId()); Assert.assertNotNull(execution.getJobInstanceResource().getInstanceId()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/CDMResultsServiceIT.java
src/test/java/org/ohdsi/webapi/test/CDMResultsServiceIT.java
package org.ohdsi.webapi.test; import com.odysseusinc.arachne.commons.types.DBMSType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.SqlRender; import org.ohdsi.sql.SqlTranslate; import org.ohdsi.webapi.achilles.service.AchillesCacheService; import org.ohdsi.webapi.cdmresults.service.CDMCacheService; import org.ohdsi.webapi.source.SourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; public class CDMResultsServiceIT extends WebApiIT { private static final String CDM_RESULTS_FILE_PATH = "/database/cdm_results.sql"; @Value("${cdmResultsService.endpoint.conceptRecordCount}") private String conceptRecordCountEndpoint; @Value("${cdmResultsService.endpoint.clearCache}") private String clearCacheEndpoint; @Autowired private SourceRepository sourceRepository; @Autowired private AchillesCacheService achillesService; @Autowired private CDMCacheService cdmCacheService; @Before public void init() throws Exception { truncateTable(String.format("%s.%s", "public", "source")); resetSequence(String.format("%s.%s", "public", "source_sequence")); sourceRepository.saveAndFlush(getCdmSource()); prepareCdmSchema(); prepareResultSchema(); addCDMResults(); } private void addCDMResults() { String resultSql = SqlRender.renderSql(ResourceHelper.GetResourceAsString( CDM_RESULTS_FILE_PATH), new String[] { "results_schema" }, new String[] { RESULT_SCHEMA_NAME }); String sql = SqlTranslate.translateSql(resultSql, DBMSType.POSTGRESQL.getOhdsiDB()); jdbcTemplate.execute(sql); } @Test public void requestConceptRecordCounts_firstTime_returnsResults() { // Arrange List<Integer> conceptIds = Arrays.asList(1); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("sourceName", SOURCE_KEY); List<LinkedHashMap<String, List<Integer>>> list = new ArrayList<>(); @SuppressWarnings("unchecked") Class<List<LinkedHashMap<String, List<Integer>>>> returnClass = (Class<List<LinkedHashMap<String, List<Integer>>>>)list.getClass(); // Act final ResponseEntity<List<LinkedHashMap<String, List<Integer>>>> entity = getRestTemplate().postForEntity(this.conceptRecordCountEndpoint, conceptIds, returnClass, queryParameters ); // Assert assertOK(entity); List<LinkedHashMap<String, List<Integer>>> results = entity.getBody(); assertEquals(1, results.size()); LinkedHashMap<String, List<Integer>> resultHashMap = results.get(0); assertEquals(1, resultHashMap.size()); assertTrue(resultHashMap.containsKey("1")); List<Integer> counts = resultHashMap.get("1"); assertEquals(100, counts.get(0).intValue()); assertEquals(101, counts.get(1).intValue()); assertEquals(102, counts.get(2).intValue()); assertEquals(103, counts.get(3).intValue()); } @Test public void achillesService_clearCache_nothingInCache_doesNothing() { // Arrange // Act achillesService.clearCache(); // Assert String sql = "SELECT COUNT(*) FROM achilles_cache"; Integer count = jdbcTemplate.queryForObject(sql, Integer.class); assertEquals(0, count.intValue()); } @Test public void achillesService_clearCache_somethingInCache_clearsAllRowsForSource() { // Arrange String insertSqlRow1 = "INSERT INTO achilles_cache (id, source_id, cache_name, cache) VALUES (1, 1, 'cache1', 'cache1')"; jdbcTemplate.execute(insertSqlRow1); String insertSqlRow2 = "INSERT INTO achilles_cache (id, source_id, cache_name, cache) VALUES (2, 1, 'cache2', 'cache2')"; jdbcTemplate.execute(insertSqlRow2); // Act achillesService.clearCache(); // Assert String sql = "SELECT COUNT(*) FROM achilles_cache"; Integer count = jdbcTemplate.queryForObject(sql, Integer.class); assertEquals(0, count.intValue()); } @Test public void cdmCacheService_clearCache_nothingInCache_doesNothing() { // Arrange // Act cdmCacheService.clearCache(); // Assert String sql = "SELECT COUNT(*) FROM cdm_cache"; Integer count = jdbcTemplate.queryForObject(sql, Integer.class); assertEquals(0, count.intValue()); } @Test public void cdmCacheService_clearCache_somethingInCache_clearsAllRowsForSource() { // Arrange String insertSqlRow1 = "INSERT INTO cdm_cache (id, concept_id, source_id, record_count, descendant_record_count, person_count, descendant_person_count) VALUES (1, 1, 1, 100, 101, 102, 103)"; jdbcTemplate.execute(insertSqlRow1); String insertSqlRow2 = "INSERT INTO cdm_cache (id, concept_id, source_id, record_count, descendant_record_count, person_count, descendant_person_count) VALUES (2, 2, 1, 200, 201, 202, 203)"; jdbcTemplate.execute(insertSqlRow2); // Act cdmCacheService.clearCache(); // Assert String sql = "SELECT COUNT(*) FROM cdm_cache"; Integer count = jdbcTemplate.queryForObject(sql, Integer.class); assertEquals(0, count.intValue()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/VocabularyServiceIT.java
src/test/java/org/ohdsi/webapi/test/VocabularyServiceIT.java
package org.ohdsi.webapi.test; import com.odysseusinc.arachne.commons.types.DBMSType; import org.junit.Before; import org.junit.Test; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.SqlRender; import org.ohdsi.sql.SqlTranslate; import org.ohdsi.webapi.source.SourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; public class VocabularyServiceIT extends WebApiIT { private static final String CONCEPT_FILE_PATH = "/database/concept.sql"; @Value("${vocabularyservice.endpoint.vocabularies}") private String endpointVocabularies; @Value("${vocabularyservice.endpoint.concept}") private String endpointConcept; @Value("${vocabularyservice.endpoint.domains}") private String endpointDomains; @Autowired private SourceRepository sourceRepository; @Before public void init() throws Exception { truncateTable(String.format("%s.%s", "public", "source")); resetSequence(String.format("%s.%s", "public", "source_sequence")); sourceRepository.saveAndFlush(getCdmSource()); prepareCdmSchema(); prepareResultSchema(); addConcept(); } private void addConcept() { String resultSql = SqlRender.renderSql(ResourceHelper.GetResourceAsString(CONCEPT_FILE_PATH), new String[]{"cdm_database_schema"}, new String[]{CDM_SCHEMA_NAME}); String sql = SqlTranslate.translateSql(resultSql, DBMSType.POSTGRESQL.getOhdsiDB()); jdbcTemplate.execute(sql); } @Test public void canGetConcept() { //Action final ResponseEntity<String> entity = getRestTemplate().getForEntity(this.endpointConcept, String.class); //Assertion assertOK(entity); } @Test public void canGetVocabularies() { //Action final ResponseEntity<String> entity = getRestTemplate().getForEntity(this.endpointVocabularies, String.class); //Assertion assertOK(entity); } @Test public void canGetDomains() { //Action final ResponseEntity<String> entity = getRestTemplate().getForEntity(this.endpointDomains, String.class); //Assertion assertOK(entity); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/ITStarter.java
src/test/java/org/ohdsi/webapi/test/ITStarter.java
package org.ohdsi.webapi.test; import io.zonky.test.db.postgres.embedded.EmbeddedPostgres; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.TestPropertySource; import javax.sql.DataSource; import java.io.IOException; import java.sql.SQLException; @RunWith(Suite.class) @Suite.SuiteClasses({ SecurityIT.class, JobServiceIT.class, CohortAnalysisServiceIT.class, VocabularyServiceIT.class, CDMResultsServiceIT.class }) @TestPropertySource(locations = "/application-test.properties") public class ITStarter extends AbstractShiro { private static EmbeddedPostgres pg; private static final Logger log = LoggerFactory.getLogger(ITStarter.class); @BeforeClass public static void before() throws IOException { if (pg == null) { pg = EmbeddedPostgres.start(); try { System.setProperty("datasource.url", pg.getPostgresDatabase().getConnection().getMetaData().getURL()); } catch (SQLException e) { throw new RuntimeException(e); } System.setProperty("flyway.datasource.url", System.getProperty("datasource.url")); System.setProperty("security.db.datasource.url", System.getProperty("datasource.url")); System.setProperty("security.db.datasource.username", "postgres"); System.setProperty("security.db.datasource.password", "postgres"); System.setProperty("security.db.datasource.schema", "public"); //set up shiro Subject subjectUnderTest = Mockito.mock(Subject.class); SimplePrincipalCollection principalCollection = Mockito.mock(SimplePrincipalCollection.class); Mockito.when(subjectUnderTest.isAuthenticated()).thenReturn(true); Mockito.when(subjectUnderTest.getPrincipals()).thenReturn(principalCollection); Mockito.when(principalCollection.getPrimaryPrincipal()).thenReturn("admin@odysseusinc.com"); //bind the subject to the current thread setSubject(subjectUnderTest); } } public static DataSource getDataSource() { return pg.getPostgresDatabase(); } @AfterClass public static void tearDownSubject() { String callerClassName = Thread.currentThread().getStackTrace()[2].getClassName(); String currentClassName = Thread.currentThread().getStackTrace()[1].getClassName(); if (pg != null && currentClassName.equalsIgnoreCase(callerClassName)) { try { //unbind the subject from the current thread clearSubject(); pg.close(); } catch (Exception ex) { log.warn("Error while stopping the embedded PostgreSQL instance", ex); } } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/CohortAnalysisServiceIT.java
src/test/java/org/ohdsi/webapi/test/CohortAnalysisServiceIT.java
/* * The contents of this file are subject to the Regenstrief Public License * Version 1.0 (the "License"); you may not use this file except in compliance with the License. * Please contact Regenstrief Institute if you would like to obtain a copy of the license. * <p> * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * <p> * Copyright (C) Regenstrief Institute. All Rights Reserved. */ package org.ohdsi.webapi.test; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.cohortanalysis.CohortAnalysisTask; import org.ohdsi.webapi.job.JobExecutionResource; import org.ohdsi.webapi.source.SourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; @DatabaseSetup("/database/cohort.xml") @DatabaseTearDown(value = "/database/empty.xml", type = DatabaseOperation.DELETE_ALL) public class CohortAnalysisServiceIT extends WebApiIT { @Value("${cohortanalysis.endpoint}") private String endpointCohortAnalysis; @Autowired private SourceRepository sourceRepository; @Before public void init() throws Exception { truncateTable(String.format("%s.%s", "public", "source")); resetSequence(String.format("%s.%s", "public", "source_sequence")); sourceRepository.saveAndFlush(getCdmSource()); prepareCdmSchema(); prepareResultSchema(); } @Test public void canCreateAnalysis() { //Arrange CohortAnalysisTask task = new CohortAnalysisTask(); task.setAnalysisIds(Collections.singletonList("0")); task.setCohortDefinitionIds(Collections.singletonList("1")); task.setSourceKey(SOURCE_KEY); //Action final ResponseEntity<JobExecutionResource> entity = getRestTemplate().postForEntity(this.endpointCohortAnalysis, task, JobExecutionResource.class); //Assert assertOK(entity); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/feasibility/StudyInfoTest.java
src/test/java/org/ohdsi/webapi/test/feasibility/StudyInfoTest.java
/* * Copyright 2015 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.test.feasibility; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.junit.Ignore; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.feasibility.FeasibilityStudy; import org.ohdsi.webapi.feasibility.FeasibilityStudyRepository; import org.ohdsi.webapi.feasibility.StudyGenerationInfo; import org.ohdsi.webapi.GenerationStatus; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; /** * * @author Chris Knoll <cknoll@ohdsi.org> */ @SpringBootTest @Rollback public class StudyInfoTest extends AbstractDatabaseTest { @Autowired private FeasibilityStudyRepository studyRepository; @Autowired private SourceRepository sourceRepository; @PersistenceContext protected EntityManager entityManager; @Ignore @Test @Transactional(transactionManager="transactionManager") public void testStudyCRUD() { Source source = new Source(); source.setSourceId(1); FeasibilityStudy newStudy = new FeasibilityStudy(); newStudy.setName("Test Info Study"); newStudy = this.studyRepository.save(newStudy); StudyGenerationInfo info = new StudyGenerationInfo(newStudy, source); // for testing, assume a sourceId of 1 exists. info.setStatus(GenerationStatus.PENDING); newStudy.getStudyGenerationInfoList().add(info); this.studyRepository.save(newStudy); newStudy.getStudyGenerationInfoList().clear(); this.studyRepository.save(newStudy); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/test/feasibility/FeasibilityTests.java
src/test/java/org/ohdsi/webapi/test/feasibility/FeasibilityTests.java
/* * Copyright 2015 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.test.feasibility; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.WebApi; import org.ohdsi.webapi.feasibility.InclusionRule; import org.ohdsi.webapi.feasibility.FeasibilityStudy; import org.ohdsi.webapi.feasibility.FeasibilityStudyRepository; import org.ohdsi.webapi.cohortdefinition.CohortDefinition; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionDetails; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; /** * * @author Chris Knoll <cknoll@ohdsi.org> */ @SpringBootTest(classes = WebApi.class) @Rollback public class FeasibilityTests extends AbstractDatabaseTest { @Autowired private CohortDefinitionRepository cohortDefinitionRepository; @Autowired private FeasibilityStudyRepository studyRepository; @PersistenceContext protected EntityManager entityManager; public int doCreate() { // create a new study, using CohortDefinition:1 as the index rule, and associate 3 inclusion rules. FeasibilityStudy newStudy = new FeasibilityStudy(); CohortDefinition def = new CohortDefinition(); CohortDefinitionDetails defDetails = new CohortDefinitionDetails(); def.setName("Index Rule for Test Study"); this.cohortDefinitionRepository.save(def); // assign details defDetails.setCohortDefinition(def); def.setDetails(defDetails); defDetails.setExpression("{\"DefinitionExpression\": \"{ some epression }\"}"); this.cohortDefinitionRepository.save(def); newStudy.setName("Test Study") .setIndexRule(def); ArrayList<InclusionRule> inclusionRules = new ArrayList<>(); inclusionRules.add(new InclusionRule() .setName("Inclusion Rule 1") .setDescription("Description for Inclusion Rule 1") .setExpression("{\"CriteriaExpression\": \"{Rule 1}\"}")); inclusionRules.add(new InclusionRule() .setName("Inclusion Rule 2") .setDescription("Description for Inclusion Rule 2") .setExpression("{\"CriteriaExpression\": \"{Rule 2}\"}")); inclusionRules.add(new InclusionRule() .setName("Inclusion Rule 3") .setDescription("Description for Inclusion Rule 3") .setExpression("{\"CriteriaExpression\": \"{Rule 3}\"}")); newStudy.setInclusionRules(inclusionRules); studyRepository.save(newStudy); return newStudy.getId(); } public void doUpdate(int id) { FeasibilityStudy updatedStudy = studyRepository.findOneWithDetail(id); CohortDefinition updatedDef = updatedStudy.getIndexRule(); updatedDef.setName("Updated By StudyTest"); // try removing the first inclusion rule List<InclusionRule> updatedRules = updatedStudy.getInclusionRules(); updatedRules.add(new InclusionRule() .setName("Inclusion Rule 4") .setDescription("Description for Inclusion Rule 4") .setExpression("{\"CriteriaExpression\": \"{Rule 4}\"}")); updatedStudy.setInclusionRules(updatedRules); this.studyRepository.save(updatedStudy); } @Test @Transactional(transactionManager="transactionManager") public void testStudyCRUD() { int newStudyId = doCreate(); doUpdate(newStudyId); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/executionengine/service/ScriptExecutionServiceImplTest.java
src/test/java/org/ohdsi/webapi/executionengine/service/ScriptExecutionServiceImplTest.java
package org.ohdsi.webapi.executionengine.service; import static org.mockito.Matchers.*; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.FileHeader; import org.apache.commons.compress.utils.IOUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.ohdsi.webapi.executionengine.entity.AnalysisResultFile; import org.ohdsi.webapi.executionengine.entity.ExecutionEngineAnalysisStatus; import org.ohdsi.webapi.executionengine.entity.ExecutionEngineGenerationEntity; import org.ohdsi.webapi.executionengine.repository.ExecutionEngineGenerationRepository; import org.ohdsi.webapi.shiro.management.datasource.SourceAccessor; @RunWith(MockitoJUnitRunner.class) public class ScriptExecutionServiceImplTest { public static final long EXECUTION_ID = 1L; @Mock private ExecutionEngineGenerationRepository executionEngineGenerationRepository; @Mock private SourceAccessor sourceAccessor; @InjectMocks @Spy private ScriptExecutionServiceImpl scriptExecutionService; @Spy private ExecutionEngineAnalysisStatus executionEngineAnalysisStatus = new ExecutionEngineAnalysisStatus(); @Spy private ExecutionEngineGenerationEntity executionEngineGenerationEntity = new DummyExecutionEngineGenerationEntity(); @Before public void setUp() throws Exception { doReturn(executionEngineAnalysisStatus) .when(executionEngineGenerationEntity) .getAnalysisExecution(); doReturn(Optional.of(executionEngineGenerationEntity)) .when(executionEngineGenerationRepository) .findById(eq(EXECUTION_ID)); doNothing() .when(sourceAccessor) .checkAccess(any()); } @Test public void getExecutionResultWithMultivalueZip() throws Exception { executionEngineAnalysisStatus.setResultFiles(Arrays.asList( createAnalysisResultFile("/analysisresult/stdout.txt"), createAnalysisResultFile("/analysisresult/file1.txt"), createAnalysisResultFile("/analysisresult/multivalue/analysis_result.zip"), createAnalysisResultFile("/analysisresult/multivalue/analysis_result.z01"), createAnalysisResultFile("/analysisresult/multivalue/analysis_result.z02"), createAnalysisResultFile("/analysisresult/multivalue/analysis_result.z03"), createAnalysisResultFile("/analysisresult/multivalue/analysis_result.z04") )); File executionResult = scriptExecutionService.getExecutionResult(EXECUTION_ID); ZipFile zipFile = new ZipFile(executionResult); List<String> fileNamesInZip = ((List<FileHeader>) zipFile.getFileHeaders()).stream().map(FileHeader::getFileName).collect(Collectors.toList()); MatcherAssert.assertThat(fileNamesInZip, Matchers.containsInAnyOrder( "stdout.txt", "file1.txt", "analysis/CohortCharacterization.zip", "analysis/runAnalysis.R", "analysis/.Rhistory")); } @Test public void getExecutionResultWithoutMultivolumeZip() throws Exception { executionEngineAnalysisStatus.setResultFiles(Arrays.asList( createAnalysisResultFile("/analysisresult/stdout.txt"), createAnalysisResultFile("/analysisresult/file1.txt"), createAnalysisResultFile("/analysisresult/analysis_result.zip") )); File executionResult = scriptExecutionService.getExecutionResult(EXECUTION_ID); ZipFile zipFile = new ZipFile(executionResult); List<String> fileNamesInZip = ((List<FileHeader>) zipFile.getFileHeaders()).stream().map(FileHeader::getFileName).collect(Collectors.toList()); MatcherAssert.assertThat(fileNamesInZip, Matchers.containsInAnyOrder( "stdout.txt", "file1.txt", "analysis/", //for some reason getFileHeaders returns directories for a normal zip, and dont for multivalue zip "analysis/CohortCharacterization.zip", "analysis/runAnalysis.R", "analysis/.Rhistory")); } @Test public void getExecutionResultWithoutZip() throws Exception { executionEngineAnalysisStatus.setResultFiles(Arrays.asList( createAnalysisResultFile("/analysisresult/stdout.txt"), createAnalysisResultFile("/analysisresult/file1.txt"), createAnalysisResultFile("/analysisresult/file2.txt") )); File executionResult = scriptExecutionService.getExecutionResult(EXECUTION_ID); ZipFile zipFile = new ZipFile(executionResult); List<String> fileNamesInZip = ((List<FileHeader>) zipFile.getFileHeaders()).stream().map(FileHeader::getFileName).collect(Collectors.toList()); MatcherAssert.assertThat(fileNamesInZip, Matchers.containsInAnyOrder("stdout.txt", "file1.txt", "file2.txt")); } private AnalysisResultFile createAnalysisResultFile(String fileName) throws IOException { AnalysisResultFile analysisResultFile = spy(new AnalysisResultFile()); analysisResultFile.setFileName(new File(fileName).getName()); analysisResultFile.setMediaType("Application"); doReturn(IOUtils.toByteArray(this.getClass().getResourceAsStream(fileName))) .when(analysisResultFile) .getContents(); return analysisResultFile; } public static class DummyExecutionEngineGenerationEntity extends ExecutionEngineGenerationEntity { } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/executionengine/service/AnalysisZipRepackServiceTest.java
src/test/java/org/ohdsi/webapi/executionengine/service/AnalysisZipRepackServiceTest.java
package org.ohdsi.webapi.executionengine.service; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.compress.utils.IOUtils; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.executionengine.entity.AnalysisResultFileContent; import org.ohdsi.webapi.executionengine.entity.ExecutionEngineAnalysisStatus; public class AnalysisZipRepackServiceTest { private AnalysisZipRepackService analysisZipRepackService = new AnalysisZipRepackService(); private AnalysisResultFileContentSensitiveInfoServiceImpl sensitiveInfoService = new AnalysisResultFileContentSensitiveInfoServiceImpl(); private ExecutionEngineAnalysisStatus execution; private List<AnalysisResultFileContent> resultFileContents; @Before public void setUp() throws Exception { execution = new ExecutionEngineAnalysisStatus(); sensitiveInfoService = new AnalysisResultFileContentSensitiveInfoServiceImpl(); sensitiveInfoService.init(); resultFileContents = Arrays.asList( new AnalysisResultFileContent(execution, "analysis_result.zip", "application", getTestArchive("/analysisresult/analysis_result.zip")), new AnalysisResultFileContent(execution, "stdout.txt", "text/plain", getTestArchive("/analysisresult/stdout.txt")) ); } @Test public void processArchivesIsBigEnoughToSplitIntoMultiplyVolumes() { List<AnalysisResultFileContent> analysisRepackResult = analysisZipRepackService.process(this.resultFileContents, 1); List<String> fileNamesAfterRepack = analysisRepackResult.stream().map(f -> f.getAnalysisResultFile().getFileName()).collect(Collectors.toList()); assertThat( fileNamesAfterRepack, Matchers.containsInAnyOrder("analysis_result.zip", "analysis_result.z01", "analysis_result.z02", "analysis_result.z03", "analysis_result.z04", "stdout.txt") ); } @Test public void processArchivesIsNotBigEnoughToSplitIntoMultiplyVolumes() { List<AnalysisResultFileContent> analysisRepackResult = analysisZipRepackService.process(this.resultFileContents, 5); List<String> fileNamesAfterRepack = analysisRepackResult.stream().map(f -> f.getAnalysisResultFile().getFileName()).collect(Collectors.toList()); assertThat( fileNamesAfterRepack, Matchers.containsInAnyOrder("analysis_result.zip", "stdout.txt") ); } @Test public void processThereIsNotArchiveToSplit() throws IOException { resultFileContents = Arrays.asList( new AnalysisResultFileContent(execution, "stdout.txt", "text/plain", getTestArchive("/analysisresult/stdout.txt")), new AnalysisResultFileContent(execution, "file1.txt", "text/plain", getTestArchive("/analysisresult/stdout.txt")), new AnalysisResultFileContent(execution, "file2.txt", "text/plain", getTestArchive("/analysisresult/stdout.txt")) ); List<AnalysisResultFileContent> analysisRepackResult = analysisZipRepackService.process(this.resultFileContents, 5); List<String> fileNamesAfterRepack = analysisRepackResult.stream().map(f -> f.getAnalysisResultFile().getFileName()).collect(Collectors.toList()); assertThat( fileNamesAfterRepack, Matchers.containsInAnyOrder("file1.txt", "file2.txt", "stdout.txt") ); } private byte[] getTestArchive(String file) throws IOException { InputStream resourceAsStream = this.getClass().getResourceAsStream(file); return IOUtils.toByteArray(resourceAsStream); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/check/checker/EstimationCheckerTest.java
src/test/java/org/ohdsi/webapi/check/checker/EstimationCheckerTest.java
package org.ohdsi.webapi.check.checker; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.check.CheckResult; import org.ohdsi.webapi.check.Checker; import org.ohdsi.webapi.check.checker.characterization.CharacterizationChecker; import org.ohdsi.webapi.check.checker.estimation.EstimationChecker; import org.ohdsi.webapi.check.warning.Warning; import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO; import org.ohdsi.webapi.estimation.dto.EstimationDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Optional; import static org.junit.Assert.*; public class EstimationCheckerTest extends BaseCheckerTest { private static final String JSON_VALID = "/check/checker/estimation-valid.json"; private static final String JSON_NO_ANALYSIS_SETTINGS = "/check/checker/estimation-no-analysis-settings.json"; private static final String JSON_POSITIVE_CONTROL_INVALID_VALUES = "/check/checker/estimation-positive-control-invalid-values.json"; @Autowired private EstimationChecker checker; @Test public void checkValid() throws IOException { String json = getJsonFromFile(JSON_VALID); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); Assert.assertEquals(0, result.getWarnings().size()); } @Test public void checkNoSpecification() throws IOException { String json = getJsonFromFile(JSON_VALID); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification - null or empty"); } @Test public void checkNoAnalysisSettings() throws IOException { String json = getJsonFromFile(JSON_NO_ANALYSIS_SETTINGS); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification - null or empty"); } @Test public void checkPositiveControlInvalidWindowStart() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: positive control synthesis :: time-at-risk window start - must be greater or equal to 0"); } @Test public void checkPositiveControlInvalidWindowEnd() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: positive control synthesis :: time-at-risk window end - must be greater or equal to 0"); } @Test public void checkPositiveControlInvalidWashout() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: positive control synthesis :: minimum required continuous observation time - must be greater or equal to 0"); } @Test public void checkPositiveControlInvalidMaxSubjects() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: positive control synthesis :: maximum number of people used to fit an outcome model - must be greater or equal to 0"); } @Test public void checkPositiveControlInvalidRatioBetweenTargetAndInjected() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: positive control synthesis :: allowed ratio between target and injected signal size - must be greater or equal to 0"); } @Test public void checkPositiveControlInvaliOutcomeIdOffset() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: positive control synthesis :: first new outcome ID that is to be created - must be greater or equal to 0"); } @Test public void checkPositiveControlInvalidMinOutcomeCountForModel() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: positive control synthesis :: minimum number of outcome events required to build a model - must be greater or equal to 0"); } @Test public void checkPositiveControlInvalidMinOutcomeCountForInjection() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: positive control synthesis :: minimum number of outcome events required to inject a signal - must be greater or equal to 0"); } @Test public void checkNegativeControlInvalidOccurrenceType() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: negative control outcome :: type of occurrence of the event when selecting from the domain - null or empty"); } @Test public void checkNegativeControlInvalidDetectOnDescendants() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: negative control outcome :: using of descendant concepts for the negative control outcome - null or empty"); } @Test public void checkNegativeControlInvalidDomains() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: negative control outcome :: domains to detect negative control outcomes - null or empty"); } @Test public void checkInvalidNegativeControl() throws IOException { String json = getJsonFromFile(JSON_POSITIVE_CONTROL_INVALID_VALUES); EstimationDTO dto = Utils.deserialize(json, EstimationDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: negative control - invalid"); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/check/checker/CharacterizationCheckerTest.java
src/test/java/org/ohdsi/webapi/check/checker/CharacterizationCheckerTest.java
package org.ohdsi.webapi.check.checker; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.check.CheckResult; import org.ohdsi.webapi.check.Checker; import org.ohdsi.webapi.check.checker.characterization.CharacterizationChecker; import org.ohdsi.webapi.check.checker.tag.helper.TagHelper; import org.ohdsi.webapi.check.warning.Warning; import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO; import org.ohdsi.webapi.service.dto.IRAnalysisDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Optional; public class CharacterizationCheckerTest extends BaseCheckerTest { private static final String JSON_VALID = "/check/checker/characterization-valid.json"; private static final String JSON_NO_COHORTS = "/check/checker/characterization-no-cohorts.json"; private static final String JSON_NO_FEATURE_ANALYSES = "/check/checker/characterization-no-fa.json"; @Autowired private CharacterizationChecker checker; @Test public void checkValid() throws IOException { String json = getJsonFromFile(JSON_VALID); CohortCharacterizationDTO dto = Utils.deserialize(json, CohortCharacterizationDTO.class); Checker<CohortCharacterizationDTO> checker = this.checker; CheckResult result = new CheckResult(checker.check(dto)); Assert.assertEquals(0, result.getWarnings().size()); } @Test public void checkNoCohorts() throws IOException { String json = getJsonFromFile(JSON_NO_COHORTS); CohortCharacterizationDTO dto = Utils.deserialize(json, CohortCharacterizationDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "cohorts - null or empty"); } @Test public void checkNoFeatureAnalyses() throws IOException { String json = getJsonFromFile(JSON_NO_FEATURE_ANALYSES); CohortCharacterizationDTO dto = Utils.deserialize(json, CohortCharacterizationDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "feature analyses - null or empty"); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/check/checker/IRCheckerTest.java
src/test/java/org/ohdsi/webapi/check/checker/IRCheckerTest.java
package org.ohdsi.webapi.check.checker; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.check.CheckResult; import org.ohdsi.webapi.check.Checker; import org.ohdsi.webapi.check.checker.ir.IRChecker; import org.ohdsi.webapi.check.checker.tag.helper.TagHelper; import org.ohdsi.webapi.check.warning.Warning; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.service.dto.IRAnalysisDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Optional; public class IRCheckerTest extends BaseCheckerTest { private static final String JSON_VALID = "/check/checker/ir-valid.json"; private static final String JSON_NO_EXPRESSION = "/check/checker/ir-no-expression.json"; private static final String JSON_NO_COHORTS = "/check/checker/ir-no-cohorts.json"; @Autowired private IRChecker checker; @Test public void checkValid() throws IOException { String json = getJsonFromFile(JSON_VALID); IRAnalysisDTO dto = Utils.deserialize(json, IRAnalysisDTO.class); Checker<IRAnalysisDTO> checker = this.checker; CheckResult result = new CheckResult(checker.check(dto)); Assert.assertEquals(0, result.getWarnings().size()); } @Test public void checkEmptyExpression() throws IOException { String json = getJsonFromFile(JSON_NO_EXPRESSION); IRAnalysisDTO dto = Utils.deserialize(json, IRAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "expression - null or empty"); } @Test public void checkNoOutcomeCohorts() throws IOException { String json = getJsonFromFile(JSON_NO_COHORTS); IRAnalysisDTO dto = Utils.deserialize(json, IRAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "outcome cohorts - null or empty"); } @Test public void checkNoTargetCohorts() throws IOException { String json = getJsonFromFile(JSON_NO_COHORTS); IRAnalysisDTO dto = Utils.deserialize(json, IRAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "target cohorts - null or empty"); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/check/checker/PredictionCheckerTest.java
src/test/java/org/ohdsi/webapi/check/checker/PredictionCheckerTest.java
package org.ohdsi.webapi.check.checker; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.check.CheckResult; import org.ohdsi.webapi.check.Checker; import org.ohdsi.webapi.check.checker.characterization.CharacterizationChecker; import org.ohdsi.webapi.check.checker.pathway.PathwayChecker; import org.ohdsi.webapi.check.checker.prediction.PredictionChecker; import org.ohdsi.webapi.check.warning.Warning; import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.prediction.dto.PredictionAnalysisDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Optional; import static org.junit.Assert.*; public class PredictionCheckerTest extends BaseCheckerTest { private static final String JSON_VALID = "/check/checker/prediction-valid.json"; private static final String JSON_INVALID_VALUES = "/check/checker/prediction-invalid-values.json"; private static final String JSON_NO_VALUES = "/check/checker/prediction-no-values.json"; @Autowired private PredictionChecker checker; @Test public void checkValid() throws IOException { String json = getJsonFromFile(JSON_VALID); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); Checker<PredictionAnalysisDTO> checker = this.checker; CheckResult result = new CheckResult(checker.check(dto)); Assert.assertEquals(0, result.getWarnings().size()); } @Test public void checkNoSpecification() throws IOException { String json = getJsonFromFile(JSON_VALID); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification - null or empty"); } @Test public void checkNoRunPplArgs() throws IOException { String json = getJsonFromFile(JSON_NO_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: settings - null or empty"); } @Test public void checkInvalidRunPplArgsTestFraction() throws IOException { String json = getJsonFromFile(JSON_INVALID_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: settings :: test fraction - must be between 0 and 100"); } @Test public void checkInvalidRunPplArgsMinFraction() throws IOException { String json = getJsonFromFile(JSON_INVALID_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: settings :: minimum covariate fraction - must be greater or equal to 0"); } @Test public void checkNoOutcomeCohorts() throws IOException { String json = getJsonFromFile(JSON_NO_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: outcome cohorts - null or empty"); } @Test public void checkNoTargetCohorts() throws IOException { String json = getJsonFromFile(JSON_NO_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: target cohorts - null or empty"); } @Test public void checkNoModelSettings() throws IOException { String json = getJsonFromFile(JSON_NO_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: model settings - null or empty"); } @Test public void checkInvalidModelSettings() throws IOException { String json = getJsonFromFile(JSON_INVALID_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: model settings - duplicate values"); } @Test public void checkNoCovariateSettings() throws IOException { String json = getJsonFromFile(JSON_NO_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: covariate settings - null or empty"); } @Test public void checkInvalidCovariateSettings() throws IOException { String json = getJsonFromFile(JSON_INVALID_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: covariate settings - duplicate values"); } @Test public void checkNoPopulationSettings() throws IOException { String json = getJsonFromFile(JSON_NO_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: population settings - null or empty"); } @Test public void checkInvalidPopulationSettings() throws IOException { String json = getJsonFromFile(JSON_INVALID_VALUES); PredictionAnalysisDTO dto = Utils.deserialize(json, PredictionAnalysisDTO.class); dto.setSpecification(json); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "specification :: population settings - duplicate values"); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/check/checker/PathwayCheckerTest.java
src/test/java/org/ohdsi/webapi/check/checker/PathwayCheckerTest.java
package org.ohdsi.webapi.check.checker; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.check.CheckResult; import org.ohdsi.webapi.check.Checker; import org.ohdsi.webapi.check.checker.pathway.PathwayChecker; import org.ohdsi.webapi.check.checker.tag.helper.TagHelper; import org.ohdsi.webapi.check.warning.Warning; import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Optional; public class PathwayCheckerTest extends BaseCheckerTest { private static final String JSON_VALID = "/check/checker/pathway-valid.json"; private static final String JSON_INVALID = "/check/checker/pathway-invalid.json"; @Autowired private PathwayChecker checker; @Test public void checkValid() throws IOException { String json = getJsonFromFile(JSON_VALID); PathwayAnalysisDTO dto = Utils.deserialize(json, PathwayAnalysisDTO.class); Checker<PathwayAnalysisDTO> checker = this.checker; CheckResult result = new CheckResult(checker.check(dto)); Assert.assertEquals(0, result.getWarnings().size()); } @Test public void checkNoTargetCohorts() throws IOException { String json = getJsonFromFile(JSON_INVALID); PathwayAnalysisDTO dto = Utils.deserialize(json, PathwayAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "target cohorts - null or empty"); } @Test public void checkNoEventCohorts() throws IOException { String json = getJsonFromFile(JSON_INVALID); PathwayAnalysisDTO dto = Utils.deserialize(json, PathwayAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "event cohorts - null or empty"); } @Test public void checkInvalidMaxPathLength() throws IOException { String json = getJsonFromFile(JSON_INVALID); PathwayAnalysisDTO dto = Utils.deserialize(json, PathwayAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "maximum path length - must be between 1 and 10"); } @Test public void checkInvalidMinCellCount() throws IOException { String json = getJsonFromFile(JSON_INVALID); PathwayAnalysisDTO dto = Utils.deserialize(json, PathwayAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "minimum cell count - must be greater or equal to 0"); } @Test public void checkInvalidCombinationWindow() throws IOException { String json = getJsonFromFile(JSON_INVALID); PathwayAnalysisDTO dto = Utils.deserialize(json, PathwayAnalysisDTO.class); CheckResult result = new CheckResult(checker.check(dto)); checkWarning(result, "combination window - must be greater or equal to 0"); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/check/checker/BaseCheckerTest.java
src/test/java/org/ohdsi/webapi/check/checker/BaseCheckerTest.java
package org.ohdsi.webapi.check.checker; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.check.CheckResult; import org.ohdsi.webapi.check.Checker; import org.ohdsi.webapi.check.checker.characterization.CharacterizationChecker; import org.ohdsi.webapi.check.warning.Warning; import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Optional; public abstract class BaseCheckerTest extends AbstractDatabaseTest { protected String getJsonFromFile(String path) throws IOException { File file = ResourceUtils.getFile(this.getClass().getResource(path)); return FileUtils.readFileToString(file, Charset.defaultCharset()); } protected void checkWarning(CheckResult result, String message) { List<String> warningMessages = result.getWarnings().stream().map(Warning::toMessage).collect(Collectors.toList()); Assert.assertThat(warningMessages, Matchers.hasItem(message)); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/PathwayEntityTest.java
src/test/java/org/ohdsi/webapi/entity/PathwayEntityTest.java
package org.ohdsi.webapi.entity; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.model.CommonEntity; import org.ohdsi.webapi.pathway.PathwayController; import org.ohdsi.webapi.pathway.PathwayService; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.ohdsi.webapi.pathway.repository.PathwayAnalysisEntityRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public class PathwayEntityTest extends AbstractDatabaseTest implements TestCreate, TestCopy<PathwayAnalysisDTO>, TestImport<PathwayAnalysisDTO, PathwayAnalysisExportDTO> { @Autowired protected ConversionService conversionService; @Autowired protected PathwayController pwController; @Autowired protected PathwayAnalysisEntityRepository pwRepository; @Autowired protected PathwayService pwService; private PathwayAnalysisDTO firstSavedDTO; // in JUnit 4 it's impossible to mark methods inside interface with annotations, it was implemented in JUnit 5. After upgrade it's needed // to mark interface methods with @Test, @Before, @After and to remove them from this class @After @Override public void tearDownDB() { pwRepository.deleteAll(); } @Before @Override public void init() throws Exception { TestCreate.super.init(); } @Test @Override public void shouldNotCreateEntityWithDuplicateName() { TestCreate.super.shouldNotCreateEntityWithDuplicateName(); } @Test @Override public void shouldCopyWithUniqueName() throws Exception { TestCopy.super.shouldCopyWithUniqueName(); } @Test @Override public void shouldCopyFromCopy() throws Exception { TestCopy.super.shouldCopyFromCopy(); } @Test @Override public void shouldCopySeveralTimesOriginal() throws Exception { TestCopy.super.shouldCopySeveralTimesOriginal(); } @Test @Override public void shouldCopyOfPartlySameName() throws Exception { TestCopy.super.shouldCopyOfPartlySameName(); } @Test @Override @Transactional public void shouldImportUniqueName() throws Exception { TestImport.super.shouldImportUniqueName(); } @Test @Override @Transactional public void shouldImportWithTheSameName() throws Exception { TestImport.super.shouldImportWithTheSameName(); } @Test @Override @Transactional public void shouldImportWhenEntityWithNameExists() throws Exception { TestImport.super.shouldImportWhenEntityWithNameExists(); } @Override public PathwayAnalysisDTO createCopy(PathwayAnalysisDTO dto) { return pwController.copy(dto.getId()); } @Override public void initFirstDTO() { firstSavedDTO = createEntity(NEW_TEST_ENTITY); } @Override public PathwayAnalysisDTO getFirstSavedDTO() { return firstSavedDTO; } @Override public PathwayAnalysisDTO createEntity(String name) { return createEntity(createAndInitIncomingEntity(name)); } @Override public PathwayAnalysisDTO createEntity(PathwayAnalysisDTO dto) { return pwController.create(dto); } @Override public PathwayAnalysisDTO createAndInitIncomingEntity(String name) { PathwayAnalysisDTO dto = new PathwayAnalysisDTO(); dto.setName(name); dto.setEventCohorts(new ArrayList<>()); dto.setTargetCohorts(new ArrayList<>()); return dto; } @Override public String getConstraintName() { return "uq_pw_name"; } @Override public CommonEntity getEntity(int id) { return pwService.getById(id); } @Override public PathwayAnalysisExportDTO getExportEntity(CommonEntity entity) { return conversionService.convert(entity, PathwayAnalysisExportDTO.class); } @Override public PathwayAnalysisDTO doImport(PathwayAnalysisExportDTO dto) { return pwController.importAnalysis(dto); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/EntityMethods.java
src/test/java/org/ohdsi/webapi/entity/EntityMethods.java
package org.ohdsi.webapi.entity; import org.ohdsi.webapi.CommonDTO; import org.springframework.test.context.TestContextManager; public interface EntityMethods<T extends CommonDTO> { void initFirstDTO() throws Exception; T createEntity(String name) throws Exception; default void init() throws Exception { TestContextManager testContextManager = new TestContextManager(getClass()); testContextManager.prepareTestInstance(this); initFirstDTO(); } void tearDownDB(); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/ConceptSetEntityTest.java
src/test/java/org/ohdsi/webapi/entity/ConceptSetEntityTest.java
package org.ohdsi.webapi.entity; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.conceptset.ConceptSetRepository; import org.ohdsi.webapi.service.ConceptSetService; import org.ohdsi.webapi.service.dto.ConceptSetDTO; import org.springframework.beans.factory.annotation.Autowired; import static org.ohdsi.webapi.service.ConceptSetService.COPY_NAME; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public class ConceptSetEntityTest extends AbstractDatabaseTest implements TestCreate, TestCopy<ConceptSetDTO> { @Autowired protected ConceptSetService csService; @Autowired protected ConceptSetRepository csRepository; private ConceptSetDTO firstSavedDTO; // in JUnit 4 it's impossible to mark methods inside interface with annotations, it was implemented in JUnit 5. After upgrade it's needed // to mark interface methods with @Test, @Before, @After and to remove them from this class @After @Override public void tearDownDB() { csRepository.deleteAll(); } @Before @Override public void init() throws Exception { TestCreate.super.init(); } @Test @Override public void shouldNotCreateEntityWithDuplicateName() { TestCreate.super.shouldNotCreateEntityWithDuplicateName(); } @Test @Override public void shouldCopyWithUniqueName() throws Exception { TestCopy.super.shouldCopyWithUniqueName(); } @Test @Override public void shouldCopyFromCopy() throws Exception { TestCopy.super.shouldCopyFromCopy(); } @Test @Override public void shouldCopySeveralTimesOriginal() throws Exception { TestCopy.super.shouldCopySeveralTimesOriginal(); } @Test @Override public void shouldCopyOfPartlySameName() throws Exception { TestCopy.super.shouldCopyOfPartlySameName(); } @Override public ConceptSetDTO createCopy(ConceptSetDTO dto) { dto.setName(csService.getNameForCopy(dto.getId()).get(COPY_NAME)); return csService.createConceptSet(dto); } @Override public void initFirstDTO() { firstSavedDTO = createEntity(NEW_TEST_ENTITY); } @Override public ConceptSetDTO getFirstSavedDTO() { return firstSavedDTO; } @Override public ConceptSetDTO createEntity(String name) { ConceptSetDTO dto = new ConceptSetDTO(); dto.setName(name); return csService.createConceptSet(dto); } @Override public String getConstraintName() { return "uq_cs_name"; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/CohortDefinitionEntityTest.java
src/test/java/org/ohdsi/webapi/entity/CohortDefinitionEntityTest.java
package org.ohdsi.webapi.entity; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO; import org.ohdsi.webapi.service.CohortDefinitionService; import org.springframework.beans.factory.annotation.Autowired; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public class CohortDefinitionEntityTest extends AbstractDatabaseTest implements TestCreate, TestCopy<CohortDTO> { @Autowired private CohortDefinitionService cdService; @Autowired protected CohortDefinitionRepository cdRepository; private CohortDTO firstSavedDTO; // in JUnit 4 it's impossible to mark methods inside interface with annotations, it was implemented in JUnit 5. After upgrade it's needed // to mark interface methods with @Test, @Before, @After and to remove them from this class @After @Override public void tearDownDB() { cdRepository.deleteAll(); } @Before @Override public void init() throws Exception { TestCreate.super.init(); } @Test @Override public void shouldNotCreateEntityWithDuplicateName() { TestCreate.super.shouldNotCreateEntityWithDuplicateName(); } @Test @Override public void shouldCopyWithUniqueName() throws Exception { TestCopy.super.shouldCopyWithUniqueName(); } @Test @Override public void shouldCopyFromCopy() throws Exception { TestCopy.super.shouldCopyFromCopy(); } @Test @Override public void shouldCopySeveralTimesOriginal() throws Exception { TestCopy.super.shouldCopySeveralTimesOriginal(); } @Test @Override public void shouldCopyOfPartlySameName() throws Exception { TestCopy.super.shouldCopyOfPartlySameName(); } @Override public CohortDTO createCopy(CohortDTO dto) { return cdService.copy(dto.getId()); } @Override public void initFirstDTO() { firstSavedDTO = createEntity(NEW_TEST_ENTITY); } @Override public CohortDTO getFirstSavedDTO() { return firstSavedDTO; } @Override public String getConstraintName() { return "uq_cd_name"; } @Override public CohortDTO createEntity(String name) { CohortDTO dto = new CohortDTO(); dto.setName(name); return cdService.createCohortDefinition(dto); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/TestImport.java
src/test/java/org/ohdsi/webapi/entity/TestImport.java
package org.ohdsi.webapi.entity; import org.ohdsi.webapi.CommonDTO; import org.ohdsi.webapi.model.CommonEntity; import static org.junit.Assert.assertEquals; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; import static org.ohdsi.webapi.test.TestConstants.SOME_UNIQUE_TEST_NAME; public interface TestImport<T extends CommonDTO, U extends CommonDTO> extends EntityMethods { CommonEntity getEntity(int id); U getExportEntity(CommonEntity entity); T doImport(U dto) throws Exception; T createAndInitIncomingEntity(String name); T createEntity(T dto) throws Exception; T getFirstSavedDTO(); default void shouldImportUniqueName() throws Exception { //Arrange CommonEntity savedEntity = getEntity(getFirstSavedDTO().getId().intValue()); U exportedEntity = getExportEntity(savedEntity); exportedEntity.setName(SOME_UNIQUE_TEST_NAME); //Action T firstImport = doImport(exportedEntity); //Assert assertEquals(SOME_UNIQUE_TEST_NAME, firstImport.getName()); } default void shouldImportWithTheSameName() throws Exception { //Arrange CommonEntity savedEntity = getEntity(getFirstSavedDTO().getId().intValue()); U exportDTO = getExportEntity(savedEntity); //Action T firstImport = doImport(exportDTO); //reset dto exportDTO = getExportEntity(savedEntity); T secondImport = doImport(exportDTO); //Assert assertEquals(NEW_TEST_ENTITY + " (1)", firstImport.getName()); assertEquals(NEW_TEST_ENTITY + " (2)", secondImport.getName()); } default void shouldImportWhenEntityWithNameExists() throws Exception { //Arrange CommonEntity firstCreatedEntity = getEntity(getFirstSavedDTO().getId().intValue()); U firstExportDTO = getExportEntity(firstCreatedEntity); T secondIncomingEntity = createAndInitIncomingEntity(NEW_TEST_ENTITY + " (1)"); //save "New test entity (1)" to DB createEntity(secondIncomingEntity); T thirdIncomingEntity = createAndInitIncomingEntity(NEW_TEST_ENTITY + " (1) (2)"); //save "New test entity (1) (2)" to DB T thirdSavedDTO = createEntity(thirdIncomingEntity); CommonEntity thirdCreatedEntity = getEntity(thirdSavedDTO.getId().intValue()); U thirdExportDTO = getExportEntity(thirdCreatedEntity); //Action //import of "New test entity" T firstImport = doImport(firstExportDTO); //import of "New test entity (1) (2)" T secondImport = doImport(thirdExportDTO); T fourthIncomingEntity = createAndInitIncomingEntity(NEW_TEST_ENTITY + " (1) (2) (2)"); //save "New test entity (1) (2) (2)" to DB createEntity(fourthIncomingEntity); //reset dto thirdExportDTO = getExportEntity(thirdCreatedEntity); //import of "New test entity (1) (2)" T thirdImport = doImport(thirdExportDTO); //Assert assertEquals(NEW_TEST_ENTITY + " (2)", firstImport.getName()); assertEquals(NEW_TEST_ENTITY + " (1) (2) (1)", secondImport.getName()); assertEquals(NEW_TEST_ENTITY + " (1) (2) (3)", thirdImport.getName()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/EstimationEntityTest.java
src/test/java/org/ohdsi/webapi/entity/EstimationEntityTest.java
package org.ohdsi.webapi.entity; import com.odysseusinc.arachne.commons.types.DBMSType; import com.odysseusinc.arachne.execution_engine_common.api.v1.dto.KerberosAuthMechanism; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.analysis.AnalysisCohortDefinition; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionDetailsRepository; import org.ohdsi.webapi.estimation.Estimation; import org.ohdsi.webapi.estimation.EstimationController; import org.ohdsi.webapi.estimation.EstimationService; import org.ohdsi.webapi.estimation.dto.EstimationDTO; import org.ohdsi.webapi.estimation.repository.EstimationRepository; import org.ohdsi.webapi.estimation.specification.EstimationAnalysisImpl; import org.ohdsi.webapi.model.CommonEntity; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.source.SourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.ohdsi.analysis.estimation.design.EstimationTypeEnum.COMPARATIVE_COHORT_ANALYSIS; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public class EstimationEntityTest extends AbstractDatabaseTest implements TestCreate, TestCopy<EstimationDTO>, TestImport<EstimationDTO, EstimationAnalysisImpl> { @Autowired protected ConversionService conversionService; @Autowired protected EstimationController pleController; @Autowired protected EstimationRepository pleRepository; @Autowired protected EstimationService pleService; @Autowired protected CohortDefinitionDetailsRepository cdRepository; @Autowired private SourceRepository sourceRepository; private EstimationDTO firstSavedDTO; private static String PLE_SPECIFICATION; @BeforeClass public static void setPleSpecification() throws IOException { File ple_spec = new File("src/test/resources/ple-specification.json"); PLE_SPECIFICATION = FileUtils.readFileToString(ple_spec, StandardCharsets.UTF_8); } // in JUnit 4 it's impossible to mark methods inside interface with annotations, it was implemented in JUnit 5. After upgrade it's needed // to mark interface methods with @Test, @Before, @After and to remove them from this class @After @Override public void tearDownDB() { pleRepository.deleteAll(); } @Before @Override public void init() throws Exception { TestCreate.super.init(); truncateTable(String.format("%s.%s", "public", "source")); resetSequence(String.format("%s.%s", "public", "source_sequence")); sourceRepository.saveAndFlush(getCdmSource()); } @Test @Override public void shouldNotCreateEntityWithDuplicateName() { TestCreate.super.shouldNotCreateEntityWithDuplicateName(); } @Test @Override public void shouldCopyWithUniqueName() throws Exception { TestCopy.super.shouldCopyWithUniqueName(); } @Test @Override public void shouldCopyFromCopy() throws Exception { TestCopy.super.shouldCopyFromCopy(); } @Test @Override public void shouldCopySeveralTimesOriginal() throws Exception { TestCopy.super.shouldCopySeveralTimesOriginal(); } @Test @Override public void shouldCopyOfPartlySameName() throws Exception { TestCopy.super.shouldCopyOfPartlySameName(); } @Test @Override public void shouldImportUniqueName() throws Exception { TestImport.super.shouldImportUniqueName(); } @Test @Override public void shouldImportWithTheSameName() throws Exception { TestImport.super.shouldImportWithTheSameName(); } @Test @Override public void shouldImportWhenEntityWithNameExists() throws Exception { TestImport.super.shouldImportWhenEntityWithNameExists(); } @Test public void shouldImportWhenHashcodesOfCDsAndCSsAreDifferent() throws Exception { //Arrange File pleFile = new File("src/test/resources/ple-example-for-import.json"); String pleStr = FileUtils.readFileToString(pleFile, StandardCharsets.UTF_8); EstimationAnalysisImpl ple = Utils.deserialize(pleStr, EstimationAnalysisImpl.class); //Action pleController.importAnalysis(ple); cdRepository.findAll().forEach(cd -> { cd.setExpression(cd.getExpression().replaceAll("5.0.0", "6.0.0")); cdRepository.save(cd); }); EstimationDTO importedEs = pleController.importAnalysis(ple); //Assert assertEquals("Comparative effectiveness of ACE inhibitors vs Thiazide diuretics as first-line monotherapy for hypertension (1)", pleController.getAnalysis(importedEs.getId()).getName()); EstimationAnalysisImpl importedExpression = pleService.getAnalysisExpression(importedEs.getId()); List<AnalysisCohortDefinition> cds = importedExpression.getCohortDefinitions(); assertEquals("New users of ACE inhibitors as first-line monotherapy for hypertension (1)", cds.get(0).getName()); assertEquals("New users of Thiazide-like diuretics as first-line monotherapy for hypertension (1)", cds.get(1).getName()); assertEquals("Acute myocardial infarction events (1)", cds.get(2).getName()); assertEquals("Angioedema events (1)", cds.get(3).getName()); } @Override public EstimationDTO createCopy(EstimationDTO dto) throws Exception { return pleController.copy(dto.getId()); } @Override public void initFirstDTO() throws Exception { firstSavedDTO = createEntity(NEW_TEST_ENTITY); } @Override public EstimationDTO getFirstSavedDTO() { return firstSavedDTO; } @Override public EstimationDTO createEntity(String name) throws Exception { return createEntity(createAndInitIncomingEntity(name)); } @Override public EstimationDTO createEntity(EstimationDTO dto) throws Exception { Estimation estimation = createEstimation(dto.getName()); return pleController.createEstimation(estimation); } @Override public EstimationDTO createAndInitIncomingEntity(String name) { Estimation estimation = createEstimation(name); return conversionService.convert(estimation, EstimationDTO.class); } private Estimation createEstimation(String name) { Estimation estimation = new Estimation(); estimation.setName(name); estimation.setType(COMPARATIVE_COHORT_ANALYSIS); estimation.setSpecification(PLE_SPECIFICATION); return estimation; } @Override public String getConstraintName() { return "uq_es_name"; } @Override public CommonEntity getEntity(int id) { return pleService.getAnalysis(id); } @Override public EstimationAnalysisImpl getExportEntity(CommonEntity entity) { return pleController.exportAnalysis(entity.getId().intValue()); } @Override public EstimationDTO doImport(EstimationAnalysisImpl dto) throws Exception { return pleController.importAnalysis(dto); } private Source getCdmSource() throws SQLException { Source source = new Source(); source.setSourceName("Embedded PG"); source.setSourceKey("Embedded_PG"); source.setSourceDialect(DBMSType.POSTGRESQL.getOhdsiDB()); source.setSourceConnection(getDataSource().getConnection().getMetaData().getURL()); source.setUsername("postgres"); source.setPassword("postgres"); source.setKrbAuthMethod(KerberosAuthMechanism.PASSWORD); SourceDaimon cdmDaimon = new SourceDaimon(); cdmDaimon.setPriority(1); cdmDaimon.setDaimonType(SourceDaimon.DaimonType.CDM); cdmDaimon.setTableQualifier("cdm"); cdmDaimon.setSource(source); SourceDaimon vocabDaimon = new SourceDaimon(); vocabDaimon.setPriority(1); vocabDaimon.setDaimonType(SourceDaimon.DaimonType.Vocabulary); vocabDaimon.setTableQualifier("cdm"); vocabDaimon.setSource(source); SourceDaimon resultsDaimon = new SourceDaimon(); resultsDaimon.setPriority(1); resultsDaimon.setDaimonType(SourceDaimon.DaimonType.Results); resultsDaimon.setTableQualifier("results"); resultsDaimon.setSource(source); source.setDaimons(Arrays.asList(cdmDaimon, vocabDaimon, resultsDaimon)); return source; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/CCEntityTest.java
src/test/java/org/ohdsi/webapi/entity/CCEntityTest.java
package org.ohdsi.webapi.entity; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.cohortcharacterization.CcController; import org.ohdsi.webapi.cohortcharacterization.CcService; import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity; import org.ohdsi.webapi.cohortcharacterization.dto.CcExportDTO; import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO; import org.ohdsi.webapi.cohortcharacterization.repository.CcRepository; import org.ohdsi.webapi.model.CommonEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.transaction.annotation.Transactional; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public class CCEntityTest extends AbstractDatabaseTest implements TestCreate, TestCopy<CohortCharacterizationDTO>, TestImport<CohortCharacterizationDTO, CcExportDTO> { @Autowired protected ConversionService conversionService; @Autowired protected CcController ccController; @Autowired protected CcRepository ccRepository; @Autowired protected CcService ccService; private CohortCharacterizationDTO firstSavedDTO; // in JUnit 4 it's impossible to mark methods inside interface with annotations, it was implemented in JUnit 5. After upgrade it's needed // to mark interface methods with @Test, @Before, @After and to remove them from this class @Before @Override public void init() throws Exception { TestCreate.super.init(); } @After @Override public void tearDownDB() { ccRepository.deleteAll(); } @Test @Override public void shouldNotCreateEntityWithDuplicateName() { TestCreate.super.shouldNotCreateEntityWithDuplicateName(); } @Test @Override public void shouldCopyWithUniqueName() throws Exception { TestCopy.super.shouldCopyWithUniqueName(); } @Test @Override public void shouldCopyFromCopy() throws Exception { TestCopy.super.shouldCopyFromCopy(); } @Test @Override public void shouldCopySeveralTimesOriginal() throws Exception { TestCopy.super.shouldCopySeveralTimesOriginal(); } @Test @Override public void shouldCopyOfPartlySameName() throws Exception { TestCopy.super.shouldCopyOfPartlySameName(); } @Test @Override @Transactional public void shouldImportUniqueName() throws Exception { TestImport.super.shouldImportUniqueName(); } @Test @Override @Transactional public void shouldImportWithTheSameName() throws Exception { TestImport.super.shouldImportWithTheSameName(); } @Test @Override @Transactional public void shouldImportWhenEntityWithNameExists() throws Exception { TestImport.super.shouldImportWhenEntityWithNameExists(); } @Override public CohortCharacterizationDTO createCopy(CohortCharacterizationDTO dto) { return ccController.copy(dto.getId()); } @Override public void initFirstDTO() { firstSavedDTO = createEntity(NEW_TEST_ENTITY); } @Override public CohortCharacterizationDTO getFirstSavedDTO() { return firstSavedDTO; } @Override public String getConstraintName() { return "uq_cc_name"; } @Override public CohortCharacterizationDTO createEntity(String name) { return createEntity(createAndInitIncomingEntity(name)); } @Override public CohortCharacterizationDTO createEntity(CohortCharacterizationDTO dto) { return ccController.create(dto); } @Override public CohortCharacterizationDTO createAndInitIncomingEntity(String name) { CohortCharacterizationDTO dto = new CohortCharacterizationDTO(); dto.setName(name); return dto; } @Override public CohortCharacterizationEntity getEntity(int id) { return ccService.findByIdWithLinkedEntities((long) id); } @Override public CcExportDTO getExportEntity(CommonEntity entity) { return conversionService.convert(entity, CcExportDTO.class); } @Override public CohortCharacterizationDTO doImport(CcExportDTO dto) { return ccController.doImport(dto); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/IREntityTest.java
src/test/java/org/ohdsi/webapi/entity/IREntityTest.java
package org.ohdsi.webapi.entity; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.ircalc.IncidenceRateAnalysisRepository; import org.ohdsi.webapi.service.IRAnalysisResource; import org.ohdsi.webapi.service.dto.IRAnalysisDTO; import org.springframework.beans.factory.annotation.Autowired; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public class IREntityTest extends AbstractDatabaseTest implements TestCreate, TestCopy<IRAnalysisDTO> { @Autowired protected IRAnalysisResource irAnalysisResource; @Autowired protected IncidenceRateAnalysisRepository irRepository; private IRAnalysisDTO firstSavedDTO; // in JUnit 4 it's impossible to mark methods inside interface with annotations, it was implemented in JUnit 5. After upgrade it's needed // to mark interface methods with @Test, @Before, @After and to remove them from this class @After @Override public void tearDownDB() { irRepository.deleteAll(); } @Before @Override public void init() throws Exception { TestCreate.super.init(); } @Test @Override public void shouldNotCreateEntityWithDuplicateName() { TestCreate.super.shouldNotCreateEntityWithDuplicateName(); } @Test @Override public void shouldCopyWithUniqueName() throws Exception { TestCopy.super.shouldCopyWithUniqueName(); } @Test @Override public void shouldCopyFromCopy() throws Exception { TestCopy.super.shouldCopyFromCopy(); } @Test @Override public void shouldCopySeveralTimesOriginal() throws Exception { TestCopy.super.shouldCopySeveralTimesOriginal(); } @Test @Override public void shouldCopyOfPartlySameName() throws Exception { TestCopy.super.shouldCopyOfPartlySameName(); } @Override public IRAnalysisDTO createCopy(IRAnalysisDTO dto) { return irAnalysisResource.copy(dto.getId()); } @Override public void initFirstDTO() { firstSavedDTO = createEntity(NEW_TEST_ENTITY); } @Override public IRAnalysisDTO getFirstSavedDTO() { return firstSavedDTO; } @Override public IRAnalysisDTO createEntity(String name) { IRAnalysisDTO dto = new IRAnalysisDTO(); dto.setName(name); return irAnalysisResource.createAnalysis(dto); } @Override public String getConstraintName() { return "uq_ir_name"; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/TestCopy.java
src/test/java/org/ohdsi/webapi/entity/TestCopy.java
package org.ohdsi.webapi.entity; import org.ohdsi.webapi.CommonDTO; import static org.junit.Assert.assertEquals; import static org.ohdsi.webapi.test.TestConstants.COPY_PREFIX; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public interface TestCopy<T extends CommonDTO> extends EntityMethods { T createCopy(T dto) throws Exception; T createEntity(String name) throws Exception; T getFirstSavedDTO(); default void shouldCopyWithUniqueName() throws Exception { //Action T copy = createCopy(getFirstSavedDTO()); //Assert assertEquals(COPY_PREFIX + NEW_TEST_ENTITY, copy.getName()); } default void shouldCopyFromCopy() throws Exception { //Action T firstCopy = createCopy(getFirstSavedDTO()); T secondCopy = createCopy(firstCopy); //Assert assertEquals(COPY_PREFIX + COPY_PREFIX + NEW_TEST_ENTITY, secondCopy.getName()); } default void shouldCopySeveralTimesOriginal() throws Exception { //Action T firstCopy = createCopy(getFirstSavedDTO()); T secondCopy = createCopy(getFirstSavedDTO()); //Assert assertEquals(COPY_PREFIX + NEW_TEST_ENTITY, firstCopy.getName()); assertEquals(COPY_PREFIX + NEW_TEST_ENTITY + " (1)", secondCopy.getName()); } default void shouldCopyOfPartlySameName() throws Exception { String firstName = "abcde, abc, abc"; String secondName = "abcde (1), abcde, abcde (2)"; //Arrange createEntity(COPY_PREFIX + firstName); T savedDTO = createEntity(secondName); //Action T copy = createCopy(savedDTO); //Assert assertEquals(COPY_PREFIX + secondName, copy.getName()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/PredictionEntityTest.java
src/test/java/org/ohdsi/webapi/entity/PredictionEntityTest.java
package org.ohdsi.webapi.entity; import com.odysseusinc.arachne.commons.types.DBMSType; import com.odysseusinc.arachne.execution_engine_common.api.v1.dto.KerberosAuthMechanism; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.model.CommonEntity; import org.ohdsi.webapi.prediction.PredictionAnalysis; import org.ohdsi.webapi.prediction.PredictionController; import org.ohdsi.webapi.prediction.PredictionService; import org.ohdsi.webapi.prediction.dto.PredictionAnalysisDTO; import org.ohdsi.webapi.prediction.repository.PredictionAnalysisRepository; import org.ohdsi.webapi.prediction.specification.PatientLevelPredictionAnalysisImpl; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.source.SourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.Arrays; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public class PredictionEntityTest extends AbstractDatabaseTest implements TestCreate, TestCopy<PredictionAnalysisDTO>, TestImport<PredictionAnalysisDTO, PatientLevelPredictionAnalysisImpl> { @Autowired protected ConversionService conversionService; @Autowired protected PredictionController plpController; @Autowired protected PredictionAnalysisRepository plpRepository; @Autowired private SourceRepository sourceRepository; @Autowired protected PredictionService plpService; private PredictionAnalysisDTO firstSavedDTO; private static String PLP_SPECIFICATION; @BeforeClass public static void setPlpSpecification() throws IOException { File plp_spec = new File("src/test/resources/plp-specification.json"); PLP_SPECIFICATION = FileUtils.readFileToString(plp_spec, StandardCharsets.UTF_8); } // in JUnit 4 it's impossible to mark methods inside interface with annotations, it was implemented in JUnit 5. After upgrade it's needed // to mark interface methods with @Test, @Before, @After and to remove them from this class @After @Override public void tearDownDB() { plpRepository.deleteAll(); } @Before @Override public void init() throws Exception { TestCreate.super.init(); truncateTable(String.format("%s.%s", "public", "source")); resetSequence(String.format("%s.%s", "public", "source_sequence")); sourceRepository.saveAndFlush(getCdmSource()); } @Test @Override public void shouldNotCreateEntityWithDuplicateName() { TestCreate.super.shouldNotCreateEntityWithDuplicateName(); } @Test @Override public void shouldCopyWithUniqueName() throws Exception { TestCopy.super.shouldCopyWithUniqueName(); } @Test @Override public void shouldCopyFromCopy() throws Exception { TestCopy.super.shouldCopyFromCopy(); } @Test @Override public void shouldCopySeveralTimesOriginal() throws Exception { TestCopy.super.shouldCopySeveralTimesOriginal(); } @Test @Override public void shouldCopyOfPartlySameName() throws Exception { TestCopy.super.shouldCopyOfPartlySameName(); } @Test @Override public void shouldImportUniqueName() throws Exception { TestImport.super.shouldImportUniqueName(); } @Test @Override public void shouldImportWithTheSameName() throws Exception { TestImport.super.shouldImportWithTheSameName(); } @Test @Override public void shouldImportWhenEntityWithNameExists() throws Exception { TestImport.super.shouldImportWhenEntityWithNameExists(); } @Override public PredictionAnalysisDTO createCopy(PredictionAnalysisDTO dto) { return plpController.copy(dto.getId()); } @Override public void initFirstDTO() { firstSavedDTO = createEntity(NEW_TEST_ENTITY); } @Override public PredictionAnalysisDTO getFirstSavedDTO() { return firstSavedDTO; } @Override public PredictionAnalysisDTO createEntity(String name) { return createEntity(createAndInitIncomingEntity(name)); } @Override public PredictionAnalysisDTO createEntity(PredictionAnalysisDTO dto) { PredictionAnalysis prediction = createPrediction(dto.getName()); return plpController.createAnalysis(prediction); } @Override public PredictionAnalysisDTO createAndInitIncomingEntity(String name) { PredictionAnalysis predictionAnalysis = createPrediction(name); return conversionService.convert(predictionAnalysis, PredictionAnalysisDTO.class); } private PredictionAnalysis createPrediction(String name) { PredictionAnalysis prediction = new PredictionAnalysis(); prediction.setName(name); prediction.setSpecification(PLP_SPECIFICATION); return prediction; } @Override public String getConstraintName() { return "uq_pd_name"; } @Override public CommonEntity getEntity(int id) { return plpService.getAnalysis(id); } @Override public PatientLevelPredictionAnalysisImpl getExportEntity(CommonEntity entity) { return plpController.exportAnalysis(entity.getId().intValue()); } @Override public PredictionAnalysisDTO doImport(PatientLevelPredictionAnalysisImpl dto) throws Exception { return plpController.importAnalysis(dto); } private Source getCdmSource() throws SQLException { Source source = new Source(); source.setSourceName("Embedded PG"); source.setSourceKey("Embedded_PG"); source.setSourceDialect(DBMSType.POSTGRESQL.getOhdsiDB()); source.setSourceConnection(getDataSource().getConnection().getMetaData().getURL()); source.setUsername("postgres"); source.setPassword("postgres"); source.setKrbAuthMethod(KerberosAuthMechanism.PASSWORD); SourceDaimon cdmDaimon = new SourceDaimon(); cdmDaimon.setPriority(1); cdmDaimon.setDaimonType(SourceDaimon.DaimonType.CDM); cdmDaimon.setTableQualifier("cdm"); cdmDaimon.setSource(source); SourceDaimon vocabDaimon = new SourceDaimon(); vocabDaimon.setPriority(1); vocabDaimon.setDaimonType(SourceDaimon.DaimonType.Vocabulary); vocabDaimon.setTableQualifier("cdm"); vocabDaimon.setSource(source); SourceDaimon resultsDaimon = new SourceDaimon(); resultsDaimon.setPriority(1); resultsDaimon.setDaimonType(SourceDaimon.DaimonType.Results); resultsDaimon.setTableQualifier("results"); resultsDaimon.setSource(source); source.setDaimons(Arrays.asList(cdmDaimon, vocabDaimon, resultsDaimon)); return source; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/entity/TestCreate.java
src/test/java/org/ohdsi/webapi/entity/TestCreate.java
package org.ohdsi.webapi.entity; import org.apache.commons.lang3.exception.ExceptionUtils; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.ohdsi.webapi.test.TestConstants.NEW_TEST_ENTITY; public interface TestCreate extends EntityMethods { String getConstraintName(); default void shouldNotCreateEntityWithDuplicateName() { //Action try { createEntity(NEW_TEST_ENTITY); fail(); } catch (Exception e) { //Assert assertTrue(ExceptionUtils.getRootCauseMessage(e).contains(getConstraintName())); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/tagging/CohortTaggingTest.java
src/test/java/org/ohdsi/webapi/tagging/CohortTaggingTest.java
package org.ohdsi.webapi.tagging; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.cohortdefinition.dto.CohortDTO; import org.ohdsi.webapi.cohortdefinition.dto.CohortRawDTO; import org.ohdsi.webapi.service.CohortDefinitionService; import org.ohdsi.webapi.tag.domain.Tag; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; public class CohortTaggingTest extends BaseTaggingTest<CohortDTO, Integer> { private static final String JSON_PATH = "/tagging/cohort.json"; @Autowired private CohortDefinitionService service; @Autowired private CohortDefinitionRepository repository; @Override public void doCreateInitialData() throws IOException { String expression = getExpression(getExpressionPath()); CohortDTO dto = deserializeExpression(expression); initialDTO = service.createCohortDefinition(dto); } @Override protected CohortDTO doCopyData(CohortDTO def) { return service.copy(def.getId()); } private CohortDTO deserializeExpression(String expression) { CohortRawDTO rawDTO = new CohortRawDTO(); rawDTO.setExpression(expression); CohortDTO dto = conversionService.convert(rawDTO, CohortDTO.class); dto.setName("test dto name"); dto.setDescription("test dto description"); return dto; } @Override protected void doClear() { repository.deleteAll(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected void assignTag(Integer id, boolean isPermissionProtected) { service.assignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignTag(Integer id, boolean isPermissionProtected) { service.unassignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void assignProtectedTag(Integer id, boolean isPermissionProtected) { service.assignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignProtectedTag(Integer id, boolean isPermissionProtected) { service.unassignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected CohortDTO getDTO(Integer id) { return service.getCohortDefinition(id); } @Override protected Integer getId(CohortDTO dto) { return dto.getId(); } @Override protected void assignTags(Integer id, Tag...tags) { for (Tag tag : tags) { service.assignTag(id, tag.getId()); } } @Override protected List<CohortDTO> getDTOsByTag(List<String> tagNames) { TagNameListRequestDTO requestDTO = new TagNameListRequestDTO(); requestDTO.setNames(tagNames); return service.listByTags(requestDTO); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/tagging/IRTaggingTest.java
src/test/java/org/ohdsi/webapi/tagging/IRTaggingTest.java
package org.ohdsi.webapi.tagging; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.ircalc.IncidenceRateAnalysisRepository; import org.ohdsi.webapi.service.IRAnalysisService; import org.ohdsi.webapi.service.dto.IRAnalysisDTO; import org.ohdsi.webapi.tag.domain.Tag; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; public class IRTaggingTest extends BaseTaggingTest<IRAnalysisDTO, Integer> { private static final String JSON_PATH = "/tagging/ir.json"; @Autowired private IRAnalysisService service; @Autowired private IncidenceRateAnalysisRepository repository; @Autowired private CohortDefinitionRepository cohortRepository; @Override public void doCreateInitialData() throws IOException { String expression = getExpression(getExpressionPath()); IRAnalysisDTO dto = deserializeExpression(expression); initialDTO = service.doImport(dto); } @Override protected IRAnalysisDTO doCopyData(IRAnalysisDTO def) { return service.copy(def.getId()); } private IRAnalysisDTO deserializeExpression(String expression) { IRAnalysisDTO dto = Utils.deserialize(expression, IRAnalysisDTO.class); dto.setName("test dto name"); dto.setDescription("test dto description"); return dto; } @Override protected void doClear() { repository.deleteAll(); cohortRepository.deleteAll(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected void assignTag(Integer id, boolean isPermissionProtected) { service.assignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignTag(Integer id, boolean isPermissionProtected) { service.unassignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void assignProtectedTag(Integer id, boolean isPermissionProtected) { service.assignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignProtectedTag(Integer id, boolean isPermissionProtected) { service.unassignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected IRAnalysisDTO getDTO(Integer id) { return service.getAnalysis(id); } @Override protected Integer getId(IRAnalysisDTO dto) { return dto.getId(); } @Override protected void assignTags(Integer id, Tag...tags) { for (Tag tag : tags) { service.assignTag(id, tag.getId()); } } @Override protected List<IRAnalysisDTO> getDTOsByTag(List<String> tagNames) { TagNameListRequestDTO requestDTO = new TagNameListRequestDTO(); requestDTO.setNames(tagNames); return service.listByTags(requestDTO); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/tagging/ReusableTaggingTest.java
src/test/java/org/ohdsi/webapi/tagging/ReusableTaggingTest.java
package org.ohdsi.webapi.tagging; import org.ohdsi.webapi.reusable.ReusableController; import org.ohdsi.webapi.reusable.dto.ReusableDTO; import org.ohdsi.webapi.reusable.repository.ReusableRepository; import org.ohdsi.webapi.tag.domain.Tag; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; public class ReusableTaggingTest extends BaseTaggingTest<ReusableDTO, Integer> { @Autowired private ReusableController controller; @Autowired private ReusableRepository repository; @Override public void doCreateInitialData() throws IOException { ReusableDTO dto = new ReusableDTO(); dto.setData("test data"); dto.setName("test name"); dto.setDescription("test description"); initialDTO = controller.create(dto); } @Override protected ReusableDTO doCopyData(ReusableDTO def) { return controller.copy(def.getId()); } @Override protected void doClear() { repository.deleteAll(); } @Override protected String getExpressionPath() { return null; } @Override protected void assignTag(Integer id, boolean isPermissionProtected) { controller.assignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignTag(Integer id, boolean isPermissionProtected) { controller.unassignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void assignProtectedTag(Integer id, boolean isPermissionProtected) { controller.assignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignProtectedTag(Integer id, boolean isPermissionProtected) { controller.unassignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected ReusableDTO getDTO(Integer id) { return controller.get(id); } @Override protected Integer getId(ReusableDTO dto) { return dto.getId(); } @Override protected void assignTags(Integer id, Tag...tags) { for (Tag tag : tags) { controller.assignTag(id, tag.getId()); } } @Override protected List<ReusableDTO> getDTOsByTag(List<String> tagNames) { TagNameListRequestDTO requestDTO = new TagNameListRequestDTO(); requestDTO.setNames(tagNames); return controller.listByTags(requestDTO); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/tagging/PathwayTaggingTest.java
src/test/java/org/ohdsi/webapi/tagging/PathwayTaggingTest.java
package org.ohdsi.webapi.tagging; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.pathway.PathwayController; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisDTO; import org.ohdsi.webapi.pathway.dto.PathwayAnalysisExportDTO; import org.ohdsi.webapi.pathway.repository.PathwayAnalysisEntityRepository; import org.ohdsi.webapi.tag.domain.Tag; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; public class PathwayTaggingTest extends BaseTaggingTest<PathwayAnalysisDTO, Integer> { private static final String JSON_PATH = "/tagging/pathway.json"; @Autowired private PathwayController service; @Autowired private PathwayAnalysisEntityRepository repository; @Autowired private CohortDefinitionRepository cohortRepository; @Override public void doCreateInitialData() throws IOException { String expression = getExpression(getExpressionPath()); PathwayAnalysisExportDTO dto = Utils.deserialize(expression, PathwayAnalysisExportDTO.class); dto.setName("test dto name"); initialDTO = service.importAnalysis(dto); } @Override protected PathwayAnalysisDTO doCopyData(PathwayAnalysisDTO def) { return service.copy(def.getId()); } @Override protected void doClear() { repository.deleteAll(); cohortRepository.deleteAll(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected void assignTag(Integer id, boolean isPermissionProtected) { service.assignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignTag(Integer id, boolean isPermissionProtected) { service.unassignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void assignProtectedTag(Integer id, boolean isPermissionProtected) { service.assignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignProtectedTag(Integer id, boolean isPermissionProtected) { service.unassignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected PathwayAnalysisDTO getDTO(Integer id) { return service.get(id); } @Override protected Integer getId(PathwayAnalysisDTO dto) { return dto.getId(); } @Override protected void assignTags(Integer id, Tag...tags) { for (Tag tag : tags) { service.assignTag(id, tag.getId()); } } @Override protected List<PathwayAnalysisDTO> getDTOsByTag(List<String> tagNames) { TagNameListRequestDTO requestDTO = new TagNameListRequestDTO(); requestDTO.setNames(tagNames); return service.listByTags(requestDTO); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/tagging/ConceptSetTaggingTest.java
src/test/java/org/ohdsi/webapi/tagging/ConceptSetTaggingTest.java
package org.ohdsi.webapi.tagging; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.ohdsi.circe.vocabulary.ConceptSetExpression; import org.ohdsi.webapi.conceptset.ConceptSetItem; import org.ohdsi.webapi.conceptset.ConceptSetRepository; import org.ohdsi.webapi.service.ConceptSetService; import org.ohdsi.webapi.service.dto.ConceptSetDTO; import org.ohdsi.webapi.tag.domain.Tag; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Arrays; import java.util.List; public class ConceptSetTaggingTest extends BaseTaggingTest<ConceptSetDTO, Integer> { private static final String JSON_PATH = "/tagging/conceptset.json"; @Autowired private ConceptSetService service; @Autowired private ConceptSetRepository repository; @Autowired private ObjectMapper mapper; @Override public void doCreateInitialData() throws IOException { ConceptSetDTO dto = new ConceptSetDTO(); dto.setName("test dto name"); initialDTO = service.createConceptSet(dto); String expression = getExpression(getExpressionPath()); ConceptSetExpression.ConceptSetItem[] expressionItems; try { ConceptSetExpression conceptSetExpression = mapper.readValue(expression, ConceptSetExpression.class); expressionItems = conceptSetExpression.items; } catch (JsonProcessingException e) { throw new RuntimeException(e); } ConceptSetItem[] items = Arrays.stream(expressionItems) .map(i -> conversionService.convert(i, ConceptSetItem.class)) .toArray(ConceptSetItem[]::new); service.saveConceptSetItems(initialDTO.getId(), items); } @Override protected ConceptSetDTO doCopyData(ConceptSetDTO def) { ConceptSetDTO dto = new ConceptSetDTO(); dto.setName("test dto name 2"); return service.createConceptSet(dto); } @Override protected void doClear() { repository.deleteAll(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected void assignTag(Integer id, boolean isPermissionProtected) { service.assignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignTag(Integer id, boolean isPermissionProtected) { service.unassignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void assignProtectedTag(Integer id, boolean isPermissionProtected) { service.assignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignProtectedTag(Integer id, boolean isPermissionProtected) { service.unassignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected ConceptSetDTO getDTO(Integer id) { return service.getConceptSet(id); } @Override protected Integer getId(ConceptSetDTO dto) { return dto.getId(); } @Override protected void assignTags(Integer id, Tag...tags) { for (Tag tag : tags) { service.assignTag(id, tag.getId()); } } @Override protected List<ConceptSetDTO> getDTOsByTag(List<String> tagNames) { TagNameListRequestDTO requestDTO = new TagNameListRequestDTO(); requestDTO.setNames(tagNames); return service.listByTags(requestDTO); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/tagging/CcTaggingTest.java
src/test/java/org/ohdsi/webapi/tagging/CcTaggingTest.java
package org.ohdsi.webapi.tagging; import org.ohdsi.analysis.Utils; import org.ohdsi.webapi.cohortcharacterization.CcController; import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity; import org.ohdsi.webapi.cohortcharacterization.dto.CcExportDTO; import org.ohdsi.webapi.cohortcharacterization.dto.CcShortDTO; import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO; import org.ohdsi.webapi.cohortcharacterization.repository.CcRepository; import org.ohdsi.webapi.cohortcharacterization.specification.CohortCharacterizationImpl; import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository; import org.ohdsi.webapi.tag.domain.Tag; import org.ohdsi.webapi.tag.dto.TagNameListRequestDTO; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; public class CcTaggingTest extends BaseTaggingTest<CcShortDTO, Long> { private static final String JSON_PATH = "/tagging/characterization.json"; @Autowired private CcController service; @Autowired private CcRepository repository; @Autowired private CohortDefinitionRepository cohortRepository; @Override public void doCreateInitialData() throws IOException { String expression = getExpression(getExpressionPath()); CohortCharacterizationImpl characterizationImpl = Utils.deserialize(expression, CohortCharacterizationImpl.class); CohortCharacterizationEntity entity = conversionService.convert(characterizationImpl, CohortCharacterizationEntity.class); CcExportDTO exportDTO = conversionService.convert(entity, CcExportDTO.class); exportDTO.setName("test dto name"); initialDTO = service.doImport(exportDTO); } @Override protected CcShortDTO doCopyData(CcShortDTO def) { return service.copy(def.getId()); } @Override protected List<CcShortDTO> getDTOsByTag(List<String> tagNames) { TagNameListRequestDTO requestDTO = new TagNameListRequestDTO(); requestDTO.setNames(tagNames); return service.listByTags(requestDTO); } @Override protected void doClear() { repository.deleteAll(); cohortRepository.deleteAll(); } @Override protected String getExpressionPath() { return JSON_PATH; } @Override protected void assignTag(Long id, boolean isPermissionProtected) { service.assignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignTag(Long id, boolean isPermissionProtected) { service.unassignTag(id, getTag(isPermissionProtected).getId()); } @Override protected void assignProtectedTag(Long id, boolean isPermissionProtected) { service.assignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected void unassignProtectedTag(Long id, boolean isPermissionProtected) { service.unassignPermissionProtectedTag(id, getTag(isPermissionProtected).getId()); } @Override protected CohortCharacterizationDTO getDTO(Long id) { return service.getDesign(id); } @Override protected Long getId(CcShortDTO dto) { return dto.getId(); } @Override protected void assignTags(Long id, Tag...tags) { for (Tag tag : tags) { service.assignTag(id, tag.getId()); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/tagging/BaseTaggingTest.java
src/test/java/org/ohdsi/webapi/tagging/BaseTaggingTest.java
package org.ohdsi.webapi.tagging; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.service.dto.CommonEntityExtDTO; import org.ohdsi.webapi.shiro.Entities.UserEntity; import org.ohdsi.webapi.shiro.Entities.UserRepository; import org.ohdsi.webapi.tag.domain.Tag; import org.ohdsi.webapi.tag.domain.TagType; import org.ohdsi.webapi.tag.repository.TagRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; public abstract class BaseTaggingTest<T extends CommonEntityExtDTO, ID extends Number> extends AbstractDatabaseTest { protected T initialDTO; @Autowired protected UserRepository userRepository; @Autowired protected TagRepository tagRepository; @Autowired protected ConversionService conversionService; private Tag tag1, tag2, tag3, protectedTag; protected String getExpression(String path) throws IOException { File ple_spec = ResourceUtils.getFile(Objects.requireNonNull(this.getClass().getResource(path))); return FileUtils.readFileToString(ple_spec, StandardCharsets.UTF_8); } @Before public void createInitialData() throws IOException { UserEntity user = new UserEntity(); user.setLogin("anonymous"); userRepository.save(user); this.protectedTag = new Tag(); this.protectedTag.setName("protected tag name"); this.protectedTag.setPermissionProtected(true); this.protectedTag.setType(TagType.SYSTEM); this.protectedTag.setCreatedDate(new Date()); tagRepository.save(this.protectedTag); this.tag1 = new Tag(); this.tag1.setName("tag name"); this.tag1.setPermissionProtected(false); this.tag1.setType(TagType.SYSTEM); this.tag1.setCreatedDate(new Date()); tagRepository.save(this.tag1); this.tag2 = new Tag(); this.tag2.setName("tag name 2"); this.tag2.setPermissionProtected(false); this.tag2.setType(TagType.SYSTEM); this.tag2.setCreatedDate(new Date()); tagRepository.save(this.tag2); this.tag3 = new Tag(); this.tag3.setName("tag name 3"); this.tag3.setPermissionProtected(false); this.tag3.setType(TagType.SYSTEM); this.tag3.setCreatedDate(new Date()); tagRepository.save(this.tag3); doCreateInitialData(); } @After public void clear() { doClear(); tagRepository.deleteAll(); userRepository.deleteAll(); } @Test public void assignTag() { assignTag(getId(initialDTO), false); T dto = getDTO(getId(initialDTO)); assertEquals(dto.getTags().size(), 1); } @Test public void assignProtectedTag() { assignProtectedTag(getId(initialDTO), true); T dto = getDTO(getId(initialDTO)); assertEquals(dto.getTags().size(), 1); } @Test public void unassignTag() { assignTag(); T dto = getDTO(getId(initialDTO)); assertEquals(dto.getTags().size(), 1); unassignTag(getId(initialDTO), false); dto = getDTO(getId(initialDTO)); assertEquals(dto.getTags().size(), 0); } @Test public void unassignProtectedTag() { assignProtectedTag(); T dto = getDTO(getId(initialDTO)); assertEquals(dto.getTags().size(), 1); unassignProtectedTag(getId(initialDTO), true); dto = getDTO(getId(initialDTO)); assertEquals(dto.getTags().size(), 0); } @Test public void byTags() { assignTags(getId(initialDTO), this.tag1, this.tag2); List<T> dtos = getDTOsByTag(Arrays.asList("tag name", "tag name 2")); assertEquals(dtos.size(), 1); dtos = getDTOsByTag(Collections.singletonList("tag name")); assertEquals(dtos.size(), 1); dtos = getDTOsByTag(Collections.singletonList("tag name 2")); assertEquals(dtos.size(), 1); dtos = getDTOsByTag(Collections.singletonList("tag name 3")); assertEquals(dtos.size(), 0); T dto = doCopyData(initialDTO); assignTags(getId(dto), this.tag3); dtos = getDTOsByTag(Arrays.asList("tag name", "tag name 2")); assertEquals(dtos.size(), 1); dtos = getDTOsByTag(Arrays.asList("tag name", "tag name 2", "tag name 3")); assertEquals(dtos.size(), 0); dtos = getDTOsByTag(Collections.singletonList("tag name")); assertEquals(dtos.size(), 1); dtos = getDTOsByTag(Collections.singletonList("tag name 2")); assertEquals(dtos.size(), 1); dtos = getDTOsByTag(Collections.singletonList("tag name 3")); assertEquals(dtos.size(), 1); assignTags(getId(dto), this.tag1, this.tag2); dtos = getDTOsByTag(Arrays.asList("tag name", "tag name 2")); assertEquals(dtos.size(), 2); dtos = getDTOsByTag(Arrays.asList("tag name", "tag name 2", "tag name 3")); assertEquals(dtos.size(), 1); } protected Tag getTag(boolean isProtected) { return tagRepository.findAll().stream() .filter(t -> t.isPermissionProtected() == isProtected) .findFirst() .orElseThrow(() -> new RuntimeException("cannot get tag")); } protected List<Tag> getTags(boolean isProtected) { return tagRepository.findAll().stream() .filter(t -> t.isPermissionProtected() == isProtected) .collect(Collectors.toList()); } protected abstract void doCreateInitialData() throws IOException; protected abstract T doCopyData(T def); protected abstract void doClear(); protected abstract String getExpressionPath(); protected abstract void assignTag(ID id, boolean isPermissionProtected); protected abstract void assignTags(ID id, Tag...tags); protected abstract void unassignTag(ID id, boolean isPermissionProtected); protected abstract void assignProtectedTag(ID id, boolean isPermissionProtected); protected abstract void unassignProtectedTag(ID id, boolean isPermissionProtected); protected abstract T getDTO(ID id); protected abstract ID getId(T dto); protected abstract List<T> getDTOsByTag(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/test/java/org/ohdsi/webapi/security/PermissionTest.java
src/test/java/org/ohdsi/webapi/security/PermissionTest.java
/* * Copyright 2024 cknoll1. * * 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.security; import java.util.Arrays; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.ThreadContext; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.dbunit.operation.DatabaseOperation; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.ohdsi.webapi.AbstractDatabaseTest; import org.ohdsi.webapi.shiro.PermissionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.TestPropertySource; /** * * @author cknoll1 */ @TestPropertySource(properties = { "security.provider=AtlasRegularSecurity" }) public class PermissionTest extends AbstractDatabaseTest { @Autowired private PermissionManager permissionManager; @Value("${security.provider}") String securityProvider; @Autowired private DefaultWebSecurityManager securityManager; private Subject subject; @Before public void setup() { // Set the SecurityManager for the current thread SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(); principalCollection.addAll(Arrays.asList("permsTest"),"testRealm"); subject = new Subject.Builder(securityManager) .authenticated(true) .principals(principalCollection) .buildSubject(); ThreadContext.bind(subject); } @Test public void permsTest() throws Exception { // need to clear authorization cache before each test permissionManager.clearAuthorizationInfoCache(); Subject s = SecurityUtils.getSubject(); String subjetName = permissionManager.getSubjectName(); final String[] testDataSetsPaths = new String[] {"/permission/permsTest_PREP.json" }; loadPrepData(testDataSetsPaths, DatabaseOperation.REFRESH); // subject can manage printer1 and printer2, can do print and query on any printer. assertTrue(s.isPermitted("printer:manage:printer1")); assertTrue(s.isPermitted("printer:manage:printer2")); assertFalse(s.isPermitted("printer:manage:printer3")); assertTrue(s.isPermitted("printer:query:printer4")); assertTrue(s.isPermitted("printer:print:printer5")); loadPrepData(testDataSetsPaths, DatabaseOperation.DELETE); } @Test public void wildcardTest() throws Exception { // need to clear authorization cache before each test permissionManager.clearAuthorizationInfoCache(); Subject s = SecurityUtils.getSubject(); final String[] testDataSetsPaths = new String[] {"/permission/wildcardTest_PREP.json" }; loadPrepData(testDataSetsPaths, DatabaseOperation.REFRESH); // subject has * permisison, so any permisison test is true assertTrue(s.isPermitted("printer:manage:printer1")); assertTrue(s.isPermitted("printer")); loadPrepData(testDataSetsPaths, DatabaseOperation.DELETE); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/cohortcharacterization/CohortCharacterizationServiceTest.java
src/test/java/org/ohdsi/webapi/cohortcharacterization/CohortCharacterizationServiceTest.java
package org.ohdsi.webapi.cohortcharacterization; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.odysseusinc.arachne.commons.types.DBMSType; import com.odysseusinc.arachne.execution_engine_common.api.v1.dto.KerberosAuthMechanism; import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.apache.commons.lang3.builder.ToStringBuilder; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.ohdsi.analysis.Utils; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.sql.SqlRender; import org.ohdsi.sql.SqlSplit; import org.ohdsi.sql.SqlTranslate; import org.ohdsi.webapi.cohortcharacterization.converter.SerializedCcToCcConverter; import org.ohdsi.webapi.cohortcharacterization.domain.CcGenerationEntity; import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity; import org.ohdsi.webapi.cohortcharacterization.dto.ExportExecutionResultRequest; import org.ohdsi.webapi.generationcache.GenerationCacheTest; import org.ohdsi.webapi.job.JobExecutionResource; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceDaimon; import org.ohdsi.webapi.source.SourceRepository; import org.ohdsi.webapi.source.SourceService; import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.core.Response; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.sql.SQLException; import java.util.*; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.ohdsi.webapi.AbstractDatabaseTest; import org.springframework.beans.factory.annotation.Value; public class CohortCharacterizationServiceTest extends AbstractDatabaseTest { private static final String CDM_SQL = ResourceHelper.GetResourceAsString("/cdm-postgresql-ddl.sql"); private static final String PARAM_JSON = ResourceHelper.GetResourceAsString("/cohortcharacterization/reportData.json"); private static final String PARAM_JSON_WITH_STRATA = ResourceHelper.GetResourceAsString("/cohortcharacterization/reportDataWithStrata.json"); private static final String CC_JSON = ResourceHelper.GetResourceAsString("/cohortcharacterization/ibuprofenVsAspirin.json"); private static final String CC_WITH_STRATA_JSON = ResourceHelper.GetResourceAsString("/cohortcharacterization/ibuprofenVsAspirinWithStrata.json"); private static final String RESULT_SCHEMA_NAME = "results"; private static final String CDM_SCHEMA_NAME = "cdm"; private static final String SOURCE_KEY = "Embedded_PG"; private static final String EUNOMIA_CSV_ZIP = "/eunomia.csv.zip"; private static boolean isCdmInitialized = false; @Autowired private CcService ccService; @Autowired private CcController ccController; @Autowired private SourceRepository sourceRepository; @Autowired private SourceService sourceService; @Value("${datasource.ohdsi.schema}") private String ohdsiSchema; private static final Collection<String> COHORT_DDL_FILE_PATHS = Arrays.asList( "/ddl/results/cohort.sql", "/ddl/results/cohort_cache.sql", "/ddl/results/cohort_inclusion.sql", "/ddl/results/cohort_inclusion_result.sql", "/ddl/results/cohort_inclusion_stats.sql", "/ddl/results/cohort_inclusion_result_cache.sql", "/ddl/results/cohort_inclusion_stats_cache.sql", "/ddl/results/cohort_summary_stats.sql", "/ddl/results/cohort_summary_stats_cache.sql", "/ddl/results/cohort_censor_stats.sql", "/ddl/results/cohort_censor_stats_cache.sql", "/ddl/results/cohort_characterizations.sql" ); @Before public void setUp() throws Exception { if (!isCdmInitialized) { // one-time setup of CDM and CDM source truncateTable(String.format("%s.%s", ohdsiSchema, "source")); resetSequence(String.format("%s.%s", ohdsiSchema,"source_sequence")); sourceRepository.saveAndFlush(getCdmSource()); prepareCdmSchema(); isCdmInitialized = true; } prepareResultSchema(); } @Ignore @Test public void testExportGeneration() throws Exception { doTestExportGeneration(CC_JSON, PARAM_JSON); } @Ignore @Test public void testExportGenerationWithStrata() throws Exception { doTestExportGeneration(CC_WITH_STRATA_JSON, PARAM_JSON_WITH_STRATA); } public void doTestExportGeneration(String entityStr, String paramData) throws Exception { CohortCharacterizationEntity entity = new SerializedCcToCcConverter().convertToEntityAttribute(entityStr); entity = ccService.importCc(entity); JobExecutionResource executionResource = ccService.generateCc(entity.getId(), SOURCE_KEY); CcGenerationEntity generationEntity; while (true) { generationEntity = ccService.findGenerationById(executionResource.getExecutionId()); if (generationEntity.getStatus().equals("FAILED") || generationEntity.getStatus().equals("COMPLETED")) { break; } Thread.sleep(2000L); } assertEquals("COMPLETED", generationEntity.getStatus()); TypeReference<Data> typeRef = new TypeReference<Data>() { }; Data data = Utils.deserialize(paramData, typeRef); for (ParamItem paramItem : data.paramItems) { checkRequest(entity, generationEntity.getId(), paramItem); } } private void checkRequest(CohortCharacterizationEntity entity, Long generationId, ParamItem paramItem) throws IOException { String dataItemMessage = String.format("Checking dataitem %s", paramItem.toString()); try { ZipFile zipFile = getZipFile(generationId, paramItem); if (paramItem.fileItems.isEmpty()) { // File is valid assertTrue(dataItemMessage, zipFile.isValidZipFile()); // but empty assertTrue(dataItemMessage, zipFile.getFileHeaders().isEmpty()); } else { // File should not be empty assertTrue(dataItemMessage, zipFile.isValidZipFile()); Path tempDir = Files.createTempDirectory(String.valueOf(System.currentTimeMillis())); tempDir.toFile().deleteOnExit(); zipFile.extractAll(tempDir.toAbsolutePath().toString()); assertEquals(dataItemMessage, paramItem.fileItems.size(), tempDir.toFile().listFiles().length); for (File file : tempDir.toFile().listFiles()) { String fileMessage = String.format("Checking filename %s for dataitem %s", file.getName(), paramItem.toString()); Optional<FileItem> fileItem = paramItem.fileItems.stream() .filter(f -> f.fileName.equals(file.getName())) .findAny(); assertTrue(fileMessage, fileItem.isPresent()); long count = Files.lines(file.toPath()).count(); // include header line assertEquals(fileMessage, fileItem.get().lineCount + 1, count); } } } catch (IllegalArgumentException e) { // Exception should be thrown when parameter of feature is invalid int analysisId = paramItem.analysisIds.stream().filter( aid -> entity.getFeatureAnalyses().stream().noneMatch(fa -> Objects.equals(fa.getId(), aid)) ).findFirst().get(); String expectedMessage = String.format("Feature with id=%s not found in analysis", analysisId); assertEquals(dataItemMessage, e.getMessage(), expectedMessage); } } private ZipFile getZipFile(Long id, ParamItem paramItem) throws IOException { ExportExecutionResultRequest request = new ExportExecutionResultRequest(); request.setCohortIds(paramItem.cohortIds); request.setAnalysisIds(paramItem.analysisIds); request.setDomainIds(paramItem.domainIds); request.setSummary(paramItem.isSummary); request.setComparative(paramItem.isComparative); Response response = ccController.exportGenerationsResults(id, request); assertEquals(200, response.getStatus()); ByteArrayOutputStream baos = (ByteArrayOutputStream) response.getEntity(); File tempFile = File.createTempFile("reports", ".zip"); tempFile.deleteOnExit(); try (OutputStream outputStream = new FileOutputStream(tempFile)) { baos.writeTo(outputStream); } return new ZipFile(tempFile); } private static void prepareResultSchema() { String resultSql = getResultTablesSql(); jdbcTemplate.batchUpdate(SqlSplit.splitSql(resultSql)); } private static void prepareCdmSchema() throws Exception { String cdmSql = getCdmSql(); jdbcTemplate.batchUpdate(SqlSplit.splitSql(cdmSql)); } private static String getResultTablesSql() { StringBuilder ddl = new StringBuilder(); ddl.append(String.format("DROP SCHEMA IF EXISTS %s CASCADE;", RESULT_SCHEMA_NAME)).append("\n"); ddl.append(String.format("CREATE SCHEMA %s;", RESULT_SCHEMA_NAME)).append("\n"); COHORT_DDL_FILE_PATHS.forEach(sqlPath -> ddl.append(ResourceHelper.GetResourceAsString(sqlPath)).append("\n")); String resultSql = SqlRender.renderSql(ddl.toString(), new String[]{"results_schema"}, new String[]{RESULT_SCHEMA_NAME}); return SqlTranslate.translateSql(resultSql, DBMSType.POSTGRESQL.getOhdsiDB()); } private Source getCdmSource() throws SQLException { Source source = new Source(); source.setSourceName("Embedded PG"); source.setSourceKey(SOURCE_KEY); source.setSourceDialect(DBMSType.POSTGRESQL.getOhdsiDB()); source.setSourceConnection(getDataSource().getConnection().getMetaData().getURL()); source.setUsername("postgres"); source.setPassword("postgres"); source.setKrbAuthMethod(KerberosAuthMechanism.PASSWORD); SourceDaimon cdmDaimon = new SourceDaimon(); cdmDaimon.setPriority(1); cdmDaimon.setDaimonType(SourceDaimon.DaimonType.CDM); cdmDaimon.setTableQualifier(CDM_SCHEMA_NAME); cdmDaimon.setSource(source); SourceDaimon vocabDaimon = new SourceDaimon(); vocabDaimon.setPriority(1); vocabDaimon.setDaimonType(SourceDaimon.DaimonType.Vocabulary); vocabDaimon.setTableQualifier(CDM_SCHEMA_NAME); vocabDaimon.setSource(source); SourceDaimon resultsDaimon = new SourceDaimon(); resultsDaimon.setPriority(1); resultsDaimon.setDaimonType(SourceDaimon.DaimonType.Results); resultsDaimon.setTableQualifier(RESULT_SCHEMA_NAME); resultsDaimon.setSource(source); source.setDaimons(Arrays.asList(cdmDaimon, vocabDaimon, resultsDaimon)); return source; } private static String getCdmSql() throws IOException, ZipException { StringBuilder cdmSqlBuilder = new StringBuilder( "DROP SCHEMA IF EXISTS @cdm_database_schema CASCADE; CREATE SCHEMA @cdm_database_schema;"); cdmSqlBuilder.append(CDM_SQL); cdmSqlBuilder.append("ALTER TABLE @cdm_database_schema.vocabulary ALTER COLUMN vocabulary_reference DROP NOT NULL;\n"); cdmSqlBuilder.append("ALTER TABLE @cdm_database_schema.vocabulary ALTER COLUMN vocabulary_version DROP NOT NULL;\n"); Path tempDir = Files.createTempDirectory(""); tempDir.toFile().deleteOnExit(); // Direct Files.copy into new file in the temp folder throws Access Denied File eunomiaZip = File.createTempFile("eunomia", "", tempDir.toFile()); try (InputStream is = GenerationCacheTest.class.getResourceAsStream(EUNOMIA_CSV_ZIP)) { Files.copy(is, eunomiaZip.toPath(), REPLACE_EXISTING); } ZipFile zipFile = new ZipFile(eunomiaZip); zipFile.extractAll(tempDir.toAbsolutePath().toString()); for (final File file : tempDir.toFile().listFiles()) { if (file.getName().endsWith(".csv")) { String tableName = file.getName().replace(".csv", ""); String sql = String.format("COPY @cdm_database_schema.%s FROM '%s' DELIMITER ',' CSV HEADER;", tableName, file.getAbsolutePath()); cdmSqlBuilder.append(sql).append("\n\n"); } } return cdmSqlBuilder.toString().replaceAll("@cdm_database_schema", CDM_SCHEMA_NAME); } public static class Data { @JsonProperty("Params") public List<ParamItem> paramItems; } public static class ParamItem { @JsonProperty("analysisIds") public List<Integer> analysisIds; @JsonProperty("cohortIds") public List<Integer> cohortIds; @JsonProperty("domainIds") public List<String> domainIds; @JsonProperty("isSummary") public Boolean isSummary; @JsonProperty("fileDatas") public List<FileItem> fileItems; @JsonProperty("isComparative") public Boolean isComparative; @Override public String toString() { return new ToStringBuilder(this) .append("analysisIds", analysisIds) .append("cohortIds", cohortIds) .append("isSummary", isSummary) .append("isComparative", isComparative) .toString(); } } public static class FileItem { @JsonProperty("fileName") public String fileName; @JsonProperty("lineCount") public Integer lineCount; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/cohortcharacterization/SkeletonCohortCharacterizationTest.java
src/test/java/org/ohdsi/webapi/cohortcharacterization/SkeletonCohortCharacterizationTest.java
/* * Copyright 2020 cknoll1. * * 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 static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import org.ohdsi.cohortcharacterization.CCQueryBuilder; /** * * @author cknoll1 */ public class SkeletonCohortCharacterizationTest { @Test public void ccQueryBuilderTest() { final Integer sourceId = 1; final String cohortTable = "cohort"; final String sessionId = "session"; final String tempSchema = "tempSchema"; CCQueryBuilder ccQueryBuilder = new CCQueryBuilder("{}", cohortTable, sessionId, null, null, null, tempSchema, 0); assertThat(ccQueryBuilder, notNullValue()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/cohortresults/CohortResultsAnalysisRunnerTest.java
src/test/java/org/ohdsi/webapi/cohortresults/CohortResultsAnalysisRunnerTest.java
package org.ohdsi.webapi.cohortresults; import org.junit.Test; public class CohortResultsAnalysisRunnerTest { @Test(expected = Exception.class) public void testSaveIsFalseScenarios() { CohortResultsAnalysisRunner r = new CohortResultsAnalysisRunner(null, null, null); r.getCohortConditionDrilldown(null, -1, -1, 0, 0, null, false); r.getCohortDataDensity(null, 0, null, null, null, false); r.getCohortDeathData(null, 0, null, null, null, false); r.getCohortDrugDrilldown(null, 0, 0, null, null, null, false); r.getCohortMeasurementResults(null, 0, null, null, null, false); r.getCohortMeasurementResultsDrilldown(null, 0, 0, null, null, null, false); r.getCohortObservationPeriod(null, 0, null, null, null, false); r.getCohortObservationResults(null, 0, null, null, null, false); r.getCohortObservationResultsDrilldown(null, 0, 0, null, null, null, false); r.getCohortProcedureDrilldown(null, 0, 0, null, null, null, false); r.getCohortProceduresDrilldown(null, 0, 0, null, null, null, false); r.getCohortSpecificSummary(null, 0, null, null, null, false); r.getCohortSpecificTreemapResults(null, 0, null, null, null, false); r.getCohortVisitsDrilldown(null, 0, 0, null, null, null, false); r.getConditionEraDrilldown(null, 0, 0, null, null, null, false); r.getConditionEraTreemap(null, 0, null, null, null, false); r.getConditionResults(null, 0, 0, null, null, null, false); r.getConditionTreemap(null, 0, null, null, null, false); r.getDashboard(null, 0, null, null, null, false, false); r.getDrugEraResults(null, 0, 0, null, null, null, false); r.getDrugEraTreemap(null, 0, null, null, null, false); r.getDrugResults(null, 0, 0, null, null, null, false); r.getDrugTreemap(null, 0, null, null, null, false); r.getHeraclesHeel(null, 0, null, false); r.getPersonResults(null, 0, null, null, null, false); r.getProcedureTreemap(null, 0, null, null, null, false); r.getVisitTreemap(null, 0, null, null, null, false); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/vocabulary/test/ConceptSetExpressionTests.java
src/test/java/org/ohdsi/webapi/vocabulary/test/ConceptSetExpressionTests.java
/* * 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.vocabulary.test; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Assert; import org.ohdsi.circe.vocabulary.Concept; import org.ohdsi.circe.vocabulary.ConceptSetExpression; import org.ohdsi.circe.vocabulary.ConceptSetExpressionQueryBuilder; /** * * @author cknoll1 */ public class ConceptSetExpressionTests { private static ConceptSetExpression getTestExpression() { ConceptSetExpression exp = new ConceptSetExpression(); exp.items = new ConceptSetExpression.ConceptSetItem[8]; exp.items[0] = new ConceptSetExpression.ConceptSetItem(); exp.items[0].concept = new Concept(); exp.items[0].concept.conceptId = 1L; exp.items[0].concept.conceptName = "First Concept"; exp.items[0].isExcluded = false; exp.items[0].includeDescendants = false; exp.items[0].includeMapped = false; exp.items[1] = new ConceptSetExpression.ConceptSetItem(); exp.items[1].concept = new Concept(); exp.items[1].concept.conceptId = 2L; exp.items[1].concept.conceptName = "Second Concept"; exp.items[1].isExcluded = false; exp.items[1].includeDescendants = true; exp.items[1].includeMapped = false; exp.items[2] = new ConceptSetExpression.ConceptSetItem(); exp.items[2].concept = new Concept(); exp.items[2].concept.conceptId = 3L; exp.items[2].concept.conceptName = "Third Concept"; exp.items[2].isExcluded = false; exp.items[2].includeDescendants = true; exp.items[2].includeMapped = true; exp.items[3] = new ConceptSetExpression.ConceptSetItem(); exp.items[3].concept = new Concept(); exp.items[3].concept.conceptId = 4L; exp.items[3].concept.conceptName = "Forth Concept (Excluded)"; exp.items[3].isExcluded = true; exp.items[3].includeDescendants = false; exp.items[3].includeMapped = false; exp.items[4] = new ConceptSetExpression.ConceptSetItem(); exp.items[4].concept = new Concept(); exp.items[4].concept.conceptId = 5L; exp.items[4].concept.conceptName = "Fith Concept (Excluded)"; exp.items[4].isExcluded = true; exp.items[4].includeDescendants = true; exp.items[4].includeMapped = false; exp.items[5] = new ConceptSetExpression.ConceptSetItem(); exp.items[5].concept = new Concept(); exp.items[5].concept.conceptId = 6L; exp.items[5].concept.conceptName = "Sixth Concept (Excluded)"; exp.items[5].isExcluded = true; exp.items[5].includeDescendants = false; exp.items[5].includeMapped = true; exp.items[6] = new ConceptSetExpression.ConceptSetItem(); exp.items[6].concept = new Concept(); exp.items[6].concept.conceptId = 7L; exp.items[6].concept.conceptName = "Seventh Concept (Excluded)"; exp.items[6].isExcluded = true; exp.items[6].includeDescendants = true; exp.items[6].includeMapped = true; exp.items[7] = new ConceptSetExpression.ConceptSetItem(); exp.items[7].concept = new Concept(); exp.items[7].concept.conceptId = 8L; exp.items[7].concept.conceptName = "Eigth Concept"; exp.items[7].isExcluded = false; exp.items[7].includeDescendants = false; exp.items[7].includeMapped = true; return exp; } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Test public void SimpleConceptSetExpressionBuild() { ConceptSetExpressionQueryBuilder builder = new ConceptSetExpressionQueryBuilder(); ConceptSetExpression testExpression = getTestExpression(); String conceptSetExpressionSql = builder.buildExpressionQuery(testExpression); // included concepts should have (1,2,3,8) Assert.assertTrue(conceptSetExpressionSql.indexOf("(1,2,3,8)") > 0); // included descendants should have (2,3) Assert.assertTrue(conceptSetExpressionSql.indexOf("(2,3)") > 0); // excluded concepts should have (4,5,6,7) Assert.assertTrue(conceptSetExpressionSql.indexOf("(4,5,6,7)") > 0); // excluded descendants should have (5,7) Assert.assertTrue(conceptSetExpressionSql.indexOf("(5,7)") > 0); // mapped concepts should have (3,8) Assert.assertTrue(conceptSetExpressionSql.indexOf("(3,8)") > 0); // mapped descendants should have 3 Assert.assertTrue(conceptSetExpressionSql.indexOf("(3)") > 0); // mapped excludes should have (6,7) Assert.assertTrue(conceptSetExpressionSql.indexOf("(6,7)") > 0); // mapped exclude descendants should have (7) Assert.assertTrue(conceptSetExpressionSql.indexOf("(7)") > 0); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/test/java/org/ohdsi/webapi/cdmresults/cache/CDMResultsCacheTest.java
src/test/java/org/ohdsi/webapi/cdmresults/cache/CDMResultsCacheTest.java
package org.ohdsi.webapi.cdmresults.cache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.only; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.ohdsi.webapi.cdmresults.DescendantRecordCount; @RunWith(MockitoJUnitRunner.class) public class CDMResultsCacheTest { private CDMResultsCache cache = new CDMResultsCache(); @Mock private Function<List<Integer>, List<DescendantRecordCount>> function; @Captor private ArgumentCaptor<List<Integer>> idForRequestCaptor; @Test public void warm() { assertFalse(cache.isWarm()); cache.warm(); assertTrue(cache.isWarm()); } @Test public void findAndCache_nothingCached() { List<Integer> ids = Arrays.asList(1, 2, 3, 4); when(function.apply(any())).thenReturn( ids.stream().map(CDMResultsCacheTest.this::createDescendantRecordCount).collect(Collectors.toList()) ); Collection<DescendantRecordCount> records = cache.findAndCache(ids, function); assertEquals(4, records.size()); assertEquals(ids, records.stream().map(DescendantRecordCount::getId).collect(Collectors.toList())); } @Test public void findAndCache_getAllDataFromCache() { List<Integer> ids = Arrays.asList(1, 2, 3, 4); when(function.apply(any())).thenReturn( ids.stream().map(CDMResultsCacheTest.this::createDescendantRecordCount).collect(Collectors.toList()) ); cache.findAndCache(ids, function); cache.findAndCache(ids, function); Collection<DescendantRecordCount> records = cache.findAndCache(ids, function); verify(function, only()).apply(any()); assertEquals(ids, records.stream().map(DescendantRecordCount::getId).collect(Collectors.toList())); } @Test public void findAndCache_getOnlySomeDataFromCache() { List<Integer> ids1 = Arrays.asList(1, 2); List<Integer> ids2 = Arrays.asList(1, 2, 3, 4); when(function.apply(any())).then(invocation -> { List<Integer> ids = invocation.getArgumentAt(0, List.class); return ids.stream().map(CDMResultsCacheTest.this::createDescendantRecordCount).collect(Collectors.toList()); } ); cache.findAndCache(ids1, function); cache.findAndCache(ids2, function); verify(function, times(2)).apply(idForRequestCaptor.capture()); assertEquals(Arrays.asList(1, 2), idForRequestCaptor.getAllValues().get(0)); assertEquals(Arrays.asList(3, 4), idForRequestCaptor.getAllValues().get(1)); } @Test public void findAndCache_idFromRequestThatDoesNotPresentInStorage() { List<Integer> ids1 = Arrays.asList(1, 2, 3, 4); List<Integer> ids2 = Arrays.asList(1, 2); when(function.apply(any())).then(invocation -> { List<Integer> ids = invocation.getArgumentAt(0, List.class); return ids2.stream().map(CDMResultsCacheTest.this::createDescendantRecordCount).collect(Collectors.toList()); } ); cache.findAndCache(ids1, function); cache.findAndCache(ids1, function); verify(function, only()).apply(idForRequestCaptor.capture()); assertEquals(ids1, idForRequestCaptor.getAllValues().get(0)); assertNotNull(cache.get(1)); assertNotNull(cache.get(2)); assertNull(cache.get(3)); assertNull(cache.get(4)); } @Test public void addValue() { cache.cacheValue(createDescendantRecordCount(1)); cache.cacheValue(createDescendantRecordCount(2)); assertEquals(new Long(1_001L), cache.get(1).getRecordCount()); assertEquals(new Long(1_000_001L), cache.get(1).getDescendantRecordCount()); assertEquals(new Long(1_002L), cache.get(2).getRecordCount()); assertEquals(new Long(1_000_002L), cache.get(2).getDescendantRecordCount()); } @Test public void addValues() { final List<DescendantRecordCount> records = IntStream.range(1, 10).boxed() .map(this::createDescendantRecordCount) .collect(Collectors.toList()); cache.cacheValues(records); records.forEach(record -> assertNotNull(cache.get(record.getId())) ); } @Test public void get() { cache.cacheValue(createDescendantRecordCount(1)); assertEquals(new Long(1_001L), cache.get(1).getRecordCount()); assertEquals(new Long(1_000_001L), cache.get(1).getDescendantRecordCount()); } @Test public void cacheRequestedIds() { final List<Integer> ids = IntStream.range(1, 5).boxed() .collect(Collectors.toList()); cache.cacheRequestedIds(ids); ids.forEach(id -> assertTrue(cache.isRequested(id)) ); } @Test public void cacheRequestedId() { cache.cacheRequestedId(1); cache.cacheRequestedId(2); assertTrue(cache.isRequested(1)); assertTrue(cache.isRequested(2)); assertFalse(cache.isRequested(3)); } @Test public void isRequested() { cache.cacheRequestedId(1); assertTrue(cache.isRequested(1)); } @Test public void notRequested() { cache.cacheRequestedId(1); assertFalse(cache.isRequested(2)); } @Test public void isWarm() { cache.warm(); assertTrue(cache.isWarm()); assertFalse(cache.notWarm()); } private DescendantRecordCount createDescendantRecordCount(int id) { long recordCount = 1_000 + id; long descendantRecordCount = 1_000_000 + id; DescendantRecordCount value = new DescendantRecordCount(); value.setId(id); value.setRecordCount(recordCount); value.setDescendantRecordCount(descendantRecordCount); return 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/JdbcExceptionMapper.java
src/main/java/org/ohdsi/webapi/JdbcExceptionMapper.java
package org.ohdsi.webapi; import com.odysseusinc.logging.event.FailedDbConnectEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.jdbc.CannotGetJdbcConnectionException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class JdbcExceptionMapper implements ExceptionMapper<CannotGetJdbcConnectionException> { @Autowired private ApplicationEventPublisher eventPublisher; @Override public Response toResponse(CannotGetJdbcConnectionException exception) { eventPublisher.publishEvent(new FailedDbConnectEvent(this, exception.getMessage())); return Response.ok().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/ConverterConfiguration.java
src/main/java/org/ohdsi/webapi/ConverterConfiguration.java
package org.ohdsi.webapi; import com.odysseusinc.arachne.commons.utils.ConverterUtils; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.convert.support.GenericConversionService; @Configuration public class ConverterConfiguration { @Bean public GenericConversionService conversionService(){ return new DefaultConversionService(); } @Bean public ConverterUtils converterUtils(final GenericConversionService conversionService) { return new ConverterUtils(conversionService); } }
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/IExecutionInfo.java
src/main/java/org/ohdsi/webapi/IExecutionInfo.java
package org.ohdsi.webapi; import java.util.Date; public interface IExecutionInfo<T extends IExecutionInfo> { Date getStartTime(); Integer getExecutionDuration(); GenerationStatus getStatus(); boolean getIsValid(); boolean getIsCanceled(); String getMessage(); T setStartTime(Date startTime); T setExecutionDuration(Integer executionDuration); T setStatus(GenerationStatus status); T setIsValid(boolean valid); T setMessage(String message); }
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/LogConfiguration.java
src/main/java/org/ohdsi/webapi/LogConfiguration.java
package org.ohdsi.webapi; import com.odysseusinc.logging.LoggingEventMessageFactory; import com.odysseusinc.logging.LoggingService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class LogConfiguration { @Bean public LoggingEventMessageFactory loggingEventMessageFactory(){ return new LoggingEventMessageFactory(); } @Bean public LoggingService loggingService(LoggingEventMessageFactory factory){ return new LoggingService(factory); } }
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/Pagination.java
src/main/java/org/ohdsi/webapi/Pagination.java
package org.ohdsi.webapi; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Pagination { }
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/CacheConfig.java
src/main/java/org/ohdsi/webapi/CacheConfig.java
package org.ohdsi.webapi; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Configuration; @Configuration @EnableCaching public class CacheConfig { }
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/JerseyConfig.java
src/main/java/org/ohdsi/webapi/JerseyConfig.java
package org.ohdsi.webapi; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.message.GZipEncoder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.filter.EncodingFilter; import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider; import org.ohdsi.webapi.cohortcharacterization.CcController; import org.ohdsi.webapi.executionengine.controller.ScriptExecutionCallbackController; import org.ohdsi.webapi.executionengine.controller.ScriptExecutionController; import org.ohdsi.webapi.info.InfoService; import org.ohdsi.webapi.security.PermissionController; import org.ohdsi.webapi.security.SSOController; import org.ohdsi.webapi.service.ActivityService; import org.ohdsi.webapi.service.CDMResultsService; import org.ohdsi.webapi.service.CohortAnalysisService; import org.ohdsi.webapi.service.CohortDefinitionService; import org.ohdsi.webapi.service.CohortResultsService; import org.ohdsi.webapi.service.CohortService; import org.ohdsi.webapi.service.ConceptSetService; import org.ohdsi.webapi.service.DDLService; import org.ohdsi.webapi.service.EvidenceService; import org.ohdsi.webapi.service.FeasibilityService; import org.ohdsi.webapi.service.FeatureExtractionService; import org.ohdsi.webapi.service.IRAnalysisResource; import org.ohdsi.webapi.service.JobService; import org.ohdsi.webapi.service.PersonService; import org.ohdsi.webapi.service.SqlRenderService; import org.ohdsi.webapi.service.TherapyPathResultsService; import org.ohdsi.webapi.service.UserService; import org.ohdsi.webapi.service.VocabularyService; import org.ohdsi.webapi.shiny.ShinyController; import org.ohdsi.webapi.source.SourceController; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.inject.Singleton; import javax.ws.rs.ext.RuntimeDelegate; import org.ohdsi.webapi.cache.CacheService; /** * */ @Component public class JerseyConfig extends ResourceConfig implements InitializingBean { @Value("${jersey.resources.root.package}") private String rootPackage; @Value("${shiny.enabled:false}") private Boolean shinyEnabled; public JerseyConfig() { RuntimeDelegate.setInstance(new org.glassfish.jersey.internal.RuntimeDelegateImpl()); EncodingFilter.enableFor(this, GZipEncoder.class); } /* (non-Jsdoc) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { packages(this.rootPackage); register(ActivityService.class); register(CacheService.class); register(CcController.class); register(CDMResultsService.class); register(CohortAnalysisService.class); register(CohortDefinitionService.class); register(CohortResultsService.class); register(CohortService.class); register(ConceptSetService.class); register(DDLService.class); register(EvidenceService.class); register(FeasibilityService.class); register(FeatureExtractionService.class); register(InfoService.class); register(IRAnalysisResource.class); register(JobService.class); register(MultiPartFeature.class); register(PermissionController.class); register(PersonService.class); register(ScriptExecutionController.class); register(ScriptExecutionCallbackController.class); register(SourceController.class); register(SqlRenderService.class); register(SSOController.class); register(TherapyPathResultsService.class); register(UserService.class); register(VocabularyService.class); register(new AbstractBinder() { @Override protected void configure() { bind(PageableValueFactoryProvider.class) .to(ValueFactoryProvider.class) .in(Singleton.class); } }); if (shinyEnabled) { register(ShinyController.class); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/SchedulerConfiguration.java
src/main/java/org/ohdsi/webapi/SchedulerConfiguration.java
package org.ohdsi.webapi; import com.cronutils.model.definition.CronDefinition; import com.cronutils.model.definition.CronDefinitionBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import static com.cronutils.model.CronType.QUARTZ; @Configuration public class SchedulerConfiguration { @Bean public TaskScheduler taskScheduler() { final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(20); taskScheduler.initialize(); return taskScheduler; } @Bean public CronDefinition cronDefinition() { return CronDefinitionBuilder.instanceDefinitionFor(QUARTZ); } }
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/WebApi.java
src/main/java/org/ohdsi/webapi/WebApi.java
package org.ohdsi.webapi; import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.scheduling.annotation.EnableScheduling; import javax.annotation.PostConstruct; import java.util.TimeZone; import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration; /** * Launch as java application or deploy as WAR (@link {@link WebApplication} * will source this file). */ @EnableScheduling @SpringBootApplication(exclude={HibernateJpaAutoConfiguration.class, ErrorMvcAutoConfiguration.class, SolrAutoConfiguration.class}) @EnableAspectJAutoProxy(proxyTargetClass = true) public class WebApi extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) { return application.sources(WebApi.class); } public static void main(final String[] args) throws Exception { TomcatURLStreamHandlerFactory.disable(); new SpringApplicationBuilder(WebApi.class).run(args); } @PostConstruct public void init() { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); } }
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/AuthDataSource.java
src/main/java/org/ohdsi/webapi/AuthDataSource.java
/* * * Copyright 2017 Observational Health Data Sciences and Informatics * 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. * * Authors: Mikhail Mironov, Vitaly Koulakov * */ package org.ohdsi.webapi; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration("authDataSourceConfig") @ConditionalOnProperty(name = "security.provider", havingValue = "AtlasRegularSecurity") public class AuthDataSource { private final Logger logger = LoggerFactory.getLogger(AuthDataSource.class); @Value("${security.db.datasource.driverClassName}") private String driverClassName; @Value("${security.db.datasource.url}") private String url; @Value("${security.db.datasource.username}") private String username; @Value("${security.db.datasource.password}") private String password; @Value("${security.db.datasource.schema}") private String schema; @Value("${spring.datasource.hikari.connection-test-query}") private String testQuery; @Value("${spring.datasource.hikari.connection-test-query-timeout}") private Long validationTimeout; @Value("${spring.datasource.hikari.maximum-pool-size}") private int maxPoolSize; @Value("${spring.datasource.hikari.minimum-idle}") private int minPoolIdle; @Value("${spring.datasource.hikari.connection-timeout}") private int connectionTimeout; @Value("${spring.datasource.hikari.register-mbeans}") private boolean registerMbeans; @Value("${spring.datasource.hikari.mbean-name}") private String mbeanName; @Bean(name = "authDataSource") public DataSource authDataSource() { try { HikariConfig config = new HikariConfig(); config.setDriverClassName(driverClassName); config.setJdbcUrl(url); config.setUsername(username); config.setPassword(password); config.setSchema(schema); config.setConnectionTestQuery(testQuery); config.setConnectionTimeout(connectionTimeout); config.setMaximumPoolSize(maxPoolSize); config.setMinimumIdle(minPoolIdle); config.setValidationTimeout(validationTimeout); config.setPoolName(mbeanName); config.setRegisterMbeans(registerMbeans); return new HikariDataSource(config); } catch (Exception ex) { logger.error("Failed to initialize connection to DB used for authentication: {}", ex.getMessage()); 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/JMXConfiguration.java
src/main/java/org/ohdsi/webapi/JMXConfiguration.java
package org.ohdsi.webapi; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.jmx.support.RegistrationPolicy; @Configuration @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class JMXConfiguration { }
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/OidcConfCreator.java
src/main/java/org/ohdsi/webapi/OidcConfCreator.java
/* * * Copyright 2017 Observational Health Data Sciences and Informatics * 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. * * Authors: Mikhail Mironov * */ package org.ohdsi.webapi; import com.nimbusds.jose.JWSAlgorithm; import org.pac4j.oidc.config.OidcConfiguration; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component public class OidcConfCreator { @Value("${security.oid.clientId}") private String clientId; @Value("${security.oid.apiSecret}") private String apiSecret; @Value("${security.oid.url}") private String url; @Value("${security.oid.logoutUrl}") private String logoutUrl; @Value("${security.oid.extraScopes}") private String extraScopes; @Value("#{${security.oid.customParams:{T(java.util.Collections).emptyMap()}}}") private Map<String, String> customParams = new HashMap<>(); @Value("${security.oauth.callback.api}") private String oauthApiCallback; public OidcConfiguration build() { OidcConfiguration conf = new OidcConfiguration(); conf.setClientId(clientId); conf.setSecret(apiSecret); conf.setDiscoveryURI(url); conf.setLogoutUrl(logoutUrl); conf.setWithState(true); conf.setUseNonce(true); if (customParams != null) { customParams.forEach(conf::addCustomParam); } String scopes = "openid"; if (extraScopes != null && !extraScopes.isEmpty()){ scopes += " "; scopes += extraScopes; } conf.setScope(scopes); conf.setPreferredJwsAlgorithm(JWSAlgorithm.RS256); return conf; } }
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/JobInvalidator.java
src/main/java/org/ohdsi/webapi/JobInvalidator.java
package org.ohdsi.webapi; import org.ohdsi.webapi.executionengine.entity.ExecutionEngineAnalysisStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.admin.service.SearchableJobExecutionDao; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Component; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.PostConstruct; import java.util.Calendar; @Component @DependsOn("flyway") public class JobInvalidator { private static final Logger log = LoggerFactory.getLogger(JobInvalidator.class); public static final String INVALIDATED_BY_SYSTEM_EXIT_MESSAGE = "Invalidated by system"; private final JobRepository jobRepository; private final TransactionTemplate transactionTemplateRequiresNew; private final SearchableJobExecutionDao jobExecutionDao; @Autowired public JobInvalidator(JobRepository repository, TransactionTemplate transactionTemplateRequiresNew, SearchableJobExecutionDao jobExecutionDao) { this.jobRepository = repository; this.transactionTemplateRequiresNew = transactionTemplateRequiresNew; this.jobExecutionDao = jobExecutionDao; } @PostConstruct private void invalidateGenerations() { transactionTemplateRequiresNew.execute(s -> { jobExecutionDao.getRunningJobExecutions().forEach(this::invalidationJobExecution); return null; }); } public void invalidateJobExecutionById(ExecutionEngineAnalysisStatus executionEngineAnalysisStatus) { JobExecution job = jobExecutionDao.getJobExecution(executionEngineAnalysisStatus.getExecutionEngineGeneration().getId()); if (job == null || job.getJobId() == null) { log.error("Cannot invalidate job. There is no job for execution-engine-analysis-status with id = {}", executionEngineAnalysisStatus.getId()); return; } invalidationJobExecution(job); } public void invalidationJobExecution(JobExecution job) { job.setStatus(BatchStatus.FAILED); job.setExitStatus(new ExitStatus(ExitStatus.FAILED.getExitCode(), INVALIDATED_BY_SYSTEM_EXIT_MESSAGE)); job.setEndTime(Calendar.getInstance().getTime()); jobRepository.update(job); } }
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/ShiroConfiguration.java
src/main/java/org/ohdsi/webapi/ShiroConfiguration.java
package org.ohdsi.webapi; import java.util.Collection; import java.util.Set; import org.apache.shiro.realm.Realm; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.ohdsi.webapi.shiro.AtlasWebSecurityManager; import org.ohdsi.webapi.shiro.lockout.*; import org.ohdsi.webapi.shiro.management.DataSourceAccessBeanPostProcessor; import org.ohdsi.webapi.shiro.management.DisabledSecurity; import org.ohdsi.webapi.shiro.management.Security; import org.ohdsi.webapi.shiro.management.datasource.DataSourceAccessParameterResolver; import org.ohdsi.webapi.shiro.realms.JwtAuthRealm; import org.ohdsi.webapi.shiro.subject.WebDelegatingRunAsSubjectFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.Filter; import java.util.Map; import java.util.stream.Collectors; /** * Created by GMalikov on 20.08.2015. */ @Configuration public class ShiroConfiguration { @Value("${security.maxLoginAttempts}") private int maxLoginAttempts; @Value("${security.duration.initial}") private long initialDuration; @Value("${security.duration.increment}") private long increment; @Value("${spring.aop.proxy-target-class:false}") private Boolean proxyTargetClass; @Autowired protected ApplicationEventPublisher eventPublisher; @Bean public ShiroFilterFactoryBean shiroFilter(Security security, LockoutPolicy lockoutPolicy) { ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); shiroFilter.setSecurityManager(securityManager(security, lockoutPolicy)); Map<String, Filter> filters = security.getFilters().entrySet().stream() .collect(Collectors.toMap(f -> f.getKey().getTemplateName(), Map.Entry::getValue)); shiroFilter.setFilters(filters); shiroFilter.setFilterChainDefinitionMap(security.getFilterChain()); return shiroFilter; } @Bean public DefaultWebSecurityManager securityManager(Security security, LockoutPolicy lockoutPolicy) { Set<Realm> realmsForAuthentication = security.getRealms(); Collection<Realm> realmsForAuthorization = getJwtAuthRealmForAuthorization(security); final DefaultWebSecurityManager securityManager = new AtlasWebSecurityManager( lockoutPolicy, security.getAuthenticator(), realmsForAuthentication, realmsForAuthorization ); securityManager.setSubjectFactory(new WebDelegatingRunAsSubjectFactory()); return securityManager; } @Bean @ConditionalOnExpression("#{!'${security.provider}'.equals('AtlasRegularSecurity')}") public LockoutPolicy noLockoutPolicy() { return new NoLockoutPolicy(); } @Bean @ConditionalOnProperty(name = "security.provider", havingValue = "AtlasRegularSecurity") public LockoutPolicy lockoutPolicy() { return new DefaultLockoutPolicy(lockoutStrategy(), maxLoginAttempts, eventPublisher); } @Bean @ConditionalOnProperty(name = "security.provider", havingValue = "AtlasRegularSecurity") public LockoutStrategy lockoutStrategy() { return new ExponentLockoutStrategy(initialDuration, increment, maxLoginAttempts); } @Bean @ConditionalOnMissingBean(value = DisabledSecurity.class) public DataSourceAccessBeanPostProcessor dataSourceAccessBeanPostProcessor(DataSourceAccessParameterResolver parameterResolver) { return new DataSourceAccessBeanPostProcessor(parameterResolver, proxyTargetClass); } private Collection<Realm> getJwtAuthRealmForAuthorization(Security security) { return security.getRealms().stream() .filter(JwtAuthRealm.class::isInstance) .collect(Collectors.toList()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/GenerationStatus.java
src/main/java/org/ohdsi/webapi/GenerationStatus.java
/* * Copyright 2015 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; /** * * @author Chris Knoll <cknoll@ohdsi.org> */ public enum GenerationStatus { ERROR, PENDING, RUNNING, COMPLETE }
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/DataAccessConfig.java
src/main/java/org/ohdsi/webapi/DataAccessConfig.java
package org.ohdsi.webapi; import com.cosium.spring.data.jpa.entity.graph.repository.support.EntityGraphJpaRepositoryFactoryBean; import com.odysseusinc.datasourcemanager.encryption.EncryptorUtils; import com.odysseusinc.datasourcemanager.encryption.NotEncrypted; import org.jasypt.encryption.pbe.PBEStringEncryptor; import org.jasypt.hibernate4.encryptor.HibernatePBEEncryptorRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.support.TransactionTemplate; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * */ @Configuration @EnableTransactionManagement @EnableJpaRepositories(repositoryFactoryBeanClass = EntityGraphJpaRepositoryFactoryBean.class) public class DataAccessConfig { private final Logger logger = LoggerFactory.getLogger(DataAccessConfig.class); @Autowired private Environment env; @Value("${jasypt.encryptor.enabled}") private boolean encryptorEnabled; private Properties getJPAProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.default_schema", this.env.getProperty("spring.jpa.properties.hibernate.default_schema")); properties.setProperty("hibernate.dialect", this.env.getProperty("spring.jpa.properties.hibernate.dialect")); properties.setProperty("hibernate.generate_statistics", this.env.getProperty("spring.jpa.properties.hibernate.generate_statistics")); properties.setProperty("hibernate.jdbc.batch_size", this.env.getProperty("spring.jpa.properties.hibernate.jdbc.batch_size")); properties.setProperty("hibernate.order_inserts", this.env.getProperty("spring.jpa.properties.hibernate.order_inserts")); properties.setProperty("hibernate.id.new_generator_mappings", "true"); return properties; } @Bean @DependsOn("defaultStringEncryptor") @Primary public DataSource primaryDataSource() { logger.info("datasource.url is: " + this.env.getRequiredProperty("datasource.url")); String driver = this.env.getRequiredProperty("datasource.driverClassName"); String url = this.env.getRequiredProperty("datasource.url"); String user = this.env.getRequiredProperty("datasource.username"); String pass = this.env.getRequiredProperty("datasource.password"); boolean autoCommit = false; //pooling - currently issues with (at least) oracle with use of temp tables and "on commit preserve rows" instead of "on commit delete rows"; //http://forums.ohdsi.org/t/transaction-vs-session-scope-for-global-temp-tables-statements/333/2 /*final PoolConfiguration pc = new org.apache.tomcat.jdbc.pool.PoolProperties(); pc.setDriverClassName(driver); pc.setUrl(url); pc.setUsername(user); pc.setPassword(pass); pc.setDefaultAutoCommit(autoCommit);*/ //non-pooling DriverManagerDataSource ds = new DriverManagerDataSource(url, user, pass); ds.setDriverClassName(driver); //note autocommit defaults vary across vendors. use provided @Autowired TransactionTemplate String[] supportedDrivers; supportedDrivers = new String[]{"org.postgresql.Driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "oracle.jdbc.driver.OracleDriver", "com.amazon.redshift.jdbc.Driver", "com.cloudera.impala.jdbc.Driver", "net.starschema.clouddb.jdbc.BQDriver", "org.netezza.Driver", "com.simba.googlebigquery.jdbc42.Driver", "org.apache.hive.jdbc.HiveDriver", "com.simba.spark.jdbc.Driver", "net.snowflake.client.jdbc.SnowflakeDriver", "com.databricks.client.jdbc.Driver", "com.intersystems.jdbc.IRISDriver"}; for (String driverName : supportedDrivers) { try { Class.forName(driverName); logger.info("driver loaded: {}", driverName); } catch (Exception ex) { logger.info("error loading {} driver. {}", driverName, ex.getMessage()); } } // Redshift driver can be loaded first because it is mentioned in manifest file - // put the redshift driver at the end so that it doesn't // conflict with postgres queries java.util.Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver d = drivers.nextElement(); if (d.getClass().getName().contains("com.amazon.redshift.jdbc")) { try { DriverManager.deregisterDriver(d); DriverManager.registerDriver(d); } catch (SQLException e) { throw new RuntimeException("Could not deregister redshift driver", e); } } } return ds; //return new org.apache.tomcat.jdbc.pool.DataSource(pc); } @Bean public PBEStringEncryptor defaultStringEncryptor(){ PBEStringEncryptor stringEncryptor = encryptorEnabled ? EncryptorUtils.buildStringEncryptor(env) : new NotEncrypted(); HibernatePBEEncryptorRegistry .getInstance() .registerPBEStringEncryptor("defaultStringEncryptor", stringEncryptor); return stringEncryptor; } @Bean public EntityManagerFactory entityManagerFactory(DataSource dataSource) { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(false); vendorAdapter.setShowSql(Boolean.valueOf(this.env.getRequiredProperty("spring.jpa.show-sql"))); //hibernate.dialect is resolved based on driver //vendorAdapter.setDatabasePlatform(hibernateDialect); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setJpaProperties(getJPAProperties()); factory.setPackagesToScan("org.ohdsi.webapi"); factory.setDataSource(dataSource); factory.afterPropertiesSet(); return factory.getObject(); } @Bean @Primary //This is needed so that JpaTransactionManager is used for autowiring, instead of DataSourceTransactionManager public PlatformTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory) { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory); return txManager; } @Bean public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) { TransactionTemplate transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager(transactionManager); return transactionTemplate; } @Bean public TransactionTemplate transactionTemplateRequiresNew(PlatformTransactionManager transactionManager) { TransactionTemplate transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager(transactionManager); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); return transactionTemplate; } @Bean public TransactionTemplate transactionTemplateNoTransaction(PlatformTransactionManager transactionManager) { TransactionTemplate transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager(transactionManager); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); return transactionTemplate; } /* public String getSparqlEndpoint() { String sparqlEndpoint = this.env.getRequiredProperty("sparql.endpoint"); return sparqlEndpoint; }*/ }
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/GenerationStatusConverter.java
src/main/java/org/ohdsi/webapi/GenerationStatusConverter.java
/* * Copyright 2015 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; import javax.persistence.AttributeConverter; import javax.persistence.Converter; /** * * @author Chris Knoll <cknoll@ohdsi.org> */ @Converter(autoApply = true) public class GenerationStatusConverter implements AttributeConverter<GenerationStatus, Integer>{ @Override public Integer convertToDatabaseColumn(GenerationStatus status) { switch (status) { case ERROR: return -1; case PENDING: return 0; case RUNNING: return 1; case COMPLETE: return 2; default: throw new IllegalArgumentException("Unknown value: " + status); } } @Override public GenerationStatus convertToEntityAttribute(Integer statusValue) { switch (statusValue) { case -1: return GenerationStatus.ERROR; case 0: return GenerationStatus.PENDING; case 1: return GenerationStatus.RUNNING; case 2: return GenerationStatus.COMPLETE; 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/FlywayConfig.java
src/main/java/org/ohdsi/webapi/FlywayConfig.java
package org.ohdsi.webapi; import com.odysseusinc.arachne.commons.config.flyway.ApplicationContextAwareSpringJdbcMigrationResolver; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.flyway.FlywayDataSource; import org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * */ @Configuration @ConditionalOnProperty(prefix = "flyway", name = "enabled", matchIfMissing = true) public class FlywayConfig { @Bean @ConfigurationProperties(prefix="flyway.datasource") @FlywayDataSource public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(initMethod = "migrate", name = "flyway") @ConfigurationProperties(prefix="flyway") public Flyway flyway() { Flyway flyway = new Flyway(); flyway.setDataSource(secondaryDataSource()); return flyway; } @Bean public FlywayMigrationInitializer flywayInitializer(ApplicationContext context, Flyway flyway) { ApplicationContextAwareSpringJdbcMigrationResolver contextAwareResolver = new ApplicationContextAwareSpringJdbcMigrationResolver(context); flyway.setResolvers(contextAwareResolver); return new FlywayMigrationInitializer(flyway, 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/RLangClassImpl.java
src/main/java/org/ohdsi/webapi/RLangClassImpl.java
package org.ohdsi.webapi; import com.fasterxml.jackson.annotation.JsonProperty; import org.ohdsi.analysis.RLangClass; /** * * @author asena5 */ public abstract class RLangClassImpl implements RLangClass { /** * */ protected String attrClass = "args"; /** * Get attrClass * @return attrClass **/ @JsonProperty("attr_class") public String getAttrClass() { return attrClass; } /** * * @param attrClass */ public void setAttrClass(String attrClass) { this.attrClass = attrClass; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/KrbConfiguration.java
src/main/java/org/ohdsi/webapi/KrbConfiguration.java
package org.ohdsi.webapi; import com.odysseusinc.datasourcemanager.krblogin.KerberosService; import com.odysseusinc.datasourcemanager.krblogin.KerberosServiceImpl; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class KrbConfiguration { @Value("${kerberos.timeout}") private long timeout; @Value("${kerberos.kinitPath}") private String kinitPath; @Value("${kerberos.configPath}") private String configPath; @Bean public KerberosService kerberosService(){ return new KerberosServiceImpl(timeout, kinitPath, configPath); } }
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/PageableValueFactoryProvider.java
src/main/java/org/ohdsi/webapi/PageableValueFactoryProvider.java
/* * * 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; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.ws.rs.DefaultValue; import javax.ws.rs.QueryParam; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory; import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; public class PageableValueFactoryProvider implements ValueFactoryProvider { private final ServiceLocator locator; @Inject public PageableValueFactoryProvider(ServiceLocator locator) { this.locator = locator; } @Override public Factory<?> getValueFactory(Parameter parameter) { if (parameter.getRawType() == Pageable.class && parameter.isAnnotationPresent(Pagination.class)) { Factory<?> factory = new PageableValueFactory(locator); return factory; } return null; } @Override public PriorityType getPriority() { return Priority.NORMAL; } private static class PageableValueFactory extends AbstractContainerRequestValueFactory<Pageable> { @QueryParam("page") @DefaultValue("0") Integer page; @QueryParam("size") @DefaultValue("10") Integer size; @QueryParam("sort") List<String> sort; private final ServiceLocator locator; private PageableValueFactory(ServiceLocator locator) { this.locator = locator; } @Override public Pageable provide() { locator.inject(this); List<Sort.Order> orders = new ArrayList<>(); for (String propOrder: sort) { String[] propOrderSplit = propOrder.split(","); String property = propOrderSplit[0]; if (propOrderSplit.length == 1) { orders.add(new Sort.Order(property)); } else { Sort.Direction direction = Sort.Direction.fromStringOrNull(propOrderSplit[1]); orders.add(new Sort.Order(direction, property)); } } return new PageRequest(page, size, orders.isEmpty() ? null : new Sort(orders)); } } }
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/CommonDTO.java
src/main/java/org/ohdsi/webapi/CommonDTO.java
package org.ohdsi.webapi; public interface CommonDTO { String getName(); void setName(String name); Number getId(); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/I18nConfig.java
src/main/java/org/ohdsi/webapi/I18nConfig.java
package org.ohdsi.webapi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import java.util.Locale; @Configuration public class I18nConfig { @Bean public LocaleResolver localeResolver() { AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); registry.addInterceptor(localeChangeInterceptor); } }
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/KerberosUtils.java
src/main/java/org/ohdsi/webapi/KerberosUtils.java
package org.ohdsi.webapi; import com.odysseusinc.arachne.execution_engine_common.api.v1.dto.DataSourceUnsecuredDTO; import com.odysseusinc.arachne.execution_engine_common.util.ConnectionParams; import org.ohdsi.webapi.source.Source; public final class KerberosUtils { private KerberosUtils(){} public static void setKerberosParams(Source source, ConnectionParams connectionParams, DataSourceUnsecuredDTO ds) { ds.setUseKerberos(Boolean.TRUE); ds.setKrbAuthMethod(source.getKrbAuthMethod()); ds.setKeyfile(source.getKeyfile()); if (source.getKrbAdminServer() != null) { ds.setKrbAdminFQDN(source.getKrbAdminServer()); } else { ds.setKrbAdminFQDN(connectionParams.getKrbFQDN()); } ds.setKrbFQDN(connectionParams.getKrbFQDN()); ds.setKrbRealm(connectionParams.getKrbRealm()); ds.setKrbPassword(connectionParams.getPassword()); ds.setKrbUser(connectionParams.getUser()); } }
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/Constants.java
src/main/java/org/ohdsi/webapi/Constants.java
package org.ohdsi.webapi; import com.google.common.collect.ImmutableList; import org.springframework.batch.core.ExitStatus; public interface Constants { String DEFAULT_DIALECT = "sql server"; String GENERATE_COHORT = "generateCohort"; String GENERATE_COHORT_CHARACTERIZATION = "generateCohortCharacterization"; String GENERATE_PATHWAY_ANALYSIS = "generatePathwayAnalysis"; String GENERATE_IR_ANALYSIS = "irAnalysis"; String GENERATE_PREDICTION_ANALYSIS = "generatePredictionAnalysis"; String GENERATE_ESTIMATION_ANALYSIS = "generateEstimationAnalysis"; String WARM_CACHE = "warmCache"; String USERS_IMPORT = "usersImport"; String JOB_IS_ALREADY_SCHEDULED = "Job for provider %s is already scheduled"; String FAILED = ExitStatus.FAILED.getExitCode(); String CANCELED = "CANCELED"; String SYSTEM_USER = "system"; String TEMP_COHORT_TABLE_PREFIX = "temp_cohort_"; Float DEFAULT_THRESHOLD = 0.01f; ImmutableList<String> ALLOWED_JOB_EXECUTION_PARAMETERS = ImmutableList.of( "jobName", "jobAuthor", "cohort_definition_id", "cohortId", "cohortDefinitionIds", "source_id", "source_key", "scriptType", "analysis_id", "concept_set_id", "cohort_characterization_id", "pathway_analysis_id", "estimation_analysis_id", "prediction_analysis_id" ); String SESSION_ID = "Session-ID"; interface SqlSchemaPlaceholders { String CDM_DATABASE_SCHEMA_PLACEHOLDER = "@cdm_database_schema"; String RESULTS_DATABASE_SCHEMA_PLACEHOLDER = "@results_database_schema"; String VOCABULARY_DATABASE_SCHEMA_PLACEHOLDER = "@vocabulary_database_schema"; String TEMP_DATABASE_SCHEMA_PLACEHOLDER = "@temp_database_schema"; } interface Params { String VOCABULARY_DATABASE_SCHEMA = "vocabulary_database_schema"; String COHORT_DEFINITION_ID = "cohort_definition_id"; String COHORT_CHARACTERIZATION_ID = "cohort_characterization_id"; String PATHWAY_ANALYSIS_ID = "pathway_analysis_id"; String PREDICTION_ANALYSIS_ID = "prediction_analysis_id"; String PREDICTION_SKELETON_VERSION = "v0.0.1"; String ESTIMATION_ANALYSIS_ID = "estimation_analysis_id"; String UPDATE_PASSWORD = "update_password"; String SOURCE_ID = "source_id"; String SOURCE_KEY = "source_key"; String ANALYSIS_ID = "analysis_id"; String CDM_DATABASE_SCHEMA = "cdm_database_schema"; String JOB_NAME = "jobName"; String JOB_AUTHOR = "jobAuthor"; String RESULTS_DATABASE_SCHEMA = "results_database_schema"; String TARGET_DATABASE_SCHEMA = "target_database_schema"; String TEMP_DATABASE_SCHEMA = "temp_database_schema"; String TARGET_DIALECT = "target_dialect"; String TARGET_TABLE = "target_table"; String COHORT_ID_FIELD_NAME = "cohort_id_field_name"; String TARGET_COHORT_ID = "target_cohort_id"; String GENERATE_STATS = "generate_stats"; String JOB_START_TIME = "time"; String USER_IMPORT_ID = "user_import_id"; String USER_ROLES = "userRoles"; String SESSION_ID = "sessionId"; String PACKAGE_NAME = "packageName"; String PACKAGE_FILE_NAME = "packageFilename"; String EXECUTABLE_FILE_NAME = "executableFilename"; String GENERATION_ID = "generation_id"; String DESIGN_HASH = "design_hash"; String DEMOGRAPHIC_STATS = "demographic_stats"; } interface Variables { String SOURCE = "source"; } interface Headers { String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"; String AUTH_PROVIDER = "x-auth-provider"; String USER_LANGAUGE = "User-Language"; String ACTION_LOCATION = "action-location"; String BEARER = "Bearer"; String X_AUTH_ERROR = "x-auth-error"; String CONTENT_DISPOSITION = "Content-Disposition"; } interface SecurityProviders { String DISABLED = "DisabledSecurity"; String REGULAR = "AtlasRegularSecurity"; String GOOGLE = "AtlasGoogleSecurity"; } interface Templates { String ENTITY_COPY_PREFIX = "COPY OF %s"; } interface Tables { String COHORT_CACHE = "cohort_cache"; String COHORT_INCLUSION_RESULT_CACHE = "cohort_inclusion_result_cache"; String COHORT_INCLUSION_STATS_CACHE = "cohort_inclusion_stats_cache"; String COHORT_SUMMARY_STATS_CACHE = "cohort_summary_stats_cache"; String COHORT_CENSOR_STATS_CACHE = "cohort_censor_stats_cache"; } interface CallbackUrlResolvers { String QUERY = "query"; String PATH = "path"; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/TerminateJobStepExceptionHandler.java
src/main/java/org/ohdsi/webapi/TerminateJobStepExceptionHandler.java
/* * Copyright 2015 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; import org.springframework.batch.repeat.RepeatContext; import org.springframework.batch.repeat.exception.ExceptionHandler; /** * * @author Chris Knoll <cknoll@ohdsi.org> */ public class TerminateJobStepExceptionHandler implements ExceptionHandler { @Override public void handleException(RepeatContext rc, Throwable thrwbl) throws Throwable { rc.setTerminateOnly(); } }
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/JobConfig.java
src/main/java/org/ohdsi/webapi/JobConfig.java
package org.ohdsi.webapi; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.apache.commons.lang3.StringUtils; import org.ohdsi.webapi.audittrail.listeners.AuditTrailJobListener; import org.ohdsi.webapi.common.generation.AutoremoveJobListener; import org.ohdsi.webapi.common.generation.CancelJobListener; import org.ohdsi.webapi.job.JobTemplate; import org.ohdsi.webapi.service.JobService; import org.ohdsi.webapi.shiro.management.Security; import org.ohdsi.webapi.util.ManagedThreadPoolTaskExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.admin.service.*; import org.springframework.batch.core.configuration.BatchConfigurationException; import org.springframework.batch.core.configuration.annotation.BatchConfigurer; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.explore.JobExplorer; import org.springframework.batch.core.explore.support.JobExplorerFactoryBean; import org.springframework.batch.core.explore.support.MapJobExplorerFactoryBean; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.SimpleJobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Primary; import org.springframework.core.task.TaskExecutor; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; /** * Had to copy DefaultBatchConfigurer and include within because jobLauncher config is private. * https://github.com/spring-projects/spring-boot/issues/1655 */ @Configuration @EnableBatchProcessing @DependsOn({"batchDatabaseInitializer"}) public class JobConfig { private static final Logger log = LoggerFactory.getLogger(CustomBatchConfigurer.class); @Value("${spring.batch.repository.tableprefix}") private String tablePrefix; @Value("${spring.batch.repository.isolationLevelForCreate}") private String isolationLevelForCreate; @Value("${spring.batch.taskExecutor.corePoolSize}") private Integer corePoolSize; @Value("${spring.batch.taskExecutor.maxPoolSize}") private Integer maxPoolSize; @Value("${spring.batch.taskExecutor.queueCapacity}") private Integer queueCapacity; @Value("${spring.batch.taskExecutor.threadGroupName}") private String threadGroupName; @Value("${spring.batch.taskExecutor.threadNamePrefix}") private String threadNamePrefix; @Autowired private DataSource dataSource; @Autowired private AuditTrailJobListener auditTrailJobListener; @Bean public String batchTablePrefix() { return this.tablePrefix; } @Bean public TaskExecutor taskExecutor() { final ThreadPoolTaskExecutor taskExecutor = new ManagedThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(corePoolSize); taskExecutor.setMaxPoolSize(maxPoolSize); taskExecutor.setQueueCapacity(queueCapacity); if (StringUtils.isNotBlank(threadGroupName)) { taskExecutor.setThreadGroupName(threadGroupName); } if (StringUtils.isNotBlank(threadNamePrefix)) { taskExecutor.setThreadNamePrefix(threadNamePrefix); } taskExecutor.afterPropertiesSet(); return taskExecutor; } @Bean public BatchConfigurer batchConfigurer() { return new CustomBatchConfigurer(this.dataSource); } @Bean public JobTemplate jobTemplate(final JobLauncher jobLauncher, final JobBuilderFactory jobBuilders, final StepBuilderFactory stepBuilders, final Security security) { return new JobTemplate(jobLauncher, jobBuilders, stepBuilders, security); } @Bean public SearchableJobExecutionDao searchableJobExecutionDao(DataSource dataSource) { JdbcSearchableJobExecutionDao dao = new JdbcSearchableJobExecutionDao(); dao.setDataSource(dataSource); dao.setTablePrefix(JobConfig.this.tablePrefix); return dao; } @Bean public SearchableJobInstanceDao searchableJobInstanceDao(JdbcTemplate jdbcTemplate) { JdbcSearchableJobInstanceDao dao = new JdbcSearchableJobInstanceDao(); dao.setJdbcTemplate(jdbcTemplate);//no setDataSource as in SearchableJobExecutionDao dao.setTablePrefix(JobConfig.this.tablePrefix); return dao; } @Primary @Bean public JobBuilderFactory jobBuilders(JobRepository jobRepository) { return new JobBuilderFactory(jobRepository) { @Override public JobBuilder get(String name) { return super.get(name) .listener(new CancelJobListener()) .listener(auditTrailJobListener); } }; } class CustomBatchConfigurer implements BatchConfigurer { private DataSource dataSource; private PlatformTransactionManager transactionManager; private JobRepository jobRepository; private JobLauncher jobLauncher; private JobExplorer jobExplorer; @Autowired public void setDataSource(final DataSource dataSource) { this.dataSource = dataSource; // this.transactionManager = new DataSourceTransactionManager(dataSource); } @Autowired public void setTransactionManager(final PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } protected CustomBatchConfigurer() { } public CustomBatchConfigurer(final DataSource dataSource) { setDataSource(dataSource); } @Override public JobRepository getJobRepository() { return this.jobRepository; } @Override public PlatformTransactionManager getTransactionManager() { return this.transactionManager; } @Override public JobLauncher getJobLauncher() { return this.jobLauncher; } @Override public JobExplorer getJobExplorer() { return this.jobExplorer; } @PostConstruct public void initialize() { try { if (this.dataSource == null) { log.warn("No datasource was provided...using a Map based JobRepository"); if (this.transactionManager == null) { this.transactionManager = new ResourcelessTransactionManager(); } final MapJobRepositoryFactoryBean jobRepositoryFactory = new MapJobRepositoryFactoryBean( this.transactionManager); jobRepositoryFactory.afterPropertiesSet(); this.jobRepository = jobRepositoryFactory.getObject(); final MapJobExplorerFactoryBean jobExplorerFactory = new MapJobExplorerFactoryBean(jobRepositoryFactory); jobExplorerFactory.afterPropertiesSet(); this.jobExplorer = jobExplorerFactory.getObject(); } else { this.jobRepository = createJobRepository(); final JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean(); jobExplorerFactoryBean.setDataSource(this.dataSource); jobExplorerFactoryBean.setTablePrefix(JobConfig.this.tablePrefix); jobExplorerFactoryBean.afterPropertiesSet(); this.jobExplorer = jobExplorerFactoryBean.getObject(); } this.jobLauncher = createJobLauncher(); } catch (final Exception e) { throw new BatchConfigurationException(e); } } private JobLauncher createJobLauncher() throws Exception { final SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); //async TODO jobLauncher.setTaskExecutor(taskExecutor()); jobLauncher.setJobRepository(this.jobRepository); jobLauncher.afterPropertiesSet(); return jobLauncher; } protected JobRepository createJobRepository() throws Exception { final JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(this.dataSource); //prevent ISOLATION_DEFAULT setting for oracle (i.e. SERIALIZABLE) //ISOLATION_REPEATABLE_READ throws READ_COMMITTED and SERIALIZABLE are the only valid transaction levels factory.setIsolationLevelForCreate(JobConfig.this.isolationLevelForCreate); factory.setTablePrefix(JobConfig.this.tablePrefix); factory.setTransactionManager(getTransactionManager()); factory.setValidateTransactionState(false); factory.afterPropertiesSet(); return factory.getObject(); } } } /*extends DefaultBatchConfigurer { private static final Log log = LogFactory.getLog(BatchConfig.class); @Autowired private JobBuilderFactory jobBuilders; @Autowired private StepBuilderFactory stepBuilders; @Autowired private DataSource dataSource; @Value("${spring.batch.repository.tableprefix}") private String tablePrefix; @Bean public String batchTablePrefix() { return this.tablePrefix; } @Override protected JobRepository createJobRepository() throws Exception { final JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(this.dataSource); factory.setTablePrefix(this.tablePrefix); factory.setIsolationLevelForCreate(this.isolationLevel); factory.setTransactionManager(getTransactionManager()); factory.afterPropertiesSet(); return factory.getObject(); } @Bean public TaskExecutor taskExecutor() { final ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setMaxPoolSize(2);//TODO taskExecutor.afterPropertiesSet(); return taskExecutor; } } */
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/shiro/TokenManager.java
src/main/java/org/ohdsi/webapi/shiro/TokenManager.java
package org.ohdsi.webapi.shiro; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.UnsupportedJwtException; import io.jsonwebtoken.impl.crypto.MacProvider; import java.security.Key; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.web.util.WebUtils; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.util.ExpiringMultimap; /** * * @author gennadiy.anisimov */ public class TokenManager { private static final String AUTHORIZATION_HEADER = "Authorization"; private static final Map<String, Key> userToKeyMap = new HashMap<>(); private static final ExpiringMultimap<String, Key> gracePeriodInvalidTokens = new ExpiringMultimap<>(30000); public static String createJsonWebToken(String subject, String sessionId, Date expiration) { Key key = MacProvider.generateKey(); Key oldKey; if ((oldKey = userToKeyMap.get(subject)) != null) { gracePeriodInvalidTokens.put(subject, oldKey); } userToKeyMap.put(subject, key); Map<String, Object> claims = new HashMap<>(); claims.put(Constants.SESSION_ID, sessionId); return Jwts.builder() .setClaims(claims) .setSubject(subject) .setExpiration(expiration) .signWith(SignatureAlgorithm.HS512, key) .compact(); } public static String getSubject(String jwt) throws JwtException { return getBody(jwt).getSubject(); } public static Claims getBody(String jwt) { // Get untrusted subject for secret key retrieval String untrustedSubject = getUntrustedSubject(jwt); if (untrustedSubject == null) { throw new UnsupportedJwtException("Cannot extract subject from the token"); } // Pick all secret keys: latest one + previous keys, which were just invalidated (to overcome concurrency issue) List<Key> keyOptions = gracePeriodInvalidTokens.get(untrustedSubject); if (userToKeyMap.containsKey(untrustedSubject)) { keyOptions.add(0, userToKeyMap.get(untrustedSubject)); } return keyOptions.stream() .map(key -> { try { return Jwts.parser() .setSigningKey(key) .parseClaimsJws(jwt) .getBody(); } catch (Exception ex) { return null; } }) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new SignatureException("Signing key is not registered for the subject.")); } protected static String getUntrustedSubject(String jws) { int i = jws.lastIndexOf('.'); if (i == -1) { return null; } String untrustedJwtString = jws.substring(0, i+1); return Jwts.parser().parseClaimsJwt(untrustedJwtString).getBody().getSubject(); } public static Boolean invalidate(String jwt) { if (jwt == null) return false; String subject; try { subject = getSubject(jwt); } catch(JwtException e) { return false; } if (!userToKeyMap.containsKey(subject)) return false; userToKeyMap.remove(subject); return true; } public static String extractToken(ServletRequest request) { HttpServletRequest httpRequest = WebUtils.toHttp(request); String header = httpRequest.getHeader(AUTHORIZATION_HEADER); if (header == null || header.isEmpty()) return null; if (!header.toLowerCase(Locale.ENGLISH).startsWith("bearer")) return null; String[] headerParts = header.split(" "); if (headerParts.length != 2) return null; String jwt = headerParts[1]; return jwt; } }
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/shiro/AtlasWebSecurityManager.java
src/main/java/org/ohdsi/webapi/shiro/AtlasWebSecurityManager.java
package org.ohdsi.webapi.shiro; import java.util.Collection; import org.apache.commons.collections.CollectionUtils; import org.apache.shiro.authc.pam.ModularRealmAuthenticator; import org.apache.shiro.authz.ModularRealmAuthorizer; import org.apache.shiro.realm.Realm; import org.ohdsi.webapi.shiro.lockout.LockoutPolicy; import org.ohdsi.webapi.shiro.lockout.LockoutWebSecurityManager; /** * WebSecurityManger uses the same collection of the realms for authentication and authorization by default. * In our case only jwtAuthRealm make a real authorization, so for this we create ModularRealmAuthenticator and ModularRealmAuthorizer by hand, * and override afterRealmsSet, to prevent reassign realms for authenticator and authorizer. * */ public class AtlasWebSecurityManager extends LockoutWebSecurityManager { public AtlasWebSecurityManager(LockoutPolicy lockoutPolicy, ModularRealmAuthenticator authenticator, Collection<Realm> authenticationRealms, Collection<Realm> authorizationRealms) { super(lockoutPolicy); ModularRealmAuthorizer authorizer = new ModularRealmAuthorizer(); Collection realms = CollectionUtils.union(authenticationRealms, authorizationRealms); if (realms != null && !realms.isEmpty()) { this.setRealms(realms); } authenticator.setRealms(authenticationRealms); authorizer.setRealms(authorizationRealms); this.setAuthenticator(authenticator); this.setAuthorizer(authorizer); } @Override protected void afterRealmsSet() { //by default this method override realms for authenticator and authorizer. we don't want this. //do nothing } }
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/shiro/PermissionManager.java
src/main/java/org/ohdsi/webapi/shiro/PermissionManager.java
package org.ohdsi.webapi.shiro; import com.fasterxml.jackson.databind.ObjectMapper; import com.odysseusinc.logging.event.AddUserEvent; import com.odysseusinc.logging.event.DeleteRoleEvent; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.subject.Subject; import org.ohdsi.webapi.helper.Guard; import org.ohdsi.webapi.security.model.UserSimpleAuthorizationInfo; import org.ohdsi.webapi.shiro.Entities.PermissionEntity; import org.ohdsi.webapi.shiro.Entities.PermissionRepository; import org.ohdsi.webapi.shiro.Entities.RequestStatus; 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.Entities.UserOrigin; import org.ohdsi.webapi.shiro.Entities.UserRepository; import org.ohdsi.webapi.shiro.Entities.UserRoleEntity; import org.ohdsi.webapi.shiro.Entities.UserRoleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.security.Principal; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import javax.cache.CacheManager; import javax.cache.configuration.MutableConfiguration; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.authz.Permission; import org.apache.shiro.authz.permission.WildcardPermission; import org.ohdsi.circe.helper.ResourceHelper; import org.ohdsi.webapi.util.CacheHelper; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.jdbc.core.JdbcTemplate; /** * * @author gennadiy.anisimov */ @Component @Transactional public class PermissionManager { //create cache @Component public static class CachingSetup implements JCacheManagerCustomizer { public static final String AUTH_INFO_CACHE = "authorizationInfo"; @Override public void customize(CacheManager cacheManager) { // due to unit tests causing application contexts to reload cache manager caches, we // have to check for the existance of a cache before creating it Set<String> cacheNames = CacheHelper.getCacheNames(cacheManager); // Evict when a user, role or permission is modified/deleted. if (!cacheNames.contains(AUTH_INFO_CACHE)) { cacheManager.createCache(AUTH_INFO_CACHE, new MutableConfiguration<String, UserSimpleAuthorizationInfo>() .setTypes(String.class, UserSimpleAuthorizationInfo.class) .setStoreByValue(false) .setStatisticsEnabled(true)); } } } @Value("${datasource.ohdsi.schema}") private String ohdsiSchema; @Autowired private UserRepository userRepository; @Autowired private RoleRepository roleRepository; @Autowired private PermissionRepository permissionRepository; @Autowired private RolePermissionRepository rolePermissionRepository; @Autowired private UserRoleRepository userRoleRepository; @Autowired private ApplicationEventPublisher eventPublisher; @Autowired private JdbcTemplate jdbcTemplate; private ThreadLocal<ConcurrentHashMap<String, UserSimpleAuthorizationInfo>> authorizationInfoCache = ThreadLocal.withInitial(ConcurrentHashMap::new); public static class PermissionsDTO { public Map<String, List<String>> permissions = null; } public RoleEntity addRole(String roleName, boolean isSystem) { Guard.checkNotEmpty(roleName); checkRoleIsAbsent(roleName, isSystem, "Can't create role - it already exists"); RoleEntity role = new RoleEntity(); role.setName(roleName); role.setSystemRole(isSystem); role = this.roleRepository.save(role); return role; } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, key = "#login") public String addUserToRole(String roleName, String login) { return addUserToRole(roleName, login, UserOrigin.SYSTEM); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, key = "#login") public String addUserToRole(String roleName, String login, UserOrigin userOrigin) { Guard.checkNotEmpty(roleName); Guard.checkNotEmpty(login); RoleEntity role = this.getSystemRoleByName(roleName); UserEntity user = this.getUserByLogin(login); UserRoleEntity userRole = this.addUser(user, role, userOrigin, null); return userRole.getStatus(); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, key = "#login") public void removeUserFromRole(String roleName, String login, UserOrigin origin) { Guard.checkNotEmpty(roleName); Guard.checkNotEmpty(login); if (roleName.equalsIgnoreCase(login)) throw new RuntimeException("Can't remove user from personal role"); RoleEntity role = this.getSystemRoleByName(roleName); UserEntity user = this.getUserByLogin(login); UserRoleEntity userRole = this.userRoleRepository.findByUserAndRole(user, role); if (userRole != null && (origin == null || origin.equals(userRole.getOrigin()))) this.userRoleRepository.delete(userRole); } public Iterable<RoleEntity> getRoles(boolean includePersonalRoles) { if (includePersonalRoles) { return this.roleRepository.findAll(); } else { return this.roleRepository.findAllBySystemRoleTrue(); } } /** * Return the UserSimpleAuthorizastionInfo which contains the login, roles and permissions for the specified login * * @param login The login to fetch the authorization info * @return A UserSimpleAuthorizationInfo containing roles and permissions. */ @Cacheable(cacheNames = CachingSetup.AUTH_INFO_CACHE) public UserSimpleAuthorizationInfo getAuthorizationInfo(final String login) { return authorizationInfoCache.get().computeIfAbsent(login, newLogin -> { final UserSimpleAuthorizationInfo info = new UserSimpleAuthorizationInfo(); final UserEntity userEntity = userRepository.findByLogin(login); if(userEntity == null) { throw new UnknownAccountException("Account does not exist"); } info.setUserId(userEntity.getId()); info.setLogin(userEntity.getLogin()); for (UserRoleEntity userRole: userEntity.getUserRoles()) { info.addRole(userRole.getRole().getName()); } // convert permission index from queryUserPermissions() into a map of WildcardPermissions Map<String, List<String>> permsIdx = this.queryUserPermissions(login).permissions; Map permissionMap = new HashMap<String, List<Permission>>(); Set<String> permissionNames = new HashSet<>(); for(String permIdxKey : permsIdx.keySet()) { List<String> perms = permsIdx.get(permIdxKey); permissionNames.addAll(perms); // convert raw string permission into Wildcard perm for each element in this key's array. permissionMap.put(permIdxKey, perms.stream().map(perm -> new WildcardPermission(perm)).collect(Collectors.toList())); } info.setStringPermissions(permissionNames); info.setPermissionIdx(permissionMap); return info; }); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void clearAuthorizationInfoCache() { authorizationInfoCache.set(new ConcurrentHashMap<>()); } @Transactional public UserEntity registerUser(final String login, final String name, final Set<String> defaultRoles) { return registerUser(login, name, UserOrigin.SYSTEM, defaultRoles); } @Transactional public UserEntity registerUser(final String login, final String name, final UserOrigin userOrigin, final Set<String> defaultRoles) { Guard.checkNotEmpty(login); UserEntity user = userRepository.findByLogin(login); if (user != null) { if (user.getName() == null || !userOrigin.equals(user.getOrigin())) { String nameToSet = name; if (name == null) { nameToSet = login; } user.setName(nameToSet); user.setOrigin(userOrigin); user = userRepository.save(user); } return user; } checkRoleIsAbsent(login, false, "User with such login has been improperly removed from the database. " + "Please contact your system administrator"); user = new UserEntity(); user.setLogin(login); user.setName(name); user.setOrigin(userOrigin); user = userRepository.save(user); eventPublisher.publishEvent(new AddUserEvent(this, user.getId(), login)); RoleEntity personalRole = this.addRole(login, false); this.addUser(user, personalRole, userOrigin, null); if (defaultRoles != null) { for (String roleName: defaultRoles) { RoleEntity defaultRole = this.getSystemRoleByName(roleName); if (defaultRole != null) { this.addUser(user, defaultRole, userOrigin, null); } } } user = userRepository.findOne(user.getId()); return user; } public Iterable<UserEntity> getUsers() { return this.userRepository.findAll(); } public PermissionEntity getOrAddPermission(final String permissionName, final String permissionDescription) { Guard.checkNotEmpty(permissionName); PermissionEntity permission = this.permissionRepository.findByValueIgnoreCase(permissionName); if (permission != null) { return permission; } permission = new PermissionEntity(); permission.setValue(permissionName); permission.setDescription(permissionDescription); permission = this.permissionRepository.save(permission); return permission; } public Set<RoleEntity> getUserRoles(Long userId) throws Exception { UserEntity user = this.getUserById(userId); Set<RoleEntity> roles = this.getUserRoles(user); return roles; } public Iterable<PermissionEntity> getPermissions() { return this.permissionRepository.findAll(); } public Set<PermissionEntity> getUserPermissions(Long userId) { UserEntity user = this.getUserById(userId); Set<PermissionEntity> permissions = this.getUserPermissions(user); return permissions; } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void removeRole(Long roleId) { eventPublisher.publishEvent(new DeleteRoleEvent(this, roleId)); this.roleRepository.delete(roleId); } public Set<PermissionEntity> getRolePermissions(Long roleId) { RoleEntity role = this.getRoleById(roleId); Set<PermissionEntity> permissions = this.getRolePermissions(role); return permissions; } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void addPermission(Long roleId, Long permissionId) { PermissionEntity permission = this.getPermissionById(permissionId); RoleEntity role = this.getRoleById(roleId); this.addPermission(role, permission, null); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void addPermission(RoleEntity role, PermissionEntity permission) { this.addPermission(role, permission, null); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void removePermission(Long permissionId, Long roleId) { RolePermissionEntity rolePermission = this.rolePermissionRepository.findByRoleIdAndPermissionId(roleId, permissionId); if (rolePermission != null) this.rolePermissionRepository.delete(rolePermission); } public Set<UserEntity> getRoleUsers(Long roleId) { RoleEntity role = this.getRoleById(roleId); Set<UserEntity> users = this.getRoleUsers(role); return users; } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void addUser(Long userId, Long roleId) { UserEntity user = this.getUserById(userId); RoleEntity role = this.getRoleById(roleId); this.addUser(user, role, UserOrigin.SYSTEM, null); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void removeUser(Long userId, Long roleId) { UserRoleEntity userRole = this.userRoleRepository.findByUserIdAndRoleId(userId, roleId); if (userRole != null) this.userRoleRepository.delete(userRole); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void removePermission(String value) { PermissionEntity permission = this.permissionRepository.findByValueIgnoreCase(value); if (permission != null) this.permissionRepository.delete(permission); } public RoleEntity getUserPersonalRole(String username) { return this.getRoleByName(username, false); } public RoleEntity getCurrentUserPersonalRole() { String username = this.getSubjectName(); return getUserPersonalRole(username); } private void checkRoleIsAbsent(String roleName, boolean isSystem, String message) { RoleEntity role = this.roleRepository.findByNameAndSystemRole(roleName, isSystem); if (role != null) { throw new RuntimeException(message); } } public Set<PermissionEntity> getUserPermissions(UserEntity user) { Set<RoleEntity> roles = this.getUserRoles(user); Set<PermissionEntity> permissions = new LinkedHashSet<>(); for (RoleEntity role : roles) { permissions.addAll(this.getRolePermissions(role)); } return permissions; } public PermissionsDTO queryUserPermissions(final String login) { String permQuery = StringUtils.replace( ResourceHelper.GetResourceAsString("/resources/security/getPermissionsForUser.sql"), "@ohdsi_schema", this.ohdsiSchema); final UserEntity user = userRepository.findByLogin(login); List<String> permissions = this.jdbcTemplate.query( permQuery, (ps) -> { ps.setLong(1, user.getId()); }, (rs, rowNum) -> { return rs.getString("value"); }); PermissionsDTO permDto = new PermissionsDTO(); permDto.permissions = permsToMap(permissions); return permDto; } /** * This method takes a list of strings and returns a JSObject representing * the first element of each permission as a key, and the List<String> of * permissions that start with the key as the value */ private Map<String, List<String>> permsToMap(List<String> permissions) { Map<String, List<String>> resultMap = new HashMap<>(); // Process each input string for (String inputString : permissions) { String[] parts = inputString.split(":"); String key = parts[0]; // Create a new JsonArray for the key if it doesn't exist resultMap.putIfAbsent(key, new ArrayList<>()); // Add the value to the JsonArray resultMap.get(key).add(inputString); } // Convert the resultMap to a JsonNode return resultMap; } private Set<PermissionEntity> getRolePermissions(RoleEntity role) { Set<PermissionEntity> permissions = new LinkedHashSet<>(); Set<RolePermissionEntity> rolePermissions = role.getRolePermissions(); for (RolePermissionEntity rolePermission : rolePermissions) { if (isRelationAllowed(rolePermission.getStatus())) { PermissionEntity permission = rolePermission.getPermission(); permissions.add(permission); } } return permissions; } private Set<RoleEntity> getUserRoles(UserEntity user) { Set<UserRoleEntity> userRoles = user.getUserRoles(); Set<RoleEntity> roles = new LinkedHashSet<>(); for (UserRoleEntity userRole : userRoles) { if (isRelationAllowed(userRole.getStatus())) { RoleEntity role = userRole.getRole(); roles.add(role); } } return roles; } private Set<UserEntity> getRoleUsers(RoleEntity role) { Set<UserEntity> users = new LinkedHashSet<>(); for (UserRoleEntity userRole : role.getUserRoles()) { if (isRelationAllowed(userRole.getStatus())) { users.add(userRole.getUser()); } } return users; } public UserEntity getCurrentUser() { final String login = this.getSubjectName(); final UserEntity currentUser = this.getUserByLogin(login); return currentUser; } public UserEntity getUserById(Long userId) { UserEntity user = this.userRepository.findOne(userId); if (user == null) throw new RuntimeException("User doesn't exist"); return user; } private UserEntity getUserByLogin(final String login) { final UserEntity user = this.userRepository.findByLogin(login); if (user == null) throw new RuntimeException("User doesn't exist"); return user; } private RoleEntity getRoleByName(String roleName, Boolean isSystemRole) { final RoleEntity roleEntity = this.roleRepository.findByNameAndSystemRole(roleName, isSystemRole); if (roleEntity == null) throw new RuntimeException("Role doesn't exist"); return roleEntity; } public RoleEntity getSystemRoleByName(String roleName) { return getRoleByName(roleName, true); } private RoleEntity getRoleById(Long roleId) { final RoleEntity roleEntity = this.roleRepository.findById(roleId); if (roleEntity == null) throw new RuntimeException("Role doesn't exist"); return roleEntity; } private PermissionEntity getPermissionById(Long permissionId) { final PermissionEntity permission = this.permissionRepository.findById(permissionId); if (permission == null ) throw new RuntimeException("Permission doesn't exist"); return permission; } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) private RolePermissionEntity addPermission(final RoleEntity role, final PermissionEntity permission, final String status) { RolePermissionEntity relation = this.rolePermissionRepository.findByRoleAndPermission(role, permission); if (relation == null) { relation = new RolePermissionEntity(); relation.setRole(role); relation.setPermission(permission); relation.setStatus(status); relation = this.rolePermissionRepository.save(relation); } return relation; } private boolean isRelationAllowed(final String relationStatus) { return relationStatus == null || relationStatus.equals(RequestStatus.APPROVED); } private UserRoleEntity addUser(final UserEntity user, final RoleEntity role, final UserOrigin userOrigin, final String status) { UserRoleEntity relation = this.userRoleRepository.findByUserAndRole(user, role); if (relation == null) { relation = new UserRoleEntity(); relation.setUser(user); relation.setRole(role); relation.setStatus(status); relation.setOrigin(userOrigin); relation = this.userRoleRepository.save(relation); } return relation; } public String getSubjectName() { Subject subject = SecurityUtils.getSubject(); Object principalObject = subject.getPrincipals().getPrimaryPrincipal(); if (principalObject instanceof String) return (String)principalObject; if (principalObject instanceof Principal) { Principal principal = (Principal)principalObject; return principal.getName(); } throw new UnsupportedOperationException(); } public RoleEntity getRole(Long id) { return this.roleRepository.findById(id); } public RoleEntity updateRole(RoleEntity roleEntity) { return this.roleRepository.save(roleEntity); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void addPermissionsFromTemplate(RoleEntity roleEntity, Map<String, String> template, String value) { for (Map.Entry<String, String> entry : template.entrySet()) { String permission = String.format(entry.getKey(), value); String description = String.format(entry.getValue(), value); PermissionEntity permissionEntity = this.getOrAddPermission(permission, description); this.addPermission(roleEntity, permissionEntity); } } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void addPermissionsFromTemplate(Map<String, String> template, String value) { RoleEntity currentUserPersonalRole = getCurrentUserPersonalRole(); addPermissionsFromTemplate(currentUserPersonalRole, template, value); } @CacheEvict(cacheNames = CachingSetup.AUTH_INFO_CACHE, allEntries = true) public void removePermissionsFromTemplate(Map<String, String> template, String value) { for (Map.Entry<String, String> entry : template.entrySet()) { String permission = String.format(entry.getKey(), value); this.removePermission(permission); } } public boolean roleExists(String roleName) { return this.roleRepository.existsByName(roleName); } }
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/shiro/management/FilterTemplates.java
src/main/java/org/ohdsi/webapi/shiro/management/FilterTemplates.java
package org.ohdsi.webapi.shiro.management; public enum FilterTemplates { SEND_TOKEN_IN_URL("sendTokenInUrl"), SEND_TOKEN_IN_HEADER("sendTokenInHeader"), SEND_TOKEN_IN_REDIRECT("sendTokenInRedirect"), JWT_AUTHC("jwtAuthc"), ACCESS_AUTHC("accessAuthc"), NEGOTIATE_AUTHC("negotiateAuthc"), GOOGLE_AUTHC("googleAuthc"), FACEBOOK_AUTHC("facebookAuthc"), GITHUB_AUTHC("githubAuthc"), CAS_AUTHC("casAuthc"), SAML_AUTHC("samlAuthc"), SAML_AUTHC_FORCE("samlAuthcForce"), NO_SESSION_CREATION("noSessionCreation"), FORCE_SESSION_CREATION("forceSessionCreation"), AUTHZ("authz"), CORS("cors"), SSL("ssl"), NO_CACHE("noCache"), HIDE_RESOURCE("hideResource"), LOGOUT("logout"), UPDATE_TOKEN("updateToken"), JDBC_FILTER("jdbcFilter"), KERBEROS_FILTER("kerberosFilter"), LDAP_FILTER("ldapFilter"), AD_FILTER("adFilter"), OIDC_AUTH("oidcAuth"), OIDC_DIRECT_AUTH("oidcDirectAuth"), OAUTH_CALLBACK("oauthCallback"), HANDLE_UNSUCCESSFUL_OAUTH("handleUnsuccessfullOAuth"), HANDLE_CAS("handleCas"), HANDLE_SAML("handleSaml"), RUN_AS("runAs"); private String templateName; FilterTemplates(String templateName){ this.templateName = templateName; } public String getTemplateName() { return templateName; } public static final FilterTemplates[] OAUTH_CALLBACK_FILTERS = new FilterTemplates[]{ SSL, FORCE_SESSION_CREATION, HANDLE_UNSUCCESSFUL_OAUTH, OAUTH_CALLBACK }; }
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/shiro/management/AtlasRegularSecurity.java
src/main/java/org/ohdsi/webapi/shiro/management/AtlasRegularSecurity.java
package org.ohdsi.webapi.shiro.management; import com.fasterxml.jackson.databind.ObjectMapper; import io.buji.pac4j.filter.CallbackFilter; import io.buji.pac4j.filter.SecurityFilter; import io.buji.pac4j.realm.Pac4jRealm; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.realm.Realm; import org.apache.shiro.realm.activedirectory.ActiveDirectoryRealm; import org.apache.shiro.realm.ldap.DefaultLdapRealm; import org.apache.shiro.realm.ldap.JndiLdapContextFactory; import org.jasig.cas.client.validation.Cas20ServiceTicketValidator; import org.ohdsi.webapi.Constants; import org.ohdsi.webapi.security.model.EntityPermissionSchemaResolver; import org.ohdsi.webapi.shiro.Entities.UserRepository; import org.ohdsi.webapi.shiro.PermissionManager; import org.ohdsi.webapi.shiro.filters.*; import org.ohdsi.webapi.shiro.filters.auth.ActiveDirectoryAuthFilter; import org.ohdsi.webapi.shiro.filters.auth.AtlasJwtAuthFilter; import org.ohdsi.webapi.shiro.filters.auth.JdbcAuthFilter; import org.ohdsi.webapi.shiro.filters.auth.KerberosAuthFilter; import org.ohdsi.webapi.shiro.filters.auth.LdapAuthFilter; import org.ohdsi.webapi.shiro.filters.auth.SamlHandleFilter; import org.ohdsi.webapi.shiro.mapper.ADUserMapper; import org.ohdsi.webapi.shiro.mapper.LdapUserMapper; import org.ohdsi.webapi.shiro.realms.ADRealm; import org.ohdsi.webapi.shiro.realms.JdbcAuthRealm; import org.ohdsi.webapi.shiro.realms.JwtAuthRealm; import org.ohdsi.webapi.shiro.realms.KerberosAuthRealm; import org.ohdsi.webapi.shiro.realms.LdapRealm; import org.ohdsi.webapi.user.importer.providers.LdapProvider; import org.ohdsi.webapi.util.ResourceUtils; import org.opensaml.saml.common.xml.SAMLConstants; import org.pac4j.cas.client.CasClient; import org.pac4j.cas.config.CasConfiguration; import org.pac4j.core.client.Client; import org.pac4j.core.client.Clients; import org.pac4j.core.config.Config; import org.pac4j.core.http.callback.CallbackUrlResolver; import org.pac4j.core.http.callback.PathParameterCallbackUrlResolver; import org.pac4j.core.http.callback.QueryParameterCallbackUrlResolver; import org.pac4j.http.client.direct.HeaderClient; import org.pac4j.oauth.client.FacebookClient; import org.pac4j.oauth.client.GitHubClient; import org.pac4j.oauth.client.Google2Client; import org.pac4j.oidc.client.OidcClient; import org.pac4j.oidc.config.OidcConfiguration; import org.pac4j.oidc.credentials.authenticator.UserInfoOidcAuthenticator; import org.pac4j.saml.client.SAML2Client; import org.pac4j.saml.config.SAML2Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.DependsOn; import org.springframework.ldap.core.LdapTemplate; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import waffle.shiro.negotiate.NegotiateAuthenticationFilter; import waffle.shiro.negotiate.NegotiateAuthenticationRealm; import javax.naming.Context; import javax.servlet.Filter; import javax.sql.DataSource; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; import static com.odysseusinc.arachne.commons.utils.QuoteUtils.dequote; import static org.ohdsi.webapi.shiro.management.FilterTemplates.*; @Component @ConditionalOnProperty(name = "security.provider", havingValue = Constants.SecurityProviders.REGULAR) @DependsOn("flyway") public class AtlasRegularSecurity extends AtlasSecurity { private final Logger logger = LoggerFactory.getLogger(AtlasRegularSecurity.class); @Value("${security.token.expiration}") private int tokenExpirationIntervalInSeconds; @Value("${security.oauth.callback.ui}") private String oauthUiCallback; @Value("${security.oauth.callback.api}") private String oauthApiCallback; @Value("${security.oauth.callback.urlResolver}") private String oauthCallbackUrlResolver; @Value("${security.oauth.google.apiKey}") private String googleApiKey; @Value("${security.oauth.google.apiSecret}") private String googleApiSecret; @Value("${security.oauth.facebook.apiKey}") private String facebookApiKey; @Value("${security.oauth.facebook.apiSecret}") private String facebookApiSecret; @Value("${security.oauth.github.apiKey}") private String githubApiKey; @Value("${security.oauth.github.apiSecret}") private String githubApiSecret; @Value("${security.kerberos.spn}") private String kerberosSpn; @Value("${security.kerberos.keytabPath}") private String kerberosKeytabPath; @Value("${security.ldap.dn}") private String userDnTemplate; @Value("${security.ldap.url}") private String ldapUrl; @Value("${security.ldap.searchString}") private String ldapSearchString; @Value("${security.ldap.searchBase}") private String ldapSearchBase; @Value("${security.ad.url}") private String adUrl; @Value("${security.ad.searchBase}") private String adSearchBase; @Value("${security.ad.principalSuffix}") private String adPrincipalSuffix; @Value("${security.ad.system.username}") private String adSystemUsername; @Value("${security.ad.system.password}") private String adSystemPassword; @Value("${security.db.datasource.authenticationQuery}") private String jdbcAuthenticationQuery; @Value("${security.ad.searchFilter}") private String adSearchFilter; @Value("${security.ad.searchString}") private String adSearchString; @Value("${security.ad.ignore.partial.result.exception}") private Boolean adIgnorePartialResultException; @Value("${security.google.accessToken.enabled}") private Boolean googleAccessTokenEnabled; @Value("${security.saml.keyManager.storePassword}") private String keyStorePassword; @Value("${security.saml.keyManager.passwords.arachnenetwork}") private String privateKeyPassword; @Value("${security.saml.entityId}") private String identityProviderEntityId; @Value("${security.saml.idpMetadataLocation}") private String metadataLocation; @Value("${security.saml.keyManager.keyStoreFile}") private String keyStoreFile; @Value("${security.saml.keyManager.defaultKey}") private String alias; @Value("${security.saml.metadataLocation}") private String spMetadataLocation; @Value("${security.saml.callbackUrl}") private String samlCallbackUrl; @Value("${security.saml.maximumAuthenticationLifetime}") private int maximumAuthenticationLifetime; @Autowired @Qualifier("activeDirectoryProvider") private LdapProvider adLdapProvider; @Autowired @Qualifier("authDataSource") private DataSource jdbcDataSource; @Autowired private UserRepository userRepository; @Autowired private ApplicationEventPublisher eventPublisher; @Autowired private ADUserMapper adUserMapper; @Autowired private LdapUserMapper ldapUserMapper; @Value("${security.oid.redirectUrl}") private String redirectUrl; @Value("${security.cas.loginUrl}") private String casLoginUrl; @Value("${security.cas.callbackUrl}") private String casCallbackUrl; @Value("${security.cas.serverUrl}") private String casServerUrl; @Value("${security.cas.cassvcs}") private String casSvcs; @Value("${security.cas.casticket}") private String casticket; @Value("${security.saml.enabled:false}") private boolean samlEnabled; @Value("${security.auth.windows.enabled}") private boolean windowsAuthEnabled; @Value("${security.auth.kerberos.enabled}") private boolean kerberosAuthEnabled; @Value("${security.auth.jdbc.enabled}") private boolean jdbcAuthEnabled; @Value("${security.auth.ldap.enabled}") private boolean ldapAuthEnabled; @Value("${security.auth.ad.enabled}") private boolean adAuthEnabled; @Value("${security.auth.cas.enabled}") private boolean casAuthEnabled; @Value("${security.auth.openid.enabled}") private boolean openidAuthEnabled; @Value("${security.auth.facebook.enabled}") private boolean facebookAuthEnabled; @Value("${security.auth.github.enabled}") private boolean githubAuthEnabled; @Value("${security.auth.google.enabled}") private boolean googleAuthEnabled; private RestTemplate restTemplate = new RestTemplate(); @Autowired private PermissionManager permissionManager; @Autowired private ObjectMapper objectMapper; public AtlasRegularSecurity(EntityPermissionSchemaResolver permissionSchemaResolver) { super(permissionSchemaResolver); } @Override public Map<FilterTemplates, Filter> getFilters() { Map<FilterTemplates, Filter> filters = super.getFilters(); filters.put(LOGOUT, new LogoutFilter(eventPublisher)); filters.put(UPDATE_TOKEN, new UpdateAccessTokenFilter(this.authorizer, this.defaultRoles, this.tokenExpirationIntervalInSeconds, this.redirectUrl)); filters.put(ACCESS_AUTHC, new GoogleAccessTokenFilter(restTemplate, permissionManager, Collections.emptySet())); filters.put(JWT_AUTHC, new AtlasJwtAuthFilter()); if (this.jdbcAuthEnabled) { filters.put(JDBC_FILTER, new JdbcAuthFilter(eventPublisher)); } if (this.kerberosAuthEnabled) { filters.put(KERBEROS_FILTER, new KerberosAuthFilter()); } if (this.ldapAuthEnabled) { filters.put(LDAP_FILTER, new LdapAuthFilter(eventPublisher)); } if (this.adAuthEnabled) { filters.put(AD_FILTER, new ActiveDirectoryAuthFilter(eventPublisher)); } if (this.windowsAuthEnabled) { filters.put(NEGOTIATE_AUTHC, new NegotiateAuthenticationFilter()); } filters.put(SEND_TOKEN_IN_URL, new SendTokenInUrlFilter(this.oauthUiCallback)); filters.put(SEND_TOKEN_IN_HEADER, new SendTokenInHeaderFilter(this.objectMapper)); filters.put(RUN_AS, new RunAsFilter(userRepository)); // OAuth // CallbackUrlResolver urlResolver = getCallbackUrlResolver(); List<Client> clients = new ArrayList<>(); if (this.googleAuthEnabled) { Google2Client googleClient = new Google2Client(this.googleApiKey, this.googleApiSecret); googleClient.setCallbackUrl(oauthApiCallback); googleClient.setCallbackUrlResolver(urlResolver); googleClient.setScope(Google2Client.Google2Scope.EMAIL_AND_PROFILE); clients.add(googleClient); } if (this.facebookAuthEnabled) { FacebookClient facebookClient = new FacebookClient(this.facebookApiKey, this.facebookApiSecret); facebookClient.setScope("email"); facebookClient.setFields("email"); clients.add(facebookClient); } if (this.githubAuthEnabled) { GitHubClient githubClient = new GitHubClient(this.githubApiKey, this.githubApiSecret); githubClient.setScope("user:email"); clients.add(githubClient); } if (this.openidAuthEnabled) { OidcConfiguration configuration = oidcConfCreator.build(); if (StringUtils.isNotBlank(configuration.getClientId())) { // https://www.pac4j.org/4.0.x/docs/clients/openid-connect.html // OidcClient allows indirect login through UI with code flow OidcClient oidcClient = new OidcClient(configuration); oidcClient.setCallbackUrl(oauthApiCallback); oidcClient.setCallbackUrlResolver(urlResolver); clients.add(oidcClient); // HeaderClient allows api access with a bearer token from the identity provider UserInfoOidcAuthenticator authenticator = new UserInfoOidcAuthenticator(configuration); HeaderClient headerClient = new HeaderClient("Authorization", "Bearer ", authenticator); clients.add(headerClient); } else { logger.warn("openidAuth is enabled but no client id is provided"); } } if (clients.size() > 0) { Config cfg = new Config( new Clients( this.oauthApiCallback, clients ) ); // assign clients to filters if (this.googleAuthEnabled) { SecurityFilter googleOauthFilter = new SecurityFilter(); googleOauthFilter.setConfig(cfg); googleOauthFilter.setClients("Google2Client"); filters.put(GOOGLE_AUTHC, googleOauthFilter); } if (this.facebookAuthEnabled) { SecurityFilter facebookOauthFilter = new SecurityFilter(); facebookOauthFilter.setConfig(cfg); facebookOauthFilter.setClients("FacebookClient"); filters.put(FACEBOOK_AUTHC, facebookOauthFilter); } if (this.githubAuthEnabled) { SecurityFilter githubOauthFilter = new SecurityFilter(); githubOauthFilter.setConfig(cfg); githubOauthFilter.setClients("GitHubClient"); filters.put(GITHUB_AUTHC, githubOauthFilter); } if (this.openidAuthEnabled) { SecurityFilter oidcFilter = new SecurityFilter(); oidcFilter.setConfig(cfg); oidcFilter.setClients("OidcClient"); filters.put(OIDC_AUTH, oidcFilter); SecurityFilter oidcDirectFilter = new SecurityFilter(); oidcDirectFilter.setConfig(cfg); oidcDirectFilter.setClients("HeaderClient"); filters.put(OIDC_DIRECT_AUTH, oidcDirectFilter); } CallbackFilter callbackFilter = new CallbackFilter(); callbackFilter.setConfig(cfg); filters.put(OAUTH_CALLBACK, callbackFilter); filters.put(HANDLE_UNSUCCESSFUL_OAUTH, new RedirectOnFailedOAuthFilter(this.oauthUiCallback)); } if (this.casAuthEnabled) { this.setUpCAS(filters); } if (this.samlEnabled) { this.setUpSaml(filters); } return filters; } @Override protected FilterChainBuilder getFilterChainBuilder() { List<FilterTemplates> authcFilters = googleAccessTokenEnabled ? Arrays.asList(ACCESS_AUTHC, JWT_AUTHC) : Collections.singletonList(JWT_AUTHC); // the order does matter - first match wins FilterChainBuilder filterChainBuilder = new FilterChainBuilder() .setRestFilters(SSL, NO_SESSION_CREATION, CORS, NO_CACHE) .setAuthcFilter(authcFilters.toArray(new FilterTemplates[0])) .setAuthzFilter(AUTHZ) // login/logout .addRestPath("/user/refresh", JWT_AUTHC, UPDATE_TOKEN, SEND_TOKEN_IN_HEADER) .addProtectedRestPath("/user/runas", RUN_AS, UPDATE_TOKEN, SEND_TOKEN_IN_HEADER) .addRestPath("/user/logout", LOGOUT); // MUST be called before adding OAuth filters if (this.openidAuthEnabled || this.googleAuthEnabled || this.facebookAuthEnabled || this.githubAuthEnabled) { filterChainBuilder .setBeforeOAuthFilters(SSL, CORS, FORCE_SESSION_CREATION) .setAfterOAuthFilters(UPDATE_TOKEN, SEND_TOKEN_IN_URL) .addPath("/user/oauth/callback", OAUTH_CALLBACK_FILTERS) .addPath("/user/oauth/callback/*", OAUTH_CALLBACK_FILTERS); } if (this.openidAuthEnabled) { filterChainBuilder .addRestPath("/user/login/openid", FORCE_SESSION_CREATION, OIDC_AUTH, UPDATE_TOKEN, SEND_TOKEN_IN_URL) .addRestPath("/user/login/openidDirect", FORCE_SESSION_CREATION, OIDC_DIRECT_AUTH, UPDATE_TOKEN, SEND_TOKEN_IN_HEADER); } if (this.googleAuthEnabled) { filterChainBuilder.addOAuthPath("/user/oauth/google", GOOGLE_AUTHC); } if (this.facebookAuthEnabled) { filterChainBuilder.addOAuthPath("/user/oauth/facebook", FACEBOOK_AUTHC); } if (this.githubAuthEnabled) { filterChainBuilder.addOAuthPath("/user/oauth/github", GITHUB_AUTHC); } if (this.kerberosAuthEnabled) { filterChainBuilder.addRestPath("/user/login/kerberos", KERBEROS_FILTER, UPDATE_TOKEN, SEND_TOKEN_IN_HEADER); } if (this.windowsAuthEnabled) { filterChainBuilder.addRestPath("/user/login/windows", NEGOTIATE_AUTHC, UPDATE_TOKEN, SEND_TOKEN_IN_HEADER); } if (this.jdbcAuthEnabled) { filterChainBuilder.addRestPath("/user/login/db", JDBC_FILTER, UPDATE_TOKEN, SEND_TOKEN_IN_HEADER); } if (this.ldapAuthEnabled) { filterChainBuilder.addRestPath("/user/login/ldap", LDAP_FILTER, UPDATE_TOKEN, SEND_TOKEN_IN_HEADER); } if (this.adAuthEnabled) { filterChainBuilder.addRestPath("/user/login/ad", AD_FILTER, UPDATE_TOKEN, SEND_TOKEN_IN_HEADER); } if (this.casAuthEnabled) { filterChainBuilder .addPath("/user/login/cas", SSL, CORS, FORCE_SESSION_CREATION, CAS_AUTHC, UPDATE_TOKEN, SEND_TOKEN_IN_URL) .addPath("/user/cas/callback", SSL, HANDLE_CAS, UPDATE_TOKEN, SEND_TOKEN_IN_URL); } if (this.samlEnabled) { filterChainBuilder .addPath("/user/login/saml", SSL, CORS, FORCE_SESSION_CREATION, SAML_AUTHC, UPDATE_TOKEN, SEND_TOKEN_IN_URL) .addPath("/user/login/samlForce", SSL, CORS, FORCE_SESSION_CREATION, SAML_AUTHC_FORCE, UPDATE_TOKEN, SEND_TOKEN_IN_URL) .addPath("/user/saml/callback", SSL, HANDLE_SAML, UPDATE_TOKEN, SEND_TOKEN_IN_URL); } setupProtectedPaths(filterChainBuilder); return filterChainBuilder.addRestPath("/**"); } @Override public Set<Realm> getRealms() { Set<Realm> realms = super.getRealms(); realms.add(new JwtAuthRealm(this.authorizer)); if (this.windowsAuthEnabled) { realms.add(new NegotiateAuthenticationRealm()); } realms.add(new Pac4jRealm()); if (jdbcAuthEnabled && jdbcDataSource != null) { realms.add(new JdbcAuthRealm(jdbcDataSource, jdbcAuthenticationQuery)); } if (this.kerberosAuthEnabled) { realms.add(new KerberosAuthRealm(kerberosSpn, kerberosKeytabPath)); } if (this.ldapAuthEnabled) { realms.add(ldapRealm()); } if (this.adAuthEnabled) { realms.add(activeDirectoryRealm()); } return realms; } private OidcClient getOidcClient() { OidcConfiguration configuration = oidcConfCreator.build(); return new OidcClient(configuration); } private GitHubClient getGitHubClient() { GitHubClient githubClient = new GitHubClient(this.githubApiKey, this.githubApiSecret); githubClient.setScope("user:email"); return githubClient; } private FacebookClient getFacebookClient() { FacebookClient facebookClient = new FacebookClient(this.facebookApiKey, this.facebookApiSecret); facebookClient.setScope("email"); facebookClient.setFields("email"); return facebookClient; } private void setUpSaml(Map<FilterTemplates, Filter> filters) { try { SAML2Client client = setUpSamlClient(filters, SAML_AUTHC, false); SAML2Client clientForce = setUpSamlClient(filters, SAML_AUTHC_FORCE, true); SamlHandleFilter samlHandleFilter = new SamlHandleFilter(client, clientForce, this.oauthUiCallback); filters.put(HANDLE_SAML, samlHandleFilter); samlEnabled = true; } catch (Exception e) { samlEnabled = false; filters.remove(SAML_AUTHC_FORCE); filters.remove(SAML_AUTHC); filters.remove(HANDLE_SAML); logger.error("Failed to initlize SAML filters: " + e.getMessage()); } } private SAML2Client setUpSamlClient(Map<FilterTemplates, Filter> filters, FilterTemplates template, boolean isForcedAuth) { final SAML2Configuration cfg = new SAML2Configuration( ResourceUtils.mapPathToResource(keyStoreFile), alias, null, keyStorePassword, privateKeyPassword, ResourceUtils.mapPathToResource(metadataLocation)); cfg.setMaximumAuthenticationLifetime(this.maximumAuthenticationLifetime); cfg.setServiceProviderEntityId(identityProviderEntityId); cfg.setForceAuth(isForcedAuth); cfg.setServiceProviderMetadataPath(spMetadataLocation); cfg.setAuthnRequestBindingType(SAMLConstants.SAML2_REDIRECT_BINDING_URI); final SAML2Client saml2Client = new SAML2Client(cfg); Config samlCfg = new Config(new Clients(samlCallbackUrl, saml2Client)); SecurityFilter samlAuthFilter = new SecurityFilter(); samlAuthFilter.setConfig(samlCfg); samlAuthFilter.setClients("saml2Client"); filters.put(template, samlAuthFilter); return saml2Client; } private Google2Client getGoogle2Client() { Google2Client googleClient = new Google2Client(this.googleApiKey, this.googleApiSecret); googleClient.setScope(Google2Client.Google2Scope.EMAIL); return googleClient; } private DefaultLdapRealm ldapRealm() { DefaultLdapRealm realm = new LdapRealm(ldapSearchString, ldapSearchBase, ldapUserMapper); JndiLdapContextFactory contextFactory = new JndiLdapContextFactory(); contextFactory.setUrl(dequote(ldapUrl)); contextFactory.setPoolingEnabled(false); contextFactory.getEnvironment().put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); realm.setContextFactory(contextFactory); if (StringUtils.isNotEmpty(userDnTemplate)) { realm.setUserDnTemplate(dequote(userDnTemplate)); } return realm; } private ActiveDirectoryRealm activeDirectoryRealm() { ActiveDirectoryRealm realm = new ADRealm(getLdapTemplate(), adSearchFilter, adSearchString, adUserMapper); realm.setUrl(dequote(adUrl)); realm.setSearchBase(dequote(adSearchBase)); realm.setPrincipalSuffix(dequote(adPrincipalSuffix)); realm.setSystemUsername(dequote(adSystemUsername)); realm.setSystemPassword(dequote(adSystemPassword)); return realm; } private LdapTemplate getLdapTemplate() { if (StringUtils.isNotBlank(adSearchFilter)) { return adLdapProvider.getLdapTemplate(); } return null; } private void setUpCAS(Map<FilterTemplates, Filter> filters) { try { /** * CAS config */ CasConfiguration casConf = new CasConfiguration(); String casLoginUrlString; if (casSvcs != null && !"".equals(casSvcs)) { casLoginUrlString = casLoginUrl + "?cassvc=" + casSvcs + "&casurl=" + URLEncoder.encode(casCallbackUrl, StandardCharsets.UTF_8.name()); } else { casLoginUrlString = casLoginUrl + "?casurl=" + URLEncoder.encode(casCallbackUrl, StandardCharsets.UTF_8.name()); } casConf.setLoginUrl(casLoginUrlString); Cas20ServiceTicketValidator cas20Validator = new Cas20ServiceTicketValidator(casServerUrl); casConf.setDefaultTicketValidator(cas20Validator); CasClient casClient = new CasClient(casConf); Config casCfg = new Config(new Clients(casCallbackUrl, casClient)); /** * CAS filter */ SecurityFilter casAuthnFilter = new SecurityFilter(); casAuthnFilter.setConfig(casCfg); casAuthnFilter.setClients("CasClient"); filters.put(CAS_AUTHC, casAuthnFilter); /** * CAS callback filter */ CasHandleFilter casHandleFilter = new CasHandleFilter(cas20Validator, casCallbackUrl, casticket); filters.put(HANDLE_CAS, casHandleFilter); } catch (UnsupportedEncodingException e) { this.logger.error("Atlas security filter errors: {}", e); } } private CallbackUrlResolver getCallbackUrlResolver() { CallbackUrlResolver resolver = new QueryParameterCallbackUrlResolver(); if (Constants.CallbackUrlResolvers.PATH.equals(oauthCallbackUrlResolver)) { resolver = new PathParameterCallbackUrlResolver(); } else if (!Constants.CallbackUrlResolvers.QUERY.equals(oauthCallbackUrlResolver)) { this.logger.warn("OAuth Callback Url Resolver {} not supported, ignored and used default QueryParameterUrlResolver", oauthCallbackUrlResolver); } return resolver; } public boolean isSamlEnabled() { return samlEnabled; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false