target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void testAppendOptionalFieldsNoOptionsGiven() { MultivaluedMap map = new MultivaluedMapImpl(); EntityBody body = new EntityBody(); body.put("student", "{\"somekey\":\"somevalue\"}"); List<EntityBody> entities = new ArrayList<EntityBody>(); entities.add(body); entities = optionalView.add(entities, ResourceNames.SECTIONS, map); assertEquals("Should only have one", 1, entities.size()); assertEquals("Should match", body, entities.get(0)); }
|
@Override public List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams) { if (factory == null) { return entities; } List<EntityBody> appendedEntities = entities; List<String> optionalFields = new ArrayList<String>(); if (queryParams.get(ParameterConstants.OPTIONAL_FIELDS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.OPTIONAL_FIELDS)); } if (queryParams.get(ParameterConstants.VIEWS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.VIEWS)); } if (!optionalFields.isEmpty()) { for (String type : optionalFields) { for (String appenderType : type.split(",")) { Map<String, String> values = extractOptionalFieldParams(appenderType); OptionalFieldAppender appender = factory.getOptionalFieldAppender(resource + "_" + values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); if (appender != null) { appendedEntities = appender.applyOptionalField(entities, values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); } } } } return appendedEntities; }
|
OptionalView implements View { @Override public List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams) { if (factory == null) { return entities; } List<EntityBody> appendedEntities = entities; List<String> optionalFields = new ArrayList<String>(); if (queryParams.get(ParameterConstants.OPTIONAL_FIELDS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.OPTIONAL_FIELDS)); } if (queryParams.get(ParameterConstants.VIEWS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.VIEWS)); } if (!optionalFields.isEmpty()) { for (String type : optionalFields) { for (String appenderType : type.split(",")) { Map<String, String> values = extractOptionalFieldParams(appenderType); OptionalFieldAppender appender = factory.getOptionalFieldAppender(resource + "_" + values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); if (appender != null) { appendedEntities = appender.applyOptionalField(entities, values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); } } } } return appendedEntities; } }
|
OptionalView implements View { @Override public List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams) { if (factory == null) { return entities; } List<EntityBody> appendedEntities = entities; List<String> optionalFields = new ArrayList<String>(); if (queryParams.get(ParameterConstants.OPTIONAL_FIELDS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.OPTIONAL_FIELDS)); } if (queryParams.get(ParameterConstants.VIEWS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.VIEWS)); } if (!optionalFields.isEmpty()) { for (String type : optionalFields) { for (String appenderType : type.split(",")) { Map<String, String> values = extractOptionalFieldParams(appenderType); OptionalFieldAppender appender = factory.getOptionalFieldAppender(resource + "_" + values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); if (appender != null) { appendedEntities = appender.applyOptionalField(entities, values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); } } } } return appendedEntities; } }
|
OptionalView implements View { @Override public List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams) { if (factory == null) { return entities; } List<EntityBody> appendedEntities = entities; List<String> optionalFields = new ArrayList<String>(); if (queryParams.get(ParameterConstants.OPTIONAL_FIELDS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.OPTIONAL_FIELDS)); } if (queryParams.get(ParameterConstants.VIEWS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.VIEWS)); } if (!optionalFields.isEmpty()) { for (String type : optionalFields) { for (String appenderType : type.split(",")) { Map<String, String> values = extractOptionalFieldParams(appenderType); OptionalFieldAppender appender = factory.getOptionalFieldAppender(resource + "_" + values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); if (appender != null) { appendedEntities = appender.applyOptionalField(entities, values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); } } } } return appendedEntities; } @Override List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams); }
|
OptionalView implements View { @Override public List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams) { if (factory == null) { return entities; } List<EntityBody> appendedEntities = entities; List<String> optionalFields = new ArrayList<String>(); if (queryParams.get(ParameterConstants.OPTIONAL_FIELDS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.OPTIONAL_FIELDS)); } if (queryParams.get(ParameterConstants.VIEWS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.VIEWS)); } if (!optionalFields.isEmpty()) { for (String type : optionalFields) { for (String appenderType : type.split(",")) { Map<String, String> values = extractOptionalFieldParams(appenderType); OptionalFieldAppender appender = factory.getOptionalFieldAppender(resource + "_" + values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); if (appender != null) { appendedEntities = appender.applyOptionalField(entities, values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); } } } } return appendedEntities; } @Override List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams); }
|
@Test public void testExtractOptionalFieldParams() { Map<String, String> values = optionalView.extractOptionalFieldParams("attendances.1"); assertEquals("Should match", "attendances", values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); assertEquals("Should match", "1", values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); values = optionalView.extractOptionalFieldParams("attendances"); assertEquals("Should match", "attendances", values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); assertEquals("Should match", null, values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); values = optionalView.extractOptionalFieldParams("attendances.1.2.3"); assertEquals("Should match", "attendances", values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); assertEquals("Should match", "1", values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); values = optionalView.extractOptionalFieldParams("attendances%1"); assertEquals("Should match", "attendances%1", values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); assertEquals("Should match", null, values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); values = optionalView.extractOptionalFieldParams("attendances.someparam"); assertEquals("Should match", "attendances", values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); assertEquals("Should match", "someparam", values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); }
|
protected Map<String, String> extractOptionalFieldParams(String optionalFieldValue) { Map<String, String> values = new HashMap<String, String>(); String appender = null, params = null; if (optionalFieldValue.contains(".")) { StringTokenizer st = new StringTokenizer(optionalFieldValue, "."); int index = 0; String token = null; while (st.hasMoreTokens()) { token = st.nextToken(); switch (index) { case 0: appender = token; break; case 1: params = token; break; } ++index; } } else { appender = optionalFieldValue; } values.put(OptionalFieldAppenderFactory.APPENDER_PREFIX, appender); values.put(OptionalFieldAppenderFactory.PARAM_PREFIX, params); return values; }
|
OptionalView implements View { protected Map<String, String> extractOptionalFieldParams(String optionalFieldValue) { Map<String, String> values = new HashMap<String, String>(); String appender = null, params = null; if (optionalFieldValue.contains(".")) { StringTokenizer st = new StringTokenizer(optionalFieldValue, "."); int index = 0; String token = null; while (st.hasMoreTokens()) { token = st.nextToken(); switch (index) { case 0: appender = token; break; case 1: params = token; break; } ++index; } } else { appender = optionalFieldValue; } values.put(OptionalFieldAppenderFactory.APPENDER_PREFIX, appender); values.put(OptionalFieldAppenderFactory.PARAM_PREFIX, params); return values; } }
|
OptionalView implements View { protected Map<String, String> extractOptionalFieldParams(String optionalFieldValue) { Map<String, String> values = new HashMap<String, String>(); String appender = null, params = null; if (optionalFieldValue.contains(".")) { StringTokenizer st = new StringTokenizer(optionalFieldValue, "."); int index = 0; String token = null; while (st.hasMoreTokens()) { token = st.nextToken(); switch (index) { case 0: appender = token; break; case 1: params = token; break; } ++index; } } else { appender = optionalFieldValue; } values.put(OptionalFieldAppenderFactory.APPENDER_PREFIX, appender); values.put(OptionalFieldAppenderFactory.PARAM_PREFIX, params); return values; } }
|
OptionalView implements View { protected Map<String, String> extractOptionalFieldParams(String optionalFieldValue) { Map<String, String> values = new HashMap<String, String>(); String appender = null, params = null; if (optionalFieldValue.contains(".")) { StringTokenizer st = new StringTokenizer(optionalFieldValue, "."); int index = 0; String token = null; while (st.hasMoreTokens()) { token = st.nextToken(); switch (index) { case 0: appender = token; break; case 1: params = token; break; } ++index; } } else { appender = optionalFieldValue; } values.put(OptionalFieldAppenderFactory.APPENDER_PREFIX, appender); values.put(OptionalFieldAppenderFactory.PARAM_PREFIX, params); return values; } @Override List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams); }
|
OptionalView implements View { protected Map<String, String> extractOptionalFieldParams(String optionalFieldValue) { Map<String, String> values = new HashMap<String, String>(); String appender = null, params = null; if (optionalFieldValue.contains(".")) { StringTokenizer st = new StringTokenizer(optionalFieldValue, "."); int index = 0; String token = null; while (st.hasMoreTokens()) { token = st.nextToken(); switch (index) { case 0: appender = token; break; case 1: params = token; break; } ++index; } } else { appender = optionalFieldValue; } values.put(OptionalFieldAppenderFactory.APPENDER_PREFIX, appender); values.put(OptionalFieldAppenderFactory.PARAM_PREFIX, params); return values; } @Override List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams); }
|
@Test public void testGetViewGenerator() { assertTrue("Should be of type studentassessment", factory.getOptionalFieldAppender(ResourceNames.SECTIONS + "_" + ParameterConstants.OPTIONAL_FIELD_ASSESSMENTS) instanceof StudentAssessmentOptionalFieldAppender); assertTrue("Should be of type studentgradebook", factory.getOptionalFieldAppender(ResourceNames.SECTIONS + "_" + ParameterConstants.OPTIONAL_FIELD_GRADEBOOK) instanceof StudentGradebookOptionalFieldAppender); assertTrue("Should be of type studenttranscript", factory.getOptionalFieldAppender(ResourceNames.SECTIONS + "_" + ParameterConstants.OPTIONAL_FIELD_TRANSCRIPT) instanceof StudentTranscriptOptionalFieldAppender); }
|
public OptionalFieldAppender getOptionalFieldAppender(String type) { return generators.get(type); }
|
OptionalFieldAppenderFactory { public OptionalFieldAppender getOptionalFieldAppender(String type) { return generators.get(type); } }
|
OptionalFieldAppenderFactory { public OptionalFieldAppender getOptionalFieldAppender(String type) { return generators.get(type); } }
|
OptionalFieldAppenderFactory { public OptionalFieldAppender getOptionalFieldAppender(String type) { return generators.get(type); } OptionalFieldAppender getOptionalFieldAppender(String type); }
|
OptionalFieldAppenderFactory { public OptionalFieldAppender getOptionalFieldAppender(String type) { return generators.get(type); } OptionalFieldAppender getOptionalFieldAppender(String type); static final String APPENDER_PREFIX; static final String PARAM_PREFIX; }
|
@Test public void testGetEntityFromList() { EntityBody body = helper.getEntityFromList(createEntityList(true), "field1", "2"); assertEquals("Should match", "2", body.get("field1")); assertEquals("Should match", "2", body.get("field2")); assertEquals("Should match", "2", body.get("id")); body = helper.getEntityFromList(null, "field1", "2"); assertNull("Should be null", body); body = helper.getEntityFromList(createEntityList(true), null, "2"); assertNull("Should be null", body); body = helper.getEntityFromList(createEntityList(true), "field1", null); assertNull("Should be null", body); body = helper.getEntityFromList(null, null, null); assertNull("Should be null", body); body = helper.getEntityFromList(createEntityList(true), "", ""); assertNull("Should be null", body); }
|
public EntityBody getEntityFromList(List<EntityBody> list, String field, String value) { if (list == null || field == null || value == null) { return null; } for (EntityBody e : list) { if (value.equals(e.get(field))) { return e; } } return null; }
|
OptionalFieldAppenderHelper { public EntityBody getEntityFromList(List<EntityBody> list, String field, String value) { if (list == null || field == null || value == null) { return null; } for (EntityBody e : list) { if (value.equals(e.get(field))) { return e; } } return null; } }
|
OptionalFieldAppenderHelper { public EntityBody getEntityFromList(List<EntityBody> list, String field, String value) { if (list == null || field == null || value == null) { return null; } for (EntityBody e : list) { if (value.equals(e.get(field))) { return e; } } return null; } }
|
OptionalFieldAppenderHelper { public EntityBody getEntityFromList(List<EntityBody> list, String field, String value) { if (list == null || field == null || value == null) { return null; } for (EntityBody e : list) { if (value.equals(e.get(field))) { return e; } } return null; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
OptionalFieldAppenderHelper { public EntityBody getEntityFromList(List<EntityBody> list, String field, String value) { if (list == null || field == null || value == null) { return null; } for (EntityBody e : list) { if (value.equals(e.get(field))) { return e; } } return null; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void testGetEntitySubList() { List<EntityBody> list = helper.getEntitySubList(createEntityList(true), "field1", "3"); assertEquals("Should match", 2, list.size()); assertEquals("Should match", "3", list.get(0).get("field1")); assertEquals("Should match", "3", list.get(1).get("field1")); list = helper.getEntitySubList(createEntityList(true), "field1", "0"); assertEquals("Should match", 0, list.size()); list = helper.getEntitySubList(null, "field1", "2"); assertEquals("Should match", 0, list.size()); list = helper.getEntitySubList(createEntityList(true), null, "2"); assertEquals("Should match", 0, list.size()); list = helper.getEntitySubList(createEntityList(true), "field1", null); assertEquals("Should match", 0, list.size()); list = helper.getEntitySubList(null, null, null); assertEquals("Should match", 0, list.size()); list = helper.getEntitySubList(createEntityList(true), "", ""); assertEquals("Should match", 0, list.size()); }
|
public List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value) { List<EntityBody> results = new ArrayList<EntityBody>(); if (list == null || field == null || value == null) { return results; } for (EntityBody e : list) { if (value.equals(e.get(field))) { results.add(e); } } return results; }
|
OptionalFieldAppenderHelper { public List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value) { List<EntityBody> results = new ArrayList<EntityBody>(); if (list == null || field == null || value == null) { return results; } for (EntityBody e : list) { if (value.equals(e.get(field))) { results.add(e); } } return results; } }
|
OptionalFieldAppenderHelper { public List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value) { List<EntityBody> results = new ArrayList<EntityBody>(); if (list == null || field == null || value == null) { return results; } for (EntityBody e : list) { if (value.equals(e.get(field))) { results.add(e); } } return results; } }
|
OptionalFieldAppenderHelper { public List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value) { List<EntityBody> results = new ArrayList<EntityBody>(); if (list == null || field == null || value == null) { return results; } for (EntityBody e : list) { if (value.equals(e.get(field))) { results.add(e); } } return results; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
OptionalFieldAppenderHelper { public List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value) { List<EntityBody> results = new ArrayList<EntityBody>(); if (list == null || field == null || value == null) { return results; } for (EntityBody e : list) { if (value.equals(e.get(field))) { results.add(e); } } return results; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void testGetIdList() { List<String> list = helper.getIdList(createEntityList(true), "id"); assertEquals("Should match", 4, list.size()); assertTrue("Should contain", list.contains("1")); assertTrue("Should contain", list.contains("2")); assertTrue("Should contain", list.contains("3")); assertTrue("Should contain", list.contains("4")); assertFalse("Should not contain", list.contains("5")); list = helper.getIdList(null, "id"); assertEquals("Should match", 0, list.size()); list = helper.getIdList(null, null); assertEquals("Should match", 0, list.size()); list = helper.getIdList(createEntityList(true), ""); assertEquals("Should match", 0, list.size()); }
|
public List<String> getIdList(List<EntityBody> list, String field) { List<String> ids = new ArrayList<String>(); if (list == null || field == null) { return ids; } for (EntityBody e : list) { if (e.get(field) != null) { ids.add((String) e.get(field)); } } return ids; }
|
OptionalFieldAppenderHelper { public List<String> getIdList(List<EntityBody> list, String field) { List<String> ids = new ArrayList<String>(); if (list == null || field == null) { return ids; } for (EntityBody e : list) { if (e.get(field) != null) { ids.add((String) e.get(field)); } } return ids; } }
|
OptionalFieldAppenderHelper { public List<String> getIdList(List<EntityBody> list, String field) { List<String> ids = new ArrayList<String>(); if (list == null || field == null) { return ids; } for (EntityBody e : list) { if (e.get(field) != null) { ids.add((String) e.get(field)); } } return ids; } }
|
OptionalFieldAppenderHelper { public List<String> getIdList(List<EntityBody> list, String field) { List<String> ids = new ArrayList<String>(); if (list == null || field == null) { return ids; } for (EntityBody e : list) { if (e.get(field) != null) { ids.add((String) e.get(field)); } } return ids; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
OptionalFieldAppenderHelper { public List<String> getIdList(List<EntityBody> list, String field) { List<String> ids = new ArrayList<String>(); if (list == null || field == null) { return ids; } for (EntityBody e : list) { if (e.get(field) != null) { ids.add((String) e.get(field)); } } return ids; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void testSectionIds() { Set<String> list = helper.getSectionIds(createEntityList(true)); assertEquals("Should match", 4, list.size()); assertTrue("Should be true", list.contains("1")); assertTrue("Should be true", list.contains("2")); assertTrue("Should be true", list.contains("3")); assertTrue("Should be true", list.contains("4")); }
|
public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void testSectionIdsNoAssociation() { Set<String> list = helper.getSectionIds(createEntityList(false)); assertTrue("List should be empty", list.isEmpty()); }
|
public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void testApplyOptionalField() { List<EntityBody> entities = new ArrayList<EntityBody>(); entities.add(new EntityBody(createTestStudentEntityWithSectionAssociation(STUDENT_ID, SECTION_ID))); entities = studentGradebookOptionalFieldAppender.applyOptionalField(entities, null); assertEquals("Should be 1", 1, entities.size()); List<EntityBody> studentGradebookAssociations = (List<EntityBody>) entities.get(0).get("studentGradebookEntries"); assertEquals("Should match", 2, studentGradebookAssociations.size()); assertEquals("Should match", STUDENT_ID, studentGradebookAssociations.get(0).get("studentId")); assertEquals("Should match", SECTION_ID, studentGradebookAssociations.get(0).get("sectionId")); EntityBody body = (EntityBody) ((List<EntityBody>) entities.get(0).get("studentGradebookEntries")).get(0); EntityBody gradebookEntry = (EntityBody) body.get("gradebookEntries"); assertNotNull("Should not be null", gradebookEntry); assertEquals("Should match", "Unit Tests", gradebookEntry.get("gradebookEntryType")); assertEquals("", gradebookEntry.get("id"), body.get("gradebookEntryId")); }
|
@Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> sectionIds = new ArrayList<String>(optionalFieldAppenderHelper.getSectionIds(entities)); List<EntityBody> studentGradebookEntries; if (sectionIds.size() != 0) { studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.SECTION_ID, sectionIds); } else { List<String> studentIds = new ArrayList<String>(optionalFieldAppenderHelper.getIdList(entities, "id")); studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.STUDENT_ID, studentIds); } List<String> gradebookEntryIds = optionalFieldAppenderHelper.getIdList(studentGradebookEntries, ParameterConstants.GRADEBOOK_ENTRY_ID); List<EntityBody> gradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.GRADEBOOK_ENTRIES, "_id", gradebookEntryIds); for (EntityBody student : entities) { List<EntityBody> studentGradebookEntriesForStudent = optionalFieldAppenderHelper.getEntitySubList(studentGradebookEntries, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentGradebookEntry : studentGradebookEntriesForStudent) { EntityBody gradebookEntry = optionalFieldAppenderHelper.getEntityFromList(gradebookEntries, "id", (String) studentGradebookEntry.get(ParameterConstants.GRADEBOOK_ENTRY_ID)); if (gradebookEntry != null) { studentGradebookEntry.put(PathConstants.GRADEBOOK_ENTRIES, gradebookEntry); } } student.put(PathConstants.STUDENT_GRADEBOOK_ENTRIES, studentGradebookEntriesForStudent); } return entities; }
|
StudentGradebookOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> sectionIds = new ArrayList<String>(optionalFieldAppenderHelper.getSectionIds(entities)); List<EntityBody> studentGradebookEntries; if (sectionIds.size() != 0) { studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.SECTION_ID, sectionIds); } else { List<String> studentIds = new ArrayList<String>(optionalFieldAppenderHelper.getIdList(entities, "id")); studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.STUDENT_ID, studentIds); } List<String> gradebookEntryIds = optionalFieldAppenderHelper.getIdList(studentGradebookEntries, ParameterConstants.GRADEBOOK_ENTRY_ID); List<EntityBody> gradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.GRADEBOOK_ENTRIES, "_id", gradebookEntryIds); for (EntityBody student : entities) { List<EntityBody> studentGradebookEntriesForStudent = optionalFieldAppenderHelper.getEntitySubList(studentGradebookEntries, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentGradebookEntry : studentGradebookEntriesForStudent) { EntityBody gradebookEntry = optionalFieldAppenderHelper.getEntityFromList(gradebookEntries, "id", (String) studentGradebookEntry.get(ParameterConstants.GRADEBOOK_ENTRY_ID)); if (gradebookEntry != null) { studentGradebookEntry.put(PathConstants.GRADEBOOK_ENTRIES, gradebookEntry); } } student.put(PathConstants.STUDENT_GRADEBOOK_ENTRIES, studentGradebookEntriesForStudent); } return entities; } }
|
StudentGradebookOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> sectionIds = new ArrayList<String>(optionalFieldAppenderHelper.getSectionIds(entities)); List<EntityBody> studentGradebookEntries; if (sectionIds.size() != 0) { studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.SECTION_ID, sectionIds); } else { List<String> studentIds = new ArrayList<String>(optionalFieldAppenderHelper.getIdList(entities, "id")); studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.STUDENT_ID, studentIds); } List<String> gradebookEntryIds = optionalFieldAppenderHelper.getIdList(studentGradebookEntries, ParameterConstants.GRADEBOOK_ENTRY_ID); List<EntityBody> gradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.GRADEBOOK_ENTRIES, "_id", gradebookEntryIds); for (EntityBody student : entities) { List<EntityBody> studentGradebookEntriesForStudent = optionalFieldAppenderHelper.getEntitySubList(studentGradebookEntries, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentGradebookEntry : studentGradebookEntriesForStudent) { EntityBody gradebookEntry = optionalFieldAppenderHelper.getEntityFromList(gradebookEntries, "id", (String) studentGradebookEntry.get(ParameterConstants.GRADEBOOK_ENTRY_ID)); if (gradebookEntry != null) { studentGradebookEntry.put(PathConstants.GRADEBOOK_ENTRIES, gradebookEntry); } } student.put(PathConstants.STUDENT_GRADEBOOK_ENTRIES, studentGradebookEntriesForStudent); } return entities; } }
|
StudentGradebookOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> sectionIds = new ArrayList<String>(optionalFieldAppenderHelper.getSectionIds(entities)); List<EntityBody> studentGradebookEntries; if (sectionIds.size() != 0) { studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.SECTION_ID, sectionIds); } else { List<String> studentIds = new ArrayList<String>(optionalFieldAppenderHelper.getIdList(entities, "id")); studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.STUDENT_ID, studentIds); } List<String> gradebookEntryIds = optionalFieldAppenderHelper.getIdList(studentGradebookEntries, ParameterConstants.GRADEBOOK_ENTRY_ID); List<EntityBody> gradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.GRADEBOOK_ENTRIES, "_id", gradebookEntryIds); for (EntityBody student : entities) { List<EntityBody> studentGradebookEntriesForStudent = optionalFieldAppenderHelper.getEntitySubList(studentGradebookEntries, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentGradebookEntry : studentGradebookEntriesForStudent) { EntityBody gradebookEntry = optionalFieldAppenderHelper.getEntityFromList(gradebookEntries, "id", (String) studentGradebookEntry.get(ParameterConstants.GRADEBOOK_ENTRY_ID)); if (gradebookEntry != null) { studentGradebookEntry.put(PathConstants.GRADEBOOK_ENTRIES, gradebookEntry); } } student.put(PathConstants.STUDENT_GRADEBOOK_ENTRIES, studentGradebookEntriesForStudent); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
StudentGradebookOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> sectionIds = new ArrayList<String>(optionalFieldAppenderHelper.getSectionIds(entities)); List<EntityBody> studentGradebookEntries; if (sectionIds.size() != 0) { studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.SECTION_ID, sectionIds); } else { List<String> studentIds = new ArrayList<String>(optionalFieldAppenderHelper.getIdList(entities, "id")); studentGradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, ParameterConstants.STUDENT_ID, studentIds); } List<String> gradebookEntryIds = optionalFieldAppenderHelper.getIdList(studentGradebookEntries, ParameterConstants.GRADEBOOK_ENTRY_ID); List<EntityBody> gradebookEntries = optionalFieldAppenderHelper.queryEntities(ResourceNames.GRADEBOOK_ENTRIES, "_id", gradebookEntryIds); for (EntityBody student : entities) { List<EntityBody> studentGradebookEntriesForStudent = optionalFieldAppenderHelper.getEntitySubList(studentGradebookEntries, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentGradebookEntry : studentGradebookEntriesForStudent) { EntityBody gradebookEntry = optionalFieldAppenderHelper.getEntityFromList(gradebookEntries, "id", (String) studentGradebookEntry.get(ParameterConstants.GRADEBOOK_ENTRY_ID)); if (gradebookEntry != null) { studentGradebookEntry.put(PathConstants.GRADEBOOK_ENTRIES, gradebookEntry); } } student.put(PathConstants.STUDENT_GRADEBOOK_ENTRIES, studentGradebookEntriesForStudent); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
@SuppressWarnings("unchecked") @Test public void testApplyOptionalField() { setupMockForApplyOptionalField(); List<EntityBody> entities = new ArrayList<EntityBody>(); entities.add(makeEntityBody(student1Entity)); entities.add(makeEntityBody(student2Entity)); entities = studentAllAttendanceOptionalFieldAppender.applyOptionalField(entities, null); assertEquals("Should be 2", 2, entities.size()); assertNotNull("Should not be null", entities.get(0).get("attendances")); List<EntityBody> attendances1 = (List<EntityBody>) ((EntityBody) entities.get(0).get("attendances")).get("attendances"); assertEquals("Should match", 6, attendances1.size()); List<EntityBody> attendances2 = (List<EntityBody>) ((EntityBody) entities.get(1).get("attendances")).get("attendances"); assertEquals("Should match", 3, attendances2.size()); }
|
@SuppressWarnings("unchecked") @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setLimit(0); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_ID, NeutralCriteria.CRITERIA_IN, studentIds)); List<EntityBody> attendances = optionalFieldAppenderHelper.queryEntities(ResourceNames.ATTENDANCES, neutralQuery); Map<String, List<EntityBody>> attendancesPerStudent = new HashMap<String, List<EntityBody>>(); for (EntityBody attendance : attendances) { String studentId = (String) attendance.get("studentId"); List<EntityBody> events = new ArrayList<EntityBody>(); if (attendance.containsKey("attendanceEvent")) { List<Map<String, Object>> yearEvents = (List<Map<String, Object>>) attendance.get("attendanceEvent"); if (yearEvents != null) { for (int j = 0; j < yearEvents.size(); j++) { events.add(new EntityBody(yearEvents.get(j))); } } } if (attendancesPerStudent.containsKey(studentId)) { attendancesPerStudent.get(studentId).addAll(events); } else { attendancesPerStudent.put(studentId, events); } } for (EntityBody student : entities) { String id = (String) student.get("id"); List<EntityBody> attendancesForStudent = attendancesPerStudent.get(id); if (attendancesForStudent != null && !attendancesForStudent.isEmpty()) { EntityBody attendancesBody = new EntityBody(); attendancesBody.put(ResourceNames.ATTENDANCES, attendancesForStudent); student.put(ParameterConstants.OPTIONAL_FIELD_ATTENDANCES, attendancesBody); } } return entities; }
|
StudentAllAttendanceOptionalFieldAppender implements OptionalFieldAppender { @SuppressWarnings("unchecked") @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setLimit(0); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_ID, NeutralCriteria.CRITERIA_IN, studentIds)); List<EntityBody> attendances = optionalFieldAppenderHelper.queryEntities(ResourceNames.ATTENDANCES, neutralQuery); Map<String, List<EntityBody>> attendancesPerStudent = new HashMap<String, List<EntityBody>>(); for (EntityBody attendance : attendances) { String studentId = (String) attendance.get("studentId"); List<EntityBody> events = new ArrayList<EntityBody>(); if (attendance.containsKey("attendanceEvent")) { List<Map<String, Object>> yearEvents = (List<Map<String, Object>>) attendance.get("attendanceEvent"); if (yearEvents != null) { for (int j = 0; j < yearEvents.size(); j++) { events.add(new EntityBody(yearEvents.get(j))); } } } if (attendancesPerStudent.containsKey(studentId)) { attendancesPerStudent.get(studentId).addAll(events); } else { attendancesPerStudent.put(studentId, events); } } for (EntityBody student : entities) { String id = (String) student.get("id"); List<EntityBody> attendancesForStudent = attendancesPerStudent.get(id); if (attendancesForStudent != null && !attendancesForStudent.isEmpty()) { EntityBody attendancesBody = new EntityBody(); attendancesBody.put(ResourceNames.ATTENDANCES, attendancesForStudent); student.put(ParameterConstants.OPTIONAL_FIELD_ATTENDANCES, attendancesBody); } } return entities; } }
|
StudentAllAttendanceOptionalFieldAppender implements OptionalFieldAppender { @SuppressWarnings("unchecked") @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setLimit(0); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_ID, NeutralCriteria.CRITERIA_IN, studentIds)); List<EntityBody> attendances = optionalFieldAppenderHelper.queryEntities(ResourceNames.ATTENDANCES, neutralQuery); Map<String, List<EntityBody>> attendancesPerStudent = new HashMap<String, List<EntityBody>>(); for (EntityBody attendance : attendances) { String studentId = (String) attendance.get("studentId"); List<EntityBody> events = new ArrayList<EntityBody>(); if (attendance.containsKey("attendanceEvent")) { List<Map<String, Object>> yearEvents = (List<Map<String, Object>>) attendance.get("attendanceEvent"); if (yearEvents != null) { for (int j = 0; j < yearEvents.size(); j++) { events.add(new EntityBody(yearEvents.get(j))); } } } if (attendancesPerStudent.containsKey(studentId)) { attendancesPerStudent.get(studentId).addAll(events); } else { attendancesPerStudent.put(studentId, events); } } for (EntityBody student : entities) { String id = (String) student.get("id"); List<EntityBody> attendancesForStudent = attendancesPerStudent.get(id); if (attendancesForStudent != null && !attendancesForStudent.isEmpty()) { EntityBody attendancesBody = new EntityBody(); attendancesBody.put(ResourceNames.ATTENDANCES, attendancesForStudent); student.put(ParameterConstants.OPTIONAL_FIELD_ATTENDANCES, attendancesBody); } } return entities; } }
|
StudentAllAttendanceOptionalFieldAppender implements OptionalFieldAppender { @SuppressWarnings("unchecked") @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setLimit(0); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_ID, NeutralCriteria.CRITERIA_IN, studentIds)); List<EntityBody> attendances = optionalFieldAppenderHelper.queryEntities(ResourceNames.ATTENDANCES, neutralQuery); Map<String, List<EntityBody>> attendancesPerStudent = new HashMap<String, List<EntityBody>>(); for (EntityBody attendance : attendances) { String studentId = (String) attendance.get("studentId"); List<EntityBody> events = new ArrayList<EntityBody>(); if (attendance.containsKey("attendanceEvent")) { List<Map<String, Object>> yearEvents = (List<Map<String, Object>>) attendance.get("attendanceEvent"); if (yearEvents != null) { for (int j = 0; j < yearEvents.size(); j++) { events.add(new EntityBody(yearEvents.get(j))); } } } if (attendancesPerStudent.containsKey(studentId)) { attendancesPerStudent.get(studentId).addAll(events); } else { attendancesPerStudent.put(studentId, events); } } for (EntityBody student : entities) { String id = (String) student.get("id"); List<EntityBody> attendancesForStudent = attendancesPerStudent.get(id); if (attendancesForStudent != null && !attendancesForStudent.isEmpty()) { EntityBody attendancesBody = new EntityBody(); attendancesBody.put(ResourceNames.ATTENDANCES, attendancesForStudent); student.put(ParameterConstants.OPTIONAL_FIELD_ATTENDANCES, attendancesBody); } } return entities; } @SuppressWarnings("unchecked") @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
StudentAllAttendanceOptionalFieldAppender implements OptionalFieldAppender { @SuppressWarnings("unchecked") @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setLimit(0); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_ID, NeutralCriteria.CRITERIA_IN, studentIds)); List<EntityBody> attendances = optionalFieldAppenderHelper.queryEntities(ResourceNames.ATTENDANCES, neutralQuery); Map<String, List<EntityBody>> attendancesPerStudent = new HashMap<String, List<EntityBody>>(); for (EntityBody attendance : attendances) { String studentId = (String) attendance.get("studentId"); List<EntityBody> events = new ArrayList<EntityBody>(); if (attendance.containsKey("attendanceEvent")) { List<Map<String, Object>> yearEvents = (List<Map<String, Object>>) attendance.get("attendanceEvent"); if (yearEvents != null) { for (int j = 0; j < yearEvents.size(); j++) { events.add(new EntityBody(yearEvents.get(j))); } } } if (attendancesPerStudent.containsKey(studentId)) { attendancesPerStudent.get(studentId).addAll(events); } else { attendancesPerStudent.put(studentId, events); } } for (EntityBody student : entities) { String id = (String) student.get("id"); List<EntityBody> attendancesForStudent = attendancesPerStudent.get(id); if (attendancesForStudent != null && !attendancesForStudent.isEmpty()) { EntityBody attendancesBody = new EntityBody(); attendancesBody.put(ResourceNames.ATTENDANCES, attendancesForStudent); student.put(ParameterConstants.OPTIONAL_FIELD_ATTENDANCES, attendancesBody); } } return entities; } @SuppressWarnings("unchecked") @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
@Test public void testApplyOptionalField() { List<EntityBody> entities = new ArrayList<EntityBody>(); entities.add(new EntityBody(createTestStudentEntity(STUDENT_ID))); entities = studentAssessmentOptionalFieldAppender.applyOptionalField(entities, null); assertEquals("Should be 1", 1, entities.size()); List<EntityBody> studentAssessments = (List<EntityBody>) entities.get(0).get("studentAssessments"); assertEquals("Should match", 2, studentAssessments.size()); assertEquals("Should match", STUDENT_ID, studentAssessments.get(0).get("studentId")); EntityBody body = (EntityBody) ((List<EntityBody>) entities.get(0).get("studentAssessments")).get(0); EntityBody assessment = (EntityBody) body.get("assessments"); assertNotNull("Should not be null", assessment); assertEquals("Should match", "Reading", assessment.get("academicSubject")); assertEquals("", assessment.get("id"), body.get("assessmentId")); }
|
@Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentAssessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ASSESSMENTS, ParameterConstants.STUDENT_ID, studentIds); List<String> assessmentIds = optionalFieldAppenderHelper.getIdList(studentAssessments, ParameterConstants.ASSESSMENT_ID); List<EntityBody> assessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.ASSESSMENTS, "_id", assessmentIds); for (EntityBody student : entities) { List<EntityBody> studentAssessmentsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAssessments, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentAssessment : studentAssessmentsForStudent) { EntityBody assessment = optionalFieldAppenderHelper.getEntityFromList(assessments, "id", (String) studentAssessment.get(ParameterConstants.ASSESSMENT_ID)); studentAssessment.put(PathConstants.ASSESSMENTS, assessment); } student.put(PathConstants.STUDENT_ASSESSMENTS, studentAssessmentsForStudent); } return entities; }
|
StudentAssessmentOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentAssessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ASSESSMENTS, ParameterConstants.STUDENT_ID, studentIds); List<String> assessmentIds = optionalFieldAppenderHelper.getIdList(studentAssessments, ParameterConstants.ASSESSMENT_ID); List<EntityBody> assessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.ASSESSMENTS, "_id", assessmentIds); for (EntityBody student : entities) { List<EntityBody> studentAssessmentsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAssessments, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentAssessment : studentAssessmentsForStudent) { EntityBody assessment = optionalFieldAppenderHelper.getEntityFromList(assessments, "id", (String) studentAssessment.get(ParameterConstants.ASSESSMENT_ID)); studentAssessment.put(PathConstants.ASSESSMENTS, assessment); } student.put(PathConstants.STUDENT_ASSESSMENTS, studentAssessmentsForStudent); } return entities; } }
|
StudentAssessmentOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentAssessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ASSESSMENTS, ParameterConstants.STUDENT_ID, studentIds); List<String> assessmentIds = optionalFieldAppenderHelper.getIdList(studentAssessments, ParameterConstants.ASSESSMENT_ID); List<EntityBody> assessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.ASSESSMENTS, "_id", assessmentIds); for (EntityBody student : entities) { List<EntityBody> studentAssessmentsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAssessments, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentAssessment : studentAssessmentsForStudent) { EntityBody assessment = optionalFieldAppenderHelper.getEntityFromList(assessments, "id", (String) studentAssessment.get(ParameterConstants.ASSESSMENT_ID)); studentAssessment.put(PathConstants.ASSESSMENTS, assessment); } student.put(PathConstants.STUDENT_ASSESSMENTS, studentAssessmentsForStudent); } return entities; } }
|
StudentAssessmentOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentAssessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ASSESSMENTS, ParameterConstants.STUDENT_ID, studentIds); List<String> assessmentIds = optionalFieldAppenderHelper.getIdList(studentAssessments, ParameterConstants.ASSESSMENT_ID); List<EntityBody> assessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.ASSESSMENTS, "_id", assessmentIds); for (EntityBody student : entities) { List<EntityBody> studentAssessmentsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAssessments, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentAssessment : studentAssessmentsForStudent) { EntityBody assessment = optionalFieldAppenderHelper.getEntityFromList(assessments, "id", (String) studentAssessment.get(ParameterConstants.ASSESSMENT_ID)); studentAssessment.put(PathConstants.ASSESSMENTS, assessment); } student.put(PathConstants.STUDENT_ASSESSMENTS, studentAssessmentsForStudent); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
StudentAssessmentOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentAssessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ASSESSMENTS, ParameterConstants.STUDENT_ID, studentIds); List<String> assessmentIds = optionalFieldAppenderHelper.getIdList(studentAssessments, ParameterConstants.ASSESSMENT_ID); List<EntityBody> assessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.ASSESSMENTS, "_id", assessmentIds); for (EntityBody student : entities) { List<EntityBody> studentAssessmentsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAssessments, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentAssessment : studentAssessmentsForStudent) { EntityBody assessment = optionalFieldAppenderHelper.getEntityFromList(assessments, "id", (String) studentAssessment.get(ParameterConstants.ASSESSMENT_ID)); studentAssessment.put(PathConstants.ASSESSMENTS, assessment); } student.put(PathConstants.STUDENT_ASSESSMENTS, studentAssessmentsForStudent); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
@Test(expected = MissingArgumentException.class) public void missingPasswordValue() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "-s", "server", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
|
public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); }
|
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } }
|
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); }
|
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); }
|
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); static final String KEY_USER; static final String KEY_PASSWORD; static final String KEY_SFTP_SERVER; static final String KEY_LOCAL_DIRECTORY; static final String KEY_PORT; final static Options OPTIONS; }
|
@Test public void testApplyOptionalField() { List<EntityBody> entities = new ArrayList<EntityBody>(); EntityBody body = new EntityBody(); body.putAll(studentEntity.getBody()); body.put("id", studentEntity.getEntityId()); entities.add(body); entities = studentTranscriptOptionalFieldAppender.applyOptionalField(entities, null); assertEquals("Should match", 1, entities.size()); EntityBody transcripts = (EntityBody) entities.get(0).get("transcript"); assertNotNull("Should be not null", transcripts); List<EntityBody> studentSectionAssociations = (List<EntityBody>) transcripts.get("studentSectionAssociations"); assertNotNull("Should be not null", studentSectionAssociations); assertEquals("Should match", 2, studentSectionAssociations.size()); EntityBody section = (EntityBody) studentSectionAssociations.get(0).get("sections"); assertNotNull("Should not be null", section); assertNotNull("Should not be null", section.get("sessions")); assertEquals("Should match", "1999", ((EntityBody) section.get("sessions")).get("schoolYear")); assertEquals("Should match", section.get("sessionId"), ((EntityBody) section.get("sessions")).get("id")); assertNotNull("Should not be null", section.get("courses")); assertEquals("Should match", "Math", ((EntityBody) section.get("courses")).get("courseTitle")); assertEquals("Should match", "Math A", section.get("sectionname")); List<EntityBody> courseTranscripts = (List<EntityBody>) transcripts.get("courseTranscripts"); assertNotNull("Should not be null", courseTranscripts); assertEquals("Should match", 2, courseTranscripts.size()); assertEquals("Should match", "A", courseTranscripts.get(0).get("letterGradeEarned")); }
|
@Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSectionAssociations = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_SECTION_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); List<String> sectionIds = optionalFieldAppenderHelper.getIdList(studentSectionAssociations, ParameterConstants.SECTION_ID); List<EntityBody> sections = optionalFieldAppenderHelper.queryEntities(ResourceNames.SECTIONS, "_id", sectionIds); List<EntityBody> studentAcademicRecords = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); List<String> studentAcademicRecordIds = optionalFieldAppenderHelper.getIdList(studentAcademicRecords, "id"); List<EntityBody> courseTranscripts = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_TRANSCRIPTS, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordIds); List<String> sessionIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.SESSION_ID); List<EntityBody> sessions = optionalFieldAppenderHelper .queryEntities(ResourceNames.SESSIONS, "_id", sessionIds); List<String> courseOfferingIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.COURSE_OFFERING_ID); List<EntityBody> courseOfferings = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_OFFERINGS, "_id", courseOfferingIds); List<String> courseIds = optionalFieldAppenderHelper.getIdList(courseOfferings, ParameterConstants.COURSE_ID); List<EntityBody> courses = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSES, "_id", courseIds); List<EntityBody> studentAcademicRecordsForStudents = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); for (EntityBody student : entities) { String studentId = (String) student.get("id"); List<EntityBody> studentSectionAssociationsForStudent = optionalFieldAppenderHelper.getEntitySubList( studentSectionAssociations, ParameterConstants.STUDENT_ID, studentId); List<EntityBody> studentCourseTranscripts = new ArrayList<EntityBody>(); for (EntityBody studentSectionAssociationForStudent : studentSectionAssociationsForStudent) { String sectionId = (String) studentSectionAssociationForStudent.get(ParameterConstants.SECTION_ID); EntityBody sectionForStudent = optionalFieldAppenderHelper.getEntityFromList(sections, "id", sectionId); if (sectionForStudent == null) { continue; } EntityBody sessionForSection = optionalFieldAppenderHelper.getEntityFromList(sessions, "id", (String) sectionForStudent.get(ParameterConstants.SESSION_ID)); EntityBody courseOfferingForSection = optionalFieldAppenderHelper.getEntityFromList(courseOfferings, "id", (String) sectionForStudent.get(ParameterConstants.COURSE_OFFERING_ID)); if (courseOfferingForSection == null) { continue; } EntityBody courseForSection = optionalFieldAppenderHelper.getEntityFromList(courses, "id", (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); List<EntityBody> studentAcademicRecordsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAcademicRecordsForStudents, ParameterConstants.STUDENT_ID, studentId); List<String> studentAcademicRecordIdsForStudent = optionalFieldAppenderHelper.getIdList(studentAcademicRecordsForStudent, "id"); List<EntityBody> studentTranscriptsForStudent = new ArrayList<EntityBody>(); for (String studentAcademicRecordId : studentAcademicRecordIdsForStudent) { studentTranscriptsForStudent.addAll(optionalFieldAppenderHelper.getEntitySubList(courseTranscripts, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordId)); } List<EntityBody> studentTranscriptsForStudentAndCourse = optionalFieldAppenderHelper.getEntitySubList( studentTranscriptsForStudent, ParameterConstants.COURSE_ID, (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); studentCourseTranscripts.addAll(studentTranscriptsForStudentAndCourse); sectionForStudent.put(PathConstants.SESSIONS, sessionForSection); sectionForStudent.put(PathConstants.COURSES, courseForSection); studentSectionAssociationForStudent.put(PathConstants.SECTIONS, sectionForStudent); } EntityBody body = new EntityBody(); body.put(PathConstants.STUDENT_SECTION_ASSOCIATIONS, studentSectionAssociationsForStudent); body.put(PathConstants.COURSE_TRANSCRIPTS, studentCourseTranscripts); student.put(ParameterConstants.OPTIONAL_FIELD_TRANSCRIPT, body); } return entities; }
|
StudentTranscriptOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSectionAssociations = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_SECTION_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); List<String> sectionIds = optionalFieldAppenderHelper.getIdList(studentSectionAssociations, ParameterConstants.SECTION_ID); List<EntityBody> sections = optionalFieldAppenderHelper.queryEntities(ResourceNames.SECTIONS, "_id", sectionIds); List<EntityBody> studentAcademicRecords = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); List<String> studentAcademicRecordIds = optionalFieldAppenderHelper.getIdList(studentAcademicRecords, "id"); List<EntityBody> courseTranscripts = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_TRANSCRIPTS, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordIds); List<String> sessionIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.SESSION_ID); List<EntityBody> sessions = optionalFieldAppenderHelper .queryEntities(ResourceNames.SESSIONS, "_id", sessionIds); List<String> courseOfferingIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.COURSE_OFFERING_ID); List<EntityBody> courseOfferings = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_OFFERINGS, "_id", courseOfferingIds); List<String> courseIds = optionalFieldAppenderHelper.getIdList(courseOfferings, ParameterConstants.COURSE_ID); List<EntityBody> courses = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSES, "_id", courseIds); List<EntityBody> studentAcademicRecordsForStudents = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); for (EntityBody student : entities) { String studentId = (String) student.get("id"); List<EntityBody> studentSectionAssociationsForStudent = optionalFieldAppenderHelper.getEntitySubList( studentSectionAssociations, ParameterConstants.STUDENT_ID, studentId); List<EntityBody> studentCourseTranscripts = new ArrayList<EntityBody>(); for (EntityBody studentSectionAssociationForStudent : studentSectionAssociationsForStudent) { String sectionId = (String) studentSectionAssociationForStudent.get(ParameterConstants.SECTION_ID); EntityBody sectionForStudent = optionalFieldAppenderHelper.getEntityFromList(sections, "id", sectionId); if (sectionForStudent == null) { continue; } EntityBody sessionForSection = optionalFieldAppenderHelper.getEntityFromList(sessions, "id", (String) sectionForStudent.get(ParameterConstants.SESSION_ID)); EntityBody courseOfferingForSection = optionalFieldAppenderHelper.getEntityFromList(courseOfferings, "id", (String) sectionForStudent.get(ParameterConstants.COURSE_OFFERING_ID)); if (courseOfferingForSection == null) { continue; } EntityBody courseForSection = optionalFieldAppenderHelper.getEntityFromList(courses, "id", (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); List<EntityBody> studentAcademicRecordsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAcademicRecordsForStudents, ParameterConstants.STUDENT_ID, studentId); List<String> studentAcademicRecordIdsForStudent = optionalFieldAppenderHelper.getIdList(studentAcademicRecordsForStudent, "id"); List<EntityBody> studentTranscriptsForStudent = new ArrayList<EntityBody>(); for (String studentAcademicRecordId : studentAcademicRecordIdsForStudent) { studentTranscriptsForStudent.addAll(optionalFieldAppenderHelper.getEntitySubList(courseTranscripts, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordId)); } List<EntityBody> studentTranscriptsForStudentAndCourse = optionalFieldAppenderHelper.getEntitySubList( studentTranscriptsForStudent, ParameterConstants.COURSE_ID, (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); studentCourseTranscripts.addAll(studentTranscriptsForStudentAndCourse); sectionForStudent.put(PathConstants.SESSIONS, sessionForSection); sectionForStudent.put(PathConstants.COURSES, courseForSection); studentSectionAssociationForStudent.put(PathConstants.SECTIONS, sectionForStudent); } EntityBody body = new EntityBody(); body.put(PathConstants.STUDENT_SECTION_ASSOCIATIONS, studentSectionAssociationsForStudent); body.put(PathConstants.COURSE_TRANSCRIPTS, studentCourseTranscripts); student.put(ParameterConstants.OPTIONAL_FIELD_TRANSCRIPT, body); } return entities; } }
|
StudentTranscriptOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSectionAssociations = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_SECTION_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); List<String> sectionIds = optionalFieldAppenderHelper.getIdList(studentSectionAssociations, ParameterConstants.SECTION_ID); List<EntityBody> sections = optionalFieldAppenderHelper.queryEntities(ResourceNames.SECTIONS, "_id", sectionIds); List<EntityBody> studentAcademicRecords = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); List<String> studentAcademicRecordIds = optionalFieldAppenderHelper.getIdList(studentAcademicRecords, "id"); List<EntityBody> courseTranscripts = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_TRANSCRIPTS, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordIds); List<String> sessionIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.SESSION_ID); List<EntityBody> sessions = optionalFieldAppenderHelper .queryEntities(ResourceNames.SESSIONS, "_id", sessionIds); List<String> courseOfferingIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.COURSE_OFFERING_ID); List<EntityBody> courseOfferings = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_OFFERINGS, "_id", courseOfferingIds); List<String> courseIds = optionalFieldAppenderHelper.getIdList(courseOfferings, ParameterConstants.COURSE_ID); List<EntityBody> courses = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSES, "_id", courseIds); List<EntityBody> studentAcademicRecordsForStudents = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); for (EntityBody student : entities) { String studentId = (String) student.get("id"); List<EntityBody> studentSectionAssociationsForStudent = optionalFieldAppenderHelper.getEntitySubList( studentSectionAssociations, ParameterConstants.STUDENT_ID, studentId); List<EntityBody> studentCourseTranscripts = new ArrayList<EntityBody>(); for (EntityBody studentSectionAssociationForStudent : studentSectionAssociationsForStudent) { String sectionId = (String) studentSectionAssociationForStudent.get(ParameterConstants.SECTION_ID); EntityBody sectionForStudent = optionalFieldAppenderHelper.getEntityFromList(sections, "id", sectionId); if (sectionForStudent == null) { continue; } EntityBody sessionForSection = optionalFieldAppenderHelper.getEntityFromList(sessions, "id", (String) sectionForStudent.get(ParameterConstants.SESSION_ID)); EntityBody courseOfferingForSection = optionalFieldAppenderHelper.getEntityFromList(courseOfferings, "id", (String) sectionForStudent.get(ParameterConstants.COURSE_OFFERING_ID)); if (courseOfferingForSection == null) { continue; } EntityBody courseForSection = optionalFieldAppenderHelper.getEntityFromList(courses, "id", (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); List<EntityBody> studentAcademicRecordsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAcademicRecordsForStudents, ParameterConstants.STUDENT_ID, studentId); List<String> studentAcademicRecordIdsForStudent = optionalFieldAppenderHelper.getIdList(studentAcademicRecordsForStudent, "id"); List<EntityBody> studentTranscriptsForStudent = new ArrayList<EntityBody>(); for (String studentAcademicRecordId : studentAcademicRecordIdsForStudent) { studentTranscriptsForStudent.addAll(optionalFieldAppenderHelper.getEntitySubList(courseTranscripts, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordId)); } List<EntityBody> studentTranscriptsForStudentAndCourse = optionalFieldAppenderHelper.getEntitySubList( studentTranscriptsForStudent, ParameterConstants.COURSE_ID, (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); studentCourseTranscripts.addAll(studentTranscriptsForStudentAndCourse); sectionForStudent.put(PathConstants.SESSIONS, sessionForSection); sectionForStudent.put(PathConstants.COURSES, courseForSection); studentSectionAssociationForStudent.put(PathConstants.SECTIONS, sectionForStudent); } EntityBody body = new EntityBody(); body.put(PathConstants.STUDENT_SECTION_ASSOCIATIONS, studentSectionAssociationsForStudent); body.put(PathConstants.COURSE_TRANSCRIPTS, studentCourseTranscripts); student.put(ParameterConstants.OPTIONAL_FIELD_TRANSCRIPT, body); } return entities; } }
|
StudentTranscriptOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSectionAssociations = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_SECTION_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); List<String> sectionIds = optionalFieldAppenderHelper.getIdList(studentSectionAssociations, ParameterConstants.SECTION_ID); List<EntityBody> sections = optionalFieldAppenderHelper.queryEntities(ResourceNames.SECTIONS, "_id", sectionIds); List<EntityBody> studentAcademicRecords = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); List<String> studentAcademicRecordIds = optionalFieldAppenderHelper.getIdList(studentAcademicRecords, "id"); List<EntityBody> courseTranscripts = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_TRANSCRIPTS, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordIds); List<String> sessionIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.SESSION_ID); List<EntityBody> sessions = optionalFieldAppenderHelper .queryEntities(ResourceNames.SESSIONS, "_id", sessionIds); List<String> courseOfferingIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.COURSE_OFFERING_ID); List<EntityBody> courseOfferings = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_OFFERINGS, "_id", courseOfferingIds); List<String> courseIds = optionalFieldAppenderHelper.getIdList(courseOfferings, ParameterConstants.COURSE_ID); List<EntityBody> courses = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSES, "_id", courseIds); List<EntityBody> studentAcademicRecordsForStudents = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); for (EntityBody student : entities) { String studentId = (String) student.get("id"); List<EntityBody> studentSectionAssociationsForStudent = optionalFieldAppenderHelper.getEntitySubList( studentSectionAssociations, ParameterConstants.STUDENT_ID, studentId); List<EntityBody> studentCourseTranscripts = new ArrayList<EntityBody>(); for (EntityBody studentSectionAssociationForStudent : studentSectionAssociationsForStudent) { String sectionId = (String) studentSectionAssociationForStudent.get(ParameterConstants.SECTION_ID); EntityBody sectionForStudent = optionalFieldAppenderHelper.getEntityFromList(sections, "id", sectionId); if (sectionForStudent == null) { continue; } EntityBody sessionForSection = optionalFieldAppenderHelper.getEntityFromList(sessions, "id", (String) sectionForStudent.get(ParameterConstants.SESSION_ID)); EntityBody courseOfferingForSection = optionalFieldAppenderHelper.getEntityFromList(courseOfferings, "id", (String) sectionForStudent.get(ParameterConstants.COURSE_OFFERING_ID)); if (courseOfferingForSection == null) { continue; } EntityBody courseForSection = optionalFieldAppenderHelper.getEntityFromList(courses, "id", (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); List<EntityBody> studentAcademicRecordsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAcademicRecordsForStudents, ParameterConstants.STUDENT_ID, studentId); List<String> studentAcademicRecordIdsForStudent = optionalFieldAppenderHelper.getIdList(studentAcademicRecordsForStudent, "id"); List<EntityBody> studentTranscriptsForStudent = new ArrayList<EntityBody>(); for (String studentAcademicRecordId : studentAcademicRecordIdsForStudent) { studentTranscriptsForStudent.addAll(optionalFieldAppenderHelper.getEntitySubList(courseTranscripts, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordId)); } List<EntityBody> studentTranscriptsForStudentAndCourse = optionalFieldAppenderHelper.getEntitySubList( studentTranscriptsForStudent, ParameterConstants.COURSE_ID, (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); studentCourseTranscripts.addAll(studentTranscriptsForStudentAndCourse); sectionForStudent.put(PathConstants.SESSIONS, sessionForSection); sectionForStudent.put(PathConstants.COURSES, courseForSection); studentSectionAssociationForStudent.put(PathConstants.SECTIONS, sectionForStudent); } EntityBody body = new EntityBody(); body.put(PathConstants.STUDENT_SECTION_ASSOCIATIONS, studentSectionAssociationsForStudent); body.put(PathConstants.COURSE_TRANSCRIPTS, studentCourseTranscripts); student.put(ParameterConstants.OPTIONAL_FIELD_TRANSCRIPT, body); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
StudentTranscriptOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSectionAssociations = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_SECTION_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); List<String> sectionIds = optionalFieldAppenderHelper.getIdList(studentSectionAssociations, ParameterConstants.SECTION_ID); List<EntityBody> sections = optionalFieldAppenderHelper.queryEntities(ResourceNames.SECTIONS, "_id", sectionIds); List<EntityBody> studentAcademicRecords = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); List<String> studentAcademicRecordIds = optionalFieldAppenderHelper.getIdList(studentAcademicRecords, "id"); List<EntityBody> courseTranscripts = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_TRANSCRIPTS, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordIds); List<String> sessionIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.SESSION_ID); List<EntityBody> sessions = optionalFieldAppenderHelper .queryEntities(ResourceNames.SESSIONS, "_id", sessionIds); List<String> courseOfferingIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.COURSE_OFFERING_ID); List<EntityBody> courseOfferings = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_OFFERINGS, "_id", courseOfferingIds); List<String> courseIds = optionalFieldAppenderHelper.getIdList(courseOfferings, ParameterConstants.COURSE_ID); List<EntityBody> courses = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSES, "_id", courseIds); List<EntityBody> studentAcademicRecordsForStudents = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); for (EntityBody student : entities) { String studentId = (String) student.get("id"); List<EntityBody> studentSectionAssociationsForStudent = optionalFieldAppenderHelper.getEntitySubList( studentSectionAssociations, ParameterConstants.STUDENT_ID, studentId); List<EntityBody> studentCourseTranscripts = new ArrayList<EntityBody>(); for (EntityBody studentSectionAssociationForStudent : studentSectionAssociationsForStudent) { String sectionId = (String) studentSectionAssociationForStudent.get(ParameterConstants.SECTION_ID); EntityBody sectionForStudent = optionalFieldAppenderHelper.getEntityFromList(sections, "id", sectionId); if (sectionForStudent == null) { continue; } EntityBody sessionForSection = optionalFieldAppenderHelper.getEntityFromList(sessions, "id", (String) sectionForStudent.get(ParameterConstants.SESSION_ID)); EntityBody courseOfferingForSection = optionalFieldAppenderHelper.getEntityFromList(courseOfferings, "id", (String) sectionForStudent.get(ParameterConstants.COURSE_OFFERING_ID)); if (courseOfferingForSection == null) { continue; } EntityBody courseForSection = optionalFieldAppenderHelper.getEntityFromList(courses, "id", (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); List<EntityBody> studentAcademicRecordsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAcademicRecordsForStudents, ParameterConstants.STUDENT_ID, studentId); List<String> studentAcademicRecordIdsForStudent = optionalFieldAppenderHelper.getIdList(studentAcademicRecordsForStudent, "id"); List<EntityBody> studentTranscriptsForStudent = new ArrayList<EntityBody>(); for (String studentAcademicRecordId : studentAcademicRecordIdsForStudent) { studentTranscriptsForStudent.addAll(optionalFieldAppenderHelper.getEntitySubList(courseTranscripts, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordId)); } List<EntityBody> studentTranscriptsForStudentAndCourse = optionalFieldAppenderHelper.getEntitySubList( studentTranscriptsForStudent, ParameterConstants.COURSE_ID, (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); studentCourseTranscripts.addAll(studentTranscriptsForStudentAndCourse); sectionForStudent.put(PathConstants.SESSIONS, sessionForSection); sectionForStudent.put(PathConstants.COURSES, courseForSection); studentSectionAssociationForStudent.put(PathConstants.SECTIONS, sectionForStudent); } EntityBody body = new EntityBody(); body.put(PathConstants.STUDENT_SECTION_ASSOCIATIONS, studentSectionAssociationsForStudent); body.put(PathConstants.COURSE_TRANSCRIPTS, studentCourseTranscripts); student.put(ParameterConstants.OPTIONAL_FIELD_TRANSCRIPT, body); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
@Test public void testApplyOptionalField() { List<EntityBody> entities = new ArrayList<EntityBody>(); entities.add(new EntityBody(createTestStudentEntity(STUDENT_ID))); entities = studentGradeLevelOptionalFieldAppender.applyOptionalField(entities, null); assertEquals("Should be 1", 1, entities.size()); assertEquals("Should match", "Eighth grade", entities.get(0).get("gradeLevel")); assertEquals("Should match", SCHOOL_ID, entities.get(0).get("schoolId")); }
|
@Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSchoolAssociationList = optionalFieldAppenderHelper.queryEntities( ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); if (studentSchoolAssociationList == null) { return entities; } Date currentDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (EntityBody student : entities) { String mostRecentGradeLevel = "Not Available"; String mostRecentSchool = ""; Date mostRecentEntry = null; try { for (EntityBody studentSchoolAssociation : studentSchoolAssociationList) { if (!studentSchoolAssociation.get(ParameterConstants.STUDENT_ID).equals(student.get("id"))) { continue; } if (studentSchoolAssociation.containsKey(EXIT_WITHDRAW_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(EXIT_WITHDRAW_DATE)); if (ssaDate.compareTo(currentDate) <= 0) { continue; } } if (studentSchoolAssociation.containsKey(ENTRY_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(ENTRY_DATE)); if (mostRecentEntry == null) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } else { if (ssaDate.compareTo(mostRecentEntry) > 0) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } } } } } catch (Exception e) { String exceptionMessage = "Exception while retrieving current gradeLevel for student with id: " + student.get("id") + " Exception: " + e.getMessage(); LOG.debug(exceptionMessage); mostRecentGradeLevel = "Not Available"; } student.put(GRADE_LEVEL, mostRecentGradeLevel); student.put(SCHOOL_ID, mostRecentSchool); } return entities; }
|
StudentGradeLevelOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSchoolAssociationList = optionalFieldAppenderHelper.queryEntities( ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); if (studentSchoolAssociationList == null) { return entities; } Date currentDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (EntityBody student : entities) { String mostRecentGradeLevel = "Not Available"; String mostRecentSchool = ""; Date mostRecentEntry = null; try { for (EntityBody studentSchoolAssociation : studentSchoolAssociationList) { if (!studentSchoolAssociation.get(ParameterConstants.STUDENT_ID).equals(student.get("id"))) { continue; } if (studentSchoolAssociation.containsKey(EXIT_WITHDRAW_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(EXIT_WITHDRAW_DATE)); if (ssaDate.compareTo(currentDate) <= 0) { continue; } } if (studentSchoolAssociation.containsKey(ENTRY_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(ENTRY_DATE)); if (mostRecentEntry == null) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } else { if (ssaDate.compareTo(mostRecentEntry) > 0) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } } } } } catch (Exception e) { String exceptionMessage = "Exception while retrieving current gradeLevel for student with id: " + student.get("id") + " Exception: " + e.getMessage(); LOG.debug(exceptionMessage); mostRecentGradeLevel = "Not Available"; } student.put(GRADE_LEVEL, mostRecentGradeLevel); student.put(SCHOOL_ID, mostRecentSchool); } return entities; } }
|
StudentGradeLevelOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSchoolAssociationList = optionalFieldAppenderHelper.queryEntities( ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); if (studentSchoolAssociationList == null) { return entities; } Date currentDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (EntityBody student : entities) { String mostRecentGradeLevel = "Not Available"; String mostRecentSchool = ""; Date mostRecentEntry = null; try { for (EntityBody studentSchoolAssociation : studentSchoolAssociationList) { if (!studentSchoolAssociation.get(ParameterConstants.STUDENT_ID).equals(student.get("id"))) { continue; } if (studentSchoolAssociation.containsKey(EXIT_WITHDRAW_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(EXIT_WITHDRAW_DATE)); if (ssaDate.compareTo(currentDate) <= 0) { continue; } } if (studentSchoolAssociation.containsKey(ENTRY_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(ENTRY_DATE)); if (mostRecentEntry == null) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } else { if (ssaDate.compareTo(mostRecentEntry) > 0) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } } } } } catch (Exception e) { String exceptionMessage = "Exception while retrieving current gradeLevel for student with id: " + student.get("id") + " Exception: " + e.getMessage(); LOG.debug(exceptionMessage); mostRecentGradeLevel = "Not Available"; } student.put(GRADE_LEVEL, mostRecentGradeLevel); student.put(SCHOOL_ID, mostRecentSchool); } return entities; } }
|
StudentGradeLevelOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSchoolAssociationList = optionalFieldAppenderHelper.queryEntities( ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); if (studentSchoolAssociationList == null) { return entities; } Date currentDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (EntityBody student : entities) { String mostRecentGradeLevel = "Not Available"; String mostRecentSchool = ""; Date mostRecentEntry = null; try { for (EntityBody studentSchoolAssociation : studentSchoolAssociationList) { if (!studentSchoolAssociation.get(ParameterConstants.STUDENT_ID).equals(student.get("id"))) { continue; } if (studentSchoolAssociation.containsKey(EXIT_WITHDRAW_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(EXIT_WITHDRAW_DATE)); if (ssaDate.compareTo(currentDate) <= 0) { continue; } } if (studentSchoolAssociation.containsKey(ENTRY_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(ENTRY_DATE)); if (mostRecentEntry == null) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } else { if (ssaDate.compareTo(mostRecentEntry) > 0) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } } } } } catch (Exception e) { String exceptionMessage = "Exception while retrieving current gradeLevel for student with id: " + student.get("id") + " Exception: " + e.getMessage(); LOG.debug(exceptionMessage); mostRecentGradeLevel = "Not Available"; } student.put(GRADE_LEVEL, mostRecentGradeLevel); student.put(SCHOOL_ID, mostRecentSchool); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
StudentGradeLevelOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSchoolAssociationList = optionalFieldAppenderHelper.queryEntities( ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); if (studentSchoolAssociationList == null) { return entities; } Date currentDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (EntityBody student : entities) { String mostRecentGradeLevel = "Not Available"; String mostRecentSchool = ""; Date mostRecentEntry = null; try { for (EntityBody studentSchoolAssociation : studentSchoolAssociationList) { if (!studentSchoolAssociation.get(ParameterConstants.STUDENT_ID).equals(student.get("id"))) { continue; } if (studentSchoolAssociation.containsKey(EXIT_WITHDRAW_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(EXIT_WITHDRAW_DATE)); if (ssaDate.compareTo(currentDate) <= 0) { continue; } } if (studentSchoolAssociation.containsKey(ENTRY_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(ENTRY_DATE)); if (mostRecentEntry == null) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } else { if (ssaDate.compareTo(mostRecentEntry) > 0) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } } } } } catch (Exception e) { String exceptionMessage = "Exception while retrieving current gradeLevel for student with id: " + student.get("id") + " Exception: " + e.getMessage(); LOG.debug(exceptionMessage); mostRecentGradeLevel = "Not Available"; } student.put(GRADE_LEVEL, mostRecentGradeLevel); student.put(SCHOOL_ID, mostRecentSchool); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
@Test public void testRead() { Response res = resource.read(); assertNotNull(res); assertEquals(Status.NOT_FOUND.getStatusCode(), res.getStatus()); Mockito.verify(service).getCustom("TEST-ID"); EntityBody mockBody = Mockito.mock(EntityBody.class); Mockito.when(service.getCustom("TEST-ID")).thenReturn(mockBody); res = resource.read(); assertNotNull(res); assertEquals(Status.OK.getStatusCode(), res.getStatus()); Mockito.verify(service, Mockito.atLeast(2)).getCustom("TEST-ID"); }
|
@GET @Path("/") public Response read() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } EntityBody entityBody = entityDefinition.getService().getCustom(entityId); if (entityBody == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entityBody).build(); }
|
CustomEntityResource { @GET @Path("/") public Response read() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } EntityBody entityBody = entityDefinition.getService().getCustom(entityId); if (entityBody == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entityBody).build(); } }
|
CustomEntityResource { @GET @Path("/") public Response read() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } EntityBody entityBody = entityDefinition.getService().getCustom(entityId); if (entityBody == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entityBody).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); }
|
CustomEntityResource { @GET @Path("/") public Response read() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } EntityBody entityBody = entityDefinition.getService().getCustom(entityId); if (entityBody == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entityBody).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
CustomEntityResource { @GET @Path("/") public Response read() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } EntityBody entityBody = entityDefinition.getService().getCustom(entityId); if (entityBody == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entityBody).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
@Test public void testCreateOrUpdatePUT() { EntityBody test = new EntityBody(); Response res = resource.createOrUpdatePut(test); assertNotNull(res); assertEquals(Status.NO_CONTENT.getStatusCode(), res.getStatus()); Mockito.verify(service).createOrUpdateCustom("TEST-ID", test); }
|
@PUT @Path("/") public Response createOrUpdatePut(final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); return Response.status(Status.NO_CONTENT).build(); }
|
CustomEntityResource { @PUT @Path("/") public Response createOrUpdatePut(final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); return Response.status(Status.NO_CONTENT).build(); } }
|
CustomEntityResource { @PUT @Path("/") public Response createOrUpdatePut(final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); return Response.status(Status.NO_CONTENT).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); }
|
CustomEntityResource { @PUT @Path("/") public Response createOrUpdatePut(final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); return Response.status(Status.NO_CONTENT).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
CustomEntityResource { @PUT @Path("/") public Response createOrUpdatePut(final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); return Response.status(Status.NO_CONTENT).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
@Test public void testCreateOrUpdatePOST() { EntityBody test = new EntityBody(); UriInfo uriInfo = Mockito.mock(UriInfo.class); final UriBuilder uriBuilder = Mockito.mock(UriBuilder.class); Mockito.when(uriInfo.getBaseUriBuilder()).thenReturn(uriBuilder); final StringBuilder path = new StringBuilder(); Mockito.when(uriBuilder.path(Mockito.anyString())).thenAnswer(new Answer<UriBuilder>() { @Override public UriBuilder answer(InvocationOnMock invocation) throws Throwable { path.append("/").append(invocation.getArguments()[0]); return uriBuilder; } }); Mockito.when(uriBuilder.build()).thenAnswer(new Answer<URI>() { @Override public URI answer(InvocationOnMock invocation) throws Throwable { URI uri = new URI(path.toString()); return uri; } }); Response res = resource.createOrUpdatePost(uriInfo, test); assertNotNull(res); assertEquals(Status.CREATED.getStatusCode(), res.getStatus()); assertNotNull(res.getMetadata().get("Location")); assertEquals(1, res.getMetadata().get("Location").size()); assertEquals("/" + PathConstants.V1 + "/TEST-ID/custom", res.getMetadata().get("Location").get(0)); Mockito.verify(service).createOrUpdateCustom("TEST-ID", test); }
|
@POST @Path("/") public Response createOrUpdatePost(@Context final UriInfo uriInfo, final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), PathConstants.TEMP_MAP.get(entityDefinition.getResourceName()), entityId, PathConstants.CUSTOM_ENTITIES) .toString(); return Response.status(Status.CREATED).header("Location", uri).build(); }
|
CustomEntityResource { @POST @Path("/") public Response createOrUpdatePost(@Context final UriInfo uriInfo, final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), PathConstants.TEMP_MAP.get(entityDefinition.getResourceName()), entityId, PathConstants.CUSTOM_ENTITIES) .toString(); return Response.status(Status.CREATED).header("Location", uri).build(); } }
|
CustomEntityResource { @POST @Path("/") public Response createOrUpdatePost(@Context final UriInfo uriInfo, final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), PathConstants.TEMP_MAP.get(entityDefinition.getResourceName()), entityId, PathConstants.CUSTOM_ENTITIES) .toString(); return Response.status(Status.CREATED).header("Location", uri).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); }
|
CustomEntityResource { @POST @Path("/") public Response createOrUpdatePost(@Context final UriInfo uriInfo, final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), PathConstants.TEMP_MAP.get(entityDefinition.getResourceName()), entityId, PathConstants.CUSTOM_ENTITIES) .toString(); return Response.status(Status.CREATED).header("Location", uri).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
CustomEntityResource { @POST @Path("/") public Response createOrUpdatePost(@Context final UriInfo uriInfo, final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), PathConstants.TEMP_MAP.get(entityDefinition.getResourceName()), entityId, PathConstants.CUSTOM_ENTITIES) .toString(); return Response.status(Status.CREATED).header("Location", uri).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
@Test public void testDelete() { Response res = resource.delete(); assertNotNull(res); assertEquals(Status.NO_CONTENT.getStatusCode(), res.getStatus()); Mockito.verify(service).deleteCustom("TEST-ID"); }
|
@DELETE @Path("/") public Response delete() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().deleteCustom(entityId); return Response.status(Status.NO_CONTENT).build(); }
|
CustomEntityResource { @DELETE @Path("/") public Response delete() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().deleteCustom(entityId); return Response.status(Status.NO_CONTENT).build(); } }
|
CustomEntityResource { @DELETE @Path("/") public Response delete() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().deleteCustom(entityId); return Response.status(Status.NO_CONTENT).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); }
|
CustomEntityResource { @DELETE @Path("/") public Response delete() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().deleteCustom(entityId); return Response.status(Status.NO_CONTENT).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
CustomEntityResource { @DELETE @Path("/") public Response delete() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().deleteCustom(entityId); return Response.status(Status.NO_CONTENT).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
@Test public void testInvalidURL() throws URISyntaxException { assertFalse("Should not validate", validator.validate(new URI("http: assertFalse("Should not validate", validator.validate(new URI("http: }
|
@Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); }
|
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } }
|
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } }
|
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } @Override boolean validate(URI url); }
|
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } @Override boolean validate(URI url); }
|
@Test public void testValidURL() throws URISyntaxException { assertTrue("Should validate", validator.validate(new URI("http: assertTrue("Should validate", validator.validate(new URI("http: }
|
@Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); }
|
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } }
|
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } }
|
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } @Override boolean validate(URI url); }
|
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } @Override boolean validate(URI url); }
|
@Test public void testInvalidQueryString() throws URISyntaxException { assertFalse("Should not validate", queryStringValidator.validate(new URI("http: }
|
@Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } @Override boolean validate(URI url); }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } @Override boolean validate(URI url); }
|
@Test public void testValidQueryString() throws URISyntaxException, UnsupportedEncodingException { assertTrue("Should validate", queryStringValidator.validate(new URI("http: assertTrue("Should validate", queryStringValidator.validate(new URI("http: + URLEncoder.encode("key<value", "UTF-8")))); assertTrue("Should validate", queryStringValidator.validate(new URI("http: + URLEncoder.encode("key>value", "UTF-8")))); }
|
@Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } @Override boolean validate(URI url); }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } @Override boolean validate(URI url); }
|
@Test public void testNonRewrite() { PathSegment segment1 = mock(PathSegment.class); when(segment1.getPath()).thenReturn("v5"); PathSegment segment2 = mock(PathSegment.class); when(segment2.getPath()).thenReturn("students"); List<PathSegment> segments = Arrays.asList(segment1, segment2); when(containerRequest.getPathSegments()).thenReturn(segments); when(containerRequest.getProperties()).thenReturn(new HashMap<String, Object>()); ContainerRequest request = versionFilter.filter(containerRequest); verify(containerRequest, never()).setUris((URI) any(), (URI) any()); assertNull("Should be null", request.getProperties().get(REQUESTED_PATH)); }
|
@Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } @Override ContainerRequest filter(ContainerRequest containerRequest); String getLatestApiVersion(String requestedVersion); }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } @Override ContainerRequest filter(ContainerRequest containerRequest); String getLatestApiVersion(String requestedVersion); }
|
@Test public void testRewriteNoQuery() throws URISyntaxException { UriBuilder builder = mock(UriBuilder.class); when(builder.path(anyString())).thenReturn(builder); URI uri = new URI("http: PathSegment segment1 = mock(PathSegment.class); when(segment1.getPath()).thenReturn("v1"); PathSegment segment2 = mock(PathSegment.class); when(segment2.getPath()).thenReturn("students"); List<PathSegment> segments = new ArrayList<PathSegment>(); segments.add(segment1); segments.add(segment2); when(containerRequest.getPathSegments()).thenReturn(segments); when(containerRequest.getBaseUriBuilder()).thenReturn(builder); when(containerRequest.getRequestUri()).thenReturn(uri); when(containerRequest.getPath()).thenReturn("http: when(containerRequest.getProperties()).thenReturn(new HashMap<String, Object>()); ContainerRequest request = versionFilter.filter(containerRequest); verify(containerRequest).setUris((URI) any(), (URI) any()); verify(builder).build(); verify(builder, times(1)).path("v1.5"); verify(builder, times(1)).path("students"); assertEquals("Should match", "http: }
|
@Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } @Override ContainerRequest filter(ContainerRequest containerRequest); String getLatestApiVersion(String requestedVersion); }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } @Override ContainerRequest filter(ContainerRequest containerRequest); String getLatestApiVersion(String requestedVersion); }
|
@Test public void testRewriteWithQuery() throws URISyntaxException { UriBuilder builder = mock(UriBuilder.class); when(builder.path(anyString())).thenReturn(builder); URI uri = new URI("http: PathSegment segment1 = mock(PathSegment.class); when(segment1.getPath()).thenReturn("v1"); PathSegment segment2 = mock(PathSegment.class); when(segment2.getPath()).thenReturn("students"); List<PathSegment> segments = new ArrayList<PathSegment>(); segments.add(segment1); segments.add(segment2); when(containerRequest.getPathSegments()).thenReturn(segments); when(containerRequest.getBaseUriBuilder()).thenReturn(builder); when(containerRequest.getRequestUri()).thenReturn(uri); versionFilter.filter(containerRequest); verify(containerRequest).setUris((URI) any(), (URI) any()); verify(builder).replaceQuery(anyString()); verify(builder).build(); verify(builder, times(1)).path("v1.5"); verify(builder, times(1)).path("students"); }
|
@Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } @Override ContainerRequest filter(ContainerRequest containerRequest); String getLatestApiVersion(String requestedVersion); }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } @Override ContainerRequest filter(ContainerRequest containerRequest); String getLatestApiVersion(String requestedVersion); }
|
@Test(expected = QueryParseException.class) public void shouldDisallowVersionOneZeroSearches() { ContainerRequest request = createRequest("v1.0/sections/1234/studentSectionAssociations", "schoolYears=2011-2012"); filter.filter(request); }
|
@Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
@Test public void shouldAllowVersionOneZeroNonSearchRequests() { ContainerRequest request = createRequest("v1.0/sections/1234/studentSectionAssociations", ""); filter.filter(request); }
|
@Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
@Test public void shonuldAllowVersionOneOneSearches() { ContainerRequest request = createRequest("v1.1/sections/1234/studentSectionAssociations", "schoolYears=2011-2012"); filter.filter(request); }
|
@Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
@Test(expected = QueryParseException.class) public void shouldDisallowExcludedUrisWithId() { String disallowedPath = "v1.1/sections/{id}/studentSectionAssociations"; String requestPath = "v1.1/sections/1234,23234/studentSectionAssociations"; disallowedEndpoints.add(disallowedPath); ContainerRequest request = createRequest(requestPath, "schoolYears=2011-2012"); filter.filter(request); }
|
@Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
@Test(expected = QueryParseException.class) public void shouldDisallowTwoPartUris() { String requestPath = "v1.1/sessions/1234567"; ContainerRequest request = createRequest(requestPath, "schoolYears=2011-2012"); filter.filter(request); }
|
@Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
@Test public void shouldAllowTwoPartUrisWithoutDates() { String requestPath = "v1.1/sessions/1234567"; ContainerRequest request = createRequest(requestPath, ""); filter.filter(request); }
|
@Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
@Test(expected = QueryParseException.class) public void shouldDisallowExcludedUrisWithoutId() { String disallowedPath = "v1.1/educationOrganizations"; String requestPath = "v1.1/educationOrganizations"; disallowedEndpoints.add(disallowedPath); ContainerRequest request = createRequest(requestPath, "schoolYears=2011-2012"); filter.filter(request); }
|
@Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
@Test public void shouldCatchInvalidDateRange() { List<String> invalidRanges = Arrays.asList("123-1234", "1234-123", "12345-1234", "1234-12345", "123A-1234", "1234-123A", "12341234", "1234--1234", "2001-2001", "2001-2000"); for (String range : invalidRanges) { try { initRepo(); calc.findDateRange(range); Assert.fail("Did not catch an invalid range: " + range); } catch (QueryParseException e) { } } }
|
public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } SessionDateInfo findDateRange(String schoolYearRange); }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } SessionDateInfo findDateRange(String schoolYearRange); }
|
@Test public void shouldAllowValidDateRange() { initRepo(); SessionDateInfo result = calc.findDateRange("2009-2010"); Assert.assertEquals("Should match", "2006-08-14", result.getStartDate()); Assert.assertEquals("Should match", "2009-05-22", result.getEndDate()); Assert.assertEquals("Should match", 4, result.getSessionIds().size()); }
|
public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } SessionDateInfo findDateRange(String schoolYearRange); }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } SessionDateInfo findDateRange(String schoolYearRange); }
|
@Test public void shouldReturnEmptyRanges() { initRepo(Collections.EMPTY_LIST); SessionDateInfo result = calc.findDateRange("2009-2010"); Assert.assertEquals("Should match", "", result.getStartDate()); Assert.assertEquals("Should match", "", result.getEndDate()); Assert.assertEquals("Should match", 0, result.getSessionIds().size()); }
|
public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } SessionDateInfo findDateRange(String schoolYearRange); }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } SessionDateInfo findDateRange(String schoolYearRange); }
|
@Test public void testGenerate() throws Exception { ContainerRequest request = mock(ContainerRequest.class); MultivaluedMap<String,String> parameters = mock(MultivaluedMap.class); List<String> schoolYears = new ArrayList<String>(); schoolYears.add("begin"); schoolYears.add("end"); SessionDateInfo sessionDateInfo = new SessionDateInfo("01-01-2010","01-31-2012", new HashSet<String>()); EntityFilterInfo entityFilterInfo = new EntityFilterInfo(); entityFilterInfo.setEntityName("testEntity"); entityFilterInfo.setBeginDateAttribute("beginDate"); entityFilterInfo.setEndDateAttribute("endDate"); Mockito.when(request.getQueryParameters()).thenReturn(parameters); Mockito.when(parameters.get(ParameterConstants.SCHOOL_YEARS)).thenReturn(schoolYears); Mockito.when(sessionRangeCalculator.findDateRange(anyString())).thenReturn(sessionDateInfo); Mockito.when(entityIdentifier.findEntity(anyString())).thenReturn(entityFilterInfo); dateFilterCriteriaGenerator.generate(request); }
|
public void generate(ContainerRequest request) { List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null && schoolYears.size() > 0) { String schoolYearRange = schoolYears.get(0); SessionDateInfo sessionDateInfo = sessionRangeCalculator.findDateRange(schoolYearRange); EntityFilterInfo entityFilterInfo = entityIdentifier.findEntity(request.getPath()); GranularAccessFilter filter = new DateFilterCriteriaBuilder().forEntity(entityFilterInfo.getEntityName()) .connectedBy(entityFilterInfo.getConnectingEntityList()) .withDateAttributes(entityFilterInfo.getBeginDateAttribute(), entityFilterInfo.getEndDateAttribute()) .withSessionAttribute(entityFilterInfo.getSessionAttribute()) .startingFrom(sessionDateInfo.getStartDate()) .endingTo(sessionDateInfo.getEndDate()) .withSessionIds(sessionDateInfo.getSessionIds()) .build(); granularAccessFilterProvider.storeGranularAccessFilter(filter); } }
|
DateFilterCriteriaGenerator { public void generate(ContainerRequest request) { List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null && schoolYears.size() > 0) { String schoolYearRange = schoolYears.get(0); SessionDateInfo sessionDateInfo = sessionRangeCalculator.findDateRange(schoolYearRange); EntityFilterInfo entityFilterInfo = entityIdentifier.findEntity(request.getPath()); GranularAccessFilter filter = new DateFilterCriteriaBuilder().forEntity(entityFilterInfo.getEntityName()) .connectedBy(entityFilterInfo.getConnectingEntityList()) .withDateAttributes(entityFilterInfo.getBeginDateAttribute(), entityFilterInfo.getEndDateAttribute()) .withSessionAttribute(entityFilterInfo.getSessionAttribute()) .startingFrom(sessionDateInfo.getStartDate()) .endingTo(sessionDateInfo.getEndDate()) .withSessionIds(sessionDateInfo.getSessionIds()) .build(); granularAccessFilterProvider.storeGranularAccessFilter(filter); } } }
|
DateFilterCriteriaGenerator { public void generate(ContainerRequest request) { List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null && schoolYears.size() > 0) { String schoolYearRange = schoolYears.get(0); SessionDateInfo sessionDateInfo = sessionRangeCalculator.findDateRange(schoolYearRange); EntityFilterInfo entityFilterInfo = entityIdentifier.findEntity(request.getPath()); GranularAccessFilter filter = new DateFilterCriteriaBuilder().forEntity(entityFilterInfo.getEntityName()) .connectedBy(entityFilterInfo.getConnectingEntityList()) .withDateAttributes(entityFilterInfo.getBeginDateAttribute(), entityFilterInfo.getEndDateAttribute()) .withSessionAttribute(entityFilterInfo.getSessionAttribute()) .startingFrom(sessionDateInfo.getStartDate()) .endingTo(sessionDateInfo.getEndDate()) .withSessionIds(sessionDateInfo.getSessionIds()) .build(); granularAccessFilterProvider.storeGranularAccessFilter(filter); } } }
|
DateFilterCriteriaGenerator { public void generate(ContainerRequest request) { List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null && schoolYears.size() > 0) { String schoolYearRange = schoolYears.get(0); SessionDateInfo sessionDateInfo = sessionRangeCalculator.findDateRange(schoolYearRange); EntityFilterInfo entityFilterInfo = entityIdentifier.findEntity(request.getPath()); GranularAccessFilter filter = new DateFilterCriteriaBuilder().forEntity(entityFilterInfo.getEntityName()) .connectedBy(entityFilterInfo.getConnectingEntityList()) .withDateAttributes(entityFilterInfo.getBeginDateAttribute(), entityFilterInfo.getEndDateAttribute()) .withSessionAttribute(entityFilterInfo.getSessionAttribute()) .startingFrom(sessionDateInfo.getStartDate()) .endingTo(sessionDateInfo.getEndDate()) .withSessionIds(sessionDateInfo.getSessionIds()) .build(); granularAccessFilterProvider.storeGranularAccessFilter(filter); } } void generate(ContainerRequest request); }
|
DateFilterCriteriaGenerator { public void generate(ContainerRequest request) { List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null && schoolYears.size() > 0) { String schoolYearRange = schoolYears.get(0); SessionDateInfo sessionDateInfo = sessionRangeCalculator.findDateRange(schoolYearRange); EntityFilterInfo entityFilterInfo = entityIdentifier.findEntity(request.getPath()); GranularAccessFilter filter = new DateFilterCriteriaBuilder().forEntity(entityFilterInfo.getEntityName()) .connectedBy(entityFilterInfo.getConnectingEntityList()) .withDateAttributes(entityFilterInfo.getBeginDateAttribute(), entityFilterInfo.getEndDateAttribute()) .withSessionAttribute(entityFilterInfo.getSessionAttribute()) .startingFrom(sessionDateInfo.getStartDate()) .endingTo(sessionDateInfo.getEndDate()) .withSessionIds(sessionDateInfo.getSessionIds()) .build(); granularAccessFilterProvider.storeGranularAccessFilter(filter); } } void generate(ContainerRequest request); }
|
@Test public void testFindEntityWithBeginDate(){ String request = "/educationOrganizations/id/sessions"; EntityDefinition definition = mock(EntityDefinition.class); ClassType sessionClassType = mock(ClassType.class); Attribute attribute = mock(Attribute.class); Mockito.when(entityDefinitionStore.lookupByResourceName(anyString())).thenReturn(definition); Mockito.when(definition.getType()).thenReturn(SESSION); Mockito.when(modelProvider.getClassType(anyString())).thenReturn(sessionClassType); Mockito.when(sessionClassType.getBeginDateAttribute()).thenReturn(attribute); Mockito.when(attribute.getName()).thenReturn("beginDate"); EntityFilterInfo entityFilterInfo = entityIdentifier.findEntity(request); assertFalse(entityFilterInfo.getBeginDateAttribute().isEmpty()); }
|
public EntityFilterInfo findEntity(String request) { this.request = request; EntityFilterInfo entityFilterInfo = new EntityFilterInfo(); List<String> resources = Arrays.asList(request.split("/")); String resource = resources.get(resources.size() - 1); EntityDefinition definition = entityDefinitionStore.lookupByResourceName(resource); if(definition != null) { ClassType entityType = modelProvider.getClassType(StringUtils.capitalize(definition.getType())); populatePath(entityFilterInfo, entityType, resource); } return entityFilterInfo; }
|
EntityIdentifier { public EntityFilterInfo findEntity(String request) { this.request = request; EntityFilterInfo entityFilterInfo = new EntityFilterInfo(); List<String> resources = Arrays.asList(request.split("/")); String resource = resources.get(resources.size() - 1); EntityDefinition definition = entityDefinitionStore.lookupByResourceName(resource); if(definition != null) { ClassType entityType = modelProvider.getClassType(StringUtils.capitalize(definition.getType())); populatePath(entityFilterInfo, entityType, resource); } return entityFilterInfo; } }
|
EntityIdentifier { public EntityFilterInfo findEntity(String request) { this.request = request; EntityFilterInfo entityFilterInfo = new EntityFilterInfo(); List<String> resources = Arrays.asList(request.split("/")); String resource = resources.get(resources.size() - 1); EntityDefinition definition = entityDefinitionStore.lookupByResourceName(resource); if(definition != null) { ClassType entityType = modelProvider.getClassType(StringUtils.capitalize(definition.getType())); populatePath(entityFilterInfo, entityType, resource); } return entityFilterInfo; } }
|
EntityIdentifier { public EntityFilterInfo findEntity(String request) { this.request = request; EntityFilterInfo entityFilterInfo = new EntityFilterInfo(); List<String> resources = Arrays.asList(request.split("/")); String resource = resources.get(resources.size() - 1); EntityDefinition definition = entityDefinitionStore.lookupByResourceName(resource); if(definition != null) { ClassType entityType = modelProvider.getClassType(StringUtils.capitalize(definition.getType())); populatePath(entityFilterInfo, entityType, resource); } return entityFilterInfo; } EntityFilterInfo findEntity(String request); }
|
EntityIdentifier { public EntityFilterInfo findEntity(String request) { this.request = request; EntityFilterInfo entityFilterInfo = new EntityFilterInfo(); List<String> resources = Arrays.asList(request.split("/")); String resource = resources.get(resources.size() - 1); EntityDefinition definition = entityDefinitionStore.lookupByResourceName(resource); if(definition != null) { ClassType entityType = modelProvider.getClassType(StringUtils.capitalize(definition.getType())); populatePath(entityFilterInfo, entityType, resource); } return entityFilterInfo; } EntityFilterInfo findEntity(String request); }
|
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testAppNotExist() throws Exception { final List<Map<String, Object>> apps = new ArrayList<Map<String, Object>>(); Mockito.when(mockRepo.create(Mockito.anyString(), Mockito.anyMap())).thenAnswer(new Answer<Entity>() { @Override public Entity answer(InvocationOnMock invocation) throws Throwable { apps.add((Map<String, Object>) invocation.getArguments()[1]); return null; } }); appInit.init(); assertEquals("Two apps registered", 2, apps.size()); assertEquals("Value replaced", "https: assertEquals("Value replaced", "https: }
|
@PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } @PostConstruct void init(); }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } @PostConstruct void init(); }
|
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testExistingApps() throws Exception { final List<Entity> apps = new ArrayList<Entity>(); props.put("bootstrap.app.keys", "admin"); saveProps(); Entity mockEntity = Mockito.mock(Entity.class); Mockito.when(mockRepo.findOne(Mockito.anyString(), Mockito.any(NeutralQuery.class))).thenReturn(mockEntity); Mockito.when(mockRepo.update(Mockito.anyString(), Mockito.any(Entity.class), Mockito.anyBoolean())).thenAnswer( new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { apps.add((Entity) invocation.getArguments()[1]); return true; } }); appInit.init(); assertEquals("One app updated", 1, apps.size()); }
|
@PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } @PostConstruct void init(); }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } @PostConstruct void init(); }
|
@Test(expected = IllegalArgumentException.class) public void testProdModeNoProps() { realmInit.bootstrap(); }
|
@PostConstruct public void bootstrap() { Map<String, Object> bootstrapAdminRealmBody = createAdminRealmBody(); createOrUpdateRealm(ADMIN_REALM_ID, bootstrapAdminRealmBody); if (!isSandbox) { ensurePropertySet("bootstrap.developer.realm.name", devRealmName); ensurePropertySet("bootstrap.developer.realm.uniqueId", devUniqueId); ensurePropertySet("bootstrap.developer.realm.idpId", devIdpId); ensurePropertySet("bootstrap.developer.realm.redirectEndpoint", devRedirectEndpoint); Map<String, Object> bootstrapDeveloperRealmBody = createDeveloperRealmBody(); createOrUpdateRealm(devUniqueId, bootstrapDeveloperRealmBody); } }
|
RealmInitializer { @PostConstruct public void bootstrap() { Map<String, Object> bootstrapAdminRealmBody = createAdminRealmBody(); createOrUpdateRealm(ADMIN_REALM_ID, bootstrapAdminRealmBody); if (!isSandbox) { ensurePropertySet("bootstrap.developer.realm.name", devRealmName); ensurePropertySet("bootstrap.developer.realm.uniqueId", devUniqueId); ensurePropertySet("bootstrap.developer.realm.idpId", devIdpId); ensurePropertySet("bootstrap.developer.realm.redirectEndpoint", devRedirectEndpoint); Map<String, Object> bootstrapDeveloperRealmBody = createDeveloperRealmBody(); createOrUpdateRealm(devUniqueId, bootstrapDeveloperRealmBody); } } }
|
RealmInitializer { @PostConstruct public void bootstrap() { Map<String, Object> bootstrapAdminRealmBody = createAdminRealmBody(); createOrUpdateRealm(ADMIN_REALM_ID, bootstrapAdminRealmBody); if (!isSandbox) { ensurePropertySet("bootstrap.developer.realm.name", devRealmName); ensurePropertySet("bootstrap.developer.realm.uniqueId", devUniqueId); ensurePropertySet("bootstrap.developer.realm.idpId", devIdpId); ensurePropertySet("bootstrap.developer.realm.redirectEndpoint", devRedirectEndpoint); Map<String, Object> bootstrapDeveloperRealmBody = createDeveloperRealmBody(); createOrUpdateRealm(devUniqueId, bootstrapDeveloperRealmBody); } } }
|
RealmInitializer { @PostConstruct public void bootstrap() { Map<String, Object> bootstrapAdminRealmBody = createAdminRealmBody(); createOrUpdateRealm(ADMIN_REALM_ID, bootstrapAdminRealmBody); if (!isSandbox) { ensurePropertySet("bootstrap.developer.realm.name", devRealmName); ensurePropertySet("bootstrap.developer.realm.uniqueId", devUniqueId); ensurePropertySet("bootstrap.developer.realm.idpId", devIdpId); ensurePropertySet("bootstrap.developer.realm.redirectEndpoint", devRedirectEndpoint); Map<String, Object> bootstrapDeveloperRealmBody = createDeveloperRealmBody(); createOrUpdateRealm(devUniqueId, bootstrapDeveloperRealmBody); } } @PostConstruct void bootstrap(); }
|
RealmInitializer { @PostConstruct public void bootstrap() { Map<String, Object> bootstrapAdminRealmBody = createAdminRealmBody(); createOrUpdateRealm(ADMIN_REALM_ID, bootstrapAdminRealmBody); if (!isSandbox) { ensurePropertySet("bootstrap.developer.realm.name", devRealmName); ensurePropertySet("bootstrap.developer.realm.uniqueId", devUniqueId); ensurePropertySet("bootstrap.developer.realm.idpId", devIdpId); ensurePropertySet("bootstrap.developer.realm.redirectEndpoint", devRedirectEndpoint); Map<String, Object> bootstrapDeveloperRealmBody = createDeveloperRealmBody(); createOrUpdateRealm(devUniqueId, bootstrapDeveloperRealmBody); } } @PostConstruct void bootstrap(); static final String ADMIN_REALM_ID; }
|
@Test public void testAllRolesCreated() throws Exception { assertTrue(roleInitializer.buildRoles("myRealmId") == 6); }
|
public int buildRoles(String realmId) { if (realmId != null) { LOG.info("Building roles for realm: {}", new Object[] { realmId }); Map<String, Object> rolesBody = new HashMap<String, Object>(); List<Map<String, Object>> groups = getDefaultRoles(); rolesBody.put("realmId", realmId); rolesBody.put("roles", groups); rolesBody.put("customRights", new ArrayList<String>()); repository.create(ROLES, rolesBody); return groups.size(); } else { LOG.warn("Null realm id --> not building roles."); } return 0; }
|
RoleInitializer { public int buildRoles(String realmId) { if (realmId != null) { LOG.info("Building roles for realm: {}", new Object[] { realmId }); Map<String, Object> rolesBody = new HashMap<String, Object>(); List<Map<String, Object>> groups = getDefaultRoles(); rolesBody.put("realmId", realmId); rolesBody.put("roles", groups); rolesBody.put("customRights", new ArrayList<String>()); repository.create(ROLES, rolesBody); return groups.size(); } else { LOG.warn("Null realm id --> not building roles."); } return 0; } }
|
RoleInitializer { public int buildRoles(String realmId) { if (realmId != null) { LOG.info("Building roles for realm: {}", new Object[] { realmId }); Map<String, Object> rolesBody = new HashMap<String, Object>(); List<Map<String, Object>> groups = getDefaultRoles(); rolesBody.put("realmId", realmId); rolesBody.put("roles", groups); rolesBody.put("customRights", new ArrayList<String>()); repository.create(ROLES, rolesBody); return groups.size(); } else { LOG.warn("Null realm id --> not building roles."); } return 0; } }
|
RoleInitializer { public int buildRoles(String realmId) { if (realmId != null) { LOG.info("Building roles for realm: {}", new Object[] { realmId }); Map<String, Object> rolesBody = new HashMap<String, Object>(); List<Map<String, Object>> groups = getDefaultRoles(); rolesBody.put("realmId", realmId); rolesBody.put("roles", groups); rolesBody.put("customRights", new ArrayList<String>()); repository.create(ROLES, rolesBody); return groups.size(); } else { LOG.warn("Null realm id --> not building roles."); } return 0; } void dropAndBuildRoles(String realmId); void dropRoles(String realmId); int buildRoles(String realmId); List<Map<String, Object>> getDefaultRoles(); void setRepository(Repository<Entity> repository); }
|
RoleInitializer { public int buildRoles(String realmId) { if (realmId != null) { LOG.info("Building roles for realm: {}", new Object[] { realmId }); Map<String, Object> rolesBody = new HashMap<String, Object>(); List<Map<String, Object>> groups = getDefaultRoles(); rolesBody.put("realmId", realmId); rolesBody.put("roles", groups); rolesBody.put("customRights", new ArrayList<String>()); repository.create(ROLES, rolesBody); return groups.size(); } else { LOG.warn("Null realm id --> not building roles."); } return 0; } void dropAndBuildRoles(String realmId); void dropRoles(String realmId); int buildRoles(String realmId); List<Map<String, Object>> getDefaultRoles(); void setRepository(Repository<Entity> repository); static final String EDUCATOR; static final String TEACHER; static final String AGGREGATE_VIEWER; static final String SPECIALIST_CONSULTANT; static final String IT_ADMINISTRATOR; static final String SCHOOL_ADMIN; static final String LEA_ADMIN; static final String LEADER; static final String PRINCIPAL; static final String SUPERINTENDENT; static final String STUDENT; static final String PARENT; static final String ROLES; static final String LEA_ADMINISTRATOR; static final String SEA_ADMINISTRATOR; static final String APP_DEVELOPER; static final String SLC_OPERATOR; static final String REALM_ADMINISTRATOR; static final String INGESTION_USER; static final String SANDBOX_SLC_OPERATOR; static final String SANDBOX_ADMINISTRATOR; }
|
@Test public void testCheckFieldAccessAdmin() { securityContextInjector.setAdminContextWithElevatedRights(); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria("economicDisadvantaged", "=", "true")); NeutralQuery query1 = new NeutralQuery(query); service.checkFieldAccess(query, false); assertTrue("Should match", query1.equals(query)); }
|
protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } }
|
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } }
|
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@Test public void testHappy() { SamlRequest request = Mockito.mock(SamlRequest.class); Mockito.when(request.getId()).thenReturn("id"); Mockito.when(request.getIdpDestination()).thenReturn("http: Mockito.when(samlDecoder.decode("samlRequest")).thenReturn(request); Request processed = authService.processRequest("samlRequest", "myrealm", null); Mockito.verify(samlDecoder).decode("samlRequest"); assertEquals("id", processed.getRequestId()); assertEquals("myrealm", processed.getRealm()); assertEquals(null, authService.processRequest(null, null, null)); }
|
public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); }
|
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } }
|
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } }
|
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } Request processRequest(String encodedSamlRequest, String realm, String developer); }
|
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } Request processRequest(String encodedSamlRequest, String realm, String developer); }
|
@Test (expected = QueryParseException.class) public void testCheckFieldAccessEducator() { securityContextInjector.setEducatorContext(); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria("economicDisadvantaged", "=", "true")); service.checkFieldAccess(query, false); }
|
protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } }
|
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } }
|
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@Test public void testIsSelf() { BasicService basicService = (BasicService) context.getBean("basicService", "teacher", new ArrayList<Treatment>(), securityRepo); basicService.setDefn(definitionStore.lookupByEntityType("teacher")); securityContextInjector.setEducatorContext("my-id"); assertTrue(basicService.isSelf(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.OPERATOR_EQUAL, "my-id")))); NeutralQuery query = new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList("my-id"))); assertTrue(basicService.isSelf(query)); query.addCriteria(new NeutralCriteria("someOtherProperty", NeutralCriteria.OPERATOR_EQUAL, "somethingElse")); assertTrue(basicService.isSelf(query)); query.addOrQuery(new NeutralQuery(new NeutralCriteria("refProperty", NeutralCriteria.OPERATOR_EQUAL, "my-id"))); assertTrue(basicService.isSelf(query)); query.addOrQuery(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.OPERATOR_EQUAL, "someoneElse"))); assertFalse(basicService.isSelf(query)); assertFalse(basicService.isSelf(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList("my-id", "someoneElse"))))); }
|
protected boolean isSelf(NeutralQuery query) { List<NeutralCriteria> allTheCriteria = query.getCriteria(); for (NeutralQuery orQuery: query.getOrQueries()) { if(!isSelf(orQuery)) { return false; } } for(NeutralCriteria criteria: allTheCriteria) { if (criteria.getOperator().equals(NeutralCriteria.CRITERIA_IN) && criteria.getValue() instanceof List) { List<?> value = (List<?>) criteria.getValue(); if (value.size() == 1 && isSelf(value.get(0).toString())) { return true; } } else if (criteria.getOperator().equals(NeutralCriteria.OPERATOR_EQUAL) && criteria.getValue() instanceof String) { if (isSelf((String) criteria.getValue())){ return true; } } } return false; }
|
BasicService implements EntityService, AccessibilityCheck { protected boolean isSelf(NeutralQuery query) { List<NeutralCriteria> allTheCriteria = query.getCriteria(); for (NeutralQuery orQuery: query.getOrQueries()) { if(!isSelf(orQuery)) { return false; } } for(NeutralCriteria criteria: allTheCriteria) { if (criteria.getOperator().equals(NeutralCriteria.CRITERIA_IN) && criteria.getValue() instanceof List) { List<?> value = (List<?>) criteria.getValue(); if (value.size() == 1 && isSelf(value.get(0).toString())) { return true; } } else if (criteria.getOperator().equals(NeutralCriteria.OPERATOR_EQUAL) && criteria.getValue() instanceof String) { if (isSelf((String) criteria.getValue())){ return true; } } } return false; } }
|
BasicService implements EntityService, AccessibilityCheck { protected boolean isSelf(NeutralQuery query) { List<NeutralCriteria> allTheCriteria = query.getCriteria(); for (NeutralQuery orQuery: query.getOrQueries()) { if(!isSelf(orQuery)) { return false; } } for(NeutralCriteria criteria: allTheCriteria) { if (criteria.getOperator().equals(NeutralCriteria.CRITERIA_IN) && criteria.getValue() instanceof List) { List<?> value = (List<?>) criteria.getValue(); if (value.size() == 1 && isSelf(value.get(0).toString())) { return true; } } else if (criteria.getOperator().equals(NeutralCriteria.OPERATOR_EQUAL) && criteria.getValue() instanceof String) { if (isSelf((String) criteria.getValue())){ return true; } } } return false; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { protected boolean isSelf(NeutralQuery query) { List<NeutralCriteria> allTheCriteria = query.getCriteria(); for (NeutralQuery orQuery: query.getOrQueries()) { if(!isSelf(orQuery)) { return false; } } for(NeutralCriteria criteria: allTheCriteria) { if (criteria.getOperator().equals(NeutralCriteria.CRITERIA_IN) && criteria.getValue() instanceof List) { List<?> value = (List<?>) criteria.getValue(); if (value.size() == 1 && isSelf(value.get(0).toString())) { return true; } } else if (criteria.getOperator().equals(NeutralCriteria.OPERATOR_EQUAL) && criteria.getValue() instanceof String) { if (isSelf((String) criteria.getValue())){ return true; } } } return false; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { protected boolean isSelf(NeutralQuery query) { List<NeutralCriteria> allTheCriteria = query.getCriteria(); for (NeutralQuery orQuery: query.getOrQueries()) { if(!isSelf(orQuery)) { return false; } } for(NeutralCriteria criteria: allTheCriteria) { if (criteria.getOperator().equals(NeutralCriteria.CRITERIA_IN) && criteria.getValue() instanceof List) { List<?> value = (List<?>) criteria.getValue(); if (value.size() == 1 && isSelf(value.get(0).toString())) { return true; } } else if (criteria.getOperator().equals(NeutralCriteria.OPERATOR_EQUAL) && criteria.getValue() instanceof String) { if (isSelf((String) criteria.getValue())){ return true; } } } return false; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@SuppressWarnings("unchecked") @Test public void testList() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { securityContextInjector.setEducatorContext(); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); EntityBody entityBody2 = new EntityBody(); entityBody2.put("studentUniqueStateId", "student2"); Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>()); Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>()); Iterable<Entity> entities = Arrays.asList(entity1, entity2); Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities); Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(2L); Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity1), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.any(Collection.class), Mockito.any(Collection.class))).thenReturn(entityBody1); Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity2), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.any(Collection.class), Mockito.any(Collection.class))).thenReturn(entityBody2); RequestUtil.setCurrentRequestId(); Iterable<EntityBody> listResult = service.list(new NeutralQuery()); List<EntityBody> bodies= new ArrayList<EntityBody>(); for (EntityBody body : listResult) { bodies.add(body); } Assert.assertEquals("EntityBody mismatch", entityBody1, bodies.toArray()[0]); Assert.assertEquals("EntityBody mismatch", entityBody2, bodies.toArray()[1]); long count = service.count(new NeutralQuery()); Assert.assertEquals(2, count); }
|
@Override public Iterable<EntityBody> list(NeutralQuery neutralQuery) { LOG.debug(">>>BasicService.list(neutralQuery)"); listSecurityCheck(neutralQuery); return listImplementationAfterSecurityChecks(neutralQuery); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> list(NeutralQuery neutralQuery) { LOG.debug(">>>BasicService.list(neutralQuery)"); listSecurityCheck(neutralQuery); return listImplementationAfterSecurityChecks(neutralQuery); } }
|
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> list(NeutralQuery neutralQuery) { LOG.debug(">>>BasicService.list(neutralQuery)"); listSecurityCheck(neutralQuery); return listImplementationAfterSecurityChecks(neutralQuery); } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> list(NeutralQuery neutralQuery) { LOG.debug(">>>BasicService.list(neutralQuery)"); listSecurityCheck(neutralQuery); return listImplementationAfterSecurityChecks(neutralQuery); } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> list(NeutralQuery neutralQuery) { LOG.debug(">>>BasicService.list(neutralQuery)"); listSecurityCheck(neutralQuery); return listImplementationAfterSecurityChecks(neutralQuery); } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@SuppressWarnings("unchecked") @Test public void testListBasedOnContextualRoles() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { securityContextInjector.setEducatorContext(); SecurityUtil.setUserContext(SecurityUtil.UserContext.TEACHER_CONTEXT); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); Collection<GrantedAuthority> teacherContextRights = new HashSet<GrantedAuthority>(Arrays.asList(Right.TEACHER_CONTEXT, Right.READ_PUBLIC, Right.WRITE_PUBLIC)); EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); EntityBody entityBody2 = new EntityBody(); entityBody2.put("studentUniqueStateId", "student2"); Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>()); Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>()); Iterable<Entity> entities = Arrays.asList(entity1, entity2); Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities); Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(2L); Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity1), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.anyBoolean(), Mockito.any(Collection.class), Mockito.any(SecurityUtil.UserContext.class))).thenReturn(entityBody1); Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity2), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.anyBoolean(), Mockito.any(Collection.class), Mockito.any(SecurityUtil.UserContext.class))).thenReturn(entityBody2); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(false), Matchers.eq(entity1), Matchers.eq(SecurityUtil.UserContext.TEACHER_CONTEXT), Matchers.eq(true))).thenReturn(teacherContextRights); ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class); Field contextValidator = BasicService.class.getDeclaredField("contextValidator"); contextValidator.setAccessible(true); contextValidator.set(service, mockContextValidator); Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>(); studentContext.put(entity1.getEntityId(), SecurityUtil.UserContext.TEACHER_CONTEXT); studentContext.put(entity2.getEntityId(), SecurityUtil.UserContext.TEACHER_CONTEXT); Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext); NeutralQuery query = new NeutralQuery(); query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT); RequestUtil.setCurrentRequestId(); Iterable<EntityBody> listResult = service.listBasedOnContextualRoles(query); List<EntityBody> bodies= new ArrayList<EntityBody>(); for (EntityBody body : listResult) { bodies.add(body); } Assert.assertEquals("EntityBody mismatch", entityBody1, bodies.toArray()[0]); Assert.assertEquals("EntityBody mismatch", entityBody2, bodies.toArray()[1]); long count = service.countBasedOnContextualRoles(new NeutralQuery()); Assert.assertEquals(2, count); }
|
@Override public Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery) { boolean isSelf = isSelf(neutralQuery); boolean noDataInDB = true; Map<String, UserContext> entityContexts = null; injectSecurity(neutralQuery); boolean findSpecial = userHasMultipleContextsOrDifferingRights() && (!EntityNames.isPublic(defn.getType())); Collection<Entity> entities = new HashSet<Entity>(); if (findSpecial) { entities = getResponseEntities(neutralQuery, isSelf); entityContexts = getEntityContexts(); } else { entities = (Collection<Entity>) repo.findAll(collectionName, neutralQuery); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { entityContexts = getEntityContextMap(entities, true); } } Collection<Entity> bodylessEntities = new HashSet<Entity>(); for(Entity ent : entities) { if(ent.getBody() == null || ent.getBody().size() == 0) { bodylessEntities.add(ent); } } entities.removeAll(bodylessEntities); noDataInDB = entities.isEmpty(); List<EntityBody> results = new ArrayList<EntityBody>(); for (Entity entity : entities) { UserContext context = getEntityContext(entity.getEntityId(), entityContexts); try { Collection<GrantedAuthority> auths = null; if (!findSpecial) { auths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); rightAccessValidator.checkAccess(true, isSelf, entity, defn.getType(), auths); rightAccessValidator.checkFieldAccess(neutralQuery, entity, defn.getType(), auths); } else { auths = getEntityAuthorities(entity.getEntityId()); } results.add(entityRightsFilter.makeEntityBody(entity, treatments, defn, isSelf, auths, context)); } catch (AccessDeniedException aex) { if (entities.size() == 1) { throw aex; } else { LOG.error(aex.getMessage()); } } } if (results.isEmpty()) { validateQuery(neutralQuery, isSelf); return noEntitiesFound(noDataInDB); } return results; }
|
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery) { boolean isSelf = isSelf(neutralQuery); boolean noDataInDB = true; Map<String, UserContext> entityContexts = null; injectSecurity(neutralQuery); boolean findSpecial = userHasMultipleContextsOrDifferingRights() && (!EntityNames.isPublic(defn.getType())); Collection<Entity> entities = new HashSet<Entity>(); if (findSpecial) { entities = getResponseEntities(neutralQuery, isSelf); entityContexts = getEntityContexts(); } else { entities = (Collection<Entity>) repo.findAll(collectionName, neutralQuery); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { entityContexts = getEntityContextMap(entities, true); } } Collection<Entity> bodylessEntities = new HashSet<Entity>(); for(Entity ent : entities) { if(ent.getBody() == null || ent.getBody().size() == 0) { bodylessEntities.add(ent); } } entities.removeAll(bodylessEntities); noDataInDB = entities.isEmpty(); List<EntityBody> results = new ArrayList<EntityBody>(); for (Entity entity : entities) { UserContext context = getEntityContext(entity.getEntityId(), entityContexts); try { Collection<GrantedAuthority> auths = null; if (!findSpecial) { auths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); rightAccessValidator.checkAccess(true, isSelf, entity, defn.getType(), auths); rightAccessValidator.checkFieldAccess(neutralQuery, entity, defn.getType(), auths); } else { auths = getEntityAuthorities(entity.getEntityId()); } results.add(entityRightsFilter.makeEntityBody(entity, treatments, defn, isSelf, auths, context)); } catch (AccessDeniedException aex) { if (entities.size() == 1) { throw aex; } else { LOG.error(aex.getMessage()); } } } if (results.isEmpty()) { validateQuery(neutralQuery, isSelf); return noEntitiesFound(noDataInDB); } return results; } }
|
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery) { boolean isSelf = isSelf(neutralQuery); boolean noDataInDB = true; Map<String, UserContext> entityContexts = null; injectSecurity(neutralQuery); boolean findSpecial = userHasMultipleContextsOrDifferingRights() && (!EntityNames.isPublic(defn.getType())); Collection<Entity> entities = new HashSet<Entity>(); if (findSpecial) { entities = getResponseEntities(neutralQuery, isSelf); entityContexts = getEntityContexts(); } else { entities = (Collection<Entity>) repo.findAll(collectionName, neutralQuery); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { entityContexts = getEntityContextMap(entities, true); } } Collection<Entity> bodylessEntities = new HashSet<Entity>(); for(Entity ent : entities) { if(ent.getBody() == null || ent.getBody().size() == 0) { bodylessEntities.add(ent); } } entities.removeAll(bodylessEntities); noDataInDB = entities.isEmpty(); List<EntityBody> results = new ArrayList<EntityBody>(); for (Entity entity : entities) { UserContext context = getEntityContext(entity.getEntityId(), entityContexts); try { Collection<GrantedAuthority> auths = null; if (!findSpecial) { auths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); rightAccessValidator.checkAccess(true, isSelf, entity, defn.getType(), auths); rightAccessValidator.checkFieldAccess(neutralQuery, entity, defn.getType(), auths); } else { auths = getEntityAuthorities(entity.getEntityId()); } results.add(entityRightsFilter.makeEntityBody(entity, treatments, defn, isSelf, auths, context)); } catch (AccessDeniedException aex) { if (entities.size() == 1) { throw aex; } else { LOG.error(aex.getMessage()); } } } if (results.isEmpty()) { validateQuery(neutralQuery, isSelf); return noEntitiesFound(noDataInDB); } return results; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery) { boolean isSelf = isSelf(neutralQuery); boolean noDataInDB = true; Map<String, UserContext> entityContexts = null; injectSecurity(neutralQuery); boolean findSpecial = userHasMultipleContextsOrDifferingRights() && (!EntityNames.isPublic(defn.getType())); Collection<Entity> entities = new HashSet<Entity>(); if (findSpecial) { entities = getResponseEntities(neutralQuery, isSelf); entityContexts = getEntityContexts(); } else { entities = (Collection<Entity>) repo.findAll(collectionName, neutralQuery); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { entityContexts = getEntityContextMap(entities, true); } } Collection<Entity> bodylessEntities = new HashSet<Entity>(); for(Entity ent : entities) { if(ent.getBody() == null || ent.getBody().size() == 0) { bodylessEntities.add(ent); } } entities.removeAll(bodylessEntities); noDataInDB = entities.isEmpty(); List<EntityBody> results = new ArrayList<EntityBody>(); for (Entity entity : entities) { UserContext context = getEntityContext(entity.getEntityId(), entityContexts); try { Collection<GrantedAuthority> auths = null; if (!findSpecial) { auths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); rightAccessValidator.checkAccess(true, isSelf, entity, defn.getType(), auths); rightAccessValidator.checkFieldAccess(neutralQuery, entity, defn.getType(), auths); } else { auths = getEntityAuthorities(entity.getEntityId()); } results.add(entityRightsFilter.makeEntityBody(entity, treatments, defn, isSelf, auths, context)); } catch (AccessDeniedException aex) { if (entities.size() == 1) { throw aex; } else { LOG.error(aex.getMessage()); } } } if (results.isEmpty()) { validateQuery(neutralQuery, isSelf); return noEntitiesFound(noDataInDB); } return results; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery) { boolean isSelf = isSelf(neutralQuery); boolean noDataInDB = true; Map<String, UserContext> entityContexts = null; injectSecurity(neutralQuery); boolean findSpecial = userHasMultipleContextsOrDifferingRights() && (!EntityNames.isPublic(defn.getType())); Collection<Entity> entities = new HashSet<Entity>(); if (findSpecial) { entities = getResponseEntities(neutralQuery, isSelf); entityContexts = getEntityContexts(); } else { entities = (Collection<Entity>) repo.findAll(collectionName, neutralQuery); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { entityContexts = getEntityContextMap(entities, true); } } Collection<Entity> bodylessEntities = new HashSet<Entity>(); for(Entity ent : entities) { if(ent.getBody() == null || ent.getBody().size() == 0) { bodylessEntities.add(ent); } } entities.removeAll(bodylessEntities); noDataInDB = entities.isEmpty(); List<EntityBody> results = new ArrayList<EntityBody>(); for (Entity entity : entities) { UserContext context = getEntityContext(entity.getEntityId(), entityContexts); try { Collection<GrantedAuthority> auths = null; if (!findSpecial) { auths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); rightAccessValidator.checkAccess(true, isSelf, entity, defn.getType(), auths); rightAccessValidator.checkFieldAccess(neutralQuery, entity, defn.getType(), auths); } else { auths = getEntityAuthorities(entity.getEntityId()); } results.add(entityRightsFilter.makeEntityBody(entity, treatments, defn, isSelf, auths, context)); } catch (AccessDeniedException aex) { if (entities.size() == 1) { throw aex; } else { LOG.error(aex.getMessage()); } } } if (results.isEmpty()) { validateQuery(neutralQuery, isSelf); return noEntitiesFound(noDataInDB); } return results; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@SuppressWarnings("unchecked") @Test public void testCreate() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { securityContextInjector.setEducatorContext(); try { Thread.currentThread().sleep(5L); } catch (InterruptedException is) { } RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); try { Thread.currentThread().sleep(5L); } catch (InterruptedException is) { } EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); EntityBody entityBody2 = new EntityBody(); entityBody2.put("studentUniqueStateId", "student2"); List<EntityBody> entityBodies = Arrays.asList(entityBody1, entityBody2); Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>()); Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>()); Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody1), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity1); Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody2), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity2); LOG.debug(ToStringBuilder.reflectionToString(entityBodies, ToStringStyle.MULTI_LINE_STYLE)); try { Thread.currentThread().sleep(5L); } catch (InterruptedException is) { } List<String> listResult = service.create(entityBodies); Assert.assertEquals("EntityBody mismatch", entity1.getEntityId(), listResult.toArray()[0]); Assert.assertEquals("EntityBody mismatch", entity2.getEntityId(), listResult.toArray()[1]); }
|
@Override public List<String> create(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(create(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; }
|
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> create(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(create(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } }
|
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> create(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(create(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> create(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(create(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> create(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(create(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@SuppressWarnings("unchecked") @Test public void testCreateBasedOnContextualRoles() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { securityContextInjector.setEducatorContext(); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); EntityBody entityBody2 = new EntityBody(); entityBody2.put("studentUniqueStateId", "student2"); List<EntityBody> entityBodies = Arrays.asList(entityBody1, entityBody2); Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>()); Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>()); Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody1), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity1); Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody2), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity2); List<String> listResult = service.createBasedOnContextualRoles(entityBodies); Assert.assertEquals("EntityBody mismatch", entity1.getEntityId(), listResult.toArray()[0]); Assert.assertEquals("EntityBody mismatch", entity2.getEntityId(), listResult.toArray()[1]); }
|
@Override public List<String> createBasedOnContextualRoles(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(createBasedOnContextualRoles(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; }
|
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> createBasedOnContextualRoles(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(createBasedOnContextualRoles(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } }
|
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> createBasedOnContextualRoles(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(createBasedOnContextualRoles(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> createBasedOnContextualRoles(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(createBasedOnContextualRoles(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> createBasedOnContextualRoles(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(createBasedOnContextualRoles(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@Test public void testgetEntityContextAuthorities() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException { securityContextInjector.setDualContext(); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); boolean isSelf = true; boolean isRead = true; EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); Entity student = securityRepo.create(EntityNames.STUDENT, entityBody1); Collection<GrantedAuthority> staffContextRights = SecurityUtil.getSLIPrincipal().getEdOrgContextRights().get(SecurityContextInjector.ED_ORG_ID).get(SecurityUtil.UserContext.STAFF_CONTEXT); Collection<GrantedAuthority> teacherContextRights = SecurityUtil.getSLIPrincipal().getEdOrgContextRights().get(SecurityContextInjector.ED_ORG_ID).get(SecurityUtil.UserContext.TEACHER_CONTEXT); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(isSelf), Matchers.eq(student), Matchers.eq(SecurityUtil.UserContext.STAFF_CONTEXT), Matchers.eq(isRead))).thenReturn(staffContextRights); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(isSelf), Matchers.eq(student), Matchers.eq(SecurityUtil.UserContext.TEACHER_CONTEXT), Matchers.eq(isRead))).thenReturn(teacherContextRights); ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class); Field contextValidator = BasicService.class.getDeclaredField("contextValidator"); contextValidator.setAccessible(true); contextValidator.set(service, mockContextValidator); Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>(); studentContext.put(student.getEntityId(), SecurityUtil.UserContext.STAFF_CONTEXT); Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext); Collection<GrantedAuthority> rights = service.getEntityContextAuthorities(student, isSelf, isRead); Assert.assertEquals(staffContextRights, rights); securityContextInjector.setEducatorContext(); rights = service.getEntityContextAuthorities(student, isSelf, isRead); Assert.assertEquals(teacherContextRights, rights); }
|
protected Collection<GrantedAuthority> getEntityContextAuthorities(Entity entity, boolean isSelf, boolean isRead) { UserContext context = SecurityUtil.getUserContext(); if (context == UserContext.DUAL_CONTEXT) { Map<String, UserContext> entityContext = getEntityContextMap(Arrays.asList(entity), isRead); if (entityContext != null) { context = entityContext.get(entity.getEntityId()); } } return rightAccessValidator.getContextualAuthorities(isSelf, entity, context, isRead); }
|
BasicService implements EntityService, AccessibilityCheck { protected Collection<GrantedAuthority> getEntityContextAuthorities(Entity entity, boolean isSelf, boolean isRead) { UserContext context = SecurityUtil.getUserContext(); if (context == UserContext.DUAL_CONTEXT) { Map<String, UserContext> entityContext = getEntityContextMap(Arrays.asList(entity), isRead); if (entityContext != null) { context = entityContext.get(entity.getEntityId()); } } return rightAccessValidator.getContextualAuthorities(isSelf, entity, context, isRead); } }
|
BasicService implements EntityService, AccessibilityCheck { protected Collection<GrantedAuthority> getEntityContextAuthorities(Entity entity, boolean isSelf, boolean isRead) { UserContext context = SecurityUtil.getUserContext(); if (context == UserContext.DUAL_CONTEXT) { Map<String, UserContext> entityContext = getEntityContextMap(Arrays.asList(entity), isRead); if (entityContext != null) { context = entityContext.get(entity.getEntityId()); } } return rightAccessValidator.getContextualAuthorities(isSelf, entity, context, isRead); } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { protected Collection<GrantedAuthority> getEntityContextAuthorities(Entity entity, boolean isSelf, boolean isRead) { UserContext context = SecurityUtil.getUserContext(); if (context == UserContext.DUAL_CONTEXT) { Map<String, UserContext> entityContext = getEntityContextMap(Arrays.asList(entity), isRead); if (entityContext != null) { context = entityContext.get(entity.getEntityId()); } } return rightAccessValidator.getContextualAuthorities(isSelf, entity, context, isRead); } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { protected Collection<GrantedAuthority> getEntityContextAuthorities(Entity entity, boolean isSelf, boolean isRead) { UserContext context = SecurityUtil.getUserContext(); if (context == UserContext.DUAL_CONTEXT) { Map<String, UserContext> entityContext = getEntityContextMap(Arrays.asList(entity), isRead); if (entityContext != null) { context = entityContext.get(entity.getEntityId()); } } return rightAccessValidator.getContextualAuthorities(isSelf, entity, context, isRead); } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@SuppressWarnings("unchecked") @Test public void testGetResponseEntities() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { securityContextInjector.setDualContext(); SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT); List<Entity> entities = new ArrayList<Entity>(); Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>(); for (int i=0; i<30; i++) { String id = "student" + i; entities.add(new MongoEntity("student", id, new HashMap<String,Object>(), new HashMap<String,Object>())); studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities); Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L); ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class); Field contextValidator = BasicService.class.getDeclaredField("contextValidator"); contextValidator.setAccessible(true); contextValidator.set(service, mockContextValidator); Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean())).thenReturn(new HashSet<GrantedAuthority>()); Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(), Mockito.anyCollection()); Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()), Mockito.anyString(), Mockito.anyCollection()); NeutralQuery query = new NeutralQuery(); query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT); Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class); method.setAccessible(true); RequestUtil.setCurrentRequestId(); Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult1 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23"); assertEntityIdsEqual(expectedResult1.iterator(), accessibleEntities.iterator()); long count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); RequestUtil.setCurrentRequestId(); accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult2 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23"); assertEntityIdsEqual(expectedResult2.iterator(), accessibleEntities.iterator()); count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); query.setOffset(7); RequestUtil.setCurrentRequestId(); accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult3 = Arrays.asList("student18", "student22", "student23"); assertEntityIdsEqual(expectedResult3.iterator(), accessibleEntities.iterator()); count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); query.setOffset(7); RequestUtil.setCurrentRequestId(); accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult4 = Arrays.asList("student18", "student22", "student23"); assertEntityIdsEqual(expectedResult4.iterator(), accessibleEntities.iterator()); count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); }
|
protected Collection<Entity> getResponseEntities(NeutralQuery neutralQuery, boolean isSelf) throws AccessDeniedException { LOG.debug(">>>BasicService.getResponseEntities()"); Collection<Entity> responseEntities = new ArrayList<Entity>(); Map<String, UserContext> entityContexts = new HashMap<String, UserContext>(); final int limit = neutralQuery.getLimit(); final int offset = neutralQuery.getOffset(); final int responseLimit = ((0 < limit) && (limit < getCountLimit())) ? limit : (int) getCountLimit(); long accessibleCount = 0; int currentOffset = 0; int totalCount = 0; Collection<Entity> batchedEntities; do { batchedEntities = getBatchedEntities(neutralQuery, getBatchSize(), currentOffset); totalCount += batchedEntities.size(); Map<String, UserContext> batchedEntityContexts = new HashMap<String, UserContext>(); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { batchedEntityContexts = getEntityContextMap(batchedEntities, true); } Iterator<Entity> batchedEntitiesIt = batchedEntities.iterator(); while ((accessibleCount < getCountLimit()) && batchedEntitiesIt.hasNext()) { Entity entity = batchedEntitiesIt.next(); try { validateEntity(entity, isSelf, neutralQuery, batchedEntityContexts); accessibleCount++; if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { responseEntities.add(entity); entityContexts.put(entity.getEntityId(), getEntityContext(entity.getEntityId(), batchedEntityContexts)); } } catch (AccessDeniedException aex) { if (totalCount == 1) { throw aex; } else if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { LOG.error(aex.getMessage()); } } } currentOffset += getBatchSize(); } while ((accessibleCount < getCountLimit()) && (batchedEntities.size() == getBatchSize())); neutralQuery.setLimit(limit); neutralQuery.setOffset(offset); if ((totalCount > 0) && (accessibleCount == 0)) { validateQuery(neutralQuery, isSelf); throw new APIAccessDeniedException("Access to resource denied."); } setEntityContexts(entityContexts); setAccessibleEntitiesCount(collectionName, accessibleCount); return responseEntities; }
|
BasicService implements EntityService, AccessibilityCheck { protected Collection<Entity> getResponseEntities(NeutralQuery neutralQuery, boolean isSelf) throws AccessDeniedException { LOG.debug(">>>BasicService.getResponseEntities()"); Collection<Entity> responseEntities = new ArrayList<Entity>(); Map<String, UserContext> entityContexts = new HashMap<String, UserContext>(); final int limit = neutralQuery.getLimit(); final int offset = neutralQuery.getOffset(); final int responseLimit = ((0 < limit) && (limit < getCountLimit())) ? limit : (int) getCountLimit(); long accessibleCount = 0; int currentOffset = 0; int totalCount = 0; Collection<Entity> batchedEntities; do { batchedEntities = getBatchedEntities(neutralQuery, getBatchSize(), currentOffset); totalCount += batchedEntities.size(); Map<String, UserContext> batchedEntityContexts = new HashMap<String, UserContext>(); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { batchedEntityContexts = getEntityContextMap(batchedEntities, true); } Iterator<Entity> batchedEntitiesIt = batchedEntities.iterator(); while ((accessibleCount < getCountLimit()) && batchedEntitiesIt.hasNext()) { Entity entity = batchedEntitiesIt.next(); try { validateEntity(entity, isSelf, neutralQuery, batchedEntityContexts); accessibleCount++; if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { responseEntities.add(entity); entityContexts.put(entity.getEntityId(), getEntityContext(entity.getEntityId(), batchedEntityContexts)); } } catch (AccessDeniedException aex) { if (totalCount == 1) { throw aex; } else if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { LOG.error(aex.getMessage()); } } } currentOffset += getBatchSize(); } while ((accessibleCount < getCountLimit()) && (batchedEntities.size() == getBatchSize())); neutralQuery.setLimit(limit); neutralQuery.setOffset(offset); if ((totalCount > 0) && (accessibleCount == 0)) { validateQuery(neutralQuery, isSelf); throw new APIAccessDeniedException("Access to resource denied."); } setEntityContexts(entityContexts); setAccessibleEntitiesCount(collectionName, accessibleCount); return responseEntities; } }
|
BasicService implements EntityService, AccessibilityCheck { protected Collection<Entity> getResponseEntities(NeutralQuery neutralQuery, boolean isSelf) throws AccessDeniedException { LOG.debug(">>>BasicService.getResponseEntities()"); Collection<Entity> responseEntities = new ArrayList<Entity>(); Map<String, UserContext> entityContexts = new HashMap<String, UserContext>(); final int limit = neutralQuery.getLimit(); final int offset = neutralQuery.getOffset(); final int responseLimit = ((0 < limit) && (limit < getCountLimit())) ? limit : (int) getCountLimit(); long accessibleCount = 0; int currentOffset = 0; int totalCount = 0; Collection<Entity> batchedEntities; do { batchedEntities = getBatchedEntities(neutralQuery, getBatchSize(), currentOffset); totalCount += batchedEntities.size(); Map<String, UserContext> batchedEntityContexts = new HashMap<String, UserContext>(); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { batchedEntityContexts = getEntityContextMap(batchedEntities, true); } Iterator<Entity> batchedEntitiesIt = batchedEntities.iterator(); while ((accessibleCount < getCountLimit()) && batchedEntitiesIt.hasNext()) { Entity entity = batchedEntitiesIt.next(); try { validateEntity(entity, isSelf, neutralQuery, batchedEntityContexts); accessibleCount++; if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { responseEntities.add(entity); entityContexts.put(entity.getEntityId(), getEntityContext(entity.getEntityId(), batchedEntityContexts)); } } catch (AccessDeniedException aex) { if (totalCount == 1) { throw aex; } else if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { LOG.error(aex.getMessage()); } } } currentOffset += getBatchSize(); } while ((accessibleCount < getCountLimit()) && (batchedEntities.size() == getBatchSize())); neutralQuery.setLimit(limit); neutralQuery.setOffset(offset); if ((totalCount > 0) && (accessibleCount == 0)) { validateQuery(neutralQuery, isSelf); throw new APIAccessDeniedException("Access to resource denied."); } setEntityContexts(entityContexts); setAccessibleEntitiesCount(collectionName, accessibleCount); return responseEntities; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); }
|
BasicService implements EntityService, AccessibilityCheck { protected Collection<Entity> getResponseEntities(NeutralQuery neutralQuery, boolean isSelf) throws AccessDeniedException { LOG.debug(">>>BasicService.getResponseEntities()"); Collection<Entity> responseEntities = new ArrayList<Entity>(); Map<String, UserContext> entityContexts = new HashMap<String, UserContext>(); final int limit = neutralQuery.getLimit(); final int offset = neutralQuery.getOffset(); final int responseLimit = ((0 < limit) && (limit < getCountLimit())) ? limit : (int) getCountLimit(); long accessibleCount = 0; int currentOffset = 0; int totalCount = 0; Collection<Entity> batchedEntities; do { batchedEntities = getBatchedEntities(neutralQuery, getBatchSize(), currentOffset); totalCount += batchedEntities.size(); Map<String, UserContext> batchedEntityContexts = new HashMap<String, UserContext>(); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { batchedEntityContexts = getEntityContextMap(batchedEntities, true); } Iterator<Entity> batchedEntitiesIt = batchedEntities.iterator(); while ((accessibleCount < getCountLimit()) && batchedEntitiesIt.hasNext()) { Entity entity = batchedEntitiesIt.next(); try { validateEntity(entity, isSelf, neutralQuery, batchedEntityContexts); accessibleCount++; if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { responseEntities.add(entity); entityContexts.put(entity.getEntityId(), getEntityContext(entity.getEntityId(), batchedEntityContexts)); } } catch (AccessDeniedException aex) { if (totalCount == 1) { throw aex; } else if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { LOG.error(aex.getMessage()); } } } currentOffset += getBatchSize(); } while ((accessibleCount < getCountLimit()) && (batchedEntities.size() == getBatchSize())); neutralQuery.setLimit(limit); neutralQuery.setOffset(offset); if ((totalCount > 0) && (accessibleCount == 0)) { validateQuery(neutralQuery, isSelf); throw new APIAccessDeniedException("Access to resource denied."); } setEntityContexts(entityContexts); setAccessibleEntitiesCount(collectionName, accessibleCount); return responseEntities; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
BasicService implements EntityService, AccessibilityCheck { protected Collection<Entity> getResponseEntities(NeutralQuery neutralQuery, boolean isSelf) throws AccessDeniedException { LOG.debug(">>>BasicService.getResponseEntities()"); Collection<Entity> responseEntities = new ArrayList<Entity>(); Map<String, UserContext> entityContexts = new HashMap<String, UserContext>(); final int limit = neutralQuery.getLimit(); final int offset = neutralQuery.getOffset(); final int responseLimit = ((0 < limit) && (limit < getCountLimit())) ? limit : (int) getCountLimit(); long accessibleCount = 0; int currentOffset = 0; int totalCount = 0; Collection<Entity> batchedEntities; do { batchedEntities = getBatchedEntities(neutralQuery, getBatchSize(), currentOffset); totalCount += batchedEntities.size(); Map<String, UserContext> batchedEntityContexts = new HashMap<String, UserContext>(); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { batchedEntityContexts = getEntityContextMap(batchedEntities, true); } Iterator<Entity> batchedEntitiesIt = batchedEntities.iterator(); while ((accessibleCount < getCountLimit()) && batchedEntitiesIt.hasNext()) { Entity entity = batchedEntitiesIt.next(); try { validateEntity(entity, isSelf, neutralQuery, batchedEntityContexts); accessibleCount++; if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { responseEntities.add(entity); entityContexts.put(entity.getEntityId(), getEntityContext(entity.getEntityId(), batchedEntityContexts)); } } catch (AccessDeniedException aex) { if (totalCount == 1) { throw aex; } else if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { LOG.error(aex.getMessage()); } } } currentOffset += getBatchSize(); } while ((accessibleCount < getCountLimit()) && (batchedEntities.size() == getBatchSize())); neutralQuery.setLimit(limit); neutralQuery.setOffset(offset); if ((totalCount > 0) && (accessibleCount == 0)) { validateQuery(neutralQuery, isSelf); throw new APIAccessDeniedException("Access to resource denied."); } setEntityContexts(entityContexts); setAccessibleEntitiesCount(collectionName, accessibleCount); return responseEntities; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
|
@Test(expected = SelectorParseException.class) public void testDollarSignThrowsExceptionWhenNotExpected() { this.selectionConverter.convert(":($)"); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test(expected = SelectorParseException.class) public void testNestedDollarSignThrowsExceptionWhenNotExpected() { this.selectionConverter.convert(":(foo:($))"); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test public void testForceAuthn() { SamlRequest request = Mockito.mock(SamlRequest.class); Mockito.when(request.getId()).thenReturn("id"); Mockito.when(request.getIdpDestination()).thenReturn("http: Mockito.when(request.isForceAuthn()).thenReturn(true); Mockito.when(samlDecoder.decode("samlRequest")).thenReturn(request); Request processed = authService.processRequest("samlRequest", "myrealm", null); Mockito.verify(samlDecoder).decode("samlRequest"); assertEquals("id", processed.getRequestId()); assertEquals("myrealm", processed.getRealm()); assertEquals(true, processed.isForceAuthn()); assertEquals(null, authService.processRequest(null, null, null)); }
|
public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); }
|
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } }
|
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } }
|
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } Request processRequest(String encodedSamlRequest, String realm, String developer); }
|
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } Request processRequest(String encodedSamlRequest, String realm, String developer); }
|
@Test public void testDollarSignDoesNotThrowExceptionWhenExpected() { SelectionConverter mySelectionConverter = new Selector2MapOfMaps(false); Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("$", true); Map<String, Object> convertResult = mySelectionConverter.convert(":($)"); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test public void testBasicWildcard() throws SelectorParseException { Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("*", true); Map<String, Object> convertResult = this.selectionConverter.convert(":( * )".replaceAll(" ", "")); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test public void testBasicString() throws SelectorParseException { Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("name", true); expectedResult.put("sectionAssociations", true); Map<String, Object> convertResult = this.selectionConverter.convert(":( name, sectionAssociations )".replaceAll(" ", "")); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test public void testTwiceNestedString() throws SelectorParseException { Map<String, Object> convertResult = this.selectionConverter.convert(":( name, sectionAssociations : ( studentId , sectionId : ( * ) ) )".replaceAll(" ", "")); Map<String, Object> sectionIdMap = new HashMap<String, Object>(); sectionIdMap.put("*", true); Map<String, Object> sectionAssociationsMap = new HashMap<String, Object>(); sectionAssociationsMap.put("studentId", true); sectionAssociationsMap.put("sectionId", sectionIdMap); Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("name", true); expectedResult.put("sectionAssociations", sectionAssociationsMap); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test public void testExcludingFeaturesFromWildcardSelection() throws SelectorParseException { Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("*", true); expectedResult.put("sequenceOfCourse", false); Map<String, Object> convertResult = this.selectionConverter.convert(":( *, sequenceOfCourse:false )".replaceAll(" ", "")); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test public void veryNestedTest() throws SelectorParseException { String selectorString = ":(foo:(bar),foo2:(bar2:true),foo3:(bar3:false),foo4:(bar4:(*,foobar5:false)))"; Map<String, Object> fooMap = new HashMap<String, Object>(); fooMap.put("bar", true); Map<String, Object> foo2Map = new HashMap<String, Object>(); foo2Map.put("bar2", true); Map<String, Object> foo3Map = new HashMap<String, Object>(); foo3Map.put("bar3", false); Map<String, Object> foo4Map = new HashMap<String, Object>(); Map<String, Object> bar4Map = new HashMap<String, Object>(); bar4Map.put("*", true); bar4Map.put("foobar5", false); foo4Map.put("bar4", bar4Map); Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("foo", fooMap); expectedResult.put("foo2", foo2Map); expectedResult.put("foo3", foo3Map); expectedResult.put("foo4", foo4Map); Map<String, Object> convertResult = this.selectionConverter.convert(selectorString); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test(expected = SelectorParseException.class) public void testInvalidSyntax() throws SelectorParseException { this.selectionConverter.convert(":("); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test(expected = SelectorParseException.class) public void testEmptyStrings() throws SelectorParseException { this.selectionConverter.convert(":(,,)"); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test(expected = SelectorParseException.class) public void testUnbalancedParens() throws SelectorParseException { Selector2MapOfMaps.getMatchingClosingParenIndex("((", 0); }
|
protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); }
|
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } }
|
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test(expected = SelectorParseException.class) public void testUnbalancedParens2() throws SelectorParseException { Selector2MapOfMaps.getMatchingClosingParenIndex(")", 0); }
|
protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); }
|
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } }
|
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test public void testGetAvailableDatasets() { service.setDatasetList("one,List One,two,List Two"); service.initDatasets(); List<Dataset> result = service.getAvailableDatasets(); assertEquals(2, result.size()); assertEquals("List One",result.get(0).getDisplayName()); assertEquals("one",result.get(0).getKey()); assertEquals("List Two",result.get(1).getDisplayName()); assertEquals("two",result.get(1).getKey()); }
|
public List<Dataset> getAvailableDatasets() { return datasets; }
|
DefaultUsersService { public List<Dataset> getAvailableDatasets() { return datasets; } }
|
DefaultUsersService { public List<Dataset> getAvailableDatasets() { return datasets; } }
|
DefaultUsersService { public List<Dataset> getAvailableDatasets() { return datasets; } @PostConstruct void postConstruct(); List<Dataset> getAvailableDatasets(); List<DefaultUser> getUsers(String dataset); DefaultUser getUser(String dataset, String userId); }
|
DefaultUsersService { public List<Dataset> getAvailableDatasets() { return datasets; } @PostConstruct void postConstruct(); List<Dataset> getAvailableDatasets(); List<DefaultUser> getUsers(String dataset); DefaultUser getUser(String dataset, String userId); }
|
@Test(expected = SelectorParseException.class) public void testUnbalancedParens3() throws SelectorParseException { String selectorString = ":(name,sectionAssociations)"; String unbalancedString = selectorString + ")"; this.selectionConverter.convert(unbalancedString); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test(expected = SelectorParseException.class) public void testEmptyStringForKey() throws SelectorParseException { String selectorString = ":(:(test))"; this.selectionConverter.convert(selectorString); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test(expected = SelectorParseException.class) public void testNonTrueFalseValueParsing() throws SelectorParseException { String selectorString = ":(someField:tru)"; this.selectionConverter.convert(selectorString); }
|
public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); }
|
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
|
@Test public void testNonNullForNull() { assertTrue(QUERY_CONVERTER.convert(null) != null); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test (expected = QueryParseException.class) public void testPreventionOfNegativeLimit() throws URISyntaxException { String queryString = "limit=-1"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test(expected = QueryParseException.class) public void testPreventionOfNegativeOffset() throws URISyntaxException { String queryString = "offset=-1"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test(expected = QueryParseException.class) public void testSelectorShouldFail() throws URISyntaxException { String queryString = "selector=:(students)"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test(expected = QueryParseException.class) public void testInvalidSelector() { try { String queryString = "selector=true"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test(expected = QueryParseException.class) public void testInvalidOffset() { try { String queryString = "offset=four"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test(expected = QueryParseException.class) public void testInvalidLimit() { try { String queryString = "limit=four"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test public void testGetUser() { service.setDatasetList("TestDataset,The Test Dataset"); service.initDatasets(); service.initUserLists(); DefaultUser user = service.getUser("TestDataset", "linda.kim"); assertEquals("linda.kim", user.getUserId()); }
|
public DefaultUser getUser(String dataset, String userId) { for (DefaultUser user : getUsers(dataset)) { if (user.getUserId().equals(userId)) { return user; } } return null; }
|
DefaultUsersService { public DefaultUser getUser(String dataset, String userId) { for (DefaultUser user : getUsers(dataset)) { if (user.getUserId().equals(userId)) { return user; } } return null; } }
|
DefaultUsersService { public DefaultUser getUser(String dataset, String userId) { for (DefaultUser user : getUsers(dataset)) { if (user.getUserId().equals(userId)) { return user; } } return null; } }
|
DefaultUsersService { public DefaultUser getUser(String dataset, String userId) { for (DefaultUser user : getUsers(dataset)) { if (user.getUserId().equals(userId)) { return user; } } return null; } @PostConstruct void postConstruct(); List<Dataset> getAvailableDatasets(); List<DefaultUser> getUsers(String dataset); DefaultUser getUser(String dataset, String userId); }
|
DefaultUsersService { public DefaultUser getUser(String dataset, String userId) { for (DefaultUser user : getUsers(dataset)) { if (user.getUserId().equals(userId)) { return user; } } return null; } @PostConstruct void postConstruct(); List<Dataset> getAvailableDatasets(); List<DefaultUser> getUsers(String dataset); DefaultUser getUser(String dataset, String userId); }
|
@Test(expected = QueryParseException.class) public void testQueryStringMissingKey() { try { String queryString = "=4"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test(expected = QueryParseException.class) public void testQueryStringMissingOperator() { try { String queryString = "key4"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test(expected = QueryParseException.class) public void testQueryStringMissingValue() { try { String queryString = "key="; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); }
|
public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
|
@Test public void testToString() throws URISyntaxException { List<String> equivalentStrings = new ArrayList<String>(); equivalentStrings.add("offset=0&limit=50"); equivalentStrings.add("offset=0&limit=50"); equivalentStrings.add("offset=0&limit=50"); equivalentStrings.add("offset=0&limit=50"); URI requestUri = new URI(URI_STRING); when(uriInfo.getRequestUri()).thenReturn(requestUri); ApiQuery apiQuery = new ApiQuery(uriInfo); assertTrue(equivalentStrings.contains(apiQuery.toString())); }
|
@Override public String toString() { StringBuilder stringBuffer = new StringBuilder("offset=" + getOffset() + "&limit=" + getLimit()); if (getIncludeFields() != null) { stringBuffer.append("&includeFields=" + StringUtils.join(getIncludeFields(), ",")); } if (getExcludeFields() != null) { stringBuffer.append("&excludeFields=" + StringUtils.join(getExcludeFields(), ",")); } if (getSortBy() != null) { stringBuffer.append("&sortBy=" + getSortBy()); } if (getSortOrder() != null) { stringBuffer.append("&sortOrder=" + getSortOrder()); } if (this.selector != null) { stringBuffer.append("&selector=" + this.toSelectorString(this.selector)); } for (NeutralCriteria neutralCriteria : getCriteria()) { stringBuffer.append("&" + neutralCriteria.getKey() + neutralCriteria.getOperator() + neutralCriteria.getValue()); } return stringBuffer.toString(); }
|
ApiQuery extends NeutralQuery { @Override public String toString() { StringBuilder stringBuffer = new StringBuilder("offset=" + getOffset() + "&limit=" + getLimit()); if (getIncludeFields() != null) { stringBuffer.append("&includeFields=" + StringUtils.join(getIncludeFields(), ",")); } if (getExcludeFields() != null) { stringBuffer.append("&excludeFields=" + StringUtils.join(getExcludeFields(), ",")); } if (getSortBy() != null) { stringBuffer.append("&sortBy=" + getSortBy()); } if (getSortOrder() != null) { stringBuffer.append("&sortOrder=" + getSortOrder()); } if (this.selector != null) { stringBuffer.append("&selector=" + this.toSelectorString(this.selector)); } for (NeutralCriteria neutralCriteria : getCriteria()) { stringBuffer.append("&" + neutralCriteria.getKey() + neutralCriteria.getOperator() + neutralCriteria.getValue()); } return stringBuffer.toString(); } }
|
ApiQuery extends NeutralQuery { @Override public String toString() { StringBuilder stringBuffer = new StringBuilder("offset=" + getOffset() + "&limit=" + getLimit()); if (getIncludeFields() != null) { stringBuffer.append("&includeFields=" + StringUtils.join(getIncludeFields(), ",")); } if (getExcludeFields() != null) { stringBuffer.append("&excludeFields=" + StringUtils.join(getExcludeFields(), ",")); } if (getSortBy() != null) { stringBuffer.append("&sortBy=" + getSortBy()); } if (getSortOrder() != null) { stringBuffer.append("&sortOrder=" + getSortOrder()); } if (this.selector != null) { stringBuffer.append("&selector=" + this.toSelectorString(this.selector)); } for (NeutralCriteria neutralCriteria : getCriteria()) { stringBuffer.append("&" + neutralCriteria.getKey() + neutralCriteria.getOperator() + neutralCriteria.getValue()); } return stringBuffer.toString(); } ApiQuery(UriInfo uriInfo); ApiQuery(String entityType, URI requestURI); ApiQuery(URI requestURI); ApiQuery(); }
|
ApiQuery extends NeutralQuery { @Override public String toString() { StringBuilder stringBuffer = new StringBuilder("offset=" + getOffset() + "&limit=" + getLimit()); if (getIncludeFields() != null) { stringBuffer.append("&includeFields=" + StringUtils.join(getIncludeFields(), ",")); } if (getExcludeFields() != null) { stringBuffer.append("&excludeFields=" + StringUtils.join(getExcludeFields(), ",")); } if (getSortBy() != null) { stringBuffer.append("&sortBy=" + getSortBy()); } if (getSortOrder() != null) { stringBuffer.append("&sortOrder=" + getSortOrder()); } if (this.selector != null) { stringBuffer.append("&selector=" + this.toSelectorString(this.selector)); } for (NeutralCriteria neutralCriteria : getCriteria()) { stringBuffer.append("&" + neutralCriteria.getKey() + neutralCriteria.getOperator() + neutralCriteria.getValue()); } return stringBuffer.toString(); } ApiQuery(UriInfo uriInfo); ApiQuery(String entityType, URI requestURI); ApiQuery(URI requestURI); ApiQuery(); @Override String toString(); Map<String, Object> getSelector(); void setSelector(Map<String, Object> selector); String getEntityType(); }
|
ApiQuery extends NeutralQuery { @Override public String toString() { StringBuilder stringBuffer = new StringBuilder("offset=" + getOffset() + "&limit=" + getLimit()); if (getIncludeFields() != null) { stringBuffer.append("&includeFields=" + StringUtils.join(getIncludeFields(), ",")); } if (getExcludeFields() != null) { stringBuffer.append("&excludeFields=" + StringUtils.join(getExcludeFields(), ",")); } if (getSortBy() != null) { stringBuffer.append("&sortBy=" + getSortBy()); } if (getSortOrder() != null) { stringBuffer.append("&sortOrder=" + getSortOrder()); } if (this.selector != null) { stringBuffer.append("&selector=" + this.toSelectorString(this.selector)); } for (NeutralCriteria neutralCriteria : getCriteria()) { stringBuffer.append("&" + neutralCriteria.getKey() + neutralCriteria.getOperator() + neutralCriteria.getValue()); } return stringBuffer.toString(); } ApiQuery(UriInfo uriInfo); ApiQuery(String entityType, URI requestURI); ApiQuery(URI requestURI); ApiQuery(); @Override String toString(); Map<String, Object> getSelector(); void setSelector(Map<String, Object> selector); String getEntityType(); static final int API_QUERY_DEFAULT_LIMIT; static final Map<String, Object> DEFAULT_SELECTOR; }
|
@Test public void testEmptyEntity() { EntityBody emptyCustomEntity = new EntityBody(); List<ValidationError> validationErrors = customEntityValidator.validate(emptyCustomEntity); Assert.assertTrue("There should be no validation errors", validationErrors.isEmpty()); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@Test public void testValidFieldName() { String validCustomEntityId = "validCustomEntity1"; EntityBody validCustomEntity = new EntityBody(); validCustomEntity.put("ID", validCustomEntityId); validCustomEntity.put("goodFieldName", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(validCustomEntity); Assert.assertTrue("There should be no validation errors", validationErrors.isEmpty()); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@SuppressWarnings("serial") @Test public void testMultipleNestedValidFieldNames() { final String validCustomEntityId = "validCustomEntity2"; EntityBody validCustomEntity = new EntityBody() { { put("ID", validCustomEntityId); put("goodFieldName1", "goodFieldValue"); put("goodFieldName2", new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); put("goodSubFieldName2", "goodFieldValue"); put("goodSubFieldName3", new LinkedList<HashMap<String, Object>>() { { add(new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); } }); add(new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); put("goodSubFieldName2", new HashMap[] { new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); } }, new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); put("goodSubFieldName2", "goodFieldValue"); } } }); } }); } }); } }); } }; List<ValidationError> validationErrors = customEntityValidator.validate(validCustomEntity); Assert.assertTrue("There should be no validation errors", validationErrors.isEmpty()); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@Test public void testInvalidFieldNameConsistingOfNullChar() { String invalidCustomEntityId = "invalidCustomEntity1"; EntityBody invalidCustomEntity = new EntityBody(); invalidCustomEntity.put("ID", invalidCustomEntityId); invalidCustomEntity.put("\u0000", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "\u0000", "\u0000", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@Test public void testInvalidFieldNameConsistingOfNullString() { String invalidCustomEntityId = "invalidCustomEntity2"; EntityBody invalidCustomEntity = new EntityBody(); invalidCustomEntity.put("ID", invalidCustomEntityId); invalidCustomEntity.put("\\x00", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "\\x00", "\\x00", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@Test public void testInvalidFieldNameContainingNullChar() { String invalidCustomEntityId = "invalidCustomEntity3"; EntityBody invalidCustomEntity = new EntityBody(); invalidCustomEntity.put("ID", invalidCustomEntityId); invalidCustomEntity.put("bad\u0000FieldName", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\u0000FieldName", "bad\u0000FieldName", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@Test public void testLogoutNoSaml() { ModelAndView mav = loginController.logout(null, null, null, httpSession); Mockito.verify(httpSession, Mockito.times(1)).removeAttribute("user_session_key"); assertEquals("loggedOut", mav.getViewName()); }
|
@RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } }
|
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } }
|
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } }
|
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } @RequestMapping(value = "/logout") ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession); @RequestMapping(value = "/", method = RequestMethod.GET) ModelAndView form(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession); @RequestMapping(value= "/admin", method = RequestMethod.POST) ModelAndView admin(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm, HttpSession httpSession); @RequestMapping(value = "/login", method = RequestMethod.POST) ModelAndView login(
@RequestParam("user_id") String userId,
@RequestParam("password") String password,
@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession,
HttpServletRequest request); @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/impersonate", method = RequestMethod.POST) ModelAndView impersonate(
@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "impersonate_user", required = false) String impersonateUser,
@RequestParam(value = "selected_roles", required = false) List<String> roles,
@RequestParam(value = "customRoles", required = false) String customRoles,
@RequestParam(value = "selected_type", required = false) String userType,
@RequestParam(value = "datasets", required = false) String dataset,
@RequestParam(value = "userList", required = false) String datasetUser,
@RequestParam(value = "manualConfig", required = false) boolean manualConfig,
HttpSession httpSession,
HttpServletRequest request); }
|
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } @RequestMapping(value = "/logout") ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession); @RequestMapping(value = "/", method = RequestMethod.GET) ModelAndView form(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession); @RequestMapping(value= "/admin", method = RequestMethod.POST) ModelAndView admin(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm, HttpSession httpSession); @RequestMapping(value = "/login", method = RequestMethod.POST) ModelAndView login(
@RequestParam("user_id") String userId,
@RequestParam("password") String password,
@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession,
HttpServletRequest request); @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/impersonate", method = RequestMethod.POST) ModelAndView impersonate(
@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "impersonate_user", required = false) String impersonateUser,
@RequestParam(value = "selected_roles", required = false) List<String> roles,
@RequestParam(value = "customRoles", required = false) String customRoles,
@RequestParam(value = "selected_type", required = false) String userType,
@RequestParam(value = "datasets", required = false) String dataset,
@RequestParam(value = "userList", required = false) String datasetUser,
@RequestParam(value = "manualConfig", required = false) boolean manualConfig,
HttpSession httpSession,
HttpServletRequest request); }
|
@Test public void testInvalidFieldNameContainingNullString() { String invalidCustomEntityId = "invalidCustomEntity4"; EntityBody invalidCustomEntity = new EntityBody(); invalidCustomEntity.put("ID", invalidCustomEntityId); invalidCustomEntity.put("bad\\x00FieldName", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\\x00FieldName", "bad\\x00FieldName", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@SuppressWarnings("serial") @Test public void testInvalidNestedFieldNameInMap() { final String invalidCustomEntityId = "invalidCustomEntity5"; EntityBody invalidCustomEntity = new EntityBody() { { put("ID", invalidCustomEntityId); put("nestedFieldName", new HashMap<String, Object>() { { put("goodFieldName", "goodFieldValue"); put("bad\u0011FieldName", "goodFieldValue"); } }); } }; List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\u0011FieldName", "bad\u0011FieldName", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@SuppressWarnings("serial") @Test public void testMultipleNestedInvalidFieldNames() { final String invalidCustomEntityId = "invalidCustomEntity6"; EntityBody invalidCustomEntity = new EntityBody() { { put("ID", invalidCustomEntityId); put("FSCommand = DEL", "goodFieldValue"); put("nestedField", new HashMap<String, Object>() { { put("goodFieldName1", "goodFieldValue"); put("bad\u0000FieldName2", "goodFieldValue"); put("goodFieldName2", new LinkedList<HashMap<String, Object>>() { { add(new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); } }); add(new HashMap<String, Object>() { { put("goodSubFieldName2", "goodFieldValue"); put("bad\\x00FieldName3", new HashMap[] { new HashMap<String, Object>() { { put("goodSubFieldName", "goodFieldValue"); } }, new HashMap<String, Object>() { { put("goodSubFieldName3", "goodFieldValue"); put("bad\u007FFieldName4", "goodFieldValue"); } } }); } }); } }); } }); } }; List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 4 validation errors", 4, validationErrors.size()); ValidationError ve1 = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "FSCommand = DEL", "FSCommand = DEL", null); ValidationError ve2 = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\u0000FieldName2", "bad\u0000FieldName2", null); ValidationError ve3 = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\\x00FieldName3", "bad\\x00FieldName3", null); ValidationError ve4 = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\u007FFieldName4", "bad\u007FFieldName4", null); assertValidationErrorIsInList(validationErrors, ve1); assertValidationErrorIsInList(validationErrors, ve2); assertValidationErrorIsInList(validationErrors, ve3); assertValidationErrorIsInList(validationErrors, ve4); }
|
public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
|
@Test public void testGetAllowedEdOrgs() { Mockito.when(secUtil.getTenantId()).thenReturn("TENANT"); Entity user = Mockito.mock(Entity.class); HashMap<String, Object> body = new HashMap<String, Object>(); body.put("stateOrganizationId", "ID"); body.put("organizationCategories", Arrays.asList("State Education Agency")); Mockito.when(user.getBody()).thenReturn(body); Mockito.when(repo.findAll(Mockito.eq(EntityNames.EDUCATION_ORGANIZATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(user)); Set<String> edOrgs = service.getAllowedEdOrgs(null, null); Assert.assertEquals(new HashSet<String>(Arrays.asList("ID")), edOrgs); Entity edOrg = Mockito.mock(Entity.class); Mockito.when(edOrg.getEntityId()).thenReturn("EDORGID"); Mockito.when(repo.findOne(Mockito.eq(EntityNames.EDUCATION_ORGANIZATION), Mockito.any(NeutralQuery.class))) .thenReturn(edOrg); edOrgs = service.getAllowedEdOrgs("TENANT", null); }
|
public Set<String> getAllowedEdOrgs(String tenant, String edOrg) { return getAllowedEdOrgs(tenant, edOrg, null, false); }
|
SuperAdminService { public Set<String> getAllowedEdOrgs(String tenant, String edOrg) { return getAllowedEdOrgs(tenant, edOrg, null, false); } }
|
SuperAdminService { public Set<String> getAllowedEdOrgs(String tenant, String edOrg) { return getAllowedEdOrgs(tenant, edOrg, null, false); } }
|
SuperAdminService { public Set<String> getAllowedEdOrgs(String tenant, String edOrg) { return getAllowedEdOrgs(tenant, edOrg, null, false); } Set<String> getAllowedEdOrgs(String tenant, String edOrg); Set<String> getAllowedEdOrgs(final String tenant, final String edOrg, final Collection<String> interestedTypes, boolean strict); }
|
SuperAdminService { public Set<String> getAllowedEdOrgs(String tenant, String edOrg) { return getAllowedEdOrgs(tenant, edOrg, null, false); } Set<String> getAllowedEdOrgs(String tenant, String edOrg); Set<String> getAllowedEdOrgs(final String tenant, final String edOrg, final Collection<String> interestedTypes, boolean strict); static final String STATE_EDUCATION_AGENCY; static final String LOCAL_EDUCATION_AGENCY; }
|
@Test public void testGetContextualAuthoritiesStaffOrphan() { String principalId = "SuperTeacher1"; Entity princEntity = new MongoEntity(null, principalId, new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(princEntity); principal.setUserType(EntityNames.STAFF); EdOrgContextRightsCache edOrgContextRights = createEdOrgContextRights(); principal.setEdOrgContextRights(edOrgContextRights); securityContextInjector.setOauthSecurityContext(principal, false); Map<String,Object> metaData = new HashMap<String,Object>(); metaData.put("createdBy", principalId); metaData.put("isOrphaned", "true"); Entity entity = new MongoEntity("student", null, new HashMap<String,Object>(), metaData); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, entity, SecurityUtil.UserContext.STAFF_CONTEXT,false); Assert.assertEquals("Expected all rights", ALL_AUTHS, auths); }
|
public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
@SuppressWarnings("unchecked") @Test public void testGetContextualAuthoritiesStaffMatchingEdOrgs() { Entity princEntity = new MongoEntity(null, "SuperTeacher2", new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(princEntity); principal.setUserType(EntityNames.STAFF); EdOrgContextRightsCache edOrgContextRights = createEdOrgContextRights(); principal.setEdOrgContextRights(edOrgContextRights); securityContextInjector.setOauthSecurityContext(principal, false); Entity student = createEntity(EntityNames.STUDENT, STUDENT_ID, new HashMap<String, Object>()); Mockito.when(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(edOrgContextRights, student, SecurityUtil.UserContext.STAFF_CONTEXT,false)).thenReturn(ADMIN_AUTHS); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, student, SecurityUtil.UserContext.STAFF_CONTEXT, false); Assert.assertEquals("Expected administrator rights", ADMIN_AUTHS, auths); }
|
public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
@Test public void testGetContextualAuthoritiesStaffNoMatchingEdOrgs() { Map<String, Collection<GrantedAuthority>> edOrgRights = new HashMap<String, Collection<GrantedAuthority>>(); Entity princEntity = new MongoEntity(null, "RegularTeacher1", new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(princEntity); principal.setUserType(EntityNames.STAFF); securityContextInjector.setOauthSecurityContext(principal, false); Entity student = createEntity(EntityNames.STUDENT, STUDENT_ID, new HashMap<String, Object>()); Mockito.when(entityEdOrgRightBuilder.buildEntityEdOrgRights(edOrgRights, student, false)).thenReturn(NO_AUTHS); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, student, SecurityUtil.UserContext.STAFF_CONTEXT,false); Assert.assertEquals("Expected no rights", NO_AUTHS, auths); }
|
public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
@Test public void testGetContextualAuthoritiesNonStaff() { String token = "AQIC5wM2LY4SfczsoqTgHpfSEciO4J34Hc5ThvD0QaM2QUI.*AAJTSQACMDE.*"; Entity princEntity = new MongoEntity(null, "RegularTeacher2", new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setUserType(EntityNames.TEACHER); principal.setEntity(princEntity); PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(principal, token, EDU_AUTHS); SecurityContextHolder.getContext().setAuthentication(authenticationToken); Entity entity = new MongoEntity("student", null, new HashMap<String,Object>(), new HashMap<String,Object>()); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, entity, SecurityUtil.UserContext.TEACHER_CONTEXT,false); Assert.assertEquals("Expected educator rights", EDU_AUTHS, auths); }
|
public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
@Test public void testGetContextualAuthoritiesNonStaffSelf() { String token = "AQIC5wM2LY4SfczsoqTgHpfSEciO4J34Hc5ThvD0QaM2QUI.*AAJTSQACMDE.*"; Entity princEntity = new MongoEntity(null, "RegularTeacher3", new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(princEntity); principal.setUserType(EntityNames.TEACHER); principal.setSelfRights(ADMIN_AUTHS); PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(principal, token, EDU_AUTHS); SecurityContextHolder.getContext().setAuthentication(authenticationToken); Entity entity = new MongoEntity("teacher", null, new HashMap<String,Object>(), new HashMap<String,Object>()); Collection<GrantedAuthority> auths = service.getContextualAuthorities(true, entity, SecurityUtil.UserContext.TEACHER_CONTEXT,false); Assert.assertEquals("Expected all rights", ALL_AUTHS, auths); }
|
public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
@Test public void testGetContextualAuthoritiesNullEntity() { securityContextInjector.setEducatorContext(); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, null, SecurityUtil.UserContext.TEACHER_CONTEXT,false); Assert.assertEquals("Expected no rights", NO_AUTHS, auths); }
|
public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
|
@Test public void testLogoutWithSaml() { ModelAndView mav = loginController.logout("SAMLRequest", "realm", null, httpSession); assertEquals("You are now logged out", mav.getModel().get("msg")); assertEquals("login", mav.getViewName()); Mockito.verify(httpSession, Mockito.times(1)).removeAttribute("user_session_key"); }
|
@RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } }
|
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } }
|
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } }
|
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } @RequestMapping(value = "/logout") ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession); @RequestMapping(value = "/", method = RequestMethod.GET) ModelAndView form(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession); @RequestMapping(value= "/admin", method = RequestMethod.POST) ModelAndView admin(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm, HttpSession httpSession); @RequestMapping(value = "/login", method = RequestMethod.POST) ModelAndView login(
@RequestParam("user_id") String userId,
@RequestParam("password") String password,
@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession,
HttpServletRequest request); @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/impersonate", method = RequestMethod.POST) ModelAndView impersonate(
@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "impersonate_user", required = false) String impersonateUser,
@RequestParam(value = "selected_roles", required = false) List<String> roles,
@RequestParam(value = "customRoles", required = false) String customRoles,
@RequestParam(value = "selected_type", required = false) String userType,
@RequestParam(value = "datasets", required = false) String dataset,
@RequestParam(value = "userList", required = false) String datasetUser,
@RequestParam(value = "manualConfig", required = false) boolean manualConfig,
HttpSession httpSession,
HttpServletRequest request); }
|
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } @RequestMapping(value = "/logout") ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession); @RequestMapping(value = "/", method = RequestMethod.GET) ModelAndView form(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession); @RequestMapping(value= "/admin", method = RequestMethod.POST) ModelAndView admin(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm, HttpSession httpSession); @RequestMapping(value = "/login", method = RequestMethod.POST) ModelAndView login(
@RequestParam("user_id") String userId,
@RequestParam("password") String password,
@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "developer", required = false) String developer,
HttpSession httpSession,
HttpServletRequest request); @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/impersonate", method = RequestMethod.POST) ModelAndView impersonate(
@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm,
@RequestParam(value = "impersonate_user", required = false) String impersonateUser,
@RequestParam(value = "selected_roles", required = false) List<String> roles,
@RequestParam(value = "customRoles", required = false) String customRoles,
@RequestParam(value = "selected_type", required = false) String userType,
@RequestParam(value = "datasets", required = false) String dataset,
@RequestParam(value = "userList", required = false) String datasetUser,
@RequestParam(value = "manualConfig", required = false) boolean manualConfig,
HttpSession httpSession,
HttpServletRequest request); }
|
@SuppressWarnings("unchecked") @Test public void testBuildEntityEdOrgRights() { Set<String> edOrgs = new HashSet<String>(); edOrgs.add("edOrg1"); edOrgs.add("edOrg2"); edOrgs.add("edOrg3"); edOrgs.add("edOrg4"); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("student"); Mockito.when(edOrgOwnershipArbiter.determineHierarchicalEdorgs(Matchers.anyList(), Matchers.anyString())).thenReturn(edOrgs); Collection<GrantedAuthority> grantedAuthorities = entityEdOrgRightBuilder.buildEntityEdOrgRights(edOrgRights, entity, false); Assert.assertEquals(5, grantedAuthorities.size()); Assert.assertTrue(grantedAuthorities.contains(READ_PUBLIC)); Assert.assertTrue(grantedAuthorities.contains(READ_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(READ_RESTRICTED)); Assert.assertTrue(grantedAuthorities.contains(WRITE_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(WRITE_RESTRICTED)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_READ)); Assert.assertFalse(grantedAuthorities.contains(WRITE_PUBLIC)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_WRITE)); }
|
public Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgRights.keySet(), entity, isRead); } for (String edorg : edorgs) { authorities.addAll(edOrgRights.get(edorg)); } return authorities; }
|
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgRights.keySet(), entity, isRead); } for (String edorg : edorgs) { authorities.addAll(edOrgRights.get(edorg)); } return authorities; } }
|
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgRights.keySet(), entity, isRead); } for (String edorg : edorgs) { authorities.addAll(edOrgRights.get(edorg)); } return authorities; } }
|
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgRights.keySet(), entity, isRead); } for (String edorg : edorgs) { authorities.addAll(edOrgRights.get(edorg)); } return authorities; } Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead); Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity,
final SecurityUtil.UserContext context, boolean isRead); void setEdOrgOwnershipArbiter(EdOrgOwnershipArbiter edOrgOwnershipArbiter); }
|
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgRights.keySet(), entity, isRead); } for (String edorg : edorgs) { authorities.addAll(edOrgRights.get(edorg)); } return authorities; } Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead); Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity,
final SecurityUtil.UserContext context, boolean isRead); void setEdOrgOwnershipArbiter(EdOrgOwnershipArbiter edOrgOwnershipArbiter); }
|
@SuppressWarnings("unchecked") @Test public void testBuildEntityEdOrgDualContextRights() { Set<String> edOrgs = new HashSet<String>(); edOrgs.add("edOrg1"); edOrgs.add("edOrg2"); edOrgs.add("edOrg3"); edOrgs.add("edOrg4"); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("student"); Mockito.when(edOrgOwnershipArbiter.determineHierarchicalEdorgs(Matchers.anyList(), Matchers.anyString())).thenReturn(edOrgs); Collection<GrantedAuthority> grantedAuthorities = entityEdOrgRightBuilder.buildEntityEdOrgContextRights(edOrgContextRights, entity, SecurityUtil.UserContext.DUAL_CONTEXT, false); Assert.assertEquals(6, grantedAuthorities.size()); Assert.assertTrue(grantedAuthorities.contains(READ_PUBLIC)); Assert.assertTrue(grantedAuthorities.contains(READ_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(READ_RESTRICTED)); Assert.assertTrue(grantedAuthorities.contains(WRITE_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(STAFF_CONTEXT)); Assert.assertTrue(grantedAuthorities.contains(TEACHER_CONTEXT)); Assert.assertFalse(grantedAuthorities.contains(WRITE_RESTRICTED)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_READ)); Assert.assertFalse(grantedAuthorities.contains(WRITE_PUBLIC)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_WRITE)); }
|
public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; }
|
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } }
|
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } }
|
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead); Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity,
final SecurityUtil.UserContext context, boolean isRead); void setEdOrgOwnershipArbiter(EdOrgOwnershipArbiter edOrgOwnershipArbiter); }
|
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead); Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity,
final SecurityUtil.UserContext context, boolean isRead); void setEdOrgOwnershipArbiter(EdOrgOwnershipArbiter edOrgOwnershipArbiter); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.