src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
|---|---|
TransitiveStaffToStaffValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean transitive) { return transitive && EntityNames.STAFF.equals(entityType) && isStaff(); } @Override boolean canValidate(String entityType, boolean transitive); @SuppressWarnings("unchecked") @Override Set<String> validate(String entityName, Set<String> staffIds); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateTeacherToStaff() throws Exception { setupCurrentUser(staff1); assertTrue(validator.canValidate(EntityNames.STAFF, true)); assertFalse(validator.canValidate(EntityNames.STAFF, false)); assertFalse(validator.canValidate(EntityNames.SECTION, false)); assertFalse(validator.canValidate(EntityNames.SECTION, true)); }
|
TransitiveStaffToStaffValidator extends AbstractContextValidator { @SuppressWarnings("unchecked") @Override public Set<String> validate(String entityName, Set<String> staffIds) throws IllegalStateException { if (!areParametersValid(EntityNames.STAFF, entityName, staffIds)) { return Collections.EMPTY_SET; } Set<String> validIds = new HashSet<String>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria("staffReference", NeutralCriteria.CRITERIA_IN, staffIds)); basicQuery.setIncludeFields(Arrays.asList("educationOrganizationReference", "staffReference")); LOG.info("Attempting to validate transitively from staff to staff with ids {}", staffIds); injectEndDateQuery(basicQuery); Iterable<Entity> edOrgAssoc = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); Map<String, Set<String>> staffEdorgMap = new HashMap<String, Set<String>>(); populateMapFromMongoResponse(staffEdorgMap, edOrgAssoc); Set<String> edOrgLineage = getStaffEdOrgLineage(); if (edOrgLineage.isEmpty() || staffEdorgMap.isEmpty()) { return Collections.EMPTY_SET; } for (Entry<String, Set<String>> entry : staffEdorgMap.entrySet()) { Set<String> tmpSet = new HashSet<String>(entry.getValue()); tmpSet.retainAll(edOrgLineage); if (tmpSet.size() != 0) { validIds.add(entry.getKey()); } } validIds.addAll(validateThrough(EntityNames.STAFF_PROGRAM_ASSOCIATION, "programId")); validIds.addAll(validateThrough(EntityNames.STAFF_COHORT_ASSOCIATION, "cohortId")); basicQuery = new NeutralQuery(new NeutralCriteria("_id", "in", edOrgLineage)); Iterable<Entity> edorgs = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, basicQuery); List<String> programs = new ArrayList<String>(); for (Entity e : edorgs) { Object value = e.getBody().get("programReference"); if (value != null) { if (List.class.isAssignableFrom(value.getClass())) { programs.addAll((List<String>) value); } else if (String.class.isAssignableFrom(value.getClass())) { programs.add((String) value); } } } validIds.addAll(getIds(EntityNames.STAFF_PROGRAM_ASSOCIATION, "programId", programs)); basicQuery = new NeutralQuery(new NeutralCriteria("educationOrgId", "in", edOrgLineage)); List<String> cohorts = (List<String>) repo.findAllIds(EntityNames.COHORT, basicQuery); validIds.addAll(getIds(EntityNames.STAFF_COHORT_ASSOCIATION, "cohortId", cohorts)); validIds.retainAll(staffIds); return validIds; } @Override boolean canValidate(String entityType, boolean transitive); @SuppressWarnings("unchecked") @Override Set<String> validate(String entityName, Set<String> staffIds); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testValidStaffStaffAssociationNoEndDate() { setupCurrentUser(staff1); Set<String> staffId = new HashSet<String>(Arrays.asList(staff2.getEntityId())); assertTrue(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); assertTrue(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); }
@Test public void testValidStaffStaffAssociationWithEndDate() { setupCurrentUser(staff1); Set<String> staffId = new HashSet<String>(Arrays.asList(staff3.getEntityId())); assertTrue(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); }
@Test public void testExpiredStaffStaffAssociation() { setupCurrentUser(staff1); Set<String> staffId = new HashSet<String>(Arrays.asList(staff4.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); }
@Test public void testStaffWithNoEdorgAssociation() { setupCurrentUser(staff1); Set<String> staffId = new HashSet<String>(Arrays.asList(staff2.getEntityId(), staff5.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); }
@Test public void testSchoolStaffToLEAStaffAssociation() { setupCurrentUser(staff2); Set<String> staffId = new HashSet<String>(Arrays.asList(staff1.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); }
@Test public void testMulti1() { setupCurrentUser(staff1); Set<String> staffId = new HashSet<String>(Arrays.asList(staff1.getEntityId(), staff2.getEntityId(), staff3.getEntityId(), staff4.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); }
@Test public void testMulti2() { setupCurrentUser(staff1); Set<String> staffId = new HashSet<String>(Arrays.asList(staff1.getEntityId(), staff4.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); }
@Test public void testMulti3() { setupCurrentUser(staff1); Set<String> staffId = new HashSet<String>(Arrays.asList(staff2.getEntityId(), staff3.getEntityId())); assertTrue(validator.validate(EntityNames.STAFF, staffId).equals(staffId)); }
|
TenantProcessor implements Processor { boolean preLoad(String landingZone, List<String> dataSets) { File landingZoneDir = new File(landingZone); if (!landingZoneDir.exists()) { try { FileUtils.forceMkdir(landingZoneDir); } catch (IOException e) { LOG.error("TenantProcessor: Failed to create landing zone: {} with absolute path {}", landingZone, landingZoneDir.getAbsolutePath()); return false; } } if (landingZoneDir.exists() && landingZoneDir.isDirectory()) { boolean result = true; for (String dataSet : dataSets) { List<String> fileNames = getDataSetLookup().get(dataSet); if (fileNames != null) { for (String fileName : fileNames) { URL fileLocation = Thread.currentThread().getContextClassLoader().getResource(fileName); try { InputStream sampleFile = fileLocation == null ? new FileInputStream(fileName) : fileLocation.openStream(); result &= sendToLandingZone(landingZoneDir, sampleFile); } catch (FileNotFoundException e) { LOG.error("sample data set {} doesn't exists", fileName); result = false; } catch (IOException e) { LOG.error("error loading sample data set", e); } } } else { result = false; } } return result; } return false; } @Override void process(Exchange exchange); static final String TENANT_POLL_HEADER; static final String TENANT_POLL_SUCCESS; static final String TENANT_POLL_FAILURE; }
|
@Test public void testPreLoad() { File landingZone = Files.createTempDir(); try { assertTrue(tenantProcessor.preLoad(landingZone.getAbsolutePath(), Arrays.asList("small"))); assertTrue(landingZone.list(new WildcardFileFilter("preload-*.zip")).length == 1); } finally { landingZone.delete(); } }
@Test public void testPreLoadBadDataSet() { File landingZone = Files.createTempDir(); try { assertTrue(!tenantProcessor.preLoad(landingZone.getAbsolutePath(), Arrays.asList("smallish"))); } finally { landingZone.delete(); } }
|
TransitiveTeacherToTeacherSchoolAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.TEACHER_SCHOOL_ASSOCIATION, entityType, ids)) { return Collections.emptySet(); } NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); Iterable<Entity> tsa = getRepo().findAll(EntityNames.TEACHER_SCHOOL_ASSOCIATION, nq); Set<String> teachers = new HashSet<String>(); Map<String, Set<String>> teacherToTSA = new HashMap<String, Set<String>>(); for (Entity e : tsa) { String teacherId = (String) e.getBody().get(ParameterConstants.TEACHER_ID); teachers.add(teacherId); if(!teacherToTSA.containsKey(teacherId)) { teacherToTSA.put(teacherId, new HashSet<String>()); } teacherToTSA.get(teacherId).add(e.getEntityId()); } Set<String> validTeacherIds = val.validate(EntityNames.TEACHER, teachers); return getValidIds(validTeacherIds, teacherToTSA); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test(expected = IllegalArgumentException.class) public void testValidateWrongType() { val.validate(EntityNames.ASSESSMENT, new HashSet<String>(Arrays.asList("Jomolungma"))); }
@Test public void testSuccessOne() { this.vth.generateTeacherSchool(USER_ID, SCHOOL_ID); Entity tsa = this.vth.generateTeacherSchool("Heru-er", SCHOOL_ID); Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, Collections.singleton(tsa.getEntityId())).contains(tsa.getEntityId())); tsa = this.vth.generateTeacherSchool("Izida", SCHOOL_ID); Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, Collections.singleton(tsa.getEntityId())).contains(tsa.getEntityId())); tsa = this.vth.generateTeacherSchool("Ptah", SCHOOL_ID); Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, Collections.singleton(tsa.getEntityId())).contains(tsa.getEntityId())); }
@Test public void testSuccessMulti() { this.vth.generateTeacherSchool(USER_ID, SCHOOL_ID); Set<String> ids = new HashSet<String>(); for (int i = 0; i < 100; i++) { ids.add(this.vth.generateTeacherSchool("Thor" + i, SCHOOL_ID).getEntityId()); } Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, ids).containsAll(ids)); }
@Test public void testWrongId() { Set<String> idsToValidate = Collections.singleton("Hammerhands"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, idsToValidate).containsAll(idsToValidate)); idsToValidate = Collections.singleton("Nagas"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, idsToValidate).containsAll(idsToValidate)); idsToValidate = Collections.singleton("Phantom Warriors"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, idsToValidate).containsAll(idsToValidate)); }
@Test public void testHeterogenousList() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(this.vth.generateTeacherSchool(USER_ID, SCHOOL_ID).getEntityId(), this.vth.generateTeacherSchool("Ssss'ra", "Arcanus").getEntityId(), this.vth.generateTeacherSchool("Kali", "Arcanus") .getEntityId())); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, idsToValidate).containsAll(idsToValidate)); }
|
GenericToGlobalBellScheduleWriteValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.BELL_SCHEDULE, entityType, ids)) { return Collections.emptySet(); } Set<String> edOrgLineage = getEdorgDescendents(getDirectEdorgs()); NeutralQuery classPeriodsQuery = new NeutralQuery(); classPeriodsQuery.addCriteria(new NeutralCriteria(ParameterConstants.EDUCATION_ORGANIZATION_ID, NeutralCriteria.CRITERIA_IN, edOrgLineage)); List<String> myClassPeriods = Lists.newArrayList(getRepo().findAllIds("classPeriod", classPeriodsQuery)); NeutralQuery bellSchedulesQuery = new NeutralQuery(); bellSchedulesQuery.addCriteria(new NeutralCriteria("meetingTime.classPeriodId", NeutralCriteria.CRITERIA_IN, myClassPeriods)); bellSchedulesQuery.addCriteria(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids, false)); Set<String> myBellSchedules = Sets.newHashSet(getRepo().findAllIds("bellSchedule", bellSchedulesQuery)); return myBellSchedules; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testFilterbellScheduleDataFromLEA() { setupStaff(staffLea, lea.getEntityId()); Set<String> expectedIds = new HashSet<String>(Arrays.asList(bellScheduleLea.getEntityId(), bellScheduleSchoolLea.getEntityId())); Set<String> actual = validator.validate(EntityNames.BELL_SCHEDULE, bellScheduleIds); Assert.assertEquals(expectedIds, actual); }
@Test public void testFilterClassPeriodDataFromSchool() { setupStaff(staffSchoolLea, schoolParentLea.getEntityId()); Set<String> expectedIds = new HashSet<String>(Arrays.asList(bellScheduleSchoolLea.getEntityId())); Set<String> actual = validator.validate(EntityNames.BELL_SCHEDULE, bellScheduleIds); Assert.assertEquals(expectedIds, actual); }
@Test public void testFilterClassPeriodDataFromSchool2() { setupStaff(staffSchoolNoParent, schoolNoParent.getEntityId()); Set<String> expectedIds = new HashSet<String>(Arrays.asList(bellScheduleSchoolNoParent.getEntityId())); Set<String> actual = validator.validate(EntityNames.BELL_SCHEDULE, bellScheduleIds); Assert.assertEquals(expectedIds, actual); }
|
TeacherToStudentValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean through) { return EntityNames.STUDENT.equals(entityType) && isTeacher(); } @Override boolean canValidate(String entityType, boolean through); @Override Set<String> validate(String entityName, Set<String> ids); @Override Set<String> getValid(String entityType, Set<String> ids); @Override void setRepo(PagingRepositoryDelegate<Entity> repo); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateTeacherToStudent() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT, false)); }
@Test public void testCanNotValidateOtherEntities() throws Exception { assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); }
|
TeacherToStudentValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityName, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STUDENT, entityName, ids)) { return Collections.emptySet(); } Set<String> idsToValidate = new HashSet<String>(ids); Set<String> validIds = new HashSet<String>(); Set<String> validWithSections = getValidatedWithSections(idsToValidate); idsToValidate.removeAll(validWithSections); validIds.addAll(validWithSections); if (idsToValidate.isEmpty()) { validIds.retainAll(ids); return validIds; } Set<String> validWithPrograms = getValidatedWithPrograms(idsToValidate); idsToValidate.removeAll(validWithPrograms); validIds.addAll(validWithPrograms); if (idsToValidate.isEmpty()) { validIds.retainAll(ids); return validIds; } validIds.addAll(getValidatedWithCohorts(idsToValidate)); validIds.retainAll(ids); return validIds; } @Override boolean canValidate(String entityType, boolean through); @Override Set<String> validate(String entityName, Set<String> ids); @Override Set<String> getValid(String entityType, Set<String> ids); @Override void setRepo(PagingRepositoryDelegate<Entity> repo); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanGetAccessThroughSingleValidStudent() throws Exception { helper.generateTSA(TEACHER_ID, "3", false); helper.generateSSA("2", "3", false); studentIds.add("2"); Assert.assertEquals(validator.validate(EntityNames.STUDENT, studentIds), studentIds); }
@Test public void testCanNotGetAccessThroughInvalidStudent() throws Exception { helper.generateTSA(TEACHER_ID, "-1", false); helper.generateSSA("2", "3", false); studentIds.add("2"); Assert.assertFalse(validator.validate(EntityNames.STUDENT, studentIds).containsAll(studentIds)); }
@Test public void testCanGetAccessThroughManyStudents() throws Exception { for (int i = 0; i < 100; ++i) { helper.generateTSA(TEACHER_ID, "" + i, false); } for (int i = 0; i < 100; ++i) { for (int j = -1; j > -31; --j) { helper.generateSSA(String.valueOf(j), "" + i, false); studentIds.add(String.valueOf(j)); } } Assert.assertEquals(validator.validate(EntityNames.STUDENT, studentIds).size(), studentIds.size()); }
@Test public void testCantGetAccessThroughManyStudents() throws Exception { for (int i = 0; i < 2; ++i) { helper.generateTSA(TEACHER_ID, String.valueOf(i), false); } for (int i = 0; i < 2; ++i) { for (int j = -1; j > -2; --j) { helper.generateSSA(String.valueOf(j), String.valueOf(i), false); studentIds.add(String.valueOf(j)); } } helper.generateSSA("100", "6", false); studentIds.add("100"); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).containsAll(studentIds)); }
@Test public void testCanGetAccessThroughStudentsWithManySections() throws Exception { helper.generateTSA(TEACHER_ID, "0", false); for (int i = 0; i < 10; ++i) { helper.generateSSA("2", String.valueOf(i), false); studentIds.add("2"); } Assert.assertEquals(validator.validate(EntityNames.STUDENT, studentIds).size(), studentIds.size()); }
@Test public void testCanNotGetAccessThroughManyStudents() throws Exception { for (int i = 100; i < 200; ++i) { helper.generateTSA(TEACHER_ID, "" + i, false); } for (int i = 0; i < 100; ++i) { for (int j = -1; j > -31; --j) { helper.generateSSA("" + j, "" + i, false); studentIds.add("" + j); } } assertFalse(validator.validate(EntityNames.STUDENT, studentIds).size() == studentIds.size()); }
@Test public void testCanNotGetAccessThroughManyStudentsWithOneFailure() throws Exception { for (int i = 0; i < 100; ++i) { helper.generateTSA(TEACHER_ID, "" + i, false); } for (int i = 0; i < 100; ++i) { for (int j = -1; j > -31; --j) { helper.generateSSA("" + j, "" + i, false); studentIds.add("" + j); } } helper.generateSSA("-32", "101", false); studentIds.add("-32"); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).size() == studentIds.size()); }
@Test @Ignore public void testCanGetAccessThroughValidCohort() throws Exception { helper.generateTeacherSchool(TEACHER_ID, ED_ORG_ID); String cohortId = helper.generateCohort(ED_ORG_ID).getEntityId(); helper.generateStaffCohort(TEACHER_ID, cohortId, false, true); for (int i = 0; i < 10; ++i) { helper.generateStudentCohort(i + "", cohortId, false); studentIds.add(i + ""); } Assert.assertEquals(validator.validate(EntityNames.STUDENT, studentIds).size(), studentIds.size()); }
@Test public void testCanNotGetAccessThroughExpiredCohort() throws Exception { assertTrue(validator.validate(EntityNames.STUDENT, studentIds).isEmpty()); }
@Test public void testCanNotGetAccessThroughDeniedCohort() throws Exception { helper.generateTeacherSchool(TEACHER_ID, ED_ORG_ID); String cohortId = helper.generateCohort(ED_ORG_ID).getEntityId(); helper.generateStaffCohort(TEACHER_ID, cohortId, false, false); for (int i = 0; i < 10; ++i) { helper.generateStudentCohort(i + "", cohortId, false); studentIds.add(i + ""); } assertFalse(validator.validate(EntityNames.STUDENT, studentIds).size() == studentIds.size()); }
@Test public void testCanNotGetAccessThroughInvalidCohort() throws Exception { helper.generateTeacherSchool(TEACHER_ID, ED_ORG_ID); String cohortId = helper.generateCohort(ED_ORG_ID).getEntityId(); helper.generateStaffCohort(TEACHER_ID, cohortId, false, true); for (int i = 0; i < 10; ++i) { helper.generateStudentCohort(i + "", "" + i * -1, false); studentIds.add(i + ""); } assertFalse(validator.validate(EntityNames.STUDENT, studentIds).size() == studentIds.size()); }
@Test @Ignore public void testCanNotGetAccessThroughCohortOutsideOfEdorg() throws Exception { helper.generateTeacherSchool(TEACHER_ID, ED_ORG_ID); String cohortId = helper.generateCohort("122").getEntityId(); helper.generateStaffCohort(TEACHER_ID, cohortId, false, true); for (int i = 0; i < 10; ++i) { helper.generateStudentCohort(i + "", cohortId, false); studentIds.add(i + ""); } assertFalse(validator.validate(EntityNames.STUDENT, studentIds).size() == studentIds.size()); }
@Test public void testCohortAccessIntersectionRules() throws Exception { assertTrue(validator.validate(EntityNames.STUDENT, studentIds).isEmpty()); }
@Test public void testCanGetAccessThroughValidProgram() throws Exception { String edOrgId = helper.generateEdorgWithProgram(Arrays.asList(programId)).getEntityId(); helper.generateTeacherSchool(TEACHER_ID, edOrgId); helper.generateStaffProgram(TEACHER_ID, programId, false, true); for (int i = 0; i < 10; ++i) { helper.generateStudentProgram(i + "", programId, false); studentIds.add(i + ""); } Assert.assertEquals(validator.validate(EntityNames.STUDENT, studentIds).size(), studentIds.size()); }
@Test public void testCanAccessStudentsThoughSectionAndProgramAssociations() throws Exception { String studentId1 = "STUDENT11"; String studentId2 = "STUDENT22"; helper.generateTSA(TEACHER_ID, SECTION_ID, false); helper.generateSSA(studentId1, SECTION_ID, false); studentIds.add(studentId1); String edOrgId = helper.generateEdorgWithProgram(Arrays.asList(programId)).getEntityId(); helper.generateTeacherSchool(TEACHER_ID, edOrgId); helper.generateStaffProgram(TEACHER_ID, programId, false, true); helper.generateStudentProgram(studentId2, programId, false); studentIds.add(studentId2); Assert.assertEquals(validator.validate(EntityNames.STUDENT, studentIds).size(), studentIds.size()); }
@Test public void testCanNotGetAccessThroughExpiredProgram() throws Exception { assertTrue(validator.validate(EntityNames.STUDENT, studentIds).isEmpty()); }
@Test public void testCanNotGetAccessThroughDeniedProgram() throws Exception { String edOrgId = helper.generateEdorgWithProgram(Arrays.asList(programId)).getEntityId(); helper.generateTeacherSchool(TEACHER_ID, edOrgId); helper.generateStaffProgram(TEACHER_ID, programId, false, false); for (int i = 0; i < 10; ++i) { helper.generateStudentProgram(i + "", programId, false); studentIds.add(i + ""); } assertFalse(validator.validate(EntityNames.STUDENT, studentIds).size() == studentIds.size()); }
@Test public void testCanNotGetAccessThroughWithOneDeniedProgram() throws Exception { String edOrgId = helper.generateEdorgWithProgram(Arrays.asList(programId)).getEntityId(); helper.generateTeacherSchool(TEACHER_ID, edOrgId); helper.generateStaffProgram(TEACHER_ID, programId, false, true); for (int i = 0; i < 10; ++i) { helper.generateStudentProgram(i + "", programId, false); studentIds.add(i + ""); } helper.generateStudentProgram("-32", "101", false); studentIds.add("-32"); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).size() == studentIds.size()); }
@Test public void testCanNotGetAccessThroughInvalidProgram() throws Exception { String edOrgId = helper.generateEdorgWithProgram(Arrays.asList(programId)).getEntityId(); helper.generateTeacherSchool(TEACHER_ID, edOrgId); helper.generateStaffProgram(TEACHER_ID, programId, false, true); for (int i = 0; i < 10; ++i) { helper.generateStudentProgram(i + "", "" + i * -1, false); studentIds.add(i + ""); } assertFalse(validator.validate(EntityNames.STUDENT, studentIds).size() == studentIds.size()); }
@Test public void testProgramAccessIntersectionRules() throws Exception { assertTrue(validator.validate(EntityNames.STUDENT, studentIds).isEmpty()); }
|
EdFiParserProcessor extends IngestionProcessor<FileEntryWorkNote, IngestionFileEntry> implements
RecordVisitor { @Override protected void process(Exchange exchange, ProcessorArgs<FileEntryWorkNote> args) { prepareState(exchange, args.workNote); Source source = new FileSource(args.workNote.getFileEntry().getResourceId()); Metrics metrics = Metrics.newInstance(args.workNote.getFileEntry().getResourceId()); InputStream input = null; boolean validData = true; try { input = args.workNote.getFileEntry().getFileStream(); Resource xsdSchema = xsdSelector.provideXsdResource(args.workNote.getFileEntry()); parse(input, xsdSchema, args.reportStats, source); metrics.setValidationErrorCount(ignoredRecordCount.get()); } catch (IOException e) { getMessageReport().error(args.reportStats, source, CoreMessageCode.CORE_0061); } catch (SAXException e) { getMessageReport().error(args.reportStats, source, CoreMessageCode.CORE_0062); } catch (XmlParseException e) { getMessageReport().error(args.reportStats, source, CoreMessageCode.CORE_0063); validData = false; } finally { IOUtils.closeQuietly(input); if (validData) { sendDataBatch(); } cleanUpState(); args.job = refreshjob(args.job.getId()); args.stage.addMetrics(metrics); } } @Override void visit(RecordMeta recordMeta, Map<String, Object> record); @Override void ignored(); void sendDataBatch(); @Override AbstractMessageReport getMessageReport(); @Override void setMessageReport(AbstractMessageReport messageReport); @Override String getStageDescription(); @Override BatchJobStageType getStage(); ProducerTemplate getProducer(); void setProducer(ProducerTemplate producer); TypeProvider getTypeProvider(); void setTypeProvider(TypeProvider typeProvider); XsdSelector getXsdSelector(); void setHelper( ReferenceHelper helper ); void setXsdSelector(XsdSelector xsdSelector); int getBatchSize(); void setBatchSize(int batchSize); void audit(SecurityEvent event); }
|
@Test public void testProcess() throws Exception { init(); Exchange exchange = createFileEntryExchange(); Resource xsd = Mockito.mock(Resource.class); Map<String, Resource> xsdList = new HashMap<String, Resource>(); FileEntryWorkNote workNote = (FileEntryWorkNote) exchange.getIn().getMandatoryBody(WorkNote.class); xsdList.put(workNote.getFileEntry().getFileType().getName(), xsd); xsdSelector.setXsdList(xsdList); processor.process(exchange); Mockito.verify(processor, Mockito.times(1)).parse(Mockito.any(InputStream.class), Mockito.any(Resource.class), Mockito.any(SimpleReportStats.class), Mockito.any(JobSource.class)); }
|
EdFiParserProcessor extends IngestionProcessor<FileEntryWorkNote, IngestionFileEntry> implements
RecordVisitor { @Override public void visit(RecordMeta recordMeta, Map<String, Object> record) { state.get().addToBatch(recordMeta, record, typeProvider, helper); if (state.get().getDataBatch().size() >= batchSize) { sendDataBatch(); } } @Override void visit(RecordMeta recordMeta, Map<String, Object> record); @Override void ignored(); void sendDataBatch(); @Override AbstractMessageReport getMessageReport(); @Override void setMessageReport(AbstractMessageReport messageReport); @Override String getStageDescription(); @Override BatchJobStageType getStage(); ProducerTemplate getProducer(); void setProducer(ProducerTemplate producer); TypeProvider getTypeProvider(); void setTypeProvider(TypeProvider typeProvider); XsdSelector getXsdSelector(); void setHelper( ReferenceHelper helper ); void setXsdSelector(XsdSelector xsdSelector); int getBatchSize(); void setBatchSize(int batchSize); void audit(SecurityEvent event); }
|
@Test public void testVisitAndSend() throws Exception { init(); Exchange exchange = createFileEntryExchange(); processor.setUpState(exchange, exchange.getIn().getBody(FileEntryWorkNote.class)); RecordMetaImpl meta = new RecordMetaImpl("student", "student"); Location loc = Mockito.mock(Location.class); Mockito.when(loc.getLineNumber()).thenReturn(1); Mockito.when(loc.getColumnNumber()).thenReturn(1); meta.setSourceStartLocation(loc); meta.setSourceEndLocation(loc); Map<String, Object> body = new HashMap<String, Object>(); body.put("studentUniqueStateId", "studentId"); processor.visit(meta, body); ParserState state = processor.getState(); List<NeutralRecord> records = state.getDataBatch(); Assert.assertNotNull(records); Assert.assertEquals(1, records.size()); Assert.assertEquals("studentId", records.get(0).getAttributes().get("studentUniqueStateId")); Assert.assertEquals("student", records.get(0).getRecordType()); }
|
StaffToSubStudentSectionAssociationEntityValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean through) { return isStaff() && isSubEntityOfStudentSectionAssociation(entityType); } @Override boolean canValidate(String entityType, boolean through); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateStaffToGrade() throws Exception { assertTrue(validator.canValidate(EntityNames.GRADE, false)); assertTrue(validator.canValidate(EntityNames.GRADE, true)); }
@Test public void testCanValidateStaffToStudentCompetency() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_COMPETENCY, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_COMPETENCY, true)); }
@Test public void testDeniedStaffToOtherEntity() throws Exception { assertFalse(validator.canValidate(EntityNames.STUDENT, false)); assertFalse(validator.canValidate(EntityNames.STUDENT, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_COMPETENCY_OBJECTIVE, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_COMPETENCY_OBJECTIVE, true)); }
|
StaffToSubStudentSectionAssociationEntityValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(SUB_ENTITIES_OF_STUDENT_SECTION, entityType, ids)) { return Collections.EMPTY_SET; } Map<String, Set<String>> studentSectionAssociationIds = getIdsContainedInFieldOnEntities(entityType, new ArrayList<String>( ids), ParameterConstants.STUDENT_SECTION_ASSOCIATION_ID); if (studentSectionAssociationIds.isEmpty()) { return Collections.EMPTY_SET; } Map<String, Set<String>> studentIds = getIdsContainedInFieldOnEntities(EntityNames.STUDENT_SECTION_ASSOCIATION, new ArrayList<String>(studentSectionAssociationIds.keySet()), ParameterConstants.STUDENT_ID); if (studentIds.isEmpty()) { return Collections.EMPTY_SET; } Set<String> validStudents = validator.validate(EntityNames.STUDENT, studentIds.keySet()); Set<String> validSSA = getValidIds(validStudents, studentIds); return getValidIds(validSSA, studentSectionAssociationIds); } @Override boolean canValidate(String entityType, boolean through); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanGetAccessToGrade() throws Exception { Set<String> grades = new HashSet<String>(); Map<String, Object> association = buildStudentSectionAssociation("student123", "section123", DateTime.now() .minusDays(3)); Entity studentSectionAssociation = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, "ssa123", association, null); Entity gradeEntity = helper.generateGrade(studentSectionAssociation.getEntityId()); grades.add(gradeEntity.getEntityId()); studentIds.add("student123"); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.GRADE), Mockito.any(NeutralQuery.class))).thenReturn( Arrays.asList(gradeEntity)); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(studentSectionAssociation)); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); assertTrue(validator.validate(EntityNames.GRADE, grades).containsAll(grades)); }
@Test public void testCanNotGetAccessToGrade() throws Exception { Set<String> grades = new HashSet<String>(); Map<String, Object> association = buildStudentSectionAssociation("student123", "section123", DateTime.now() .minusDays(3)); Entity studentSectionAssociation = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, association); Entity gradeEntity = helper.generateGrade(studentSectionAssociation.getEntityId()); grades.add(gradeEntity.getEntityId()); studentIds.add("student123"); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.GRADE), Mockito.any(NeutralQuery.class))).thenReturn( Arrays.asList(gradeEntity)); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(studentSectionAssociation)); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(Collections.EMPTY_SET); assertFalse(validator.validate(EntityNames.GRADE, grades).equals(grades)); }
@Test public void testCanNotGetAccessToGradeDueToGradeLookup() throws Exception { Set<String> grades = new HashSet<String>(); Map<String, Object> association = buildStudentSectionAssociation("student123", "section123", DateTime.now() .minusDays(3)); Entity studentSectionAssociation = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, association); ; Entity gradeEntity = helper.generateGrade(studentSectionAssociation.getEntityId()); grades.add(gradeEntity.getEntityId()); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.GRADE), Mockito.any(NeutralQuery.class))).thenReturn( new ArrayList<Entity>()); assertFalse(validator.validate(EntityNames.GRADE, grades).equals(grades)); }
@Test public void testCanNotGetAccessToGradeDueToStudentSectionAssociationLookup() throws Exception { Set<String> grades = new HashSet<String>(); Map<String, Object> association = buildStudentSectionAssociation("student123", "section123", DateTime.now() .minusDays(3)); Entity studentSectionAssociation = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, association); Entity gradeEntity = helper.generateGrade(studentSectionAssociation.getEntityId()); grades.add(gradeEntity.getEntityId()); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.GRADE), Mockito.any(NeutralQuery.class))).thenReturn( Arrays.asList(gradeEntity)); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(new ArrayList<Entity>()); assertFalse(validator.validate(EntityNames.GRADE, grades).equals(grades)); }
|
StudentToStudentAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isStudent() && STUDENT_ASSOCIATIONS.contains(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.PROGRAM, false)); assertFalse(validator.canValidate(EntityNames.ASSESSMENT, true)); assertFalse(validator.canValidate(EntityNames.GRADEBOOK_ENTRY, true)); assertFalse(validator.canValidate(EntityNames.COHORT, true)); assertFalse(validator.canValidate(EntityNames.STAFF_COHORT_ASSOCIATION, false)); }
|
ControlFilePreProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { processUsingNewBatchJob(exchange); } @Override void process(Exchange exchange); Set<String> getShardCollections(); void setShardCollections(Set<String> shardCollections); void setBatchJobDAO(BatchJobDAO batchJobDAO); void setTenantDA(TenantDA tenantDA); static final BatchJobStageType BATCH_JOB_STAGE; static final String INDEX_SCRIPT; }
|
@Test public void testProcess() throws Exception { List<Stage> mockedStages = createFakeStages(); Map<String, String> mockedProperties = createFakeBatchProperties(); File testZip = IngestionTest.getFile("ctl_tmp/test.zip"); NewBatchJob job = new NewBatchJob(BATCHJOBID, testZip.getAbsolutePath(), "finished", 29, mockedProperties, mockedStages, null); job.setBatchProperties(mockedProperties); job.setTenantId(tenantId); ResourceEntry entry = new ResourceEntry(); entry.setResourceName(testZip.getAbsolutePath()); entry.setResourceFormat(FileFormat.ZIP_FILE.getCode()); job.addResourceEntry(entry); WorkNote workNote = Mockito.mock(WorkNote.class); Mockito.when(workNote.getBatchJobId()).thenReturn(BATCHJOBID); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); exchange.getIn().setBody(workNote); Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(BATCHJOBID))).thenReturn(job); controlFilePreProcessor.setBatchJobDAO(mockedBatchJobDAO); controlFilePreProcessor.setTenantDA(mockedTenantDA); controlFilePreProcessor.process(exchange); Assert.assertEquals(2, job.getResourceEntries().size()); Assert.assertEquals(29, job.getTotalFiles()); }
|
StudentToStudentAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(STUDENT_ASSOCIATIONS, entityType, ids)) { return Collections.emptySet(); } Set<String> otherStudentIds = new HashSet<String>(); Set<String> toValidateIds = new HashSet<String>(ids); Entity self = SecurityUtil.getSLIPrincipal().getEntity(); List<Entity> associations = self.getEmbeddedData().get(entityType); for(Entity assoc : associations) { if (ids.contains(assoc.getEntityId())) { toValidateIds.remove(assoc.getEntityId()); } } if (toValidateIds.isEmpty()) { return ids; } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, toValidateIds)); Map<String, Set<String>> studentIdsToAssoc = new HashMap<String, Set<String>>(); for(Entity association : getRepo().findAll(entityType, query)) { Map<String, Object>body = association.getBody(); if (!isFieldExpired(body, ParameterConstants.END_DATE, false)) { String studentId = (String) body.get(ParameterConstants.STUDENT_ID); otherStudentIds.add(studentId); if(!studentIdsToAssoc.containsKey(studentId)) { studentIdsToAssoc.put(studentId, new HashSet<String>()); } studentIdsToAssoc.get(studentId).add(association.getEntityId()); } else { return Collections.emptySet(); } } Set<String> validStudentIds = studentValidator.validate(EntityNames.STUDENT, otherStudentIds); toValidateIds.removeAll(getValidIds(validStudentIds, studentIdsToAssoc)); Set<String> validIds = new HashSet<String>(ids); validIds.removeAll(toValidateIds); return validIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
|
@Test public void testPositiveValidate() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(assoc1Current.getEntityId(), assoc1Past.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, idsToValidate).containsAll(idsToValidate)); }
@Test public void testHeterogeneousValidate() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(assoc1Current.getEntityId(), assoc2.getEntityId())); assertFalse(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, idsToValidate).containsAll(idsToValidate)); }
|
TransitiveStudentToStudentSectionAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isStudentOrParent() && EntityNames.STUDENT_SECTION_ASSOCIATION.equals(entityType) && isTransitive; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.PROGRAM, false)); assertFalse(validator.canValidate(EntityNames.ASSESSMENT, true)); assertFalse(validator.canValidate(EntityNames.GRADEBOOK_ENTRY, true)); assertFalse(validator.canValidate(EntityNames.COHORT, true)); assertFalse(validator.canValidate(EntityNames.STAFF_COHORT_ASSOCIATION, false)); }
|
TransitiveStudentToStudentSectionAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STUDENT_SECTION_ASSOCIATION, entityType, ids)) { return Collections.emptySet(); } Set<String> otherStudentIds = new HashSet<String>(); Map<String, Set<String>> studentIdToSSA = new HashMap<String, Set<String>>(); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); for(Entity ssa : getRepo().findAll(EntityNames.STUDENT_SECTION_ASSOCIATION, query)) { Map<String, Object> body = ssa.getBody(); if (getDirectStudentIds().contains(body.get(ParameterConstants.STUDENT_ID))) { continue; } if (!isFieldExpired(body, ParameterConstants.END_DATE, false)) { String studentId = (String) ssa.getBody().get(ParameterConstants.STUDENT_ID); otherStudentIds.add(studentId); if(!studentIdToSSA.containsKey(studentId)) { studentIdToSSA.put(studentId, new HashSet<String>()); } studentIdToSSA.get(studentId).add(ssa.getEntityId()); } else { return Collections.emptySet(); } } Set<String> result; if(otherStudentIds.isEmpty()) { result = ids; } else { result = getValidIds(studentValidator.validate(EntityNames.STUDENT, otherStudentIds), studentIdToSSA); } return result; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
|
@Test public void testPositiveValidate() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(assoc1Current.getEntityId(), assoc1Past.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, idsToValidate).containsAll(idsToValidate)); }
@Test public void testHeterogeneousValidate() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(assoc1Current.getEntityId(), assoc2.getEntityId())); assertFalse(validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, idsToValidate).containsAll(idsToValidate)); }
|
TeacherToSectionValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isTeacher() && EntityNames.SECTION.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.SECTION, false)); assertTrue(validator.canValidate(EntityNames.SECTION, true)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, true)); }
|
TeacherToSectionValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.SECTION, entityType, ids)) { return Collections.EMPTY_SET; } Set<String> sectionIds = new HashSet<String>(); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.SECTION_ID, NeutralCriteria.CRITERIA_IN, ids)); query.addCriteria(new NeutralCriteria(ParameterConstants.TEACHER_ID, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.getSLIPrincipal().getEntity().getEntityId())); Iterable<Entity> associations = getRepo().findAll(EntityNames.TEACHER_SECTION_ASSOCIATION, query); if (associations != null) { for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE)) { sectionIds.add((String) association.getBody().get(ParameterConstants.SECTION_ID)); } } } return sectionIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateSingleSection() { helper.generateTeacherSchool(ValidatorTestHelper.STAFF_ID, ValidatorTestHelper.ED_ORG_ID); Entity section = helper.generateSection(ValidatorTestHelper.ED_ORG_ID); helper.generateTSA(ValidatorTestHelper.STAFF_ID, section.getEntityId(), false); sectionIds.add(section.getEntityId()); assertTrue(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testCanNotValidateInvalidSection() { helper.generateTeacherSchool(ValidatorTestHelper.STAFF_ID, ValidatorTestHelper.ED_ORG_ID); Entity section = helper.generateSection(ValidatorTestHelper.ED_ORG_ID); helper.generateTSA("BEEPBOOP", section.getEntityId(), false); sectionIds.add(section.getEntityId()); assertFalse(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); helper.generateTSA(ValidatorTestHelper.STAFF_ID, "DERPBERP", false); assertFalse(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testCanValidateMultiple() { helper.generateTeacherSchool(ValidatorTestHelper.STAFF_ID, ValidatorTestHelper.ED_ORG_ID); for (int i = 0; i < 10; ++i) { Entity section = helper.generateSection(ValidatorTestHelper.ED_ORG_ID); helper.generateTSA(ValidatorTestHelper.STAFF_ID, section.getEntityId(), false); sectionIds.add(section.getEntityId()); } assertTrue(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testValidateIntersection() { helper.generateTeacherSchool(ValidatorTestHelper.STAFF_ID, ValidatorTestHelper.ED_ORG_ID); Entity section = null; for (int i = 0; i < 10; ++i) { section = helper.generateSection(ValidatorTestHelper.ED_ORG_ID); helper.generateTSA(ValidatorTestHelper.STAFF_ID, section.getEntityId(), false); sectionIds.add(section.getEntityId()); } section = helper.generateSection(ValidatorTestHelper.ED_ORG_ID); sectionIds.add(section.getEntityId()); assertFalse(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); helper.generateTSA("DERPDERP", section.getEntityId(), false); assertFalse(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); helper.generateTSA(ValidatorTestHelper.STAFF_ID, "MERPMERP", false); assertFalse(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); helper.generateTSA(ValidatorTestHelper.STAFF_ID, section.getEntityId(), false); assertTrue(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
|
DeterministicIdResolver implements BatchJobStage { public void resolveInternalIds(NeutralRecordEntity entity, String tenantId, AbstractMessageReport report, ReportStats reportStats) { DidEntityConfig entityConfig = getEntityConfig(entity.getType()); if (entityConfig == null) { return; } if (entityConfig.getReferenceSources() == null || entityConfig.getReferenceSources().isEmpty()) { LOG.debug("Entity configuration contains no references --> returning..."); return; } for (DidRefSource didRefSource : entityConfig.getReferenceSources()) { String referenceEntityType = didRefSource.getEntityType(); String sourceRefPath = didRefSource.getSourceRefPath(); try { handleDeterministicIdForReference(entity, didRefSource, tenantId); } catch (IdResolutionException e) { handleException(entity, sourceRefPath, entity.getType(), referenceEntityType, e, report, reportStats); } } } void resolveInternalIds(NeutralRecordEntity entity, String tenantId, AbstractMessageReport report,
ReportStats reportStats); DidSchemaParser getDidSchemaParser(); void setDidSchemaParser(DidSchemaParser didSchemaParser); @Override String getStageName(); }
|
@Test public void shouldAddAppropriateContextForReference() throws IOException { NeutralRecordEntity entity = createSourceEntity(); DidRefConfig refConfig = createRefConfig("Simple_DID_ref_config.json"); DidEntityConfig entityConfig = createEntityConfig("Simple_DID_entity_config.json"); mockRefConfig(refConfig, ENTITY_TYPE); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put(SRC_KEY_FIELD, SRC_KEY_VALUE); String entityType = ENTITY_TYPE; String tenantId = TENANT; NaturalKeyDescriptor ndk = new NaturalKeyDescriptor(naturalKeys, tenantId, entityType, null); Mockito.when(didGenerator.generateId(Mockito.eq(ndk))).thenReturn(DID_VALUE); AbstractMessageReport errorReport = new DummyMessageReport(); EntityConfig oldEntityConfig = Mockito.mock(EntityConfig.class); Mockito.when(entityConfigs.getEntityConfiguration(Mockito.anyString())).thenReturn(oldEntityConfig); List<RefDef> references = new ArrayList<RefDef>(); Mockito.when(oldEntityConfig.getReferences()).thenReturn(references); RefDef refDef1 = Mockito.mock(RefDef.class); Ref ref1 = Mockito.mock(Ref.class); Mockito.when(ref1.getEntityType()).thenReturn(ENTITY_TYPE); Mockito.when(refDef1.getRef()).thenReturn(ref1); references.add(refDef1); RefDef refDef2 = Mockito.mock(RefDef.class); Ref ref2 = Mockito.mock(Ref.class); Mockito.when(ref2.getEntityType()).thenReturn("wrongEntityType"); Mockito.when(refDef2.getRef()).thenReturn(ref2); references.add(refDef2); ReportStats reportStats = new SimpleReportStats(); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Assert.assertEquals(DID_VALUE, entity.getBody().get(REF_FIELD)); Assert.assertFalse("no errors should be reported from reference resolution ", reportStats.hasErrors()); }
@Test public void shouldResolveSimpleDid() throws IOException { NeutralRecordEntity entity = createSourceEntity(); DidRefConfig refConfig = createRefConfig("Simple_DID_ref_config.json"); DidEntityConfig entityConfig = createEntityConfig("Simple_DID_entity_config.json"); mockRefConfig(refConfig, ENTITY_TYPE); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put(SRC_KEY_FIELD, SRC_KEY_VALUE); String entityType = ENTITY_TYPE; String tenantId = TENANT; NaturalKeyDescriptor ndk = new NaturalKeyDescriptor(naturalKeys, tenantId, entityType, null); Mockito.when(didGenerator.generateId(Mockito.eq(ndk))).thenReturn(DID_VALUE); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Assert.assertEquals(DID_VALUE, entity.getBody().get(REF_FIELD)); Assert.assertFalse("no errors should be reported from reference resolution ", reportStats.hasErrors()); }
@Test public void shouldIgnoreOptionalEmptyRefs() throws IOException { NeutralRecordEntity entity = createSourceEntity(); DidRefConfig refConfig = createRefConfig("Simple_DID_ref_config.json"); DidEntityConfig entityConfig = createEntityConfig("optional_DID_entity_config.json"); mockRefConfig(refConfig, ENTITY_TYPE); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put(SRC_KEY_FIELD, SRC_KEY_VALUE); String entityType = ENTITY_TYPE; String tenantId = TENANT; NaturalKeyDescriptor ndk = new NaturalKeyDescriptor(naturalKeys, tenantId, entityType, null); Mockito.when(didGenerator.generateId(Mockito.eq(ndk))).thenReturn(DID_VALUE); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Assert.assertEquals(DID_VALUE, entity.getBody().get(REF_FIELD)); Assert.assertFalse("no errors should be reported from reference resolution ", reportStats.hasErrors()); }
@Test public void shouldResolveListOfReferences() throws IOException { NeutralRecordEntity entity = createSourceEntityWithRefList(); DidRefConfig refConfig = createRefConfig("Simple_DID_ref_config.json"); DidEntityConfig entityConfig = createEntityConfig("Simple_DID_entity_config.json"); mockRefConfig(refConfig, ENTITY_TYPE); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); Map<String, String> naturalKeys1 = new HashMap<String, String>(); naturalKeys1.put(SRC_KEY_FIELD, SRC_KEY_VALUE_1); NaturalKeyDescriptor ndk1 = new NaturalKeyDescriptor(naturalKeys1, TENANT, ENTITY_TYPE, null); Map<String, String> naturalKeys2 = new HashMap<String, String>(); naturalKeys2.put(SRC_KEY_FIELD, SRC_KEY_VALUE_2); NaturalKeyDescriptor ndk2 = new NaturalKeyDescriptor(naturalKeys2, TENANT, ENTITY_TYPE, null); Mockito.when(didGenerator.generateId(Mockito.eq(ndk1))).thenReturn(DID_VALUE_1); Mockito.when(didGenerator.generateId(Mockito.eq(ndk2))).thenReturn(DID_VALUE_2); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); @SuppressWarnings("unchecked") List<String> did_list = (List<String>) entity.getBody().get(REF_FIELD); Assert.assertNotNull(did_list); Assert.assertEquals(2, did_list.size()); Assert.assertEquals(DID_VALUE_1, did_list.get(0)); Assert.assertEquals(DID_VALUE_2, did_list.get(1)); Assert.assertFalse("no errors should be reported from reference resolution ", reportStats.hasErrors()); }
@Test public void shouldFailFastForNonDidEntities() { NeutralRecordEntity entity = createSourceEntity(); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); mockEntityConfig(null, NON_DID_ENTITY_TYPE); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Mockito.verify(didSchemaParser, Mockito.never()).getRefConfigs(); DidEntityConfig entityConfig = Mockito.mock(DidEntityConfig.class); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(entityConfig.getReferenceSources()).thenReturn(null); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Mockito.verify(didSchemaParser, Mockito.never()).getRefConfigs(); Mockito.when(entityConfig.getReferenceSources()).thenReturn(new ArrayList<DidRefSource>()); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Mockito.verify(didSchemaParser, Mockito.never()).getRefConfigs(); }
@Test public void shouldResolveNestedDid() throws IOException { DidRefConfig refConfig = createRefConfig("nested_DID_ref_config.json"); DidEntityConfig entityConfig = createEntityConfig("Simple_DID_entity_config.json"); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); NeutralRecordEntity entity = createNestedSourceEntity(); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put(SRC_KEY_FIELD, NESTED_DID_VALUE); String entityType = ENTITY_TYPE; String tenantId = TENANT; NaturalKeyDescriptor ndk = new NaturalKeyDescriptor(naturalKeys, tenantId, entityType, null); Map<String, String> nestedNaturalKeys = new HashMap<String, String>(); nestedNaturalKeys.put(NESTED_SRC_KEY_FIELD, NESTED_SRC_KEY_VALUE); NaturalKeyDescriptor nestedNdk = new NaturalKeyDescriptor(nestedNaturalKeys, tenantId, NESTED_ENTITY_TYPE, null); mockRefConfig(refConfig, ENTITY_TYPE); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); Mockito.when(didGenerator.generateId(Mockito.eq(ndk))).thenReturn(DID_VALUE); Mockito.when(didGenerator.generateId(Mockito.eq(nestedNdk))).thenReturn(NESTED_DID_VALUE); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Object resolvedId = entity.getBody().get(REF_FIELD); Assert.assertEquals(DID_VALUE, resolvedId); Assert.assertFalse("no errors should be reported from reference resolution ", reportStats.hasErrors()); }
@Test public void shouldResolveNestedDidWithOptionalNestedReference() throws IOException { NeutralRecordEntity entity = createEntity("NeutralRecord_StudentTranscriptAssoc_missingOptionalEdOrg.json"); DidRefConfig refConfig = createRefConfig("StudentAcademicRecord_optional_ref_config.json"); DidEntityConfig entityConfig = createEntityConfig("StudentTranscriptAssoc_entity_config.json"); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", ""); naturalKeys.put("sessionName", "Spring 2011 East Daybreak Junior High"); naturalKeys.put("schoolId", ""); String tenantId = TENANT; NaturalKeyDescriptor sessionNKD = new NaturalKeyDescriptor(naturalKeys, tenantId, "session", null); Mockito.when(didGenerator.generateId(Mockito.eq(sessionNKD))).thenReturn("sessionDID"); naturalKeys = new HashMap<String, String>(); naturalKeys.put("sessionId", "sessionDID"); NaturalKeyDescriptor studentAcademicRecordNKD = new NaturalKeyDescriptor(naturalKeys, tenantId, "studentAcademicRecord", null); Mockito.when(didGenerator.generateId(Mockito.eq(studentAcademicRecordNKD))).thenReturn( "studentAcademicRecordDID"); mockRefConfig(refConfig, "studentAcademicRecord"); mockEntityConfig(entityConfig, "studentTranscriptAssociation"); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Object resolvedId = entity.getBody().get("StudentAcademicRecordReference"); Assert.assertEquals("studentAcademicRecordDID", resolvedId); Assert.assertFalse("no errors should be reported from reference resolution ", reportStats.hasErrors()); }
@SuppressWarnings("unchecked") @Test public void shouldResolveDidsInEmbeddedList() throws IOException { NeutralRecordEntity entity = createSourceEmbeddedEntity(); DidRefConfig refConfig = createRefConfig("Simple_DID_ref_config.json"); DidEntityConfig entityConfig = createEntityConfig("Embedded_DID_entity_config.json"); mockRefConfig(refConfig, ENTITY_TYPE); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); Map<String, String> naturalKeys1 = new HashMap<String, String>(); naturalKeys1.put(SRC_KEY_FIELD, SRC_KEY_VALUE_1); String entityType = ENTITY_TYPE; String tenantId = TENANT; NaturalKeyDescriptor ndk1 = new NaturalKeyDescriptor(naturalKeys1, tenantId, entityType, null); Map<String, String> naturalKeys2 = new HashMap<String, String>(); naturalKeys2.put(SRC_KEY_FIELD, SRC_KEY_VALUE_2); NaturalKeyDescriptor ndk2 = new NaturalKeyDescriptor(naturalKeys2, tenantId, entityType, null); Mockito.when(didGenerator.generateId(Mockito.eq(ndk1))).thenReturn(DID_VALUE_1); Mockito.when(didGenerator.generateId(Mockito.eq(ndk2))).thenReturn(DID_VALUE_2); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); List<Object> embeddedList = (List<Object>) entity.getBody().get(EMBEDDED_LIST_FIELD); Assert.assertNotNull(embeddedList); Assert.assertEquals(2, embeddedList.size()); Map<String, Object> subObj1 = (Map<String, Object>) embeddedList.get(0); Map<String, Object> subObj2 = (Map<String, Object>) embeddedList.get(1); Assert.assertEquals(DID_VALUE_1, subObj1.get(REF_FIELD)); Assert.assertEquals(DID_VALUE_2, subObj2.get(REF_FIELD)); Assert.assertFalse("no errors should be reported from reference resolution ", reportStats.hasErrors()); }
@Test public void testErrorReportingOnEntityRefFieldMissing() throws IOException { AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); NeutralRecordEntity entity = createSourceEntityMissingRefField(); DidRefConfig refConfig = createRefConfig("Simple_DID_ref_config.json"); DidEntityConfig entityConfig = createEntityConfig("Simple_DID_entity_config.json"); mockRefConfig(refConfig, ENTITY_TYPE); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Assert.assertNull("Id should not have been resolved", entity.getBody().get(REF_FIELD)); Assert.assertTrue("Errors should be reported from reference resolution ", reportStats.hasErrors()); }
@Test public void testErrorReportingOnFactoryMissingRefConfigForEntityType() throws IOException { AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); NeutralRecordEntity entity = createSourceEntityMissingRefField(); DidEntityConfig entityConfig = createEntityConfig("Simple_DID_entity_config.json"); mockRefConfig(null, ENTITY_TYPE); mockEntityConfig(entityConfig, ENTITY_TYPE); Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null); didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats); Assert.assertNull("Id should not have been resolved", entity.getBody().get(REF_FIELD)); Assert.assertFalse("No errors should be reported from reference resolution ", reportStats.hasErrors()); }
|
StaffToStaffProgramAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.STAFF_PROGRAM_ASSOCIATION.equals(entityType) && isStaff(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STAFF_PROGRAM_ASSOCIATION, false)); assertTrue(validator.canValidate(EntityNames.STAFF_PROGRAM_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.PROGRAM, true)); assertFalse(validator.canValidate(EntityNames.PROGRAM, false)); }
|
StaffToStaffProgramAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STAFF_PROGRAM_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); Map<String, Set<String>> staffIdsToSPA = new HashMap<String, Set<String>>(); Iterable<Entity> staffPrograms = getRepo().findAll(EntityNames.STAFF_PROGRAM_ASSOCIATION, basicQuery); for (Entity staff : staffPrograms) { Map<String, Object> body = staff.getBody(); if (isFieldExpired(body, ParameterConstants.END_DATE, true)) { continue; } String id = (String) body.get(ParameterConstants.STAFF_ID); if (!staffIdsToSPA.containsKey(id)) { staffIdsToSPA.put(id, new HashSet<String>()); } staffIdsToSPA.get(id).add(staff.getEntityId()); } Set<String> validStaffs = staffValidator.validate(EntityNames.STAFF, staffIdsToSPA.keySet()); Set<String> validSPA = getValidIds(validStaffs, staffIdsToSPA); return validSPA; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateStaffProgramAssociation() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); Entity school = helper.generateEdorgWithParent(lea.getEntityId()); helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); Entity sca = helper.generateStaffProgram(helper.STAFF_ID, helper.generateProgram().getEntityId(), false, true); cohortIds.add(sca.getEntityId()); assertTrue(validator.validate(EntityNames.STAFF_PROGRAM_ASSOCIATION, cohortIds).equals(cohortIds)); for (int i = 0; i < 5; ++i) { sca = helper.generateStaffProgram(i + "", helper.generateProgram().getEntityId(), false, true); helper.generateStaffEdorg(i + "", school.getEntityId(), false); cohortIds.add(sca.getEntityId()); } assertTrue(validator.validate(EntityNames.STAFF_PROGRAM_ASSOCIATION, cohortIds).equals(cohortIds)); }
@Test public void testCanNotValidateExpiredAssociation() { Entity school = helper.generateEdorgWithParent(null); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), false); Entity sca = helper.generateStaffProgram(helper.STAFF_ID, helper.generateProgram() .getEntityId(), true, false); cohortIds.add(sca.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_PROGRAM_ASSOCIATION, cohortIds).equals(cohortIds)); cohortIds.clear(); cleanProgramData(); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), true); sca = helper.generateStaffProgram(helper.STAFF_ID, helper.generateProgram() .getEntityId(), false, false); cohortIds.add(sca.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_PROGRAM_ASSOCIATION, cohortIds).equals(cohortIds)); }
@Test public void testCanNotValidateOutsideOfEdorg() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); helper.generateEdorgWithParent(lea.getEntityId()); helper.generateEdorgWithParent(null); helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); Entity sca = helper.generateStaffProgram("MOOP", helper.generateProgram().getEntityId(), false, true); cohortIds.add(sca.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_PROGRAM_ASSOCIATION, cohortIds).equals(cohortIds)); }
@Test public void testCanNotValidateAtStateLevel() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); helper.generateEdorgWithParent(lea.getEntityId()); helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); Entity sca = helper.generateStaffProgram("MOOP", helper.generateProgram().getEntityId(), false, true); cohortIds.add(sca.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_PROGRAM_ASSOCIATION, cohortIds).equals(cohortIds)); }
|
StaffToTeacherSchoolAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isStaff() && EntityNames.TEACHER_SCHOOL_ASSOCIATION.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateStaffToTeacherSchoolAssociation() throws Exception { assertTrue(validator.canValidate(EntityNames.TEACHER_SCHOOL_ASSOCIATION, false)); assertTrue(validator.canValidate(EntityNames.TEACHER_SCHOOL_ASSOCIATION, true)); }
@Test public void testDeniedStaffToOtherEntities() throws Exception { assertFalse(validator.canValidate(EntityNames.STUDENT, true)); assertFalse(validator.canValidate(EntityNames.STUDENT, false)); assertFalse(validator.canValidate(EntityNames.TEACHER, true)); assertFalse(validator.canValidate(EntityNames.TEACHER, false)); }
|
StaffToTeacherSchoolAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.TEACHER_SCHOOL_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids))); Iterable<Entity> teacherSchoolAssociations = getRepo().findAll(entityType, query); Map<String, Set<String>> schools = new HashMap<String, Set<String>>(); if (teacherSchoolAssociations != null) { for (Entity teacherSchoolAssociation : teacherSchoolAssociations) { Map<String, Object> body = teacherSchoolAssociation.getBody(); String school = (String) body.get("schoolId"); if (!schools.containsKey(school)) { schools.put(school, new HashSet<String>()); } schools.get(school).add(teacherSchoolAssociation.getEntityId()); } } if (schools.isEmpty()) { return Collections.EMPTY_SET; } Set<String> validSchools = validator.validate(EntityNames.EDUCATION_ORGANIZATION, schools.keySet()); return getValidIds(validSchools, schools); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testNullTeacherSchoolAssociation() throws Exception { assertTrue(validator.validate(EntityNames.TEACHER_SCHOOL_ASSOCIATION, null).isEmpty()); }
@Test public void testEmptyTeacherSchoolAssociation() throws Exception { Set<String> teacherSchoolAssociations = new HashSet<String>(); assertTrue(validator.validate(EntityNames.TEACHER_SCHOOL_ASSOCIATION, teacherSchoolAssociations).isEmpty()); }
@Test public void testCanGetAccessToTeacherSchoolAssociation() throws Exception { Set<String> teacherSchoolAssociations = new HashSet<String>(); Map<String, Object> association = buildTeacherSchoolAssociation("teacher123", "school123"); Entity teacherSchoolAssociation = new MongoEntity(EntityNames.TEACHER_SCHOOL_ASSOCIATION, association); teacherSchoolAssociations.add(teacherSchoolAssociation.getEntityId()); schoolIds.add("school123"); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.TEACHER_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(teacherSchoolAssociation)); Mockito.when(staffToSchoolValidator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds)).thenReturn(schoolIds); assertTrue(validator.validate(EntityNames.TEACHER_SCHOOL_ASSOCIATION, teacherSchoolAssociations).equals(teacherSchoolAssociations)); }
@Test public void testCanNotGetAccessToTeacherSchoolAssociationDueToBadLookup() throws Exception { Set<String> teacherSchoolAssociations = new HashSet<String>(); Map<String, Object> association = buildTeacherSchoolAssociation("teacher123", "school123"); Entity teacherSchoolAssociation = new MongoEntity(EntityNames.TEACHER_SCHOOL_ASSOCIATION, association); teacherSchoolAssociations.add(teacherSchoolAssociation.getEntityId()); schoolIds.add("school123"); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.TEACHER_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(new ArrayList<Entity>()); assertFalse(validator.validate(EntityNames.TEACHER_SCHOOL_ASSOCIATION, teacherSchoolAssociations).equals(teacherSchoolAssociations)); }
@Test public void testCanNotGetAccessToTeacherSchoolAssociation() throws Exception { Set<String> teacherSchoolAssociations = new HashSet<String>(); Map<String, Object> association = buildTeacherSchoolAssociation("teacher123", "school123"); Entity teacherSchoolAssociation = new MongoEntity(EntityNames.TEACHER_SCHOOL_ASSOCIATION, association); teacherSchoolAssociations.add(teacherSchoolAssociation.getEntityId()); schoolIds.add("school123"); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.TEACHER_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(teacherSchoolAssociation)); Mockito.when(staffToSchoolValidator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds)).thenReturn(Collections.EMPTY_SET); assertFalse(validator.validate(EntityNames.TEACHER_SCHOOL_ASSOCIATION, teacherSchoolAssociations).equals(teacherSchoolAssociations)); }
|
GenericToCohortValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return !isStudentOrParent() && !isTransitive && EntityNames.COHORT.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.COHORT, false)); assertFalse(validator.canValidate(EntityNames.COHORT, true)); assertFalse(validator.canValidate(EntityNames.COMPETENCY_LEVEL_DESCRIPTOR, false)); assertFalse(validator.canValidate(EntityNames.STAFF_COHORT_ASSOCIATION, true)); }
|
GenericToCohortValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.COHORT, entityType, ids)) { return new HashSet<String>(); } NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.getSLIPrincipal().getEntity().getEntityId())); if (SecurityUtil.getSLIPrincipal().isStudentAccessFlag()) { basicQuery.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_RECORD_ACCESS, NeutralCriteria.OPERATOR_EQUAL, true)); } Set<String> myCohortIds = new HashSet<String>(); Iterable<Entity> scas = getRepo().findAll(EntityNames.STAFF_COHORT_ASSOCIATION, basicQuery); for (Entity sca : scas) { Map<String, Object> body = sca.getBody(); if (!isFieldExpired(body, ParameterConstants.END_DATE, true)) { myCohortIds.add((String) body.get(ParameterConstants.COHORT_ID)); } } myCohortIds.retainAll(ids); return myCohortIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test(expected = IllegalArgumentException.class) public void testValidateWrongType() { validator.validate(EntityNames.ASSESSMENT, new HashSet<String>(Arrays.asList("Jomolungma"))); }
@Test public void testCanAccessAll() { List<String> descs = Arrays.asList("Just Cause", "Armaggedon", "Awareness"); Set<String> cohortIds = new HashSet<String>(); for (String desc : descs) { cohortIds.add(this.generateCohortAndAssociate(USER_ID, desc)); } Assert.assertEquals(validator.validate(EntityNames.COHORT, cohortIds).size(), cohortIds.size()); }
@Test public void testCannotAccessAll() { List<String> descs = Arrays.asList("Just Cause", "Armaggedon", "Awareness"); Set<String> cohortIds = new HashSet<String>(); for (String desc : descs) { cohortIds.add(this.generateCohort(USER_ID, desc)); } Assert.assertFalse(validator.validate(EntityNames.COHORT, cohortIds).size() == cohortIds.size()); for (String id : cohortIds) { Assert.assertFalse(validator.validate(EntityNames.COHORT, Collections.singleton(id)).size() == 1); } }
@Test public void testHeterogeneousList() { List<String> descs = Arrays.asList("Just Cause", "Armaggedon", "Awareness", "Chaos Mastery", "Life Mastery", "Death and Decay", "Node Mastery", "Artificer", "Warlord", "Conjurer"); Set<String> cohortIds = new HashSet<String>(); List<String> successes = new ArrayList<String>(); for (String desc : descs) { if (desc.endsWith("y")) { cohortIds.add(this.generateCohort(USER_ID, desc)); } else { String id = this.generateCohortAndAssociate(USER_ID, desc); cohortIds.add(id); successes.add(id); } } Assert.assertFalse(validator.validate(EntityNames.COHORT, cohortIds).size() == cohortIds.size()); for (String id : cohortIds) { if(successes.contains(id)) { Assert.assertEquals(validator.validate(EntityNames.COHORT, Collections.singleton(id)).size(), 1); } else { Assert.assertFalse(validator.validate(EntityNames.COHORT, Collections.singleton(id)).size() == 1); } } }
@Test public void testCanNotValidateStudentRecordFlag() { Set<String> cohortIds = new HashSet<String>(); Entity lea = helper.generateEdorgWithParent(null); Entity school = helper.generateEdorgWithParent(lea.getEntityId()); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), false); Entity cohort = helper.generateCohort(lea.getEntityId()); cohortIds.add(cohort.getEntityId()); helper.generateStaffCohort(helper.STAFF_ID, cohort.getEntityId(), false, false); assertFalse(validator.validate(EntityNames.COHORT, cohortIds).size() == cohortIds.size()); }
|
StaffToGlobalSectionValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.SECTION.equals(entityType) && isStaff(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { setContext(seaStaff, Arrays.asList(SecureRoleRightAccessImpl.SEA_ADMINISTRATOR)); assertTrue(validator.canValidate(EntityNames.SECTION, true)); assertTrue(validator.canValidate(EntityNames.SECTION, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, true)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); }
@Test public void testCanNotValidate() { setContext(educator2, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); SecurityUtil.setUserContext(SecurityUtil.UserContext.TEACHER_CONTEXT); assertFalse(validator.canValidate(EntityNames.SECTION, true)); assertFalse(validator.canValidate(EntityNames.SECTION, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, true)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); }
|
StaffToGlobalSectionValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.SECTION, entityType, ids)) { return Collections.EMPTY_SET; } Set<String> edOrgLineage = getEdorgDescendents(getDirectEdorgs()); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids, false)); query.addCriteria(new NeutralCriteria(ParameterConstants.SCHOOL_ID, NeutralCriteria.CRITERIA_IN, edOrgLineage)); Set<String> validSections = new HashSet<String>(); if (ids.size() != getRepo().count(entityType, query)) { Iterable<String> sections = getRepo().findAllIds(entityType, query); validSections = Sets.newHashSet(sections); } else { validSections = ids; } return validSections; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testSeaAdministratorCanSeeSectionAtSchool() { setContext(seaStaff, Arrays.asList(SecureRoleRightAccessImpl.SEA_ADMINISTRATOR)); Set<String> sectionIds = new HashSet<String>(); sectionIds.add(section1.getEntityId()); sectionIds.add(section2.getEntityId()); assertTrue(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testLeaAdministratorCanSeeSectionAtSchool() { setContext(lea1Staff, Arrays.asList(SecureRoleRightAccessImpl.LEA_ADMINISTRATOR)); Set<String> sectionIds = new HashSet<String>(); sectionIds.add(section1.getEntityId()); assertTrue(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testLeaAdministratorCanNotSeeSectionAtSchool() { setContext(lea2Staff, Arrays.asList(SecureRoleRightAccessImpl.LEA_ADMINISTRATOR)); Set<String> sectionIds = new HashSet<String>(); sectionIds.add(section1.getEntityId()); assertFalse(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testSchoolAdministratorCanSeeSectionAtSchool() { setContext(school1Staff, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); Set<String> sectionIds = new HashSet<String>(); sectionIds.add(section1.getEntityId()); assertTrue(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testSchoolAdministratorCanNotSeeSectionAtSchool() { setContext(school2Staff, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); Set<String> sectionIds = new HashSet<String>(); sectionIds.add(section1.getEntityId()); assertFalse(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testEducatorCanSeeSectionAtSchool() { setContext(educator1, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); Set<String> sectionIds = new HashSet<String>(); sectionIds.add(section1.getEntityId()); assertTrue(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
@Test public void testEducatorCanNotSeeSectionAtSchool() { setContext(educator2, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); Set<String> sectionIds = new HashSet<String>(); sectionIds.add(section2.getEntityId()); assertTrue(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); sectionIds.add(section1.getEntityId()); assertFalse(validator.validate(EntityNames.SECTION, sectionIds).equals(sectionIds)); }
|
TeacherToTeacherSchoolAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.TEACHER_SCHOOL_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.TEACHER_ID, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.getSLIPrincipal().getEntity().getEntityId())); Iterable<String> it = this.repo.findAllIds(EntityNames.TEACHER_SCHOOL_ASSOCIATION, nq); Set<String> fin = Sets.newHashSet(it); fin.retainAll(ids); return fin; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test(expected = IllegalArgumentException.class) public void testValidateWrongType() { val.validate(EntityNames.ASSESSMENT, new HashSet<String>(Arrays.asList("Jomolungma"))); }
@Test public void testSuccessOne() { Entity tsa = this.vth.generateTeacherSchool(USER_ID, "Myrran"); Set<String> ids = Collections.singleton(tsa.getEntityId()); Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); }
@Test public void testSuccessMulti() { Set<String> ids = new HashSet<String>(); for (int i = 0; i < 100; i++) { ids.add(this.vth.generateTeacherSchool(USER_ID, "Myrran"+i).getEntityId()); } Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); }
@Test public void testWrongId() { Set<String> ids = Collections.singleton("Hammerhands"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); ids = Collections.singleton("Nagas"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); ids = Collections.singleton("Phantom Warriors"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); }
@Test public void testHeterogenousList() { Set<String> ids = new HashSet<String>(Arrays.asList(this.vth.generateTeacherSchool(USER_ID, "Myrran").getEntityId(), "Pikemen", "Pegasi")); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); }
|
StudentToSubStudentValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return SUB_STUDENT_ENTITIES.contains(entityType) && isStudentOrParent(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
|
@Test public void testCanValidate() { injector.setStudentContext(student1); assertTrue(validator.canValidate(EntityNames.ATTENDANCE, true)); assertTrue(validator.canValidate(EntityNames.ATTENDANCE, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_ASSESSMENT, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_ASSESSMENT, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_GRADEBOOK_ENTRY, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_GRADEBOOK_ENTRY, false)); assertTrue(validator.canValidate(EntityNames.GRADE, true)); assertTrue(validator.canValidate(EntityNames.GRADE, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_ACADEMIC_RECORD, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_ACADEMIC_RECORD, false)); assertTrue(validator.canValidate(EntityNames.REPORT_CARD, true)); assertTrue(validator.canValidate(EntityNames.REPORT_CARD, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT, false)); assertFalse(validator.canValidate(EntityNames.PARENT, true)); assertFalse(validator.canValidate(EntityNames.EDUCATION_ORGANIZATION, false)); assertFalse(validator.canValidate(EntityNames.STAFF, true)); assertFalse(validator.canValidate(EntityNames.DISCIPLINE_ACTION, false)); assertFalse(validator.canValidate(EntityNames.GRADUATION_PLAN, true)); assertFalse(validator.canValidate(EntityNames.PROGRAM, true)); }
|
StudentToSubStudentValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(SUB_STUDENT_ENTITIES, entityType, ids)) { return Collections.emptySet(); } Map<String, Set<String>> studentIds = new HashMap<String, Set<String>>(getIdsContainedInFieldOnEntities(entityType, new ArrayList<String>(ids), ParameterConstants.STUDENT_ID)); return getValidIds(getDirectStudentIds(), studentIds); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
|
@Test public void testValidateSingleEntity() { injector.setStudentContext(student1); Set<String> idsToValidate = new HashSet<String>(Arrays.asList(attendance1.getEntityId())); assertTrue(validator.validate(EntityNames.ATTENDANCE, idsToValidate).containsAll(idsToValidate)); idsToValidate = new HashSet<String>(Arrays.asList(studentAcademicRecord1.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_ACADEMIC_RECORD, idsToValidate).containsAll(idsToValidate)); injector.setStudentContext(student2); idsToValidate = new HashSet<String>(Arrays.asList(attendance2.getEntityId())); assertTrue(validator.validate(EntityNames.ATTENDANCE, idsToValidate).containsAll(idsToValidate)); idsToValidate = new HashSet<String>(Arrays.asList(studentAcademicRecord2.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_ACADEMIC_RECORD, idsToValidate).containsAll(idsToValidate)); }
@Test public void testValidateNegativeHeterogeneousList() { injector.setStudentContext(student1); Set<String> idsToValidate = new HashSet<String>(Arrays.asList(attendance1.getEntityId(),attendance2.getEntityId())); assertFalse(validator.validate(EntityNames.ATTENDANCE, idsToValidate).containsAll(idsToValidate)); idsToValidate = new HashSet<String>(Arrays.asList(studentAcademicRecord1.getEntityId(), studentAcademicRecord2.getEntityId())); assertFalse(validator.validate(EntityNames.STUDENT_ACADEMIC_RECORD, idsToValidate).containsAll(idsToValidate)); }
|
TransitiveTeacherToTeacherValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.TEACHER, entityType, ids)) { return Collections.emptySet(); } NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, "=", SecurityUtil .getSLIPrincipal().getEntity().getEntityId())); Iterable<Entity> tsa = getRepo().findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, nq); List<String> schools = new ArrayList<String>(); for (Entity e : tsa) { if (!isFieldExpired(e.getBody(), ParameterConstants.END_DATE, false)) { schools.add((String) e.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE)); } } nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE, "in", schools)); nq.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, "in", ids)); tsa = getRepo().findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, nq); Set<String> validIds = new HashSet<String>(); for (Entity e : tsa) { if (!isFieldExpired(e.getBody(), ParameterConstants.END_DATE, false)) { validIds.add(e.getBody().get(ParameterConstants.STAFF_REFERENCE).toString()); } } validIds.add(SecurityUtil.getSLIPrincipal().getEntity().getEntityId()); validIds.retainAll(ids); return validIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test(expected = IllegalArgumentException.class) public void testValidateWrongType() { val.validate(EntityNames.ASSESSMENT, new HashSet<String>(Arrays.asList("Jomolungma"))); }
@Test public void testCanAccessAll() { vth.generateStaffEdorg(USER_ID, ED_ORG, false); Set<String> teacherIds = new HashSet<String>(Arrays.asList("Just Cause", "Armaggedon", "Awareness")); for (String id : teacherIds) { vth.generateStaffEdorg(id, ED_ORG, false); } Assert.assertTrue(val.validate(EntityNames.TEACHER, teacherIds).containsAll(teacherIds)); }
@Test public void testCannotAccessAll() { Set<String> teacherIds = new HashSet<String>(Arrays.asList("Just Cause", "Armaggedon", "Awareness")); for (String id : teacherIds) { vth.generateStaffEdorg(id, ED_ORG, false); } Assert.assertFalse(val.validate(EntityNames.TEACHER, teacherIds).containsAll(teacherIds)); for (String id : teacherIds) { Assert.assertFalse(val.validate(EntityNames.TEACHER, Collections.singleton(id)).contains(id)); } }
@Test public void testHeterogeneousList() { vth.generateStaffEdorg(USER_ID, ED_ORG, false); Set<String> teacherIds = new HashSet<String>(Arrays.asList("Just Cause", "Armaggedon", "Awareness", "Chaos Mastery", "Life Mastery", "Death and Decay", "Node Mastery", "Artificer", "Warlord", "Conjurer")); List<String> successes = new ArrayList<String>(); for (String id : teacherIds) { if (Math.random() > 0.5) { vth.generateStaffEdorg(id, ED_ORG, false); successes.add(id); } else { vth.generateStaffEdorg(id, "Arcanus", false); } } Assert.assertFalse(val.validate(EntityNames.TEACHER, teacherIds).containsAll(teacherIds)); for (String id : teacherIds) { if (successes.contains(id)) { Assert.assertTrue(val.validate(EntityNames.TEACHER, Collections.singleton(id)).contains(id)); } else { Assert.assertFalse(val.validate(EntityNames.TEACHER, Collections.singleton(id)).contains(id)); } } }
@Test public void testExpiredTeacher() { vth.generateStaffEdorg(USER_ID, ED_ORG, false); Set<String> teacherIds = new HashSet<String>(Arrays.asList("Just Cause")); for (String id : teacherIds) { vth.generateStaffEdorg(id, ED_ORG, true); } Assert.assertFalse(val.validate(EntityNames.TEACHER, teacherIds).containsAll(teacherIds)); for (String id : teacherIds) { vth.generateStaffEdorg(id, ED_ORG, false); } Assert.assertTrue(val.validate(EntityNames.TEACHER, teacherIds).containsAll(teacherIds)); }
|
TeacherToStudentCompetencyValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isTeacher() && EntityNames.STUDENT_COMPETENCY.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STUDENT_COMPETENCY, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_COMPETENCY, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); }
|
TeacherToStudentCompetencyValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STUDENT_COMPETENCY, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); query.setIncludeFields(Arrays.asList(ParameterConstants.STUDENT_SECTION_ASSOCIATION_ID)); Iterable<Entity> comps = getRepo().findAll(EntityNames.STUDENT_COMPETENCY, query); Map<String, Set<String>> secAssocIds = new HashMap<String, Set<String>>(); for (Entity comp : comps) { String id = (String) comp.getBody().get(ParameterConstants.STUDENT_SECTION_ASSOCIATION_ID); if (!secAssocIds.containsKey(id)) { secAssocIds.put(id, new HashSet<String>()); } secAssocIds.get(id).add(comp.getEntityId()); } Set<String> validSectionIds = sectionAssocValidator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, secAssocIds.keySet()); return getValidIds(validSectionIds, secAssocIds); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testValidComps() { Set<String> ids = new HashSet<String>(Arrays.asList(sComp1.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_COMPETENCY, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(sComp2.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_COMPETENCY, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(sComp1.getEntityId(), sComp2.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_COMPETENCY, ids).equals(ids)); }
@Test public void testInvalidComps() { Set<String> ids = new HashSet<String>(Arrays.asList(sComp3.getEntityId())); assertFalse(validator.validate(EntityNames.STUDENT_COMPETENCY, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(sComp1.getEntityId(), sComp3.getEntityId())); assertFalse(validator.validate(EntityNames.STUDENT_COMPETENCY, ids).equals(ids)); }
|
TeacherToCourseTranscriptValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isTeacher() && EntityNames.COURSE_TRANSCRIPT.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateAsTeacher() { setupCurrentUser(teacher1); Assert.assertTrue("Must be able to validate", validator.canValidate(EntityNames.COURSE_TRANSCRIPT, false)); Assert.assertTrue("Must be able to validate", validator.canValidate(EntityNames.COURSE_TRANSCRIPT, true)); Assert.assertFalse("Must not be able to validate", validator.canValidate(EntityNames.ADMIN_DELEGATION, false)); }
|
TeacherToCourseTranscriptValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.COURSE_TRANSCRIPT, entityType, ids)) { return Collections.emptySet(); } Map<String, Set<String>> studentAcademicRecordToCT = new HashMap<String, Set<String>>(); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids))); Iterable<Entity> entities = getRepo().findAll(EntityNames.COURSE_TRANSCRIPT, query); for (Entity entity : entities) { Map<String, Object> body = entity.getBody(); if (body.get(ParameterConstants.STUDENT_ACADEMIC_RECORD_ID) instanceof String) { String id = (String) body.get(ParameterConstants.STUDENT_ACADEMIC_RECORD_ID); if (!studentAcademicRecordToCT.containsKey(id)) { studentAcademicRecordToCT.put(id, new HashSet<String>()); } studentAcademicRecordToCT.get(id).add(entity.getEntityId()); } else { LOG.warn("Possible Corrupt Data detected at "+entityType+"/"+entity.getEntityId()); } } if (studentAcademicRecordToCT.isEmpty()) { return Collections.EMPTY_SET; } Set<String> sarIds = validator.validate(EntityNames.STUDENT_ACADEMIC_RECORD, studentAcademicRecordToCT.keySet()); return getValidIds(sarIds, studentAcademicRecordToCT); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testValidAssociations() { setupCurrentUser(teacher1); Assert.assertEquals(1, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>(Arrays.asList(courseTranscript1.getEntityId()))).size()); }
@Test public void testInvalidAssociations() { setupCurrentUser(teacher1); Assert.assertEquals(0, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>(Arrays.asList(UUID.randomUUID().toString()))).size()); Assert.assertEquals(0, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>()).size()); Assert.assertEquals(0, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>(Arrays.asList(courseTranscript2.getEntityId()))).size()); }
|
StaffToDisciplineIncidentValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isStaff() && EntityNames.DISCIPLINE_INCIDENT.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); void setSubStudentValidator(StaffToSubStudentEntityValidator subStudentValidator); void setSchoolValidator(GenericToEdOrgValidator schoolValidator); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.DISCIPLINE_INCIDENT, true)); assertTrue(validator.canValidate(EntityNames.DISCIPLINE_INCIDENT, false)); assertFalse(validator.canValidate(EntityNames.SECTION, true)); assertFalse(validator.canValidate(EntityNames.SECTION, false)); }
|
StaffToDisciplineIncidentValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.DISCIPLINE_INCIDENT, entityType, ids)) { return Collections.emptySet(); } boolean match = false; Set<String> validIds = new HashSet<String>(); for (String id : ids) { match = false; NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.DISCIPLINE_INCIDENT_ID, NeutralCriteria.OPERATOR_EQUAL, id)); Iterable<Entity> associations = getRepo().findAll(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, basicQuery); for (Entity association : associations) { Set<String> sdia = subStudentValidator.validate(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, new HashSet<String>(Arrays.asList(association.getEntityId()))); if (!sdia.isEmpty()) { match = true; } } basicQuery = new NeutralQuery( new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.OPERATOR_EQUAL, id)); Entity di = getRepo().findOne(EntityNames.DISCIPLINE_INCIDENT, basicQuery); if (di == null) { continue; } basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.OPERATOR_EQUAL, di.getBody().get(ParameterConstants.SCHOOL_ID))); Entity edorg = getRepo().findOne(EntityNames.EDUCATION_ORGANIZATION, basicQuery); if (edorg == null) { continue; } Set<String> schoolId = new HashSet<String>(Arrays.asList(edorg.getEntityId())); Set<String> validSchools = schoolValidator.validate(EntityNames.SCHOOL, schoolId); if (!validSchools.isEmpty()) { match = true; } if (match) { validIds.add(id); } } return validIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); void setSubStudentValidator(StaffToSubStudentEntityValidator subStudentValidator); void setSchoolValidator(GenericToEdOrgValidator schoolValidator); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateDisciplineIncidentFromSchool() { Entity school = helper.generateEdorgWithParent(null); Set<String> schoolId = new HashSet<String>(Arrays.asList(school.getEntityId())); Mockito.when(mockSchoolValidator.validate(EntityNames.SCHOOL, schoolId)).thenReturn(schoolId); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), false); Entity di = helper.generateDisciplineIncident(school.getEntityId()); diIds.add(di.getEntityId()); Assert.assertEquals(diIds, validator.validate(EntityNames.DISCIPLINE_INCIDENT, diIds)); }
@Test public void testCanValidateDisciplineIncidentFromStudent() { Entity school = helper.generateEdorgWithParent(null); Entity di = helper.generateDisciplineIncident(school.getEntityId()); diIds.add(di.getEntityId()); Entity sdia = helper.generateStudentDisciplineIncidentAssociation("Berp", di.getEntityId()); Mockito.when( mockStudentValidator.validate(Mockito.eq(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION), Mockito.any(Set.class))).thenReturn(new HashSet<String>(Arrays.asList(sdia.getEntityId()))); assertTrue(validator.validate(EntityNames.DISCIPLINE_INCIDENT, diIds).equals(diIds)); }
@Test public void testCanValidateDisciplineIncidentFromState() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); Entity seoas = helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); for (int i = 0; i < 10; ++i) { Entity school = helper.generateEdorgWithParent(lea.getEntityId()); Entity di = helper.generateDisciplineIncident(school.getEntityId()); diIds.add(di.getEntityId()); } Mockito.when(mockSchoolValidator.validate(Mockito.eq(EntityNames.SCHOOL), Mockito.any(Set.class))).thenReturn(new HashSet<String>(Arrays.asList(lea.getEntityId()))); Assert.assertEquals(diIds, validator.validate(EntityNames.DISCIPLINE_INCIDENT, diIds)); Mockito.when(mockSchoolValidator.validate(Mockito.eq(EntityNames.SCHOOL), Mockito.any(Set.class))).thenReturn(Collections.EMPTY_SET); diIds.add(helper.generateDisciplineIncident(sea.getEntityId()).getEntityId()); assertFalse(validator.validate(EntityNames.DISCIPLINE_INCIDENT, diIds).equals(diIds)); }
@Test public void testCanNotValidateDisciplineIncidentFromOtherSchool() { Entity school = helper.generateEdorgWithParent(null); Entity school2 = helper.generateEdorgWithParent(null); Mockito.when( mockSchoolValidator.validate(EntityNames.SCHOOL, new HashSet<String>(Arrays.asList(school2.getEntityId())))).thenReturn(Collections.EMPTY_SET); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), false); Entity di = helper.generateDisciplineIncident(school2.getEntityId()); diIds.add(di.getEntityId()); assertFalse(validator.validate(EntityNames.DISCIPLINE_INCIDENT, diIds).equals(diIds)); }
@Test public void testCanNotValidateDisciplineIncidentFromInvalidAssoc() { Mockito.when( mockStudentValidator.validate(Mockito.eq(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION), Mockito.any(Set.class))).thenReturn(Collections.EMPTY_SET); Entity school = helper.generateEdorgWithParent(null); Entity di = helper.generateDisciplineIncident(school.getEntityId()); diIds.add(di.getEntityId()); helper.generateStudentDisciplineIncidentAssociation("Berp", di.getEntityId()); assertFalse(validator.validate(EntityNames.DISCIPLINE_INCIDENT, diIds).equals(diIds)); }
|
TeacherToStaffCohortAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STAFF_COHORT_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.getSLIPrincipal().getEntity().getEntityId())); nq.addCriteria(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); Iterable<String> result = getRepo().findAllIds(EntityNames.STAFF_COHORT_ASSOCIATION, nq); return Sets.newHashSet(result); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test(expected = IllegalArgumentException.class) public void testValidateWrongType() { val.validate(EntityNames.ASSESSMENT, new HashSet<String>(Arrays.asList("Jomolungma"))); }
@Test public void testCanAccessAll() { List<String> ids = Arrays.asList("Just Cause", "Armaggedon", "Awareness"); Set<String> sca = new HashSet<String>(); for (String id : ids) { sca.add(this.vth.generateStaffCohort(USER_ID, id, false, true).getEntityId()); } Assert.assertTrue(val.validate(EntityNames.STAFF_COHORT_ASSOCIATION, sca).equals(sca)); }
@Test public void testCannotAccessAll() { List<String> ids = Arrays.asList("Just Cause", "Armaggedon", "Awareness"); Set<String> sca = new HashSet<String>(); for (String id : ids) { sca.add(this.vth.generateStaffCohort("Sky Drake", id, false, true).getEntityId()); } Assert.assertFalse(val.validate(EntityNames.STAFF_COHORT_ASSOCIATION, sca).equals(sca)); for (String id : sca) { Set<String> single = Collections.singleton(id); Assert.assertFalse(val.validate(EntityNames.STAFF_COHORT_ASSOCIATION, single).equals(single)); } }
@Test public void testHeterogeneousList() { List<String> ids = Arrays.asList("Just Cause", "Armaggedon", "Awareness", "Chaos Mastery", "Life Mastery", "Death and Decay", "Node Mastery", "Artificer", "Warlord", "Conjurer"); Set<String> sca = new HashSet<String>(); List<String> successes = new ArrayList<String>(); for (String id : ids) { if (Math.random() > 0.33) { sca.add(this.vth.generateStaffCohort("Sky Drake", id, false, true).getEntityId()); } else if (Math.random() > 0.5) { String id2 = this.vth.generateStaffCohort(USER_ID, id, false, true).getEntityId(); sca.add(id2); successes.add(id2); } else { sca.add("Earth Elemental"); } } Assert.assertFalse(val.validate(EntityNames.STAFF_COHORT_ASSOCIATION, sca).equals(sca)); for (String id : sca) { Set<String> single = Collections.singleton(id); if (successes.contains(id)) { Assert.assertTrue(val.validate(EntityNames.STAFF_COHORT_ASSOCIATION, single).equals(single)); } else { Assert.assertFalse(val.validate(EntityNames.STAFF_COHORT_ASSOCIATION, single).equals(single)); } } }
|
TeacherToSubStudentEntityValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean through) { return isTeacher() && isSubEntityOfStudent(entityType); } @Override boolean canValidate(String entityType, boolean through); @SuppressWarnings("unchecked") @Override Set<String> validate(String entityType, Set<String> ids); void setRepo(PagingRepositoryDelegate<Entity> repo); void setTeacherToStudentValidator(TeacherToStudentValidator teacherToStudentValidator); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateTeacherToAttendance() throws Exception { assertTrue(validator.canValidate(EntityNames.ATTENDANCE, false)); }
@Test public void testCanValidateTeacherToDisciplineAction() throws Exception { assertTrue(validator.canValidate(EntityNames.DISCIPLINE_ACTION, false)); }
@Test public void testCanValidateTeacherToStudentAcademicRecord() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_ACADEMIC_RECORD, false)); }
@Test public void testCanValidateTeacherToStudentAssessment() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_ASSESSMENT, false)); }
@Test public void testCanValidateTeacherToStudentDisciplineIncident() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, false)); }
@Test public void testCanValidateTeacherToStudentGradebookEntry() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_GRADEBOOK_ENTRY, false)); }
@Test public void testCanValidateTeacherToStudentSchoolAssociation() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, false)); }
@Test public void testCanValidateTeacherToStudentSectionAssociation() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, false)); }
@Test public void testCanNotValidateOtherEntities() throws Exception { assertFalse(validator.canValidate(EntityNames.STUDENT, false)); }
|
TeacherToSubStudentEntityValidator extends AbstractContextValidator { @SuppressWarnings("unchecked") @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(SUB_ENTITIES_OF_STUDENT, entityType, ids)) { return Collections.emptySet(); } Map<String, Set<String>> students = new HashMap<String, Set<String>>(); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids))); Iterable<Entity> entities = repo.findAll(entityType, query); for (Entity entity : entities) { Map<String, Object> body = entity.getBody(); if (body.get(ParameterConstants.STUDENT_ID) instanceof String) { students = putStudents(Arrays.asList((String) body.get(ParameterConstants.STUDENT_ID)), entity.getEntityId(), students); } else if (body.get(ParameterConstants.STUDENT_ID) instanceof List) { students = putStudents((List<String>) body.get(ParameterConstants.STUDENT_ID), entity.getEntityId(), students); } else { LOG.warn("Possible Corrupt Data detected at "+entityType+"/"+entity.getEntityId()); } } if (students.isEmpty()) { return Collections.EMPTY_SET; } Set<String> validStudents = validator.validate(EntityNames.STUDENT, students.keySet()); return getValidIds(validStudents, students); } @Override boolean canValidate(String entityType, boolean through); @SuppressWarnings("unchecked") @Override Set<String> validate(String entityType, Set<String> ids); void setRepo(PagingRepositoryDelegate<Entity> repo); void setTeacherToStudentValidator(TeacherToStudentValidator teacherToStudentValidator); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanGetAccessToAttendance() throws Exception { Set<String> studentIds = new HashSet<String>(); Set<String> attendances = new HashSet<String>(); Map<String, Object> attendance1 = buildAttendanceForStudent("student123", "school123"); Entity attendanceEntity1 = new MongoEntity("attendance", attendance1); attendances.add(attendanceEntity1.getEntityId()); studentIds.add("student123"); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.ATTENDANCE), Mockito.any(NeutralQuery.class))).thenReturn( Arrays.asList(attendanceEntity1)); Mockito.when(teacherToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); Assert.assertEquals(attendances.size(), validator.validate(EntityNames.ATTENDANCE, attendances).size()); }
@Test public void testCanNotGetAccessToAttendance() throws Exception { Set<String> attendances = new HashSet<String>(); Map<String, Object> attendance1 = buildAttendanceForStudent("student123", "school123"); Entity attendanceEntity1 = new MongoEntity("attendance", attendance1); attendances.add(attendanceEntity1.getEntityId()); studentIds.add("student123"); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.ATTENDANCE), Mockito.any(NeutralQuery.class))).thenReturn( Arrays.asList(attendanceEntity1)); Mockito.when(teacherToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(Collections.EMPTY_SET); assertFalse(validator.validate(EntityNames.ATTENDANCE, attendances).size() == attendance1.size()); }
@Test public void testCanGetAccessToCurrentStudentSchoolAssociation() throws Exception { Map<String, Object> goodStudentSchoolAssociation = buildStudentSchoolAssociation("student123", "school123", new DateTime().plusHours(1)); Entity association = new MongoEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, goodStudentSchoolAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); studentIds.add("student123"); Mockito.when(teacherToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); Assert.assertEquals(studentIds.size(), validator.validate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, associations).size()); }
@Test public void testCanGetAccessToStudentSchoolAssociationWithoutExitWithdrawDate() throws Exception { Map<String, Object> goodStudentSchoolAssociation = buildStudentSchoolAssociation("student123", "school123"); Entity association = new MongoEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, goodStudentSchoolAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); studentIds.add("student123"); Mockito.when(teacherToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); Assert.assertEquals(studentIds.size(), validator.validate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, associations).size()); }
@Test public void testDeniedAccessToExpiredStudentSchoolAssociation() throws Exception { Map<String, Object> badStudentSchoolAssociation = buildStudentSchoolAssociation("student123", "school123", new DateTime().minusDays(1)); Entity association = new MongoEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, badStudentSchoolAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); assertFalse(validator.validate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, associations).size() == associations.size()); }
@Test public void testCanGetAccessToCurrentStudentSectionAssociation() throws Exception { Map<String, Object> goodStudentSectionAssociation = buildStudentSectionAssociation("student123", "section123", new DateTime().plusDays(1)); Entity association = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, "assoc123", goodStudentSectionAssociation, null); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); studentIds.add("student123"); Mockito.when(teacherToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); Assert.assertEquals(associations, validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, associations)); }
@Test public void testCanGetAccessToStudentSectionAssociationWithoutEndDate() throws Exception { Map<String, Object> goodStudentSectionAssociation = buildStudentSectionAssociation("student123", "section123"); Entity association = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, goodStudentSectionAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); studentIds.add("student123"); Mockito.when(teacherToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); Assert.assertEquals(studentIds.size(), validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, associations).size()); }
@Test public void testDeniedAccessToExpiredStudentSectionAssociation() throws Exception { Map<String, Object> badStudentSectionAssociation = buildStudentSchoolAssociation("student123", "section123", new DateTime().minusDays(1)); Entity association = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, badStudentSectionAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); assertFalse(validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, associations).size() == associations.size()); }
|
StaffToStudentValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.STUDENT.equals(entityType) && isStaff(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> getValid(String entityType, Set<String> studentIds); @Override Set<String> validate(String entityType, Set<String> studentIds); void setProgramValidator(GenericToProgramValidator programValidator); void setCohortValidator(GenericToCohortValidator cohortValidator); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateStaffToStudents() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT, false)); }
@Test public void testCanNotValidateOtherEntities() throws Exception { assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); }
|
StaffToStudentValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> studentIds) throws IllegalStateException { LOG.debug(">>>StaffToStudentValidator.validate(?)", entityType); LOG.debug(" studentIds: {}", (studentIds==null) ? "null" : studentIds.toString() ); if (!areParametersValid(EntityNames.STUDENT, entityType, studentIds)) { LOG.debug(" !areParametersValid"); return new HashSet<String>(); } return validateStaffToStudentContextThroughSharedEducationOrganization(studentIds); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> getValid(String entityType, Set<String> studentIds); @Override Set<String> validate(String entityType, Set<String> studentIds); void setProgramValidator(GenericToProgramValidator programValidator); void setCohortValidator(GenericToCohortValidator cohortValidator); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanGetAccessThroughSingleValidAssociation() throws Exception { helper.generateStaffEdorg(STAFF_ID, ED_ORG_ID, NOT_EXPIRED); String studentId = helper.generateStudentAndStudentSchoolAssociation("2", edOrg.getEntityId(), NOT_EXPIRED); studentIds.add(studentId); assertTrue(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
@Test public void testCanNotGetAccessThroughInvalidAssociation() throws Exception { helper.generateStaffEdorg(STAFF_ID, ED_ORG_ID, NOT_EXPIRED); String studentId = helper.generateStudentAndStudentSchoolAssociation("2", ED_ORG_ID_2, NOT_EXPIRED); studentIds.add(studentId); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
@Test public void testCanNotGetAccessDueToExpiration() throws Exception { helper.generateStaffEdorg(STAFF_ID, ED_ORG_ID, NOT_EXPIRED); String studentId = helper.generateStudentAndStudentSchoolAssociation("2", ED_ORG_ID, IS_EXPIRED); studentIds.add(studentId); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
@Test public void testCanGetAccessThroughManyStudents() throws Exception { Set<String> expectedIds = new HashSet<String>(); for (int i = 0; i < N_TEST_EDORGS/2; ++i) { helper.generateStaffEdorg(STAFF_ID, edorgArray[ i ], NOT_EXPIRED); injector.addToAuthorizingEdOrgs( edorgArray[ i ] ); } for (int i = 0; i < N_TEST_EDORGS/2; ++i) { for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), edorgArray[ i ], NOT_EXPIRED); studentIds.add(studentId); expectedIds.add(studentId); } } assertTrue(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); for (int i = N_TEST_EDORGS/2; i < N_TEST_EDORGS; ++i) { for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), edorgArray[ i ], NOT_EXPIRED); studentIds.add(studentId); } } Assert.assertEquals(expectedIds, validator.validate(EntityNames.STUDENT, studentIds)); }
@Test public void testCanNotGetAccessThroughManyStudents() throws Exception { for (int i = N_TEST_EDORGS/2; i < N_TEST_EDORGS; ++i) { helper.generateStaffEdorg(STAFF_ID, edorgArray[ i ], NOT_EXPIRED); injector.addToAuthorizingEdOrgs( edorgArray[ i ] ); } for (int i = 0; i < N_TEST_EDORGS/2; ++i) { for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), edorgArray[ i ], NOT_EXPIRED); studentIds.add(studentId); } } assertFalse(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
@Test public void testCanNotGetAccessThroughManyStudentsWithOneFailure() throws Exception { for (int i = 0; i < N_TEST_EDORGS/2; ++i) { helper.generateStaffEdorg(STAFF_ID, edorgArray[ i ], NOT_EXPIRED); injector.addToAuthorizingEdOrgs( edorgArray[ i ] ); } Set<String> expected = new HashSet<String>(); for (int i = 0; i < N_TEST_EDORGS/2; ++i) { for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), edorgArray[ i ], NOT_EXPIRED); studentIds.add(studentId); expected.add(studentId); } } String anotherEdOrg = helper.generateSchoolEdOrg(null).getEntityId(); String studentId = helper.generateStudentAndStudentSchoolAssociation("-32", anotherEdOrg, NOT_EXPIRED); studentIds.add(studentId); Assert.assertEquals(expected, validator.validate(EntityNames.STUDENT, studentIds)); }
@Test public void testCanGetAccessThroughCohort() { Entity cohort = helper.generateStudentCohort("Merp", "Derp", false); Mockito.when(mockCohortValidator.validate(Mockito.eq(EntityNames.COHORT), Mockito.anySet())).thenReturn(new HashSet<String>(Arrays.asList(cohort.getEntityId()))); helper.generateStaffEdorg(STAFF_ID, DERP, NOT_EXPIRED); for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), ED_ORG_ID, NOT_EXPIRED); studentIds.add(studentId); } assertTrue(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
@Test public void testCanNotGetAccessThroughExpiredCohort() { Entity cohort = helper.generateStudentCohort("Merp", "Derp", true); Mockito.when(mockCohortValidator.validate(Mockito.eq(EntityNames.COHORT), Mockito.anySet())).thenReturn(new HashSet<String>(Arrays.asList(cohort.getEntityId()))); helper.generateStaffEdorg(STAFF_ID, DERP, NOT_EXPIRED); for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), ED_ORG_ID, NOT_EXPIRED); studentIds.add(studentId); } studentIds.add("Merp"); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
@Test public void testCanNotGetAccessThroughExpiredProgram() { Entity program = helper.generateStudentProgram("Merp", DERP, true); Mockito.when(mockProgramValidator.validate(Mockito.eq(EntityNames.PROGRAM), Mockito.anySet())).thenReturn(new HashSet<String>(Arrays.asList(program.getEntityId()))); helper.generateStaffEdorg(STAFF_ID, DERP, NOT_EXPIRED); for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), ED_ORG_ID, NOT_EXPIRED); studentIds.add(studentId); } studentIds.add("Merp"); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
@Test public void testCanNotGetAccessThroughInvalidProgram() { Entity program = helper.generateStudentProgram("Merp", "Derp", false); Mockito.when(mockProgramValidator.validate(Mockito.eq(EntityNames.PROGRAM), Mockito.anySet())).thenReturn(new HashSet<String>(Arrays.asList(program.getEntityId()))); helper.generateStaffEdorg(STAFF_ID, DERP, NOT_EXPIRED); for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), ED_ORG_ID, NOT_EXPIRED); studentIds.add(studentId); } studentIds.add("Merp"); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
@Test public void testCanNotGetAccessThroughInvalidCohort() { Entity cohort = helper.generateStudentCohort("Merp", "Derp", false); Mockito.when( mockCohortValidator.validate(Mockito.eq(EntityNames.COHORT), Mockito.anySet())).thenReturn(new HashSet<String>(Arrays.asList(cohort.getEntityId()))); helper.generateStaffEdorg(STAFF_ID, DERP, NOT_EXPIRED); for (int j = -1; j > -31; --j) { String studentId = helper.generateStudentAndStudentSchoolAssociation(String.valueOf(j), ED_ORG_ID, NOT_EXPIRED); studentIds.add(studentId); } studentIds.add("Merp"); assertFalse(validator.validate(EntityNames.STUDENT, studentIds).equals(studentIds)); }
|
StaffToStaffCohortAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.STAFF_COHORT_ASSOCIATION.equals(entityType) && isStaff(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STAFF_COHORT_ASSOCIATION, false)); assertTrue(validator.canValidate(EntityNames.STAFF_COHORT_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.COHORT, true)); assertFalse(validator.canValidate(EntityNames.COHORT, false)); }
|
StaffToStaffCohortAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STAFF_COHORT_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); Map<String, Set<String>> staffToSCA = new HashMap<String, Set<String>>(); Iterable<Entity> staffCohorts = getRepo().findAll(EntityNames.STAFF_COHORT_ASSOCIATION, basicQuery); for (Entity staff : staffCohorts) { Map<String, Object> body = staff.getBody(); if (isFieldExpired(body, ParameterConstants.END_DATE, true)) { continue; } String id = (String) body.get(ParameterConstants.STAFF_ID); if(!staffToSCA.containsKey(id)) { staffToSCA.put(id, new HashSet<String>()); } staffToSCA.get(id).add(staff.getEntityId()); } Set<String> staffIds = staffValidator.validate(EntityNames.STAFF, staffToSCA.keySet()); return getValidIds(staffIds, staffToSCA); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateStaffCohortAssociation() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); Entity school = helper.generateEdorgWithParent(lea.getEntityId()); helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); Entity sca = helper.generateStaffCohort(helper.STAFF_ID, helper.generateCohort(sea.getEntityId()).getEntityId(), false, true); cohortIds.add(sca.getEntityId()); Mockito.when(mockStaffValidator.validate(Mockito.eq(EntityNames.STAFF), Mockito.any(Set.class))).thenReturn(new HashSet<String>(Arrays.asList(helper.STAFF_ID))); assertTrue(validator.validate(EntityNames.STAFF_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); List<String> staffIds = new ArrayList<String>(); for (int i = 0; i < 5; ++i) { sca = helper.generateStaffCohort(i + "", helper.generateCohort(school.getEntityId()).getEntityId(), false, true); helper.generateStaffEdorg(i + "", school.getEntityId(), false); cohortIds.add(sca.getEntityId()); staffIds.add(i + ""); } Mockito.when(mockStaffValidator.validate(Mockito.eq(EntityNames.STAFF), Mockito.any(Set.class))).thenReturn(new HashSet<String>(staffIds)); assertTrue(validator.validate(EntityNames.STAFF_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); }
@Test public void testCanNotValidateExpiredAssociation() { Entity school = helper.generateEdorgWithParent(null); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), false); Entity sca = helper.generateStaffCohort(helper.STAFF_ID, helper.generateCohort(school.getEntityId()) .getEntityId(), true, false); cohortIds.add(sca.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); cohortIds.clear(); cleanCohortData(); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), true); sca = helper.generateStaffCohort(helper.STAFF_ID, helper.generateCohort(school.getEntityId()) .getEntityId(), false, false); cohortIds.add(sca.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); }
@Test public void testCanNotValidateOutsideOfEdorg() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); Entity school2 = helper.generateEdorgWithParent(null); helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); Entity sca = helper.generateStaffCohort("MOOP", helper.generateCohort(school2.getEntityId()).getEntityId(), false, true); cohortIds.add(sca.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); }
@Test public void testCanNotValidateAtStateLevel() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); Entity sca = helper.generateStaffCohort("MOOP", helper.generateCohort(sea.getEntityId()).getEntityId(), false, true); cohortIds.add(sca.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); }
|
StaffToCourseTranscriptValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.COURSE_TRANSCRIPT.equals(entityType) && isStaff(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateAsStaff() { setupCurrentUser(staff1); Assert.assertTrue("Must be able to validate", validator.canValidate(EntityNames.COURSE_TRANSCRIPT, false)); Assert.assertTrue("Must be able to validate", validator.canValidate(EntityNames.COURSE_TRANSCRIPT, true)); Assert.assertFalse("Must not be able to validate", validator.canValidate(EntityNames.ADMIN_DELEGATION, false)); }
|
StaffToCourseTranscriptValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.COURSE_TRANSCRIPT, entityType, ids)) { return Collections.emptySet(); } LOG.info("Validating {}'s access to courseTranscripts: [{}]", SecurityUtil.getSLIPrincipal().getName(), ids); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids))); Iterable<Entity> entities = getRepo().findAll(EntityNames.COURSE_TRANSCRIPT, query); Map<String, Set<String>> studentAcademicRecords = new HashMap<String, Set<String>>(); for (Entity entity : entities) { Map<String, Object> body = entity.getBody(); if (body.get(ParameterConstants.STUDENT_ACADEMIC_RECORD_ID) instanceof String) { String key = (String) body.get(ParameterConstants.STUDENT_ACADEMIC_RECORD_ID); if(!studentAcademicRecords.containsKey(key)) { studentAcademicRecords.put(key, new HashSet<String>()); } studentAcademicRecords.get(key).add(entity.getEntityId()); } else { LOG.warn("Possible Corrupt Data detected at "+entityType+"/"+entity.getEntityId()); } } if (studentAcademicRecords.isEmpty()) { return Collections.EMPTY_SET; } Set<String> validStudentAcademicRecords = validator.validate(EntityNames.STUDENT_ACADEMIC_RECORD, studentAcademicRecords.keySet()); return getValidIds(validStudentAcademicRecords, studentAcademicRecords); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testValidAssociationsForStaff1() { setupCurrentUser(staff1); Assert.assertEquals(1, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>(Arrays.asList(courseTranscript1.getEntityId()))).size()); }
@Test public void testValidAssociationsForStaff2() { setupCurrentUser(staff2); Assert.assertEquals(1, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>(Arrays.asList(courseTranscript2.getEntityId()))).size()); }
@Test public void testInValidAssociationsForStaff1() { setupCurrentUser(staff1); Assert.assertEquals(0, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>(Arrays.asList(courseTranscript2.getEntityId()))).size()); }
@Test public void testInValidAssociationsForStaff2() { setupCurrentUser(staff2); Assert.assertEquals(0, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>(Arrays.asList(courseTranscript1.getEntityId()))).size()); }
@Test public void testInvalidAssociations() { setupCurrentUser(staff2); Assert.assertEquals(0, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>(Arrays.asList(UUID.randomUUID().toString()))).size()); Assert.assertEquals(0, validator.validate(EntityNames.COURSE_TRANSCRIPT, new HashSet<String>()).size()); }
|
TeacherToCohortValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isTransitive && EntityNames.COHORT.equals(entityType) && isTeacher(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertFalse(val.canValidate(EntityNames.COHORT, false)); assertTrue(val.canValidate(EntityNames.COHORT, true)); assertFalse(val.canValidate(EntityNames.SECTION, true)); assertFalse(val.canValidate(EntityNames.SECTION, false)); }
|
TeacherToCohortValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { Set<String> validIds = new HashSet<String>(); if (!areParametersValid(EntityNames.COHORT, entityType, ids)) { return validIds; } NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil .getSLIPrincipal().getEntity().getEntityId())); nq.addCriteria(new NeutralCriteria(ParameterConstants.COHORT_ID, NeutralCriteria.CRITERIA_IN, ids)); Iterable<Entity> entities = getRepo().findAll(EntityNames.STAFF_COHORT_ASSOCIATION, nq); for (Entity entity : entities) { validIds.add((String) entity.getBody().get(ParameterConstants.COHORT_ID)); } validIds.retainAll(ids); return validIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test(expected = IllegalArgumentException.class) public void testValidateWrongType() { val.validate(EntityNames.ASSESSMENT, new HashSet<String>(Arrays.asList("Jomolungma"))); }
@Test public void testCanAccessAll() { List<String> descs = Arrays.asList("Just Cause", "Armaggedon", "Awareness"); Set<String> cohortIds = new HashSet<String>(); for (String desc : descs) { cohortIds.add(this.generateCohortAndAssociate(USER_ID, desc)); } Assert.assertTrue(!val.validate(EntityNames.COHORT, cohortIds).isEmpty()); }
@Test public void testCannotAccessAll() { List<String> descs = Arrays.asList("Just Cause", "Armaggedon", "Awareness"); Set<String> cohortIds = new HashSet<String>(); for (String desc : descs) { cohortIds.add(this.generateCohort(USER_ID, desc)); } Assert.assertFalse(val.validate(EntityNames.COHORT, cohortIds).size() == cohortIds.size()); for (String id : cohortIds) { Assert.assertFalse(val.validate(EntityNames.COHORT, Collections.singleton(id)).size() == 1); } }
@Test public void testHeterogeneousList() { List<String> descs = Arrays.asList("Just Cause", "Armageddon", "Awareness", "Chaos Mastery", "Life Mastery", "Death and Decay", "Node Mastery", "Artificer", "Warlord", "Conjurer"); Set<String> cohortIds = new HashSet<String>(); List<String> successes = new ArrayList<String>(); cohortIds.add(this.generateCohort(USER_ID, "Artifacts Home World")); String idPerm = this.generateCohortAndAssociate(USER_ID, "Large Home World"); cohortIds.add(idPerm); successes.add(idPerm); for (String desc : descs) { if(Math.random()>0.5) { cohortIds.add(this.generateCohort(USER_ID, desc)); } else { String id = this.generateCohortAndAssociate(USER_ID, desc); cohortIds.add(id); successes.add(id); } } Assert.assertFalse(val.validate(EntityNames.COHORT, cohortIds).containsAll(cohortIds)); for (String id : cohortIds) { if(successes.contains(id)) { Assert.assertEquals(val.validate(EntityNames.COHORT, Collections.singleton(id)).size(), 1); } else { Assert.assertFalse(!val.validate(EntityNames.COHORT, Collections.singleton(id)).isEmpty()); } } }
|
DidSchemaParser implements ResourceLoaderAware { public Map<String, DidRefConfig> getRefConfigs() { return refConfigs; } String getExtensionXsdLocation(); void setExtensionXsdLocation(String entensionXsdLocation); String getExtensionXsdParentLocation(); void setExtensionXsdParentLocation(String extensionXsdParentLocation); String getXsdParentLocation(); void setXsdParentLocation(String xsdParentLocation); String getXsdLocation(); void setXsdLocation(String xsdLocation); Map<String, List<DidNaturalKey>> getNaturalKeys(); void setNaturalKeys(Map<String, List<DidNaturalKey>> naturalKeys); @Override void setResourceLoader(ResourceLoader resourceLoader); @PostConstruct void setup(); Map<String, DidRefConfig> getRefConfigs(); Map<String, DidEntityConfig> getEntityConfigs(); Map<String, List<DidNaturalKey>> extractNaturalKeys(); }
|
@Test public void shouldExtractSimpleRefConfigs() { Map<String, DidRefConfig> refConfigs = didSchemaParser.getRefConfigs(); Assert.assertEquals("Should extract 9 ref configs for the SLC section and edOrg referenceTypes", 9, refConfigs.size()); Assert.assertTrue(refConfigs.containsKey(SECTION_TYPE)); Assert.assertTrue(refConfigs.containsKey(EDORG_TYPE)); DidRefConfig schoolRefConfig = refConfigs.get(EDORG_TYPE); Assert.assertNotNull(schoolRefConfig); Assert.assertEquals(EDORG_TYPE, schoolRefConfig.getEntityType()); Assert.assertNotNull(schoolRefConfig.getKeyFields()); Assert.assertEquals("nested schoolId ref should contain 1 key field", 1, schoolRefConfig.getKeyFields().size()); KeyFieldDef schoolStateOrgId = schoolRefConfig.getKeyFields().get(0); Assert.assertNotNull(schoolStateOrgId); Assert.assertEquals(SCHOOL_KEYFIELD, schoolStateOrgId.getKeyFieldName()); Assert.assertEquals("EducationalOrgIdentity.StateOrganizationId._value", schoolStateOrgId.getValueSource()); Assert.assertNull("school stateOrgId should not contain a nested reference", schoolStateOrgId.getRefConfig()); }
@Test public void shouldExtractNestedRefConfigs() { Map<String, DidRefConfig> refConfigs = didSchemaParser.getRefConfigs(); Assert.assertEquals("Should extract 9 ref configs for the SLC section and edOrg referenceTypes", 9, refConfigs.size()); Assert.assertTrue(refConfigs.containsKey(SECTION_TYPE)); Assert.assertTrue(refConfigs.containsKey(EDORG_TYPE)); DidRefConfig sectionRefConfig = refConfigs.get(SECTION_TYPE); Assert.assertNotNull(sectionRefConfig); Assert.assertEquals(sectionRefConfig.getEntityType(), SECTION_TYPE); Assert.assertNotNull(sectionRefConfig.getKeyFields()); List<KeyFieldDef> keyFields = sectionRefConfig.getKeyFields(); Assert.assertEquals("keyFields list should contain 2 keyfields", 2, keyFields.size()); Map<String, KeyFieldDef> keyFieldMap = new HashMap<String, KeyFieldDef>(); for (KeyFieldDef keyField : keyFields) { keyFieldMap.put(keyField.getKeyFieldName(), keyField); } Assert.assertTrue(keyFieldMap.containsKey(SECTION_KEY_FIELD)); KeyFieldDef uniqSectionCode = keyFieldMap.get(SECTION_KEY_FIELD); Assert.assertNotNull(uniqSectionCode); Assert.assertEquals(SECTION_KEY_FIELD, uniqSectionCode.getKeyFieldName()); Assert.assertNull("uniqueSectionCode should not have a nested DID", uniqSectionCode.getRefConfig()); Assert.assertEquals("SectionIdentity.UniqueSectionCode._value", uniqSectionCode.getValueSource()); Assert.assertTrue(keyFieldMap.containsKey(SECTION_SCHOOL_KEYFIELD)); KeyFieldDef schoolId = keyFieldMap.get(SECTION_SCHOOL_KEYFIELD); Assert.assertEquals(SECTION_SCHOOL_KEYFIELD, schoolId.getKeyFieldName()); Assert.assertNotNull("schoolId should have a nested DID", schoolId.getRefConfig()); Assert.assertNotNull("schoolId should have a value source", schoolId.getValueSource()); Assert.assertNotNull("SectionIdentity.EducationalOrgReference", schoolId.getValueSource()); DidRefConfig nestedRefConfig = schoolId.getRefConfig(); Assert.assertEquals(EDORG_TYPE, nestedRefConfig.getEntityType()); Assert.assertNotNull(nestedRefConfig.getKeyFields()); Assert.assertEquals("nested schoolId ref should contain 1 key field", 1, nestedRefConfig.getKeyFields().size()); KeyFieldDef stateOrgId = nestedRefConfig.getKeyFields().get(0); Assert.assertNotNull(stateOrgId); Assert.assertEquals(SCHOOL_KEYFIELD, stateOrgId.getKeyFieldName()); Assert.assertEquals("EducationalOrgIdentity.StateOrganizationId._value", stateOrgId.getValueSource()); Assert.assertNull("nested stateOrgId should not contain a nested reference", stateOrgId.getRefConfig()); }
|
GenericToProgramValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return !isStudentOrParent() && EntityNames.PROGRAM.equals(entityType) && !isTransitive; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { setupCurrentUser(teacher1); Assert.assertTrue(validator.canValidate(EntityNames.PROGRAM, false)); Assert.assertFalse(validator.canValidate(EntityNames.PROGRAM, true)); injector.setStaffContext(); Assert.assertTrue(validator.canValidate(EntityNames.PROGRAM, false)); Assert.assertFalse(validator.canValidate(EntityNames.PROGRAM, true)); }
|
GenericToProgramValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.PROGRAM, entityType, ids)) { return new HashSet<String>(); } NeutralQuery nq = new NeutralQuery(new NeutralCriteria("body.staffId", "=", SecurityUtil.getSLIPrincipal().getEntity().getEntityId(), false)); if (SecurityUtil.getSLIPrincipal().isStudentAccessFlag()) { nq.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_RECORD_ACCESS, NeutralCriteria.OPERATOR_EQUAL, true)); } addEndDateToQuery(nq, false); Set<String> validIds = new HashSet<String>(); Iterable<Entity> assocs = getRepo().findAll(EntityNames.STAFF_PROGRAM_ASSOCIATION, nq); for (Entity assoc : assocs) { validIds.add((String) assoc.getBody().get("programId")); } validIds.retainAll(ids); return validIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testValidAccessTeacher1() { setupCurrentUser(teacher1); Assert.assertTrue(validator.validate(EntityNames.PROGRAM, new HashSet<String>(Arrays.asList(program1.getEntityId()))).size() == 1); }
@Test public void testValidAccessTeacher2() { setupCurrentUser(teacher2); Assert.assertTrue(validator.validate(EntityNames.PROGRAM, new HashSet<String>(Arrays.asList(program2.getEntityId()))).size() == 1); }
@Test public void testInvalidAccessTeacher1() { setupCurrentUser(teacher1); Set<String> program = new HashSet<String>(Arrays.asList(program2.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.PROGRAM, program).equals(program)); program = new HashSet<String>(Arrays.asList(program3.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.PROGRAM, program).equals(program)); program = new HashSet<String>(Arrays.asList(program4.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.PROGRAM, program).equals(program)); }
@Test public void testInvalidAccessTeacher2() { setupCurrentUser(teacher2); Set<String> program = new HashSet<String>(Arrays.asList(program1.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.PROGRAM, program).equals(program)); program = new HashSet<String>(Arrays.asList(program3.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.PROGRAM, program).equals(program)); program = new HashSet<String>(Arrays.asList(program4.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.PROGRAM, program).equals(program)); }
|
StaffToCohortValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isTransitive && isStaff() && EntityNames.COHORT.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertFalse(validator.canValidate(EntityNames.COHORT, false)); assertTrue(validator.canValidate(EntityNames.COHORT, true)); assertFalse(validator.canValidate(EntityNames.SECTION, true)); assertFalse(validator.canValidate(EntityNames.SECTION, false)); }
|
StaffToCohortValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { Set<String> myCohortIds = new HashSet<String>(); if (!areParametersValid(EntityNames.COHORT, entityType, ids)) { return myCohortIds; } NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.getSLIPrincipal().getEntity().getEntityId())); Iterable<Entity> scas = getRepo().findAll(EntityNames.STAFF_COHORT_ASSOCIATION, basicQuery); for (Entity sca : scas) { Map<String, Object> body = sca.getBody(); if (isFieldExpired(body, ParameterConstants.END_DATE, true)) { continue; } else { myCohortIds.add((String) body.get(ParameterConstants.COHORT_ID)); } } basicQuery = new NeutralQuery(new NeutralCriteria("educationOrgId", NeutralCriteria.CRITERIA_IN, getStaffEdOrgLineage())); Iterable<Entity> cohorts = getRepo().findAll(EntityNames.COHORT, basicQuery); for (Entity cohort : cohorts) { myCohortIds.add(cohort.getEntityId()); } myCohortIds.retainAll(ids); return myCohortIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateStaffToCohort() { Entity school = helper.generateEdorgWithParent(null); Entity cohort = helper.generateCohort(school.getEntityId()); cohortIds.add(cohort.getEntityId()); Entity school2 = helper.generateEdorgWithParent(null); cohort = helper.generateCohort(school2.getEntityId()); helper.generateStaffCohort(helper.STAFF_ID, cohort.getEntityId(), false, true); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), false); cohortIds.add(cohort.getEntityId()); Set<String> validIds = validator.validate(EntityNames.COHORT, cohortIds); Assert.assertEquals(cohortIds, validIds); }
@Test public void testCanValidateStaffAtStateToCohort() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); Entity cohort = helper.generateCohort(sea.getEntityId()); cohortIds.add(cohort.getEntityId()); Set<String> validIds = validator.validate(EntityNames.COHORT, cohortIds); assertFalse(validIds.size() == cohortIds.size()); helper.generateStaffCohort(helper.STAFF_ID, cohort.getEntityId(), false, true); validIds = validator.validate(EntityNames.COHORT, cohortIds); Assert.assertEquals(validIds.size(), cohortIds.size()); }
@Test public void testCanNotValidateInvalidCohort() { Entity lea = helper.generateEdorgWithParent(null); Entity school = helper.generateEdorgWithParent(lea.getEntityId()); Entity school2 = helper.generateEdorgWithParent(null); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), false); Entity cohort = helper.generateCohort(lea.getEntityId()); cohortIds.add(cohort.getEntityId()); assertFalse(validator.validate(EntityNames.COHORT, cohortIds).size() == cohortIds.size()); cohortIds.clear(); cohort = helper.generateCohort(school2.getEntityId()); cohortIds.add(cohort.getEntityId()); assertFalse(validator.validate(EntityNames.COHORT, cohortIds).size() == cohortIds.size()); }
@Test public void testCanNotValidateExpiredCohort() { Entity lea = helper.generateEdorgWithParent(null); Entity school = helper.generateEdorgWithParent(lea.getEntityId()); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), true); Entity cohort = helper.generateCohort(lea.getEntityId()); cohortIds.add(cohort.getEntityId()); helper.generateStaffCohort(helper.STAFF_ID, cohort.getEntityId(), false, true); assertTrue(validator.validate(EntityNames.COHORT, cohortIds).equals(cohortIds)); repo.deleteAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, new NeutralQuery()); repo.deleteAll(EntityNames.STAFF_COHORT_ASSOCIATION, new NeutralQuery()); helper.generateStaffEdorg(helper.STAFF_ID, school.getEntityId(), false); helper.generateStaffCohort(helper.STAFF_ID, cohort.getEntityId(), true, true); assertFalse(validator.validate(EntityNames.COHORT, cohortIds).size() == cohortIds.size()); repo.deleteAll(EntityNames.STAFF_COHORT_ASSOCIATION, new NeutralQuery()); helper.generateStaffCohort(helper.STAFF_ID, cohort.getEntityId(), false, false); assertTrue(validator.validate(EntityNames.COHORT, cohortIds).equals(cohortIds)); }
@Test public void testCanValidateIntersectionRules() { Entity sea = helper.generateEdorgWithParent(null); Entity lea = helper.generateEdorgWithParent(sea.getEntityId()); Entity school = helper.generateEdorgWithParent(lea.getEntityId()); helper.generateStaffEdorg(helper.STAFF_ID, lea.getEntityId(), false); for (int i = 0; i < 10; ++i) { Entity cohort = helper.generateCohort(school.getEntityId()); cohortIds.add(cohort.getEntityId()); } Entity cohort = helper.generateCohort(lea.getEntityId()); cohortIds.add(cohort.getEntityId()); helper.generateStaffCohort(helper.STAFF_ID, cohort.getEntityId(), false, true); Assert.assertEquals(cohortIds, validator.validate(EntityNames.COHORT, cohortIds)); for (int i = 0; i < 5; ++i) { cohort = helper.generateCohort(sea.getEntityId()); helper.generateStaffCohort(helper.STAFF_ID, cohort.getEntityId(), false, true); cohortIds.add(cohort.getEntityId()); } Assert.assertEquals(validator.validate(EntityNames.COHORT, cohortIds), cohortIds); }
|
GenericToEdOrgValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { if (EntityNames.SCHOOL.equals(entityType) || EntityNames.EDUCATION_ORGANIZATION.equals(entityType)) { if (isStudentOrParent()) { return !isTransitive; } return true; } return false; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.SCHOOL, false)); assertTrue(validator.canValidate(EntityNames.SCHOOL, true)); assertTrue(validator.canValidate(EntityNames.EDUCATION_ORGANIZATION, false)); assertTrue(validator.canValidate(EntityNames.EDUCATION_ORGANIZATION, true)); }
@Test public void testCanNotValidate() { assertFalse(validator.canValidate(EntityNames.ATTENDANCE, true)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); assertFalse(validator.canValidate(EntityNames.SECTION, true)); assertFalse(validator.canValidate(EntityNames.SECTION, false)); }
|
GenericToEdOrgValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { LOG.trace(">>>GenericToEdOrgValidator.validate()"); LOG.trace(" entityType: " + entityType); LOG.trace(" ids: " + ids); if (!areParametersValid(Arrays.asList(EntityNames.SCHOOL, EntityNames.EDUCATION_ORGANIZATION), entityType, ids)) { LOG.trace(" ...return empty set - areParametersValid"); return Collections.emptySet(); } Set<String> edOrgs = getDirectEdorgs(); LOG.trace(" ...count after adding DirectEdorgs: " + edOrgs.size()); edOrgs.addAll(getEdorgDescendents(edOrgs)); LOG.trace(" ...count after adding getEdorgDescendents: " + edOrgs.size()); edOrgs.retainAll(ids); LOG.trace(" ...count after adding providedIds: " + edOrgs.size()); LOG.trace(" edOrgs: " + edOrgs.toString()); return edOrgs; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateTeacherAtSchool() { setTeacherContext(school.getEntityId()); schoolIds.add(school.getEntityId()); helper.generateTeacherSchool(teacher.getEntityId(), school.getEntityId()); Assert.assertEquals(schoolIds, validator.validate(EntityNames.SCHOOL, schoolIds)); Assert.assertEquals(schoolIds, validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds)); }
@Test public void testCanValidateStaffAtSchool() { setStaffContext(school.getEntityId()); schoolIds.add(school.getEntityId()); helper.generateStaffEdorg(staff.getEntityId(), school.getEntityId(), false); Assert.assertEquals(schoolIds, validator.validate(EntityNames.SCHOOL, schoolIds)); Assert.assertEquals(schoolIds, validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds)); }
@Test public void testCanValidateStaffFromStateDownToSchool() { setStaffContext(sea.getEntityId()); helper.generateStaffEdorg(staff.getEntityId(), sea.getEntityId(), false); schoolIds.add(school.getEntityId()); schoolIds.add(lea.getEntityId()); schoolIds.add(sea.getEntityId()); Assert.assertEquals(schoolIds, validator.validate(EntityNames.SCHOOL, schoolIds)); Assert.assertEquals(schoolIds, validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds)); }
@Test public void testCanNotValidateTeacherAccessingParentEdOrg() { setTeacherContext(school.getEntityId()); helper.generateTeacherSchool(teacher.getEntityId(), school.getEntityId()); schoolIds.add(school.getEntityId()); schoolIds.add(lea.getEntityId()); schoolIds.add(sea.getEntityId()); assertFalse(validator.validate(EntityNames.SCHOOL, schoolIds).equals(schoolIds)); assertFalse(validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds).equals(schoolIds)); }
@Test public void testCanValidateTeacherAtSchoolIntersection() { setTeacherContext(school.getEntityId()); for (int i = 0; i < 10; ++i) { Entity newSchool = helper.generateEdorgWithParent(lea.getEntityId()); injector.addToAuthorizingEdOrgs(newSchool.getEntityId()); helper.generateTeacherSchool(teacher.getEntityId(), newSchool.getEntityId()); schoolIds.add(newSchool.getEntityId()); } Assert.assertEquals(schoolIds, validator.validate(EntityNames.SCHOOL, schoolIds)); Assert.assertEquals(schoolIds, validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds)); Entity newSchool = helper.generateEdorgWithParent(lea.getEntityId()); injector.addToAuthorizingEdOrgs(newSchool.getEntityId()); schoolIds.add(newSchool.getEntityId()); assertFalse(validator.validate(EntityNames.SCHOOL, schoolIds).equals(schoolIds)); assertFalse(validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds).equals(schoolIds)); }
@Test public void testCanValidateStaffAtSchoolIntersection() { setStaffContext(sea.getEntityId()); for (int i = 0; i < 10; ++i) { Entity newSchool = helper.generateEdorgWithParent(lea.getEntityId()); injector.addToAuthorizingEdOrgs(newSchool.getEntityId()); helper.generateStaffEdorg(staff.getEntityId(), newSchool.getEntityId(), false); schoolIds.add(newSchool.getEntityId()); } assertTrue(validator.validate(EntityNames.SCHOOL, schoolIds).equals(schoolIds)); assertTrue(validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds).equals(schoolIds)); Entity newSchool = helper.generateEdorgWithParent(lea.getEntityId()); injector.addToAuthorizingEdOrgs(newSchool.getEntityId()); schoolIds.add(newSchool.getEntityId()); assertFalse(validator.validate(EntityNames.SCHOOL, schoolIds).equals(schoolIds)); assertFalse(validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds).equals(schoolIds)); }
@Test public void testCanNotValidateTeacherNotAtSchool() { setTeacherContext(school.getEntityId()); schoolIds.add(school.getEntityId()); school = helper.generateEdorgWithParent(null); helper.generateTeacherSchool(teacher.getEntityId(), school.getEntityId()); assertFalse(validator.validate(EntityNames.SCHOOL, schoolIds).equals(schoolIds)); assertFalse(validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds).equals(schoolIds)); }
@Test public void testCanNotValidateStaffNotAtSchool() { setStaffContext(school.getEntityId()); schoolIds.add(school.getEntityId()); school = helper.generateEdorgWithParent(null); helper.generateStaffEdorg(staff.getEntityId(), school.getEntityId(), false); assertFalse(validator.validate(EntityNames.SCHOOL, schoolIds).equals(schoolIds)); assertFalse(validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds).equals(schoolIds)); }
@Test public void testCanNotValidateExpiredStaff() { setStaffContext(school.getEntityId()); schoolIds.add(school.getEntityId()); helper.generateStaffEdorg(staff.getEntityId(), school.getEntityId(), true); assertFalse(validator.validate(EntityNames.SCHOOL, schoolIds).equals(schoolIds)); assertFalse(validator.validate(EntityNames.EDUCATION_ORGANIZATION, schoolIds).equals(schoolIds)); }
|
DidSchemaParser implements ResourceLoaderAware { public Map<String, DidEntityConfig> getEntityConfigs() { return entityConfigs; } String getExtensionXsdLocation(); void setExtensionXsdLocation(String entensionXsdLocation); String getExtensionXsdParentLocation(); void setExtensionXsdParentLocation(String extensionXsdParentLocation); String getXsdParentLocation(); void setXsdParentLocation(String xsdParentLocation); String getXsdLocation(); void setXsdLocation(String xsdLocation); Map<String, List<DidNaturalKey>> getNaturalKeys(); void setNaturalKeys(Map<String, List<DidNaturalKey>> naturalKeys); @Override void setResourceLoader(ResourceLoader resourceLoader); @PostConstruct void setup(); Map<String, DidRefConfig> getRefConfigs(); Map<String, DidEntityConfig> getEntityConfigs(); Map<String, List<DidNaturalKey>> extractNaturalKeys(); }
|
@Test public void shouldExtractEntityConfigs() { Map<String, DidEntityConfig> entityConfigs = didSchemaParser.getEntityConfigs(); Assert.assertEquals("Should extract 5 entity config for the 5 complexType containing a sectionReference (SLC-GradebookEntry)", 5, entityConfigs.size()); Assert.assertTrue(entityConfigs.containsKey(GRADEBOOKENTRY_TYPE)); DidEntityConfig gbeConfig = entityConfigs.get(GRADEBOOKENTRY_TYPE); Assert.assertNotNull(gbeConfig); Assert.assertNotNull(gbeConfig.getReferenceSources()); List<DidRefSource> refSources = gbeConfig.getReferenceSources(); Assert.assertEquals("entity config should contain a single DidRefSource (section)", 1, refSources.size()); DidRefSource refSource = refSources.get(0); Assert.assertNotNull(refSource); Assert.assertEquals(SECTION_TYPE, refSource.getEntityType()); Assert.assertEquals("body.SectionReference", refSource.getSourceRefPath()); }
|
TeacherToGradeValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isTeacher() && EntityNames.GRADE.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.GRADE, true)); assertTrue(validator.canValidate(EntityNames.GRADE, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); }
|
TeacherToGradeValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.GRADE, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); query.setIncludeFields(Arrays.asList(ParameterConstants.STUDENT_SECTION_ASSOCIATION_ID)); Iterable<Entity> grades = getRepo().findAll(EntityNames.GRADE, query); Map<String, Set<String>> secAssocIdsToGrade = new HashMap<String, Set<String>>(); for(Entity grade : grades) { String id = (String) grade.getBody().get(ParameterConstants.STUDENT_SECTION_ASSOCIATION_ID); if (!secAssocIdsToGrade.containsKey(id)) { secAssocIdsToGrade.put(id, new HashSet<String>()); } secAssocIdsToGrade.get(id).add(grade.getEntityId()); } Set<String> validSecAssocIds = sectionAssocValidator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, secAssocIdsToGrade.keySet()); return getValidIds(validSecAssocIds, secAssocIdsToGrade); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testValidGrades() { Set<String> ids = new HashSet<String>(Arrays.asList(grade1.getEntityId())); assertTrue(validator.validate(EntityNames.GRADE, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(grade2.getEntityId())); assertTrue(validator.validate(EntityNames.GRADE, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(grade1.getEntityId(), grade2.getEntityId())); assertTrue(validator.validate(EntityNames.GRADE, ids).equals(ids)); }
@Test public void testInvalidGrades() { Set<String> ids = new HashSet<String>(Arrays.asList(grade3.getEntityId())); assertFalse(validator.validate(EntityNames.GRADE, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(grade1.getEntityId(), grade3.getEntityId())); assertFalse(validator.validate(EntityNames.GRADE, ids).equals(ids)); }
|
StaffToTeacherSectionAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isStaff() && EntityNames.TEACHER_SECTION_ASSOCIATION.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testCanValidateStaffToTeacherSectionAssociation() throws Exception { setContext(seaStaff, Arrays.asList(SecureRoleRightAccessImpl.SEA_ADMINISTRATOR)); assertTrue(validator.canValidate(EntityNames.TEACHER_SECTION_ASSOCIATION, false)); assertTrue(validator.canValidate(EntityNames.TEACHER_SECTION_ASSOCIATION, true)); }
@Test public void testDeniedStaffToOtherEntities() throws Exception { setContext(seaStaff, Arrays.asList(SecureRoleRightAccessImpl.SEA_ADMINISTRATOR)); assertFalse(validator.canValidate(EntityNames.STUDENT, true)); assertFalse(validator.canValidate(EntityNames.STUDENT, false)); assertFalse(validator.canValidate(EntityNames.TEACHER, true)); assertFalse(validator.canValidate(EntityNames.TEACHER, false)); }
@Test public void testCanNotValidateAsNonStaffToTeacherSectionAssociation() throws Exception { setContext(educator, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); SecurityUtil.setUserContext(SecurityUtil.UserContext.TEACHER_CONTEXT); assertFalse(validator.canValidate(EntityNames.TEACHER_SECTION_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.TEACHER_SECTION_ASSOCIATION, true)); }
|
DidSchemaParser implements ResourceLoaderAware { public Map<String, List<DidNaturalKey>> getNaturalKeys() { return naturalKeys; } String getExtensionXsdLocation(); void setExtensionXsdLocation(String entensionXsdLocation); String getExtensionXsdParentLocation(); void setExtensionXsdParentLocation(String extensionXsdParentLocation); String getXsdParentLocation(); void setXsdParentLocation(String xsdParentLocation); String getXsdLocation(); void setXsdLocation(String xsdLocation); Map<String, List<DidNaturalKey>> getNaturalKeys(); void setNaturalKeys(Map<String, List<DidNaturalKey>> naturalKeys); @Override void setResourceLoader(ResourceLoader resourceLoader); @PostConstruct void setup(); Map<String, DidRefConfig> getRefConfigs(); Map<String, DidEntityConfig> getEntityConfigs(); Map<String, List<DidNaturalKey>> extractNaturalKeys(); }
|
@Test public void shouldextractNaturalKeys() { Map<String, List<DidNaturalKey>> naturalKeys = didSchemaParser.getNaturalKeys(); Assert.assertNotNull(naturalKeys); Assert.assertTrue(naturalKeys.containsKey("learningObjective")); List<DidNaturalKey> keys = naturalKeys.get("learningObjective"); Assert.assertNotNull(keys); Assert.assertEquals(3, keys.size()); Assert.assertEquals("Objective", keys.get(0).getNaturalKeyName()); Assert.assertFalse(keys.get(0).isOptional); Assert.assertTrue(naturalKeys.containsKey("localEducationAgency")); keys = naturalKeys.get("localEducationAgency"); Assert.assertNotNull(keys); Assert.assertEquals(1, keys.size()); Assert.assertEquals("StateOrganizationId", keys.get(0).getNaturalKeyName()); Assert.assertFalse(keys.get(0).isOptional); Assert.assertTrue(naturalKeys.containsKey("studentCompetency")); keys = naturalKeys.get("studentCompetency"); Assert.assertNotNull(keys); Assert.assertEquals(4, keys.size()); Assert.assertEquals("CompetencyLevel.CodeValue", keys.get(1).getNaturalKeyName()); Assert.assertFalse(keys.get(1).isOptional); Assert.assertEquals("LearningObjectiveReference", keys.get(3).getNaturalKeyName()); Assert.assertTrue(keys.get(3).isOptional); Assert.assertTrue(naturalKeys.containsKey("attendance")); keys = naturalKeys.get("attendance"); Assert.assertNotNull(keys); Assert.assertEquals(4, keys.size()); Assert.assertEquals("StateOrganizationId", keys.get(1).getNaturalKeyName()); Assert.assertFalse(keys.get(1).isOptional); Assert.assertTrue(naturalKeys.containsKey("reportCard")); keys = naturalKeys.get("reportCard"); Assert.assertNotNull(keys); Assert.assertEquals(2, keys.size()); Assert.assertEquals("GradingPeriodReference", keys.get(1).getNaturalKeyName()); Assert.assertFalse(keys.get(1).isOptional); Assert.assertTrue(naturalKeys.containsKey("program")); keys = naturalKeys.get("program"); Assert.assertNotNull(keys); Assert.assertEquals(1, keys.size()); Assert.assertEquals("ProgramId", keys.get(0).getNaturalKeyName()); Assert.assertFalse(keys.get(0).isOptional); }
|
StaffToTeacherSectionAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.TEACHER_SECTION_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids))); Iterable<Entity> teacherSectionAssociations = getRepo().findAll(entityType, query); Map<String, Set<String>> sections = new HashMap<String, Set<String>>(); if (teacherSectionAssociations != null) { for (Entity teacherSectionAssociation : teacherSectionAssociations) { Map<String, Object> body = teacherSectionAssociation.getBody(); String section = (String) body.get(ParameterConstants.SECTION_ID); if (!sections.containsKey(section)) { sections.put(section, new HashSet<String>()); } sections.get(section).add(teacherSectionAssociation.getEntityId()); } } if (sections.isEmpty()) { return Collections.EMPTY_SET; } Set<String> validSections = validator.validate(EntityNames.SECTION, sections.keySet()); return getValidIds(validSections, sections); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test public void testNullTeacherSectionAssociation() throws Exception { assertTrue(validator.validate(EntityNames.TEACHER_SECTION_ASSOCIATION, null).isEmpty()); }
@Test public void testEmptyTeacherSectionAssociation() throws Exception { Set<String> teacherSectionAssociations = new HashSet<String>(); assertTrue(validator.validate(EntityNames.TEACHER_SECTION_ASSOCIATION, teacherSectionAssociations).isEmpty()); }
@Test public void testSeaAdministratorCanGetAccessToTeacherSectionAssociation() throws Exception { setContext(seaStaff, Arrays.asList(SecureRoleRightAccessImpl.SEA_ADMINISTRATOR)); Set<String> teacherSectionAssociations = new HashSet<String>(); teacherSectionAssociations.add(teacherSectionAssociation.getEntityId()); assertTrue(validator.validate(EntityNames.TEACHER_SECTION_ASSOCIATION, teacherSectionAssociations).equals(teacherSectionAssociations)); }
@Test public void testLeaAdministratorCanGetAccessToTeacherSectionAssociation() throws Exception { setContext(leaStaff, Arrays.asList(SecureRoleRightAccessImpl.LEA_ADMINISTRATOR)); Set<String> teacherSectionAssociations = new HashSet<String>(); teacherSectionAssociations.add(teacherSectionAssociation.getEntityId()); assertTrue(validator.validate(EntityNames.TEACHER_SECTION_ASSOCIATION, teacherSectionAssociations).equals(teacherSectionAssociations)); }
@Test public void testSchoolAdministratorCanGetAccessToTeacherSectionAssociation() throws Exception { setContext(schoolStaff, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); Set<String> teacherSectionAssociations = new HashSet<String>(); teacherSectionAssociations.add(teacherSectionAssociation.getEntityId()); assertTrue(validator.validate(EntityNames.TEACHER_SECTION_ASSOCIATION, teacherSectionAssociations).equals(teacherSectionAssociations)); }
|
TeacherToStaffProgramAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STAFF_PROGRAM_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.getSLIPrincipal().getEntity().getEntityId())); nq.addCriteria(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); Iterable<String> validIds= getRepo().findAllIds(EntityNames.STAFF_PROGRAM_ASSOCIATION, nq); return Sets.newHashSet(validIds); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
|
@Test(expected = IllegalArgumentException.class) public void testValidateWrongType() { val.validate(EntityNames.ASSESSMENT, new HashSet<String>(Arrays.asList("Jomolungma"))); }
@Test public void testSuccessOne() { Entity tsa = this.vth.generateStaffProgram(USER_ID, PROGRAM_ID, false, true); Set<String> ids = Collections.singleton(tsa.getEntityId()); Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); }
@Test public void testSuccessMulti() { Set<String> ids = new HashSet<String>(); for (int i = 0; i < 100; i++) { ids.add(this.vth.generateStaffProgram(USER_ID, PROGRAM_ID, false, true).getEntityId()); } Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); }
@Test public void testWrongId() { Set<String> ids = Collections.singleton("Hammerhands"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); ids = Collections.singleton("Nagas"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); ids = Collections.singleton("Phantom Warriors"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); }
@Test public void testHeterogenousList() { Set<String> ids = new HashSet<String>(Arrays.asList(this.vth.generateStaffProgram(USER_ID, PROGRAM_ID, false, true).getEntityId(), this.vth.generateStaffProgram("Ssss'ra", "Arcanus", false, true).getEntityId(), this.vth.generateStaffProgram("Kali", "Arcanus", false, true).getEntityId())); Assert.assertFalse(val.validate( CORRECT_ENTITY_TYPE, ids).equals(ids)); }
|
SmooksEdFi2SLITransformer extends EdFi2SLITransformer { @Override public List<SimpleEntity> transform(NeutralRecord item, AbstractMessageReport report, ReportStats reportStats) { JavaResult result = new JavaResult(); Smooks smooks = smooksConfigs.get(item.getRecordType()); if (smooks == null) { String type = item.getRecordType().replaceAll("_transformed", ""); Map<String, Object> body = item.getAttributes(); SimpleEntity entity = new SimpleEntity(); entity.setType(type); entity.setBody(body); entity.setStagedEntityId(item.getRecordId()); entity.setSourceFile(item.getSourceFile()); entity.setVisitBeforeLineNumber(item.getVisitBeforeLineNumber()); entity.setVisitBeforeColumnNumber(item.getVisitBeforeColumnNumber()); entity.setVisitAfterLineNumber(item.getVisitAfterLineNumber()); entity.setVisitAfterColumnNumber(item.getVisitAfterColumnNumber()); if (entity.getMetaData() == null) { entity.setMetaData(new HashMap<String, Object>()); } String externalId = (String) item.getLocalId(); if (externalId != null) { entity.getMetaData().put("externalId", externalId); } entity.setAction( item.getActionVerb()); entity.setActionAttributes(item.getActionAttributes()); return Arrays.asList(entity); } List<SimpleEntity> sliEntities; try { StringSource source = new StringSource(MAPPER.writeValueAsString(item)); smooks.filterSource(source, result); sliEntities = getEntityListResult(result); for (SimpleEntity entity : sliEntities) { entity.setSourceFile(item.getSourceFile()); entity.setVisitBeforeLineNumber(item.getVisitBeforeLineNumber()); entity.setVisitBeforeColumnNumber(item.getVisitBeforeColumnNumber()); entity.setVisitAfterLineNumber(item.getVisitAfterLineNumber()); entity.setVisitAfterColumnNumber(item.getVisitAfterColumnNumber()); if (entity.getMetaData() == null) { entity.setMetaData(new HashMap<String, Object>()); } entity.setAction( item.getActionVerb()); entity.setActionAttributes(item.getActionAttributes()); } } catch (java.io.IOException e) { sliEntities = Collections.emptyList(); } return sliEntities; } @Override List<SimpleEntity> transform(NeutralRecord item, AbstractMessageReport report, ReportStats reportStats); Map<String, Smooks> getSmooksConfigs(); void setSmooksConfigs(Map<String, Smooks> smooksConfigs); @Override List<List<SimpleEntity>> handle(List<NeutralRecord> items, AbstractMessageReport report,
ReportStats reportStats); @Override String getStageName(); }
|
@Test public void testDirectMapping() { NeutralRecord directlyMapped = new NeutralRecord(); directlyMapped.setRecordType("directEntity"); directlyMapped.setAttributeField("field2", "Test String"); ReportStats reportStats = new SimpleReportStats(); List<? extends Entity> result = transformer.transform(directlyMapped, new DummyMessageReport(), reportStats); Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); Assert.assertEquals("Test String", result.get(0).getBody().get("field1")); }
@Test public void testEncoding() { NeutralRecord directlyMapped = new NeutralRecord(); directlyMapped.setRecordType("directEntity"); directlyMapped.setAttributeField("field2", "Test&String"); ReportStats reportStats = new SimpleReportStats(); List<? extends Entity> result = transformer.transform(directlyMapped, new DummyMessageReport(), reportStats); Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); Assert.assertEquals("Test&String", result.get(0).getBody().get("field1")); }
@SuppressWarnings("unchecked") @Test public void testTeacherSchoolAssociationMapping() { NeutralRecord teacherSchoolAssociation = createTeacherSchoolAssociationNeutralRecord(); ReportStats reportStats = new SimpleReportStats(); List<? extends Entity> result = transformer.transform(teacherSchoolAssociation, new DummyMessageReport(), reportStats); Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); Entity tsa = result.get(0); Assert.assertNotNull(tsa.getBody().get("teacherId")); Assert.assertEquals("teacherreference", tsa.getBody().get("teacherId")); Assert.assertNotNull(tsa.getBody().get("schoolId")); Assert.assertEquals("schoolreference", tsa.getBody().get("schoolId")); Assert.assertNotNull(tsa.getBody().get("programAssignment")); Assert.assertEquals("programassignment", tsa.getBody().get("programAssignment")); Assert.assertNotNull(tsa.getBody().get("academicSubjects")); List<String> academicSubjects =((List<String>) tsa.getBody().get("academicSubjects")); Assert.assertEquals(2, academicSubjects.size()); Assert.assertTrue(academicSubjects.contains("Computer Science")); Assert.assertTrue(academicSubjects.contains("AP Computer Science")); Assert.assertNotNull(tsa.getBody().get("instructionalGradeLevels")); List<String> instructionalGradeLevels =((List<String>) tsa.getBody().get("instructionalGradeLevels")); Assert.assertEquals(2, instructionalGradeLevels.size()); Assert.assertTrue(instructionalGradeLevels.contains("High School")); Assert.assertTrue(instructionalGradeLevels.contains("8th Grade")); }
@SuppressWarnings("unchecked") @Test public void testAssessmentMapping() { NeutralRecord assessment = createAssessmentNeutralRecord(false); ReportStats reportStats = new SimpleReportStats(); List<? extends Entity> result = transformer.transform(assessment, new DummyMessageReport(), reportStats); Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); Assert.assertEquals("assessmentTitle", result.get(0).getBody().get("assessmentTitle")); Assert.assertEquals(ASSESSMENT_FAMILY_ID, result.get(0).getBody().get("assessmentFamilyReference")); List<Map<String, Object>> assessmentIDCodeList = (List<Map<String, Object>>) result.get(0) .getBody().get("assessmentIdentificationCode"); Assert.assertNotNull(assessmentIDCodeList); Assert.assertEquals(2, assessmentIDCodeList.size()); Map<String, Object> assessmentIDCode1 = assessmentIDCodeList.get(0); Assert.assertNotNull(assessmentIDCode1); Assert.assertEquals("202A1", assessmentIDCode1.get("ID")); Assert.assertEquals("School", assessmentIDCode1.get("identificationSystem")); Assert.assertEquals("assigningOrganizationCode", assessmentIDCode1.get("assigningOrganizationCode")); Map<String, Object> assessmentIDCode2 = assessmentIDCodeList.get(1); Assert.assertNotNull(assessmentIDCode2); Assert.assertEquals("303A1", assessmentIDCode2.get("ID")); Assert.assertEquals("State", assessmentIDCode2.get("identificationSystem")); Assert.assertEquals("assigningOrganizationCode2", assessmentIDCode2.get("assigningOrganizationCode")); List<Map<String, Object>> assessmentPerfLevelList = (List<Map<String, Object>>) result .get(0).getBody().get("assessmentPerformanceLevel"); Assert.assertNotNull(assessmentPerfLevelList); Assert.assertEquals(2, assessmentPerfLevelList.size()); Map<String, Object> assessmentPerfLevel1 = assessmentPerfLevelList.get(0); Assert.assertNotNull(assessmentPerfLevel1); Assert.assertEquals(2400, assessmentPerfLevel1.get("maximumScore")); Assert.assertEquals(1600, assessmentPerfLevel1.get("minimumScore")); Assert.assertEquals("C-scaled scores", assessmentPerfLevel1.get("assessmentReportingMethod")); List<Map<String, Object>> perfLevelDescriptor1 = (List<Map<String, Object>>) assessmentPerfLevel1 .get("performanceLevelDescriptor"); Assert.assertEquals("description1", perfLevelDescriptor1.get(0).get("description")); Map<String, Object> assessmentPerfLevel2 = assessmentPerfLevelList.get(1); Assert.assertNotNull(assessmentPerfLevel2); Assert.assertEquals(2600, assessmentPerfLevel2.get("maximumScore")); Assert.assertEquals(1800, assessmentPerfLevel2.get("minimumScore")); Assert.assertEquals("ACT score", assessmentPerfLevel2.get("assessmentReportingMethod")); List<Map<String, Object>> perfLevelDescriptor2 = (List<Map<String, Object>>) assessmentPerfLevel2 .get("performanceLevelDescriptor"); Assert.assertEquals("description2", perfLevelDescriptor2.get(0).get("description")); Assert.assertEquals("Achievement test", result.get(0).getBody().get("assessmentCategory")); Assert.assertEquals("English", result.get(0).getBody().get("academicSubject")); Assert.assertEquals("Adult Education", result.get(0).getBody().get("gradeLevelAssessed")); Assert.assertEquals("Early Education", result.get(0).getBody().get("lowestGradeLevelAssessed")); Assert.assertEquals("SAT", result.get(0).getBody().get("contentStandard")); Assert.assertEquals("assessmentForm", result.get(0).getBody().get("assessmentForm")); Assert.assertEquals(1, result.get(0).getBody().get("version")); Assert.assertEquals("1999-01-01", result.get(0).getBody().get("revisionDate")); Assert.assertEquals(2400, result.get(0).getBody().get("maxRawScore")); Assert.assertEquals("nomenclature", result.get(0).getBody().get("nomenclature")); }
@Test public void testCourseTranscriptMapping() { NeutralRecord transcript = createCourseTranscriptNeutralRecord(false); ReportStats reportStats = new SimpleReportStats(); List<? extends Entity> result = transformer.transform(transcript, new DummyMessageReport(), reportStats); Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); Assert.assertFalse( transcript.getAttributes().containsKey( "GradeType")); Assert.assertEquals("courseAttemptResult", result.get(0).getBody().get("courseAttemptResult")); Assert.assertEquals("C", result.get(0).getBody().get("finalLetterGradeEarned")); Assert.assertEquals("Final", result.get(0).getBody().get("gradeType")); Assert.assertEquals("courseTranscript", result.get(0).getType()); NeutralRecord transcript1 = createCourseTranscriptNeutralRecord( true ); ReportStats reportStats1 = new SimpleReportStats(); result = transformer.transform(transcript1, new DummyMessageReport(), reportStats1); Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); Assert.assertTrue( transcript1.getAttributes().containsKey( "GradeType")); Assert.assertEquals("courseAttemptResult", result.get(0).getBody().get("courseAttemptResult")); Assert.assertEquals("C", result.get(0).getBody().get("finalLetterGradeEarned")); Assert.assertEquals("GradeType", result.get(0).getBody().get("gradeType")); Assert.assertEquals("courseTranscript", result.get(0).getType()); }
|
PagingRepositoryDelegate implements Repository<T> { public List<List<String>> extractBrokenListOfIds(List<String> queriedIds) { List<List<String>> brokenList = new ArrayList<List<String>>(); int blocks = queriedIds.size() / count; if (queriedIds.size() % count > 0) { blocks++; } for (int i = 0; i < blocks; ++i) { List<String> part = new ArrayList<String>(); int offSet = queriedIds.size() - i * count; if (offSet > count) { offSet = count; } part.addAll(queriedIds.subList(i * count, i * count + offSet)); brokenList.add(part); } return brokenList; } @Override T createWithRetries(String type, String id, Map<String, Object> body, Map<String, Object> metaData,
String collectionName, int noOfRetries); @Override WriteResult updateMulti(NeutralQuery query, Map<String, Object> update, String entityReferenced); List<List<String>> extractBrokenListOfIds(List<String> queriedIds); @Override T create(String type, Map<String, Object> body); @Override T create(String type, Map<String, Object> body, String collectionName); @Override T create(String type, Map<String, Object> body, Map<String, Object> metaData, String collectionName); @Override List<T> insert(List<T> records, String collectionName); @Override T findById(String collectionName, String id); @Override T findById(String collectionName, String id, boolean allFields); @Override boolean exists(String collectionName, String id); @Override T findOne(String collectionName, NeutralQuery neutralQuery); @Override T findOne(String collectionName, NeutralQuery neutralQuery, boolean allFields); @Override Iterable<T> findAll(String collectionName, NeutralQuery neutralQuery); @Override Iterable<String> findAllIds(String collectionName, NeutralQuery neutralQuery); @Override long count(String collectionName, NeutralQuery neutralQuery); @Override boolean update(String collection, T object, boolean isSuperdoc); @Override boolean doUpdate(String collection, NeutralQuery query, Update update); @Override CascadeResult safeDelete(String entityType, String id, boolean cascade, boolean dryrun, boolean forced, boolean logViolations,
Integer maxObjects, AccessibilityCheck access); @Override boolean delete(String collectionName, String id); @Override void deleteAll(String collectionName, NeutralQuery query); @Override DBCollection getCollection(String collectionName); @Override List<DBCollection> getCollections(boolean includeSystemCollections); @Override @Deprecated Iterable<T> findByQuery(String collectionName, Query query, int skip, int max); @Override boolean collectionExists(String collection); @Override void setWriteConcern(String writeConcern); @Override void setReferenceCheck(String referenceCheck); @Override long count(String collectionName, Query query); @Override boolean updateWithRetries(String collection, T object, int noOfRetries); @Override boolean patch(String type, String collectionName, String id, Map<String, Object> newValues); @Override T findAndUpdate(String collectionName, NeutralQuery neutralQuery, Update update); @Override Iterator<T> findEach(String collectionName, NeutralQuery query); @Override Iterator<T> findEach(String collectionName, Query query); @Override CascadeResult safeDelete(Entity entity, String id, boolean cascade, boolean dryrun, boolean force, boolean logViolations,
Integer maxObjects, AccessibilityCheck access); }
|
@Test public void testPagingBreakup() { List<List<String>> brokenIds = delegate.extractBrokenListOfIds(generateIds(count)); assertEquals(brokenIds.size(), 1); brokenIds = delegate.extractBrokenListOfIds(generateIds(count + 1)); assertEquals(brokenIds.size(), 2); assertEquals(brokenIds.get(1).size(), 1); assertEquals((String) brokenIds.get(1).get(0), "" + count); brokenIds = delegate.extractBrokenListOfIds(generateIds(count - 1)); assertEquals(brokenIds.size(), 1); assertEquals(brokenIds.get(0).size(), count - 1); brokenIds = delegate.extractBrokenListOfIds(generateIds(count / 2)); assertEquals(brokenIds.size(), 1); assertEquals(brokenIds.get(0).size(), count / 2); brokenIds = delegate.extractBrokenListOfIds(generateIds(count * 3 + count / 2)); assertEquals(brokenIds.size(), 4); assertEquals(brokenIds.get(3).size(), count / 2); }
|
SecurityEventBuilder { public SecurityEvent createSecurityEvent(String loggingClass, URI requestUri, String slMessage, boolean defaultTargetToUserEdOrg) { return createSecurityEvent( loggingClass, requestUri, slMessage, null, null,null, null, defaultTargetToUserEdOrg); } SecurityEventBuilder(); SecurityEvent createSecurityEvent(String loggingClass, URI requestUri, String slMessage, boolean defaultTargetToUserEdOrg); SecurityEvent createSecurityEvent(String loggingClass, URI requestUri, String slMessage,
Entity explicitRealmEntity, String entityType, String[] entityIds); SecurityEvent createSecurityEvent(String loggingClass, URI requestUri, String slMessage,
Entity explicitRealmEntity, String entityType, Set<Entity> entities); SecurityEvent createSecurityEvent(String loggingClass, URI explicitUri, String slMessage, SLIPrincipal explicitPrincipal, String clientId, Entity explicitRealmEntity,
Set<String> targetEdOrgs, boolean defaultTargetToUserEdOrg); CallingApplicationInfoProvider getCallingApplicationInfoProvider(); void setCallingApplicationInfoProvider(CallingApplicationInfoProvider callingApplicationInfoProvider); }
|
@Test public void testCreateSecurityEventUsingDefaultTargetToUserEdOrg() { SecurityEvent se = builder.createSecurityEvent(this.getClass().getName(), URI.create(ONE_PART_URI), LOG_MESSAGE, true); Assert.assertTrue(se.getActionUri().equals(ONE_PART_URI)); Assert.assertTrue(se.getLogMessage().equals(LOG_MESSAGE)); Assert.assertTrue(se.getUserEdOrg().equals(REALM_EDORG_STATEID)); Assert.assertTrue(se.getTargetEdOrgList().contains(se.getUserEdOrg())); }
@Test public void testCreateSecurityEventFromEntityIds() { prepareTargetEdOrgMocks(); String[] entityIds = {SECTION_ENTITY_ID, SECTION_ENTITY2_ID}; SecurityEvent se = builder.createSecurityEvent(this.getClass().getName(), URI.create(ONE_PART_URI), LOG_MESSAGE, null, EntityNames.SECTION, entityIds); Assert.assertTrue(se.getActionUri().equals(ONE_PART_URI)); Assert.assertTrue(se.getLogMessage().equals(LOG_MESSAGE)); Assert.assertTrue(se.getUserEdOrg().equals(REALM_EDORG_STATEID)); Assert.assertTrue(containsTheSame(se.getTargetEdOrgList(), Arrays.asList(EDORG_STATEID, EDORG2_STATEID))); }
@Test public void testCreateSecurityFromEventEntities() { prepareTargetEdOrgMocks(); Set<Entity> entities = new HashSet<Entity>(); entities.add(section1); entities.add(section2); SecurityEvent se = builder.createSecurityEvent(this.getClass().getName(), URI.create(ONE_PART_URI), LOG_MESSAGE, null, EntityNames.SECTION, entities); Assert.assertTrue(se.getActionUri().equals(ONE_PART_URI)); Assert.assertTrue(se.getLogMessage().equals(LOG_MESSAGE)); Assert.assertTrue(se.getUserEdOrg().equals(REALM_EDORG_STATEID)); Assert.assertTrue(containsTheSame(se.getTargetEdOrgList(), Arrays.asList(EDORG_STATEID, EDORG2_STATEID))); }
|
ApplicationAuthorizationValidator { @SuppressWarnings("unchecked") public boolean isAuthorizedForApp(Entity app, SLIPrincipal principal) { if (principal.isAdminRealmAuthenticated()) { return isAdminVisible(app); } else { if (isAutoAuthorized(app)) { return true; } else if (!isOperatorApproved(app)) { return false; } else { Set<String> edOrgs = helper.locateDirectEdorgs(principal.getEntity()); NeutralQuery appAuthCollQuery = new NeutralQuery(); appAuthCollQuery.addCriteria(new NeutralCriteria("applicationId", "=", app.getEntityId())); appAuthCollQuery.addCriteria(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, edOrgs)); Entity authorizedApps = repo.findOne("applicationAuthorization", appAuthCollQuery); if (authorizedApps != null) { if (isAutoApproved(app)) { return true; } else { List<String> approvedDistricts = new ArrayList<String>((List<String>) app.getBody().get("authorized_ed_orgs")); List<String> myDistricts = helper.getDistricts(edOrgs); approvedDistricts.retainAll(myDistricts); return !approvedDistricts.isEmpty(); } } } } return false; } @SuppressWarnings("unchecked") boolean isAuthorizedForApp(Entity app, SLIPrincipal principal); Set<String> getAuthorizingEdOrgsForApp(String clientId); }
|
@Test public void testStaffUser() throws InterruptedException { SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(staff1); principal.setEdOrg(lea1.getEntityId()); principal.setRealm(leaRealm.getEntityId()); injector.setSecurityContext(principal, false); assertTrue("Can see autoApp", validator.isAuthorizedForApp(autoApp, principal)); assertTrue("Can see approvedApp", validator.isAuthorizedForApp(approvedApp, principal)); assertFalse("Cannot see notOperatorApproved", validator.isAuthorizedForApp(notOperatorApproved, principal)); assertFalse("Cannot see approvedAppWithoutOperator", validator.isAuthorizedForApp(approvedAppWithoutOperator, principal)); assertFalse("Cannot see adminApp", validator.isAuthorizedForApp(adminApp, principal)); assertFalse("Cannot see noAuthApp", validator.isAuthorizedForApp(noAuthApp, principal)); assertFalse("Cannot see nonApprovedApp", validator.isAuthorizedForApp(nonApprovedApp, principal)); assertFalse("Cannot see notAuthorizedApp", validator.isAuthorizedForApp(notAuthorizedApp, principal)); }
@Test public void testAdminUser() throws InterruptedException { SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(null); principal.setEdOrg("SOMETHING"); principal.setRealm(sliRealm.getEntityId()); principal.setAdminRealmAuthenticated(true); injector.setSecurityContext(principal, false); assertFalse("Cannot see autoApp", validator.isAuthorizedForApp(autoApp, principal)); assertFalse("Cannot see approvedApp", validator.isAuthorizedForApp(approvedApp, principal)); assertTrue("Can see adminApp", validator.isAuthorizedForApp(adminApp, principal)); assertFalse("Cannot see notOperatorApproved", validator.isAuthorizedForApp(notOperatorApproved, principal)); assertFalse("Cannot see approvedAppWithoutOperator", validator.isAuthorizedForApp(approvedAppWithoutOperator, principal)); assertFalse("Cannot see noAuthApp", validator.isAuthorizedForApp(noAuthApp, principal)); assertFalse("Cannot see nonApprovedApp", validator.isAuthorizedForApp(nonApprovedApp, principal)); assertFalse("Cannot see notAuthorizedApp", validator.isAuthorizedForApp(notAuthorizedApp, principal)); }
|
TokenGenerator { public static String generateToken(int length) { byte[] verifierBytes = new byte[length]; random.nextBytes(verifierBytes); return getAuthorizationCodeString(verifierBytes); } static String generateToken(int length); }
|
@Test public void testIdGeneratorZeroLength() { String string = TokenGenerator.generateToken(0); assertEquals("", string); }
@Test public void testIdGeneratorLargeLength() { String string = TokenGenerator.generateToken(1000); assertEquals(1000, string.length()); for (int i = 0; i < string.length(); i++) { assertTrue(Character.isDigit(string.charAt(i)) || Character.isLetter(string.charAt(i))); } }
@Test public void testEdgeCharacters() { boolean foundChars = false; for (int i = 0; i < 25; i++) { String token = TokenGenerator.generateToken(10000); foundChars = token.indexOf('a') > -1 && token.indexOf('u') > -1 && token.indexOf('z') > -1 && token.indexOf('w') > -1 && token.indexOf('0') > -1 && token.indexOf('9') > -1; if (foundChars) break; } assertTrue(foundChars); }
|
ApiSchemaAdapter { private Map<String, Map<String, List<MigrationStrategy>>> buildMigrationStrategyMap(Resource migrationConfigResource) { Map<String, Map<String, List<MigrationStrategy>>> migrationStrategyMap = new HashMap<String, Map<String, List<MigrationStrategy>>>(); MigrationConfig config = null; try { config = MigrationConfig.parse(migrationConfigResource.getInputStream()); } catch (IOException e) { LOG.error("Unable to read migration config file", e); return migrationStrategyMap; } Map<String, Map<String, List<Map<Strategy, Map<String, Object>>>>> entityConfig = config.getEntities(); for (Map.Entry<String, Map<String, List<Map<Strategy, Map<String, Object>>>>> entityEntry : entityConfig .entrySet()) { String entityType = entityEntry.getKey(); Map<String, List<Map<Strategy, Map<String, Object>>>> versionUpdates = entityEntry.getValue(); Map<String, List<MigrationStrategy>> migrationsForVersion = new HashMap<String, List<MigrationStrategy>>(); for (Map.Entry<String, List<Map<Strategy, Map<String, Object>>>> versionEntry : versionUpdates.entrySet()) { String versionNumber = versionEntry.getKey(); List<Map<Strategy, Map<String, Object>>> versionStrategies = versionEntry.getValue(); List<MigrationStrategy> strategies = new ArrayList<MigrationStrategy>(); migrationsForVersion.put(versionNumber, strategies); for (Map<Strategy, Map<String, Object>> versionStrategy : versionStrategies) { for (Map.Entry<Strategy, Map<String, Object>> strategy : versionStrategy.entrySet()) { try { MigrationStrategy migrationStrategy = (MigrationStrategy) beanFactory .getBean(strategy.getKey().getBeanName()); migrationStrategy.setParameters(strategy.getValue()); strategies.add(migrationStrategy); } catch (MigrationException e) { LOG.error("Unable to instantiate TransformStrategy: " + strategy, e); } } } } migrationStrategyMap.put(entityType, migrationsForVersion); } return migrationStrategyMap; } @PostConstruct void initMigration(); List<MigrationStrategy> getUpMigrationStrategies(String entityType, String versionNumber); List<MigrationStrategy> getDownMigrationStrategies(String entityType, String versionNumber); List<MigrationStrategy> getEntityTransformMigrationStrategies(String entityType, String versionNumber); Entity migrate(Entity entity, String apiVersion, boolean upConversion); Iterable<Entity> migrate(Iterable<Entity> entities, String apiVersion, boolean upConversion); List<EntityBody> migrate(EntityBody entityBody, String entityType, String versionNumber); List<EntityBody> migrate(List<EntityBody> entityBodies, String entityType, String versionNumber); Resource getUpMigrationConfigResource(); void setUpMigrationConfigResource(Resource upMigrationConfigResource); Resource getDownMigrationConfigResource(); void setDownMigrationConfigResource(Resource downMigrationConfigResource); Resource getEntityTransformConfigResource(); void setEntityTransformConfigResource(Resource entityTransformConfigResource); }
|
@Test public void testBuildMigrationStrategyMap() throws NoSuchFieldException, IllegalAccessException { ApiSchemaAdapter apiSchemaAdapter = initApiSchemaAdapter(); List<MigrationStrategy> downList = apiSchemaAdapter.getDownMigrationStrategies("session", ONE); List<MigrationStrategy> upList = apiSchemaAdapter.getUpMigrationStrategies("session", ONE); assertTrue(downList != null); assertTrue(upList != null); assertTrue(downList.get(0) instanceof AddStrategy); assertTrue((getField(downList.get(0), "fieldName")).equals("downFoo")); assertTrue((getField(downList.get(0), "defaultValue")).equals("downBar")); assertTrue(downList.get(1) instanceof RemoveFieldStrategy); assertTrue(( getField(downList.get(1), "fieldName")).equals("removeDownFoo")); assertTrue(downList.get(2) instanceof RenameFieldStrategy); assertTrue((getField(downList.get(2), "oldFieldName")).equals("oldDownFoo")); assertTrue((getField(downList.get(2), "newFieldName")).equals("newDownFoo")); assertTrue(upList.get(0) instanceof AddStrategy); assertTrue(( getField(upList.get(0), "fieldName")).equals("upFoo")); assertTrue((getField(upList.get(0), "defaultValue")).equals("upBar")); assertTrue(upList.get(1) instanceof RemoveFieldStrategy); assertTrue(( getField(upList.get(1), "fieldName")).equals("removeUpFoo")); assertTrue(upList.get(2) instanceof RenameFieldStrategy); assertTrue((getField(upList.get(2), "oldFieldName")).equals("oldUpFoo")); assertTrue((getField(upList.get(2), "newFieldName")).equals("newUpFoo")); }
|
ApiSchemaAdapter { public Entity migrate(Entity entity, String apiVersion, boolean upConversion) throws MigrationException { if (entity == null) { return null; } String entityType = entity.getType(); List<MigrationStrategy> migrationStrategies = null; if (upConversion) { migrationStrategies = getUpMigrationStrategies(entityType, apiVersion); } else { migrationStrategies = getDownMigrationStrategies(entityType, apiVersion); } Entity migratedEntity = entity; if (migrationStrategies != null) { for (MigrationStrategy migrationStrategy : migrationStrategies) { migratedEntity = (Entity) migrationStrategy.migrate(migratedEntity); } } return migratedEntity; } @PostConstruct void initMigration(); List<MigrationStrategy> getUpMigrationStrategies(String entityType, String versionNumber); List<MigrationStrategy> getDownMigrationStrategies(String entityType, String versionNumber); List<MigrationStrategy> getEntityTransformMigrationStrategies(String entityType, String versionNumber); Entity migrate(Entity entity, String apiVersion, boolean upConversion); Iterable<Entity> migrate(Iterable<Entity> entities, String apiVersion, boolean upConversion); List<EntityBody> migrate(EntityBody entityBody, String entityType, String versionNumber); List<EntityBody> migrate(List<EntityBody> entityBodies, String entityType, String versionNumber); Resource getUpMigrationConfigResource(); void setUpMigrationConfigResource(Resource upMigrationConfigResource); Resource getDownMigrationConfigResource(); void setDownMigrationConfigResource(Resource downMigrationConfigResource); Resource getEntityTransformConfigResource(); void setEntityTransformConfigResource(Resource entityTransformConfigResource); }
|
@Test public void testMigrate() { ApiSchemaAdapter apiSchemaAdapter = initApiSchemaAdapter(); EntityBody downBody = new EntityBody(); downBody.put("removeDownFoo", "removeDownBar"); downBody.put("oldDownFoo", "oldDownBar"); Entity downEntity = new MongoEntity("session", downBody); EntityBody upBody = new EntityBody(); upBody.put("removeUpFoo", "removeUpBar"); upBody.put("oldUpFoo", "oldUpBar"); Entity upEntity = new MongoEntity("session", upBody); Entity newDownEntity = apiSchemaAdapter.migrate(downEntity, ONE, false); Entity newUpEntity = apiSchemaAdapter.migrate(upEntity, ONE, true); assertTrue(newDownEntity.getBody().containsKey("downFoo")); assertTrue(newDownEntity.getBody().get("downFoo").equals("downBar")); assertTrue(!newDownEntity.getBody().containsKey("removeDownFoo")); assertTrue(!newDownEntity.getBody().containsKey("oldDownFoo")); assertTrue(newDownEntity.getBody().containsKey("newDownFoo")); assertTrue(newDownEntity.getBody().get("newDownFoo").equals("oldDownBar")); assertTrue(newUpEntity.getBody().containsKey("upFoo")); assertTrue(newUpEntity.getBody().get("upFoo").equals("upBar")); assertTrue(!newUpEntity.getBody().containsKey("removeUpFoo")); assertTrue(!newUpEntity.getBody().containsKey("oldUpFoo")); assertTrue(newUpEntity.getBody().containsKey("newUpFoo")); assertTrue(newUpEntity.getBody().get("newUpFoo").equals("oldUpBar")); }
@Test public void testMigrateIterable() { EntityBody downBody = new EntityBody(); downBody.put("removeDownFoo", "removeDownBar"); downBody.put("oldDownFoo", "oldDownBar"); Entity downSessionEntity = new MongoEntity("session", downBody); Entity downStudentEntity = new MongoEntity("student", null); EntityBody upBody = new EntityBody(); upBody.put("removeUpFoo", "removeUpBar"); upBody.put("oldUpFoo", "oldUpBar"); Entity upSessionEntity = new MongoEntity("session", upBody); Entity upStudentEntity = new MongoEntity("student", null); ArrayList<Entity> oldDownEntityList = new ArrayList<Entity>(); oldDownEntityList.add(downSessionEntity); oldDownEntityList.add(downStudentEntity); ArrayList<Entity> oldUpEntityList = new ArrayList<Entity>(); oldUpEntityList.add(upSessionEntity); oldUpEntityList.add(upStudentEntity); Iterator<Entity> newDownEntityList = apiSchemaAdapter.migrate(oldDownEntityList, ONE, false).iterator(); Entity currDownEntity = newDownEntityList.next(); assertTrue(currDownEntity.getBody().containsKey("downFoo")); assertTrue(currDownEntity.getBody().get("downFoo").equals("downBar")); assertTrue(!currDownEntity.getBody().containsKey("removeDownFoo")); assertTrue(!currDownEntity.getBody().containsKey("oldDownFoo")); assertTrue(currDownEntity.getBody().containsKey("newDownFoo")); assertTrue(currDownEntity.getBody().get("newDownFoo").equals("oldDownBar")); assertTrue(newDownEntityList.next() != null); assertTrue(!newDownEntityList.hasNext()); Iterator<Entity> newUpEntityList = apiSchemaAdapter.migrate(oldUpEntityList, ONE, true).iterator(); Entity firstUpEntity = newUpEntityList.next(); assertTrue(firstUpEntity.getBody().containsKey("upFoo")); assertTrue(firstUpEntity.getBody().get("upFoo").equals("upBar")); assertTrue(!firstUpEntity.getBody().containsKey("removeUpFoo")); assertTrue(!firstUpEntity.getBody().containsKey("oldUpFoo")); assertTrue(firstUpEntity.getBody().containsKey("newUpFoo")); assertTrue(firstUpEntity.getBody().get("newUpFoo").equals("oldUpBar")); assertTrue(newUpEntityList.next() != null); assertTrue(!newUpEntityList.hasNext()); }
|
EntityDefinition { public void setSchema(NeutralSchema neutralSchema) { this.schema = neutralSchema; this.referenceFields = new LinkedHashMap<String, ReferenceSchema>(); if (this.schema != null) { addRefs("", neutralSchema); } } protected EntityDefinition(String type, String resourceName, String collectionName, EntityService service,
boolean supportsAggregates); protected EntityDefinition(String type, String dbType, String resourceName, String collectionName, EntityService service,
boolean supportsAggregates, boolean skipContextValidation, boolean pullTypeFromEntity, NeutralCriteria typeCriteria,
boolean supportsPut, boolean supportsPatch); boolean hasArrayField(String fieldName); NeutralSchema getSchema(); void setSchema(NeutralSchema neutralSchema); Iterable<String> getReferenceFieldNames(String resource); final Map<String, ReferenceSchema> getReferenceFields(); final void addReferencingEntity(EntityDefinition entityDefinition); final Collection<EntityDefinition> getReferencingEntities(); String getStoredCollectionName(); String getType(); String getResourceName(); EntityService getService(); boolean isOfType(String id); boolean isRestrictedForLogging(); static void setDefaultRepo(Repository<Entity> defaultRepo); static Repository<Entity> getDefaultRepo(); boolean supportsAggregates(); boolean skipContextValidation(); boolean wrapperEntity(); String getDbType(); NeutralCriteria getTypeCriteria(); boolean supportsPut(); boolean supportsPatch(); }
|
@Test public void testSetSchema() { NeutralSchema mockSchema = new ComplexSchema(); populate(mockSchema); entityDefinition.setSchema(mockSchema); Map<String, ReferenceSchema> referenceFields = entityDefinition.getReferenceFields(); assertEquals("Expected map with two entries", 3, referenceFields.size()); ReferenceSchema stringSchema = referenceFields.get("StringSchema1"); assertNull("Expected null schema", stringSchema); ReferenceSchema referenceSchema = referenceFields.get("ReferenceSchema1"); assertNotNull("Expected non-null schema", referenceSchema); assertEquals("Expected different reference type", referenceSchema.getType(), "straightReferenceTest"); ReferenceSchema listSchema = referenceFields.get("ListSchema1"); assertNotNull("Expected non-null schema", listSchema); assertEquals("Expected different reference type", listSchema.getType(), "listReferenceTest"); assertTrue(entityDefinition.hasArrayField("ListSchema1")); assertFalse(entityDefinition.hasArrayField("StringSchema1")); assertFalse(entityDefinition.hasArrayField("Foo")); }
|
SessionCache { public void put(String token, OAuth2Authentication auth) { if (auth != null) { this.sessions.put(new Element(token, auth)); replicate(token, auth); } else { LOG.warn("Attempting to cache null session!"); } } void put(String token, OAuth2Authentication auth); OAuth2Authentication get(String token); void remove(String token); void clear(); }
|
@Test public void testPut() { Authentication userAuthentication = new PreAuthenticatedAuthenticationToken(new SLIPrincipal("1234"), "auth", Arrays.asList(Right.FULL_ACCESS)); sessions.put(TOKEN, new OAuth2Authentication(new ClientToken("the", "ordinary", Collections.singleton("man")), userAuthentication)); Assert.assertNotNull(sessions.get(TOKEN)); }
|
SessionCache { public void remove(String token) { this.sessions.remove(token); try { ObjectMessage msg = createMessage(token, null, REMOVE); tp.send(msg); } catch (JMSException e) { LOG.error("Failed to replicate session cache entry", e); } } void put(String token, OAuth2Authentication auth); OAuth2Authentication get(String token); void remove(String token); void clear(); }
|
@Test @Ignore public void testRemove() { Authentication userAuthentication = new PreAuthenticatedAuthenticationToken(new SLIPrincipal("1234"), "auth", Arrays.asList(Right.FULL_ACCESS)); sessions.put(TOKEN2, new OAuth2Authentication(new ClientToken("the", "ordinary", Collections.singleton("man")), userAuthentication)); Assert.assertNotNull(sessions.get(TOKEN2)); sessions.remove(TOKEN2); Assert.assertNull(sessions.get(TOKEN2)); }
|
DefaultSelectorDocument implements SelectorDocument { @Override public List<EntityBody> aggregate(SelectorQuery selectorQuery, final NeutralQuery constraint) { return executeQueryPlan(selectorQuery, constraint, new ArrayList<EntityBody>(), new Stack<Type>(), true, new MyCounter()); } @Override List<EntityBody> aggregate(SelectorQuery selectorQuery, final NeutralQuery constraint); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); static final int EMBEDDED_DOCUMENT_LIMIT; }
|
@Test public void testComplexSelectorQueryPlan() { List<String> ids = new ArrayList<String>(); ids.add(student1.getEntityId()); ids.add(student2.getEntityId()); NeutralQuery constraint = new NeutralQuery(); constraint.addCriteria(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, ids)); List<EntityBody> results = defaultSelectorDocument.aggregate(createQueryPlan("Student", getSelectorQueryPlan()), constraint); assertNotNull("Should not be null", results); assertEquals("Should match", 2, results.size()); EntityBody student = results.get(0); String studentId = (String) student.get("id"); assertTrue("Should be true", student.containsKey("studentSectionAssociations")); assertTrue("Should be true", student.containsKey("name")); assertEquals("Should match", 4, student.keySet().size()); @SuppressWarnings("unchecked") List<EntityBody> studentSectionAssociationList = (List<EntityBody>) student.get("studentSectionAssociations"); assertEquals("Should match", 2, studentSectionAssociationList.size()); EntityBody studentSectionAssociation = studentSectionAssociationList.get(0); String sectionId = (String) studentSectionAssociation.get("sectionId"); assertEquals("Should match", studentId, studentSectionAssociation.get("studentId")); assertTrue("Should be true", studentSectionAssociation.containsKey("sections")); assertTrue("Should be true", studentSectionAssociation.containsKey("sectionId")); assertEquals("Should match", 5, studentSectionAssociation.keySet().size()); @SuppressWarnings("unchecked") List<EntityBody> sectionList = (List<EntityBody>) studentSectionAssociation.get("sections"); assertEquals("Should match", 1, sectionList.size()); EntityBody section = sectionList.get(0); assertEquals("Should match", sectionId, section.get("id")); assertTrue("Should be true", section.containsKey("sectionName")); assertEquals("Should match", 3, section.keySet().size()); }
@Test public void testDirectReferenceQueryPlan() { List<String> ids = new ArrayList<String>(); ids.add(section1.getEntityId()); ids.add(section2.getEntityId()); NeutralQuery constraint = new NeutralQuery(); constraint.addCriteria(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, ids)); List<EntityBody> results = defaultSelectorDocument.aggregate(createQueryPlan("Section", getDirectRefQueryPlan()), constraint); assertNotNull("Should not be null", results); assertEquals("Should match", 2, results.size()); EntityBody section = results.get(0); assertTrue("Should be true", section.containsKey("sessions")); @SuppressWarnings("unchecked") List<EntityBody> sessionList = (List<EntityBody>) section.get("sessions"); assertEquals("Should match", 1, sessionList.size()); EntityBody session = sessionList.get(0); assertTrue("Should be true", session.containsKey("sessionName")); }
@Test public void testIncludeXSDSelector() { List<String> ids = new ArrayList<String>(); ids.add(student1.getEntityId()); NeutralQuery constraint = new NeutralQuery(); constraint.addCriteria(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, ids)); List<EntityBody> results = defaultSelectorDocument.aggregate(createQueryPlan("Student", getIncludeXSDPlan()), constraint); assertNotNull("Should not be null", results); assertEquals("Should match", 1, results.size()); EntityBody body = results.get(0); assertEquals("Should match", 3, body.keySet().size()); assertTrue("Should be true", body.containsKey("name")); }
@Test public void testEmptySelector() { List<String> ids = new ArrayList<String>(); ids.add(student1.getEntityId()); NeutralQuery constraint = new NeutralQuery(); constraint.addCriteria(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, ids)); List<EntityBody> results = defaultSelectorDocument.aggregate(createQueryPlan("Student", getEmptyPlan()), constraint); assertNotNull("Should not be null", results); assertNotNull("Should not be null", results); assertEquals("Should match", 1, results.size()); EntityBody body = results.get(0); assertEquals("Should match", 2, body.keySet().size()); }
|
DefaultSelectorDocument implements SelectorDocument { protected List<EntityBody> filterFields(List<EntityBody> results, SelectorQueryPlan plan) { List<EntityBody> filteredList = filterIncludeFields(results, plan); filteredList = filterExcludeFields(filteredList, plan); return filteredList; } @Override List<EntityBody> aggregate(SelectorQuery selectorQuery, final NeutralQuery constraint); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); static final int EMBEDDED_DOCUMENT_LIMIT; }
|
@Test public void testFilterFields() { SelectorQueryPlan plan = new SelectorQueryPlan(); List<EntityBody> results = createResults(); plan.getIncludeFields().add("field1"); List<EntityBody> out = defaultSelectorDocument.filterFields(results, plan); assertEquals("Should match", 1, out.size()); EntityBody body = out.get(0); assertTrue("Should be true", body.containsKey("field1")); assertFalse("Should be false", body.containsKey("field2")); assertFalse("Should be false", body.containsKey("field3")); plan.getIncludeFields().clear(); plan.getIncludeFields().add("field1"); plan.getIncludeFields().add("field2"); out = defaultSelectorDocument.filterFields(results, plan); assertEquals("Should match", 1, out.size()); body = out.get(0); assertTrue("Should be true", body.containsKey("field1")); assertTrue("Should be true", body.containsKey("field2")); assertFalse("Should be false", body.containsKey("field3")); plan.getIncludeFields().clear(); plan.getExcludeFields().add("field1"); out = defaultSelectorDocument.filterFields(results, plan); assertEquals("Should match", 1, out.size()); body = out.get(0); assertFalse("Should be false", body.containsKey("field1")); assertFalse("Should be false", body.containsKey("field2")); assertFalse("Should be false", body.containsKey("field3")); plan.getIncludeFields().clear(); plan.getExcludeFields().clear(); plan.getExcludeFields().add("field1"); plan.getIncludeFields().add("field1"); out = defaultSelectorDocument.filterFields(results, plan); assertEquals("Should match", 1, out.size()); body = out.get(0); assertFalse("Should be false", body.containsKey("field1")); assertFalse("Should be false", body.containsKey("field2")); assertFalse("Should be false", body.containsKey("field3")); plan.getIncludeFields().clear(); plan.getExcludeFields().clear(); out = defaultSelectorDocument.filterFields(results, plan); assertEquals("Should match", 1, out.size()); body = out.get(0); assertFalse("Should be false", body.containsKey("field1")); assertFalse("Should be false", body.containsKey("field2")); assertFalse("Should be false", body.containsKey("field3")); }
|
DefaultSelectorDocument implements SelectorDocument { protected List<EntityBody> getEmbeddedEntities(List<EntityBody> previousEntities, Type currentType) { List<EntityBody> embeddedBodyList = new ArrayList<EntityBody>(); String currType = StringUtils.lowercaseFirstLetter(currentType.getName()); for (EntityBody body : previousEntities) { if (body.containsKey(currType)) { embeddedBodyList.addAll((Collection<? extends EntityBody>) body.get(currType)); } } return embeddedBodyList; } @Override List<EntityBody> aggregate(SelectorQuery selectorQuery, final NeutralQuery constraint); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); static final int EMBEDDED_DOCUMENT_LIMIT; }
|
@Test public void testGetEmbeddedEntities() { ClassType classType = mock(ClassType.class); when(classType.getName()).thenReturn("StudentSectionAssociation"); List<EntityBody> embeddedEntities = defaultSelectorDocument.getEmbeddedEntities(createEmbeddedEntity(), classType); assertEquals(embeddedEntities.size(), 1); }
|
DefaultSelectorDocument implements SelectorDocument { protected void addChildTypesToQuery(Type currentType, SelectorQueryPlan selectorQueryPlan, NeutralQuery neutralQuery) { List<Object> childQueries = selectorQueryPlan.getChildQueryPlans(); List<String> embeddedFields = new ArrayList<String>(); for (Object plan : childQueries) { SelectorQuery query = (SelectorQuery) plan; for (Type key : query.keySet()) { String childType = StringUtils.uncapitalise(key.getName()); if (currentType.getName().equalsIgnoreCase(EmbeddedDocumentRelations.getParentEntityType(childType))) { embeddedFields.add(childType); } } } neutralQuery.setEmbeddedFields(embeddedFields); } @Override List<EntityBody> aggregate(SelectorQuery selectorQuery, final NeutralQuery constraint); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); static final int EMBEDDED_DOCUMENT_LIMIT; }
|
@Test public void testAddChildTypesToQuery() { ClassType parentType = mock(ClassType.class); when(parentType.getName()).thenReturn("Section"); ClassType childType = mock(ClassType.class); when(childType.getName()).thenReturn("StudentSectionAssociation"); ClassType nonChildType = mock(ClassType.class); when(nonChildType.getName()).thenReturn("StudentParentAssociation"); SelectorQuery childQuery = new SelectorQuery(); childQuery.put(childType, new SelectorQueryPlan()); List<Object> childQueryPlans = new ArrayList<Object>(); childQueryPlans.add(childQuery); SelectorQueryPlan plan = new SelectorQueryPlan(); plan.setChildQueryPlans(childQueryPlans); NeutralQuery query = new NeutralQuery(); defaultSelectorDocument.addChildTypesToQuery(parentType, plan, query); assertEquals("Should match", 1, query.getEmbeddedFields().size()); assertEquals("Should match", "studentSectionAssociation", query.getEmbeddedFields().get(0)); query = new NeutralQuery(); defaultSelectorDocument.addChildTypesToQuery(parentType, new SelectorQueryPlan(), query); assertEquals("Should match", 0, query.getEmbeddedFields().size()); childQuery = new SelectorQuery(); childQuery.put(nonChildType, new SelectorQueryPlan()); childQueryPlans = new ArrayList<Object>(); childQueryPlans.add(childQuery); plan = new SelectorQueryPlan(); plan.setChildQueryPlans(childQueryPlans); query = new NeutralQuery(); defaultSelectorDocument.addChildTypesToQuery(parentType, new SelectorQueryPlan(), query); assertEquals("Should match", 0, query.getEmbeddedFields().size()); }
|
DefaultSelectorQueryEngine implements SelectorQueryEngine, SelectorQueryVisitor { @Override public SelectorQuery assembleQueryPlan(SemanticSelector semanticSelector) { return buildQueryPlan(semanticSelector); } @Override SelectorQuery assembleQueryPlan(SemanticSelector semanticSelector); @Override SelectorQueryPlan visit(SelectorQueryVisitable visitable); SelectorQueryPlan visit(SemanticSelector semanticSelector); SelectorQueryPlan visit(BooleanSelectorElement booleanSelectorElement); SelectorQueryPlan visit(ComplexSelectorElement complexSelectorElement); SelectorQueryPlan visit(IncludeAllSelectorElement includeAllSelectorElement); SelectorQueryPlan visit(IncludeXSDSelectorElement includeXSDSelectorElement); SelectorQueryPlan visit(IncludeDefaultSelectorElement includeDefaultSelectorElement); SelectorQueryPlan visit(EmptySelectorElement emptySelectorElement); }
|
@Test public void testComplexSelector() { SemanticSelector selectorsWithType = generateSelectorObjectMap(); ClassType studentType = provider.getClassType("Student"); Map<Type, SelectorQueryPlan> queryPlan = defaultSelectorQueryEngine.assembleQueryPlan(selectorsWithType); assertNotNull("Should not be null", queryPlan); SelectorQueryPlan plan = queryPlan.get(studentType); assertNotNull("Should not be null", plan); assertNotNull("Should not be null", plan.getQuery()); assertEquals("Should match", 2, plan.getChildQueryPlans().size()); assertEquals("Should match", 2, plan.getIncludeFields().size()); }
@Test public void testIncludeAllSelector() { SemanticSelector selectorsWithType = generateIncludeAllSelectorObjectMap(); ClassType studentType = provider.getClassType("Student"); Map<Type, SelectorQueryPlan> queryPlan = defaultSelectorQueryEngine.assembleQueryPlan(selectorsWithType); assertNotNull("Should not be null", queryPlan); SelectorQueryPlan plan = queryPlan.get(studentType); assertNotNull("Should not be null", plan); assertNotNull("Should not be null", plan.getQuery()); assertFalse("Should be false", plan.getIncludeFields().isEmpty()); assertFalse("Should be false", plan.getChildQueryPlans().isEmpty()); assertTrue("Should be true", plan.getExcludeFields().isEmpty()); }
@Test public void testExcludeSelector() { SemanticSelector selectorsWithType = generateExcludeSelectorObjectMap(); ClassType studentType = provider.getClassType("Student"); Map<Type, SelectorQueryPlan> queryPlan = defaultSelectorQueryEngine.assembleQueryPlan(selectorsWithType); assertNotNull("Should not be null", queryPlan); SelectorQueryPlan plan = queryPlan.get(studentType); assertNotNull("Should not be null", plan); assertNotNull("Should not be null", plan.getQuery()); assertFalse("Should be false", plan.getIncludeFields().isEmpty()); assertFalse("Should be false", plan.getExcludeFields().isEmpty()); assertFalse("Should be false", plan.getChildQueryPlans().isEmpty()); }
@Test public void testAssociationSelector() { SemanticSelector selectorsWithType = generateAssociationSelectorMap(); ClassType studentType = provider.getClassType("Student"); Map<Type, SelectorQueryPlan> queryPlan = defaultSelectorQueryEngine.assembleQueryPlan(selectorsWithType); assertNotNull("Should not be null", queryPlan); SelectorQueryPlan plan = queryPlan.get(studentType); assertNotNull("Should not be null", plan); assertNotNull("Should not be null", plan.getQuery()); assertEquals("Should match", 1, plan.getChildQueryPlans().size()); }
@Test public void testSkipAssociation() { final SemanticSelector selector = generateSkipAssociationSelectorMap(); final ClassType studentType = provider.getClassType("Student"); final ClassType sectionType = provider.getClassType("Section"); final Map<Type, SelectorQueryPlan> queryPlan = defaultSelectorQueryEngine.assembleQueryPlan(selector); assertNotNull(queryPlan); final SelectorQueryPlan plan = queryPlan.get(studentType); final List<Object> childPlans = plan.getChildQueryPlans(); assertEquals(1, childPlans.size()); @SuppressWarnings("unchecked") final Map<Type, SelectorQueryPlan> studentSectionPlanMap = (Map<Type, SelectorQueryPlan>) childPlans.get(0); assertNotNull(studentSectionPlanMap); final SelectorQueryPlan studentSectionPlan = studentSectionPlanMap.get(sectionType); assertNotNull(studentSectionPlan); }
@Test public void testDefaultSelector() { final ClassType studentType = provider.getClassType("Student"); final ClassType studentSectionAssociationType = provider.getClassType("StudentSectionAssociation"); final SemanticSelector selector = generateDefaultSelectorMap(); final Map<Type, SelectorQueryPlan> queryPlan = defaultSelectorQueryEngine.assembleQueryPlan(selector); assertNotNull(queryPlan); SelectorQueryPlan plan = queryPlan.get(studentType); assertFalse("Should be false", plan.getIncludeFields().isEmpty()); assertTrue("Should be true", plan.getExcludeFields().isEmpty()); assertFalse("Should be false", plan.getChildQueryPlans().isEmpty()); SelectorQuery childQuery = (SelectorQuery) plan.getChildQueryPlans().get(0); SelectorQueryPlan childPlan = childQuery.get(studentSectionAssociationType); assertNotNull("Should not be null", childPlan.getQuery()); }
@Test public void testXSDSelector() { final ClassType studentType = provider.getClassType("Student"); final SemanticSelector selector = generateXSDSelectorMap(); final Map<Type, SelectorQueryPlan> queryPlan = defaultSelectorQueryEngine.assembleQueryPlan(selector); assertNotNull(queryPlan); SelectorQueryPlan plan = queryPlan.get(studentType); assertFalse("should be false", plan.getIncludeFields().isEmpty()); assertTrue("should be true", plan.getExcludeFields().isEmpty()); assertTrue("should be true", plan.getChildQueryPlans().isEmpty()); }
@Test public void testEmptySelector() { final ClassType studentType = provider.getClassType("Student"); final SemanticSelector selector = generateEmptySelectorMap(); final Map<Type, SelectorQueryPlan> queryPlan = defaultSelectorQueryEngine.assembleQueryPlan(selector); assertNotNull(queryPlan); SelectorQueryPlan plan = queryPlan.get(studentType); assertTrue("should be true", plan.getIncludeFields().isEmpty()); assertTrue("should be true", plan.getExcludeFields().isEmpty()); assertTrue("should be true", plan.getChildQueryPlans().isEmpty()); assertNotNull("Should not be null", plan.getQuery()); }
|
DefaultSelectorSemanticModel implements SelectorSemanticModel { public SemanticSelector parse(final Map<String, Object> selectors, final ClassType type) throws SelectorParseException { if (type == null) { throw new IllegalArgumentException("type"); } if (selectors == null) { throw new IllegalArgumentException("selectors"); } final SemanticSelector selector = new SemanticSelector(); if (selectors.isEmpty()) { selector.addSelector(type, new EmptySelectorElement(type)); } for (final Map.Entry<String, Object> entry : selectors.entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue(); addEntryToSelector(type, selector, key, value); } return selector; } SemanticSelector parse(final Map<String, Object> selectors, final ClassType type); }
|
@Test public void testSemanticParser() throws SelectorParseException { final ClassType student = provider.getClassType("Student"); final SemanticSelector selector; final ClassType section = provider.getClassType("Section"); final ClassType studentSectionAssociation = provider.getClassType("StudentSectionAssociation"); final Attribute name = provider.getAttributeType(student, "name"); final Attribute economicDisadvantaged = provider.getAttributeType(student, "economicDisadvantaged"); final ClassType studentSchoolAssociation = provider.getClassType("StudentSchoolAssociation"); final Attribute entryDate = provider.getAttributeType(studentSchoolAssociation, "entryDate"); selector = defaultSelectorSemanticModel.parse(generateSelectorObjectMap(), student); assertTrue("Should contain base type", selector.containsKey(student)); assertNotNull("Should have a list of attributes", selector.get(student)); assertEquals("Base type should have 1 selector", 1, selector.size()); final List<SelectorElement> studentList = selector.get(student); assertEquals(5, studentList.size()); assertTrue(!studentList.contains(null)); final Map<ModelElement, Object> selectorMap = mapify(studentList); assertTrue(selectorMap.containsKey(section)); assertTrue(selectorMap.containsKey(studentSectionAssociation)); assertTrue(selectorMap.containsKey(name)); assertTrue(selectorMap.containsKey(economicDisadvantaged)); assertTrue(selectorMap.containsKey(studentSchoolAssociation)); @SuppressWarnings("unchecked") final SemanticSelector sectionSelector = (SemanticSelector) selectorMap.get(section); final List<SelectorElement> sectionSelectorElements = (List<SelectorElement>) sectionSelector.get(section); assertEquals(1, sectionSelectorElements.size()); assertTrue(sectionSelectorElements.get(0) instanceof IncludeAllSelectorElement); assertEquals(true, selectorMap.get(studentSectionAssociation)); assertTrue(selectorMap.get(name) instanceof SemanticSelector); assertTrue(selectorMap.get(studentSchoolAssociation) instanceof SemanticSelector); final SemanticSelector studentSchoolSelector = (SemanticSelector) selectorMap.get(studentSchoolAssociation); final Map<ModelElement, Object> studentSchoolSelectorMap = mapify(studentSchoolSelector.get(studentSchoolAssociation)); assertEquals(true, studentSchoolSelectorMap.get(entryDate)); }
@Test public void testIncludeAll() { final Map<String, Object> selector = new HashMap<String, Object>(); final Map<String, Object> sectionAssocs = new HashMap<String, Object>(); sectionAssocs.put("*", true); sectionAssocs.put("beginDate", false); selector.put("studentSectionAssociations", sectionAssocs); final ClassType student = provider.getClassType("Student"); final SemanticSelector semanticSelector = defaultSelectorSemanticModel.parse(selector, student); }
@Test(expected = SelectorParseException.class) public void testInvalidSelectors() throws SelectorParseException { final ClassType student = provider.getClassType("Student"); final SemanticSelector selector = defaultSelectorSemanticModel.parse(generateFaultySelectorObjectMap(), student); }
@Test public void testDefaultXSD() { final Map<String, Object> studentAttrs = new HashMap<String, Object>(); studentAttrs.put("$", true); final ClassType student = provider.getClassType("Student"); final SemanticSelector semanticSelector = defaultSelectorSemanticModel.parse(studentAttrs, student); final List<SelectorElement> elementList = semanticSelector.get(student); assertEquals(1, elementList.size()); assertTrue(elementList.get(0) instanceof IncludeXSDSelectorElement); }
@Test public void testDefault() { final Map<String, Object> studentAttrs = new HashMap<String, Object>(); studentAttrs.put(".", true); final ClassType student = provider.getClassType("Student"); final SemanticSelector semanticSelector = defaultSelectorSemanticModel.parse(studentAttrs, student); final List<SelectorElement> elementList = semanticSelector.get(student); assertEquals(1, elementList.size()); assertTrue(elementList.get(0) instanceof IncludeDefaultSelectorElement); final Map<String, Object> embedded = new HashMap<String, Object>(); final Map<String, Object> sectionAttrs = new HashMap<String, Object>(); sectionAttrs.put(".", true); embedded.put("sections", sectionAttrs); final SemanticSelector embeddedSelector = defaultSelectorSemanticModel.parse(embedded, student); assertEquals(1, embeddedSelector.get(student).size()); final SelectorElement embeddedElement = embeddedSelector.get(student).get(0); assertTrue(embeddedElement instanceof ComplexSelectorElement); assertEquals(1, ((ComplexSelectorElement) embeddedElement).getSelector().size()); }
@Test public void testEmptySelectors() { final Map<String, Object> studentAttrs = new HashMap<String, Object>(); final ClassType student = provider.getClassType("Student"); final SemanticSelector semanticSelector = defaultSelectorSemanticModel.parse(studentAttrs, student); assertEquals(1, semanticSelector.get(student).size()); assertTrue(semanticSelector.get(student).get(0) instanceof EmptySelectorElement); final Map<String, Object> embeddedEmpty = new HashMap<String, Object>(); embeddedEmpty.put("sections", new HashMap<String, Object>()); final SemanticSelector emptySelector = defaultSelectorSemanticModel.parse(embeddedEmpty, student); assertEquals(1, semanticSelector.get(student).size()); final ClassType section = provider.getClassType("Section"); assertEquals(section, emptySelector.get(student).get(0).getLHS()); }
|
SemanticSelector extends HashMap<Type, List<SelectorElement>> implements SelectorQueryVisitable { public void addSelector(final Type type, final SelectorElement se) { if (this.containsKey(type)) { this.get(type).add(se); } else { this.put(type, new ArrayList<SelectorElement>(Arrays.asList(se))); } } void addSelector(final Type type, final SelectorElement se); @Override SelectorQueryPlan accept(SelectorQueryVisitor selectorQueryVisitor); @Override String toString(); }
|
@Test public void testAddSelector() { final Type testType = mock(Type.class); final SelectorElement se = mock(SelectorElement.class); selector.addSelector(testType, se); assertNotNull(selector.get(testType)); assertEquals(1, selector.get(testType).size()); selector.addSelector(testType, mock(BooleanSelectorElement.class)); assertEquals(2, selector.get(testType).size()); }
|
SemanticSelector extends HashMap<Type, List<SelectorElement>> implements SelectorQueryVisitable { @Override public String toString() { final StringBuilder builder = new StringBuilder(); for (final Map.Entry<Type, List<SelectorElement>> item : this.entrySet()) { final List<SelectorElement> elements = item.getValue(); builder.append("["); builder.append(StringUtils.join(elements, ',')); builder.append("]"); } return builder.toString(); } void addSelector(final Type type, final SelectorElement se); @Override SelectorQueryPlan accept(SelectorQueryVisitor selectorQueryVisitor); @Override String toString(); }
|
@Test public void testToString() { assertTrue(selector.toString().isEmpty()); }
|
SemanticSelector extends HashMap<Type, List<SelectorElement>> implements SelectorQueryVisitable { @Override public SelectorQueryPlan accept(SelectorQueryVisitor selectorQueryVisitor) { return selectorQueryVisitor.visit(this); } void addSelector(final Type type, final SelectorElement se); @Override SelectorQueryPlan accept(SelectorQueryVisitor selectorQueryVisitor); @Override String toString(); }
|
@Test public void testVisitor() { final SelectorQueryVisitor visitor = mock(SelectorQueryVisitor.class); selector.accept(visitor); verify(visitor).visit(selector); }
|
DefaultSelectorStore implements SelectorRepository { @Override public SemanticSelector getSelector(String type) { return defaultSelectors.containsKey(type) ? defaultSelectors.get(type) : getFallBackSelector(type); } @Override SemanticSelector getSelector(String type); static final String DEFAULT_SELECTOR_TYPE_KEY; static final String DEFAULT_SELECTOR_VALUE_KEY; static final String DEFAULT_SELECTOR_RESOURCE_FILENAME; static final Map<String, Object> FALLBACK_SELECTOR; }
|
@Test public void testSuccessfulLoadOfData() { final ClassType studentType = provider.getClassType("Student"); final ClassType studentSectionAssociationType = provider.getClassType("StudentSectionAssociation"); final ClassType sectionType = provider.getClassType("Section"); SemanticSelector sectionSelector = defaultSelectorRepository.getSelector("Section"); assertNotNull("Should not be null", sectionSelector); List<SelectorElement> elements = sectionSelector.get(sectionType); SelectorElement element = elements.get(0); assertTrue("Should be true", element instanceof BooleanSelectorElement); assertEquals("Should match", "sequenceOfCourse", element.getElementName()); SemanticSelector studentSelector = defaultSelectorRepository.getSelector("Student"); assertNotNull("Should not be null", studentSelector); elements = studentSelector.get(studentType); for (SelectorElement e : elements) { if (e instanceof IncludeXSDSelectorElement) { assertEquals("Should match", studentType, e.getLHS()); } else if (e instanceof BooleanSelectorElement) { assertEquals("Should match", studentSectionAssociationType, e.getLHS()); } else { fail("unknown type"); } } SemanticSelector studentSectionAssociationSelector = defaultSelectorRepository.getSelector("StudentSectionAssociation"); assertNotNull("Should not be null", studentSectionAssociationSelector); elements = studentSectionAssociationSelector.get(studentSectionAssociationType); element = elements.get(0); assertTrue("Should be true", element instanceof IncludeXSDSelectorElement); }
@Test public void assertGracefulHandlingOfInvalidTypeDefaultSelector() { assertNull("Should be null", defaultSelectorRepository.getSelector("type1")); }
@Test public void assertGracefulHandlingOfMissingDefaultSelector() { final ClassType schoolType = provider.getClassType("School"); SemanticSelector schoolSelector = defaultSelectorRepository.getSelector("School"); assertNotNull("Should not be null", schoolSelector); List<SelectorElement> elements = schoolSelector.get(schoolType); assertEquals("Should match", 1, elements.size()); SelectorElement element = elements.get(0); assertTrue("Should be true", element instanceof IncludeXSDSelectorElement); }
|
DefaultLogicalEntity implements LogicalEntity { @Override public List<EntityBody> getEntities(final ApiQuery apiQuery, final String resourceName) { if (apiQuery == null) { throw new IllegalArgumentException("apiQuery"); } if (apiQuery.getSelector() == null) { throw new UnsupportedSelectorException("No selector to parse"); } final EntityDefinition typeDef = resourceHelper.getEntityDefinition(resourceName); final ClassType entityType = provider.getClassType(StringUtils.capitalize(typeDef.getType())); if (UNSUPPORTED_RESOURCE_LIST.contains(resourceName)) { throw new UnsupportedSelectorException("Selector is not supported yet for this resource"); } final SemanticSelector semanticSelector = selectorSemanticModel.parse(apiQuery.getSelector(), entityType); final SelectorQuery selectorQuery = selectorQueryEngine.assembleQueryPlan(semanticSelector); return selectorDocument.aggregate(selectorQuery, apiQuery); } @Override List<EntityBody> getEntities(final ApiQuery apiQuery, final String resourceName); }
|
@Test public void testCreateEntities() { final EntityDefinition mockEntityDefinition = mock(EntityDefinition.class); when(mockEntityDefinition.getType()).thenReturn("TEST"); when(resourceHelper.getEntityDefinition(anyString())).thenReturn(mockEntityDefinition); @SuppressWarnings("unchecked") final SelectorQuery mockPlan = mock(SelectorQuery.class); when(selectorQueryEngine.assembleQueryPlan(any(SemanticSelector.class))).thenReturn(mockPlan); final ApiQuery apiQuery = mock(ApiQuery.class); when(apiQuery.getSelector()).thenReturn(new HashMap<String, Object>()); @SuppressWarnings("unchecked") final List<EntityBody> mockEntityList = mock(List.class); when(selectorDocument.aggregate(mockPlan, apiQuery)).thenReturn(mockEntityList); final List<EntityBody> entityList = logicalEntity.getEntities(apiQuery, "TEST"); assertEquals(mockEntityList, entityList); }
|
URITranslator { public void translate(ContainerRequest request) { String uri = request.getPath(); List<PathSegment> segments = request.getPathSegments(); String version = PathConstants.V1; if (!segments.isEmpty()) { version = segments.get(0).getPath(); } for (Map.Entry<String, URITranslation> entry : uriTranslationMap.entrySet()) { String key = entry.getKey(); if (uri.contains(key)) { String newPath = uriTranslationMap.get(key).translate(request.getPath()); if (!newPath.equals(uri)) { request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(newPath).build()); } } } } URITranslator(); void setRepository(PagingRepositoryDelegate<Entity> repository); void translate(ContainerRequest request); URITranslation getTranslator(String uri); }
|
@Test public void testTranslate() throws Exception { List<Entity> learningObjectiveList = new ArrayList<Entity>(); Entity loEntity = mock(Entity.class); Map<String, Object> body = new HashMap<String, Object>(); body.put("parentLearningObjective", "456"); when(loEntity.getEntityId()).thenReturn("123"); when(loEntity.getBody()).thenReturn(body); learningObjectiveList.add(loEntity); when(repository.findAll(anyString(), any(NeutralQuery.class))).thenReturn(learningObjectiveList); String newPath = translator.getTranslator("parentLearningObjective").translate("v1/learningObjectives/123/parentLearningObjectives"); assertTrue("Should match new uri", "learningObjectives/456".equals(newPath)); }
|
EntityBody extends HashMap<String, Object> { public List<String> getValues(String key) { List<String> valueList = new ArrayList<String>(); Object value = this.get(key); if (value instanceof String) { valueList.add((String) value); } else if (value instanceof List<?>) { for (Object subValues : (List<?>) value) { valueList.add(subValues.toString()); } } return valueList; } EntityBody(); EntityBody(Map<? extends String, ? extends Object> m); List<String> getValues(String key); }
|
@Test public void testGetId() { EntityBody entityBody = new EntityBody(createTestMap()); List<String> list1 = entityBody.getValues("key1"); assertNotNull("List should not be null", list1); assertEquals("List should have 1 value", list1.size(), 1); assertEquals("List value should be original id", list1.get(0), "stringValue1"); List<String> list2 = entityBody.getValues("key2"); assertNotNull("List should not be null", list2); assertEquals("List should have 1 value", list2.size(), 1); assertEquals("List value should be original id", list2.get(0), "stringValue2"); List<String> list3 = entityBody.getValues("key3"); assertNotNull("List should not be null", list3); assertEquals("List should have 2 values", list3.size(), 2); assertEquals("List value 1 should be original id", list3.get(0), "stringInList1"); assertEquals("List value 2 should be original id", list3.get(1), "stringInList2"); List<String> list4 = entityBody.getValues("key4"); assertNotNull("List should not be null", list4); assertEquals("List should have 0 values", list4.size(), 0); }
|
EntityResponse extends HashMap<String, Object> { public EntityResponse(String entityCollectionName, Object object) { super(); setEntityCollectionName(entityCollectionName); put(this.entityCollectionName, object); } EntityResponse(String entityCollectionName, Object object); Object getEntity(); final void setEntityCollectionName(String entityCollectionName); String getEntityCollectionName(); }
|
@Test public void testEntityResponse() { Map<String, String> map = new HashMap<String, String>(); map.put("testkey", "testvalue"); EntityResponse response = new EntityResponse("testcollection", map); assertNotNull("Should not be null", response.getEntity()); Map<String, String> testMap = (Map<String, String>) response.getEntity(); assertEquals("Should match", "testvalue", testMap.get("testkey")); }
|
EntityResponse extends HashMap<String, Object> { public Object getEntity() { return this.get(entityCollectionName); } EntityResponse(String entityCollectionName, Object object); Object getEntity(); final void setEntityCollectionName(String entityCollectionName); String getEntityCollectionName(); }
|
@Test public void testEntityResponseNullCollectionName() { EntityResponse response = new EntityResponse(null, new HashMap<String, String>()); assertNotNull("Should not be null", response.getEntity()); }
|
TenantIdToDbName { public static String convertTenantIdToDbName(String tenantId) { if (tenantId != null) { return TENANT_ID_CACHE.getUnchecked(tenantId); } else { return tenantId; } } static String convertTenantIdToDbName(String tenantId); }
|
@Test public void testConvertTenantIdToDbName() { Assert.assertEquals("7be07aaf460d593a323d0db33da05b64bfdcb3a5", TenantIdToDbName.convertTenantIdToDbName("ABCDE")); Assert.assertEquals("782a35eb5b9cd3e771047a60381e1274d76bc069", TenantIdToDbName.convertTenantIdToDbName("ABC.DE")); Assert.assertEquals("1072a2a56f16654387d030014968a48f04ca7488", TenantIdToDbName.convertTenantIdToDbName(" ABC DE ")); Assert.assertEquals("f89b39e01f5b1bb76655211472cd71274766070e", TenantIdToDbName.convertTenantIdToDbName("$ABCDE")); Assert.assertEquals("8e1cea182e0e0499fe1e0fe28e02d9ffb47ba098", TenantIdToDbName.convertTenantIdToDbName("ABC/DE")); }
|
DateHelper { public boolean isFieldExpired(Map<String, Object> body) { for (String key : Arrays.asList("endDate", "exitWithdrawDate")) { if (body.containsKey(key)) { return isFieldExpired(body, key, false); } } return false; } String getFilterDate(boolean useGracePeriod); DateTime getNowMinusGracePeriod(); boolean isFieldExpired(Map<String, Object> body); boolean isFieldExpired(Map<String, Object> body, String fieldName); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); DateTime getDate(Map<String, Object> body, String fieldName); boolean isLhsBeforeRhs(DateTime lhs, DateTime rhs); static DateTimeFormatter getDateTimeFormat(); static Criteria getExpiredCriteria(); static Criteria getExpiredCriteria(String endDateField); }
|
@Test public void testIsFieldExpired() { Map<String, Object> body = generateEntityBody(); Assert.assertTrue(dateHelper.isFieldExpired(body, "endDate", false)); body.put("exitWithdrawDate", "2070-10-25"); Assert.assertFalse(dateHelper.isFieldExpired(body, "exitWithdrawDate", false)); }
|
DateHelper { public DateTime getDate(Map<String, Object> body, String fieldName) { DateTime date = null; if (body.get(fieldName) != null) { date = DateTime.parse((String) body.get(fieldName), FMT); } return date; } String getFilterDate(boolean useGracePeriod); DateTime getNowMinusGracePeriod(); boolean isFieldExpired(Map<String, Object> body); boolean isFieldExpired(Map<String, Object> body, String fieldName); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); DateTime getDate(Map<String, Object> body, String fieldName); boolean isLhsBeforeRhs(DateTime lhs, DateTime rhs); static DateTimeFormatter getDateTimeFormat(); static Criteria getExpiredCriteria(); static Criteria getExpiredCriteria(String endDateField); }
|
@Test public void testGetDate() { Map<String, Object> body = generateEntityBody(); DateTime result = dateHelper.getDate(body, "endDate"); Assert.assertEquals(2010, result.getYear()); Assert.assertEquals(07, result.getMonthOfYear()); Assert.assertEquals(10, result.getDayOfMonth()); result = dateHelper.getDate(body, "expirationDate"); Assert.assertNull(result); }
|
SmooksEdFi2SLITransformer extends EdFi2SLITransformer { @Override public List<List<SimpleEntity>> handle(List<NeutralRecord> items, AbstractMessageReport report, ReportStats reportStats) { return null; } @Override List<SimpleEntity> transform(NeutralRecord item, AbstractMessageReport report, ReportStats reportStats); Map<String, Smooks> getSmooksConfigs(); void setSmooksConfigs(Map<String, Smooks> smooksConfigs); @Override List<List<SimpleEntity>> handle(List<NeutralRecord> items, AbstractMessageReport report,
ReportStats reportStats); @Override String getStageName(); }
|
@SuppressWarnings("deprecation") @Test public void testCreateAssessmentEntity() { EntityConfigFactory entityConfigurations = new EntityConfigFactory(); MongoEntityRepository mockedEntityRepository = mock(MongoEntityRepository.class); NeutralRecord assessmentRC = createAssessmentNeutralRecord(true); entityConfigurations.setResourceLoader(new DefaultResourceLoader()); entityConfigurations.setSearchPath("classpath:smooksEdFi2SLI/"); transformer.setEntityRepository(mockedEntityRepository); transformer.setEntityConfigurations(entityConfigurations); DeterministicIdResolver mockDidResolver = Mockito.mock(DeterministicIdResolver.class); transformer.setDIdResolver(mockDidResolver); List<Entity> le = new ArrayList<Entity>(); le.add(createAssessmentEntity(true)); when( mockedEntityRepository.findByQuery(eq("assessment"), Mockito.any(Query.class), eq(0), eq(0))).thenReturn(le); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); List<SimpleEntity> res = transformer.handle(assessmentRC, errorReport, reportStats); verify(mockedEntityRepository).findByQuery(eq("assessment"), Mockito.any(Query.class), eq(0), eq(0)); Assert.assertNotNull(res); Assert.assertEquals(ASSESSMENT_TITLE, res.get(0).getBody().get("assessmentTitle")); Assert.assertEquals(TENANT_ID, res.get(0).getMetaData().get(TENANT_ID_FIELD)); Assert.assertEquals(STUDENT_ID, res.get(0).getMetaData().get(EXTERNAL_ID_FIELD)); }
|
EntityManipulator { public static void removeFields(final Map<String, Object> toRemoveFrom, final List<String> toRemoveList) { if (toRemoveList == null || toRemoveList.isEmpty()) { return; } if (toRemoveFrom == null) { return; } for (final String toStrip : toRemoveList) { removeField(toRemoveFrom, toStrip); } } private EntityManipulator(); static void removeFields(final Map<String, Object> toRemoveFrom, final List<String> toRemoveList); static void removeFields(final Map<String, Object> toRemoveFrom, final String toRemove); }
|
@Test public void testStripFields() { Map<String, Object> body = new HashMap<String, Object>(); body.put("f1", "v1"); EntityManipulator.removeFields(body, "f1"); assertTrue(body.get("f1") == null); }
@Test public void testWrongExclude() { Map<String, Object> body = new HashMap<String, Object>(); body.put("f1", "v1"); EntityManipulator.removeFields(body, "foobar"); assertTrue(body.get("f1") != null); }
@Test public void testMultipleExclude() { Map<String, Object> body = new HashMap<String, Object>(); body.put("f1", "v1"); body.put("f2", "v2"); body.put("f3", "v3"); List<String> toStrip = Arrays.asList("f1", "f2"); EntityManipulator.removeFields(body, toStrip); assertTrue(body.get("f1") == null); assertTrue(body.get("f2") == null); assertTrue(body.get("f3") != null); }
@Test public void testStripMap() { Map<String, Object> body = new HashMap<String, Object>(); Map<String, Object> embeddedMap = new HashMap<String, Object>(); embeddedMap.put("ef1", "ev1"); embeddedMap.put("ef2", "ev2"); body.put("f1", embeddedMap); EntityManipulator.removeFields(body, "f1.ef1"); @SuppressWarnings("unchecked") Map<String, Object> f1 = (Map<String, Object>) body.get("f1"); assertTrue(f1 != null); assertEquals("ev2", f1.get("ef2")); assertTrue(f1.get("ef1") == null); }
@SuppressWarnings("unchecked") @Test public void testStripList() { Map<String, Object> body = new HashMap<String, Object>(); List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); Map<String, Object> em1 = new HashMap<String, Object>(); em1.put("ek1", "ev1"); em1.put("ek2", "ev2"); Map<String, Object> em2 = new HashMap<String, Object>(); em2.put("ek1", "ev1"); em2.put("ek2", "ev2"); mapList.add(em1); mapList.add(em2); body.put("k1", mapList); EntityManipulator.removeFields(body, "k1.ek1"); assertTrue(body.get("k1") instanceof List); List<Map<String, Object>> mapListRemoved = (List<Map<String, Object>>) body.get("k1"); assertEquals(2, mapListRemoved.size()); assertEquals("ev2", mapListRemoved.get(0).get("ek2")); assertEquals(null, mapListRemoved.get(0).get("ek1")); assertEquals("ev2", mapListRemoved.get(1).get("ek2")); assertEquals(null, mapListRemoved.get(1).get("ek1")); body = new HashMap<String, Object>(); List<String> values = Arrays.asList("ev1", "ev2"); body.put("k1", values); body.put("k2", "v2"); EntityManipulator.removeFields(body, "k1"); assertEquals("v2", body.get("k2")); assertFalse(body.containsKey("k1")); body = new HashMap<String, Object>(); List<Object> el1 = new ArrayList<Object>(); List<Object> el2 = new ArrayList<Object>(); em2 = new HashMap<String, Object>(); em2.put("eek1", "eev1"); em2.put("eek2", "eev2"); el2.add(em2); em1 = new HashMap<String, Object>(); em1.put("ek1", el2); el1.add(em1); body.put("k1", el1); EntityManipulator.removeFields(body, "k1.ek1.eek1"); List<Object> k1List = (List<Object>) body.get("k1"); Map<String, Object> ek1Map = (Map<String, Object>) k1List.get(0); List<Object> ek1List = (List<Object>) ek1Map.get("ek1"); Map<String, Object> removedMap = (Map<String, Object>) ek1List.get(0); assertTrue(removedMap.containsKey("eek2")); assertEquals("eev2", removedMap.get("eek2")); assertEquals(null, removedMap.get("eek1")); }
|
DeterministicUUIDGeneratorStrategy implements UUIDGeneratorStrategy { @Override public String generateId() { return uuidStrategy.generateId(); } @Override String generateId(); @Override String generateId(NaturalKeyDescriptor naturalKeyDescriptor); static final String DIGEST_ALGORITHM; }
|
@Test public void testDeterministicUUID() { String resultUuid = "someId"; Mockito.when(mockShardType1UUIDGeneratorStrategy.generateId()).thenReturn(resultUuid); String uuid = deterministicUUIDGeneratorStrategy.generateId(); assertNotNull(uuid); assertEquals(resultUuid, uuid); }
@Test public void shouldHaveSuffix() { String expectedSuffix = "_id"; Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("key1", "value1"); NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(); naturalKeyDescriptor.setNaturalKeys(hashMap); naturalKeyDescriptor.setEntityType("testEntityType"); naturalKeyDescriptor.setTenantId("testTenantId"); String deterministicId = deterministicUUIDGeneratorStrategy.generateId(naturalKeyDescriptor); boolean hasSuffix = deterministicId.endsWith(expectedSuffix); Assert.assertTrue("Incorrect suffix: " + deterministicId, hasSuffix); }
@Test public void testDeterministicUUIDMapOfStringString() { Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("key1", "value1"); hashMap.put("key2", "value2"); hashMap.put("key3", "value3"); NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(); naturalKeyDescriptor.setNaturalKeys(hashMap); naturalKeyDescriptor.setEntityType("testEntityType"); naturalKeyDescriptor.setTenantId("testTenantId"); String deterministicId = deterministicUUIDGeneratorStrategy.generateId(naturalKeyDescriptor); assertEquals("deterministicId should be of length 43", 43, deterministicId.length()); assertEquals("deterministicId should be a specific value", "a9e40c18e0638c2ef986deca9dec43ccc26349f4_id", deterministicId); }
@Test public void testNullNaturalKeyDescriptor() { String resultUuid = "someId"; Mockito.when(mockShardType1UUIDGeneratorStrategy.generateId()).thenReturn(resultUuid); String uuid = deterministicUUIDGeneratorStrategy.generateId(null); assertNotNull(uuid); assertEquals(resultUuid, uuid); }
@Test public void testDeterministicUUIDMapOfStringString2() { Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("key1", "value1"); hashMap.put("key2", "value2"); hashMap.put("key3", "value3"); NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(); naturalKeyDescriptor.setNaturalKeys(hashMap); naturalKeyDescriptor.setEntityType("entity||"); naturalKeyDescriptor.setTenantId("Type"); String deterministicId = deterministicUUIDGeneratorStrategy.generateId(naturalKeyDescriptor); NaturalKeyDescriptor naturalKeyDescriptor2 = new NaturalKeyDescriptor(); naturalKeyDescriptor2.setNaturalKeys(hashMap); naturalKeyDescriptor2.setEntityType("entity"); naturalKeyDescriptor2.setTenantId("||Type"); String deterministicId2 = deterministicUUIDGeneratorStrategy.generateId(naturalKeyDescriptor2); Assert.assertFalse("Ids should not be the same: ", deterministicId.equals(deterministicId2)); }
@Test public void testWithBothDelimiters() { Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("key1", "value1"); NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(); naturalKeyDescriptor.setNaturalKeys(hashMap); naturalKeyDescriptor.setEntityType("entity|~"); naturalKeyDescriptor.setTenantId("Type"); String deterministicId = deterministicUUIDGeneratorStrategy.generateId(naturalKeyDescriptor); NaturalKeyDescriptor naturalKeyDescriptor2 = new NaturalKeyDescriptor(); naturalKeyDescriptor2.setNaturalKeys(hashMap); naturalKeyDescriptor2.setEntityType("entity"); naturalKeyDescriptor2.setTenantId("|~Type"); String deterministicId2 = deterministicUUIDGeneratorStrategy.generateId(naturalKeyDescriptor2); Assert.assertFalse("Ids should not be the same: ", deterministicId.equals(deterministicId2)); }
@Test public void testWithSecondDelimiter() { Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("key1", "value1"); NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(); naturalKeyDescriptor.setNaturalKeys(hashMap); naturalKeyDescriptor.setEntityType("entity~"); naturalKeyDescriptor.setTenantId("Type"); String deterministicId = deterministicUUIDGeneratorStrategy.generateId(naturalKeyDescriptor); NaturalKeyDescriptor naturalKeyDescriptor2 = new NaturalKeyDescriptor(); naturalKeyDescriptor2.setNaturalKeys(hashMap); naturalKeyDescriptor2.setEntityType("entity"); naturalKeyDescriptor2.setTenantId("~Type"); String deterministicId2 = deterministicUUIDGeneratorStrategy.generateId(naturalKeyDescriptor2); Assert.assertFalse("Ids should not be the same: ", deterministicId.equals(deterministicId2)); }
|
DeterministicUUIDGeneratorStrategy implements UUIDGeneratorStrategy { protected static UUID generateUuid(byte[] data) { ByteBuffer byteBuffer = ByteBuffer.wrap(data); long msb = byteBuffer.getLong(0); long lsb = byteBuffer.getLong(8); UUID uuid = new UUID(msb, lsb); return uuid; } @Override String generateId(); @Override String generateId(NaturalKeyDescriptor naturalKeyDescriptor); static final String DIGEST_ALGORITHM; }
|
@Test public void testGenerateUuid() { byte[] testBytes = "abcdefghij1234567890".getBytes(); UUID uuid = DeterministicUUIDGeneratorStrategy.generateUuid(testBytes); assertNotNull("uuid must not be null", uuid); assertEquals("61626364-6566-6768-696a-313233343536", uuid.toString()); }
|
EntityPersistHandler extends AbstractIngestionHandler<SimpleEntity, Entity> implements InitializingBean { public void setEntityRepository(Repository<Entity> entityRepository) { this.entityRepository = entityRepository; } @Override void afterPropertiesSet(); void setEntityRepository(Repository<Entity> entityRepository); EntityConfigFactory getEntityConfigurations(); void setEntityConfigurations(EntityConfigFactory entityConfigurations); @Override String getStageName(); static final Logger LOG; }
|
@Test public void testCreateStudentEntity() { MongoEntityRepository entityRepository = mock(MongoEntityRepository.class); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria(METADATA_BLOCK + "." + REGION_ID_FIELD, NeutralCriteria.OPERATOR_EQUAL, REGION_ID, false)); query.addCriteria(new NeutralCriteria(METADATA_BLOCK + "." + EXTERNAL_ID_FIELD, NeutralCriteria.OPERATOR_EQUAL, STUDENT_ID, false)); SimpleEntity studentEntity = createStudentEntity(true); List<Entity> le = new ArrayList<Entity>(); le.add(studentEntity); when(entityRepository.findAll(eq("student"), any(NeutralQuery.class))).thenReturn(le); when(entityRepository.updateWithRetries(studentEntity.getType(), studentEntity, totalRetries)).thenReturn(true); entityPersistHandler.setEntityRepository(entityRepository); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); entityPersistHandler.handle(studentEntity, errorReport, reportStats); verify(entityRepository).updateWithRetries(studentEntity.getType(), studentEntity, totalRetries); le.clear(); SimpleEntity studentEntity2 = createStudentEntity(false); le.add(studentEntity2); entityPersistHandler.handle(studentEntity2, errorReport, reportStats); verify(entityRepository).createWithRetries(studentEntity.getType(), null, studentEntity.getBody(), studentEntity.getMetaData(), "student", totalRetries); Assert.assertFalse("Error report should not contain errors", reportStats.hasErrors()); }
@Test public void testCreateAndDeleteStudentEntity() { MongoEntityRepository entityRepository = mock(MongoEntityRepository.class); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria(METADATA_BLOCK + "." + REGION_ID_FIELD, NeutralCriteria.OPERATOR_EQUAL, REGION_ID, false)); query.addCriteria(new NeutralCriteria(METADATA_BLOCK + "." + EXTERNAL_ID_FIELD, NeutralCriteria.OPERATOR_EQUAL, STUDENT_ID, false)); SimpleEntity studentEntity = createStudentEntity(true); List<Entity> le = new ArrayList<Entity>(); le.add(studentEntity); when(entityRepository.findAll(eq("student"), any(NeutralQuery.class))).thenReturn(le); when(entityRepository.updateWithRetries(studentEntity.getType(), studentEntity, totalRetries)).thenReturn(true); CascadeResult mockCascadeResult = new CascadeResult(); mockCascadeResult.setStatus(CascadeResult.Status.SUCCESS); when(entityRepository.safeDelete(eq(studentEntity), eq(studentEntity.getEntityId()), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(), anyInt(), any(AccessibilityCheck.class))).thenReturn(mockCascadeResult); entityPersistHandler.setEntityRepository(entityRepository); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); entityPersistHandler.handle(studentEntity, errorReport, reportStats); verify(entityRepository).updateWithRetries(studentEntity.getType(), studentEntity, totalRetries); studentEntity.setAction( ActionVerb.CASCADE_DELETE); studentEntity.setActionAttributes(ImmutableMap.of( "Force", "true", "LogViolations", "true" )); entityPersistHandler.handle( studentEntity, errorReport, reportStats); verify(entityRepository).safeDelete(studentEntity, studentEntity.getEntityId(), true, false, true, true, null, null); Assert.assertFalse("Error report should not contain errors", reportStats.hasErrors()); }
|
ShardType1UUIDGeneratorStrategy implements UUIDGeneratorStrategy { @Override public String generateId() { StringBuilder builder = new StringBuilder(); char c1 = (char) (r.nextInt(26) + 'a'); char c2 = (char) (r.nextInt(26) + 'a'); builder.append(new DateTime().getYear()); builder.append(c1); builder.append(c2); builder.append("-"); builder.append(generator.generate().toString()); String uuid = builder.toString(); return uuid; } @Override String generateId(); @Override String generateId(NaturalKeyDescriptor naturalKeyDescriptor); }
|
@Test public void testShardType1UUIDGenerator() { ShardType1UUIDGeneratorStrategy uuidGen = new ShardType1UUIDGeneratorStrategy(); String uuid = uuidGen.generateId(); assertNotNull(uuid); assertEquals('1', uuid.charAt(22)); assertEquals(43, uuid.length()); }
|
LdapServiceImpl implements LdapService { @SuppressWarnings("rawtypes") @Override public User getUser(String realm, String uid) { AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, userObjectClass)).and(new EqualsFilter(userSearchAttribute, uid)); DistinguishedName dn = new DistinguishedName("ou=" + realm); User user; try { List userList = ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] { "*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper()); if (userList == null || userList.size() == 0) { throw new EmptyResultDataAccessException(1); } else if (userList.size() > 1) { throw new IncorrectResultSizeDataAccessException("User must be unique", 1); } user = (User) userList.get(0); user.setUid(uid); user.setGroups(getGroupNames(getUserGroups(realm, uid))); } catch (EmptyResultDataAccessException e) { return null; } return user; } @SuppressWarnings("rawtypes") @Override User getUser(String realm, String uid); @SuppressWarnings("unchecked") @Override Collection<Group> getUserGroups(String realm, String uid); @Override void removeUser(String realm, String uid); @Override String createUser(String realm, User user); @Override boolean updateUser(String realm, User user); @Override Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames,
final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant); @Override Collection<User> findUsersByAttributes(String realm, Collection<String> attributes); @Override Group getGroup(String realm, String groupName); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant,
Collection<String> edorgs); @Override boolean addUserToGroup(String realm, Group group, User user); @Override boolean removeUserFromGroup(String realm, Group group, User user); @Override boolean updateGroup(String realm, Group group); @Override void setLdapTemplate(LdapTemplate ldapTemplate); static final String OBJECTCLASS; }
|
@Test public void testGetUser() { User slcoperator = ldapService.getUser("LocalNew", "slcoperator"); assertNotNull(slcoperator); assertTrue(slcoperator.getGroups().contains("SLC Operator")); assertTrue(slcoperator.getEmail().equals("slcoperator@slidev.org")); assertTrue(slcoperator.getUid().equals("slcoperator")); assertNotNull(slcoperator.getHomeDir()); assertNotNull(slcoperator.getGivenName()); assertNotNull(slcoperator.getSn()); assertNotNull(slcoperator.getFullName()); assertNull(slcoperator.getTenant()); assertNull(slcoperator.getEdorg()); assertNotNull(slcoperator.getCreateTime()); assertNotNull(slcoperator.getModifyTime()); }
|
LdapServiceImpl implements LdapService { @Override public Group getGroup(String realm, String groupName) { DistinguishedName dn = new DistinguishedName("ou=" + realm); AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, groupObjectClass)).and(new EqualsFilter("cn", groupName)); try { return (Group) ldapTemplate.searchForObject(dn, filter.toString(), new GroupContextMapper()); } catch (EmptyResultDataAccessException e) { return null; } } @SuppressWarnings("rawtypes") @Override User getUser(String realm, String uid); @SuppressWarnings("unchecked") @Override Collection<Group> getUserGroups(String realm, String uid); @Override void removeUser(String realm, String uid); @Override String createUser(String realm, User user); @Override boolean updateUser(String realm, User user); @Override Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames,
final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant); @Override Collection<User> findUsersByAttributes(String realm, Collection<String> attributes); @Override Group getGroup(String realm, String groupName); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant,
Collection<String> edorgs); @Override boolean addUserToGroup(String realm, Group group, User user); @Override boolean removeUserFromGroup(String realm, Group group, User user); @Override boolean updateGroup(String realm, Group group); @Override void setLdapTemplate(LdapTemplate ldapTemplate); static final String OBJECTCLASS; }
|
@Test public void testGetGroup() { Group slcoperatorGroup = ldapService.getGroup("LocalNew", "SLC Operator"); assertNotNull(slcoperatorGroup); assertEquals("SLC Operator", slcoperatorGroup.getGroupName()); assertTrue(slcoperatorGroup.getMemberUids().contains("slcoperator")); }
|
LdapServiceImpl implements LdapService { @SuppressWarnings("unchecked") @Override public Collection<Group> getUserGroups(String realm, String uid) { DistinguishedName dn = new DistinguishedName("ou=" + realm); AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, groupObjectClass)).and(new EqualsFilter(groupSearchAttribute, uid)); List<Group> groups = ldapTemplate.search(dn, filter.toString(), new GroupContextMapper()); return groups; } @SuppressWarnings("rawtypes") @Override User getUser(String realm, String uid); @SuppressWarnings("unchecked") @Override Collection<Group> getUserGroups(String realm, String uid); @Override void removeUser(String realm, String uid); @Override String createUser(String realm, User user); @Override boolean updateUser(String realm, User user); @Override Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames,
final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant); @Override Collection<User> findUsersByAttributes(String realm, Collection<String> attributes); @Override Group getGroup(String realm, String groupName); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant,
Collection<String> edorgs); @Override boolean addUserToGroup(String realm, Group group, User user); @Override boolean removeUserFromGroup(String realm, Group group, User user); @Override boolean updateGroup(String realm, Group group); @Override void setLdapTemplate(LdapTemplate ldapTemplate); static final String OBJECTCLASS; }
|
@Test public void testGetUserGroups() { Collection<Group> groups = ldapService.getUserGroups("LocalNew", "slcoperator"); assertNotNull(groups); Collection<String> groupNames = new ArrayList<String>(); for (Group group : groups) { groupNames.add(group.getGroupName()); } assertTrue(groupNames.contains("SLC Operator")); }
|
LdapServiceImpl implements LdapService { @Override public Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames, final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs) { Collection<String> allowed = allowedGroupNames; Collection<String> disallowed = disallowedGroupNames; if (allowed == null) { allowed = new LinkedList<String>(); } if (disallowed == null) { disallowed = new LinkedList<String>(); } Set<String> allowedUsers = new HashSet<String>(); Map<String, List<String>> uidToGroupsMap = new HashMap<String, List<String>>(); for (String groupName : allowed) { Group group = getGroup(realm, groupName); if (group != null) { List<String> memberUids = group.getMemberUids(); if (memberUids != null && memberUids.size() > 0) { for (String memberUid : memberUids) { if (uidToGroupsMap.containsKey(memberUid)) { uidToGroupsMap.get(memberUid).add(groupName); } else { List<String> uidGroupNames = new ArrayList<String>(); uidGroupNames.add(groupName); uidToGroupsMap.put(memberUid, uidGroupNames); } allowedUsers.add(memberUid); } } } } for (String groupName : disallowed) { Group group = getGroup(realm, groupName); if (group != null) { allowedUsers.removeAll(group.getMemberUids()); } } AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, userObjectClass)); OrFilter orFilter = new OrFilter(); for (String uid : allowedUsers) { orFilter.or(new EqualsFilter(userSearchAttribute, uid)); } filter.and(orFilter); DistinguishedName dn = new DistinguishedName("ou=" + realm); @SuppressWarnings("unchecked") Collection<User> users = (ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] { "*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper())); for (User user : users) { user.setGroups(uidToGroupsMap.get(user.getUid())); } if (tenant != null) { users = filterByTenant(users, tenant); } if (edorgs != null) { users = filterByEdorgs(users, edorgs); } return users; } @SuppressWarnings("rawtypes") @Override User getUser(String realm, String uid); @SuppressWarnings("unchecked") @Override Collection<Group> getUserGroups(String realm, String uid); @Override void removeUser(String realm, String uid); @Override String createUser(String realm, User user); @Override boolean updateUser(String realm, User user); @Override Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames,
final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant); @Override Collection<User> findUsersByAttributes(String realm, Collection<String> attributes); @Override Group getGroup(String realm, String groupName); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant,
Collection<String> edorgs); @Override boolean addUserToGroup(String realm, Group group, User user); @Override boolean removeUserFromGroup(String realm, Group group, User user); @Override boolean updateGroup(String realm, Group group); @Override void setLdapTemplate(LdapTemplate ldapTemplate); static final String OBJECTCLASS; }
|
@Test public void testFindUserByGroups() { String[] groups = new String[] { "SEA Administrator" }; Collection<User> users = ldapService.findUsersByGroups("LocalNew", Arrays.asList(groups)); assertNotNull(users); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.