method2testcases
stringlengths 118
6.63k
|
---|
### Question:
TenantAndIdEmittableKey extends EmittableKey { @Override public BSONObject toBSON() { BSONObject bson = new BasicBSONObject(); bson.put(getTenantIdField().toString(), getTenantId().toString()); bson.put(getIdField().toString(), getId().toString()); return bson; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }### Answer:
@Test public void testToBSON() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); key.setTenantId(new Text("Midgar")); key.setId(new Text("1234")); BSONObject bson = key.toBSON(); assertNotNull(bson); assertTrue(bson.containsField("meta.data.tenantId")); Object obj = bson.get("meta.data.tenantId"); assertNotNull(obj); assertTrue(obj instanceof String); String val = (String) obj; assertEquals(val, "Midgar"); assertTrue(bson.containsField("test.id.key.field")); obj = bson.get("test.id.key.field"); assertNotNull(obj); assertTrue(obj instanceof String); val = (String) obj; assertEquals(val, "1234"); } |
### Question:
OnboardingResource { @POST @RightsAllowed({Right.INGEST_DATA }) public Response provision(Map<String, String> reqBody, @Context final UriInfo uriInfo) { String orgId = reqBody.get(STATE_EDORG_ID); if (orgId == null) { return Response.status(Status.BAD_REQUEST).entity("Missing required " + STATE_EDORG_ID).build(); } Response r = createEdOrg(orgId); return r; } @Autowired OnboardingResource(@Value("${sli.landingZone.server}") String landingZoneServer); @POST @RightsAllowed({Right.INGEST_DATA }) Response provision(Map<String, String> reqBody, @Context final UriInfo uriInfo); Response createEdOrg(final String orgId); static final String STATE_EDUCATION_AGENCY; static final String STATE_EDORG_ID; static final String EDORG_INSTITUTION_NAME; static final String ADDRESSES; static final String ADDRESS_STREET; static final String ADDRESS_CITY; static final String ADDRESS_STATE_ABRV; static final String ADDRESS_POSTAL_CODE; static final String CATEGORIES; static final String PRELOAD_FILES_ID; }### Answer:
@Test public void testBadData() { Response response = resource.provision(new HashMap<String, String>(), null); assertEquals(response.getStatus(), Status.BAD_REQUEST.getStatusCode()); }
@SuppressWarnings("unchecked") @Test public void testProvision() { Map<String, String> requestBody = new HashMap<String, String>(); requestBody.put(OnboardingResource.STATE_EDORG_ID, "TestOrg"); requestBody.put(ResourceConstants.ENTITY_METADATA_TENANT_ID, "12345"); requestBody.put(OnboardingResource.PRELOAD_FILES_ID, "small_sample_dataset"); LandingZoneInfo landingZone = new LandingZoneInfo("LANDING ZONE", "INGESTION SERVER"); Map<String, String> tenantBody = new HashMap<String, String>(); tenantBody.put("landingZone", "LANDING ZONE"); tenantBody.put("ingestionServer", "INGESTION SERVER"); try { when(mockTenantResource.createLandingZone(Mockito.anyString(), Mockito.eq("TestOrg"), Mockito.anyBoolean())).thenReturn(landingZone); } catch (TenantResourceCreationException e) { Assert.fail(e.getMessage()); } Response res = resource.provision(requestBody, null); assertTrue(Status.fromStatusCode(res.getStatus()) == Status.CREATED); Map<String, String> result = (Map<String, String>) res.getEntity(); assertNotNull(result.get("landingZone")); Assert.assertEquals("LANDING ZONE", result.get("landingZone")); assertNotNull(result.get("serverName")); Assert.assertEquals("landingZone", result.get("serverName")); res = resource.provision(requestBody, null); assertEquals(Status.CREATED, Status.fromStatusCode(res.getStatus())); } |
### Question:
ApprovedApplicationResource { @GET @RightsAllowed(any = true) public Response getApplications(@DefaultValue("") @QueryParam("is_admin") String adminFilter) { List<EntityBody> results = new ArrayList<EntityBody>(); NeutralQuery query = new NeutralQuery(0); for (Entity result : repo.findAll("application", query)) { if (appValidator.isAuthorizedForApp(result, SecurityUtil.getSLIPrincipal())) { EntityBody body = new EntityBody(result.getBody()); if (!shouldFilterApp(result, adminFilter)) { filterAttributes(body); results.add(body); } } } return Response.status(Status.OK).entity(results).build(); } @GET @RightsAllowed(any = true) Response getApplications(@DefaultValue("") @QueryParam("is_admin") String adminFilter); static final String RESOURCE_NAME; }### Answer:
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testGetApps() { ResponseImpl resp = (ResponseImpl) resource.getApplications(""); List<Map> list = (List<Map>) resp.getEntity(); List<String> names = new ArrayList<String>(); for (Map map : list) { String name = (String) map.get("name"); names.add(name); } Assert.assertTrue(names.contains("MyApp")); } |
### Question:
AdminDelegationResource { @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getDelegations() { SecurityUtil.ensureAuthenticated(); if (SecurityUtil.hasRight(Right.EDORG_DELEGATE)) { String edOrg = SecurityUtil.getEdOrg(); if (edOrg == null) { throw new APIAccessDeniedException("Can not grant access because no edOrg exists on principal."); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); NeutralQuery query = new NeutralQuery(); Set<String> delegatedEdorgs = new HashSet<String>(); delegatedEdorgs.addAll(util.getSecurityEventDelegateEdOrgs()); query.addCriteria(new NeutralCriteria(LEA_ID, NeutralCriteria.CRITERIA_IN, delegatedEdorgs)); for (Entity entity : repo.findAll(RESOURCE_NAME, query)) { entity.getBody().put("id", entity.getEntityId()); results.add(entity.getBody()); } return Response.ok(results).build(); } else if (SecurityUtil.hasRight(Right.EDORG_APP_AUTHZ)) { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(Arrays.asList(entity)).build(); } return SecurityUtil.forbiddenResponse(); } @PostConstruct void init(); @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getDelegations(); @PUT @Path("myEdOrg") @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response setLocalDelegation(EntityBody body, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response create(EntityBody body, @Context final UriInfo uriInfo); @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getSingleDelegation(); static final String RESOURCE_NAME; static final String LEA_ID; }### Answer:
@Test(expected = APIAccessDeniedException.class) public void testGetDelegationsNoEdOrg() throws Exception { securityContextInjector.setLeaAdminContext(); resource.getDelegations(); }
@Test public void testGetDelegationsBadRole() throws Exception { securityContextInjector.setEducatorContext(); Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), resource.getDelegations().getStatus()); } |
### Question:
TenantAndIdEmittableKey extends EmittableKey { public Text getTenantIdField() { return fieldNames[TENANT_FIELD]; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }### Answer:
@Test public void testGetTenantIdField() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); assertEquals(key.getTenantIdField().toString(), "meta.data.tenantId"); } |
### Question:
AdminDelegationResource { @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) public Response getSingleDelegation() { EntityBody entity = getEntity(); if (entity == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entity).build(); } @PostConstruct void init(); @GET @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getDelegations(); @PUT @Path("myEdOrg") @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response setLocalDelegation(EntityBody body, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.EDORG_APP_AUTHZ }) Response create(EntityBody body, @Context final UriInfo uriInfo); @GET @Path("myEdOrg") @RightsAllowed({Right.EDORG_DELEGATE, Right.EDORG_APP_AUTHZ }) Response getSingleDelegation(); static final String RESOURCE_NAME; static final String LEA_ID; }### Answer:
@Test public void testGetSingleDelegation() throws Exception { securityContextInjector.setLeaAdminContext(); ((SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).setEdOrg("1234"); ((SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).setEdOrgId("1234"); Assert.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resource.getSingleDelegation().getStatus()); } |
### Question:
ApplicationResource extends UnversionedResource { @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) public Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { EntityBody ent = service.get(uuid); if (ent != null) { validateDeveloperHasAccessToApp(ent); } return super.delete(uuid, uriInfo); } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); static final String AUTHORIZED_ED_ORGS; static final String APPLICATION; static final String MESSAGE; static final String STATUS_PENDING; static final String STATUS_APPROVED; static final String REGISTRATION; static final String CLIENT_ID; static final String CLIENT_SECRET; static final String APPROVAL_DATE; static final String REQUEST_DATE; static final String STATUS; static final String RESOURCE_NAME; static final String UUID; static final String LOCATION; }### Answer:
@Test public void testBadDelete() throws URISyntaxException { String uuid = "9999999999"; when(uriInfo.getRequestUri()).thenReturn(new URI("http: try { @SuppressWarnings("unused") Response resp = resource.delete(uuid, uriInfo); } catch (EntityNotFoundException e) { assertTrue(true); return; } assertTrue(false); } |
### Question:
ApplicationResource extends UnversionedResource { @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) public Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo) { Response resp = super.getWithId(uuid, uriInfo); filterSensitiveData((Map) resp.getEntity()); return resp; } @Autowired ApplicationResource(EntityDefinitionStore entityDefs); void setAutoRegister(boolean register); @PostConstruct void init(); @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) Response post(EntityBody newApp, @Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) @Override Response getAll(@Context final UriInfo uriInfo); @SuppressWarnings("rawtypes") @GET @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.APP_AUTHORIZE, Right.ADMIN_ACCESS }) Response getWithId(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @DELETE @Override @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD }) Response delete(@PathParam(UUID) String uuid, @Context final UriInfo uriInfo); @SuppressWarnings("unchecked") @PUT @Path("{" + UUID + "}") @RightsAllowed({ Right.DEV_APP_CRUD, Right.SLC_APP_APPROVE}) @Override Response put(@PathParam(UUID) String uuid, EntityBody app, @Context final UriInfo uriInfo); boolean isSandboxEnabled(); void setSandboxEnabled(boolean sandboxEnabled); static final String AUTHORIZED_ED_ORGS; static final String APPLICATION; static final String MESSAGE; static final String STATUS_PENDING; static final String STATUS_APPROVED; static final String REGISTRATION; static final String CLIENT_ID; static final String CLIENT_SECRET; static final String APPROVAL_DATE; static final String REQUEST_DATE; static final String STATUS; static final String RESOURCE_NAME; static final String UUID; static final String LOCATION; }### Answer:
@Test public void testGoodGet() throws URISyntaxException { String uuid = createApp(); when(uriInfo.getRequestUri()).thenReturn(new URI("http: Response resp = resource.getWithId(uuid, uriInfo); assertEquals(STATUS_FOUND, resp.getStatus()); }
@Test public void testBadGet() throws URISyntaxException { String uuid = "9999999999"; when(uriInfo.getRequestUri()).thenReturn(new URI("http: try { Response resp = resource.getWithId(uuid, uriInfo); assertEquals(STATUS_NOT_FOUND, resp.getStatus()); } catch (EntityNotFoundException e) { assertTrue(true); return; } assertTrue(false); } |
### Question:
ArtifactBindingHelper { protected ArtifactResolve generateArtifactResolveRequest(String artifactString, KeyStore.PrivateKeyEntry pkEntry, String idpUrl) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Artifact artifact = (Artifact) xmlObjectBuilderFactory.getBuilder(Artifact.DEFAULT_ELEMENT_NAME).buildObject(Artifact.DEFAULT_ELEMENT_NAME); artifact.setArtifact(artifactString); Issuer issuer = (Issuer) xmlObjectBuilderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME).buildObject(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(issuerName); ArtifactResolve artifactResolve = (ArtifactResolve) xmlObjectBuilderFactory.getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME).buildObject(ArtifactResolve.DEFAULT_ELEMENT_NAME); artifactResolve.setIssuer(issuer); artifactResolve.setIssueInstant(new DateTime()); artifactResolve.setID(UUID.randomUUID().toString()); artifactResolve.setDestination(idpUrl); artifactResolve.setArtifact(artifact); Signature signature = samlHelper.getDigitalSignature(pkEntry); artifactResolve.setSignature(signature); try { Configuration.getMarshallerFactory().getMarshaller(artifactResolve).marshall(artifactResolve); } catch (MarshallingException ex) { LOG.error("Error composing artifact resolution request: Marshalling artifact resolution request failed", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } try { Signer.signObject(signature); } catch (SignatureException ex) { LOG.error("Error composing artifact resolution request: Failed to sign artifact resolution request", ex); throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex); } return artifactResolve; } }### Answer:
@Test public void generateArtifactRequestTest() { ArtifactResolve ar = artifactBindingHelper.generateArtifactResolveRequest("test1234", pkEntry, idpUrl); Assert.assertEquals("test1234", ar.getArtifact().getArtifact()); Assert.assertTrue(ar.isSigned()); Assert.assertNotNull(ar.getSignature().getKeyInfo().getX509Datas()); Assert.assertEquals(ar.getDestination(), idpUrl); Assert.assertEquals(issuerName, ar.getIssuer().getValue()); } |
### Question:
ArtifactBindingHelper { protected Envelope generateSOAPEnvelope(ArtifactResolve artifactResolutionRequest) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Envelope envelope = (Envelope) xmlObjectBuilderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_ELEMENT_NAME); Body body = (Body) xmlObjectBuilderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); body.getUnknownXMLObjects().add(artifactResolutionRequest); envelope.setBody(body); return envelope; } }### Answer:
@Test public void generateSOAPEnvelopeTest() { ArtifactResolve artifactRequest = Mockito.mock(ArtifactResolve.class); Envelope env = artifactBindingHelper.generateSOAPEnvelope(artifactRequest); Assert.assertEquals(artifactRequest, env.getBody().getUnknownXMLObjects().get(0)); Assert.assertEquals(Envelope.DEFAULT_ELEMENT_NAME, env.getElementQName()); } |
### Question:
TenantAndIdEmittableKey extends EmittableKey { public Text getIdField() { return fieldNames[ID_FIELD]; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }### Answer:
@Test public void testGetIdField() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); assertEquals(key.getIdField().toString(), "test.id.key.field"); } |
### Question:
TenantAndIdEmittableKey extends EmittableKey { @Override public String toString() { return "TenantAndIdEmittableKey [" + getIdField() + "=" + getId().toString() + ", " + getTenantIdField() + "=" + getTenantId().toString() + "]"; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final String idFieldName); Text getTenantId(); void setTenantId(final Text id); Text getTenantIdField(); Text getId(); void setId(final Text id); Text getIdField(); @Override void readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }### Answer:
@Test public void testToString() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); key.setTenantId(new Text("Midgar")); key.setId(new Text("1234")); assertEquals(key.toString(), "TenantAndIdEmittableKey [test.id.key.field=1234, meta.data.tenantId=Midgar]"); } |
### Question:
StringValueMapper extends ValueMapper { @Override public Writable getValue(BSONWritable entity) { Writable rval = NullWritable.get(); String value = BSONUtilities.getValue(entity, fieldName); if (value != null && value instanceof String) { rval = new Text(value); } return rval; } StringValueMapper(String fieldName); @Override Writable getValue(BSONWritable entity); }### Answer:
@Test public void testGetValue() { BSONObject field = new BasicBSONObject("field", "testing123"); BSONObject entry = new BasicBSONObject("string", field); BSONWritable entity = new BSONWritable(entry); StringValueMapper mapper = new StringValueMapper("string.field"); Writable value = mapper.getValue(entity); assertFalse(value instanceof NullWritable); assertTrue(value instanceof Text); assertEquals(value.toString(), "testing123"); }
@Test public void testValueNotFound() { BSONObject field = new BasicBSONObject("field", "testing123"); BSONObject entry = new BasicBSONObject("string", field); BSONWritable entity = new BSONWritable(entry); StringValueMapper mapper = new StringValueMapper("string.missing_field"); Writable value = mapper.getValue(entity); assertTrue(value instanceof NullWritable); } |
### Question:
UserResource { Response validateAdminRights(Collection<GrantedAuthority> rights, String tenant) { Collection<GrantedAuthority> rightSet = new HashSet<GrantedAuthority>(rights); rightSet.retainAll(Arrays.asList(Right.ALL_ADMIN_CRUD_RIGHTS)); boolean nullTenant = (tenant == null && !(rights.contains(Right.CRUD_SANDBOX_SLC_OPERATOR) || rights .contains(Right.CRUD_SLC_OPERATOR))); if (nullTenant) { LOG.error("Non-operator user {} has null tenant. Giving up.", new Object[] { secUtil.getUid() }); throw new IllegalArgumentException("Non-operator user " + secUtil.getUid() + " has null tenant. Giving up."); } if (rightSet.isEmpty() || nullTenant) { return composeForbiddenResponse("You are not authorized to access this resource."); } return null; } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }### Answer:
@Test public void testValidateAdminRights() { assertNotNull(resource.validateAdminRights(Arrays.asList(EMPTY_RIGHT), "tenant")); assertNotNull(resource.validateAdminRights(Arrays.asList(NO_ADMIN_RIGHT), "tenant")); assertNull(resource.validateAdminRights(Arrays.asList(ONE_ADMIN_RIGHT_ONLY), "tenant")); assertNull(resource.validateAdminRights(Arrays.asList(ONE_ADMIN_RIGHT_WITH_OTHERS), "tenant")); assertNull(resource.validateAdminRights(Arrays.asList(TWO_ADMIN_RIGHTS_ONLY), "tenant")); assertNull(resource.validateAdminRights(Arrays.asList(TWO_ADMIN_RIGHTS_WITH_OTHERS), "tenant")); }
@Test (expected = RuntimeException.class) public void testValidateAdminBadRights() { assertNull(resource.validateAdminRights(Arrays.asList(ONE_ADMIN_RIGHT_ONLY), null)); } |
### Question:
UserResource { static Response validateAtMostOneAdminRole(final Collection<String> roles) { Collection<String> adminRoles = new ArrayList<String>(Arrays.asList(ADMIN_ROLES)); adminRoles.retainAll(roles); if (adminRoles.size() > 1) { return composeForbiddenResponse("You cannot assign more than one admin role to a user"); } return null; } @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response create(final User newUser); @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response readAll(); @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response update(final User updateUser); @DELETE @Path("{uid}") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response delete(@PathParam("uid") final String uid); @GET @Path("edorgs") @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) final Response getEdOrgs(); void setRealm(String realm); }### Answer:
@Test public void testValidateAtMostOneAdminRole() { assertNull(UserResource.validateAtMostOneAdminRole(Arrays.asList(new String[] {}))); assertNull(UserResource.validateAtMostOneAdminRole(Arrays .asList(new String[] { RoleInitializer.INGESTION_USER }))); assertNull(UserResource .validateAtMostOneAdminRole(Arrays.asList(new String[] { RoleInitializer.SLC_OPERATOR }))); assertNotNull(UserResource.validateAtMostOneAdminRole(Arrays.asList(new String[] { RoleInitializer.SLC_OPERATOR, RoleInitializer.LEA_ADMINISTRATOR }))); assertNull(UserResource.validateAtMostOneAdminRole(Arrays.asList(new String[] { RoleInitializer.LEA_ADMINISTRATOR, RoleInitializer.LEA_ADMINISTRATOR }))); } |
### Question:
ObjectXMLWriter implements MessageBodyWriter { @Override public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); xmlMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); xmlMapper.writeValue(entityStream, o); } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap httpHeaders, OutputStream entityStream); }### Answer:
@Test(expected = IOException.class) public void testEntityNullCollection() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); Home response = new Home(null, body); writer.writeTo(response, null, null, null, null, null, out); }
@Test public void testEntityHome() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); Home response = new Home("TestEntity", body); writer.writeTo(response, null, null, null, null, null, out); assertNotNull("Should not be null", out); String value = new String(out.toByteArray()); assertTrue("Should match", value.startsWith("<Home")); assertTrue("Should match", value.indexOf("<id>") > 0); assertTrue("Should match", value.indexOf("<name>") > 0); }
@Test(expected = IOException.class) public void testNullObject() throws IOException { EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); Home response = new Home("TestEntity", body); writer.writeTo(response, null, null, null, null, null, null); } |
### Question:
ObjectXMLWriter implements MessageBodyWriter { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.Home") || type.getName().equals("org.slc.sli.api.representation.ErrorResponse")) { return true; } return false; } @Override boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap httpHeaders, OutputStream entityStream); }### Answer:
@Test public void testIsWritable() { assertTrue(writer.isWriteable(ErrorResponse.class, null, null, null)); assertTrue(writer.isWriteable(Home.class, null, null, null)); assertFalse(writer.isWriteable(EntityResponse.class, null, null, null)); } |
### Question:
XMLMsgBodyReader implements MessageBodyReader<EntityBody> { @Override public EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { EntityBody body = null; if (entityStream != null) { try { body = reader.deserialize(entityStream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Response.Status.BAD_REQUEST); } } else { body = new EntityBody(); } return body; } @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override EntityBody readFrom(Class<EntityBody> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream); }### Answer:
@Test public void testNullStream() throws IOException { EntityBody body = reader.readFrom(EntityBody.class, null, null, null, null, null); assertNotNull("Should not be null", body); assertTrue("Should be empty", body.isEmpty()); }
@Test public void testBadXml() throws Exception { try { InputStream is = new ByteArrayInputStream("{\"test\":\"foo\"}".getBytes()); reader.readFrom(EntityBody.class, null, null, null, null, is); fail("Should throw Exception because of invalid XML format"); } catch(WebApplicationException wae) { assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), wae.getResponse().getStatus()); } } |
### Question:
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { writeEntity(entityResponse, entityStream); } catch (XMLStreamException e) { LOG.error("Could not write out to XML {}", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }### Answer:
@Test public void testEntityBody() throws IOException { EntityDefinition def = mock(EntityDefinition.class); when(entityDefinitionStore.lookupByEntityType(anyString())).thenReturn(def); ByteArrayOutputStream out = new ByteArrayOutputStream(); EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); EntityResponse response = new EntityResponse("TestEntity", body); writer.writeTo(response, null, null, null, null, null, out); assertNotNull("Should not be null", out); String value = new String(out.toByteArray()); assertTrue("Should match", value.indexOf("<TestEntity") > 0); assertTrue("Should match", value.indexOf("<id>") > 0); assertTrue("Should match", value.indexOf("<name>") > 0); }
@Test public void testEntityNullCollection() throws IOException { EntityDefinition def = mock(EntityDefinition.class); when(entityDefinitionStore.lookupByEntityType(anyString())).thenReturn(def); ByteArrayOutputStream out = new ByteArrayOutputStream(); EntityBody body = new EntityBody(); body.put("id", "1234"); body.put("name", "test name"); EntityResponse response = new EntityResponse(null, body); writer.writeTo(response, null, null, null, null, null, out); assertNotNull("Should not be null", out); String value = new String(out.toByteArray()); assertTrue("Should match", value.indexOf("<Entity") > 0); }
@Test public void testHandleLists() throws IOException { final EntityDefinition def = mock(EntityDefinition.class); when(entityDefinitionStore.lookupByEntityType(anyString())).thenReturn(def); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final EntityBody body = new EntityBody(); final Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("k1", "v1"); testMap.put("k2", "v2"); body.put("mapKey", testMap); final List<String> list = new ArrayList<String>(); list.add("test1"); list.add("test2"); list.add("test3"); body.put("listItem", list); body.put("id", "1234"); body.put("name", "test name"); final EntityResponse response = new EntityResponse("TestEntity", Arrays.asList(body)); writer.writeTo(response, null, null, null, null, null, out); assertNotNull("Should not be null", out); String value = new String(out.toByteArray()); assertTrue("Should match", value.indexOf("<TestEntityList") > 0); assertTrue("Should match", value.indexOf("<id>") > 0); assertTrue("Should match", value.indexOf("<name>") > 0); assertEquals(3, StringUtils.countMatches(value, "<listItem")); assertEquals(1, StringUtils.countMatches(value, "<mapKey>")); } |
### Question:
ExtractorImpl implements Extractor { @Override public void execute() { Future<String> call; List<Future<String>> futures = new LinkedList<Future<String>>(); for (String tenant : tenants) { try { call = executor.submit(new ExtractWorker(tenant)); futures.add(call); } catch (FileNotFoundException e) { LOG.error("Error while extracting data for tenant " + tenant, e); } } for (Future<String> future : futures) { processFuture(future); } destroy(); } void destroy(); void init(); void createExtractDir(); @Override void execute(); @Override void execute(String tenant); @Override String getHealth(); File extractEntity(String tenant, OutstreamZipFile zipFile, String entityName); void setExtractDir(String extractDir); void setExecutorThreads(int executorThreads); void setRunOnStartup(boolean runOnStartup); void setEntityRepository(Repository<Entity> entityRepository); void setTenants(List<String> tenants); void setEntities(List<String> entities); void setQueriedEntities(Map<String, String> queriedEntities); void setCombinedEntities(Map<String, List<String>> combinedEntities); }### Answer:
@Test public void testExtractMultipleTenantsIntoSeparateZipFiles() throws Exception { extractor.execute(); File zipFile1 = new File(extractDir, TENANT1 + ".zip"); Assert.assertTrue(zipFile1.length() > 0); File zipFile2 = new File(extractDir, TENANT2 + ".zip"); Assert.assertTrue(zipFile2.length() > 0); } |
### Question:
EntityXMLWriter implements MessageBodyWriter<EntityResponse> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (type.getName().equals("org.slc.sli.api.representation.EntityResponse")) { return true; } return false; } @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(EntityResponse entityResponse, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType); @Override void writeTo(EntityResponse entityResponse, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }### Answer:
@Test public void testIsWritable() { assertFalse(writer.isWriteable(ErrorResponse.class, null, null, null)); assertFalse(writer.isWriteable(Home.class, null, null, null)); assertTrue(writer.isWriteable(EntityResponse.class, null, null, null)); } |
### Question:
FourPartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.FOUR_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.FOUR_PART); final Resource association = resourceHelper.getAssociationName(uriInfo, ResourceTemplate.FOUR_PART); return resourceService.getEntities(base, id, association, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo,
@PathParam("id") final String id); }### Answer:
@Test public void testGet() throws URISyntaxException { String studentId = resourceService.postEntity(studentResource, createTestEntity()); String sectionId = resourceService.postEntity(sectionResource, createSectionEntity()); String assocId = resourceService.postEntity(ssaResource, createAssociationEntity(studentId, sectionId)); setupMocks(BASE_URI + "/" + studentId + "/studentSectionAssociations/sections"); Response response = fourPartResource.get(uriInfo, studentId); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); } |
### Question:
ChangedUriInfo implements UriInfo { @Override public String getPath() { String uriPath = this.uri.getPath(); if (uriPath != null) { String removeString = "/rest/"; if (uriPath.startsWith(removeString)) { return uriPath.substring(removeString.length()); } return uriPath; } return null; } ChangedUriInfo(String uri, UriInfo uriInfo); String getOriginalUri(); @Override String getPath(); @Override String getPath(boolean decode); @Override List<PathSegment> getPathSegments(); @Override List<PathSegment> getPathSegments(boolean decode); @Override URI getRequestUri(); @Override UriBuilder getRequestUriBuilder(); @Override URI getAbsolutePath(); @Override UriBuilder getAbsolutePathBuilder(); @Override URI getBaseUri(); @Override UriBuilder getBaseUriBuilder(); @Override MultivaluedMap<String, String> getPathParameters(); @Override MultivaluedMap<String, String> getPathParameters(boolean decode); @Override MultivaluedMap<String, String> getQueryParameters(); @Override MultivaluedMap<String, String> getQueryParameters(boolean decode); @Override List<String> getMatchedURIs(); @Override List<String> getMatchedURIs(boolean decode); @Override List<Object> getMatchedResources(); static final String ORIGINAL_REQUEST_KEY; }### Answer:
@Test public void testGetPath() { assertTrue(new ChangedUriInfo("/rest/foo/bar", null).getPath().equals("foo/bar")); } |
### Question:
DefaultAssessmentResourceService implements AssessmentResourceService { @Override public ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI) { final EntityDefinition baseEntityDefinition = resourceHelper.getEntityDefinition(base); final EntityDefinition finalEntityDefinition = resourceHelper.getEntityDefinition(returnResource); final List<String> ids = Arrays.asList(idList.split(",")); ApiQuery apiQuery = resourceServiceHelper.getApiQuery(baseEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", ids)); apiQuery.setLimit(0); apiQuery.setOffset(0); List<EntityBody> baseResults = (List<EntityBody>) baseEntityDefinition.getService().list(apiQuery); String key = null; if (returnResource.getResourceType().equals("learningStandards")) { key = "assessmentItem"; } else { key = "objectiveAssessment"; } List<String> finalIds = new ArrayList<String>(); for (EntityBody entityBody : baseResults) { List<Map<String, Object>> items = (List<Map<String, Object>>) entityBody.get(key); if (items != null) { for (Map<String, Object> item : items) { finalIds.addAll((List<String>) item.get(returnResource.getResourceType())); } } } apiQuery = resourceServiceHelper.getApiQuery(finalEntityDefinition, requestURI); apiQuery.addCriteria(new NeutralCriteria("_id", "in", finalIds)); List<EntityBody> finalResults = null; try { finalResults = logicalEntity.getEntities(apiQuery, returnResource.getResourceType()); } catch (UnsupportedSelectorException e) { finalResults = (List<EntityBody>) finalEntityDefinition.getService().list(apiQuery); } return new ServiceResponse(finalResults, finalResults.size()); } @Override ServiceResponse getLearningStandards(final Resource base, final String idList, final Resource returnResource, final URI requestURI); }### Answer:
@Test public void testGetLearningStandards() throws URISyntaxException { String learningStandardId = resourceService.postEntity(learningStandards, createLearningStandardEntity()); String assessmentId = resourceService.postEntity(assessments, createAssessmentEntity(learningStandardId)); requestURI = new java.net.URI(URI + "/" + assessmentId + "/learningStandards"); List<EntityBody> entityBodyList = defaultAssessmentResourceService.getLearningStandards(assessments, assessmentId, learningStandards, requestURI).getEntityBodyList(); assertNotNull("Should return an entity", entityBodyList); assertEquals("Should match", 1, entityBodyList.size()); assertEquals("Should match", "learningStandard", entityBodyList.get(0).get("entityType")); } |
### Question:
CustomEntityDecorator implements EntityDecorator { @Override public void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams) { List<String> params = queryParams.get(ParameterConstants.INCLUDE_CUSTOM); final Boolean includeCustomEntity = Boolean.valueOf((params != null) ? params.get(0) : "false"); if (includeCustomEntity) { String entityId = (String) entity.get("id"); EntityBody custom = definition.getService().getCustom(entityId); if (custom != null) { entity.put(ResourceConstants.CUSTOM, custom); } } } @Override void decorate(EntityBody entity, EntityDefinition definition, MultivaluedMap<String, String> queryParams); }### Answer:
@Test public void testDecoratorNonParam() { MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add(ParameterConstants.INCLUDE_CUSTOM, String.valueOf(false)); EntityBody body = createTestEntity(); customEntityDecorator.decorate(body, null, map); assertEquals("Should match", 3, body.keySet().size()); assertEquals("Should match", "Male", body.get("sex")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); }
@Test public void testDecoratorWithParam() { MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add(ParameterConstants.INCLUDE_CUSTOM, String.valueOf(true)); EntityBody custom = createCustomEntity(); EntityService service = mock(EntityService.class); when(service.getCustom("1234")).thenReturn(custom); EntityDefinition definition = mock(EntityDefinition.class); when(definition.getService()).thenReturn(service); EntityBody body = createTestEntity(); customEntityDecorator.decorate(body, definition, map); assertEquals("Should match", 4, body.keySet().size()); assertEquals("Should match", "Male", body.get("sex")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); EntityBody customBody = (EntityBody) body.get(ResourceConstants.CUSTOM); assertNotNull("Should not be null", customBody); assertEquals("Should match", "1", customBody.get("customValue")); } |
### Question:
ResourceServiceHelper { protected ApiQuery addTypeCriteria(EntityDefinition entityDefinition, ApiQuery apiQuery) { if (apiQuery != null && entityDefinition != null) { if( !entityDefinition.getType().equals(entityDefinition.getStoredCollectionName())) { apiQuery.addCriteria(new NeutralCriteria("type", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityDefinition.getDbType()), false)); } NeutralCriteria criteria = entityDefinition.getTypeCriteria(); if(criteria != null) { apiQuery.addCriteria(criteria); } } return apiQuery; } ApiQuery getApiQuery(EntityDefinition definition, final URI requestURI); ApiQuery getApiQuery(EntityDefinition definition); }### Answer:
@Test public void testAddTypeCriteria() { EntityDefinition def = entityDefs.lookupByResourceName(ResourceNames.TEACHERS); ApiQuery query = new ApiQuery(); query = resourceServiceHelper.addTypeCriteria(def, query); List<NeutralCriteria> criteriaList = query.getCriteria(); assertEquals("Should match", 1, criteriaList.size()); NeutralCriteria criteria = criteriaList.get(0); assertEquals("Should match", "type", criteria.getKey()); assertEquals("Should match", NeutralCriteria.CRITERIA_IN, criteria.getOperator()); assertEquals("Should match", Arrays.asList(def.getType()), criteria.getValue()); }
@Test public void testAddTypeCriteriaNoChange() { EntityDefinition def = entityDefs.lookupByResourceName(ResourceNames.STAFF); ApiQuery query = new ApiQuery(); query = resourceServiceHelper.addTypeCriteria(def, query); List<NeutralCriteria> criteriaList = query.getCriteria(); assertEquals("Should match", 0, criteriaList.size()); }
@Test public void testAddTypeCriteriaNullValues() { ApiQuery query = null; assertNull("Should be null", resourceServiceHelper.addTypeCriteria(null, null)); query = new ApiQuery(); query = resourceServiceHelper.addTypeCriteria(null, query); List<NeutralCriteria> criteriaList = query.getCriteria(); assertEquals("Should match", 0, criteriaList.size()); } |
### Question:
WordCountCascading { public void execute(String inputPath, String outputPath) { Scheme sourceScheme = new TextLine( new Fields( "line" ) ); Tap source = new Hfs( sourceScheme, inputPath ); Scheme sinkScheme = new TextLine( new Fields( "word", "count" ) ); Tap sink = new Hfs( sinkScheme, outputPath, SinkMode.REPLACE ); Pipe assembly = new Pipe( "wordcount" ); String regex = "(?<!\\pL)(?=\\pL)[^ ]*(?<=\\pL)(?!\\pL)"; Function function = new RegexGenerator( new Fields( "word" ), regex ); assembly = new Each( assembly, new Fields( "line" ), function ); assembly = new GroupBy( assembly, new Fields( "word" ) ); Aggregator count = new Count( new Fields( "count" ) ); assembly = new Every( assembly, count ); Properties properties = new Properties(); FlowConnector.setApplicationJarClass( properties, WordCountCascading.class ); FlowConnector flowConnector = new FlowConnector( properties ); Flow flow = flowConnector.connect( "word-count", source, sink, assembly ); flow.complete(); } void execute(String inputPath, String outputPath); }### Answer:
@Test public void testExecute() { WordCountCascading wc = new WordCountCascading(); wc.execute("src/main/resources/short.txt", "target/cascading-result"); System.out.println("completed Cascading word count"); } |
### Question:
DefaultResourceService implements ResourceService { @Override @MigratePostedEntity public String postEntity(final Resource resource, EntityBody entity) { EntityDefinition definition = resourceHelper.getEntityDefinition(resource); List<String> entityIds = new ArrayList<String>(); if (SecurityUtil.isStaffUser()) { entityIds = definition.getService().createBasedOnContextualRoles(adapter.migrate(entity, definition.getResourceName(), POST)); } else { entityIds = definition.getService().create(adapter.migrate(entity, definition.getResourceName(), POST)); } return StringUtils.join(entityIds.toArray(), ","); } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI,
final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }### Answer:
@Test public void testCreate() { String id = resourceService.postEntity(resource, new EntityBody(createTestEntity())); assertNotNull("ID should not be null", id); } |
### Question:
DefaultResourceService implements ResourceService { @Override public String getEntityType(Resource resource) { return resourceHelper.getEntityDefinition(resource).getType(); } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI,
final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }### Answer:
@Test public void testGetEntityType() { assertEquals("Should match", "student", resourceService.getEntityType(new Resource("v1", "students"))); assertEquals("Should match", "staff", resourceService.getEntityType(new Resource("v1", "staff"))); assertEquals("Should match", "teacher", resourceService.getEntityType(new Resource("v1", "teachers"))); } |
### Question:
DefaultResourceService implements ResourceService { protected long getEntityCount(EntityDefinition definition, ApiQuery apiQuery) { long count = 0; if (definition.getService() == null) { return count; } if (apiQuery == null) { return definition.getService().count(new NeutralQuery()); } int originalLimit = apiQuery.getLimit(); int originalOffset = apiQuery.getOffset(); apiQuery.setLimit(0); apiQuery.setOffset(0); if (SecurityUtil.isStaffUser()) { count = definition.getService().countBasedOnContextualRoles(apiQuery); } else { count = definition.getService().count(apiQuery); } apiQuery.setLimit(originalLimit); apiQuery.setOffset(originalOffset); return count; } @PostConstruct void init(); @Override @MigrateResponse ServiceResponse getEntitiesByIds(final Resource resource, final String idList, final URI requestURI); @Override @MigrateResponse ServiceResponse getEntities(final Resource resource, final URI requestURI,
final boolean getAllEntities); @Override @MigratePostedEntity String postEntity(final Resource resource, EntityBody entity); @Override @MigratePostedEntity void putEntity(Resource resource, String id, EntityBody entity); @Override @MigratePostedEntity void patchEntity(Resource resource, String id, EntityBody entity); @Override void deleteEntity(Resource resource, String id); @Override String getEntityType(Resource resource); @Override CalculatedData<String> getCalculatedData(Resource resource, String id); @Override CalculatedData<Map<String, Integer>> getAggregateData(Resource resource, String id); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @MigrateResponse ServiceResponse getEntities(final Resource base, final String id, final Resource resource, final URI requestURI); @Override ServiceResponse getEntities(Resource base, String id, Resource association, Resource resource, URI requestUri); }### Answer:
@Test public void testGetEntityCount() { String id = resourceService.postEntity(resource, new EntityBody(createTestEntity())); ApiQuery apiQuery = new ApiQuery(); apiQuery.addCriteria(new NeutralCriteria("_id", "in", Arrays.asList(id))); Long count = resourceService.getEntityCount(entityDefs.lookupByResourceName(resource.getResourceType()), apiQuery); assertEquals("Should match", 1, count.longValue()); } |
### Question:
PublicDefaultResource extends DefaultResource { @Override @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.ONE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), true); } }); } @Override @GET Response getAll(@Context final UriInfo uriInfo); }### Answer:
@Test public void testGetAll() throws URISyntaxException { setupMocks(BASE_URI); Response response = publicDefaultResource.getAll(uriInfo); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); } |
### Question:
AssessmentResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return assessmentResourceService.getLearningStandards(base, id, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo,
@PathParam("id") final String id); }### Answer:
@Test public void testGet() throws URISyntaxException { String learningStandardId = resourceService.postEntity(learningStandards, createLearningStandardEntity()); String assessmentId = resourceService.postEntity(assessments, createAssessmentEntity(learningStandardId)); setupMocks(BASE_URI + "/" + assessmentId + "/learningStandards"); Response response = assessmentResource.get(uriInfo, assessmentId); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); EntityResponse entityResponse = (EntityResponse) response.getEntity(); assertEquals("Should match", 1, ((List<EntityBody>) entityResponse.getEntity()).size()); } |
### Question:
ResourceEndPoint { protected String getResourceClass(final String resourcePath, ResourceEndPointTemplate template) { if (template.getResourceClass() != null) { return template.getResourceClass(); } String resourceClass = bruteForceMatch(resourcePath); return resourceClass; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }### Answer:
@Test public void testGetResourceClass() { ResourceEndPointTemplate template = new ResourceEndPointTemplate(); template.setResourceClass("templateClass"); assertEquals("Should match", "templateClass", resourceEndPoint.getResourceClass("/students", template)); template.setResourceClass(null); assertEquals("Should match", "org.slc.sli.api.resources.generic.FourPartResource", resourceEndPoint.getResourceClass("/students", template)); }
@Test(expected = RuntimeException.class) public void testNoClass() { ResourceEndPointTemplate template = new ResourceEndPointTemplate(); template.setResourceClass(null); when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.FOUR_PART)).thenReturn(false); when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.THREE_PART)).thenReturn(false); when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.TWO_PART)).thenReturn(false); when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.ONE_PART)).thenReturn(false); resourceEndPoint.getResourceClass("/students", template); } |
### Question:
ResourceEndPoint { protected Map<String, String> buildEndPoints(String nameSpace, String resourcePath, ResourceEndPointTemplate template) { Map<String, String> resources = new HashMap<String, String>(); String fullPath = nameSpace + resourcePath + template.getPath(); resources.put(fullPath, getResourceClass("/rest/" + fullPath, template)); List<ResourceEndPointTemplate> subResources = template.getSubResources(); if (subResources != null) { for (ResourceEndPointTemplate subTemplate : subResources) { resources.putAll(buildEndPoints(nameSpace, resourcePath + template.getPath(), subTemplate)); } } return resources; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }### Answer:
@Test public void testBuildEndPoints() { when(resourceHelper.resolveResourcePath("/students", ResourceTemplate.THREE_PART)).thenReturn(true); ResourceEndPointTemplate template = new ResourceEndPointTemplate(); template.setPath("/students"); template.setResourceClass("someClass"); ResourceEndPointTemplate subResource = new ResourceEndPointTemplate(); subResource.setPath("/{id}/studentSectionAssociations"); template.setSubResources(Arrays.asList(subResource)); Map<String, String> resources = resourceEndPoint.buildEndPoints("v1", "", template); assertEquals("Should match", 2, resources.keySet().size()); assertEquals("Should match", "someClass", resources.get("v1/students")); assertEquals("Should match", "org.slc.sli.api.resources.generic.ThreePartResource", resources.get("v1/students/{id}/studentSectionAssociations")); } |
### Question:
ResourceEndPoint { protected ApiNameSpace[] loadNameSpace(InputStream fileStream) throws IOException { ObjectMapper mapper = new ObjectMapper(); ApiNameSpace[] apiNameSpaces = mapper.readValue(fileStream, ApiNameSpace[].class); for (ApiNameSpace apiNameSpace : apiNameSpaces) { String[] nameSpaces = apiNameSpace.getNameSpace(); for (String nameSpace : nameSpaces) { nameSpaceMappings.putAll(buildNameSpaceMappings(nameSpace, nameSpaceMappings)); List<ResourceEndPointTemplate> resources = apiNameSpace.getResources(); for (ResourceEndPointTemplate resource : resources) { if (!resource.isQueryable()) { queryingDisallowedEndPoints.add(resource.getPath().substring(1)); } if (resource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath()); } if (resource.isBlockGetRequest()) { blockGetRequestEndPoints.add(nameSpace + resource.getPath()); } if (resource.getSubResources() != null) { for (ResourceEndPointTemplate subResource : resource.getSubResources()) { if (subResource.isDateSearchDisallowed()) { dateRangeDisallowedEndPoints.add(nameSpace + resource.getPath() + subResource.getPath()); } } } resourceEndPoints.putAll(buildEndPoints(nameSpace, "", resource)); } } } return apiNameSpaces; } @PostConstruct void load(); List<String> getQueryingDisallowedEndPoints(); Set<String> getDateRangeDisallowedEndPoints(); Set<String> getBlockGetRequestEndPoints(); Map<String, String> getResources(); Map<String, SortedSet<String>> getNameSpaceMappings(); void setNameSpaceMappings(Map<String, SortedSet<String>> nameSpaceMappings); }### Answer:
@Test public void testLoadNameSpace() throws IOException { String json = "[" + "{\n" + " \"nameSpace\": [\"v6.0\", \"v6.1\"],\n" + " \"resources\":[\n" + " {\n" + " \"path\":\"/reportCards\",\n" + " \"doc\":\"some doc.\"\n" + " }]}," + "{\n" + " \"nameSpace\": [\"v7.0\"],\n" + " \"resources\":[\n" + " {\n" + " \"path\":\"/schools\",\n" + " \"dateSearchDisallowed\":\"true\",\n" + " \"doc\":\"some school doc.\"\n" + " }]}]"; ByteArrayInputStream inputStream = new ByteArrayInputStream(json.getBytes()); ApiNameSpace[] nameSpaces = resourceEndPoint.loadNameSpace(inputStream); assertEquals("Should match", 2, nameSpaces.length); ApiNameSpace nameSpace = nameSpaces[0]; assertEquals("Should match", 2, nameSpace.getNameSpace().length); assertEquals("Should match", "v6.0", nameSpace.getNameSpace()[0]); assertEquals("Should match", "v6.1", nameSpace.getNameSpace()[1]); assertEquals("Should match", 1, nameSpace.getResources().size()); assertEquals("Should match", "/reportCards", nameSpace.getResources().get(0).getPath()); assertEquals("Should match", "some doc.", nameSpace.getResources().get(0).getDoc()); nameSpace = nameSpaces[1]; assertEquals("Should match", 1, nameSpace.getNameSpace().length); assertEquals("Should match", "v7.0", nameSpace.getNameSpace()[0]); assertEquals("Should match", 1, nameSpace.getResources().size()); assertEquals("Should match", "/schools", nameSpace.getResources().get(0).getPath()); assertEquals("Should match", "some school doc.", nameSpace.getResources().get(0).getDoc()); assertEquals("Should have one entry", 1, resourceEndPoint.getDateRangeDisallowedEndPoints().size()); assertTrue("Should match", resourceEndPoint.getDateRangeDisallowedEndPoints().contains("v7.0/schools")); } |
### Question:
WordCountHadoop { public void execute(String inputPath, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "wordcount"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } void execute(String inputPath, String outputPath); }### Answer:
@Test public void testExecute() throws Exception { WordCountHadoop wc = new WordCountHadoop(); wc.execute("src/main/resources/short.txt", "target/hadoop-result"); System.out.println("completed Hadoop word count"); } |
### Question:
MethodNotAllowedException extends RuntimeException { public Set<String> getAllowedMethods() { return allowedMethods; } MethodNotAllowedException(Set<String> allowedMethods); Set<String> getAllowedMethods(); }### Answer:
@Test public void testExceptionMethods() { assertEquals("Should match", 2, exception.getAllowedMethods().size()); assertTrue("Should be true", exception.getAllowedMethods().contains("GET")); assertTrue("Should be true", exception.getAllowedMethods().contains("POST")); } |
### Question:
ThreePartResource extends GenericResource { @GET public Response get(@Context final UriInfo uriInfo, @PathParam("id") final String id) { return getAllResponseBuilder.build(uriInfo, ResourceTemplate.THREE_PART, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { final Resource base = resourceHelper.getBaseName(uriInfo, ResourceTemplate.THREE_PART); return resourceService.getEntities(base, id, resource, uriInfo.getRequestUri()); } }); } @GET Response get(@Context final UriInfo uriInfo,
@PathParam("id") final String id); }### Answer:
@Test public void testGet() throws URISyntaxException { String studentId = resourceService.postEntity(studentResource, createTestEntity()); String sectionId = resourceService.postEntity(sectionResource, createSectionEntity()); String assocId = resourceService.postEntity(ssaResource, createAssociationEntity(studentId, sectionId)); setupMocks(BASE_URI + "/" + studentId + "/studentSectionAssociations"); Response response = threePartResource.get(uriInfo, studentId); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); } |
### Question:
ResponseBuilder { protected Resource constructAndCheckResource(final UriInfo uriInfo, final ResourceTemplate template, final ResourceMethod method) { Resource resource = resourceHelper.getResourceName(uriInfo, template); resourceAccessLog.logAccessToRestrictedEntity(uriInfo, resource, GetResponseBuilder.class.toString()); return resource; } }### Answer:
@Test public void testConstructAndCheckResource() { Resource resourceContainer = responseBuilder.constructAndCheckResource(uriInfo, ResourceTemplate.ONE_PART, ResourceMethod.GET); assertNotNull("Should not be null", resourceContainer); assertEquals("Should match", "v1", resourceContainer.getNamespace()); assertEquals("Should match", "students", resourceContainer.getResourceType()); } |
### Question:
GetResponseBuilder extends ResponseBuilder { protected void validatePublicResourceQuery(final UriInfo uriInfo) { List<PathSegment> uriPathSegments = uriInfo.getPathSegments(); if (uriPathSegments != null) { if (uriPathSegments.size() == 2) { String endpoint = uriPathSegments.get(1).getPath(); if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) { ApiQuery apiQuery = new ApiQuery(uriInfo); if (apiQuery.getCriteria().size() > 0) { throw new QueryParseException("Querying not allowed", apiQuery.toString()); } } } } } Response build(final UriInfo uriInfo, final ResourceTemplate template,
final ResourceMethod method, final GenericResource.GetResourceLogic logic); static final String ORIGINAL_REQUEST_KEY; }### Answer:
@Ignore @Test(expected = QueryParseException.class) public void testValidatePublicResourceInvalidQuery() throws URISyntaxException { requestURI = new URI(URI + "?someField=someValue"); setupMocks("assessments"); getResponseBuilder.validatePublicResourceQuery(uriInfo); }
@Ignore @Test(expected = QueryParseException.class) public void testValidatePublicResourceMultiInvalidQuery() throws URISyntaxException { requestURI = new URI(URI + "?limit=0&someField=someValue&includeFields=somefield"); setupMocks("assessments"); getResponseBuilder.validatePublicResourceQuery(uriInfo); }
@Test public void testValidatePublicResourceQueryValidQuery() throws URISyntaxException { try { requestURI = new URI(URI + "?limit=0"); setupMocks("assessments"); getResponseBuilder.validatePublicResourceQuery(uriInfo); } catch (QueryParseException e) { fail("Should not throw an exception"); } }
@Test public void testValidatePublicResourceQueryMultiValidQuery() throws URISyntaxException { try { requestURI = new URI(URI + "?limit=0&includeFields=somefield"); setupMocks("assessments"); getResponseBuilder.validatePublicResourceQuery(uriInfo); } catch (QueryParseException e) { fail("Should not throw an exception"); } }
@Test public void testValidateNonPublicResourceFilter() throws URISyntaxException { try { requestURI = new URI(URI + "?someField=someValue"); setupMocks("students"); getResponseBuilder.validatePublicResourceQuery(uriInfo); } catch (QueryParseException e) { fail("Should not throw an exception"); } }
@Test public void testValidateNonPublicResource() throws URISyntaxException { try { requestURI = new URI(URI + "?limit=0"); setupMocks("students"); getResponseBuilder.validatePublicResourceQuery(uriInfo); } catch (QueryParseException e) { fail("Should not throw an exception"); } } |
### Question:
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody,
@Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }### Answer:
@Ignore @Test public void testGetAll() throws URISyntaxException { setupMocks(BASE_URI); Response response = defaultResource.getAll(uriInfo); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); } |
### Question:
BigDiffHadoop { public void execute(String inputPath1, String inputPath2, String outputPath) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "bigdiff"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(inputPath1)); FileInputFormat.addInputPath(job, new Path(inputPath2)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); } void execute(String inputPath1, String inputPath2, String outputPath); }### Answer:
@Test public void testExecute() throws Exception { BigDiffHadoop bd = new BigDiffHadoop(); bd.execute("src/main/resources/bigdiff/left.txt", "src/main/resources/bigdiff/right-sorted.txt", outputDirectory); System.out.println("completed Hadoop big diff"); } |
### Question:
DefaultResource extends GenericResource implements CustomEntityReturnable { @POST public Response post(final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, onePartTemplate, ResourceMethod.POST, new ResourceLogic() { @Override public Response run(Resource resource) { if (entityBody == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } final String id = resourceService.postEntity(resource, entityBody); final String uri = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), resource.getResourceType(), id).toString(); return Response.status(Response.Status.CREATED).header("Location", uri).build(); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody,
@Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }### Answer:
@Ignore @Test public void testPost() throws URISyntaxException { setupMocks(BASE_URI); Response response = defaultResource.post(createTestEntity(), uriInfo); assertEquals("Status code should be OK", Response.Status.CREATED.getStatusCode(), response.getStatus()); assertNotNull("Should not be null", parseIdFromLocation(response)); } |
### Question:
DefaultResource extends GenericResource implements CustomEntityReturnable { @GET @Path("{id}") public Response getWithId(@PathParam("id") final String id, @Context final UriInfo uriInfo) { return getResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.GET, new GenericResource.GetResourceLogic() { @Override public ServiceResponse run(Resource resource) { return resourceService.getEntitiesByIds(resource, id, uriInfo.getRequestUri()); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody,
@Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }### Answer:
@Ignore @Test public void testGetWithId() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); Response response = defaultResource.getWithId(id, uriInfo); EntityResponse entityResponse = (EntityResponse) response.getEntity(); EntityBody body = (EntityBody) entityResponse.getEntity(); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("Should match", id, body.get("id")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); }
@Test(expected = EntityNotFoundException.class) public void testGetInvalidId() throws URISyntaxException { setupMocks(BASE_URI + "/1234"); defaultResource.getWithId("1234", uriInfo); } |
### Question:
DefaultResource extends GenericResource implements CustomEntityReturnable { @PUT @Path("{id}") public Response put(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PUT, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPut()) { resourceService.putEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody,
@Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }### Answer:
@Test public void testPut() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); Response response = defaultResource.put(id, createTestUpdateEntity(), uriInfo); assertEquals("Status code should be OK", Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); Response getResponse = defaultResource.getWithId(id, uriInfo); EntityResponse entityResponse = (EntityResponse) getResponse.getEntity(); EntityBody body = (EntityBody) entityResponse.getEntity(); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), getResponse.getStatus()); assertEquals("Should match", id, body.get("id")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); assertEquals("Should match", "Female", body.get("sex")); } |
### Question:
DefaultResource extends GenericResource implements CustomEntityReturnable { @PATCH @Path("{id}") public Response patch(@PathParam("id") final String id, final EntityBody entityBody, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(entityBody, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.PATCH, new ResourceLogic() { @Override public Response run(Resource resource) { EntityDefinition entityDefinition = entityDefinitionStore.lookupByResourceName(resource.getResourceType()); if(entityDefinition.supportsPatch()) { resourceService.patchEntity(resource, id, entityBody); return Response.status(Response.Status.NO_CONTENT).build(); } else { return Response.status(405).build(); } } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody,
@Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }### Answer:
@Test public void testPatch() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); Response response = defaultResource.patch(id, createTestPatchEntity(), uriInfo); assertEquals("Status code should be OK", Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); Response getResponse = defaultResource.getWithId(id, uriInfo); EntityResponse entityResponse = (EntityResponse) getResponse.getEntity(); EntityBody body = (EntityBody) entityResponse.getEntity(); assertEquals("Status code should be OK", Response.Status.OK.getStatusCode(), getResponse.getStatus()); assertEquals("Should match", id, body.get("id")); assertEquals("Should match", 1234, body.get("studentUniqueStateId")); assertEquals("Should match", "Female", body.get("sex")); } |
### Question:
DefaultResource extends GenericResource implements CustomEntityReturnable { @DELETE @Path("{id}") public Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo) { writeValidator.validateWriteRequest(null, uriInfo, SecurityUtil.getSLIPrincipal()); return defaultResponseBuilder.build(uriInfo, twoPartTemplate, ResourceMethod.DELETE, new ResourceLogic() { @Override public Response run(Resource resource) { resourceService.deleteEntity(resource, id); return Response.status(Response.Status.NO_CONTENT).build(); } }); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody,
@Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }### Answer:
@Test(expected = EntityNotFoundException.class) public void testDelete() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); Response response = defaultResource.delete(id, uriInfo); assertEquals("Status code should be OK", Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); defaultResource.getWithId(id, uriInfo); } |
### Question:
DefaultResource extends GenericResource implements CustomEntityReturnable { @Override public CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo) { final Resource resource = resourceHelper.getResourceName(uriInfo, ResourceTemplate.CUSTOM); return new CustomEntityResource(id, resourceHelper.getEntityDefinition(resource.getResourceType()), resourceHelper); } DefaultResource(); @GET Response getAll(@Context final UriInfo uriInfo); @POST Response post(final EntityBody entityBody,
@Context final UriInfo uriInfo); @GET @Path("{id}") Response getWithId(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PUT @Path("{id}") Response put(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @DELETE @Path("{id}") Response delete(@PathParam("id") final String id,
@Context final UriInfo uriInfo); @PATCH @Path("{id}") Response patch(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @Override CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); }### Answer:
@Test public void testGetCustomResource() throws URISyntaxException { String id = resourceService.postEntity(resource, createTestEntity()); setupMocks(BASE_URI + "/" + id); CustomEntityResource resource = defaultResource.getCustomResource(id, uriInfo); assertNotNull("Should not be null", resource); } |
### Question:
SupportResource { @GET @Path("email") public Object getEmail() { if (!isAuthenticated(SecurityContextHolder.getContext())) { throw new InsufficientAuthenticationException("User must be logged in"); } Map<String, String> emailMap = new HashMap<String, String>(); emailMap.put("email", email); return emailMap; } @GET @Path("email") Object getEmail(); }### Answer:
@Test public void testGetEmailFailure() throws Exception { assertNotNull(resource); AnonymousAuthenticationToken anon = new AnonymousAuthenticationToken("anon", "anon", Arrays.<GrantedAuthority>asList(Right.ANONYMOUS_ACCESS)); anon.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(anon); try { resource.getEmail(); assertFalse(true); } catch (InsufficientAuthenticationException e) { assertTrue(true); } }
@Test public void testGetEmailPass() throws Exception { injector.setEducatorContext(); Map<String, String> returned = (Map<String, String>) resource.getEmail(); assertTrue(returned.get("email").equals(email)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
OptionalFieldAppenderFactory { public OptionalFieldAppender getOptionalFieldAppender(String type) { return generators.get(type); } OptionalFieldAppender getOptionalFieldAppender(String type); static final String APPENDER_PREFIX; static final String PARAM_PREFIX; }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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")); }
@Test public void testSectionIdsNoAssociation() { Set<String> list = helper.getSectionIds(createEntityList(false)); assertTrue("List should be empty", list.isEmpty()); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@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"); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void testDelete() { Response res = resource.delete(); assertNotNull(res); assertEquals(Status.NO_CONTENT.getStatusCode(), res.getStatus()); Mockito.verify(service).deleteCustom("TEST-ID"); } |
### Question:
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); }### Answer:
@Test public void testInvalidURL() throws URISyntaxException { assertFalse("Should not validate", validator.validate(new URI("http: assertFalse("Should not validate", validator.validate(new URI("http: }
@Test public void testValidURL() throws URISyntaxException { assertTrue("Should validate", validator.validate(new URI("http: assertTrue("Should validate", validator.validate(new URI("http: } |
### Question:
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); }### Answer:
@Test public void testInvalidQueryString() throws URISyntaxException { assertFalse("Should not validate", queryStringValidator.validate(new URI("http: }
@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")))); } |
### Question:
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); }### Answer:
@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)); }
@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: }
@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"); } |
### Question:
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); }### Answer:
@Test(expected = QueryParseException.class) public void shouldDisallowVersionOneZeroSearches() { ContainerRequest request = createRequest("v1.0/sections/1234/studentSectionAssociations", "schoolYears=2011-2012"); filter.filter(request); }
@Test public void shouldAllowVersionOneZeroNonSearchRequests() { ContainerRequest request = createRequest("v1.0/sections/1234/studentSectionAssociations", ""); filter.filter(request); }
@Test public void shonuldAllowVersionOneOneSearches() { ContainerRequest request = createRequest("v1.1/sections/1234/studentSectionAssociations", "schoolYears=2011-2012"); filter.filter(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); }
@Test(expected = QueryParseException.class) public void shouldDisallowTwoPartUris() { String requestPath = "v1.1/sessions/1234567"; ContainerRequest request = createRequest(requestPath, "schoolYears=2011-2012"); filter.filter(request); }
@Test public void shouldAllowTwoPartUrisWithoutDates() { String requestPath = "v1.1/sessions/1234567"; ContainerRequest request = createRequest(requestPath, ""); filter.filter(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); } |
### Question:
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); }### Answer:
@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) { } } }
@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()); }
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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: }
@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()); } |
### Question:
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; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testProdModeNoProps() { realmInit.bootstrap(); } |
### Question:
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; }### Answer:
@Test public void testAllRolesCreated() throws Exception { assertTrue(roleInitializer.buildRoles("myRealmId") == 6); } |
### Question:
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); }### Answer:
@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)); }
@Test (expected = QueryParseException.class) public void testCheckFieldAccessEducator() { securityContextInjector.setEducatorContext(); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria("economicDisadvantaged", "=", "true")); service.checkFieldAccess(query, false); } |
### Question:
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); }### Answer:
@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)); }
@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)); } |
### Question:
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); }### Answer:
@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"))))); } |
### Question:
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); }### Answer:
@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]); } |
### Question:
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); }### Answer:
@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]); } |
### Question:
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; }### Answer:
@Test(expected = SelectorParseException.class) public void testUnbalancedParens() throws SelectorParseException { Selector2MapOfMaps.getMatchingClosingParenIndex("((", 0); }
@Test(expected = SelectorParseException.class) public void testUnbalancedParens2() throws SelectorParseException { Selector2MapOfMaps.getMatchingClosingParenIndex(")", 0); } |
### Question:
DefaultUsersService { public List<Dataset> getAvailableDatasets() { return datasets; } @PostConstruct void postConstruct(); List<Dataset> getAvailableDatasets(); List<DefaultUser> getUsers(String dataset); DefaultUser getUser(String dataset, String userId); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@Test public void testNonNullForNull() { assertTrue(QUERY_CONVERTER.convert(null) != null); }
@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); }
@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); }
@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); }
@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); }
@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); }
@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); }
@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); }
@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); }
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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())); } |
### Question:
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); }### Answer:
@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()); }
@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"); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
EntityRightsFilter { @SuppressWarnings("unchecked") protected void filterFields(EntityBody entityBody, Collection<GrantedAuthority> auths, String prefix, String entityType) { if (!auths.contains(Right.FULL_ACCESS)) { List<String> toRemove = new LinkedList<String>(); for (Iterator<Map.Entry<String, Object>> it = entityBody.entrySet().iterator(); it.hasNext();) { String fieldName = it.next().getKey(); Set<Right> neededRights = rightAccessValidator.getNeededRights(prefix + fieldName, entityType); if (!neededRights.isEmpty() && !rightAccessValidator.intersection(auths, neededRights)) { it.remove(); } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf,
Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn,
Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }### Answer:
@Test public void testFilterFields() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity student = createStudentEntity(EntityNames.STUDENT, STUDENT_ID); EntityBody sb = new EntityBody(student.getBody()); entityRightsFilter.filterFields(sb, auths, "", EntityNames.STUDENT); Assert.assertEquals(1, sb.size()); Assert.assertEquals(STUDENT_UNIQUE_STATE_ID, sb.get(ParameterConstants.STUDENT_UNIQUE_STATE_ID)); } |
### Question:
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf,
Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn,
Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }### Answer:
@Test public void testComplexFilterReadGeneral() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); EntityBody sb = new EntityBody(staff.getBody()); entityRightsFilter.complexFilter(sb, auths, EntityNames.STAFF); List<Map<String, Object>> telepone = (List<Map<String, Object>>) sb.get(TELEPONE_FEILD); List<Map<String, Object>> emails = (List<Map<String, Object>>) sb.get(EMAIL_FIELD); Assert.assertEquals(1, telepone.size()); Assert.assertEquals(1, emails.size()); Assert.assertEquals(WORK_PHONE, telepone.get(0).get(TELEPONE_VALUE)); Assert.assertEquals(WORK_EMAIL, emails.get(0).get(EMAIL_VALUE)); }
@Test public void testComplexFilterReadRestrict() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_RESTRICTED); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); EntityBody sb = new EntityBody(staff.getBody()); entityRightsFilter.complexFilter(sb, auths, EntityNames.STAFF); List<Map<String, Object>> telepone = (List<Map<String, Object>>) sb.get(TELEPONE_FEILD); List<Map<String, Object>> emails = (List<Map<String, Object>>) sb.get(EMAIL_FIELD); Assert.assertEquals(2, telepone.size()); Assert.assertEquals(2, emails.size()); } |
### Question:
EntityRightsFilter { public EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context) { Collection<GrantedAuthority> selfAuths; if (isSelf) { selfAuths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); } else { selfAuths = nonSelfAuths; } return makeEntityBody(entity, treamts, defn, nonSelfAuths, selfAuths); } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf,
Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn,
Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }### Answer:
@Test public void testMakeEntityBody() { Treatment treatment1 = Mockito.mock(Treatment.class); Treatment treatment2 = Mockito.mock(Treatment.class); List<Treatment> treatments = new ArrayList<Treatment>(); treatments.add(treatment1); treatments.add(treatment2); Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity student = createStudentEntity(EntityNames.STUDENT, STUDENT_ID); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); student.getEmbeddedData().put("studentSchoolAssociation", Arrays.asList(staff)); EntityBody sb = new EntityBody(student.getBody()); EntityBody staffBody = new EntityBody(staff.getBody()); Mockito.when(treatment1.toExposed(Matchers.any(EntityBody.class), Matchers.any(EntityDefinition.class), Matchers.any(Entity.class))).thenReturn(sb, staffBody); Mockito.when(treatment2.toExposed(Matchers.any(EntityBody.class), Matchers.any(EntityDefinition.class), Matchers.any(Entity.class))).thenReturn(sb, staffBody); EntityDefinition definition = Mockito.mock(EntityDefinition.class); Mockito.when(definition.getType()).thenReturn("student"); EntityBody res = entityRightsFilter.makeEntityBody(student, treatments, definition, false, auths, SecurityUtil.UserContext.STAFF_CONTEXT); Assert.assertNotNull(res); List<EntityBody> ssa = (List<EntityBody>) res.get("studentSchoolAssociation"); Assert.assertNotNull(ssa); Assert.assertEquals(1, ssa.size()); Assert.assertEquals(STAFF_ID, ssa.get(0).get(ParameterConstants.STAFF_UNIQUE_STATE_ID)); } |
### Question:
EdOrgContextualRoleBuilder { private Map<String, List<String>> buildEdOrgContextualRoles(Set<Entity> seoas, Set<String> samlRoleSet) { Map<String, List<String>> edOrgRoles = new HashMap<String, List<String>>(); if (seoas != null) { for (Entity seoa : seoas) { String edOrgId = (String) seoa.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE); String role = (String) seoa.getBody().get(ParameterConstants.STAFF_EDORG_ASSOC_STAFF_CLASSIFICATION); if(isValidRole(role, samlRoleSet)) { if (edOrgRoles.get(edOrgId) == null) { edOrgRoles.put(edOrgId, new ArrayList<String>()); edOrgRoles.get(edOrgId).add(role); } else if (!edOrgRoles.get(edOrgId).contains(role)) { edOrgRoles.get(edOrgId).add(role); } } } } return edOrgRoles; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }### Answer:
@Test public void testBuildEdOrgContextualRoles () { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "IT Admin")); seoas.add(createSEOA("LEA1", "Educator")); seoas.add(createSEOA("LEA2", "Educator")); seoas.add(createSEOA("LEA2", "Educator")); Set<Role> edOrg1RolesSet = new HashSet<Role>(); edOrg1RolesSet.add(createRole("Educator")); edOrg1RolesSet.add(createRole("IT Admin")); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("Educator", "IT Admin"), false)).thenReturn(edOrg1RolesSet); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("IT Admin", "Educator"), false)).thenReturn(edOrg1RolesSet); Set<Role> edOrg2RolesSet = new HashSet<Role>(); edOrg2RolesSet.add(createRole("Educator")); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("Educator"), false)).thenReturn(edOrg2RolesSet); Mockito.when(edorgHelper.locateNonExpiredSEOAs(staffId)).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId,tenant, samlRoles); Assert.assertNotNull(edOrgRoles); Assert.assertEquals(2,edOrgRoles.size()); List<String> edOrg1Roles = edOrgRoles.get("LEA1"); Assert.assertNotNull(edOrg1Roles); Assert.assertEquals(2, edOrg1Roles.size()); Assert.assertTrue(edOrg1Roles.contains("IT Admin")); Assert.assertTrue(edOrg1Roles.contains("Educator")); List<String> edOrg2Roles = edOrgRoles.get("LEA2"); Assert.assertNotNull(edOrg2Roles); Assert.assertEquals(1, edOrg2Roles.size()); Assert.assertTrue(edOrg2Roles.contains("Educator")); } |
### Question:
MutatedContainer { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MutatedContainer rhs = (MutatedContainer) obj; return new EqualsBuilder().append(path, rhs.path) .append(queryParameters, rhs.queryParameters) .append(headers, rhs.headers).isEquals(); } static MutatedContainer generate(String queryParameters,
String pathFormat, String... pathArgs); String getPath(); void setPath(String path); String getQueryParameters(); void setQueryParameters(String queryParameters); Map<String, String> getHeaders(); void setHeaders(Map<String, String> headers); boolean isModified(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testEquals() { MutatedContainer m1 = new MutatedContainer(); setParams(m1, "a", "b", null); MutatedContainer m2 = new MutatedContainer(); setParams(m2, "a", "b", null); Assert.assertTrue(m1.equals(m2)); setParams(m1, "a", "b", null); setParams(m2, "c", "b", null); Assert.assertFalse(m1.equals(m2)); setParams(m1, "a", "b", null); setParams(m2, "a", "c", null); Assert.assertFalse(m1.equals(m2)); setParams(m1, "a", "b", new HashMap<String, String>()); setParams(m2, "a", "b", new HashMap<String, String>()); Assert.assertTrue(m1.equals(m2)); setParams(m1, "a", "b", new HashMap<String, String>()); setParams(m2, "a", "b", null); Assert.assertFalse(m1.equals(m2)); HashMap<String, String> h1 = new HashMap<String, String>(); h1.put("1", "1"); HashMap<String, String> h2 = new HashMap<String, String>(); h2.put("1", "2"); setParams(m1, "a", "b", h1); setParams(m2, "a", "b", h2); Assert.assertFalse(m1.equals(m2)); h1 = new HashMap<String, String>(); h1.put("1", "1"); h2 = new HashMap<String, String>(); h2.put("1", "1"); setParams(m1, "a", "b", h1); setParams(m2, "a", "b", h2); Assert.assertTrue(m1.equals(m2)); } |
### Question:
RootSearchMutator { public String mutatePath(String version, String resource, String queryParameters) { String mutatedPath = null; Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String curParameter = parameterResourcePair.getLeft(); String curResource = parameterResourcePair.getRight(); if (parameters.containsKey(curParameter)) { if (isValidPath(version, curResource, resource)) { mutatedPath = "/" + curResource + "/" + parameters.get(curParameter) + "/" + resource; break; } } } return mutatedPath; } String mutatePath(String version, String resource, String queryParameters); }### Answer:
@Test public void testMutatePath() throws Exception { String expectedPath; String resultPath; resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "studentId=some_id"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "studentId=some_id&something=else"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "key1=val1&studentId=some_id&key2=val2"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.REPORT_CARDS, "schoolId=school_id&studentId=id1,id2,id3&key2=val2"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "id1,id2,id3" + "/" + ResourceNames.REPORT_CARDS; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.TEACHER_SECTION_ASSOCIATIONS, "schoolId=school_id"); expectedPath = null; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); } |
### Question:
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } void mutateURI(Authentication auth, ContainerRequest request); }### Answer:
@Test public void testGetResourceVersionForSearch() { List<PathSegment> segments = getPathSegmentList("v1/search"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/search"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/search"); assertEquals("Should match", "v1.0", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/search"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/search"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); }
@Test public void testGetResourceVersion() { List<PathSegment> segments = getPathSegmentList("v1/students"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/studentSectionAssociations/1234/students"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/students"); assertEquals("Should match", "v1.0", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/students"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/students"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/students"); when(mutated.getPath()).thenReturn(null); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); }
@Test public void testGetResourceVersionForPublicResources() { List<PathSegment> segments = getPathSegmentList("v1/assessments"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/search/assessments"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/assessments"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/assessments"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/assessments"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); } |
### Question:
EndpointMutator { public void mutateURI(Authentication auth, ContainerRequest request) { if (request.getMethod().equals(POST)) { return; } SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); String clientId = ((OAuth2Authentication) auth).getClientAuthentication().getClientId(); List<PathSegment> segments = sanitizePathSegments(request); String parameters = request.getRequestUri().getQuery(); if (segments.size() == 0) { throw new NotFoundException(); } if (usingVersionedApi(segments)) { if (!request.getProperties().containsKey(REQUESTED_PATH)) { request.getProperties().put(REQUESTED_PATH, request.getPath()); } MutatedContainer mutated = uriMutator.mutate(segments, parameters, user, clientId); if (mutated != null && mutated.isModified()) { String version = getResourceVersion(segments, mutated); if (mutated.getHeaders() != null) { InBoundHeaders headers = new InBoundHeaders(); headers.putAll(request.getRequestHeaders()); for (String key : mutated.getHeaders().keySet()) { headers.putSingle(key, mutated.getHeaders().get(key)); } request.setHeaders(headers); } if (mutated.getPath() != null) { if (mutated.getQueryParameters() != null && !mutated.getQueryParameters().isEmpty()) { LOG.info("URI Rewrite: {}?{} --> {}?{}", new Object[] { request.getPath(), parameters, mutated.getPath(), mutated.getQueryParameters() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()) .replaceQuery(mutated.getQueryParameters()).build()); } else { LOG.info("URI Rewrite: {} --> {}", new Object[] { request.getPath(), mutated.getPath() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()).build()); } } } } } void mutateURI(Authentication auth, ContainerRequest request); }### Answer:
@Test(expected = NotFoundException.class) public void testNoPathSegments() throws URISyntaxException { SLIPrincipal principle = mock(SLIPrincipal.class); ClientToken clientToken = mock(ClientToken.class); when(clientToken.getClientId()).thenReturn("theAppId"); OAuth2Authentication auth = mock(OAuth2Authentication.class); when(auth.getPrincipal()).thenReturn(principle); when(auth.getClientAuthentication()).thenReturn(clientToken); ContainerRequest request = mock(ContainerRequest.class); List<PathSegment> segments = Collections.emptyList(); when(request.getPathSegments()).thenReturn(segments); when(request.getMethod()).thenReturn("GET"); when(request.getRequestUri()).thenReturn(new URI("http: endpointMutator.mutateURI(auth, request); } |
### Question:
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } @Override Set<GrantedAuthority> resolveRolesIntersect(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<GrantedAuthority> resolveRolesUnion(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<Role> mapRoles(String tenantId, String realmId,
List<String> roleNames, boolean isAdminRealm); }### Answer:
@Test public void sandboxAdminBecomeDeveloperInDevRealm() { Set<Role> roles = resolver.mapRoles(null, DEVELOPER_REALM_ID, sandboxRole, false); assertTrue("sandbox admin is not mapped to developer in developer realm", roles.containsAll(defaultRoles.findAdminRoles(appAndProdLoginUser))); assertTrue("sandbox admin is not only mapped to developer in developer realm", defaultRoles.findAdminRoles(appAndProdLoginUser).containsAll(roles)); }
@Test public void sandboxAdminstaysSandboxAdminInAdminRealm() { Set<Role> roles = resolver.mapRoles(null, ADMIN_REALM_ID, sandboxRole, true); assertTrue("sandbox admin is changed in admin realm", roles.containsAll(defaultRoles.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.SANDBOX_ADMINISTRATOR)))); assertTrue("sandbox admin is only mapped to sandbox admin in admin realm", defaultRoles.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.SANDBOX_ADMINISTRATOR)).containsAll(roles)); }
@Test public void roleWithoutProdLoginIsChangedToEmptyGroupInDevRealm() { Set<Role> roles = resolver.mapRoles(null, DEVELOPER_REALM_ID, otherRole, false); assertTrue("other admin is not mapped to developer in developer realm", roles.isEmpty()); } |
### Question:
SecurityCriteria { public NeutralQuery applySecurityCriteria(NeutralQuery query) { if (securityCriteria != null) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); if (EntityNames.TEACHER.equals(user.getEntity().getType())) { List<String> ids = (List) securityCriteria.getValue(); if (ids.size() > inClauseSize) { throw new ResponseTooLargeException(); } } query.addOrQuery(new NeutralQuery(securityCriteria)); } return query; } String getCollectionName(); void setCollectionName(String collectionName); NeutralCriteria getSecurityCriteria(); void setSecurityCriteria(NeutralCriteria securityCriteria); NeutralQuery applySecurityCriteria(NeutralQuery query); void setInClauseSize(Long size); }### Answer:
@Test public void testApplySecurityCriteria() { injector.setAccessAllAdminContext(); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setSecurityCriteria(new NeutralCriteria("key", "in", "value")); NeutralQuery query = new NeutralQuery(); query = securityCriteria.applySecurityCriteria(query); assertEquals("Should match", 1, query.getOrQueries().size()); } |
### Question:
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }### Answer:
@Test public void testGetArtifactUrl() { setRealm(VALID_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); }
@Test(expected = APIAccessDeniedException.class) public void testGetArtifactUrlIncorrectSourceId() { setRealm(INCORRECT_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); }
@Test(expected = IllegalArgumentException.class) public void testGetArtifactUrlInvalidSourceIdFormat() { setRealm(NOT_HEX_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); } |
### Question:
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); static final String STR_0X38; }### Answer:
@Test public void testEnsureIndexes() { String result = MongoCommander.ensureIndexes("mongoTestIndexes.txt", dbName, mockedMongoTemplate); assertNull(result); for (String collection : shardCollections) { DBObject asskeys = new BasicDBObject(); asskeys.put("creationTime", 1); DBObject options = buildOpts(dbName + "." + collection, collectionOrder.get(collection)); Mockito.verify(collectionIns.get(collection), Mockito.times(1)).createIndex(asskeys, options); } }
@Test public void testEnsureSetIndexes() { String result = MongoCommander.ensureIndexes(indexes, dbName, mockedMongoTemplate); assertNull(result); for (String collection : shardCollections) { DBObject asskeys = new BasicDBObject(); asskeys.put("creationTime", 1); DBObject options = buildOpts(dbName + "." + collection, collectionOrder.get(collection)); Mockito.verify(collectionIns.get(collection), Mockito.times(1)).createIndex(asskeys, options); } } |
### Question:
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }### Answer:
@Test public void testInlineDecryption() { Resource inlineAssertionResource = new ClassPathResource("saml/inlineEncryptedAssertion.xml"); EncryptedAssertion encAssertion = createAssertion(inlineAssertionResource); Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry); verifyAssertion(assertion); }
@Test public void testPeerDecryption() { Resource peerAssertionResource = new ClassPathResource("saml/peerEncryptedAssertion.xml"); EncryptedAssertion encAssertion = createAssertion(peerAssertionResource); Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry); verifyAssertion(assertion); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.