src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
|---|---|
PropertyUtils { public static Properties getProperties(String[] args) throws ParseException { Properties props = new Properties(); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(OPTIONS, args); String zoneUrl = cmd.getOptionValue(FLAG_ZONE_URL, DEFAULT_ZONE_URL); String zoneId = cmd.getOptionValue(FLAG_ZONE_ID, DEFAULT_ZONE_ID); String agentId = cmd.getOptionValue(FLAG_AGENT_ID, DEFAULT_AGENT_ID); String script = cmd.getOptionValue(FLAG_SCRIPT, DEFAULT_SCRIPT); String waitTimeStr = cmd.getOptionValue(FLAG_WAIT_TIME, "DEFAULT_WAIT_TIME"); long waitTime; try { waitTime = Long.parseLong(waitTimeStr); } catch (NumberFormatException e) { waitTime = Long.parseLong(DEFAULT_WAIT_TIME); } props.put(KEY_ZONE_URL, zoneUrl); props.put(KEY_ZONE_ID, zoneId); props.put(KEY_AGENT_ID, agentId); props.put(KEY_SCRIPT, script); props.put(KEY_WAIT_TIME, waitTime); String messageFile = cmd.getOptionValue(FLAG_MESSAGE_FILE, DEFAULT_MESSAGE_FILE); props.put(KEY_MESSAGE_FILE, messageFile); String eventAction = cmd.getOptionValue(FLAG_EVENT_ACTION, DEFAULT_EVENT_ACTION); props.put(KEY_EVENT_ACTION, eventAction); return props; } static Properties getProperties(String[] args); static final String KEY_ZONE_URL; static final String KEY_ZONE_ID; static final String KEY_AGENT_ID; static final String KEY_SCRIPT; static final String KEY_WAIT_TIME; static final String KEY_MESSAGE_FILE; static final String KEY_EVENT_ACTION; static final Options OPTIONS; }
|
@Test public void testGetPropertiesDefault() throws ParseException { String[] args = {}; Properties props = PropertyUtils.getProperties(args); Assert.assertEquals("test.publisher.agent", props.getProperty(PropertyUtils.KEY_AGENT_ID)); Assert.assertEquals("http: Assert.assertEquals("TestZone", props.getProperty(PropertyUtils.KEY_ZONE_ID)); Assert.assertEquals("LEAInfoAdd", props.getProperty(PropertyUtils.KEY_SCRIPT)); Assert.assertEquals(5000, ((Long) props.get(PropertyUtils.KEY_WAIT_TIME)).longValue()); Assert.assertEquals("", props.getProperty(PropertyUtils.KEY_MESSAGE_FILE)); Assert.assertEquals("ADD", props.getProperty(PropertyUtils.KEY_EVENT_ACTION)); }
@Test public void testGetPropertiesNonDefault() throws ParseException { String agentId = "agentId"; String zoneUrl = "http: String zoneId = "MyZone"; String script = "step1,step2,step3"; long waitTime = 9999; String messageFile = "path/to/file"; String eventAction = "DELETE"; String[] args = {"-a", agentId, "-u", zoneUrl, "-z", zoneId, "-s", script, "-w", String.valueOf(waitTime), "-f", messageFile, "-e", eventAction}; Properties props = PropertyUtils.getProperties(args); Assert.assertEquals(agentId, props.getProperty(PropertyUtils.KEY_AGENT_ID)); Assert.assertEquals(zoneUrl, props.getProperty(PropertyUtils.KEY_ZONE_URL)); Assert.assertEquals(zoneId, props.getProperty(PropertyUtils.KEY_ZONE_ID)); Assert.assertEquals(script, props.getProperty(PropertyUtils.KEY_SCRIPT)); Assert.assertEquals(waitTime, ((Long) props.get(PropertyUtils.KEY_WAIT_TIME)).longValue()); Assert.assertEquals(messageFile, props.getProperty(PropertyUtils.KEY_MESSAGE_FILE)); Assert.assertEquals(eventAction, props.getProperty(PropertyUtils.KEY_EVENT_ACTION)); }
|
EventReporterAgent extends Agent { public void startAgent() throws Exception { super.initialize(); setProperties(); Zone[] allZones = getZoneFactory().getAllZones(); zoneConfigurator.configure(allZones); } EventReporterAgent(); EventReporterAgent(String id); EventReporterAgent(String id, ZoneConfigurator zoneConfig, Properties agentProperties,
Properties httpProperties, Properties httpsProperties, String zoneId,
String zoneUrl, SIFVersion sifVersion); void startAgent(); void setConfigFilePath(String configFilePath); String getConfigFilePath(); void setZoneConfigurator(ZoneConfigurator zoneConfigurator); ZoneConfigurator getZoneConfigurator(); void setAgentProperties(Properties agentProperties); Properties getAgentProperties(); void setHttpProperties(Properties httpProperties); Properties getHttpProperties(); void setHttpsProperties(Properties httpsProperties); Properties getHttpsProperties(); void setSifVersion(SIFVersion sifVersion); SIFVersion getSifVersion(); }
|
@Test public void shouldCreateAndConfigureAgent() throws Exception { ZoneConfigurator mockZoneConfigurator = Mockito.mock(ZoneConfigurator.class); EventReporterAgent agent = createEventReporterAgent(mockZoneConfigurator); agent.startAgent(); AgentProperties props = agent.getProperties(); Assert.assertEquals("Push", props.getProperty("adk.messaging.mode")); Assert.assertEquals("http", props.getProperty("adk.messaging.transport")); Assert.assertEquals("30000", props.getProperty("adk.messaging.pullFrequency")); Assert.assertEquals("32000", props.getProperty("adk.messaging.maxBufferSize")); Assert.assertEquals("test.publisher.agent", agent.getId()); TransportManager transportManager = agent.getTransportManager(); Transport transport = transportManager.getTransport("http"); TransportProperties transportProperties = transport.getProperties(); Assert.assertEquals("25101", transportProperties.getProperty("port")); Zone[] allZones = agent.getZoneFactory().getAllZones(); Assert.assertNotNull("Agents zones should not be null", allZones); Assert.assertEquals("Agent should be configured with one zone", 1, allZones.length); Assert.assertNotNull("Agent's zone should not be null", allZones[0]); Assert.assertEquals("Agent's zone Id should be TestZone", "TestZone", allZones[0].getZoneId()); Assert.assertEquals("Agent's zone URL should be http: "http: Mockito.verify(mockZoneConfigurator, Mockito.times(1)).configure(Mockito.any(Zone[].class)); }
|
DatelessExtractVerifier implements ExtractVerifier { @Override public boolean shouldExtract(Entity entity, DateTime upToDate) { return true; } @Override boolean shouldExtract(Entity entity, DateTime upToDate); }
|
@Test public void testshouldExtract() { Entity student = Mockito.mock(Entity.class); Mockito.when(student.getType()).thenReturn(EntityNames.STUDENT); Assert.assertTrue(datelessExtractVerifier.shouldExtract(student, DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()))); Assert.assertTrue(datelessExtractVerifier.shouldExtract(student, null)); }
|
EventReporter implements Publisher { public List<Event> runReportScript(String script, long waitTime) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { List<Event> eventsSent = new ArrayList<Event>(); LOG.info("Wait time (ms): " + waitTime); String[] eventDescriptors = script.split(","); for (String descriptor : eventDescriptors) { GeneratorScriptMethod scriptMethod = GeneratorScriptMethod.get(descriptor); if (scriptMethod == null) { LOG.error("Error retrieving scriptMethod - " + descriptor); } else { LOG.info("Executing script method - " + scriptMethod.toString()); try { Event eventSent = scriptMethod.execute(this); eventsSent.add(eventSent); Thread.sleep(waitTime); } catch (SecurityException e) { LOG.error("Failed to execute method for descriptor " + descriptor, e); } catch (NoSuchMethodException e) { LOG.error("Failed to execute method for descriptor " + descriptor, e); } catch (InterruptedException e) { LOG.error("Exception while sleeping", e); } } } return eventsSent; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void testRunReportScript() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ADKException { Map<Class<? extends SIFDataObject>, List<EventAction>> testMap; testMap = new LinkedHashMap<Class<? extends SIFDataObject>, List<EventAction>>(); List<EventAction> addChangeDeleteEventActionList = new ArrayList<EventAction>(); addChangeDeleteEventActionList.add(EventAction.ADD); addChangeDeleteEventActionList.add(EventAction.CHANGE); addChangeDeleteEventActionList.add(EventAction.DELETE); testMap.put(LEAInfo.class, addChangeDeleteEventActionList); testMap.put(SchoolInfo.class, addChangeDeleteEventActionList); testMap.put(StudentPersonal.class, addChangeDeleteEventActionList); testMap.put(StudentLEARelationship.class, addChangeDeleteEventActionList); testMap.put(StudentSchoolEnrollment.class, addChangeDeleteEventActionList); String[] scriptArray = { "LEAInfoAdd", "LEAInfoChange", "LEAInfoDelete", "SchoolInfoAdd", "SchoolInfoChange", "SchoolInfoDelete", "StudentPersonalAdd", "StudentPersonalChange", "StudentPersonalDelete", "StudentLEARelationshipAdd", "StudentLEARelationshipChange", "StudentLEARelationshipDelete", "StudentSchoolEnrollmentAdd", "StudentSchoolEnrollmentChange", "StudentSchoolEnrollmentDelete", "StaffPersonalAdd", "StaffPersonalChange", "StaffPersonalDelete", "EmployeePersonalAdd", "EmployeePersonalChange", "EmployeePersonalDelete", "StaffAssignmentAdd", "StaffAssignmentChange", "StaffAssignmentDelete", "EmploymentRecordAdd", "EmploymentRecordChange", "EmploymentRecordDelete", "EmployeeAssignmentAdd", "EmployeeAssignmentChange", "EmployeeAssignmentDelete" }; String script = ""; for (String item : scriptArray) { script += item + ","; } long waitTime = 0; List<Event> eventsSent = eventReporter.runReportScript(script, waitTime); Mockito.verify(zone, Mockito.times(scriptArray.length)).reportEvent(Mockito.any(Event.class)); Assert.assertEquals(scriptArray.length, eventsSent.size()); int index = 0; for (Class<? extends SIFDataObject> expectedClass : testMap.keySet()) { for (EventAction expectedAction : testMap.get(expectedClass)) { Event event = eventsSent.get(index++); checkScriptedEvent(event, expectedClass, expectedAction); } } }
|
EventReporter implements Publisher { public Event reportLeaInfoEvent(EventAction action) throws ADKException { LOG.info("LeaInfo " + action.toString()); LEAInfo leaInfo = SifEntityGenerator.generateTestLEAInfo(); if (action == EventAction.CHANGE) { leaInfo.setChanged(); leaInfo.setLEAURL("http: } Event event = new Event(leaInfo, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportLeaInfoEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = LEAInfo.class; String expectedId = SifEntityGenerator.TEST_LEAINFO_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportLeaInfoEvent(eventAction); LEAInfo dataObject = (LEAInfo) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals("http: eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportLeaInfoEvent(eventAction); dataObject = (LEAInfo) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); Assert.assertEquals("http: eventAction = EventAction.DELETE; sentEvent = eventReporter.reportLeaInfoEvent(eventAction); dataObject = (LEAInfo) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals("http: }
|
EventReporter implements Publisher { public Event reportSchoolInfoEvent(EventAction action) throws ADKException { LOG.info("SchoolInfo " + action.toString()); SchoolInfo schoolInfo = SifEntityGenerator.generateTestSchoolInfo(); if (action == EventAction.CHANGE) { schoolInfo.setChanged(); schoolInfo.setSchoolURL("http: } Event event = new Event(schoolInfo, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportSchoolInfoEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = SchoolInfo.class; String expectedId = SifEntityGenerator.TEST_SCHOOLINFO_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportSchoolInfoEvent(eventAction); SchoolInfo dataObject = (SchoolInfo) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals("http: eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportSchoolInfoEvent(eventAction); dataObject = (SchoolInfo) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); Assert.assertEquals("http: eventAction = EventAction.DELETE; sentEvent = eventReporter.reportSchoolInfoEvent(eventAction); dataObject = (SchoolInfo) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals("http: }
|
EventReporter implements Publisher { public Event reportStudentPersonalEvent(EventAction action) throws ADKException { LOG.info("StudentPersonal " + action.toString()); StudentPersonal studentPersonal = SifEntityGenerator.generateTestStudentPersonal(); if (action == EventAction.CHANGE) { studentPersonal.setChanged(); studentPersonal.setMigrant(YesNoUnknown.UNKNOWN); } Event event = new Event(studentPersonal, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportStudentPersonalEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = StudentPersonal.class; String expectedId = SifEntityGenerator.TEST_STUDENTPERSONAL_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportStudentPersonalEvent(eventAction); StudentPersonal dataObject = (StudentPersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(YesNoUnknown.NO.getValue(), dataObject.getMigrant()); eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportStudentPersonalEvent(eventAction); dataObject = (StudentPersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); Assert.assertEquals(YesNoUnknown.UNKNOWN.getValue(), dataObject.getMigrant()); eventAction = EventAction.DELETE; sentEvent = eventReporter.reportStudentPersonalEvent(eventAction); dataObject = (StudentPersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(YesNoUnknown.NO.getValue(), dataObject.getMigrant()); }
|
EventReporter implements Publisher { public Event reportStudentLeaRelationshipEvent(EventAction action) throws ADKException { LOG.info("StudentLeaRelationship " + action.toString()); StudentLEARelationship studentLeaRelationship = SifEntityGenerator.generateTestStudentLeaRelationship(); if (action == EventAction.CHANGE) { studentLeaRelationship.setChanged(); studentLeaRelationship.setGradeLevel(GradeLevelCode._09); } Event event = new Event(studentLeaRelationship, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportStudentLeaRelationshipEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = StudentLEARelationship.class; String expectedId = SifEntityGenerator.TEST_STUDENTLEARELATIONSHIP_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportStudentLeaRelationshipEvent(eventAction); StudentLEARelationship dataObject = (StudentLEARelationship) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(GradeLevelCode._10.getValue(), dataObject.getGradeLevel().getCode()); eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportStudentLeaRelationshipEvent(eventAction); dataObject = (StudentLEARelationship) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); Assert.assertEquals(GradeLevelCode._09.getValue(), dataObject.getGradeLevel().getCode()); eventAction = EventAction.DELETE; sentEvent = eventReporter.reportStudentLeaRelationshipEvent(eventAction); dataObject = (StudentLEARelationship) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(GradeLevelCode._10.getValue(), dataObject.getGradeLevel().getCode()); }
|
EventReporter implements Publisher { public Event reportStudentSchoolEnrollmentEvent(EventAction action) throws ADKException { LOG.info("StudentSchoolEnrollment " + action.toString()); StudentSchoolEnrollment studentSchoolEnrollment = SifEntityGenerator.generateTestStudentSchoolEnrollment(); if (action == EventAction.CHANGE) { studentSchoolEnrollment.setChanged(); studentSchoolEnrollment.setExitType(ExitTypeCode._1923_DIED_OR_INCAPACITATED); } Event event = new Event(studentSchoolEnrollment, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportStudentSchoolEnrollmentEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = StudentSchoolEnrollment.class; String expectedId = SifEntityGenerator.TEST_STUDENTSCHOOLENROLLMENT_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportStudentSchoolEnrollmentEvent(eventAction); StudentSchoolEnrollment dataObject = (StudentSchoolEnrollment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(ExitTypeCode._3502_NOT_ENROLLED_ELIGIBLE_TO.getValue(), dataObject.getExitType().getCode()); eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportStudentSchoolEnrollmentEvent(eventAction); dataObject = (StudentSchoolEnrollment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); Assert.assertEquals(ExitTypeCode._1923_DIED_OR_INCAPACITATED.getValue(), dataObject.getExitType().getCode()); eventAction = EventAction.DELETE; sentEvent = eventReporter.reportStudentSchoolEnrollmentEvent(eventAction); dataObject = (StudentSchoolEnrollment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(ExitTypeCode._3502_NOT_ENROLLED_ELIGIBLE_TO.getValue(), dataObject.getExitType().getCode()); }
|
EventReporter implements Publisher { public Event reportStaffPersonalEvent(EventAction action) throws ADKException { LOG.info("StaffPersonal " + action.toString()); StaffPersonal staffPersonal = SifEntityGenerator.generateTestStaffPersonal(); if (action == EventAction.CHANGE) { staffPersonal.setChanged(); staffPersonal.setEmailList(new EmailList(new Email(EmailType.PRIMARY, "chuckyw@imginc.com"))); } Event event = new Event(staffPersonal, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportStaffPersonalEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = StaffPersonal.class; String expectedId = SifEntityGenerator.TEST_STAFFPERSONAL_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportStaffPersonalEvent(eventAction); StaffPersonal dataObject = (StaffPersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); String emailAddress = dataObject.getEmailList().get(0).getValue(); Assert.assertEquals("chuckw@imginc.com", emailAddress); eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportStaffPersonalEvent(eventAction); dataObject = (StaffPersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); emailAddress = dataObject.getEmailList().get(0).getValue(); Assert.assertEquals("chuckyw@imginc.com", emailAddress); eventAction = EventAction.DELETE; sentEvent = eventReporter.reportStaffPersonalEvent(eventAction); dataObject = (StaffPersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); emailAddress = dataObject.getEmailList().get(0).getValue(); Assert.assertEquals("chuckw@imginc.com", emailAddress); }
|
EventReporter implements Publisher { public Event reportEmployeePersonalEvent(EventAction action) throws ADKException { LOG.info("EmployeePersonal " + action.toString()); EmployeePersonal employeePersonal = SifEntityGenerator.generateTestEmployeePersonal(); if (action == EventAction.CHANGE) { employeePersonal.setChanged(); employeePersonal.setOtherIdList(new HrOtherIdList(new OtherId(OtherIdType.CERTIFICATE, "certificate"))); } Event event = new Event(employeePersonal, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportEmployeePersonalEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = EmployeePersonal.class; String expectedId = SifEntityGenerator.TEST_EMPLOYEEPERSONAL_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportEmployeePersonalEvent(eventAction); EmployeePersonal dataObject = (EmployeePersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); OtherId otherId = dataObject.getOtherIdList().get(0); Assert.assertEquals(OtherIdType.SOCIALSECURITY.getValue(), otherId.getType()); Assert.assertEquals("333333333", otherId.getValue()); eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportEmployeePersonalEvent(eventAction); dataObject = (EmployeePersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); otherId = dataObject.getOtherIdList().get(0); Assert.assertEquals(OtherIdType.CERTIFICATE.getValue(), otherId.getType()); Assert.assertEquals("certificate", otherId.getValue()); eventAction = EventAction.DELETE; sentEvent = eventReporter.reportEmployeePersonalEvent(eventAction); dataObject = (EmployeePersonal) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); otherId = dataObject.getOtherIdList().get(0); Assert.assertEquals(OtherIdType.SOCIALSECURITY.getValue(), otherId.getType()); Assert.assertEquals("333333333", otherId.getValue()); }
|
EventReporter implements Publisher { public Event reportStaffAssignmentEvent(EventAction action) throws ADKException { LOG.info("StaffAssignment " + action.toString()); StaffAssignment staffAssignment = SifEntityGenerator.generateTestStaffAssignment(); if (action == EventAction.CHANGE) { staffAssignment.setChanged(); staffAssignment.setPrimaryAssignment(YesNo.NO); } Event event = new Event(staffAssignment, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportStaffAssignmentEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = StaffAssignment.class; String expectedId = SifEntityGenerator.TEST_STAFFASSIGNMENT_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportStaffAssignmentEvent(eventAction); StaffAssignment dataObject = (StaffAssignment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(YesNo.YES.getValue(), dataObject.getPrimaryAssignment()); eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportStaffAssignmentEvent(eventAction); dataObject = (StaffAssignment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); Assert.assertEquals(YesNo.NO.getValue(), dataObject.getPrimaryAssignment()); eventAction = EventAction.DELETE; sentEvent = eventReporter.reportStaffAssignmentEvent(eventAction); dataObject = (StaffAssignment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(YesNo.YES.getValue(), dataObject.getPrimaryAssignment()); }
|
EventReporter implements Publisher { public Event reportEmploymentRecordEvent(EventAction action) throws ADKException { LOG.info("EmploymentRecord " + action.toString()); EmploymentRecord employmentRecord = SifEntityGenerator.generateTestEmploymentRecord(); if (action == EventAction.CHANGE) { employmentRecord.setChanged(); employmentRecord.setPositionNumber("15"); } Event event = new Event(employmentRecord, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportEmploymentRecordEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = EmploymentRecord.class; String expectedId = SifEntityGenerator.TEST_EMPLOYMENTRECORD_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportEmploymentRecordEvent(eventAction); EmploymentRecord dataObject = (EmploymentRecord) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals("10", dataObject.getPositionNumber()); eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportEmploymentRecordEvent(eventAction); dataObject = (EmploymentRecord) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); Assert.assertEquals("15", dataObject.getPositionNumber()); eventAction = EventAction.DELETE; sentEvent = eventReporter.reportEmploymentRecordEvent(eventAction); dataObject = (EmploymentRecord) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals("10", dataObject.getPositionNumber()); }
|
AttendanceExtractVerifier implements ExtractVerifier { @Override public boolean shouldExtract(Entity entity, DateTime upToDate) { String schoolYear = null; if (entity.getBody().containsKey("schoolYearAttendance")) { schoolYear = (String) ((List<Map<String, Object>>) entity.getBody().get("schoolYearAttendance")).get(0).get("schoolYear"); } else { schoolYear = EntityDateHelper.retrieveDate(entity); } return EntityDateHelper.isPastOrCurrentDate(schoolYear, upToDate, entity.getType()); } @Override boolean shouldExtract(Entity entity, DateTime upToDate); }
|
@Test public void testshouldExtractEntityBeforeAndAfterTreatment() { Map<String, Object> entityBody = new HashMap<String, Object>(); entityBody.put(ParameterConstants.SCHOOL_YEAR, "2009-2010"); Entity attendance = Mockito.mock(Entity.class); Mockito.when(attendance.getType()).thenReturn(EntityNames.ATTENDANCE); Mockito.when(attendance.getBody()).thenReturn(entityBody); Assert.assertTrue(attendanceExtractVerifier.shouldExtract(attendance, DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()))); entityBody.clear(); List<Map<String, Object>> schoolYearAttendances = new ArrayList<Map<String, Object>>(); Map<String, Object> schoolYearAttendance = new HashMap<String, Object>(); schoolYearAttendance.put(ParameterConstants.SCHOOL_YEAR, "2009-2010"); schoolYearAttendances.add(schoolYearAttendance); entityBody.put("schoolYearAttendance", schoolYearAttendances); Assert.assertTrue(attendanceExtractVerifier.shouldExtract(attendance, DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()))); Assert.assertTrue(attendanceExtractVerifier.shouldExtract(attendance, DateTime.parse("2010-05-23", DateHelper.getDateTimeFormat()))); Assert.assertFalse(attendanceExtractVerifier.shouldExtract(attendance, DateTime.parse("2009-05-24", DateHelper.getDateTimeFormat()))); Assert.assertFalse(attendanceExtractVerifier.shouldExtract(attendance, DateTime.parse("2008-05-24", DateHelper.getDateTimeFormat()))); }
|
EventReporter implements Publisher { public Event reportEmployeeAssignmentEvent(EventAction action) throws ADKException { LOG.info("EmployeeAssignment " + action.toString()); EmployeeAssignment employeeAssignment = SifEntityGenerator.generateTestEmployeeAssignment(); if (action == EventAction.CHANGE) { employeeAssignment.setChanged(); employeeAssignment.setPrimaryAssignment(YesNo.NO); } Event event = new Event(employeeAssignment, action); zone.reportEvent(event); return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void runReportEmployeeAssignmentEventTests() throws ADKException { Class<? extends SIFDataObject> expectedClass = EmployeeAssignment.class; String expectedId = SifEntityGenerator.TEST_EMPLOYEEASSIGNMENT_REFID; EventAction eventAction = EventAction.ADD; Event sentEvent = eventReporter.reportEmployeeAssignmentEvent(eventAction); EmployeeAssignment dataObject = (EmployeeAssignment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(YesNo.YES.getValue(), dataObject.getPrimaryAssignment()); eventAction = EventAction.CHANGE; sentEvent = eventReporter.reportEmployeeAssignmentEvent(eventAction); dataObject = (EmployeeAssignment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, true); Assert.assertEquals(YesNo.NO.getValue(), dataObject.getPrimaryAssignment()); eventAction = EventAction.DELETE; sentEvent = eventReporter.reportEmployeeAssignmentEvent(eventAction); dataObject = (EmployeeAssignment) runDataObjectEventTest(sentEvent, eventAction, expectedClass, expectedId, false); Assert.assertEquals(YesNo.YES.getValue(), dataObject.getPrimaryAssignment()); }
|
EventReporter implements Publisher { public Event reportEvent(String messageFile, String eventAction) throws ADKException { Event event = CustomEventGenerator.generateEvent(messageFile, EventAction.valueOf(eventAction)); if (event == null) { LOG.error("Null event can not be reported"); return null; } if (zone.isConnected()) { zone.reportEvent(event); } else { LOG.error("Zone is not connected"); return null; } return event; } EventReporter(Zone zone); static void main(String[] args); List<Event> runReportScript(String script, long waitTime); Event reportLeaInfoEvent(EventAction action); Event reportSchoolInfoEvent(EventAction action); Event reportStudentPersonalEvent(EventAction action); Event reportStudentLeaRelationshipEvent(EventAction action); Event reportStudentSchoolEnrollmentEvent(EventAction action); Event reportStaffPersonalEvent(EventAction action); Event reportEmployeePersonalEvent(EventAction action); Event reportStaffAssignmentEvent(EventAction action); Event reportEmploymentRecordEvent(EventAction action); Event reportEmployeeAssignmentEvent(EventAction action); Event reportEvent(String messageFile, String eventAction); @Override void onRequest(DataObjectOutputStream out, Query query, Zone zone, MessageInfo info); static final Logger LOG; }
|
@Test public void testReportEventValidFile() throws ADKException { URL url = getClass().getResource("/element_xml/StudentPersonal.xml"); String validFilename = url.getPath(); String eventActionStr = EventAction.ADD.toString(); Event event = eventReporter.reportEvent(validFilename, eventActionStr); Assert.assertNotNull(event); EventAction eventAction = event.getAction(); Assert.assertEquals(eventActionStr, eventAction.toString()); Mockito.verify(zone, Mockito.times(1)).reportEvent(Mockito.eq(event)); eventActionStr = EventAction.CHANGE.toString(); event = eventReporter.reportEvent(validFilename, eventActionStr); Assert.assertNotNull(event); eventAction = event.getAction(); Assert.assertEquals(eventActionStr, eventAction.toString()); Mockito.verify(zone, Mockito.times(1)).reportEvent(Mockito.eq(event)); eventActionStr = EventAction.DELETE.toString(); event = eventReporter.reportEvent(validFilename, eventActionStr); Assert.assertNotNull(event); eventAction = event.getAction(); Assert.assertEquals(eventActionStr, eventAction.toString()); Mockito.verify(zone, Mockito.times(1)).reportEvent(Mockito.eq(event)); Mockito.when(zone.isConnected()).thenReturn(false); event = eventReporter.reportEvent(validFilename, EventAction.ADD.toString()); Assert.assertNull(event); Mockito.verify(zone, Mockito.times(0)).reportEvent(Mockito.eq(event)); }
@Test public void testReportEventInvalidFile() throws ADKException { String invalidFilename = "doesntexist.xml"; Event event = eventReporter.reportEvent(invalidFilename, EventAction.ADD.toString()); Assert.assertNull(event); Mockito.verify(zone, Mockito.times(0)).reportEvent(Mockito.eq(event)); }
|
CharacterBlacklistStrategy extends AbstractBlacklistStrategy { @Override public boolean isValid(String context, String input) { if (input == null) { return false; } for (char c : input.toCharArray()) { if (characterSet.contains(c)) { return false; } } return true; } CharacterBlacklistStrategy(); @Override boolean isValid(String context, String input); }
|
@Test public void testIsValid() { AbstractBlacklistStrategy strategy = new CharacterBlacklistStrategy(); List<String> badStringList = createBadStringList(); List<Character> badCharList = createCharacterListFromStringList(badStringList); strategy.setInputCollection(badStringList); strategy.init(); runTestLoop(badCharList, strategy, false); List<String> goodStringList = createGoodStringList(); List<Character> goodCharList = createCharacterListFromStringList(goodStringList); runTestLoop(goodCharList, strategy, true); }
|
RegexBlacklistStrategy extends AbstractBlacklistStrategy { @Override public boolean isValid(String context, String input) { if (input == null) { return false; } for (Pattern pattern : patternList) { Matcher matcher = pattern.matcher(input); if (matcher.find()) { return false; } } return true; } RegexBlacklistStrategy(); @Override boolean isValid(String context, String input); }
|
@Test public void testIsValid() { AbstractBlacklistStrategy strategy = new RegexBlacklistStrategy(); List<String> badRegexStringList = createBadRegexStringList(); strategy.setInputCollection(badRegexStringList); strategy.init(); List<String> badStringList = createBadStringList(); runTestLoop(badStringList, strategy, false); List<String> goodStringList = createGoodStringList(); runTestLoop(goodStringList, strategy, true); }
|
SelfReferenceExtractor { public String getSelfReferenceFields(Entity entity) { String selfReferenceField = null; NeutralSchema schema = entitySchemaRegistry.getSchema(entity.getType()); if (schema != null) { AppInfo appInfo = schema.getAppInfo(); if (appInfo != null) { selfReferenceField = getSelfReferenceFields(schema, ""); } } return selfReferenceField; } String getSelfReferenceFields(Entity entity); Map<String, NeutralSchema> getSchemaFields(NeutralSchema schema); }
|
@Test public void testGetSelfReferenceFields() { Entity srEntity = Mockito.mock(Entity.class); Mockito.when(srEntity.getType()).thenReturn(SELF_REFERENCE_COLLECTION); Entity nonSrEntity = Mockito.mock(Entity.class); Mockito.when(nonSrEntity.getType()).thenReturn(NON_SELF_REFERENCE_COLLECTION); String selfReferenceField = selfReferenceExtractor.getSelfReferenceFields(srEntity); Assert.assertEquals("field2", selfReferenceField); selfReferenceField = selfReferenceExtractor.getSelfReferenceFields(nonSrEntity); Assert.assertEquals(null, selfReferenceField); }
|
TokenSchema extends NeutralSchema { @Override protected boolean validate(String fieldName, Object entity, List<ValidationError> errors, Repository<Entity> repo) { return addError(this.matchesToken(entity), fieldName, entity, getQuotedTokens(), ErrorType.ENUMERATION_MISMATCH, errors); } TokenSchema(); TokenSchema(String xsdType); @Override NeutralSchemaType getSchemaType(); @Override boolean isPrimitive(); @Override Object convert(Object value); static final String TOKENS; }
|
@Test public void testTokenValidation() throws IllegalArgumentException { List<String> tokens = new ArrayList<String>(); tokens.add("validToken"); schema.getProperties().put(TokenSchema.TOKENS, tokens); String tokenEntity = "validToken"; assertTrue("Token entity validation failed", schema.validate(tokenEntity)); }
@Test public void testTokenValidationFailure() throws IllegalArgumentException { List<String> tokens = new ArrayList<String>(); tokens.add("validToken"); schema.getProperties().put(TokenSchema.TOKENS, tokens); String tokenEntity = "invalidToken"; assertFalse("Expected TokenSchema invalid token validation failure did not succeed", schema.validate(tokenEntity)); }
@Test public void testValidationOfBooleanFailure() { Boolean booleanEntity = true; assertFalse("Expected TokenSchema boolean validation failure did not succeed", schema.validate(booleanEntity)); }
@Test public void testValidationOfIntegerFailure() { Integer integerEntity = 0; assertFalse("Expected TokenSchema integer validation failure did not succeed", schema.validate(integerEntity)); }
@Test public void testValidationOfFloatFailure() { Float floatEntity = new Float(0); assertFalse("Expected TokenSchema float validation failure did not succeed", schema.validate(floatEntity)); }
|
EntityDateHelper { public static String retrieveDate(Entity entity) { return (String) entity.getBody().get(EntityDates.ENTITY_DATE_FIELDS.get(entity.getType())); } static boolean shouldExtract(Entity entity, DateTime upToDate); static String retrieveDate(Entity entity); static boolean isPastOrCurrentDate(String entityDate, DateTime upToDate, String type); }
|
@Test public void testRetrieveDate() { Map<String, Object> body = new HashMap<String, Object>(); body.put(ParameterConstants.BEGIN_DATE, "01-01-01"); Entity studentProgramAssociation = new MongoEntity(EntityNames.STUDENT_PROGRAM_ASSOCIATION, body); Assert.assertEquals("01-01-01", EntityDateHelper.retrieveDate(studentProgramAssociation)); }
|
IDMapper extends Mapper<T, BSONWritable, T, BSONWritable> { @Override public void map(T id, BSONWritable entity, Context context) throws IOException, InterruptedException { for (String field : idFields.values()) { BSONUtilities.removeField(entity, field); } context.write(id, entity); } @Override void map(T id, BSONWritable entity, Context context); }
|
@SuppressWarnings("unchecked") @Test public void testMapIdFieldKey() throws Exception { String[] fields = { "data.element.id" }; BSONObject elem = new BasicBSONObject("value", 7631); BSONObject data = new BasicBSONObject("element", elem); BSONObject entry = new BasicBSONObject("data", data); final BSONWritable entity = new BSONWritable(entry); IDMapper<IdFieldEmittableKey> mapper = new IDMapper<IdFieldEmittableKey>(); IDMapper<IdFieldEmittableKey>.Context context = Mockito.mock(IDMapper.Context.class); PowerMockito.when(context, "write", Matchers.any(EmittableKey.class), Matchers.any(BSONObject.class)).thenAnswer(new Answer<BSONObject>() { @Override public BSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); assertNotNull(args); assertEquals(args.length, 2); assertTrue(args[0] instanceof IdFieldEmittableKey); assertTrue(args[1] instanceof BSONWritable); IdFieldEmittableKey id = (IdFieldEmittableKey) args[0]; assertEquals(id.getIdField().toString(), "data.element.id"); Text idValue = id.getId(); assertEquals(Long.parseLong(idValue.toString()), 3697); BSONWritable e = (BSONWritable) args[1]; assertEquals(e, entity); return null; } }); IdFieldEmittableKey id = new IdFieldEmittableKey(); id.setFieldNames(fields); id.setId(new Text("3697")); mapper.map(id, entity, context); }
@SuppressWarnings("unchecked") @Test public void testMapTenantAndIdKey() throws Exception { String[] fields = { "metaData.tenantId", "data.element.id" }; BSONObject elem = new BasicBSONObject("value", 7632); BSONObject data = new BasicBSONObject("element", elem); BSONObject entry = new BasicBSONObject("data", data); final BSONWritable entity = new BSONWritable(entry); BSONObject tenantId = new BasicBSONObject("EdOrgs", "Midtown"); entity.put("metaData", tenantId); IDMapper<TenantAndIdEmittableKey> mapper = new IDMapper<TenantAndIdEmittableKey>(); IDMapper<TenantAndIdEmittableKey>.Context context = Mockito.mock(IDMapper.Context.class); PowerMockito.when(context, "write", Matchers.any(EmittableKey.class), Matchers.any(BSONObject.class)).thenAnswer(new Answer<BSONObject>() { @Override public BSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); assertNotNull(args); assertEquals(args.length, 2); assertTrue(args[0] instanceof TenantAndIdEmittableKey); assertTrue(args[1] instanceof BSONObject); TenantAndIdEmittableKey id = (TenantAndIdEmittableKey) args[0]; assertEquals(id.getIdField().toString(), "data.element.id"); Text idValue = id.getId(); assertEquals(Long.parseLong(idValue.toString()), 90210); assertEquals(id.getTenantIdField().toString(), "metaData.tenantId"); idValue = id.getTenantId(); assertEquals(idValue.toString(), "Midgar"); BSONObject e = (BSONObject) args[1]; assertEquals(e, entity); return null; } }); TenantAndIdEmittableKey id = new TenantAndIdEmittableKey(); id.setFieldNames(fields); id.setTenantId(new Text("Midgar")); id.setId(new Text("90210")); mapper.map(id, entity, context); }
|
ReferenceSchema extends NeutralSchema { @Override protected boolean validate(String fieldName, Object entity, List<ValidationError> errors, Repository<Entity> repo) { boolean isValidReference = isValidReference(entity); if (!addError(isValidReference, fieldName, entity, "String", ErrorType.INVALID_DATATYPE, errors)) { return false; } boolean found = false; String collectionType = getEntityType(); try { found = repo.exists(collectionType, (String) entity); } catch (Exception e) { LOG.error("Exception when looking up reference in repository. ", e); } if (!found) { LOG.debug("Broken reference in {}, {}, {}", new Object[] { entity, fieldName, errors }); addError(false, fieldName, entity, "Valid reference", ErrorType.REFERENTIAL_INFO_MISSING, errors); return false; } return true; } ReferenceSchema(String xsdType, SchemaRepository schemaRepository); @Override NeutralSchemaType getSchemaType(); String getEntityType(); @Override Object convert(Object value); }
|
@Test public void testReferenceValidation() throws IllegalArgumentException { List<ValidationError> errors = new ArrayList<ValidationError>(); assertTrue("Reference entity validation failed", spySchema.validate(REFERENCE_FIELDNAME, UUID, errors, repo)); }
@Test public void testInvalidReferenceValidation() throws IllegalArgumentException { List<ValidationError> errors = new ArrayList<ValidationError>(); assertFalse("Invalid Reference entity validation failed", spySchema.validate(REFERENCE_FIELDNAME, "45679", errors, repo)); }
@Test public void testNullReferenceValidation() throws IllegalArgumentException { List<ValidationError> errors = new ArrayList<ValidationError>(); assertFalse("Null reference should not be valid", spySchema.validate(REFERENCE_FIELDNAME, null, errors, repo)); }
@Test public void testNonStringReferenceValidation() throws IllegalArgumentException { List<ValidationError> errors = new ArrayList<ValidationError>(); assertFalse("Non-string reference should not be valid", spySchema.validate(REFERENCE_FIELDNAME, new Integer(0), errors, repo)); }
@Test public void testEmptyStringReferenceValidation() throws IllegalArgumentException { List<ValidationError> errors = new ArrayList<ValidationError>(); assertFalse("Non-string reference should not be valid", spySchema.validate(REFERENCE_FIELDNAME, "", errors, repo)); }
|
LongSchema extends PrimitiveNumericSchema<Long> { @Override public Object convert(Object value) { if (value instanceof Integer) { return ((Integer) value).longValue(); } else if (value instanceof Long) { return (Long) value; } else if (value instanceof String) { try { return Long.parseLong((String) value); } catch (NumberFormatException nfe) { throw (IllegalArgumentException) new IllegalArgumentException(value + " cannot be parsed to a long").initCause(nfe); } } throw new IllegalArgumentException(value + " is not a long"); } LongSchema(); @Override Object convert(Object value); }
|
@Test public void testConvert() throws Exception { long value = 10L; Object convertedValue = this.schema.convert("" + value); assertTrue(convertedValue instanceof Long); Long convertedInput = (Long) convertedValue; assertTrue(convertedInput.longValue() == value); }
@Test(expected = IllegalArgumentException.class) public void testBadConvert() { this.schema.convert("INVALID INPUT"); }
@Test public void testNonConvert() { Object convertedValue = this.schema.convert(12345L); assertTrue(convertedValue instanceof Long); }
@Test public void testLongConverter() { long data = 12345L; int intData = (int) data; assertTrue("Failure returning same object", this.schema.convert(data).equals(data)); assertTrue("Failure parsing long from integer", this.schema.convert(intData).equals(data)); assertTrue("Failure parsing long data", this.schema.convert("" + data).equals(data)); }
@Test(expected = IllegalArgumentException.class) public void testInvalidStringThrowsException() throws IllegalArgumentException { this.schema.convert("INVALID INPUT"); }
@Test(expected = IllegalArgumentException.class) public void testUnsupportedObjectTypeThrowsException() throws IllegalArgumentException { this.schema.convert(new Object()); }
|
EntityDateHelper { public static boolean isPastOrCurrentDate(String entityDate, DateTime upToDate, String type) { DateTime finalUpToDate = (upToDate == null) ? DateTime.now() : upToDate; if (YEAR_BASED_ENTITIES.contains(type)) { return isBeforeOrEqualYear(entityDate, finalUpToDate.year().get()); } else { return isBeforeOrEqualDate(entityDate, finalUpToDate); } } static boolean shouldExtract(Entity entity, DateTime upToDate); static String retrieveDate(Entity entity); static boolean isPastOrCurrentDate(String entityDate, DateTime upToDate, String type); }
|
@Test public void testIsPastOrCurrentDateWithDate() { Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2010-05-23", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.DISCIPLINE_INCIDENT)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2011-05-23", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.DISCIPLINE_INCIDENT)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate(null, DateTime.now(), EntityNames.DISCIPLINE_INCIDENT)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2012-11-11", DateTime.parse("2012-11-11T00:00:00"), EntityNames.DISCIPLINE_INCIDENT)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2012-11-11", DateTime.parse("2012-11-11T23:59:59.999"), EntityNames.DISCIPLINE_INCIDENT)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate(null, DateTime.now().minusMillis(1), EntityNames.DISCIPLINE_INCIDENT)); DateTimeFormatter datefrmt = new DateTimeFormatterBuilder().appendYear(4, 4).appendLiteral('-').appendMonthOfYear(2).appendLiteral('-').appendDayOfMonth(2).toFormatter(); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate(datefrmt.print(DateTime.now().plusDays(1)), DateTime.now(), EntityNames.DISCIPLINE_INCIDENT)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate(null, DateTime.now().minusDays(1), EntityNames.DISCIPLINE_INCIDENT)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate(null, DateTime.parse("2012-11-11"), EntityNames.DISCIPLINE_INCIDENT)); }
@Test public void testIsPastOrCurrentDateWithYear() { DateTime dt = DateTime.now(); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2009-2010", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2010-2011", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate((DateTime.now().getYear() - 1) + "-" + DateTime.now().getYear(), null, EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate("2011-2012", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate("2012-2013", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate(DateTime.now().getYear() + "-" + (DateTime.now().getYear() + 1), null, EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate(dt.getYear()-1 + "-" + dt.getYear(), null, EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate(dt.getYear() + "-" + dt.getYear() + 1, null, EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate("2011-2012", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate("2012-2013", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2010-2009", DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()), EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate("2009-2010", new DateTime(2008, 1, 31, 9, 0), EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate("2009-2010", new DateTime(2009, 1, 1, 0, 0).minusMillis(1), EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate("2009-2010", new DateTime(2010, 1, 1, 0, 0).minusMillis(1), EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2009-2010", new DateTime(2010, 1, 1, 0, 0), EntityNames.GRADE)); Assert.assertFalse(EntityDateHelper.isPastOrCurrentDate("2010-2011", new DateTime(2009, 1, 31, 9, 0), EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2009-2010", new DateTime(2010, 1, 31, 9, 0), EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2007-2008", new DateTime(2010, 1, 1, 0, 0), EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2008-2009", new DateTime(2010, 1, 1, 0, 0), EntityNames.GRADE)); Assert.assertTrue(EntityDateHelper.isPastOrCurrentDate("2009-2010", new DateTime(2010, 1, 1, 0, 0), EntityNames.GRADE)); }
|
StringSchema extends NeutralSchema { @Override protected boolean validate(String fieldName, Object entity, List<ValidationError> errors, Repository<Entity> repo) { if (!addError(String.class.isInstance(entity), fieldName, entity, "String", ErrorType.INVALID_DATATYPE, errors)) { return false; } String data = (String) entity; if (this.getProperties() != null) { for (Entry<String, Object> entry : this.getProperties().entrySet()) { if (Restriction.isRestriction(entry.getKey())) { String restrictionValue = (String) entry.getValue(); switch (Restriction.fromValue(entry.getKey())) { case PATTERN: if (!addError(data.matches(restrictionValue), fieldName, entity, "pattern=" + restrictionValue, ErrorType.INVALID_VALUE, errors)) { return false; } break; case LENGTH: if (!addError(data.length() == Integer.parseInt(restrictionValue), fieldName, entity, "length=" + restrictionValue, ErrorType.INVALID_VALUE, errors)) { return false; } break; case MIN_LENGTH: if (!addError(data.length() >= Integer.parseInt(restrictionValue), fieldName, entity, "min-length=" + restrictionValue, ErrorType.INVALID_VALUE, errors)) { return false; } break; case MAX_LENGTH: if (!addError(data.length() <= Integer.parseInt(restrictionValue), fieldName, entity, "max-length=" + restrictionValue, ErrorType.INVALID_VALUE, errors)) { return false; } break; } } } } if (isRelaxedBlacklisted()) { for (AbstractBlacklistStrategy validationRule : relaxedValidationRuleList) { boolean isValid = validationRule.isValid("StringSchemaContext", data); if (!addError(isValid, fieldName, entity, "Invalid value caught by relaxed blacklisting strategy: " + validationRule.getIdentifier(), ErrorType.INVALID_VALUE, errors)) { return false; } } } else { for (AbstractBlacklistStrategy validationRule : validationRuleList) { boolean isValid = validationRule.isValid("StringSchemaContext", data); if (!addError(isValid, fieldName, entity, "Invalid value caught by strict blacklisting strategy: " + validationRule.getIdentifier(), ErrorType.INVALID_VALUE, errors)) { return false; } } } return true; } StringSchema(); StringSchema(String xsdType); StringSchema(List<AbstractBlacklistStrategy> validationRuleList, List<AbstractBlacklistStrategy> relaxedValidationRuleList); StringSchema(String xsdType, List<AbstractBlacklistStrategy> validationRuleList, List<AbstractBlacklistStrategy> relaxedValidationRuleList); @Override NeutralSchemaType getSchemaType(); @Override Object convert(Object value); }
|
@Test public void testStringValidation() throws IllegalArgumentException { String stringEntity = "test"; assertTrue("String entity validation failed", schema.validate(stringEntity)); }
@Test public void testValidationOfBooleanFailure() { Boolean booleanEntity = true; assertFalse("Expected StringSchema boolean validation failure did not succeed", schema.validate(booleanEntity)); }
@Test public void testValidationOfIntegerFailure() { Integer integerEntity = 0; assertFalse("Expected StringSchema integer validation failure did not succeed", schema.validate(integerEntity)); }
@Test public void testValidationOfFloatFailure() { Float floatEntity = new Float(0); assertFalse("Expected StringSchema float validation failure did not succeed", schema.validate(floatEntity)); }
@Test public void testRestrictions() { schema.getProperties().put(Restriction.MIN_LENGTH.getValue(), "2"); schema.getProperties().put(Restriction.MAX_LENGTH.getValue(), "4"); assertTrue(schema.validate("12")); assertTrue(schema.validate("1234")); assertFalse(schema.validate("1")); assertFalse(schema.validate("12345")); schema.getProperties().put(Restriction.LENGTH.getValue(), "4"); assertTrue(schema.validate("1234")); assertFalse(schema.validate("123")); assertFalse(schema.validate("12345")); }
@Test public void testStrictBlacklist() { AppInfo info = Mockito.mock(AppInfo.class); Mockito.when(info.isRelaxedBlacklisted()).thenReturn(false); Mockito.when(info.getType()).thenReturn(AnnotationType.APPINFO); AbstractBlacklistStrategy mockStrictStrategy = Mockito.mock(AbstractBlacklistStrategy.class); Mockito.when(mockStrictStrategy.isValid(Mockito.anyString(), Mockito.eq("input1"))).thenReturn(true); Mockito.when(mockStrictStrategy.isValid(Mockito.anyString(), Mockito.eq("input2"))).thenReturn(false); AbstractBlacklistStrategy mockRelaxedStrategy = Mockito.mock(AbstractBlacklistStrategy.class); Mockito.when(mockRelaxedStrategy.isValid(Mockito.anyString(), Mockito.eq("input2"))).thenReturn(true); Mockito.when(mockRelaxedStrategy.isValid(Mockito.anyString(), Mockito.eq("input1"))).thenReturn(false); List<AbstractBlacklistStrategy> strictList = new ArrayList<AbstractBlacklistStrategy>(); strictList.add(mockStrictStrategy); List<AbstractBlacklistStrategy> relaxedList = new ArrayList<AbstractBlacklistStrategy>(); relaxedList.add(mockRelaxedStrategy); StringSchema testSchema = new StringSchema("string", strictList, relaxedList); testSchema.addAnnotation(info); assertFalse("Error in setup, schema should not be relax-blacklisted", testSchema.isRelaxedBlacklisted()); boolean isValid = testSchema.validate("input1"); assertTrue("Based on strict strategy, input1 should have passed validation", isValid); isValid = testSchema.validate("input2"); assertFalse("Based on strict strategy, input2 should have failed validation", isValid); Mockito.verify(mockRelaxedStrategy, Mockito.times(0)).isValid(Mockito.anyString(), Mockito.anyString()); Mockito.verify(mockStrictStrategy, Mockito.times(2)).isValid(Mockito.anyString(), Mockito.anyString()); }
@Test public void testRelaxedBlacklist() { AppInfo info = Mockito.mock(AppInfo.class); Mockito.when(info.isRelaxedBlacklisted()).thenReturn(true); Mockito.when(info.getType()).thenReturn(AnnotationType.APPINFO); AbstractBlacklistStrategy mockStrictStrategy = Mockito.mock(AbstractBlacklistStrategy.class); Mockito.when(mockStrictStrategy.isValid(Mockito.anyString(), Mockito.eq("input1"))).thenReturn(true); Mockito.when(mockStrictStrategy.isValid(Mockito.anyString(), Mockito.eq("input2"))).thenReturn(false); AbstractBlacklistStrategy mockRelaxedStrategy = Mockito.mock(AbstractBlacklistStrategy.class); Mockito.when(mockRelaxedStrategy.isValid(Mockito.anyString(), Mockito.eq("input2"))).thenReturn(true); Mockito.when(mockRelaxedStrategy.isValid(Mockito.anyString(), Mockito.eq("input1"))).thenReturn(false); List<AbstractBlacklistStrategy> strictList = new ArrayList<AbstractBlacklistStrategy>(); strictList.add(mockStrictStrategy); List<AbstractBlacklistStrategy> relaxedList = new ArrayList<AbstractBlacklistStrategy>(); relaxedList.add(mockRelaxedStrategy); StringSchema testSchema = new StringSchema("string", strictList, relaxedList); testSchema.addAnnotation(info); assertTrue("Error in setup, schema should be relax-blacklisted", testSchema.isRelaxedBlacklisted()); boolean isValid = testSchema.validate("input1"); assertFalse("Based on relaxed strategy, input1 should have failed validation", isValid); isValid = testSchema.validate("input2"); assertTrue("Based on relaxed strategy, input2 should have passed validation", isValid); Mockito.verify(mockRelaxedStrategy, Mockito.times(2)).isValid(Mockito.anyString(), Mockito.anyString()); Mockito.verify(mockStrictStrategy, Mockito.times(0)).isValid(Mockito.anyString(), Mockito.anyString()); }
|
ChoiceSchema extends NeutralSchema { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected boolean validate(String fieldName, Object entity_in, List<ValidationError> errors, Repository<Entity> repo) { Object entity = entity_in; if (entity instanceof Set) { entity = new ArrayList<Object>((Set) entity); } if (getMaxOccurs() == 1) { if (getMinOccurs() == 0 && entity == null) { return true; } if (!(entity instanceof Map)) { return addError(false, fieldName, entity, "Map", ErrorType.INVALID_DATATYPE, errors); } Map<?, ?> datum = (Map<?, ?>) entity; if (datum.size() != 1) { return addError(false, fieldName, entity, "Single Entry", ErrorType.INVALID_DATATYPE, errors); } Entry<?, ?> datumValue = datum.entrySet().iterator().next(); if (!(datumValue.getKey() instanceof String)) { return addError(false, fieldName, entity, this.getFields().keySet().toArray(new String[0]), ErrorType.INVALID_CHOICE_TYPE, errors); } String key = (String) datumValue.getKey(); Object value = datumValue.getValue(); NeutralSchema fieldSchema = this.getFields().get(key); if (fieldSchema == null) { return addError(false, fieldName, entity, this.getFields().keySet().toArray(new String[0]), ErrorType.INVALID_CHOICE_TYPE, errors); } if (fieldSchema.validate(key, value, errors, repo)) { return true; } } else if (getMaxOccurs() > 1) { if (!(entity instanceof List)) { return addError(false, fieldName, entity, "List", ErrorType.INVALID_DATATYPE, errors); } if (((List) entity).size() < getMinOccurs()) { return addError(false, fieldName, entity, "min-length=" + this.getMinOccurs(), ErrorType.INVALID_VALUE, errors); } else if (((List) entity).size() > getMaxOccurs()) { return addError(false, fieldName, entity, "max-length=" + this.getMinOccurs(), ErrorType.INVALID_VALUE, errors); } List<Object> data = (List<Object>) entity; for (Object uncastedDatum : data) { if (!(uncastedDatum instanceof Map)) { return addError(false, fieldName, entity, "Map", ErrorType.INVALID_DATATYPE, errors); } Map<?, ?> datum = (Map<?, ?>) uncastedDatum; if (datum.size() != 1) { return addError(false, fieldName, entity, "Single Entry", ErrorType.INVALID_DATATYPE, errors); } Entry<?, ?> datumValue = datum.entrySet().iterator().next(); if (!(datumValue.getKey() instanceof String)) { return addError(false, fieldName, entity, this.getFields().keySet().toArray(new String[0]), ErrorType.INVALID_CHOICE_TYPE, errors); } String key = (String) datumValue.getKey(); Object value = datumValue.getValue(); NeutralSchema fieldSchema = this.getFields().get(key); if (fieldSchema == null) { return addError(false, fieldName, entity, this.getFields().keySet().toArray(new String[0]), ErrorType.INVALID_CHOICE_TYPE, errors); } if (!fieldSchema.validate(key, value, errors, repo)) { return false; } } return true; } return false; } ChoiceSchema(long minOccurs, long maxOccurs); ChoiceSchema(String name); void setMinOccurs(long i); void setMaxOccurs(long i); long getMinOccurs(); long getMaxOccurs(); @Override NeutralSchemaType getSchemaType(); @Override boolean isPrimitive(); @Override boolean isSimple(); static final long UNBOUNDED; }
|
@Test public void testRequiredValue() { ChoiceSchema choice = new ChoiceSchema(1, 1); choice.addField("aString", new StringSchema()); choice.addField("aLong", new LongSchema()); choice.addField("aDouble", new DoubleSchema()); Map<String, Object> data = new HashMap<String, Object>(); data.put("aString", "abc"); assertTrue(choice.validate(data)); data.put("aLong", 1L); assertFalse(choice.validate(data)); data.remove("aString"); assertTrue(choice.validate(data)); data.put("aLong", "abc"); assertFalse(choice.validate(data)); }
@Test public void testListValue() { ChoiceSchema choice = new ChoiceSchema(1, 5); choice.addField("aString", new StringSchema()); choice.addField("aLong", new LongSchema()); choice.addField("aDouble", new DoubleSchema()); List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); assertFalse(choice.validate(data)); data.add(createMap("aString", "abc")); assertTrue(choice.validate(data)); data.add(createMap("aLong", 1L)); assertTrue(choice.validate(data)); data.add(createMap("aDouble", 1.0D)); assertTrue(choice.validate(data)); data.add(createMap("aString", "def")); assertTrue(choice.validate(data)); data.add(createMap("invalid", "abc")); assertFalse(choice.validate(data)); data.remove(data.size() - 1); data.add(createMap("aString", "hij")); assertTrue(choice.validate(data)); data.add(createMap("aString", "hij")); assertFalse(choice.validate(data)); }
@Test public void testComplexSchemas() { ComplexSchema c1 = new ComplexSchema(); c1.addField("s1", new StringSchema()); c1.addField("l1", new LongSchema()); ComplexSchema c2 = new ComplexSchema(); c2.addField("s2", new StringSchema()); c2.addField("l2", new LongSchema()); ChoiceSchema choice = new ChoiceSchema(0, 1); choice.addField("c1", c1); choice.addField("c2", c2); choice.addField("s3", new StringSchema()); Map<String, Object> c1data = new HashMap<String, Object>(); c1data.put("s1", "abc"); c1data.put("l1", 1L); Map<String, Object> c2data = new HashMap<String, Object>(); c2data.put("s2", "efg"); c2data.put("l2", 1L); assertTrue(choice.validate(createMap("s3", "abc"))); assertTrue(choice.validate(createMap("c1", c1data))); assertTrue(choice.validate(createMap("c2", c2data))); assertFalse(choice.validate(createMap("c2", "abc"))); assertFalse(choice.validate(createMap("s3", c1data))); assertFalse(choice.validate(createMap("c1", c2data))); }
|
DateTimeSchema extends NeutralSchema { protected boolean validate(String fieldName, Object entity, List<ValidationError> errors, Repository<Entity> repo) { boolean isValid; try { javax.xml.bind.DatatypeConverter.parseDateTime((String) entity); isValid = true; } catch (IllegalArgumentException e2) { isValid = false; } return addError(isValid, fieldName, entity, "RFC 3339 DateTime", ErrorType.INVALID_DATE_FORMAT, errors); } DateTimeSchema(); DateTimeSchema(String xsdType); @Override NeutralSchemaType getSchemaType(); @Override Object convert(Object value); }
|
@Test public void testDateTimeStringValidation() throws IllegalArgumentException { String dateTimeString = "2012-01-01T12:00:00-05:00"; assertTrue("DateTime entity validation failed", schema.validate(dateTimeString)); }
@Test public void testDateTimeValidation() { Calendar calendar = Calendar.getInstance(); String dateTimeString = javax.xml.bind.DatatypeConverter.printTime(calendar); assertTrue("DateTime entity validation failed", schema.validate(dateTimeString)); }
@Test public void testValidationOfStringFailure() { String stringEntity = ""; assertFalse("Expected DateTimeSchema string validation failure did not succeed", schema.validate(stringEntity)); }
|
NaturalKeyExtractor implements INaturalKeyExtractor { @Override public Map<String, Boolean> getNaturalKeyFields(Entity entity) throws NoNaturalKeysDefinedException { Map<String, Boolean> naturalKeyFields = null; NeutralSchema schema = entitySchemaRegistry.getSchema(entity.getType()); if (schema != null) { AppInfo appInfo = schema.getAppInfo(); if (appInfo != null) { if (appInfo.applyNaturalKeys()) { naturalKeyFields = new HashMap<String, Boolean>(); getNaturalKeyFields(naturalKeyFields, schema, false, ""); if (naturalKeyFields.isEmpty()) { LOG.error("Failed to find natural key definitions for the " + entity.getType() + " entity"); throw new NoNaturalKeysDefinedException(entity.getType()); } } } } return naturalKeyFields; } @Override Map<String, String> getNaturalKeys(Entity entity); @Override Map<String, Boolean> getNaturalKeyFields(Entity entity); @Override NaturalKeyDescriptor getNaturalKeyDescriptor(Entity entity); String getCollectionName(Entity entity); }
|
@Test public void testGetNaturalKeyFields() throws NoNaturalKeysDefinedException { Entity e = setup(); Map<String, Boolean> naturalKeyFields = naturalKeyExtractor.getNaturalKeyFields(e); Assert.assertEquals(1, naturalKeyFields.size()); Assert.assertEquals("someField", naturalKeyFields.entrySet().iterator().next().getKey()); Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString()); }
|
NaturalKeyExtractor implements INaturalKeyExtractor { @Override public NaturalKeyDescriptor getNaturalKeyDescriptor(Entity entity) throws NoNaturalKeysDefinedException { Map<String, String> map = getNaturalKeys(entity); if (map == null) { NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(); naturalKeyDescriptor.setNaturalKeysNotNeeded(true); return naturalKeyDescriptor; } String entityType = getCollectionName(entity); String tenantId = TenantContext.getTenantId(); String parentId = retrieveParentId(entity); NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(map, tenantId, entityType, parentId); return naturalKeyDescriptor; } @Override Map<String, String> getNaturalKeys(Entity entity); @Override Map<String, Boolean> getNaturalKeyFields(Entity entity); @Override NaturalKeyDescriptor getNaturalKeyDescriptor(Entity entity); String getCollectionName(Entity entity); }
|
@Test public void testGetNaturalKeyDescriptor() throws NoNaturalKeysDefinedException { Entity e = setup(); TenantContext.setTenantId("someTenant"); NaturalKeyDescriptor desc = naturalKeyExtractor.getNaturalKeyDescriptor(e); Map<String, String> naturalKeys = desc.getNaturalKeys(); Assert.assertEquals(COLLECTION_TYPE, desc.getEntityType()); Assert.assertEquals("someTenant", desc.getTenantId()); Assert.assertEquals(1, naturalKeys.size()); Assert.assertEquals("someValue", naturalKeys.get("someField")); Mockito.verify(entitySchemaRegistry, Mockito.times(2)).getSchema(Mockito.anyString()); }
|
NaturalKeyExtractor implements INaturalKeyExtractor { @Override public Map<String, String> getNaturalKeys(Entity entity) throws NoNaturalKeysDefinedException { Map<String, String> map = new HashMap<String, String>(); List<String> missingKeys = new ArrayList<String>(); Map<String, Boolean> naturalKeyFields = getNaturalKeyFields(entity); if (naturalKeyFields == null) { return null; } for (Entry<String, Boolean> keyField : naturalKeyFields.entrySet()) { Object value = null; try { value = PropertyUtils.getProperty(entity.getBody(), keyField.getKey()); } catch (IllegalAccessException e) { handleFieldAccessException(keyField.getKey(), entity); } catch (InvocationTargetException e) { handleFieldAccessException(keyField.getKey(), entity); } catch (NoSuchMethodException e) { handleFieldAccessException(keyField.getKey(), entity); } if (value == null) { if (keyField.getValue().booleanValue()) { map.put(keyField.getKey(), ""); } else { missingKeys.add(keyField.getKey()); } } else { String strValue = value.toString(); map.put(keyField.getKey(), strValue); } } if (!missingKeys.isEmpty()) { throw new NaturalKeyValidationException(entity.getType(), missingKeys); } return map; } @Override Map<String, String> getNaturalKeys(Entity entity); @Override Map<String, Boolean> getNaturalKeyFields(Entity entity); @Override NaturalKeyDescriptor getNaturalKeyDescriptor(Entity entity); String getCollectionName(Entity entity); }
|
@Test public void testGetNaturalKeys() throws NoNaturalKeysDefinedException { Entity e = setup(); Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e); Assert.assertEquals(1, naturalKeys.size()); Assert.assertEquals("someValue", naturalKeys.get("someField")); Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString()); }
@Test(expected = NaturalKeyValidationException.class) public void shouldThrowExceptionWhenMissingRequiredKeyField() throws NoNaturalKeysDefinedException { Entity e = setup(); e.getBody().remove("someField"); @SuppressWarnings("unused") Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e); }
@Test public void shouldNotThrowExceptionWhenMissingOptionalKeyField() throws NoNaturalKeysDefinedException { Entity e = setup(); AppInfo mockAppInfo = Mockito.mock(AppInfo.class); Mockito.when(mockAppInfo.applyNaturalKeys()).thenReturn(true); Mockito.when(mockAppInfo.getType()).thenReturn(AnnotationType.APPINFO); mockSchema.addAnnotation(mockAppInfo); NeutralSchema mockFieldSchema = Mockito.mock(NeutralSchema.class); mockSchema.addField("optionalField", mockFieldSchema); AppInfo mockFieldAppInfo = Mockito.mock(AppInfo.class); Mockito.when(mockFieldSchema.getAppInfo()).thenReturn(mockFieldAppInfo); Mockito.when(mockFieldAppInfo.isNaturalKey()).thenReturn(true); Mockito.when(mockFieldAppInfo.isRequired()).thenReturn(false); Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e); Assert.assertEquals(2, naturalKeys.size()); Assert.assertEquals("someValue", naturalKeys.get("someField")); Assert.assertEquals("", naturalKeys.get("optionalField")); Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString()); }
@Test public void shouldExtractNestedKeyField() throws NoNaturalKeysDefinedException { Entity e = setup(); Map<String, String> parentValue = new HashMap<String, String>(); parentValue.put("childField", "someNestedValue"); e.getBody().put("parentField", parentValue); AppInfo mockAppInfo = Mockito.mock(AppInfo.class); Mockito.when(mockAppInfo.applyNaturalKeys()).thenReturn(true); Mockito.when(mockAppInfo.getType()).thenReturn(AnnotationType.APPINFO); mockSchema.addAnnotation(mockAppInfo); ComplexSchema parentFieldSchema = new ComplexSchema(); mockSchema.addField("parentField", parentFieldSchema); AppInfo mockAppInfoForParent = Mockito.mock(AppInfo.class); Mockito.when(mockAppInfoForParent.isNaturalKey()).thenReturn(true); Mockito.when(mockAppInfoForParent.getType()).thenReturn(AnnotationType.APPINFO); parentFieldSchema.addAnnotation(mockAppInfoForParent); NeutralSchema mockChildFieldSchema = Mockito.mock(NeutralSchema.class); AppInfo mockFieldAppInfo = Mockito.mock(AppInfo.class); Mockito.when(mockChildFieldSchema.getAppInfo()).thenReturn(mockFieldAppInfo); Mockito.when(mockFieldAppInfo.isNaturalKey()).thenReturn(true); Mockito.when(mockFieldAppInfo.isRequired()).thenReturn(false); parentFieldSchema.addField("childField", mockChildFieldSchema); Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e); Assert.assertEquals(2, naturalKeys.size()); Assert.assertEquals("someValue", naturalKeys.get("someField")); Assert.assertEquals("someNestedValue", naturalKeys.get("parentField.childField")); Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString()); }
@Test public void shouldNotExtractNestedKeyFieldWhenParentFieldIsNotANaturalKey() throws NoNaturalKeysDefinedException { Entity e = setup(); Map<String, String> parentValue = new HashMap<String, String>(); parentValue.put("childField", "someNestedValue"); e.getBody().put("parentField", parentValue); AppInfo mockAppInfo = Mockito.mock(AppInfo.class); Mockito.when(mockAppInfo.applyNaturalKeys()).thenReturn(true); Mockito.when(mockAppInfo.getType()).thenReturn(AnnotationType.APPINFO); mockSchema.addAnnotation(mockAppInfo); ComplexSchema parentFieldSchema = new ComplexSchema(); mockSchema.addField("parentField", parentFieldSchema); AppInfo mockAppInfoForParent = Mockito.mock(AppInfo.class); Mockito.when(mockAppInfoForParent.isNaturalKey()).thenReturn(false); Mockito.when(mockAppInfoForParent.getType()).thenReturn(AnnotationType.APPINFO); parentFieldSchema.addAnnotation(mockAppInfoForParent); NeutralSchema mockChildFieldSchema = Mockito.mock(NeutralSchema.class); AppInfo mockFieldAppInfo = Mockito.mock(AppInfo.class); Mockito.when(mockChildFieldSchema.getAppInfo()).thenReturn(mockFieldAppInfo); Mockito.when(mockFieldAppInfo.isNaturalKey()).thenReturn(true); Mockito.when(mockFieldAppInfo.isRequired()).thenReturn(false); parentFieldSchema.addField("childField", mockChildFieldSchema); Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e); Assert.assertEquals(1, naturalKeys.size()); Assert.assertEquals("someValue", naturalKeys.get("someField")); Assert.assertNull("The nested field should not be extracted", naturalKeys.get("parentField.childField")); Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString()); }
|
EntityDateHelper { protected static boolean isBeforeOrEqualYear(String yearSpan, int upToYear) { int fromYear = Integer.parseInt(yearSpan.split("-")[0]); int toYear = Integer.parseInt(yearSpan.split("-")[1]); return ((upToYear >= toYear) && (upToYear > fromYear)); } static boolean shouldExtract(Entity entity, DateTime upToDate); static String retrieveDate(Entity entity); static boolean isPastOrCurrentDate(String entityDate, DateTime upToDate, String type); }
|
@Test public void testIsBeforeOrEqualYear() { Assert.assertTrue(EntityDateHelper.isBeforeOrEqualYear("2008-2009", 2011)); Assert.assertTrue(EntityDateHelper.isBeforeOrEqualYear("2008-2008", 2011)); Assert.assertTrue(EntityDateHelper.isBeforeOrEqualYear("2009-2008", 2011)); Assert.assertTrue(EntityDateHelper.isBeforeOrEqualYear("2009-2010", 2011)); Assert.assertTrue(EntityDateHelper.isBeforeOrEqualYear("2009-2009", 2011)); Assert.assertTrue(EntityDateHelper.isBeforeOrEqualYear("2010-2009", 2011)); Assert.assertTrue(EntityDateHelper.isBeforeOrEqualYear("2010-2011", 2011)); Assert.assertTrue(EntityDateHelper.isBeforeOrEqualYear("2010-2010", 2011)); Assert.assertFalse(EntityDateHelper.isBeforeOrEqualYear("2011-2010", 2011)); Assert.assertFalse(EntityDateHelper.isBeforeOrEqualYear("2011-2012", 2011)); Assert.assertFalse(EntityDateHelper.isBeforeOrEqualYear("2012-2011", 2011)); Assert.assertFalse(EntityDateHelper.isBeforeOrEqualYear("2012-2013", 2011)); Assert.assertFalse(EntityDateHelper.isBeforeOrEqualYear("2013-2012", 2011)); }
|
NaturalKeyExtractor implements INaturalKeyExtractor { public String getCollectionName(Entity entity) { NeutralSchema schema = entitySchemaRegistry.getSchema(entity.getType()); if (schema != null) { AppInfo appInfo = schema.getAppInfo(); if (appInfo != null) { return appInfo.getCollectionType(); } } LOG.error("No collectionType found in schema for entity: " + entity.getType()); return null; } @Override Map<String, String> getNaturalKeys(Entity entity); @Override Map<String, Boolean> getNaturalKeyFields(Entity entity); @Override NaturalKeyDescriptor getNaturalKeyDescriptor(Entity entity); String getCollectionName(Entity entity); }
|
@Test public void shouldLookupEntityCollection() { Entity e = setup(); AppInfo mockAppInfo = Mockito.mock(AppInfo.class); mockSchema.addAnnotation(mockAppInfo); String collectionName = naturalKeyExtractor.getCollectionName(e); Assert.assertEquals(COLLECTION_TYPE, collectionName); }
|
IntegerSchema extends PrimitiveNumericSchema<Integer> { @Override public Object convert(Object value) { if (value instanceof Integer) { return (Integer) value; } else if (value instanceof String) { try { return Integer.parseInt((String) value); } catch (NumberFormatException nfe) { throw (IllegalArgumentException)new IllegalArgumentException(value + " cannot be parsed to an integer").initCause(nfe); } } throw new IllegalArgumentException(value + " is not an integer"); } IntegerSchema(); @Override Object convert(Object value); }
|
@Test public void testConvert() throws Exception { int value = 12345; Object convertedValue = this.schema.convert("" + value); assertTrue(convertedValue instanceof Integer); Integer convertedInput = (Integer) convertedValue; assertTrue(convertedInput.intValue() == value); }
@Test(expected = IllegalArgumentException.class) public void testBadConvert() { this.schema.convert("INVALID INPUT"); }
@Test public void testNonConvert() { Object convertedValue = this.schema.convert(12); assertTrue(convertedValue instanceof Integer); }
@Test public void testIntegerConverter() { int data = 123; assertTrue("Failure returning same object", this.schema.convert(data).equals(data)); assertTrue("Failure parsing int data", this.schema.convert("" + data).equals(data)); }
@Test(expected = IllegalArgumentException.class) public void testInvalidStringThrowsException() throws IllegalArgumentException { this.schema.convert("INVALID INPUT"); }
@Test(expected = IllegalArgumentException.class) public void testUnsupportedObjectTypeThrowsException() throws IllegalArgumentException { this.schema.convert(new Object()); }
|
SecurityEventUtil implements MessageSourceAware { public SecurityEvent createSecurityEvent(String loggingClass, String actionDesc, LogLevelType logLevel, String appId, BEMessageCode code, Object... args) { SecurityEvent event = new SecurityEvent(); String seAppId = (appId == null) ? "BulkExtract" : "BulkExtract#" + appId; event.setTenantId(TenantContext.getTenantId()); event.setAppId(seAppId); event.setActionUri(actionDesc); event.setTimeStamp(new Date()); event.setProcessNameOrId(ManagementFactory.getRuntimeMXBean().getName()); try { event.setExecutedOn(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { LOG.info("Could not find hostname/process for SecurityEventLogging!"); event.setExecutedOn("localhost"); } event.setClassName(loggingClass); event.setLogLevel(logLevel); event.setLogMessage(messageSource.getMessage(code.getCode(), args, "#?" + code.getCode() + "?#", null)); LOG.debug(event.toString()); return event; } SecurityEvent createSecurityEvent(String loggingClass, String actionDesc, LogLevelType logLevel, String appId, BEMessageCode code, Object... args); SecurityEvent createSecurityEvent(String loggingClass, String actionDesc, LogLevelType logLevel, BEMessageCode code, Object... args); @Override void setMessageSource(MessageSource messageSource); }
|
@Test public void testSEValues() { SecurityEventUtil spyObject = Mockito.spy(securityEventUtil); SecurityEvent event = spyObject.createSecurityEvent("class", "Action Description", LogLevelType.TYPE_INFO, BEMessageCode.BE_SE_CODE_0001); String appId = null; Mockito.verify(spyObject, Mockito.atMost(1)).createSecurityEvent(Mockito.anyString(), Mockito.anyString(), Mockito.eq(LogLevelType.TYPE_INFO), Mockito.eq(appId), Mockito.eq(BEMessageCode.BE_SE_CODE_0001)); assertEquals("BulkExtract", event.getAppId()); String processName = ManagementFactory.getRuntimeMXBean().getName(); assertEquals(processName, event.getProcessNameOrId()); assertEquals(null, event.getTargetEdOrgList()); }
|
BooleanSchema extends PrimitiveSchema { @Override public Object convert(Object value) { if (value instanceof Boolean) { return (Boolean) value; } else if (value instanceof String) { String stringData = (String) value; stringData = stringData.toLowerCase(); if (stringData.equals("true")) { return Boolean.TRUE; } else if (stringData.equals("false")) { return Boolean.FALSE; } else { throw new IllegalArgumentException(stringData + " cannot be parsed to a boolean"); } } throw new IllegalArgumentException(value + " is not a boolean"); } BooleanSchema(); @Override Object convert(Object value); }
|
@Test public void testConvert() throws Exception { boolean value = true; Object convertedValue = this.schema.convert("" + value); assertTrue(convertedValue instanceof Boolean); Boolean convertedInput = (Boolean) convertedValue; assertTrue(convertedInput.booleanValue() == value); }
@Test(expected = IllegalArgumentException.class) public void testInvalidStringThrowsException() throws IllegalArgumentException { this.schema.convert("INVALID INPUT"); }
@Test(expected = IllegalArgumentException.class) public void testUnsupportedObjectTypeThrowsException() throws IllegalArgumentException { this.schema.convert(new Object()); }
@Test public void testBooleanConverter() { assertTrue("Failure returning same object", this.schema.convert(true).equals(Boolean.TRUE)); assertTrue("Failure returning same object", this.schema.convert(false).equals(Boolean.FALSE)); assertTrue("Failure parsing true", this.schema.convert("true").equals(Boolean.TRUE)); assertTrue("Failure parsing false", this.schema.convert("false").equals(Boolean.FALSE)); }
|
DateSchema extends NeutralSchema { @Override protected boolean validate(String fieldName, Object entity, List<ValidationError> errors, Repository<Entity> repo) { boolean isValid; try { javax.xml.bind.DatatypeConverter.parseDate((String) entity); isValid = true; } catch (IllegalArgumentException e2) { isValid = false; } return addError(isValid, fieldName, entity, "RFC 3339 Date", ErrorType.INVALID_DATE_FORMAT, errors); } DateSchema(); DateSchema(String xsdType); @Override NeutralSchemaType getSchemaType(); @Override Object convert(Object value); }
|
@Test public void testDateStringValidation() throws IllegalArgumentException { String dateString = "2012-01-01T12:00:00-05:00"; assertTrue("DateTime entity validation failed", schema.validate(dateString)); }
@Test public void testDateValidation() { Calendar calendar = Calendar.getInstance(); String dateString = javax.xml.bind.DatatypeConverter.printDate(calendar); assertTrue("Date entity validation failed", schema.validate(dateString)); }
@Test public void testValidationOfStringFailure() { String stringEntity = ""; assertFalse("Expected DateSchema string validation failure did not succeed", schema.validate(stringEntity)); }
|
ListSchema extends NeutralSchema { public List<NeutralSchema> getList() { return list; } ListSchema(); ListSchema(String xsdType); @Override NeutralSchemaType getSchemaType(); @Override boolean isPrimitive(); void setList(List<NeutralSchema> list); List<NeutralSchema> getList(); @Override boolean isSimple(); void updateAnnotations(); @Override Object convert(Object value); Map<String, NeutralSchema> getFields(); }
|
@Test public void testAnnotations() throws IllegalArgumentException { schema.clearFields(); complexSchema.clearFields(); AppInfo d = new AppInfo(null); d.put(AppInfo.READ_ENFORCEMENT_ELEMENT_NAME, new HashSet<String>(Arrays.asList(Right.READ_RESTRICTED.toString()))); complexSchema.addAnnotation(d); schema.getList().add(complexSchema); assertTrue("The schema should have a read_restricted annotation", schema.getAppInfo().getReadAuthorities() .contains(Right.READ_RESTRICTED)); }
|
ListSchema extends NeutralSchema { @Override protected boolean validate(String fieldName, Object entity, List<ValidationError> errors, Repository<Entity> repo) { boolean isValid = true; Object convertedEntity = convert(entity); if (convertedEntity instanceof Set) { convertedEntity = new ArrayList<Object>((Set) convertedEntity); } if (convertedEntity instanceof List) { List<?> entityList = (List<?>) convertedEntity; for (Object fieldEntity : entityList) { boolean isFieldValid = false; for (NeutralSchema itemSchema : getList()) { if (itemSchema.validate(fieldName, fieldEntity, errors, repo)) { isFieldValid = true; break; } } if (!isFieldValid) { isValid = false; if (errors == null) { return false; } } } if (getProperties() != null) { for (Entry<String, Object> entry : getProperties().entrySet()) { if (Restriction.isRestriction(entry.getKey())) { long restrictionValue = Long.parseLong(entry.getValue().toString()); switch (Restriction.fromValue(entry.getKey())) { case LENGTH: if (!addError(entityList.size() == restrictionValue, fieldName, convertedEntity, "length=" + restrictionValue, ErrorType.INVALID_VALUE, errors)) { return false; } break; case MIN_LENGTH: if (!addError(entityList.size() >= restrictionValue, fieldName, convertedEntity, "min-length=" + restrictionValue, ErrorType.INVALID_VALUE, errors)) { return false; } break; case MAX_LENGTH: if (!addError(entityList.size() <= restrictionValue, fieldName, convertedEntity, "max-length=" + restrictionValue, ErrorType.INVALID_VALUE, errors)) { return false; } break; } } } } } else { return addError(false, fieldName, convertedEntity, "List", ErrorType.INVALID_DATATYPE, errors); } return isValid; } ListSchema(); ListSchema(String xsdType); @Override NeutralSchemaType getSchemaType(); @Override boolean isPrimitive(); void setList(List<NeutralSchema> list); List<NeutralSchema> getList(); @Override boolean isSimple(); void updateAnnotations(); @Override Object convert(Object value); Map<String, NeutralSchema> getFields(); }
|
@Test public void testValidationOfBooleanFailure() { Boolean booleanEntity = true; assertFalse("Expected ListSchema boolean validation failure did not succeed", schema.validate(booleanEntity)); }
@Test public void testValidationOfIntegerFailure() { Integer integerEntity = 0; assertFalse("Expected ListSchema integer validation failure did not succeed", schema.validate(integerEntity)); }
@Test public void testValidationOfFloatFailure() { Float floatEntity = new Float(0); assertFalse("Expected ListSchema float validation failure did not succeed", schema.validate(floatEntity)); }
|
EdOrgExtractHelper implements InitializingBean { @SuppressWarnings("unchecked") public Set<String> getBulkExtractApps() { TenantContext.setIsSystemCall(true); Iterable<Entity> apps = repository.findAll("application", new NeutralQuery()); TenantContext.setIsSystemCall(false); Set<String> appIds = new HashSet<String>(); for (Entity app : apps) { if (app.getBody().containsKey("isBulkExtract") && (Boolean) app.getBody().get("isBulkExtract")) { if (app.getBody().containsKey("registration") && "APPROVED".equals(((Map<String, Object>) app.getBody().get("registration")).get("status"))) { appIds.add(app.getEntityId()); } } } return appIds; } @Override void afterPropertiesSet(); Set<String> getBulkExtractEdOrgs(); Map<String, Set<String>> getBulkExtractEdOrgsPerApp(); @SuppressWarnings("unchecked") Set<String> getBulkExtractApps(); Set<String> getChildEdOrgs(Collection<String> edOrgs); Iterable<Entity> retrieveSEOAS(String teacherId, String edorgId); void logSecurityEvent(Set<String> leas, String entityName, String className); void setSecurityEventUtil(SecurityEventUtil securityEventUtil); Map<String, List<String>> getEdOrgLineages(); void setEdOrgLineages(Map<String, List<String>> edOrgLineages); }
|
@Test public void getBulkExtractAppsTest() { when(repository.findAll("application", new NeutralQuery())).thenReturn( Arrays.asList( buildAppEntity("1", true, true), buildAppEntity("2", false, false), buildAppEntity("3", true, false), buildAppEntity("4", false, true), buildAppEntity("5", true, true) ) ); Set<String> bulkExtractApps = helper.getBulkExtractApps(); bulkExtractApps.removeAll(Arrays.asList("1","5")); assertTrue(bulkExtractApps.isEmpty()); }
|
TimeSchema extends NeutralSchema { protected boolean validate(String fieldName, Object entity, List<ValidationError> errors, Repository<Entity> repo) { boolean isValid = false; try { javax.xml.bind.DatatypeConverter.parseTime((String) entity); isValid = true; } catch (IllegalArgumentException e2) { isValid = false; } return addError(isValid, fieldName, entity, "RFC 3339", ErrorType.INVALID_DATE_FORMAT, errors); } TimeSchema(); TimeSchema(String xsdType); @Override NeutralSchemaType getSchemaType(); }
|
@Test public void testTimeStringValidation() throws IllegalArgumentException { String timeString = "12:00:00-05:00"; assertTrue("Time entity validation failed", schema.validate(timeString)); }
@Test public void testTimeValidation() { Calendar calendar = Calendar.getInstance(); String timeString = javax.xml.bind.DatatypeConverter.printTime(calendar); assertTrue("Time entity validation failed", schema.validate(timeString)); }
@Test public void testValidationOfStringFailure() { String stringEntity = ""; assertFalse("Expected TimeSchema string validation failure did not succeed", schema.validate(stringEntity)); }
|
ApiNeutralSchemaValidator extends NeutralSchemaValidator { protected Object getValue(String path, Map<String, Object> data) { Object retValue = null; Map<?, ?> values = new HashMap<String, Object>(data); String[] keys = path.split("\\."); for (String key : keys) { Object value = values.get(key); if (Map.class.isInstance(value)) { values = (Map<?, ?>) value; retValue = value; } else { retValue = value; break; } } return retValue; } @Override boolean validateNaturalKeys(final Entity entity, boolean overWrite); }
|
@Test public void testGetValueOneLevel() { Map<String, Object> data = new HashMap<String, Object>(); data.put("key1", "value1"); data.put("key2", "value2"); data.put("key3", "value3"); assertEquals("Should match", "value1", apiNeutralSchemaValidator.getValue("key1", data)); assertEquals("Should match", "value2", apiNeutralSchemaValidator.getValue("key2", data)); assertEquals("Should match", "value3", apiNeutralSchemaValidator.getValue("key3", data)); assertEquals("Should match", null, apiNeutralSchemaValidator.getValue("key4", data)); }
@Test public void testGetValueMultiLevel() { Map<String, Object> inner2 = new HashMap<String, Object>(); inner2.put("key7", "value7"); inner2.put("key8", "value8"); Map<String, Object> inner1 = new HashMap<String, Object>(); inner1.put("key4", "value4"); inner1.put("key5", "value5"); inner1.put("key6", inner2); Map<String, Object> data = new HashMap<String, Object>(); data.put("key1", "value1"); data.put("key2", "value2"); data.put("key3", inner1); assertEquals("Should match", "value1", apiNeutralSchemaValidator.getValue("key1", data)); assertEquals("Should match", "value2", apiNeutralSchemaValidator.getValue("key2", data)); assertEquals("Should match", inner1, apiNeutralSchemaValidator.getValue("key3", data)); assertEquals("Should match", "value4", apiNeutralSchemaValidator.getValue("key3.key4", data)); assertEquals("Should match", "value5", apiNeutralSchemaValidator.getValue("key3.key5", data)); assertEquals("Should match", inner2, apiNeutralSchemaValidator.getValue("key3.key6", data)); assertEquals("Should match", "value7", apiNeutralSchemaValidator.getValue("key3.key6.key7", data)); assertEquals("Should match", "value8", apiNeutralSchemaValidator.getValue("key3.key6.key8", data)); }
|
DoubleSchema extends PrimitiveNumericSchema<Double> { @Override public Object convert(Object value) { if (value instanceof Integer) { return ((Integer) value).doubleValue(); } else if (value instanceof Long) { return ((Long) value).doubleValue(); } else if (value instanceof Float) { return ((Float) value).doubleValue(); } else if (value instanceof Double) { return (Double) value; } else if (value instanceof String) { try { return Double.parseDouble((String) value); } catch (NumberFormatException nfe) { throw (IllegalArgumentException) new IllegalArgumentException(value + " cannot be parsed to a double").initCause(nfe); } } throw new IllegalArgumentException(value + " is not a double"); } DoubleSchema(); @Override Object convert(Object value); }
|
@Test public void testConvert() throws Exception { double value = 1.2; Object convertedValue = this.schema.convert("" + value); assertTrue(convertedValue instanceof Double); Double convertedInput = (Double) convertedValue; assertTrue(convertedInput.doubleValue() == value); }
@Test(expected = IllegalArgumentException.class) public void testBadConvert() { this.schema.convert("INVALID INPUT"); }
@Test public void testNonConvert() { Object convertedValue = this.schema.convert(12.345); assertTrue(convertedValue instanceof Double); }
@Test public void testDoubleConverter() { double data = 12.0; float floatData = (float) data; int intData = (int) data; long longData = (long) data; assertTrue("Failure returning same object", this.schema.convert(data).equals(data)); assertTrue("Failure parsing double from long", this.schema.convert(longData).equals(data)); assertTrue("Failure parsing double from integer", this.schema.convert(intData).equals(data)); assertTrue("Failure parsing double from float", this.schema.convert(floatData).equals(data)); assertTrue("Failure parsing double data", this.schema.convert("" + data).equals(data)); }
@Test(expected = IllegalArgumentException.class) public void testInvalidStringThrowsException() throws IllegalArgumentException { this.schema.convert("INVALID INPUT"); }
@Test(expected = IllegalArgumentException.class) public void testUnsupportedObjectTypeThrowsException() throws IllegalArgumentException { this.schema.convert(new Object()); }
|
EdOrgExtractHelper implements InitializingBean { public Map<String, Set<String>> getBulkExtractEdOrgsPerApp() { NeutralQuery appQuery = new NeutralQuery(new NeutralCriteria("applicationId", NeutralCriteria.CRITERIA_IN, getBulkExtractApps())); Iterable<Entity> apps = repository.findAll("applicationAuthorization", appQuery); Map<String, Set<String>> edorgIds = new HashMap<String, Set<String>>(); for (Entity app : apps) { Set<String> edorgs = new HashSet<String>(BulkExtractMongoDA.getAuthorizedEdOrgIds(app)); edorgIds.put((String) app.getBody().get("applicationId"), edorgs); } return edorgIds; } @Override void afterPropertiesSet(); Set<String> getBulkExtractEdOrgs(); Map<String, Set<String>> getBulkExtractEdOrgsPerApp(); @SuppressWarnings("unchecked") Set<String> getBulkExtractApps(); Set<String> getChildEdOrgs(Collection<String> edOrgs); Iterable<Entity> retrieveSEOAS(String teacherId, String edorgId); void logSecurityEvent(Set<String> leas, String entityName, String className); void setSecurityEventUtil(SecurityEventUtil securityEventUtil); Map<String, List<String>> getEdOrgLineages(); void setEdOrgLineages(Map<String, List<String>> edOrgLineages); }
|
@Test public void getBulkExtractEdOrgsPerAppTest() { getBulkExtractAppsTest(); Map<String, Object> edorg1 = new HashMap<String, Object>(); edorg1.put("authorizedEdorg", "edOrg1"); Map<String, Object> edorg2 = new HashMap<String, Object>(); edorg2.put("authorizedEdorg", "edOrg2"); @SuppressWarnings("unchecked") Entity authOne = buildAuthEntity("1", Arrays.asList(edorg1, edorg2)); Entity authTwo = buildAuthEntity("5", new ArrayList<Map<String, Object>>()); List<Entity> auths = Arrays.asList(authOne, authTwo); when(repository.findAll(Mockito.eq("applicationAuthorization"), Mockito.any(NeutralQuery.class))).thenReturn(auths); Map<String, Set<String>> bulkExtractEdOrgsPerApp = helper.getBulkExtractEdOrgsPerApp(); assertTrue(bulkExtractEdOrgsPerApp.size() == 2); assertTrue(bulkExtractEdOrgsPerApp.get(authOne.getBody().get("applicationId")).containsAll( Arrays.asList("edOrg1","edOrg2"))); assertTrue(bulkExtractEdOrgsPerApp.get(authTwo.getBody().get("applicationId")).isEmpty()); }
|
ComplexSchema extends NeutralSchema { @Override protected boolean validate(String validateFieldName, Object entity, List<ValidationError> errors, Repository<Entity> repo) { return this.validate(validateFieldName, entity, errors, repo, true); } ComplexSchema(); ComplexSchema(String xsdType); @Override boolean isPrimitive(); @Override NeutralSchemaType getSchemaType(); @Override boolean validatePresent(Object entity, List<ValidationError> errors, Repository<Entity> repo); @Override boolean isSimple(); }
|
@Test public void testComplexValidation() throws IllegalArgumentException { schema.clearFields(); schema.addField("booleanField", booleanSchema); schema.addField("longField", longSchema); schema.addField("doubleField", doubleSchema); schema.addField("stringField", stringSchema); schema.addField("tokenField", tokenSchema); schema.addField("dateTimeField", dateTimeSchema); tokenSchema.getProperties().clear(); List<String> tokens = new ArrayList<String>(); tokens.add("validToken"); tokenSchema.getProperties().put(TokenSchema.TOKENS, tokens); Map<String, Object> complexEntity = new HashMap<String, Object>(); Boolean booleanEntity = true; Long longEntity = 0L; Double doubleEntity = 0.0; String stringEntity = "test"; String tokenEntity = "validToken"; String dateTimeEntity = "2012-01-01T12:00:00-05:00"; complexEntity.put("booleanField", booleanEntity); complexEntity.put("longField", longEntity); complexEntity.put("doubleField", doubleEntity); complexEntity.put("stringField", stringEntity); complexEntity.put("tokenField", tokenEntity); complexEntity.put("dateTimeField", dateTimeEntity); assertTrue("Complex entity validation failed", schema.validate(complexEntity)); }
@Test public void testInputConversionPerFieldSchema() { schema.clearFields(); schema.addField("booleanField", booleanSchema); schema.addField("longField", longSchema); schema.addField("doubleField", doubleSchema); schema.addField("stringField", stringSchema); schema.addField("tokenField", tokenSchema); tokenSchema.getProperties().clear(); List<String> tokens = new ArrayList<String>(); tokens.add("validToken"); tokenSchema.getProperties().put(TokenSchema.TOKENS, tokens); Map<String, Object> complexEntity = new HashMap<String, Object>(); String booleanEntity = "true"; String longEntity = "0"; String doubleEntity = "0.0"; String stringEntity = "test"; String tokenEntity = "validToken"; complexEntity.put("booleanField", booleanEntity); complexEntity.put("longField", longEntity); complexEntity.put("doubleField", doubleEntity); complexEntity.put("stringField", stringEntity); complexEntity.put("tokenField", tokenEntity); assertTrue("Complex entity validation failed", schema.validate(complexEntity)); assertTrue("Failed to properly convert boolean input", complexEntity.get("booleanField") instanceof Boolean); assertTrue("Failed to properly convert boolean input", complexEntity.get("longField") instanceof Long); assertTrue("Failed to properly convert boolean input", complexEntity.get("doubleField") instanceof Double); assertTrue("Failed to properly convert boolean input", complexEntity.get("stringField") instanceof String); assertTrue("Failed to properly convert boolean input", complexEntity.get("tokenField") instanceof String); }
@Test public void testOptionalFields() { schema.clearFields(); BooleanSchema required = new BooleanSchema(); AppInfo info = new AppInfo(null); info.put("required", "true"); required.addAnnotation(info); schema.addField("optionalField", booleanSchema); schema.addField("requiredField", required); Map<String, Object> complexEntity = new HashMap<String, Object>(); complexEntity.put("requiredField", Boolean.TRUE); assertTrue(schema.validate(complexEntity)); complexEntity.put("optionalField", Boolean.FALSE); assertTrue(schema.validate(complexEntity)); complexEntity.remove("requiredField"); assertFalse(schema.validate("requiredField")); }
@Test public void testComplexFailureValidation() throws IllegalArgumentException { schema.clearFields(); schema.addField("booleanField", booleanSchema); schema.addField("longField", longSchema); schema.addField("doubleField", doubleSchema); schema.addField("stringField", stringSchema); schema.addField("tokenField", tokenSchema); schema.addField("dateTimeField", dateTimeSchema); tokenSchema.getProperties().clear(); List<String> tokens = new ArrayList<String>(); tokens.add("validToken"); tokenSchema.getProperties().put(TokenSchema.TOKENS, tokens); Map<String, Object> complexEntity = new HashMap<String, Object>(); Long longEntity = 0L; Double doubleEntity = 0.0; BigDecimal decimalEntity = new BigDecimal(0); String stringEntity = "test"; String tokenEntity = "token"; String dateTimeEntity = "2012-01-01T12:00:00-05:00"; complexEntity.put("booleanField", stringEntity); complexEntity.put("longField", longEntity); complexEntity.put("doubleField", doubleEntity); complexEntity.put("decimalField", decimalEntity); complexEntity.put("stringField", stringEntity); complexEntity.put("tokenField", tokenEntity); complexEntity.put("dateTimeField", dateTimeEntity); assertFalse("Expected ComplexSchema validation failure did not succeed", schema.validate(complexEntity)); }
@Test public void testComplexHierarchyValidation() throws IllegalArgumentException { hierarchySchema.clearFields(); hierarchySchema.addField("schemaField", schema); schema.clearFields(); schema.addField("booleanField", booleanSchema); schema.addField("longField", longSchema); schema.addField("doubleField", doubleSchema); schema.addField("stringField", stringSchema); schema.addField("tokenField", tokenSchema); schema.addField("dateTimeField", dateTimeSchema); tokenSchema.getProperties().clear(); List<String> tokens = new ArrayList<String>(); tokens.add("validToken"); tokenSchema.getProperties().put(TokenSchema.TOKENS, tokens); Map<String, Object> hierarchyEntity = new HashMap<String, Object>(); Map<String, Object> complexEntity = new HashMap<String, Object>(); Boolean booleanEntity = true; Long longEntity = 0L; Double doubleEntity = 0.0; String stringEntity = "test"; String tokenEntity = "validToken"; String dateTimeEntity = "2012-01-01T12:00:00-05:00"; hierarchyEntity.put("schemaField", complexEntity); complexEntity.put("booleanField", booleanEntity); complexEntity.put("longField", longEntity); complexEntity.put("doubleField", doubleEntity); complexEntity.put("stringField", stringEntity); complexEntity.put("tokenField", tokenEntity); complexEntity.put("dateTimeField", dateTimeEntity); assertTrue("Complex hierarchy entity validation failed", hierarchySchema.validate(hierarchyEntity)); }
@Test public void testComplexHierarchyFailureValidation() throws IllegalArgumentException { hierarchySchema.clearFields(); hierarchySchema.addField("schemaField", schema); schema.clearFields(); schema.addField("booleanField", booleanSchema); schema.addField("longField", longSchema); schema.addField("doubleField", doubleSchema); schema.addField("stringField", stringSchema); schema.addField("tokenField", tokenSchema); schema.addField("dateTimeField", dateTimeSchema); tokenSchema.getProperties().clear(); List<String> tokens = new ArrayList<String>(); tokens.add("validToken"); tokenSchema.getProperties().put(TokenSchema.TOKENS, tokens); Map<String, Object> hierarchyEntity = new HashMap<String, Object>(); Map<String, Object> complexEntity = new HashMap<String, Object>(); Long longEntity = 0L; Double doubleEntity = 0.0; String stringEntity = "test"; String tokenEntity = "validToken"; String dateTimeEntity = "2012-01-01T12:00:00-05:00"; Boolean booleanEntity = true; hierarchyEntity.put("schemaField", complexEntity); complexEntity.put("longField", stringEntity); complexEntity.put("booleanField", booleanEntity); complexEntity.put("doubleField", doubleEntity); complexEntity.put("stringField", stringEntity); complexEntity.put("tokenField", tokenEntity); complexEntity.put("dateTimeField", dateTimeEntity); assertFalse("Expected ComplexSchema hierarchy validation failure did not succeed", hierarchySchema.validate(hierarchyEntity)); }
@Test public void testComplexHierarchyMapFailureValidation() throws IllegalArgumentException { hierarchySchema.clearFields(); hierarchySchema.addField("schemaField", schema); schema.clearFields(); schema.addField("booleanField", booleanSchema); schema.addField("longField", longSchema); schema.addField("doubleField", doubleSchema); schema.addField("stringField", stringSchema); schema.addField("tokenField", tokenSchema); schema.addField("dateTimeField", dateTimeSchema); tokenSchema.getProperties().clear(); List<String> tokens = new ArrayList<String>(); tokens.add("validToken"); tokenSchema.getProperties().put(TokenSchema.TOKENS, tokens); Map<String, Object> hierarchyEntity = new HashMap<String, Object>(); Map<String, Object> complexEntity = new HashMap<String, Object>(); Boolean booleanEntity = true; Long longEntity = 0L; Double doubleEntity = 0.0; BigDecimal decimalEntity = new BigDecimal(0); String stringEntity = "test"; String tokenEntity = "validToken"; String dateTimeEntity = "2012-01-01T12:00:00-05:00"; hierarchyEntity.put("schemaField", stringEntity); complexEntity.put("booleanField", booleanEntity); complexEntity.put("longField", longEntity); complexEntity.put("doubleField", doubleEntity); complexEntity.put("decimalField", decimalEntity); complexEntity.put("stringField", stringEntity); complexEntity.put("tokenField", tokenEntity); complexEntity.put("dateTimeField", dateTimeEntity); assertFalse("Expected ComplexSchema hierarchy validation failure did not succeed", hierarchySchema.validate(hierarchyEntity)); }
@Test public void testValidationOfBooleanFailure() { Boolean booleanEntity = true; assertFalse("Expected ComplexSchema boolean validation failure did not succeed", schema.validate(booleanEntity)); }
@Test public void testValidationOfIntegerFailure() { Integer integerEntity = 0; assertFalse("Expected ComplexSchema integer validation failure did not succeed", schema.validate(integerEntity)); }
@Test public void testValidationOfFloatFailure() { Float floatEntity = new Float(0); assertFalse("Expected ComplexSchema float validation failure did not succeed", schema.validate(floatEntity)); }
|
Launcher { public void execute(String tenant, boolean isDelta) { audit(securityEventUtil.createSecurityEvent(Launcher.class.getName(), "Bulk extract execution", LogLevelType.TYPE_INFO, BEMessageCode.BE_SE_CODE_0001)); Entity tenantEntity = bulkExtractMongoDA.getTenant(tenant); if (tenantEntity != null) { DateTime startTime = new DateTime(); if (isDelta) { LOG.info("isDelta=true ... deltaExtractor.execute()"); deltaExtractor.execute(tenant, getTenantDirectory(tenant), startTime); } else { LOG.info("isDelta=false ... localEdOrgExtractor.execute()"); edOrgExtractor.execute(tenant, getTenantDirectory(tenant), startTime); LOG.info("Starting public data extract..."); tenantPublicDataExtractor.execute(tenant, getTenantDirectory(tenant), startTime); } } else { audit(securityEventUtil.createSecurityEvent(Launcher.class.getName(), "Bulk extract execution", LogLevelType.TYPE_ERROR, BEMessageCode.BE_SE_CODE_0002, tenant)); LOG.error( "A bulk extract is not being initiated for the tenant {} because the tenant has not been onboarded.", tenant); } } void execute(String tenant, boolean isDelta); static String getTimeStamp(Date date); void setBaseDirectory(String baseDirectory); static void main(String[] args); void setEdOrgExtractor(EdOrgExtractor edOrgExtractor); EdOrgExtractor getEdOrgExtractor(); void setTenantPublicDataExtractor(TenantPublicDataExtractor tenantPublicDataExtractor); BulkExtractMongoDA getBulkExtractMongoDA(); void setBulkExtractMongoDA(BulkExtractMongoDA bulkExtractMongoDA); void setSecurityEventUtil(SecurityEventUtil securityEventUtil); }
|
@Test public void testInvalidTenant() { String tenantId = "testTenant"; Mockito.when(bulkExtractMongoDA.getTenant(tenantId)).thenReturn(null); launcher.execute(tenantId, false); Mockito.verify(localEdOrgExtractor, Mockito.never()).execute(Mockito.eq("tenant"), Mockito.any(File.class), Mockito.any(DateTime.class)); }
@Test public void testValidTenant() { String tenantId = "Midgar"; Mockito.doNothing().when(localEdOrgExtractor).execute(Mockito.eq("tenant"), Mockito.any(File.class), Mockito.any(DateTime.class)); Mockito.when(bulkExtractMongoDA.getTenant(tenantId)).thenReturn(testTenantEntity); launcher.execute(tenantId, false); Mockito.verify(localEdOrgExtractor, Mockito.times(1)).execute(Mockito.eq(tenantId), Mockito.any(File.class), Mockito.any(DateTime.class)); }
|
SelfReferenceValidator { public boolean validate(Entity entity, List<ValidationError> errors) { String selfReferencePath = selfReferenceExtractor.getSelfReferenceFields(entity); if (selfReferencePath != null) { Map<String, Object> body = entity.getBody(); if (body != null) { String property = (String) body.get(selfReferencePath); String uuid = entity.getEntityId(); if (uuid == null) { uuid = getDeterministicId(entity); } if (property != null && property.equals(uuid)) { Map<String, String> naturalKeys = null; try { naturalKeys = naturalKeyExtractor.getNaturalKeys(entity); if (naturalKeys != null && naturalKeys.size() > 0) { property = naturalKeys.toString(); } } catch (NoNaturalKeysDefinedException e) { LOG.error(e.getMessage(), e); } errors.add(new ValidationError(ErrorType.SELF_REFERENCING_DATA, selfReferencePath, property, new String[] { "Reference to a separate entity" })); return false; } return true; } } return true; } boolean validate(Entity entity, List<ValidationError> errors); String getDeterministicId(Entity entity); }
|
@Test public void testValidate() { Entity entity = Mockito.mock(Entity.class); Map<String, Object> body = new HashMap<String, Object>(); body.put(REFERENCE_FIELD, UUID); Mockito.when(entity.getBody()).thenReturn(body); Mockito.when(entity.getEntityId()).thenReturn(UUID); List<ValidationError> errors = new ArrayList<ValidationError>(); boolean valid = selfReferenceValidator.validate(entity, errors); Assert.assertFalse(valid); Assert.assertEquals(1, errors.size()); }
|
NeutralQuery { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } NeutralQuery other = (NeutralQuery) obj; if (excludeFields == null) { if (other.excludeFields != null) { return false; } } else if (!excludeFields.equals(other.excludeFields)) { return false; } if (includeFields == null) { if (other.includeFields != null) { return false; } } else if (!includeFields.equals(other.includeFields)) { return false; } if (limit != other.limit) { return false; } if (offset != other.offset) { return false; } if (orQueries == null) { if (other.orQueries != null) { return false; } } else if (!orQueries.equals(other.orQueries)) { return false; } if (queryCriteria == null) { if (other.queryCriteria != null) { return false; } } else if (!queryCriteria.equals(other.queryCriteria)) { return false; } if (sortBy == null) { if (other.sortBy != null) { return false; } } else if (!sortBy.equals(other.sortBy)) { return false; } if (sortOrder != other.sortOrder) { return false; } return true; } NeutralQuery(); NeutralQuery(int limit); NeutralQuery(NeutralQuery otherNeutralQuery); NeutralQuery(NeutralCriteria neutralCriteria); List<String> getEmbeddedFields(); void setEmbeddedFields(List<String> embeddedFields); @Override int hashCode(); @Override boolean equals(Object obj); NeutralQuery addOrQuery(NeutralQuery orQuery); List<NeutralQuery> getOrQueries(); final NeutralQuery addCriteria(NeutralCriteria criteria); NeutralQuery prependCriteria(NeutralCriteria criteria); List<NeutralCriteria> getCriteria(); List<String> getIncludeFields(); NeutralQuery setIncludeFields(List<String> includeFields); List<String> getExcludeFields(); NeutralQuery setExcludeFields(List<String> excludeFields); boolean removeCriteria(NeutralCriteria criteria); @Deprecated String getIncludeFieldString(); @Deprecated String getExcludeFieldString(); int getOffset(); int getLimit(); String getSortBy(); SortOrder getSortOrder(); NeutralQuery setLimit(int newLimit); NeutralQuery setOffset(int newOffset); NeutralQuery setIncludeFieldString(String newIncludeFields); NeutralQuery setExcludeFieldString(String newExcludeFields); NeutralQuery setEmbeddedFieldString(String newEmbeddedFields); NeutralQuery setSortBy(String newSortBy); NeutralQuery setSortOrder(SortOrder newSortOrder); NeutralQuery setQueryCriteria(List<NeutralCriteria> newQueryCriteria); void setCountOnly(boolean value); boolean getCountOnly(); boolean isCountOnly(); @Override String toString(); }
|
@Test public void testEquals() { String includeFields = "field1,field2"; String excludeFields = "field3,field4"; String sortBy = "field5"; int offset = 4; int limit = 5; NeutralQuery.SortOrder sortOrderAscending = NeutralQuery.SortOrder.ascending; NeutralQuery.SortOrder sortOrderDescending = NeutralQuery.SortOrder.descending; NeutralQuery neutralQuery1 = new NeutralQuery(); neutralQuery1.setIncludeFieldString(includeFields); neutralQuery1.setExcludeFieldString(excludeFields); neutralQuery1.setLimit(limit); neutralQuery1.setOffset(offset); neutralQuery1.setSortBy(sortBy); neutralQuery1.setSortOrder(sortOrderAscending); NeutralQuery neutralQuery2 = new NeutralQuery(neutralQuery1); assertTrue(neutralQuery1.equals(neutralQuery2)); assertTrue(neutralQuery1 != neutralQuery2); neutralQuery1.setIncludeFieldString(""); assertFalse(neutralQuery1.equals(neutralQuery2)); neutralQuery2.setIncludeFieldString(""); assertTrue(neutralQuery1.equals(neutralQuery2)); neutralQuery1.setExcludeFieldString(""); assertFalse(neutralQuery1.equals(neutralQuery2)); neutralQuery2.setExcludeFieldString(""); assertTrue(neutralQuery1.equals(neutralQuery2)); neutralQuery1.setLimit(7); assertFalse(neutralQuery1.equals(neutralQuery2)); neutralQuery2.setLimit(7); assertTrue(neutralQuery1.equals(neutralQuery2)); neutralQuery1.setOffset(9); assertFalse(neutralQuery1.equals(neutralQuery2)); neutralQuery2.setOffset(9); assertTrue(neutralQuery1.equals(neutralQuery2)); neutralQuery1.setSortBy(""); assertFalse(neutralQuery1.equals(neutralQuery2)); neutralQuery2.setSortBy(""); assertTrue(neutralQuery1.equals(neutralQuery2)); neutralQuery1.setSortOrder(sortOrderDescending); assertFalse(neutralQuery1.equals(neutralQuery2)); neutralQuery2.setSortOrder(sortOrderDescending); assertTrue(neutralQuery1.equals(neutralQuery2)); neutralQuery1.addCriteria(new NeutralCriteria("x=1")); neutralQuery2.addCriteria(new NeutralCriteria("x=2")); assertFalse(neutralQuery1.equals(neutralQuery2)); neutralQuery1.addCriteria(new NeutralCriteria("x=2")); assertFalse(neutralQuery1.equals(neutralQuery2)); neutralQuery2.prependCriteria(new NeutralCriteria("x=1")); assertTrue(neutralQuery1.equals(neutralQuery2)); }
|
NeutralQuery { @Override public String toString() { return "NeutralQuery [includeFields=" + includeFields + ", excludeFields=" + excludeFields + ", offset=" + offset + ", limit=" + limit + ", sortBy=" + sortBy + ", sortOrder=" + sortOrder + ", queryCriteria=" + queryCriteria + ", orQueries=" + orQueries + "]"; } NeutralQuery(); NeutralQuery(int limit); NeutralQuery(NeutralQuery otherNeutralQuery); NeutralQuery(NeutralCriteria neutralCriteria); List<String> getEmbeddedFields(); void setEmbeddedFields(List<String> embeddedFields); @Override int hashCode(); @Override boolean equals(Object obj); NeutralQuery addOrQuery(NeutralQuery orQuery); List<NeutralQuery> getOrQueries(); final NeutralQuery addCriteria(NeutralCriteria criteria); NeutralQuery prependCriteria(NeutralCriteria criteria); List<NeutralCriteria> getCriteria(); List<String> getIncludeFields(); NeutralQuery setIncludeFields(List<String> includeFields); List<String> getExcludeFields(); NeutralQuery setExcludeFields(List<String> excludeFields); boolean removeCriteria(NeutralCriteria criteria); @Deprecated String getIncludeFieldString(); @Deprecated String getExcludeFieldString(); int getOffset(); int getLimit(); String getSortBy(); SortOrder getSortOrder(); NeutralQuery setLimit(int newLimit); NeutralQuery setOffset(int newOffset); NeutralQuery setIncludeFieldString(String newIncludeFields); NeutralQuery setExcludeFieldString(String newExcludeFields); NeutralQuery setEmbeddedFieldString(String newEmbeddedFields); NeutralQuery setSortBy(String newSortBy); NeutralQuery setSortOrder(SortOrder newSortOrder); NeutralQuery setQueryCriteria(List<NeutralCriteria> newQueryCriteria); void setCountOnly(boolean value); boolean getCountOnly(); boolean isCountOnly(); @Override String toString(); }
|
@Test public void testToString() { assertNotNull(new NeutralQuery().toString()); }
|
NeutralCriteria { @Override public boolean equals(Object o) { if (o instanceof NeutralCriteria) { NeutralCriteria nc = (NeutralCriteria) o; boolean keysMatch = this.valuesMatch(this.key, nc.key); boolean operatorsMatch = this.valuesMatch(this.operator, nc.operator); boolean valuesMatch = this.valuesMatch(this.value, nc.value); boolean prefixesMatch = (this.canBePrefixed == nc.canBePrefixed); boolean typeMatch = ( this.getType() == nc.getType() ); boolean removableMatch = (this.isRemovable() == nc.isRemovable()); return (keysMatch && operatorsMatch && valuesMatch && prefixesMatch && typeMatch && removableMatch); } return false; } NeutralCriteria(String criteria); NeutralCriteria(String newKey, String newOperator, Object newValue); NeutralCriteria(String newKey, String newOperator, Object newValue, boolean canBePrefixed); @SuppressWarnings("PMD.UselessOverridingMethod") // this is overridden because equals is also overridden @Override int hashCode(); String getKey(); String getOperator(); Object getValue(); void setKey(String key); void setOperator(String operator); void setValue(Object value); boolean canBePrefixed(); void setCanBePrefixed(boolean canBePrefixed); @Override String toString(); @Override boolean equals(Object o); SearchType getType(); void setType(SearchType type); boolean isRemovable(); void setRemovable(boolean removable); static final String CRITERIA_IN; static final String CRITERIA_REGEX; static final String CRITERIA_GT; static final String CRITERIA_GTE; static final String CRITERIA_LT; static final String CRITERIA_LTE; static final String OPERATOR_EQUAL; static final String CRITERIA_EXISTS; }
|
@Test public void testEqualsComparison() { NeutralCriteria neutralCriteria1 = new NeutralCriteria("key", "=", "value"); NeutralCriteria neutralCriteria2 = new NeutralCriteria("key", "=", "value"); NeutralCriteria neutralCriteria3 = new NeutralCriteria("differentKey", "=", "value"); NeutralCriteria neutralCriteria4 = new NeutralCriteria("key", "!=", "value"); NeutralCriteria neutralCriteria5 = new NeutralCriteria("key", "!=", "differentValue"); NeutralCriteria neutralCriteria6 = new NeutralCriteria("key", "=", "value", true); NeutralCriteria neutralCriteria7 = new NeutralCriteria("key", "=", "value", false); assertTrue(neutralCriteria1.equals(neutralCriteria2)); assertFalse(neutralCriteria1 == neutralCriteria2); assertFalse(neutralCriteria1.equals(neutralCriteria3)); assertFalse(neutralCriteria1.equals(neutralCriteria4)); assertFalse(neutralCriteria1.equals(neutralCriteria5)); assertTrue(neutralCriteria1.equals(neutralCriteria6)); assertFalse(neutralCriteria1.equals(neutralCriteria7)); }
|
EdOrgHierarchyHelper { public Set<Entity> getAncestorsOfEdOrg(Entity entity) { if (isSEA(entity)) { return null; } Set<String> visitedIds = new HashSet<String>(); Set<Entity> ancestors = new HashSet<Entity>(); List<Entity> stack = new ArrayList<Entity>(10); ancestors.add(entity); stack.add(entity); while (!stack.isEmpty()) { Entity cur = stack.remove(stack.size() - 1); if (visitedIds.contains(cur.getEntityId())) { continue; } else { visitedIds.add(cur.getEntityId()); } if (cur.getBody().containsKey("parentEducationAgencyReference")) { List<Entity> parentEdOrgs = getParentEdOrg(cur); if (parentEdOrgs != null) { for (Entity parent:parentEdOrgs) { stack.add(parent); if (!isSEA(parent)) { ancestors.add(parent); } } } } } return ancestors; } EdOrgHierarchyHelper(Repository<Entity> repo); boolean isSEA(Entity entity); boolean isLEA(Entity entity); boolean isSchool(Entity entity); List<Entity> getTopLEAOfEdOrg(Entity entity); Set<Entity> getAncestorsOfEdOrg(Entity entity); String getSEAOfEdOrg(Entity entity); Entity getSEA(); }
|
@Test public void testGetAncestorsOfEdOrgWithCycle() { Entity sea = buildEntityType(SEA); Entity lea = buildEntityType(LEA); Entity school = buildEntityType(SCHOOL); school.getBody().put(PARENT_ED_ORG_REF, Arrays.asList(lea.getEntityId())); lea.getBody().put(PARENT_ED_ORG_REF, Arrays.asList(sea.getEntityId(), school.getEntityId())); sea.getBody().put(PARENT_ED_ORG_REF, Arrays.asList()); when(repo.findById(EntityNames.EDUCATION_ORGANIZATION, sea.getEntityId())).thenReturn(sea); when(repo.findById(EntityNames.EDUCATION_ORGANIZATION, lea.getEntityId())).thenReturn(lea); when(repo.findById(EntityNames.EDUCATION_ORGANIZATION, school.getEntityId())).thenReturn(school); Set<Entity> ancestors = underTest.getAncestorsOfEdOrg(school); assertNotNull(ancestors); assertTrue("LEA must be an ancestor", ancestors.contains(lea)); assertTrue("school should be contained in the results as well, per required behavior", ancestors.contains(school)); assertEquals("unexpected ancestors", 2, ancestors.size()); }
|
TypeResolver { public Set<String> resolveType(String type) { if (typeMaps.containsKey(type)) { return typeMaps.get(type); } return new HashSet<String>(Arrays.asList(type)); } Set<String> resolveType(String type); }
|
@Test public void educationOrganzationCollectionAlsoContainsSchools() { Set<String> types = resolver.resolveType("educationOrganization"); assertTrue(types.size() == 2); assertTrue(types.contains("school")); assertTrue(types.contains("educationOrganization")); types = resolver.resolveType("staff"); assertTrue(types.size() == 2); assertTrue(types.contains("teacher")); assertTrue(types.contains("staff")); types = resolver.resolveType("non-existance"); assertTrue(types.size() == 1); }
|
EdOrgContextResolverFactory { public ContextResolver getResolver(String entityType) { return resolverMap.get(entityType); } ContextResolver getResolver(String entityType); }
|
@Test public void test() { assertNull(factory.getResolver("doesn't exist")); ContextResolver resolver = factory.getResolver("educationOrganization"); assertTrue(resolver instanceof SimpleEntityTypeContextResolver); }
@Test public void testStudentParent() { assertTrue(factory.getResolver("studentParentAssociation") instanceof StudentDirectRelatedContextResolver); }
|
StaffTeacherDirectRelatedContextResolver extends RelatedContextResolver { @Override protected String getReferenceProperty(String entityType) { if (EntityNames.TEACHER_SCHOOL_ASSOCIATION.equals(entityType) || EntityNames.TEACHER_SECTION_ASSOCIATION.equals(entityType)) { return ParameterConstants.TEACHER_ID; } if (EntityNames.STAFF_ED_ORG_ASSOCIATION.equals(entityType)) { return ParameterConstants.STAFF_REFERENCE; } if (EntityNames.STAFF_COHORT_ASSOCIATION.equals(entityType) || EntityNames.STAFF_PROGRAM_ASSOCIATION.equals(entityType)) { return ParameterConstants.STAFF_ID; } return null; } }
|
@Test public void canResolveTeacherAndStaffRelatedEntities() { assertEquals(ParameterConstants.TEACHER_ID, resolver.getReferenceProperty(EntityNames.TEACHER_SCHOOL_ASSOCIATION)); assertEquals(ParameterConstants.TEACHER_ID, resolver.getReferenceProperty(EntityNames.TEACHER_SECTION_ASSOCIATION)); assertEquals(ParameterConstants.STAFF_REFERENCE, resolver.getReferenceProperty(EntityNames.STAFF_ED_ORG_ASSOCIATION)); assertEquals(ParameterConstants.STAFF_ID, resolver.getReferenceProperty(EntityNames.STAFF_COHORT_ASSOCIATION)); assertEquals(ParameterConstants.STAFF_ID, resolver.getReferenceProperty(EntityNames.STAFF_PROGRAM_ASSOCIATION)); assertEquals(null, resolver.getReferenceProperty(EntityNames.STAFF)); assertEquals(null, resolver.getReferenceProperty(EntityNames.TEACHER)); }
|
StudentCompetencyContextResolver implements ContextResolver { @Override public Set<String> findGoverningEdOrgs(Entity entity) { if (entity == null) { return Collections.emptySet(); } String studentSectionAssociationId = (String) entity.getBody().get(ParameterConstants.STUDENT_SECTION_ASSOCIATION_ID); Entity studentSectionAssociation = repo.findById(EntityNames.STUDENT_SECTION_ASSOCIATION, studentSectionAssociationId); if (studentSectionAssociation == null) { return Collections.emptySet(); } String studentId = (String) studentSectionAssociation.getBody().get(ParameterConstants.STUDENT_ID); return studentResolver.findGoverningEdOrgs(studentId, entity); } @Override Set<String> findGoverningEdOrgs(Entity entity); }
|
@Test public void noStudentSectionAssociation() { Entity studentCompetency = buildStudentCompetency(); when(repo.findById(EntityNames.STUDENT_SECTION_ASSOCIATION, "association123")).thenReturn(null); assertEquals(Collections.<String> emptySet(), underTest.findGoverningEdOrgs(studentCompetency)); }
@Test public void shouldFollowStudent() { Entity studentCompetency = buildStudentCompetency(); when(repo.findById(EntityNames.STUDENT_SECTION_ASSOCIATION, "association123")).thenReturn(buildStudentSectionAssociation()); Set<String> topLeas = new HashSet<String>(Arrays.asList("lea1", "lea2")); when(studentResolver.findGoverningEdOrgs("student123", studentCompetency)).thenReturn(topLeas); assertEquals(topLeas, underTest.findGoverningEdOrgs(studentCompetency)); }
|
CourseTranscriptContextResolver implements ContextResolver { @Override public Set<String> findGoverningEdOrgs(Entity entity) { Set<String> edOrgs = new HashSet<String>(); if (entity == null) { return edOrgs; } String studentId = (String) entity.getBody().get(STUDENT_ID); if (studentId != null) { edOrgs.addAll(studentResolver.findGoverningEdOrgs(studentId, entity)); } String studentAcademicRecordId = (String) entity.getBody().get(STUDENT_ACADEMIC_RECORD_ID); if (studentAcademicRecordId != null) { Entity studentAcademicRecord = repo.findById(EntityNames.STUDENT_ACADEMIC_RECORD, studentAcademicRecordId); if (studentAcademicRecord != null) { edOrgs.addAll(studentResolver.findGoverningEdOrgs((String) studentAcademicRecord.getBody().get(STUDENT_ID), entity)); } } return edOrgs; } @Override Set<String> findGoverningEdOrgs(Entity entity); static final String ED_ORG_REFERENCE; static final String STUDENT_ACADEMIC_RECORD_ID; static final String STUDENT_ID; }
|
@Test public void returnEmptySetIfNoStudent() { Entity courseTranscript = buildCourseTranscript(); courseTranscript.getBody().remove(STUDENT_ID); courseTranscript.getBody().remove(STUDENT_ACADEMIC_RECORD_ID); assertEquals(Collections.emptySet(), underTest.findGoverningEdOrgs(courseTranscript)); }
@Test public void followStudentId() { Entity courseTranscript = buildCourseTranscript(); when(studentResolver.findGoverningEdOrgs("student1", courseTranscript)).thenReturn(new HashSet<String>(Arrays.asList("toplea2"))); assertEquals(new HashSet<String>(Arrays.asList("toplea2")), underTest.findGoverningEdOrgs(courseTranscript)); }
@Test public void noStudentIdFollowAcademicRecord() { Entity courseTranscript = buildCourseTranscript(); courseTranscript.getBody().remove(STUDENT_ID); when(studentResolver.findGoverningEdOrgs("student1", courseTranscript)).thenReturn(new HashSet<String>(Arrays.asList("toplea2"))); assertEquals(new HashSet<String>(Arrays.asList("toplea2")), underTest.findGoverningEdOrgs(courseTranscript)); }
@Test public void testDifferentEdOrgs() { Entity courseTranscript = buildCourseTranscript(); Entity studentAcademicRecord = buildStudentAcademicRecord(); studentAcademicRecord.getBody().put(STUDENT_ID, "student2"); when(repo.findById(EntityNames.STUDENT_ACADEMIC_RECORD, "studentacademicrecord1")).thenReturn(studentAcademicRecord); when(studentResolver.findGoverningEdOrgs("student1", courseTranscript)).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); when(studentResolver.findGoverningEdOrgs("student2", courseTranscript)).thenReturn(new HashSet<String>(Arrays.asList("edOrg2"))); assertEquals(new HashSet<String>(Arrays.asList("edOrg1", "edOrg2")), underTest.findGoverningEdOrgs(courseTranscript)); }
|
GradebookEntryContextResolver implements ContextResolver { @Override public Set<String> findGoverningEdOrgs(Entity entity) { Set<String> edOrgs = new HashSet<String>(); Iterator<Entity> studentGradebookEntries = repo.findEach(EntityNames.STUDENT_GRADEBOOK_ENTRY, Query.query(Criteria.where("body.gradebookEntryId").is(entity.getEntityId()))); while(studentGradebookEntries.hasNext()) { Entity studentGradebookEntry = studentGradebookEntries.next(); edOrgs.addAll(studentResolver.findGoverningEdOrgs((String) studentGradebookEntry.getBody().get(ParameterConstants.STUDENT_ID), entity)); } return edOrgs; } @Override Set<String> findGoverningEdOrgs(Entity entity); }
|
@Test public void test() { Entity gradebookEntry = Mockito.mock(Entity.class); Mockito.when(gradebookEntry.getEntityId()).thenReturn("123_id"); Mockito.when(gradebookEntry.getType()).thenReturn(EntityNames.GRADEBOOK_ENTRY); Entity sgbe1 = Mockito.mock(Entity.class); Map<String, Object> body1 = new HashMap<String, Object>(); body1.put(ParameterConstants.STUDENT_ID, "student1"); Mockito.when(sgbe1.getBody()).thenReturn(body1); Entity sgbe2 = Mockito.mock(Entity.class); Map<String, Object> body2 = new HashMap<String, Object>(); body2.put(ParameterConstants.STUDENT_ID, "student2"); Mockito.when(sgbe2.getBody()).thenReturn(body2); Mockito.when(repo.findEach(eq(EntityNames.STUDENT_GRADEBOOK_ENTRY), argThat(new BaseMatcher<Query>() { @Override public boolean matches(Object item) { Query q = (Query) item; return q.getQueryObject().get("body.gradebookEntryId").equals("123_id"); } @Override public void describeTo(Description description) { } }))).thenReturn(Arrays.asList(sgbe1, sgbe2).iterator()); Mockito.when(studentResolver.findGoverningEdOrgs("student1", gradebookEntry)).thenReturn(new HashSet<String>(Arrays.asList("lea1", "lea2"))); Mockito.when(studentResolver.findGoverningEdOrgs("student2", gradebookEntry)).thenReturn(new HashSet<String>(Arrays.asList("lea1", "lea3"))); Assert.assertEquals(new HashSet<String>(Arrays.asList("lea1", "lea2", "lea3")), resolver.findGoverningEdOrgs(gradebookEntry)); }
|
ParentContextResolver implements ContextResolver { @Override public Set<String> findGoverningEdOrgs(Entity entity) { Set<String> leas = new HashSet<String>(); Iterator<Entity> kids = repo.findEach(EntityNames.STUDENT, Query.query(Criteria.where(PATH_TO_PARENT).is(entity.getEntityId()))); while(kids.hasNext()) { Entity student = kids.next(); leas.addAll(studentResolver.findGoverningEdOrgs(student.getEntityId(), entity)); } return leas; } @Override Set<String> findGoverningEdOrgs(Entity entity); static final String PATH_TO_PARENT; }
|
@Test public void test() { Entity parent = mock(Entity.class); Entity kid1 = mock(Entity.class); when(kid1.getEntityId()).thenReturn("kid1"); Entity kid2 = mock(Entity.class); when(kid2.getEntityId()).thenReturn("kid2"); when(parent.getEntityId()).thenReturn("parentId"); when(repo.findEach(eq("student"), argThat(new BaseMatcher<Query>() { @Override public boolean matches(Object item) { Query q = (Query) item; return q.getQueryObject().get("studentParentAssociation.body.parentId").equals("parentId"); } @Override public void describeTo(Description description) { } }))).thenReturn(Arrays.asList(kid1, kid2).iterator()); when(studentResolver.findGoverningEdOrgs("kid1", parent)).thenReturn(new HashSet<String>(Arrays.asList("lea1", "lea2"))); when(studentResolver.findGoverningEdOrgs("kid2", parent)).thenReturn(new HashSet<String>(Arrays.asList("lea1", "lea3"))); assertEquals(new HashSet<String>(Arrays.asList("lea1", "lea2", "lea3")), underTest.findGoverningEdOrgs(parent)); }
|
LongValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = null; try { value = BSONUtilities.getValue(entity, fieldName); if (value != null) { rval = new LongWritable(Long.parseLong(value.toString())); } } catch (NumberFormatException e) { log.severe(String.format("Failed to convert value {'%s'} to Long", value)); } return rval; } LongValueMapper(String fieldName); @Override Writable getValue(BSONWritable entity); }
|
@Test public void testGetValue() { BSONObject field = new BasicBSONObject("field", 123L); BSONObject entry = new BasicBSONObject("long", field); BSONWritable entity = new BSONWritable(entry); LongValueMapper mapper = new LongValueMapper("long.field"); Writable value = mapper.getValue(entity); assertFalse(value instanceof NullWritable); assertTrue(value instanceof LongWritable); assertEquals(((LongWritable) value).get(), 123L); }
@Test public void testValueNotFound() { BSONObject field = new BasicBSONObject("field", 123L); BSONObject entry = new BasicBSONObject("long", field); BSONWritable entity = new BSONWritable(entry); LongValueMapper mapper = new LongValueMapper("long.missing_field"); Writable value = mapper.getValue(entity); assertTrue(value instanceof NullWritable); }
@Test public void testValueNotLong() { BSONObject field = new BasicBSONObject("field", true); BSONObject entry = new BasicBSONObject("long", field); BSONWritable entity = new BSONWritable(entry); LongValueMapper mapper = new LongValueMapper("long.field"); Writable value = mapper.getValue(entity); assertTrue(value instanceof NullWritable); }
|
RelatedContextResolver implements ContextResolver { @Override public Set<String> findGoverningEdOrgs(Entity entity) { if (entity.getBody() == null) { return Collections.emptySet(); } String referredId = getReferredId(entity.getType(), entity.getBody()); if (referredId == null) { return Collections.emptySet(); } return getReferredResolver().findGoverningEdOrgs(referredId, entity); } RelatedContextResolver(); @Override Set<String> findGoverningEdOrgs(Entity entity); }
|
@Test public void testfindGoverningEdOrgs() { Mockito.when(mockEntity.getType()).thenReturn(EntityNames.TEACHER_SCHOOL_ASSOCIATION); Mockito.when(mockEntity.getBody()).thenReturn(body); Set<String> edOrgs = new HashSet<String>(Arrays.asList("springfieldElementary", "springfieldHigh")); Mockito.when(staffTeacherResolver.findGoverningEdOrgs(Mockito.eq(REFERRED_ID), Mockito.eq(mockEntity))).thenReturn(edOrgs); assertTrue(resolver.findGoverningEdOrgs(mockEntity).equals(edOrgs)); }
|
RelatedContextResolver implements ContextResolver { protected String getReferredId(String type, Map<String, Object> body) { String reference = getReferenceProperty(type); if (reference == null) { return null; } String referredId = (String) body.get(reference); return referredId; } RelatedContextResolver(); @Override Set<String> findGoverningEdOrgs(Entity entity); }
|
@Test public void testgetReferredId() { assertTrue(resolver.getReferredId(EntityNames.TEACHER_SCHOOL_ASSOCIATION, body).equals(REFERRED_ID)); }
|
DisciplineIncidentContextResolver implements ContextResolver { @Override public Set<String> findGoverningEdOrgs(Entity entity) { Set<String> edOrgs = new HashSet<String>(); Iterator<Entity> students = repo.findEach(EntityNames.STUDENT, Query.query(Criteria.where(DISCIPLINE_INCIDENT_ID).is(entity.getEntityId()))); while (students.hasNext()) { Entity student = students.next(); edOrgs.addAll(studentResolver.findGoverningEdOrgs(student.getEntityId(), entity)); } return edOrgs; } @Override Set<String> findGoverningEdOrgs(Entity entity); static final String DISCIPLINE_INCIDENT_ID; }
|
@Test public void testSingleStudent() { setFindEachReturn(Arrays.asList(student1)); Assert.assertEquals(new HashSet<String>(Arrays.asList("school1")), resolver.findGoverningEdOrgs(disciplineIncident)); }
@Test public void testMultipleStudents() { setFindEachReturn(Arrays.asList(student1, student2, student3)); Assert.assertEquals(new HashSet<String>(Arrays.asList("school1", "school2", "school3")), resolver.findGoverningEdOrgs(disciplineIncident)); }
@Test public void testNoStudentDIAssociation() { setFindEachReturn(Arrays.asList(student4)); Assert.assertTrue(resolver.findGoverningEdOrgs(disciplineIncident).isEmpty()); }
|
DisciplineActionContextResolver implements ContextResolver { @Override public Set<String> findGoverningEdOrgs(Entity entity) { Set<String> edOrgs = new HashSet<String>(); List<String> studentIds = (List<String>) entity.getBody().get(ParameterConstants.STUDENT_ID); for(String studentId: studentIds){ edOrgs.addAll(studentResolver.findGoverningEdOrgs(studentId, entity)); } return edOrgs; } @Override Set<String> findGoverningEdOrgs(Entity entity); }
|
@Test public void testSingleStudent() { Entity disciplineAction = Mockito.mock(Entity.class); Map<String, Object> body = new HashMap<String, Object>(); body.put(ParameterConstants.STUDENT_ID, Arrays.asList("student1")); Mockito.when(disciplineAction.getBody()).thenReturn(body); Mockito.when(studentResolver.findGoverningEdOrgs("student1", disciplineAction)).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); Assert.assertEquals(new HashSet<String>(Arrays.asList("edOrg1")), resolver.findGoverningEdOrgs(disciplineAction)); }
@Test public void testMultipleStudents() { Entity disciplineAction = Mockito.mock(Entity.class); Map<String, Object> body = new HashMap<String, Object>(); body.put(ParameterConstants.STUDENT_ID, Arrays.asList("student1", "student2", "student3", "student4")); Mockito.when(disciplineAction.getBody()).thenReturn(body); Mockito.when(studentResolver.findGoverningEdOrgs("student1", disciplineAction)).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); Mockito.when(studentResolver.findGoverningEdOrgs("student2", disciplineAction)).thenReturn(new HashSet<String>(Arrays.asList("edOrg2", "edOrg1"))); Mockito.when(studentResolver.findGoverningEdOrgs("student3", disciplineAction)).thenReturn(new HashSet<String>(Arrays.asList("edOrg3","edOrg2", "edOrg1"))); Mockito.when(studentResolver.findGoverningEdOrgs("student4", disciplineAction)).thenReturn(new HashSet<String>(Arrays.asList("edOrg4"))); Assert.assertEquals(new HashSet<String>(Arrays.asList("edOrg1", "edOrg2", "edOrg3", "edOrg4")), resolver.findGoverningEdOrgs(disciplineAction)); }
|
AllPublicDataExtractor implements PublicDataExtractor { @Override public void extract(ExtractFile file) { extractor.setExtractionQuery(new NeutralQuery()); for (PublicEntityDefinition entity : PublicEntityDefinition.values()) { extractor.extractEntities(file, entity.getEntityName(), new Predicate<Entity>() { @Override public boolean apply(Entity input) { boolean shouldExtract = true; if (!isPublicEntity(input.getType())) { shouldExtract = false; } return shouldExtract; } }); } } AllPublicDataExtractor(EntityExtractor extractor); @Override void extract(ExtractFile file); }
|
@Test public void testExtract() { publicDataExtractor.extract(file); for (PublicEntityDefinition definition : PublicEntityDefinition.values()) { Mockito.verify(extractor, Mockito.times(1)).extractEntities(Mockito.eq(file), Mockito.eq(definition.getEntityName()), Mockito.any(Predicate.class)); } }
|
PublicDataFactory { public PublicDataExtractor buildAllPublicDataExtractor(EntityExtractor extractor) { return new AllPublicDataExtractor(extractor); } PublicDataExtractor buildAllPublicDataExtractor(EntityExtractor extractor); List<PublicDataExtractor> buildPublicDataExtracts(EntityExtractor extractor); }
|
@Test public void buildUnfilteredPublicDataExtractor() { Assert.assertTrue(factory.buildAllPublicDataExtractor(null) != null); Assert.assertTrue(factory.buildAllPublicDataExtractor(null).getClass() == AllPublicDataExtractor.class); }
|
PublicDataFactory { public List<PublicDataExtractor> buildPublicDataExtracts(EntityExtractor extractor) { List<PublicDataExtractor> list = new ArrayList<PublicDataExtractor>(); list.add(buildAllPublicDataExtractor(extractor)); return list; } PublicDataExtractor buildAllPublicDataExtractor(EntityExtractor extractor); List<PublicDataExtractor> buildPublicDataExtracts(EntityExtractor extractor); }
|
@Test public void testBuildAllPublicDataExtracts() { Assert.assertTrue(factory.buildPublicDataExtracts(null) != null); List<PublicDataExtractor> extractors = factory.buildPublicDataExtracts(null); Assert.assertEquals(extractors.size(), 1); Assert.assertTrue(extractors.get(0).getClass() == AllPublicDataExtractor.class); }
|
SectionEmbeddedDocsExtractor implements EntityDatedExtract { @SuppressWarnings("unchecked") @Override public void extractEntities(final EntityToEdOrgDateCache gradebookEntryCache) { Iterator<Entity> sections = this.repository.findEach(EntityNames.SECTION, new NeutralQuery()); while (sections.hasNext()) { Entity section = sections.next(); extractTeacherSectionAssociation(section); extractGradebookEntry(section, gradebookEntryCache); extractStudentSectionAssociation(section); } } SectionEmbeddedDocsExtractor(EntityExtractor entityExtractor, ExtractFileMap leaToExtractFileMap,
Repository<Entity> repository, EntityToEdOrgDateCache studentCache,
EntityToEdOrgDateCache staffDatedCache); @SuppressWarnings("unchecked") @Override void extractEntities(final EntityToEdOrgDateCache gradebookEntryCache); EntityToEdOrgDateCache getStudentSectionAssociationDateCache(); }
|
@Test public void testExtractValidTSA() throws Exception { List<Entity> list = Arrays.asList(AccessibleVia.VALIDTSA.generate(), AccessibleVia.VALIDTSA.generate(), AccessibleVia.VALIDTSA.generate(), AccessibleVia.NONE.generate()); Mockito.when(repo.findEach(Mockito.eq(EntityNames.SECTION), Mockito.any(NeutralQuery.class))).thenReturn(list.iterator()); se.extractEntities(null); Mockito.verify(ex, Mockito.times(3)).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq(EntityNames.TEACHER_SECTION_ASSOCIATION)); }
@Test public void testExtractInvalidTSAs() throws Exception { List<Entity> list = Arrays.asList(AccessibleVia.INVALIDTSA.generate(), AccessibleVia.INVALIDTSA.generate(), AccessibleVia.INVALIDTSA.generate()); Mockito.when(repo.findEach(Mockito.eq(EntityNames.SECTION), Mockito.any(NeutralQuery.class))).thenReturn(list.iterator()); se.extractEntities(null); Mockito.verify(ex, Mockito.never()).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq(EntityNames.TEACHER_SECTION_ASSOCIATION)); }
@Test public void testExtractValidSSAs() throws Exception { List<Entity> list = Arrays.asList(AccessibleVia.VALIDSSA.generate(), AccessibleVia.VALIDSSA.generate(), AccessibleVia.VALIDSSA.generate(), AccessibleVia.NONE.generate()); Mockito.when(repo.findEach(Mockito.eq(EntityNames.SECTION), Mockito.any(NeutralQuery.class))).thenReturn(list.iterator()); se.extractEntities(null); Mockito.verify(ex, Mockito.times(3)).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION)); }
@Test public void testExtractInvalidSSAs() throws Exception { List<Entity> list = Arrays.asList(AccessibleVia.INVALIDSSA.generate(), AccessibleVia.INVALIDSSA.generate(), AccessibleVia.INVALIDSSA.generate()); Mockito.when(repo.findEach(Mockito.eq(EntityNames.SECTION), Mockito.any(NeutralQuery.class))).thenReturn(list.iterator()); se.extractEntities(null); Mockito.verify(ex, Mockito.never()).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.any(String.class)); }
|
StudentGradebookEntryExtractor implements EntityDatedExtract { @Override public void extractEntities(EntityToEdOrgDateCache studentCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), EntityNames.STUDENT_GRADEBOOK_ENTRY, this.getClass().getName()); Iterator<Entity> studentGradebookEntries = repo.findEach(EntityNames.STUDENT_GRADEBOOK_ENTRY, new NeutralQuery()); while (studentGradebookEntries.hasNext()) { Entity studentGradebookEntry = studentGradebookEntries.next(); String studentId = (String) studentGradebookEntry.getBody().get(ParameterConstants.STUDENT_ID); String gradebookEntryId = (String) studentGradebookEntry.getBody().get(ParameterConstants.GRADEBOOK_ENTRY_ID); Map<String, DateTime> studentEdOrgs = studentCache.getEntriesById(studentId); for (Map.Entry<String, DateTime> entry: studentEdOrgs.entrySet()) { DateTime upToDate = entry.getValue(); if(shouldExtract(studentGradebookEntry, upToDate)) { extractor.extractEntity(studentGradebookEntry, map.getExtractFileForEdOrg(entry.getKey()), EntityNames.STUDENT_GRADEBOOK_ENTRY); gradebookEntryCache.addEntry(gradebookEntryId, entry.getKey(), upToDate); } } } } StudentGradebookEntryExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgDateCache studentCache); EntityToEdOrgDateCache getGradebookEntryCache(); }
|
@Test public void testExtractNoEntityBecauseOfIdMiss() { entityBody.put(ParameterConstants.STUDENT_ID, "studentId99"); Mockito.when(mockRepo.findEach(Mockito.eq("studentGradebookEntry"), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq("studentGradebookEntry")); }
|
YearlyTranscriptExtractor implements EntityDatedExtract { @Override public void extractEntities(EntityToEdOrgDateCache studentDatedCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), ContainerEntityNames.YEARLY_TRANSCRIPT, this.getClass().getName()); Iterator<Entity> yearlyTranscripts = repo.findEach(ContainerEntityNames.YEARLY_TRANSCRIPT, new NeutralQuery()); while (yearlyTranscripts.hasNext()) { Entity yearlyTranscript = yearlyTranscripts.next(); String studentId = (String) yearlyTranscript.getBody().get(ParameterConstants.STUDENT_ID); final Map<String, DateTime> studentEdOrgs = studentDatedCache.getEntriesById(studentId); Set<String> studentAcademicRecords = fetchStudentAcademicRecordsFromYearlyTranscript(yearlyTranscript); for (Map.Entry<String, DateTime> studentEdOrg : studentEdOrgs.entrySet()) { if (shouldExtract(yearlyTranscript, studentEdOrg.getValue())) { extractor.extractEntity(yearlyTranscript, map.getExtractFileForEdOrg(studentEdOrg.getKey()), ContainerEntityNames.YEARLY_TRANSCRIPT); for (String sarId : studentAcademicRecords) { studentAcademicRecordDateCache.addEntry(sarId, studentEdOrg.getKey(), studentEdOrg.getValue()); } } } } } YearlyTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgDateCache studentDatedCache); EntityToEdOrgDateCache getStudentAcademicRecordDateCache(); }
|
@Test public void testDoNotWriteDatedBasedEntity() { Mockito.when(mockRepo.findEach(Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); entityBody.put(ParameterConstants.STUDENT_ID, "student"); entityBody.put(ParameterConstants.SCHOOL_YEAR, "2012-2013"); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT)); }
@Test public void testWriteOneEntity() { Mockito.when(mockRepo.findEach(Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); entityBody.put(ParameterConstants.STUDENT_ID, "student"); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT)); }
@Test public void testWriteManyEntities() { Mockito.when(mockRepo.findEach(Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity, mockEntity, mockEntity).iterator()); entityBody.put(ParameterConstants.STUDENT_ID, "student"); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.times(3)).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT)); }
@Test public void testExtractNoEntityBecauseOfLEAMiss() { Mockito.when(mockRepo.findEach(Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(null); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT)); }
@Test public void testExtractNoEntityBecauseOfIdMiss() { entityBody.put(ParameterConstants.STUDENT_ID, "STUDENT1"); Mockito.when(mockRepo.findEach(Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(ContainerEntityNames.YEARLY_TRANSCRIPT)); }
|
ParentExtractor implements EntityExtract { @Override public void extractEntities(EntityToEdOrgCache entityToEdorgCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), EntityNames.PARENT, this.getClass().getName()); Iterator<Entity> parents = repo.findEach(EntityNames.PARENT, new NeutralQuery()); Set<String> validParents = entityToEdorgCache.getEntityIds(); while (parents.hasNext()) { Entity parent = parents.next(); if (!validParents.contains(parent.getEntityId())) { continue; } for (String edOrg : entityToEdorgCache.getEntriesById(parent.getEntityId())) { extractor.extractEntity(parent, map.getExtractFileForEdOrg(edOrg), EntityNames.PARENT); } } } ParentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgCache entityToEdorgCache); }
|
@Test public void testWriteOneEntity() { Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.PARENT), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity).iterator()); extractor.extractEntities(mockParentCache); Mockito.verify(mockExtractor).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.PARENT)); }
@Test public void testWriteManyEntities() { Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.PARENT), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity, mockEntity, mockEntity).iterator()); extractor.extractEntities(mockParentCache); Mockito.verify(mockExtractor, Mockito.times(3)).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.PARENT)); }
@Test public void testExtractNoEntityBecauseOfLEAMiss() { Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.PARENT), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(null); extractor.extractEntities(mockParentCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.PARENT)); }
@Test public void testExtractNoEntityBecauseOfIdMiss() { Mockito.when(mockEntity.getEntityId()).thenReturn("parent2"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.PARENT), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(mockParentCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.PARENT)); }
|
StaffExtractor implements EntityDatedExtract { @Override public void extractEntities(EntityToEdOrgDateCache staffToEdorgDateCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), EntityNames.STAFF, this.getClass().getName()); Iterator<Entity> staffs = repo.findEach(EntityNames.STAFF, new NeutralQuery()); while (staffs.hasNext()) { Entity staff = staffs.next(); Set<String> edOrgs = staffToEdorgDateCache.getEntriesById(staff.getEntityId()).keySet(); for (String edOrg : edOrgs) { extractor.extractEntity(staff, map.getExtractFileForEdOrg(edOrg), EntityNames.STAFF); } } } StaffExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgDateCache staffToEdorgDateCache); }
|
@Test public void testExtractOneEntity() { Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(staffToLeaDateCache); Mockito.verify(mockExtractor).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF)); }
@Test public void testExtractManyEntity() { Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity, mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(staffToLeaDateCache); Mockito.verify(mockExtractor, Mockito.times(2)).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF)); }
@Test public void testExtractNoEntityBecauseOfLEAMiss() { Mockito.when(mockEntity.getEntityId()).thenReturn("Staff2"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(null); extractor.extractEntities(staffToLeaDateCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF)); }
|
StudentExtractor implements EntityExtract { @Override public void extractEntities(EntityToEdOrgCache dummyCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), EntityNames.STUDENT, this.getClass().getName()); Iterator<Entity> cursor = repo.findEach(EntityNames.STUDENT, new NeutralQuery()); while (cursor.hasNext()) { Entity student = cursor.next(); buildStudentDatedCache(student); final Map<String, DateTime> datedEdOrgs = studentDatedCache.getEntriesById(student.getEntityId()); for (final String edOrg : map.getEdOrgs()) { if (datedEdOrgs.containsKey(edOrg)) { extractor.extractEntity(student, map.getExtractFileForEdOrg(edOrg), EntityNames.STUDENT, new Predicate<Entity>() { @Override public boolean apply(Entity input) { boolean shouldExtract = true; if (DATED_SUBDOCS.contains(input.getType())) { DateTime upToDate = datedEdOrgs.get(edOrg); shouldExtract = EntityDateHelper.shouldExtract(input, upToDate); } return shouldExtract; } }); Iterable<String> parents = helper.fetchCurrentParentsFromStudent(student); for (String parent : parents) { parentCache.addEntry(parent, edOrg); } } } List<Entity> sdias = student.getEmbeddedData().get("studentDisciplineIncidentAssociation"); if (sdias != null) { for (Entity sdia : sdias) { String did = (String) sdia.getBody().get("disciplineIncidentId"); Map<String, DateTime> edOrgsDate = studentDatedCache.getEntriesById(student.getEntityId()); for (Map.Entry<String, DateTime> entry : edOrgsDate.entrySet()) { diDateCache.addEntry(did, entry.getKey(), entry.getValue()); } } } } } StudentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
ExtractorHelper helper, EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgCache dummyCache); EntityToEdOrgCache getParentCache(); EntityToEdOrgDateCache getStudentDatedCache(); EntityToEdOrgDateCache getDiDateCache(); }
|
@Test public void testOneExtractedEntity() { Entity e = Mockito.mock(Entity.class); Mockito.when(mockRepo.findEach(Mockito.eq("student"), Mockito.eq(new NeutralQuery()))).thenReturn(Arrays.asList(e).iterator()); Map<String, DateTime> datedEdorgs = new HashMap<String, DateTime>(); datedEdorgs.put("LEA", DateTime.now()); Mockito.when(helper.fetchAllEdOrgsForStudent(Mockito.any(Entity.class))).thenReturn(datedEdorgs); extractor.extractEntities(null); Mockito.verify(mockExtractor).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq("student"), Mockito.any(Predicate.class)); }
@Test public void testManyExtractedEntities() { Entity e = Mockito.mock(Entity.class); Mockito.when(mockRepo.findEach(Mockito.eq("student"), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(e, e, e).iterator()); Map<String, DateTime> datedEdorgs = new HashMap<String, DateTime>(); datedEdorgs.put("LEA", DateTime.now()); Mockito.when(helper.fetchAllEdOrgsForStudent(Mockito.any(Entity.class))).thenReturn(datedEdorgs); extractor.extractEntities(null); Mockito.verify(mockExtractor, Mockito.times(3)).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq("student"), Mockito.any(Predicate.class)); }
@Test public void testNoExtractedEntities() { Entity e = Mockito.mock(Entity.class); Mockito.when(mockRepo.findEach(Mockito.eq("student"), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(e).iterator()); extractor.extractEntities(null); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq("student")); extractor.extractEntities(null); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq("student")); }
|
EnumValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = null; try { value = BSONUtilities.getValue(entity, fieldName); if (value != null) { value = Enum.valueOf(enumClass, value).toString(); rval = new Text(value); } } catch (IllegalArgumentException e) { log.severe(String.format("Failed to convert value {%s} to Enum", value)); } return rval; } EnumValueMapper(String fieldName, Class<T> v); @Override Writable getValue(BSONWritable entity); }
|
@Test public void testGetValue() { BSONObject field = new BasicBSONObject("field", "TEST1"); BSONObject entry = new BasicBSONObject("enum", field); BSONWritable entity = new BSONWritable(entry); EnumValueMapper<Testing> m = new EnumValueMapper<Testing>("enum.field", Testing.class); Writable value = m.getValue(entity); assertFalse(value instanceof NullWritable); assertTrue(value instanceof Text); assertEquals(((Text) value).toString(), Testing.TEST1.toString()); }
@Test public void testGetValueNotFound() { BSONObject field = new BasicBSONObject("field", "Unknown"); BSONObject entry = new BasicBSONObject("enum", field); BSONWritable entity = new BSONWritable(entry); EnumValueMapper<Testing> m = new EnumValueMapper<Testing>("enum.field", Testing.class); Writable value = m.getValue(entity); assertTrue(value instanceof NullWritable); }
|
StaffProgramAssociationExtractor implements EntityDatedExtract { @Override public void extractEntities(EntityToEdOrgDateCache staffDatedCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), EntityNames.STAFF_PROGRAM_ASSOCIATION, this.getClass().getName()); Iterator<Entity> spas = repo.findEach(EntityNames.STAFF_PROGRAM_ASSOCIATION, new NeutralQuery()); while (spas.hasNext()) { Entity spa = spas.next(); String staffId = (String) spa.getBody().get(ParameterConstants.STAFF_ID); Map<String, DateTime> edOrgs = staffDatedCache.getEntriesById(staffId); for (Map.Entry<String, DateTime> datedEdOrg : edOrgs.entrySet()) { if (EntityDateHelper.shouldExtract(spa, datedEdOrg.getValue())) { extractor.extractEntity(spa, map.getExtractFileForEdOrg(datedEdOrg.getKey()), EntityNames.STAFF_PROGRAM_ASSOCIATION); } } } } StaffProgramAssociationExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgDateCache staffDatedCache); }
|
@Test public void testExtractOneEntity() { entityBody.put(ParameterConstants.BEGIN_DATE, "2010-05-01"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF_PROGRAM_ASSOCIATION), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(staffToLeaCache); Mockito.verify(mockExtractor).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF_PROGRAM_ASSOCIATION)); }
@Test public void testExtractManyEntity() { entityBody.put(ParameterConstants.BEGIN_DATE, "2010-05-01"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF_PROGRAM_ASSOCIATION), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity, mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(staffToLeaCache); Mockito.verify(mockExtractor, Mockito.times(2)).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF_PROGRAM_ASSOCIATION)); }
@Test public void testExtractNoEntityBecauseWrongDate() { entityBody.put(ParameterConstants.BEGIN_DATE, "2012-05-01"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF_PROGRAM_ASSOCIATION), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(staffToLeaCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF_PROGRAM_ASSOCIATION)); }
@Test public void testExtractNoEntityBecauseOfLEAMiss() { entityBody.put(ParameterConstants.BEGIN_DATE, "2010-05-01"); Mockito.when(mockEntity.getEntityId()).thenReturn("Staff2"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF_PROGRAM_ASSOCIATION), Mockito.eq(new NeutralQuery()))).thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(null); extractor.extractEntities(staffToLeaCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF_PROGRAM_ASSOCIATION)); }
|
ExtractorFactory { public ExtractFile buildEdOrgExtractFile(String path, String edOrg, String archiveName, Map<String, PublicKey> appPublicKeys, SecurityEventUtil securityEventUtil) { File directory = new File(path, edOrg); directory.mkdirs(); return new ExtractFile(directory, archiveName, appPublicKeys, securityEventUtil); } StudentExtractor buildStudentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentAssessmentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); YearlyTranscriptExtractor buildYearlyTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityExtract buildParentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); StaffEdorgAssignmentExtractor buildStaffAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStaffExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildTeacherSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildAttendanceExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); ExtractFile buildEdOrgExtractFile(String path, String edOrg, String archiveName,
Map<String, PublicKey> appPublicKeys, SecurityEventUtil securityEventUtil); EntityDatedExtract buildStaffCohortAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); SectionEmbeddedDocsExtractor buildSectionExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache studentDatedCache, EdOrgExtractHelper edOrgExtractHelper, EntityToEdOrgDateCache staffDatedCache); EntityDatedExtract buildStaffProgramAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildCourseTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
EntityToEdOrgDateCache studentDatedCache); StudentGradebookEntryExtractor buildStudentGradebookEntryExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentCompetencyExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository); EntityDatedExtract buildDisciplineExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache entityCache); }
|
@Test public void testBuildExtractFile() { Assert.assertTrue(factory.buildEdOrgExtractFile("bloop", "Bleep", "BLOO BLOO", null, null) != null); Assert.assertTrue(factory.buildEdOrgExtractFile("bloop", "Bleep", "BLOOB BLOO", null, null).getClass() == ExtractFile.class); }
|
ExtractorFactory { public EntityDatedExtract buildAttendanceExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper) { return new AttendanceExtractor(extractor, map, repo, edOrgExtractHelper); } StudentExtractor buildStudentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentAssessmentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); YearlyTranscriptExtractor buildYearlyTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityExtract buildParentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); StaffEdorgAssignmentExtractor buildStaffAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStaffExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildTeacherSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildAttendanceExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); ExtractFile buildEdOrgExtractFile(String path, String edOrg, String archiveName,
Map<String, PublicKey> appPublicKeys, SecurityEventUtil securityEventUtil); EntityDatedExtract buildStaffCohortAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); SectionEmbeddedDocsExtractor buildSectionExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache studentDatedCache, EdOrgExtractHelper edOrgExtractHelper, EntityToEdOrgDateCache staffDatedCache); EntityDatedExtract buildStaffProgramAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildCourseTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
EntityToEdOrgDateCache studentDatedCache); StudentGradebookEntryExtractor buildStudentGradebookEntryExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentCompetencyExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository); EntityDatedExtract buildDisciplineExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache entityCache); }
|
@Test public void testBuildAttendanceExtractor() { Assert.assertTrue(factory.buildAttendanceExtractor(null, null, null, null) != null); Assert.assertTrue(factory.buildAttendanceExtractor(null, null, null, null).getClass() == AttendanceExtractor.class); }
|
ExtractorFactory { public StudentExtractor buildStudentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper) { return new StudentExtractor(extractor, map, repo, new ExtractorHelper(edOrgExtractHelper), edOrgExtractHelper); } StudentExtractor buildStudentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentAssessmentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); YearlyTranscriptExtractor buildYearlyTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityExtract buildParentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); StaffEdorgAssignmentExtractor buildStaffAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStaffExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildTeacherSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildAttendanceExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); ExtractFile buildEdOrgExtractFile(String path, String edOrg, String archiveName,
Map<String, PublicKey> appPublicKeys, SecurityEventUtil securityEventUtil); EntityDatedExtract buildStaffCohortAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); SectionEmbeddedDocsExtractor buildSectionExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache studentDatedCache, EdOrgExtractHelper edOrgExtractHelper, EntityToEdOrgDateCache staffDatedCache); EntityDatedExtract buildStaffProgramAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildCourseTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
EntityToEdOrgDateCache studentDatedCache); StudentGradebookEntryExtractor buildStudentGradebookEntryExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentCompetencyExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository); EntityDatedExtract buildDisciplineExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache entityCache); }
|
@Test public void testBuildStudentExtractor() { Assert.assertTrue(factory.buildStudentExtractor(null, null, null, null) != null); Assert.assertTrue(factory.buildStudentExtractor(null, null, null, null).getClass() == StudentExtractor.class); }
|
ExtractorFactory { public EntityDatedExtract buildStudentAssessmentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper) { return new StudentAssessmentExtractor(extractor, map, repo, edOrgExtractHelper); } StudentExtractor buildStudentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentAssessmentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); YearlyTranscriptExtractor buildYearlyTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityExtract buildParentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); StaffEdorgAssignmentExtractor buildStaffAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStaffExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildTeacherSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildAttendanceExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); ExtractFile buildEdOrgExtractFile(String path, String edOrg, String archiveName,
Map<String, PublicKey> appPublicKeys, SecurityEventUtil securityEventUtil); EntityDatedExtract buildStaffCohortAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); SectionEmbeddedDocsExtractor buildSectionExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache studentDatedCache, EdOrgExtractHelper edOrgExtractHelper, EntityToEdOrgDateCache staffDatedCache); EntityDatedExtract buildStaffProgramAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildCourseTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
EntityToEdOrgDateCache studentDatedCache); StudentGradebookEntryExtractor buildStudentGradebookEntryExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentCompetencyExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository); EntityDatedExtract buildDisciplineExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache entityCache); }
|
@Test public void testBuildStudentAssessmentExtractor() { Assert.assertTrue(factory.buildStudentAssessmentExtractor(null, null, null, null) != null); Assert.assertTrue(factory.buildStudentAssessmentExtractor(null, null, null, null).getClass() == StudentAssessmentExtractor.class); }
|
ExtractorFactory { public EntityDatedExtract buildStaffExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper) { return new StaffExtractor(extractor, map, repo, edOrgExtractHelper); } StudentExtractor buildStudentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentAssessmentExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); YearlyTranscriptExtractor buildYearlyTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityExtract buildParentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); StaffEdorgAssignmentExtractor buildStaffAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStaffExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildTeacherSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildAttendanceExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); ExtractFile buildEdOrgExtractFile(String path, String edOrg, String archiveName,
Map<String, PublicKey> appPublicKeys, SecurityEventUtil securityEventUtil); EntityDatedExtract buildStaffCohortAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); SectionEmbeddedDocsExtractor buildSectionExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache studentDatedCache, EdOrgExtractHelper edOrgExtractHelper, EntityToEdOrgDateCache staffDatedCache); EntityDatedExtract buildStaffProgramAssociationExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildCourseTranscriptExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
EntityToEdOrgDateCache studentDatedCache); StudentGradebookEntryExtractor buildStudentGradebookEntryExtractor(EntityExtractor extractor, ExtractFileMap map,
Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); EntityDatedExtract buildStudentCompetencyExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository); EntityDatedExtract buildDisciplineExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository,
EntityToEdOrgDateCache entityCache); }
|
@Test public void testBuildStaffExtractor() { Assert.assertTrue(factory.buildStaffExtractor(null, null, null, null) != null); Assert.assertTrue(factory.buildStaffExtractor(null, null, null, null).getClass() == StaffExtractor.class); }
|
ExtractorHelper { public Set<String> fetchCurrentParentsFromStudent(Entity student) { Set<String> parents = new TreeSet<String>(); if (student.getEmbeddedData().containsKey(EntityNames.STUDENT_PARENT_ASSOCIATION)) { for (Entity assoc : student.getEmbeddedData().get(EntityNames.STUDENT_PARENT_ASSOCIATION)) { String parentId = (String) assoc.getBody().get(ParameterConstants.PARENT_ID); if (parentId != null) { parents.add(parentId); } } } return parents; } ExtractorHelper(); ExtractorHelper(EdOrgExtractHelper edOrgExtractHelper); Map<String, DateTime> fetchAllEdOrgsForStudent(Entity student); Map<String, DateTime> updateEdorgToDateMap(Map<String, Object> entityBody, Map<String, DateTime> edOrgToDate,
String edOrgIdField, String beginDateField, String endDateField); void setDateHelper(DateHelper helper); Set<String> fetchCurrentParentsFromStudent(Entity student); Map<String, Collection<String>> buildSubToParentEdOrgCache(EntityToEdOrgCache edOrgCache); EdOrgExtractHelper getEdOrgExtractHelper(); void setEdOrgExtractHelper(EdOrgExtractHelper edOrgExtractHelper); }
|
@Test public void testFetchCurrentParentsFromStudentNullChecks() { Map<String, List<Entity>> embeddedData = new HashMap<String, List<Entity>>(); Assert.assertTrue(helper.fetchCurrentParentsFromStudent(mockEntity).size() == 0); Mockito.when(mockEntity.getEmbeddedData()).thenReturn(embeddedData); Assert.assertTrue(helper.fetchCurrentParentsFromStudent(mockEntity).size() == 0); Entity parentAssoc1 = Mockito.mock(Entity.class); Entity parentAssoc2 = Mockito.mock(Entity.class); Map<String, Object> body = Mockito.mock(Map.class); Map<String, Object> body2 = Mockito.mock(Map.class); Mockito.when(parentAssoc1.getBody()).thenReturn(body); Mockito.when(parentAssoc2.getBody()).thenReturn(body2); List<Entity> parentAssociations = Arrays.asList(parentAssoc1, parentAssoc2); embeddedData.put(EntityNames.STUDENT_PARENT_ASSOCIATION, parentAssociations); Assert.assertTrue(helper.fetchCurrentParentsFromStudent(mockEntity).size() == 0); Mockito.when(body.get(Mockito.eq(ParameterConstants.PARENT_ID))).thenReturn("ParentId123"); Mockito.when(body2.get(Mockito.eq(ParameterConstants.PARENT_ID))).thenReturn("ParentId456"); Assert.assertTrue(helper.fetchCurrentParentsFromStudent(mockEntity).size() == 2); }
|
ExtractorHelper { public Map<String, Collection<String>> buildSubToParentEdOrgCache(EntityToEdOrgCache edOrgCache) { Map<String, String> result = new HashMap<String, String>(); HashMultimap<String, String> map = HashMultimap.create(); for(String lea : edOrgCache.getEntityIds()) { for (String child : edOrgCache.getEntriesById(lea)) { result.put(child, lea); map.put(child, lea); } } return map.asMap(); } ExtractorHelper(); ExtractorHelper(EdOrgExtractHelper edOrgExtractHelper); Map<String, DateTime> fetchAllEdOrgsForStudent(Entity student); Map<String, DateTime> updateEdorgToDateMap(Map<String, Object> entityBody, Map<String, DateTime> edOrgToDate,
String edOrgIdField, String beginDateField, String endDateField); void setDateHelper(DateHelper helper); Set<String> fetchCurrentParentsFromStudent(Entity student); Map<String, Collection<String>> buildSubToParentEdOrgCache(EntityToEdOrgCache edOrgCache); EdOrgExtractHelper getEdOrgExtractHelper(); void setEdOrgExtractHelper(EdOrgExtractHelper edOrgExtractHelper); }
|
@Test public void testBuildSubToParentEdOrgCache() { EntityToEdOrgCache cache = new EntityToEdOrgCache(); cache.addEntry("lea-1", "school-1"); cache.addEntry("lea-1", "school-2"); cache.addEntry("lea-1", "school-3"); cache.addEntry("lea-2", "school-4"); cache.addEntry("lea-2", "school-5"); cache.addEntry("lea-3", "school-6"); Map<String, Collection<String>> result = helper.buildSubToParentEdOrgCache(cache); Assert.assertEquals(6, result.keySet().size()); Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-1")); Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-2")); Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-3")); Assert.assertEquals(Sets.newHashSet("lea-2"), result.get("school-4")); Assert.assertEquals(Sets.newHashSet("lea-2"), result.get("school-5")); Assert.assertEquals(Sets.newHashSet("lea-3"), result.get("school-6")); }
|
StaffCohortAssociationExtractor implements EntityDatedExtract { @Override public void extractEntities(EntityToEdOrgDateCache staffDatedCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), EntityNames.STAFF_COHORT_ASSOCIATION, this.getClass().getName()); Iterator<Entity> scas = repo.findEach(EntityNames.STAFF_COHORT_ASSOCIATION, new NeutralQuery()); while (scas.hasNext()) { Entity sca = scas.next(); String staffId = (String) sca.getBody().get(ParameterConstants.STAFF_ID); Map<String, DateTime> edOrgs = staffDatedCache.getEntriesById(staffId); for (Map.Entry<String, DateTime> datedEdOrg : edOrgs.entrySet()) { if (EntityDateHelper.shouldExtract(sca, datedEdOrg.getValue())) { extractor.extractEntity(sca, map.getExtractFileForEdOrg(datedEdOrg.getKey()), EntityNames.STAFF_COHORT_ASSOCIATION); } } } } StaffCohortAssociationExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgDateCache staffDatedCache); }
|
@Test public void testExtractOneEntity() { entityBody.put(ParameterConstants.BEGIN_DATE, "2010-05-01"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF_COHORT_ASSOCIATION), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(staffToLeaCache); Mockito.verify(mockExtractor).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF_COHORT_ASSOCIATION)); }
@Test public void testExtractManyEntity() { entityBody.put(ParameterConstants.BEGIN_DATE, "2010-05-01"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF_COHORT_ASSOCIATION), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity, mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(staffToLeaCache); Mockito.verify(mockExtractor, Mockito.times(2)).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF_COHORT_ASSOCIATION)); }
@Test public void testExtractNoEntityBecauseWrongDate() { entityBody.put(ParameterConstants.BEGIN_DATE, "2012-05-01"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF_COHORT_ASSOCIATION), Mockito.eq(new NeutralQuery()))) .thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(staffToLeaCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF_COHORT_ASSOCIATION)); }
@Test public void testExtractNoEntityBecauseOfLEAMiss() { entityBody.put(ParameterConstants.BEGIN_DATE, "2010-05-01"); Mockito.when(mockEntity.getEntityId()).thenReturn("Staff2"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STAFF_COHORT_ASSOCIATION), Mockito.eq(new NeutralQuery()))).thenReturn(Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(null); extractor.extractEntities(staffToLeaCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STAFF_COHORT_ASSOCIATION)); }
|
AttendanceExtractor implements EntityDatedExtract { @Override public void extractEntities(EntityToEdOrgDateCache studentCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), EntityNames.ATTENDANCE, this.getClass().getName()); Iterator<Entity> attendances = repo.findEach("attendance", new NeutralQuery()); while (attendances.hasNext()) { Entity attendance = attendances.next(); Map<String, DateTime> studentEdOrgDate = studentCache.getEntriesById((String) attendance.getBody().get("studentId")); for (Map.Entry<String, DateTime> entry: studentEdOrgDate.entrySet()) { DateTime upToDate = entry.getValue(); if (EntityDateHelper.shouldExtract(attendance, upToDate)) { extractor.extractEntity(attendance, map.getExtractFileForEdOrg(entry.getKey()), EntityNames.ATTENDANCE); } } } } AttendanceExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo,
EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgDateCache studentCache); }
|
@Test public void testWriteOneAttendance() { Mockito.when(mockRepo.findEach(Mockito.eq("attendance"), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity).iterator()); entityBody.put("studentId", "student"); entityBody.put(ParameterConstants.SCHOOL_YEAR, "2010-2011"); extractor.extractEntities(mockCache); Mockito.verify(mockExtractor).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq("attendance")); }
@Test public void testWriteManyAttendances() { Mockito.when(mockRepo.findEach(Mockito.eq("attendance"), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity, mockEntity, mockEntity).iterator()); entityBody.put("studentId", "student"); entityBody.put(ParameterConstants.SCHOOL_YEAR, "2010-2011"); extractor.extractEntities(mockCache); Mockito.verify(mockExtractor, Mockito.times(3)).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq("attendance")); }
@Test public void testWriteNoAttendances() { Mockito.when(mockRepo.findEach(Mockito.eq("attendance"), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity, mockEntity, mockEntity).iterator()); entityBody.put("studentId", "student"); entityBody.put(ParameterConstants.SCHOOL_YEAR, "2010-2011"); Mockito.when(mockCache.getEntriesById("student")).thenReturn(new HashMap<String, DateTime>()); extractor.extractEntities(mockCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq("attendance")); }
@Test public void testWriteFutureAttendances() { Mockito.when(mockRepo.findEach(Mockito.eq("attendance"), Mockito.eq(new NeutralQuery()))).thenReturn( Arrays.asList(mockEntity, mockEntity, mockEntity).iterator()); entityBody.put("studentId", "student"); entityBody.put(ParameterConstants.SCHOOL_YEAR, "3010-3011"); extractor.extractEntities(mockCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq("attendance")); }
|
StudentSchoolAssociationExtractor implements EntityDatedExtract { @Override public void extractEntities(EntityToEdOrgDateCache studentDateCache) { helper.logSecurityEvent(map.getEdOrgs(), EntityNames.STUDENT_SCHOOL_ASSOCIATION, this.getClass().getName()); Iterator<Entity> cursor = repo.findEach("studentSchoolAssociation", new NeutralQuery()); while(cursor.hasNext()) { Entity ssa = cursor.next(); Map<String, DateTime> studentEdOrgDate = studentDateCache.getEntriesById((String) ssa.getBody().get(ParameterConstants.STUDENT_ID)); for (Map.Entry<String, DateTime> entry: studentEdOrgDate.entrySet()) { DateTime upToDate = entry.getValue(); if(EntityDateHelper.shouldExtract(ssa, upToDate)) { extractor.extractEntity(ssa, map.getExtractFileForEdOrg(entry.getKey()), EntityNames.STUDENT_SCHOOL_ASSOCIATION); } } } } StudentSchoolAssociationExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper helper); @Override void extractEntities(EntityToEdOrgDateCache studentDateCache); }
|
@Test public void testTwoLeasOneStudent() { Map<String, DateTime> edOrgDate = new HashMap<String, DateTime>(); edOrgDate.put("LEA-1", DateTime.now()); edOrgDate.put("LEA-2", DateTime.now()); Mockito.when(mockStudentCache.getEntriesById(Mockito.eq("student-1"))).thenReturn(edOrgDate); Entity e = Mockito.mock(Entity.class); Map entityBody = new HashMap<String, Object>(); entityBody.put("studentId", "student-1"); entityBody.put(ParameterConstants.ENTRY_DATE, "2013-01-01"); Mockito.when(e.getBody()).thenReturn(entityBody); Mockito.when(e.getType()).thenReturn(EntityNames.STUDENT_SCHOOL_ASSOCIATION); Mockito.when(mockRepo.findEach(Mockito.eq("studentSchoolAssociation"), Mockito.eq(new NeutralQuery()))).thenReturn(Arrays.asList(e).iterator()); ssaExtractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.times(2)).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq("studentSchoolAssociation")); }
@Test public void testOneStudentOneLea() { Map<String, DateTime> edOrgDate = new HashMap<String, DateTime>(); edOrgDate.put("LEA-1", DateTime.now()); Mockito.when(mockStudentCache.getEntriesById(Mockito.eq("student-1"))).thenReturn(edOrgDate); Entity e = Mockito.mock(Entity.class); Map entityBody = new HashMap<String, Object>(); entityBody.put("studentId", "student-1"); entityBody.put(ParameterConstants.ENTRY_DATE, "2013-01-01"); Mockito.when(e.getBody()).thenReturn(entityBody); Mockito.when(e.getType()).thenReturn(EntityNames.STUDENT_SCHOOL_ASSOCIATION); Mockito.when(mockRepo.findEach(Mockito.eq("studentSchoolAssociation"), Mockito.eq(new NeutralQuery()))).thenReturn(Arrays.asList(e).iterator()); ssaExtractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.times(1)).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq("studentSchoolAssociation")); }
@Test public void testTwoStudentsOneLea() { Map<String, DateTime> edOrgDate = new HashMap<String, DateTime>(); edOrgDate.put("LEA-1", DateTime.now()); Mockito.when(mockStudentCache.getEntriesById(Mockito.eq("student-1"))).thenReturn(edOrgDate); Mockito.when(mockStudentCache.getEntriesById(Mockito.eq("student-2"))).thenReturn(edOrgDate); Entity e1 = Mockito.mock(Entity.class); Map entityBody1 = new HashMap<String, Object>(); entityBody1.put("studentId", "student-1"); entityBody1.put(ParameterConstants.ENTRY_DATE, "2013-01-01"); Mockito.when(e1.getBody()).thenReturn(entityBody1); Mockito.when(e1.getType()).thenReturn(EntityNames.STUDENT_SCHOOL_ASSOCIATION); Entity e2 = Mockito.mock(Entity.class); Map entityBody2 = new HashMap<String, Object>(); entityBody2.put("studentId", "student-2"); entityBody2.put(ParameterConstants.ENTRY_DATE, "2013-01-01"); Mockito.when(e2.getBody()).thenReturn(entityBody2); Mockito.when(e2.getType()).thenReturn(EntityNames.STUDENT_SCHOOL_ASSOCIATION); Mockito.when(mockRepo.findEach(Mockito.eq("studentSchoolAssociation"), Mockito.eq(new NeutralQuery()))).thenReturn(Arrays.asList(e1, e2).iterator()); ssaExtractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.times(2)).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq("studentSchoolAssociation")); }
@Test public void testNonCurrentDate() { Map<String, DateTime> edOrgDate = new HashMap<String, DateTime>(); edOrgDate.put("LEA-1", DateTime.now()); Mockito.when(mockStudentCache.getEntriesById(Mockito.eq("student-1"))).thenReturn(edOrgDate); Mockito.when(mockStudentCache.getEntriesById(Mockito.eq("student-2"))).thenReturn(edOrgDate); Entity e1 = Mockito.mock(Entity.class); Map entityBody1 = new HashMap<String, Object>(); entityBody1.put("studentId", "student-1"); entityBody1.put(ParameterConstants.ENTRY_DATE, "2013-01-01"); Mockito.when(e1.getBody()).thenReturn(entityBody1); Mockito.when(e1.getType()).thenReturn(EntityNames.STUDENT_SCHOOL_ASSOCIATION); Entity e2 = Mockito.mock(Entity.class); Map entityBody2 = new HashMap<String, Object>(); entityBody2.put("studentId", "student-2"); entityBody2.put(ParameterConstants.ENTRY_DATE, "3000-01-01"); Mockito.when(e2.getBody()).thenReturn(entityBody2); Mockito.when(e2.getType()).thenReturn(EntityNames.STUDENT_SCHOOL_ASSOCIATION); Mockito.when(mockRepo.findEach(Mockito.eq("studentSchoolAssociation"), Mockito.eq(new NeutralQuery()))).thenReturn(Arrays.asList(e1, e2).iterator()); ssaExtractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.times(1)).extractEntity(Mockito.any(Entity.class), Mockito.any(ExtractFile.class), Mockito.eq("studentSchoolAssociation")); }
|
DoubleValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = null; try { value = BSONUtilities.getValue(entity, fieldName); if (value != null) { rval = new DoubleWritable(Double.parseDouble(value.toString())); } } catch (NumberFormatException e) { log.severe(String.format("Failed to convert value {%s} to Double", value)); } return rval; } DoubleValueMapper(String fieldName); @Override Writable getValue(BSONWritable entity); }
|
@Test public void testGetValue() { BSONObject field = new BasicBSONObject("field", 1.312D); BSONObject entry = new BasicBSONObject("double", field); BSONWritable entity = new BSONWritable(entry); DoubleValueMapper mapper = new DoubleValueMapper("double.field"); Writable value = mapper.getValue(entity); assertFalse(value instanceof NullWritable); assertTrue(value instanceof DoubleWritable); assertEquals(((DoubleWritable) value).get(), 1.312D, 0.05); }
@Test public void testValueNotFound() { BSONObject field = new BasicBSONObject("field", 1.312D); BSONObject entry = new BasicBSONObject("double", field); BSONWritable entity = new BSONWritable(entry); DoubleValueMapper mapper = new DoubleValueMapper("double.missing_field"); Writable value = mapper.getValue(entity); assertTrue(value instanceof NullWritable); }
@Test public void testGetValueNotDouble() { BSONObject field = new BasicBSONObject("field", "Bob"); BSONObject entry = new BasicBSONObject("double", field); BSONWritable entity = new BSONWritable(entry); DoubleValueMapper mapper = new DoubleValueMapper("double.field"); Writable value = mapper.getValue(entity); assertTrue(value instanceof NullWritable); }
|
DisciplineExtractor implements EntityDatedExtract { @Override @SuppressWarnings("unchecked") public void extractEntities(final EntityToEdOrgDateCache diCache) { extract(EntityNames.DISCIPLINE_INCIDENT, new Function<Entity, Set<String>>() { @Override public Set<String> apply(Entity input) { String id = input.getEntityId(); Map<String, DateTime> edorgDate = diCache.getEntriesById(id); Set<String> edOrgs = new HashSet<String>(); for (Map.Entry<String, DateTime> entry: edorgDate.entrySet()) { DateTime upToDate = entry.getValue(); if (shouldExtract(input, upToDate)) { edOrgs.add(entry.getKey()); } } return edOrgs; } }); extract(EntityNames.DISCIPLINE_ACTION, new Function<Entity, Set<String>>() { @Override public Set<String> apply(Entity input) { Set<String> edOrgs = new HashSet<String>(); List<String> students = (List<String>) input.getBody().get("studentId"); for (String student : students) { Map<String, DateTime> edorgDate = studentCache.getEntriesById(student); for (Map.Entry<String, DateTime> entry: edorgDate.entrySet()) { DateTime upToDate = entry.getValue(); if (shouldExtract(input, upToDate)) { edOrgs.add(entry.getKey()); } } } return edOrgs; } }); } DisciplineExtractor(EntityExtractor entityExtractor, ExtractFileMap extractFileMap, Repository<Entity> repository, EntityToEdOrgDateCache studentCache); @Override @SuppressWarnings("unchecked") void extractEntities(final EntityToEdOrgDateCache diCache); }
|
@Test public void testExtractDisciplineIncidentAndAction() { Entity da1 = createDisciplineAction("2009-01-01"); Entity da2 = createDisciplineAction("2010-02-13"); Mockito.when(repo.findEach(Mockito.eq("disciplineAction"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(da1, da2).listIterator(0)); Entity di1 = createDisciplineIncident("2000-02-01"); Entity di2 = createDisciplineIncident("2011-02-01"); Mockito.when(repo.findEach(Mockito.eq("disciplineIncident"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(di1, di2).listIterator(0)); EntityToEdOrgDateCache diCache = new EntityToEdOrgDateCache(); diCache.addEntry("marker", LEA2, DateTime.parse("2010-02-12", DateHelper.getDateTimeFormat())); diCache.addEntry(DI_ID, LEA2, DateTime.parse("2010-02-12", DateHelper.getDateTimeFormat())); disc.extractEntities(diCache); Mockito.verify(ex, Mockito.times(1)).extractEntity(Mockito.eq(da1), Mockito.any(ExtractFile.class), Mockito.eq("disciplineAction")); Mockito.verify(ex, Mockito.never()).extractEntity(Mockito.eq(da2), Mockito.any(ExtractFile.class), Mockito.eq("disciplineAction")); Mockito.verify(ex, Mockito.times(1)).extractEntity(Mockito.eq(di1), Mockito.any(ExtractFile.class), Mockito.eq("disciplineIncident")); Mockito.verify(ex, Mockito.never()).extractEntity(Mockito.eq(di2), Mockito.any(ExtractFile.class), Mockito.eq("disciplineIncident")); }
|
StudentAssessmentExtractor implements EntityDatedExtract { @Override public void extractEntities(EntityToEdOrgDateCache entityToEdOrgDateCache) { edOrgExtractHelper.logSecurityEvent(map.getEdOrgs(), EntityNames.STUDENT_ASSESSMENT, this.getClass().getName()); Iterator<Entity> assessments = repo.findEach(EntityNames.STUDENT_ASSESSMENT, new NeutralQuery()); while (assessments.hasNext()) { Entity assessment = assessments.next(); String studentId = (String) assessment.getBody().get(ParameterConstants.STUDENT_ID); Map<String, DateTime> studentEdOrgDate = entityToEdOrgDateCache.getEntriesById(studentId); for (Map.Entry<String, DateTime> entry: studentEdOrgDate.entrySet()) { DateTime upToDate = entry.getValue(); if(EntityDateHelper.shouldExtract(assessment, upToDate)) { extractor.extractEntity(assessment, map.getExtractFileForEdOrg(entry.getKey()), EntityNames.STUDENT_ASSESSMENT); } } } } StudentAssessmentExtractor(EntityExtractor extractor, ExtractFileMap map, Repository<Entity> repo, EdOrgExtractHelper edOrgExtractHelper); @Override void extractEntities(EntityToEdOrgDateCache entityToEdOrgDateCache); }
|
@Test public void testWriteOneEntity() { Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STUDENT_ASSESSMENT), Mockito.eq(new NeutralQuery()))) .thenReturn( Arrays.asList(mockEntity).iterator()); entityBody.put(ParameterConstants.STUDENT_ID, "student"); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STUDENT_ASSESSMENT)); }
@Test public void testWriteManyEntities() { Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STUDENT_ASSESSMENT), Mockito.eq(new NeutralQuery()))) .thenReturn( Arrays.asList(mockEntity, mockEntity, mockEntity).iterator()); entityBody.put(ParameterConstants.STUDENT_ID, "student"); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.times(3)).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STUDENT_ASSESSMENT)); }
@Test public void testWriteSomeEntities() { Entity saEntity = Mockito.mock(Entity.class); Map<String, Object> saEntityBody = new HashMap<String, Object>(); saEntityBody.put("administrationDate", "3000-12-21"); saEntityBody.put(ParameterConstants.STUDENT_ID, "student"); Mockito.when(saEntity.getBody()).thenReturn(saEntityBody); Mockito.when(saEntity.getType()).thenReturn(EntityNames.STUDENT_ASSESSMENT); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STUDENT_ASSESSMENT), Mockito.eq(new NeutralQuery()))) .thenReturn( Arrays.asList(mockEntity, saEntity).iterator()); entityBody.put(ParameterConstants.STUDENT_ID, "student"); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.times(1)).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STUDENT_ASSESSMENT)); Mockito.verify(mockExtractor, Mockito.times(0)).extractEntity(Mockito.eq(saEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STUDENT_ASSESSMENT)); }
@Test public void testExtractNoEntityBecauseOfLEAMiss() { Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STUDENT_ASSESSMENT), Mockito.eq(new NeutralQuery()))) .thenReturn( Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(null); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STUDENT_ASSESSMENT)); }
@Test public void testExtractNoEntityBecauseOfIdMiss() { entityBody.put(ParameterConstants.STUDENT_ID, "STUDENT1"); Mockito.when(mockRepo.findEach(Mockito.eq(EntityNames.STUDENT_ASSESSMENT), Mockito.eq(new NeutralQuery()))) .thenReturn( Arrays.asList(mockEntity).iterator()); Mockito.when(mockMap.getExtractFileForEdOrg("LEA")).thenReturn(mockFile); extractor.extractEntities(mockStudentCache); Mockito.verify(mockExtractor, Mockito.never()).extractEntity(Mockito.eq(mockEntity), Mockito.eq(mockFile), Mockito.eq(EntityNames.STUDENT_ASSESSMENT)); }
|
LogUtil { public static void audit(SecurityEvent event) { if (entityRepository != null) { Map<String, Object> metadata = new HashMap<String, Object>(); metadata.put("tenantId", event.getTenantId()); entityRepository.create("securityEvent", event.getProperties(), metadata, "securityEvent"); } else { LOG.error("Could not log SecurityEvent to the database."); } switch (event.getLogLevel()) { case TYPE_DEBUG: LOG.debug(event.toString()); break; case TYPE_WARN: LOG.warn(event.toString()); break; case TYPE_INFO: LOG.info(event.toString()); break; case TYPE_ERROR: LOG.error(event.toString()); break; case TYPE_TRACE: LOG.trace(event.toString()); break; default: LOG.info(event.toString()); break; } } @Autowired LogUtil(@Qualifier("secondaryRepo") Repository<Entity> repo); static void audit(SecurityEvent event); static Repository<Entity> getEntityRepository(); static void setEntityRepository(Repository<Entity> entityRepository); }
|
@Test public void testAudit() { SecurityEvent securityEvent = new SecurityEvent(); securityEvent.setClassName(this.getClass().getName()); securityEvent.setLogMessage("Test Message"); securityEvent.setLogLevel(LogLevelType.TYPE_TRACE); audit(securityEvent); Mockito.verify(mockedEntityRepository, times(1)).create(any(String.class), any(Map.class), any(Map.class), any(String.class)); }
|
ExtractFile { public boolean generateArchive() { boolean success = true; TarArchiveOutputStream tarArchiveOutputStream = null; MultiOutputStream multiOutputStream = new MultiOutputStream(); try { for(String app : clientKeys.keySet()){ SecurityEvent event = securityEventUtil.createSecurityEvent(this.getClass().getName(), "Writing extract file to the file system", LogLevelType.TYPE_INFO, app, BEMessageCode.BE_SE_CODE_0022, app); event.setTargetEdOrgList(edorg); audit(event); multiOutputStream.addStream(getAppStream(app)); } tarArchiveOutputStream = new TarArchiveOutputStream(multiOutputStream); archiveFile(tarArchiveOutputStream, manifestFile.getFile()); File errors = errorFile.getFile(); if (errors != null) { archiveFile(tarArchiveOutputStream, errors); } for (JsonFileWriter dataFile : dataFiles.values()) { File df = dataFile.getFile(); if (df != null && df.exists()) { archiveFile(tarArchiveOutputStream, df); } } } catch (Exception e) { SecurityEvent event = securityEventUtil.createSecurityEvent(this.getClass().getName(), "Writing extract file to the file system", LogLevelType.TYPE_ERROR, BEMessageCode.BE_SE_CODE_0023); event.setTargetEdOrgList(edorg); audit(event); LOG.error("Error writing to tar file: {}", e.getMessage()); success = false; for(File archiveFile : archiveFiles.values()){ FileUtils.deleteQuietly(archiveFile); } } finally { IOUtils.closeQuietly(tarArchiveOutputStream); FileUtils.deleteQuietly(tempDir); } return success; } ExtractFile(File parentDir, String archiveName, Map<String, PublicKey> clientKeys, SecurityEventUtil securityEventUtil); JsonFileWriter getDataFileEntry(String filePrefix); void closeWriters(); ManifestFile getManifestFile(); ErrorFile getErrorLogger(); boolean generateArchive(); boolean finalizeExtraction(DateTime startTime); String getFileName(String appId); Map<String, File> getArchiveFiles(); Map<String, PublicKey> getClientKeys(); void setClientKeys(Map<String, PublicKey> clientKeys); String getEdorg(); void setEdorg(String edorg); }
|
@Test public void generateArchiveTest() throws Exception { String fileName = archiveFile.getFileName(testApp); archiveFile.generateArchive(); TarArchiveInputStream tarInputStream = null; List<String> names = new ArrayList<String>(); File decryptedFile = null; try { decryptedFile = decrypt(new File(fileName)); tarInputStream = new TarArchiveInputStream(new FileInputStream(decryptedFile)); TarArchiveEntry entry = null; while((entry = tarInputStream.getNextTarEntry())!= null) { names.add(entry.getName()); } } finally { IOUtils.closeQuietly(tarInputStream); } Assert.assertEquals(2, names.size()); Assert.assertTrue("Student extract file not found", names.get(1).contains("student")); Assert.assertTrue("Metadata file not found", names.get(0).contains("metadata")); FileUtils.deleteQuietly(decryptedFile); }
|
ErrorFile { public ErrorFile(File parent) { errorFile = new File(parent, ERROR_FILE_NAME); } ErrorFile(File parent); void logEntityError(Entity entity); File getFile(); static final String ERROR_FILE_NAME; }
|
@Test public void testErrorFile() throws IOException { File parentDir = new File("./"); parentDir.deleteOnExit(); ErrorFile error = new ErrorFile(parentDir); for (int i=0; i < 3; i++) { Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("TYPE" + i); error.logEntityError(entity); } Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("TYPE0"); error.logEntityError(entity); File result = error.getFile(); assertNotNull(result); String errorString = FileUtils.readFileToString(result); assertTrue(errorString.contains("2 errors occurred for entity type TYPE0\n")); assertTrue(errorString.contains("1 errors occurred for entity type TYPE1\n")); assertTrue(errorString.contains("1 errors occurred for entity type TYPE2\n")); }
|
EntityWriterManager { public Entity write(Entity entity, ExtractFile archiveFile) { writeEntityFile(entity, archiveFile); writerCollectionFile(entity, archiveFile); return entity; } Entity write(Entity entity, ExtractFile archiveFile); void writeDeleteFile(Entity entity, ExtractFile archiveFile); void setWriters(DefaultHashMap<String, EntityWriter> writers); void setMultiFileEntities(Map<String, String> multiFileEntities); void setEntities(Map<String, String> entities); }
|
@Test public void testWrite() { ExtractFile archiveFile = Mockito.mock(ExtractFile.class); JsonFileWriter jsonFile = Mockito.mock(JsonFileWriter.class); Mockito.when(archiveFile.getDataFileEntry(Mockito.anyString())).thenReturn(jsonFile); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("teacher"); writer.write(entity, archiveFile); Mockito.verify(jsonWriter1, Mockito.times(1)).write(Mockito.any(Entity.class), Mockito.any(JsonFileWriter.class), Mockito.any(ErrorFile.class)); Mockito.verify(jsonWriter2, Mockito.times(1)).write(Mockito.any(Entity.class), Mockito.any(JsonFileWriter.class), Mockito.any(ErrorFile.class)); }
@Test public void testWriteDefault() { ExtractFile archiveFile = Mockito.mock(ExtractFile.class); JsonFileWriter jsonFile = Mockito.mock(JsonFileWriter.class); Mockito.when(archiveFile.getDataFileEntry(Mockito.anyString())).thenReturn(jsonFile); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("student"); writer.write(entity, archiveFile); Mockito.verify(defaultWriter, Mockito.times(1)).write(Mockito.any(Entity.class), Mockito.any(JsonFileWriter.class), Mockito.any(ErrorFile.class)); Mockito.verify(jsonWriter1, Mockito.times(0)).write(Mockito.any(Entity.class), Mockito.any(JsonFileWriter.class), Mockito.any(ErrorFile.class)); Mockito.verify(jsonWriter2, Mockito.times(0)).write(Mockito.any(Entity.class), Mockito.any(JsonFileWriter.class), Mockito.any(ErrorFile.class)); }
|
EntityWriter { public Entity write(Entity entity, JsonFileWriter file, ErrorFile errors) { Entity treated = applicator.apply(entity); try { file.write(treated); } catch (JsonProcessingException e) { LOG.error("Error while extracting from " + entity.getType(), e); errors.logEntityError(entity); } catch (IOException e) { LOG.error("Error while extracting from " + entity.getType(), e); errors.logEntityError(entity); } return treated; } EntityWriter(Treatment treatment); Entity write(Entity entity, JsonFileWriter file, ErrorFile errors); }
|
@Test public void testWrite() { JsonFileWriter file = Mockito.mock(JsonFileWriter.class); ErrorFile errorFile = Mockito.mock(ErrorFile.class); Entity entity = Mockito.mock(Entity.class); Entity check = writer.write(entity, file, errorFile); Assert.assertEquals(treatedEntity, check); try { Mockito.verify(file, Mockito.times(1)).write(treatedEntity); } catch (IOException e) { Assert.fail(); } }
@Test public void testIOException() throws IOException { JsonFileWriter file = Mockito.mock(JsonFileWriter.class); Mockito.doThrow(new IOException("Mock IOException")).when(file).write(Mockito.any(Entity.class)); ErrorFile errorFile = Mockito.mock(ErrorFile.class); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("MOCK_ENTITY_TYPE"); writer.write(entity, file, errorFile); Mockito.verify(errorFile).logEntityError(entity); Mockito.doThrow(Mockito.mock(JsonProcessingException.class)).when(file).write(Mockito.any(Entity.class)); writer.write(entity, file, errorFile); Mockito.verify(errorFile, Mockito.times(2)).logEntityError(entity); }
|
BulkExtract { @GET @Path("extract") @RightsAllowed({ Right.BULK_EXTRACT }) public Response get(@Context HttpServletRequest request) throws Exception { LOG.info("Received request to stream sample bulk extract..."); logSecurityEvent("Received request to stream sample bulk extract"); validateRequestCertificate(request); final InputStream is = this.getClass().getResourceAsStream("/bulkExtractSampleData/" + SAMPLED_FILE_NAME); StreamingOutput out = new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { int n; byte[] buffer = new byte[1024]; while ((n = is.read(buffer)) > -1) { output.write(buffer, 0, n); } } }; ResponseBuilder builder = Response.ok(out); builder.header("content-disposition", "attachment; filename = " + SAMPLED_FILE_NAME); builder.header("last-modified", "Not Specified"); logSecurityEvent("Successful request to stream sample bulk extract"); return builder.build(); } @GET @Path("extract") @RightsAllowed({ Right.BULK_EXTRACT }) Response get(@Context HttpServletRequest request); @GET @Path("extract/{edOrgId}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId); @GET @Path("extract/public") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request); @GET @Path("extract/list") @RightsAllowed({ Right.BULK_EXTRACT }) Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context); @GET @Path("extract/{edOrgId}/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("edOrgId") String edOrgId, @PathParam("date") String date); @GET @Path("extract/public/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("date") String date); Repository<Entity> getMongoEntityRepository(); void setMongoEntityRepository(Repository<Entity> mongoEntityRepository); void setEdorgValidator(GenericToEdOrgValidator validator); void setFileResource(FileResource fileResource); static final String BULK_EXTRACT_FILES; static final String BULK_EXTRACT_FILE_PATH; static final String BULK_EXTRACT_DATE; static final DateTimeFormatter DATE_TIME_FORMATTER; }
|
@Test public void testGetSampleExtract() throws Exception { injector.setEducatorContext(); ResponseImpl res = (ResponseImpl) bulkExtract.get(req); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf("sample-extract.tar") > 0); Object entity = res.getEntity(); assertNotNull(entity); StreamingOutput out = (StreamingOutput) entity; File file = new File("out.zip"); FileOutputStream os = new FileOutputStream(file); out.write(os); os.flush(); assertTrue(file.exists()); assertEquals(798669192L, FileUtils.checksumCRC32(file)); FileUtils.deleteQuietly(file); }
|
BulkExtract { Response getEdOrgExtractResponse(final HttpRequestContext req, final String edOrgId, final String deltaDate) { ExtractFile ef = getEdOrgExtractFile(edOrgId, deltaDate); if (ef == null) { return Response.status(Status.NOT_FOUND).build(); } return fileResource.getFileResponse(req, ef, ef.getLastModified()); } @GET @Path("extract") @RightsAllowed({ Right.BULK_EXTRACT }) Response get(@Context HttpServletRequest request); @GET @Path("extract/{edOrgId}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId); @GET @Path("extract/public") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request); @GET @Path("extract/list") @RightsAllowed({ Right.BULK_EXTRACT }) Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context); @GET @Path("extract/{edOrgId}/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("edOrgId") String edOrgId, @PathParam("date") String date); @GET @Path("extract/public/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("date") String date); Repository<Entity> getMongoEntityRepository(); void setMongoEntityRepository(Repository<Entity> mongoEntityRepository); void setEdorgValidator(GenericToEdOrgValidator validator); void setFileResource(FileResource fileResource); static final String BULK_EXTRACT_FILES; static final String BULK_EXTRACT_FILE_PATH; static final String BULK_EXTRACT_DATE; static final DateTimeFormatter DATE_TIME_FORMATTER; }
|
@Test public void testGetExtractResponse() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext context = new HttpRequestContextAdapter() { @Override public String getMethod() { return "GET"; } }; Response res = bulkExtract.getEdOrgExtractResponse(context, null, null); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf(INPUT_FILE_NAME) > 0); Object entity = res.getEntity(); assertNotNull(entity); StreamingOutput out = (StreamingOutput) entity; ByteArrayOutputStream os = new ByteArrayOutputStream(); out.write(os); os.flush(); byte[] responseData = os.toByteArray(); String s = new String(responseData); assertEquals(BULK_DATA, s); }
@Test public void testHeadTenant() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext context = new HttpRequestContextAdapter() { @Override public String getMethod() { return "HEAD"; } }; Response res = bulkExtract.getEdOrgExtractResponse(context, null, null); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf(INPUT_FILE_NAME) > 0); Object entity = res.getEntity(); assertNull(entity); }
@Test public void testRange() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext failureContext = Mockito.mock(HttpRequestContext.class); Mockito.when(failureContext.getMethod()).thenReturn("HEAD"); Mockito.when(failureContext.getHeaderValue("Range")).thenReturn("bytes=0"); Response failureRes = bulkExtract.getEdOrgExtractResponse(failureContext, null, null); assertEquals(416, failureRes.getStatus()); HttpRequestContext validContext = Mockito.mock(HttpRequestContext.class); Mockito.when(validContext.getMethod()).thenReturn("HEAD"); Mockito.when(validContext.getHeaderValue("Range")).thenReturn("bytes=0-5"); Response validRes = bulkExtract.getEdOrgExtractResponse(validContext, null, null); assertEquals(200, validRes.getStatus()); HttpRequestContext multiRangeContext = Mockito.mock(HttpRequestContext.class); Mockito.when(multiRangeContext.getMethod()).thenReturn("HEAD"); Mockito.when(multiRangeContext.getHeaderValue("Range")).thenReturn("bytes=0-5,6-10"); Response multiRangeRes = bulkExtract.getEdOrgExtractResponse(validContext, null, null); assertEquals(200, multiRangeRes.getStatus()); }
@Test public void testFailedEvaluatePreconditions() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext context = new HttpRequestContextAdapter() { @Override public ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag eTag) { return Responses.preconditionFailed(); } }; Response res = bulkExtract.getEdOrgExtractResponse(context, null, null); assertEquals(412, res.getStatus()); }
|
BulkExtract { @GET @Path("extract/{edOrgId}/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) public Response getDelta(@Context HttpServletRequest request, @Context HttpContext context, @PathParam("edOrgId") String edOrgId, @PathParam("date") String date) { logSecurityEvent("Received request to stream Edorg delta bulk extract data"); if (deltasEnabled) { LOG.info("Retrieving delta bulk extract for {}, at date {}", edOrgId, date); if (edOrgId == null || edOrgId.isEmpty()) { logSecurityEvent("Failed delta request, missing edOrgId"); throw new IllegalArgumentException("edOrgId cannot be missing"); } if (date == null || date.isEmpty()) { logSecurityEvent("Failed delta request, missing date"); throw new IllegalArgumentException("date cannot be missing"); } validateRequestCertificate(request); validateCanAccessEdOrgExtract(edOrgId); return getEdOrgExtractResponse(context.getRequest(), edOrgId, date); } logSecurityEvent("Failed request for Edorg delta bulk extract data"); return Response.status(404).build(); } @GET @Path("extract") @RightsAllowed({ Right.BULK_EXTRACT }) Response get(@Context HttpServletRequest request); @GET @Path("extract/{edOrgId}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId); @GET @Path("extract/public") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request); @GET @Path("extract/list") @RightsAllowed({ Right.BULK_EXTRACT }) Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context); @GET @Path("extract/{edOrgId}/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("edOrgId") String edOrgId, @PathParam("date") String date); @GET @Path("extract/public/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("date") String date); Repository<Entity> getMongoEntityRepository(); void setMongoEntityRepository(Repository<Entity> mongoEntityRepository); void setEdorgValidator(GenericToEdOrgValidator validator); void setFileResource(FileResource fileResource); static final String BULK_EXTRACT_FILES; static final String BULK_EXTRACT_FILE_PATH; static final String BULK_EXTRACT_DATE; static final DateTimeFormatter DATE_TIME_FORMATTER; }
|
@Test public void testGetDelta() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockAppAuth(); Map<String, Object> body = new HashMap<String, Object>(); File f = File.createTempFile("bulkExtract", ".tar"); try { body.put(BulkExtract.BULK_EXTRACT_FILE_PATH, f.getAbsolutePath()); body.put(BulkExtract.BULK_EXTRACT_DATE, ISODateTimeFormat.dateTime().parseDateTime("2013-04-22T11:00:00.000Z").toDate()); Entity e = new MongoEntity("bulkExtractEntity", body); final DateTime d = ISODateTimeFormat.dateTime().parseDateTime("2013-03-31T11:00:00.000Z"); when( mockMongoEntityRepository.findOne(eq(BulkExtract.BULK_EXTRACT_FILES), argThat(new BaseMatcher<NeutralQuery>() { @Override public boolean matches(Object arg0) { NeutralQuery query = (NeutralQuery) arg0; return query.getCriteria().contains( new NeutralCriteria("date", NeutralCriteria.OPERATOR_EQUAL, d.toDate())) && query.getCriteria().contains( new NeutralCriteria("edorg", NeutralCriteria.OPERATOR_EQUAL, "Midvale")); } @Override public void describeTo(Description arg0) { } }))).thenReturn(e); Response r = bulkExtract.getDelta(req, CONTEXT, "Midvale", "2013-03-31T11:00:00.000Z"); assertEquals(200, r.getStatus()); Response notExisting = bulkExtract.getDelta(req, CONTEXT, "Midvale", "2013-04-01T11:00:00.000Z"); assertEquals(404, notExisting.getStatus()); } finally { f.delete(); } }
@Test(expected = AccessDeniedException.class) public void testAppIsNotAuthorizedForDeltaLea() throws Exception { injector.setEducatorContext(); Map<String, Object> body = new HashMap<String, Object>(); body.put("isBulkExtract", true); body.put("authorized_ed_orgs", Arrays.asList("ONE")); body.put("public_key", "KEY"); Entity mockEntity = Mockito.mock(Entity.class); when(mockEntity.getBody()).thenReturn(body); when(mockEntity.getEntityId()).thenReturn("App1"); when(mockMongoEntityRepository.findOne(eq("application"), Mockito.any(NeutralQuery.class))).thenReturn( mockEntity); Map<String, Object> authBody = new HashMap<String, Object>(); authBody.put("applicationId", "App1"); authBody.put(ApplicationAuthorizationResource.EDORG_IDS, ApplicationAuthorizationResourceTest.getAuthList("TWO")); Entity mockAuth = Mockito.mock(Entity.class); when(mockAuth.getBody()).thenReturn(authBody); when(mockMongoEntityRepository.findOne(eq("applicationAuthorization"), Mockito.any(NeutralQuery.class))) .thenReturn(mockAuth); bulkExtract.getDelta(req, CONTEXT, "BLEEP", "2012-12-21"); }
@Test public void testNullDeltaDate() { try { bulkExtract.getDelta(req, CONTEXT, "Midgar", null); fail("Should have thrown exception for null date"); } catch (IllegalArgumentException e) { assertTrue(!e.getMessage().isEmpty()); } }
|
BulkExtract { @GET @Path("extract/public/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) public Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context, @PathParam("date") String date) { logSecurityEvent("Received request to stream public delta bulk extract data"); if (deltasEnabled) { LOG.info("Retrieving delta public bulk extract at date {}", date); if (date == null || date.isEmpty()) { logSecurityEvent("Failed delta request, missing date"); throw new IllegalArgumentException("date cannot be missing"); } validateRequestCertificate(request); return getPublicExtractResponse(context.getRequest(), date); } logSecurityEvent("Failed request for Edorg delta bulk extract data"); return Response.status(404).build(); } @GET @Path("extract") @RightsAllowed({ Right.BULK_EXTRACT }) Response get(@Context HttpServletRequest request); @GET @Path("extract/{edOrgId}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId); @GET @Path("extract/public") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request); @GET @Path("extract/list") @RightsAllowed({ Right.BULK_EXTRACT }) Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context); @GET @Path("extract/{edOrgId}/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("edOrgId") String edOrgId, @PathParam("date") String date); @GET @Path("extract/public/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("date") String date); Repository<Entity> getMongoEntityRepository(); void setMongoEntityRepository(Repository<Entity> mongoEntityRepository); void setEdorgValidator(GenericToEdOrgValidator validator); void setFileResource(FileResource fileResource); static final String BULK_EXTRACT_FILES; static final String BULK_EXTRACT_FILE_PATH; static final String BULK_EXTRACT_DATE; static final DateTimeFormatter DATE_TIME_FORMATTER; }
|
@Test public void testSEADelta() throws Exception { String edOrgId = "Midvale"; Map<String, Object> edOrgBody = new HashMap<String, Object>(); List<String> orgCategory = new ArrayList<String>(); orgCategory.add("State Education Agency"); edOrgBody.put("organizationCategories", orgCategory); Entity edOrg = new MongoEntity(EntityNames.EDUCATION_ORGANIZATION, edOrgId, edOrgBody, null); when(edOrgHelper.byId(edOrgId)).thenReturn(edOrg); when(edOrgHelper.isSEA(edOrg)).thenReturn(true); DateTime d = ISODateTimeFormat.dateTime().parseDateTime("2013-05-14T11:00:00.000Z"); Date date = d.toDate(); mockBulkExtractEntity(date); Mockito.when(edOrgHelper.getDirectChildLEAsOfEdOrg(edOrg)).thenReturn(Arrays.asList("lea123")); Set<String> lea = new HashSet<String>(); lea.add("lea123"); Mockito.when(mockValidator.validate(EntityNames.EDUCATION_ORGANIZATION, lea)).thenReturn(lea); Map<String, Object> authBody = new HashMap<String, Object>(); authBody.put("applicationId", "App1"); authBody.put(ApplicationAuthorizationResource.EDORG_IDS, ApplicationAuthorizationResourceTest.getAuthList("lea123")); Entity mockAppAuth = Mockito.mock(Entity.class); Mockito.when(mockAppAuth.getBody()).thenReturn(authBody); Mockito.when(mockMongoEntityRepository.findOne(eq("applicationAuthorization"), Mockito.any(NeutralQuery.class))) .thenReturn(mockAppAuth); Response res = bulkExtract.getPublicDelta(req, CONTEXT, "2013-05-14T11:00:00.000Z"); assertEquals(200, res.getStatus()); }
|
BulkExtract { @GET @Path("extract/{edOrgId}") @RightsAllowed({ Right.BULK_EXTRACT }) public Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId) { logSecurityEvent("Received request to stream Edorg data"); if (edOrgId == null || edOrgId.isEmpty()) { logSecurityEvent("Failed request to stream edOrg data, missing edOrgId"); throw new IllegalArgumentException("edOrgId cannot be missing"); } validateRequestCertificate(request); validateCanAccessEdOrgExtract(edOrgId); return getEdOrgExtractResponse(context.getRequest(), edOrgId, null); } @GET @Path("extract") @RightsAllowed({ Right.BULK_EXTRACT }) Response get(@Context HttpServletRequest request); @GET @Path("extract/{edOrgId}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId); @GET @Path("extract/public") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request); @GET @Path("extract/list") @RightsAllowed({ Right.BULK_EXTRACT }) Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context); @GET @Path("extract/{edOrgId}/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("edOrgId") String edOrgId, @PathParam("date") String date); @GET @Path("extract/public/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("date") String date); Repository<Entity> getMongoEntityRepository(); void setMongoEntityRepository(Repository<Entity> mongoEntityRepository); void setEdorgValidator(GenericToEdOrgValidator validator); void setFileResource(FileResource fileResource); static final String BULK_EXTRACT_FILES; static final String BULK_EXTRACT_FILE_PATH; static final String BULK_EXTRACT_DATE; static final DateTimeFormatter DATE_TIME_FORMATTER; }
|
@Test(expected = AccessDeniedException.class) public void testAppIsNotAuthorizedForLea() throws Exception { injector.setEducatorContext(); Map<String, Object> body = new HashMap<String, Object>(); body.put("isBulkExtract", true); body.put("authorized_ed_orgs", Arrays.asList("ONE")); body.put("public_key", "KEY"); Entity mockEntity = Mockito.mock(Entity.class); when(mockEntity.getBody()).thenReturn(body); when(mockEntity.getEntityId()).thenReturn("App1"); when(mockMongoEntityRepository.findOne(eq("application"), Mockito.any(NeutralQuery.class))).thenReturn( mockEntity); Map<String, Object> authBody = new HashMap<String, Object>(); authBody.put("applicationId", "App1"); authBody.put(ApplicationAuthorizationResource.EDORG_IDS, ApplicationAuthorizationResourceTest.getAuthList("TWO")); Entity mockAuth = Mockito.mock(Entity.class); when(mockAuth.getBody()).thenReturn(authBody); when(mockMongoEntityRepository.findOne(eq("applicationAuthorization"), Mockito.any(NeutralQuery.class))) .thenReturn(mockAuth); bulkExtract.getEdOrgExtract(CONTEXT, req, "BLEEP"); }
@Test(expected = AccessDeniedException.class) public void testAppAuthIsEmpty() throws Exception { injector.setEducatorContext(); Map<String, Object> body = new HashMap<String, Object>(); body.put("isBulkExtract", true); body.put("authorized_ed_orgs", Arrays.asList("ONE")); body.put("public_key", "KEY"); Entity mockEntity = Mockito.mock(Entity.class); when(mockEntity.getBody()).thenReturn(body); when(mockEntity.getEntityId()).thenReturn("App1"); when(mockMongoEntityRepository.findOne(eq("application"), Mockito.any(NeutralQuery.class))).thenReturn( mockEntity); Map<String, Object> authBody = new HashMap<String, Object>(); authBody.put("applicationId", "App1"); authBody.put(ApplicationAuthorizationResource.EDORG_IDS, ApplicationAuthorizationResourceTest.getAuthList()); Entity mockAuth = Mockito.mock(Entity.class); when(mockAuth.getBody()).thenReturn(authBody); when(mockMongoEntityRepository.findOne(eq("applicationAuthorization"), Mockito.any(NeutralQuery.class))) .thenReturn(mockAuth); bulkExtract.getEdOrgExtract(CONTEXT, req, "BLEEP"); }
@Test(expected = AccessDeniedException.class) public void testAppHasNoAuthorizedEdorgs() throws Exception { injector.setEducatorContext(); Map<String, Object> body = new HashMap<String, Object>(); body.put("isBulkExtract", true); body.put("authorized_ed_orgs", Arrays.asList()); body.put("public_key", "KEY"); Entity mockEntity = Mockito.mock(Entity.class); when(mockEntity.getBody()).thenReturn(body); when(mockEntity.getEntityId()).thenReturn("App1"); when(mockMongoEntityRepository.findOne(eq("application"), Mockito.any(NeutralQuery.class))).thenReturn( mockEntity); bulkExtract.getEdOrgExtract(CONTEXT, req, "BLEEP"); }
@Test(expected = AccessDeniedException.class) public void testUserNotInLEA() throws Exception { injector.setEducatorContext(); Mockito.when(mockValidator.validate(eq(EntityNames.EDUCATION_ORGANIZATION), Mockito.any(Set.class))) .thenReturn(Collections.EMPTY_SET); bulkExtract.getEdOrgExtract(CONTEXT, req, "BLEEP"); }
@Test public void testEdOrgFullExtract() throws IOException, ParseException { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); Entity mockedEntity = mockBulkExtractEntity(null); Mockito.when(edOrgHelper.byId(eq("ONE"))).thenReturn(mockedEntity); Map<String, Object> authBody = new HashMap<String, Object>(); authBody.put("applicationId", "App1"); authBody.put(ApplicationAuthorizationResource.EDORG_IDS, ApplicationAuthorizationResourceTest.getAuthList("ONE")); Entity mockAppAuth = Mockito.mock(Entity.class); Mockito.when(mockAppAuth.getBody()).thenReturn(authBody); Mockito.when(mockMongoEntityRepository.findOne(eq("applicationAuthorization"), Mockito.any(NeutralQuery.class))) .thenReturn(mockAppAuth); Response res = bulkExtract.getEdOrgExtract(CONTEXT, req, "ONE"); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf(INPUT_FILE_NAME) > 0); Object entity = res.getEntity(); assertNotNull(entity); StreamingOutput out = (StreamingOutput) entity; ByteArrayOutputStream os = new ByteArrayOutputStream(); out.write(os); os.flush(); byte[] responseData = os.toByteArray(); String s = new String(responseData); assertEquals(BULK_DATA, s); }
|
BulkExtract { @GET @Path("extract/list") @RightsAllowed({ Right.BULK_EXTRACT }) public Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context) throws Exception { LOG.info("Received request for list of links for all edOrgs and public data for this user/app"); logSecurityEvent("Received request for list of links for all edOrgs and public data for this user/app"); validateRequestAndApplicationAuthorization(request); logSecurityEvent("Successful request for list of links for all edOrgs and public data for this user/app"); return getPublicAndEdOrgListResponse(context); } @GET @Path("extract") @RightsAllowed({ Right.BULK_EXTRACT }) Response get(@Context HttpServletRequest request); @GET @Path("extract/{edOrgId}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId); @GET @Path("extract/public") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request); @GET @Path("extract/list") @RightsAllowed({ Right.BULK_EXTRACT }) Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context); @GET @Path("extract/{edOrgId}/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("edOrgId") String edOrgId, @PathParam("date") String date); @GET @Path("extract/public/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("date") String date); Repository<Entity> getMongoEntityRepository(); void setMongoEntityRepository(Repository<Entity> mongoEntityRepository); void setEdorgValidator(GenericToEdOrgValidator validator); void setFileResource(FileResource fileResource); static final String BULK_EXTRACT_FILES; static final String BULK_EXTRACT_FILE_PATH; static final String BULK_EXTRACT_DATE; static final DateTimeFormatter DATE_TIME_FORMATTER; }
|
@Test(expected = AccessDeniedException.class) public void testGetSLEAListFalseAppAuth() throws Exception { injector.setEducatorContext(); Entity mockEntity = mockApplicationEntity(); mockEntity.getBody().put("isBulkExtract", false); bulkExtract.getBulkExtractList(req, CONTEXT); }
@Test(expected = AccessDeniedException.class) public void testGetSLEAListCheckUserAssociatedSLEAsFailure() throws Exception { injector.setEducatorContext(); mockApplicationEntity(); bulkExtract.getBulkExtractList(req, CONTEXT); }
@Test() public void testGetLEAListNoUserAssociatedLEAs() throws Exception { injector.setEducatorContext(); mockApplicationEntity(); Mockito.when(edOrgHelper.getUserEdorgs(Mockito.any(Entity.class))).thenReturn(Arrays.asList("123")); Response res = bulkExtract.getBulkExtractList(req, CONTEXT); assertEquals(404, res.getStatus()); }
|
IdFieldEmittableKey extends EmittableKey { @Override public BSONObject toBSON() { BSONObject rval = new BasicBSONObject(); rval.put(getIdField().toString(), getId().toString()); return rval; } IdFieldEmittableKey(); IdFieldEmittableKey(final String mongoFieldName); Text getIdField(); Text getId(); void setId(final Text value); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
|
@Test public void testToBSON() { IdFieldEmittableKey key = new IdFieldEmittableKey("test.id.key.field"); key.setId(new Text("1234")); BSONObject bson = key.toBSON(); assertNotNull(bson); assertTrue(bson.containsField("test.id.key.field")); Object obj = bson.get("test.id.key.field"); assertNotNull(obj); assertTrue(obj instanceof String); String val = (String) obj; assertEquals(val, "1234"); }
|
BulkExtract { @GET @Path("extract/public") @RightsAllowed({ Right.BULK_EXTRACT }) public Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request) { logSecurityEvent("Received request to stream public data"); validateRequestCertificate(request); return getPublicExtractResponse(context.getRequest(), null); } @GET @Path("extract") @RightsAllowed({ Right.BULK_EXTRACT }) Response get(@Context HttpServletRequest request); @GET @Path("extract/{edOrgId}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getEdOrgExtract(@Context HttpContext context, @Context HttpServletRequest request, @PathParam("edOrgId") String edOrgId); @GET @Path("extract/public") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicExtract(@Context HttpContext context, @Context HttpServletRequest request); @GET @Path("extract/list") @RightsAllowed({ Right.BULK_EXTRACT }) Response getBulkExtractList(@Context HttpServletRequest request, @Context HttpContext context); @GET @Path("extract/{edOrgId}/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("edOrgId") String edOrgId, @PathParam("date") String date); @GET @Path("extract/public/delta/{date}") @RightsAllowed({ Right.BULK_EXTRACT }) Response getPublicDelta(@Context HttpServletRequest request, @Context HttpContext context,
@PathParam("date") String date); Repository<Entity> getMongoEntityRepository(); void setMongoEntityRepository(Repository<Entity> mongoEntityRepository); void setEdorgValidator(GenericToEdOrgValidator validator); void setFileResource(FileResource fileResource); static final String BULK_EXTRACT_FILES; static final String BULK_EXTRACT_FILE_PATH; static final String BULK_EXTRACT_DATE; static final DateTimeFormatter DATE_TIME_FORMATTER; }
|
@Test public void testPublicExtract() throws IOException, ParseException { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); Entity mockedEntity = mockBulkExtractEntity(null); Mockito.when(edOrgHelper.byId(eq("ONE"))).thenReturn(mockedEntity); Response res = bulkExtract.getPublicExtract(CONTEXT, req); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf(INPUT_FILE_NAME) > 0); Object entity = res.getEntity(); assertNotNull(entity); StreamingOutput out = (StreamingOutput) entity; ByteArrayOutputStream os = new ByteArrayOutputStream(); out.write(os); os.flush(); byte[] responseData = os.toByteArray(); String s = new String(responseData); assertEquals(BULK_DATA, s); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.