src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ResourceUtil { public static String getApiVersion(final UriInfo uriInfo) { if (uriInfo != null) { String uriPath = uriInfo.getPath(); if (uriPath != null) { int indexOfSlash = uriPath.indexOf("/"); if (indexOfSlash >= 0) { String version = uriPath.substring(0, indexOfSlash); return version; } else { return uriPath; } }...
@Test public void testGetApiVersionSolo() { String version = "foo"; String uriPath = version + "/bar"; UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getPath()).thenReturn(uriPath); assertTrue(ResourceUtil.getApiVersion(uriInfo).equals(version)); } @Test public void testGetApiVersionNothingElse() { String version ...
ResourceUtil { public static EmbeddedLink getSelfLinkForEntity(final UriInfo uriInfo, final String entityId, final EntityDefinition defn) { return new EmbeddedLink(ResourceConstants.SELF, getURI(uriInfo, getApiVersion(uriInfo), PathConstants.TEMP_MAP.get(defn.getResourceName()), entityId).toString()); } static String ...
@Test public void testGetApiVersionLinked() { String version = "bar"; String uriPath = version + "/foo"; UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getPath()).thenReturn(uriPath); when(uriInfo.getBaseUriBuilder()).thenReturn(this.createUriBuilder()); EntityDefinition defn = mock(EntityDefinition.class); String...
InProcessDateQueryEvaluator { public boolean entitySatisfiesDateQuery(EntityBody entity, NeutralQuery query) { for (NeutralCriteria andCriteria : query.getCriteria()) { String fieldName = andCriteria.getKey(); String operator = andCriteria.getOperator(); if (NeutralCriteria.CRITERIA_EXISTS.equals(operator)) { boolean s...
@Test public void shouldVerifyMissingFieldReturnsFalse() { EntityBody entity = new EntityBody(); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria("foo", NeutralCriteria.CRITERIA_EXISTS, true)); boolean result = eval.entitySatisfiesDateQuery(entity, query); Assert.assertEquals("Should match...
IdFieldEmittableKey extends EmittableKey { public Text getIdField() { return super.getFieldName(); } IdFieldEmittableKey(); IdFieldEmittableKey(final String mongoFieldName); Text getIdField(); Text getId(); void setId(final Text value); @Override void readFields(DataInput data); @Override void write(DataOutput data); ...
@Test public void testGetIdField() { IdFieldEmittableKey key = new IdFieldEmittableKey("test.id.key.field"); assertEquals(key.getIdField().toString(), "test.id.key.field"); }
SecuritySessionResource { @GET @Path("check") public Object sessionCheck() { final Map<String, Object> sessionDetails = new TreeMap<String, Object>(); if (isAuthenticated(SecurityContextHolder.getContext())) { sessionDetails.put("authenticated", true); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getCo...
@Test public void testSessionEmails() throws Exception { buildWithEmailType(Arrays.asList("Work")); Map<String, Object> response = (Map<String, Object>) resource.sessionCheck(); assertEquals("Work@Work.com", response.get("email")); buildWithEmailType(Arrays.asList("Organization")); response = (Map<String, Object>) reso...
RealmResource { @PUT @Path("{realmId}") @Consumes("application/json") @RightsAllowed({ Right.CRUD_REALM }) public Response updateRealm(@PathParam("realmId") String realmId, EntityBody updatedRealm, @Context final UriInfo uriInfo) { if (updatedRealm == null) { throw new IllegalArgumentException("Updated Realm was null")...
@Test public void testAddClientRole() throws Exception { try { resource.updateRealm("-1", null, null); assertFalse(false); } catch (IllegalArgumentException e) { assertTrue(true); } UriInfo uriInfo = ResourceTestUtil.buildMockUriInfo(""); Response res = resource.updateRealm("1234", mapping, uriInfo); Assert.assertEqual...
RealmResource { protected Response validateArtifactResolution(String artifactResolutionEndpoint, String sourceId) { if (artifactResolutionEndpoint == null && sourceId == null) { return null; } Map<String, String> res = new HashMap<String, String>(); if (artifactResolutionEndpoint != null && sourceId != null) { if ((art...
@Test public void testvalidateArtifactResolution() { Response res = resource.validateArtifactResolution(null, null); Assert.assertNull(res); res = resource.validateArtifactResolution("", ""); Assert.assertNull(res); res = resource.validateArtifactResolution("testEndpoint", "ccf4f3895f6e37896e7511ed1d991b1d96f04ac1"); A...
RealmResource { @GET @Path("{realmId}") @RightsAllowed({ Right.ADMIN_ACCESS }) public Response readRealm(@PathParam("realmId") String realmId) { EntityBody result = service.get(realmId); return Response.ok(result).build(); } @PostConstruct void init(); void setService(EntityService service); @PUT @Path("{realmId}") @C...
@Test public void testGetMappingsFound() throws Exception { Response res = resource.readRealm("1234"); Assert.assertEquals(Response.Status.OK.getStatusCode(), res.getStatus()); Assert.assertNotNull(res.getEntity()); } @Test public void testGetMappingsNotFound() throws Exception { Response res = resource.readRealm("-1")...
SamlFederationResource { @GET @Path("metadata") @Produces({ "text/xml" }) public Response getMetadata() { if (!metadata.isEmpty()) { return Response.ok(metadata).build(); } return Response.status(Response.Status.NOT_FOUND).build(); } @GET @Path("metadata") @Produces({ "text/xml" }) Response getMetadata(); @POST @Path(...
@SuppressWarnings("unchecked") @Test public void getMetadataTest() { Response response = resource.getMetadata(); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Exception exception = null; try { DocumentBuilderFactory dbf ...
SamlFederationResource { @GET @Path("sso/artifact") public Response processArtifactBinding(@Context HttpServletRequest request, @Context UriInfo uriInfo) { String artifact = request.getParameter("SAMLart"); String realmId = request.getParameter("RelayState"); if (artifact == null) { throw new APIAccessDeniedException("...
@Test (expected= APIAccessDeniedException.class) public void processArtifactBindingInvalidRequest() { setRealm(false); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); UriInfo uriInfo = Mockito.mock(UriInfo.class); Mockito.when(request.getParameter("RelayState")).thenReturn("My Realm"); resource.pro...
CustomRoleResource { @POST @RightsAllowed({Right.CRUD_ROLE }) public Response createCustomRole(EntityBody newCustomRole, @Context final UriInfo uriInfo) { String realmId = (String) newCustomRole.get("realmId"); Response res = validateRights(newCustomRole); if (res != null) { auditSecEvent(uriInfo, "Failed to create cus...
@Test public void testValidCreate() throws URISyntaxException { setRealms(REALM_ID); EntityBody body = getValidRoleDoc(); mockGetRealmId(); Mockito.when(service.create(body)).thenReturn("new-role-id"); Response res = resource.createCustomRole(body, getMockUriInfo()); Assert.assertEquals(201, res.getStatus()); } @Test p...
IdFieldEmittableKey extends EmittableKey { @Override public String toString() { return "IdFieldEmittableKey [" + getIdField() + "=" + getId().toString() + "]"; } IdFieldEmittableKey(); IdFieldEmittableKey(final String mongoFieldName); Text getIdField(); Text getId(); void setId(final Text value); @Override void readFi...
@Test public void testToString() { IdFieldEmittableKey key = new IdFieldEmittableKey("test.id.key.field"); key.setId(new Text("1234")); assertEquals(key.toString(), "IdFieldEmittableKey [test.id.key.field=1234]"); }
CustomRoleResource { @PUT @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) public Response updateCustomRole(@PathParam("id") String id, EntityBody updated, @Context final UriInfo uriInfo) { Response res = validateRights(updated); if (res != null) { auditSecEvent(uriInfo, "Failed to create custom role rights validation ...
@Test public void testValidUpdate() { setRealms(REALM_ID); EntityBody body = getValidRoleDoc(); mockGetRealmId(); String id = "old-id"; Mockito.when(service.get(id)).thenReturn((EntityBody) body.clone()); body.put("roles", new ArrayList<Map<String, List<String>>>()); Mockito.when(service.update(id, body, false)).thenRe...
CustomRoleResource { @GET @RightsAllowed({Right.CRUD_ROLE }) public Response readAll(@Context final UriInfo uriInfo, @DefaultValue("") @QueryParam("realmId") String realmId) { if (uriInfo.getQueryParameters() != null) { String defaultsOnly = uriInfo.getQueryParameters().getFirst("defaultsOnly"); if (defaultsOnly != nul...
@Test public void testReadAll() { setRealms(REALM_ID); EntityBody body = getValidRoleDoc(); String id = "old-id"; Mockito.when(service.get(id)).thenReturn((EntityBody) body.clone()); mockGetRealmId(); Entity mockEntity = Mockito.mock(Entity.class); Mockito.when(mockEntity.getEntityId()).thenReturn("mock-id"); Mockito.w...
CustomRoleResource { @GET @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) public Response read(@PathParam("id") String id, @Context final UriInfo uriInfo) { EntityBody customRole = service.get(id); String realmId = (String)customRole.get("realmId"); if (!realmHelper.getAssociatedRealmIds().contains(realmId)) { auditSe...
@Test public void testReadAccessible() { setRealms(REALM_ID); EntityBody body = getValidRoleDoc(); String id = "old-id"; Mockito.when(service.get(id)).thenReturn((EntityBody) body.clone()); mockGetRealmId(); Response res = resource.read(id, uriInfo); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(body, ...
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(fina...
@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 =...
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(); } Res...
@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>(); req...
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 (a...
@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); }...
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...
@Test(expected = APIAccessDeniedException.class) public void testGetDelegationsNoEdOrg() throws Exception { securityContextInjector.setLeaAdminContext(); resource.getDelegations(); } @Test public void testGetDelegationsBadRole() throws Exception { securityContextInjector.setEducatorContext(); Assert.assertEquals(Respon...
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(); vo...
@Test public void testGetTenantIdField() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); assertEquals(key.getTenantIdField().toString(), "meta.data.tenantId"); }
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(); } @...
@Test public void testGetSingleDelegation() throws Exception { securityContextInjector.setLeaAdminContext(); ((SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).setEdOrg("1234"); ((SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).setEdOrgId("1234");...
ApplicationResource extends UnversionedResource { @POST @Override @RightsAllowed({ Right.DEV_APP_CRUD }) public Response post(EntityBody newApp, @Context final UriInfo uriInfo) { if (newApp.containsKey(CLIENT_SECRET) || newApp.containsKey(CLIENT_ID) || newApp.containsKey("id")) { EntityBody body = new EntityBody(); bod...
@SuppressWarnings("rawtypes") @Test public void testGoodCreate() throws URISyntaxException { when(uriInfo.getRequestUri()).thenReturn(new URI("http: EntityBody app = getNewApp(); Response resp = resource.post(app, uriInfo); assertEquals(STATUS_CREATED, resp.getStatus()); assertTrue("Client id set", app.get(CLIENT_ID).t...
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 ...
@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); }
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); fil...
@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 = "9999...
ArtifactBindingHelper { protected ArtifactResolve generateArtifactResolveRequest(String artifactString, KeyStore.PrivateKeyEntry pkEntry, String idpUrl) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Artifact artifact = (Artifact) xmlObjectBuilderFactory.getBuilder(Artifact.DEFAU...
@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())...
ArtifactBindingHelper { protected Envelope generateSOAPEnvelope(ArtifactResolve artifactResolutionRequest) { XMLObjectBuilderFactory xmlObjectBuilderFactory = Configuration.getBuilderFactory(); Envelope envelope = (Envelope) xmlObjectBuilderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_...
@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_ELEMEN...
ApplicationAuthorizationResource { @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); EntityBody appAuth = getAppAuth(appId); if (appAuth =...
@Test public void testGetAuthForNonExistingAppAndNonExistingAuth() { ResponseImpl resp = (ResponseImpl) res.getAuthorization("someAppId", null); Assert.assertEquals(404, resp.getStatus()); } @Test public void testGetAuthForNonExistingAppAndExistingAuth() { Map<String, Object> auth = new HashMap<String, Object>(); auth....
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(f...
@Test public void testGetIdField() { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey("meta.data.tenantId", "test.id.key.field"); assertEquals(key.getIdField().toString(), "test.id.key.field"); }
ApplicationAuthorizationResource { @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) public Response getAuthorizations(@QueryParam("edorg") String edorg) { Set<String> myEdorgs = validateEdOrg(edorg); Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); SLIPrincipal principal = (SLIPrincipal) SecurityC...
@Test public void testGetAuths() { Map<String, Object> appBody = new HashMap<String, Object>(); Entity app = repo.create("application", appBody); Map<String, Object> auth = new HashMap<String, Object>(); auth.put("applicationId", app.getEntityId()); auth.put("edorgs", getAuthList(SecurityUtil.getEdOrgId())); repo.creat...
SecurityEventResource extends UnversionedResource { @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) public Response getAll(@Context final UriInfo uriInfo) { return getAllResponseBuilder.build(uriInfo, getOnePartTemplate(), ResourceMethod.GET, new GetResourceLogic() { @Override public ServiceResponse run(Re...
@Test public void testSLCOperatorOffsetGetSecurityEvents() throws URISyntaxException { injector.setOperatorContext(); URI mockUri = new URI("/rest/securityEvent?limit=100&offset=3"); when(uriInfo.getRequestUri()).thenReturn(mockUri); Response response = resource.getAll(uriInfo); Object responseEntityObj = null; if (res...
TenantAndIdEmittableKey extends EmittableKey { @Override public String toString() { return "TenantAndIdEmittableKey [" + getIdField() + "=" + getId().toString() + ", " + getTenantIdField() + "=" + getTenantId().toString() + "]"; } TenantAndIdEmittableKey(); TenantAndIdEmittableKey(final String tenantIdFieldName, final...
@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]"); }
UserResource { @POST @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response create(final User newUser) { Response result = validateUserCreate(newUser, secUtil.getTenantId()); if (result != null) { return res...
@Test public void testCreate() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); User newUser = new User(); newUser.setGroups(Arrays.asList(R...
UserResource { @PUT @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response update(final User updateUser) { Response result = validateUserUpdate(updateUser, secUtil.getTenantId()); if (result != null) { retur...
@Test public void testUpdate() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn(UUID1); User newUs...
UserResource { @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 }) public final Response delete(@PathParam("uid") final String uid) { Response result = validateUserDelete(uid, secUtil.getTenantId()); if ...
@Test public void testDelete() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn(UUID1); User newUs...
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); @O...
@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); assertFals...
UserResource { @GET @RightsAllowed({Right.CRUD_LEA_ADMIN, Right.CRUD_SEA_ADMIN, Right.CRUD_SLC_OPERATOR, Right.CRUD_SANDBOX_ADMIN, Right.CRUD_SANDBOX_SLC_OPERATOR }) public final Response readAll() { String tenant = secUtil.getTenantId(); String edorg = secUtil.getEdOrg(); Response result = validateAdminRights(secUtil....
@SuppressWarnings("unchecked") @Test public void testReadAll() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid(...
UserResource { @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 }) public final Response getEdOrgs() { String tenant = secUtil.getTenantId(); Response result = validateAdminRights(secUtil.getAllRights(), t...
@Test public void testGetEdOrgs() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.hasRole(RoleInitializer.LEA_ADMINIST...
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_SL...
@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(resou...
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")...
@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.asLis...
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.config...
@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, n...
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; } r...
@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)); }
StAXMsgBodyReader { public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } } EntityBody deserial...
@Test public void testValues() { final String xmlValues = "<test><k1>v1</k1><k2>v2</k2></test>"; EntityBody body = null; try { body = deserialize(xmlValues); } catch (XMLStreamException e) { fail(e.getMessage()); } assertNotNull(body); assertEquals("v1", body.get("k1")); assertEquals("v2", body.get("k2")); } @Test publ...
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 = ...
@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 ByteArrayInp...
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 {...
@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", ...
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 wh...
@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); }
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 isWriteabl...
@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)); }
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 Res...
@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, s...
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, UriIn...
@Test public void testGetPath() { assertTrue(new ChangedUriInfo("/rest/foo/bar", null).getPath().equals("foo/bar")); }
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 Ent...
@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...
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) ?...
@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()); asse...
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.CR...
@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.siz...
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 ); ...
@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"); }
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()) { entity...
@Test public void testCreate() { String id = resourceService.postEntity(resource, new EntityBody(createTestEntity())); assertNotNull("ID should not be null", id); }
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...
@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 Res...
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.getL...
@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(resour...
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.get...
@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()); }
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 ...
@Test public void testGet() throws URISyntaxException { String learningStandardId = resourceService.postEntity(learningStandards, createLearningStandardEntity()); String assessmentId = resourceService.postEntity(assessments, createAssessmentEntity(learningStandardId)); setupMocks(BASE_URI + "/" + assessmentId + "/learn...
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> ge...
@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"...
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/" + ...
@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 = ...
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.getName...
@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\"...
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); j...
@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"); }
MethodNotAllowedException extends RuntimeException { public Set<String> getAllowedMethods() { return allowedMethods; } MethodNotAllowedException(Set<String> allowedMethods); Set<String> getAllowedMethods(); }
@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")); }
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 R...
@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, s...
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(...
@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("...
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....
@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.clas...
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 resourceSer...
@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()); }
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....
@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"); }
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, Re...
@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(r...
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 pu...
@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 ...
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 defaultResp...
@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...
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 default...
@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.getStatusC...
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, tw...
@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...
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.get...
@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); }
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 @Pa...
@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...
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 (queryPar...
@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); ...
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, "."...
@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.PAR...
OptionalFieldAppenderFactory { public OptionalFieldAppender getOptionalFieldAppender(String type) { return generators.get(type); } OptionalFieldAppender getOptionalFieldAppender(String type); static final String APPENDER_PREFIX; static final String PARAM_PREFIX; }
@Test public void testGetViewGenerator() { assertTrue("Should be of type studentassessment", factory.getOptionalFieldAppender(ResourceNames.SECTIONS + "_" + ParameterConstants.OPTIONAL_FIELD_ASSESSMENTS) instanceof StudentAssessmentOptionalFieldAppender); assertTrue("Should be of type studentgradebook", factory.getOpti...
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 re...
@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(...
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))) { result...
@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.getEn...
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> qu...
@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 c...
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 assoc...
@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 ...
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...
@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, e...
StudentAllAttendanceOptionalFieldAppender implements OptionalFieldAppender { @SuppressWarnings("unchecked") @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); NeutralQuery neutralQuery = ne...
@SuppressWarnings("unchecked") @Test public void testApplyOptionalField() { setupMockForApplyOptionalField(); List<EntityBody> entities = new ArrayList<EntityBody>(); entities.add(makeEntityBody(student1Entity)); entities.add(makeEntityBody(student2Entity)); entities = studentAllAttendanceOptionalFieldAppender.applyOpt...
StudentAssessmentOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentAssessments = optionalFieldAppenderHelpe...
@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>...
StudentTranscriptOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSectionAssociations = optionalFieldAppen...
@Test public void testApplyOptionalField() { List<EntityBody> entities = new ArrayList<EntityBody>(); EntityBody body = new EntityBody(); body.putAll(studentEntity.getBody()); body.put("id", studentEntity.getEntityId()); entities.add(body); entities = studentTranscriptOptionalFieldAppender.applyOptionalField(entities, ...
StudentGradeLevelOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSchoolAssociationList = optionalFieldApp...
@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("Sh...
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.sta...
@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 = r...
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(); } C...
@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); }
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 = Resourc...
@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(uri...
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 EntityDefi...
@Test public void testDelete() { Response res = resource.delete(); assertNotNull(res); assertEquals(Status.NO_CONTENT.getStatusCode(), res.getStatus()); Mockito.verify(service).deleteCustom("TEST-ID"); }
SimpleURLValidator implements URLValidator { @Override public boolean validate(URI url) { String[] schemes = {"http", "https"}; UrlValidator validator = new UrlValidator(schemes); return validator.isValid(url.toString()); } @Override boolean validate(URI url); }
@Test public void 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...
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 : validationSt...
@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(...
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"); Sorte...
@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.getPathSe...
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 ){ validat...
@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...
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 findD...
@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("D...
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 = sessionRangeCal...
@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 ...
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 = entityDefinitionSto...
@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(an...
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.war...
@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(Invocat...
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.real...
@Test(expected = IllegalArgumentException.class) public void testProdModeNoProps() { realmInit.bootstrap(); }
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("role...
@Test public void testAllRolesCreated() throws Exception { assertTrue(roleInitializer.buildRoles("myRealmId") == 6); }