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; } } } return null; } static String getApiVersion(final UriInfo uriInfo); @Deprecated static List<EmbeddedLink> getSelfLink(final UriInfo uriInfo, final String userId, final EntityDefinition defn); static EmbeddedLink getSelfLinkForEntity(final UriInfo uriInfo, final String entityId,
final EntityDefinition defn); static EmbeddedLink getCustomLink(final UriInfo uriInfo, final String entityId, final EntityDefinition defn); @Deprecated static List<EmbeddedLink> getAssociationsLinks(final EntityDefinitionStore entityDefs,
final EntityDefinition defn, final String id, final UriInfo uriInfo); static List<EmbeddedLink> getLinks(final EntityDefinitionStore entityDefs, final EntityDefinition defn,
final EntityBody entityBody, final UriInfo uriInfo); static List<EmbeddedLink> getAggregateLink(final UriInfo uriInfo); static void putValue(MultivaluedMap<String, String> queryParameters, String key, String value); static void putValue(MultivaluedMap<String, String> queryParameters, String key, int value); static Map<String, String> convertToMap(Map<String, List<String>> map); static URI getURI(UriInfo uriInfo, String... paths); static String getVersionedUriString(UriInfo uriInfo, String... paths); static SLIPrincipal getSLIPrincipalFromSecurityContext(); static String getLinkName(String resourceName, String referenceName, String referenceField,
boolean isReferenceEntity); }
|
@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 = "foo"; UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getPath()).thenReturn(version); assertTrue(ResourceUtil.getApiVersion(uriInfo).equals(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 getApiVersion(final UriInfo uriInfo); @Deprecated static List<EmbeddedLink> getSelfLink(final UriInfo uriInfo, final String userId, final EntityDefinition defn); static EmbeddedLink getSelfLinkForEntity(final UriInfo uriInfo, final String entityId,
final EntityDefinition defn); static EmbeddedLink getCustomLink(final UriInfo uriInfo, final String entityId, final EntityDefinition defn); @Deprecated static List<EmbeddedLink> getAssociationsLinks(final EntityDefinitionStore entityDefs,
final EntityDefinition defn, final String id, final UriInfo uriInfo); static List<EmbeddedLink> getLinks(final EntityDefinitionStore entityDefs, final EntityDefinition defn,
final EntityBody entityBody, final UriInfo uriInfo); static List<EmbeddedLink> getAggregateLink(final UriInfo uriInfo); static void putValue(MultivaluedMap<String, String> queryParameters, String key, String value); static void putValue(MultivaluedMap<String, String> queryParameters, String key, int value); static Map<String, String> convertToMap(Map<String, List<String>> map); static URI getURI(UriInfo uriInfo, String... paths); static String getVersionedUriString(UriInfo uriInfo, String... paths); static SLIPrincipal getSLIPrincipalFromSecurityContext(); static String getLinkName(String resourceName, String referenceName, String referenceField,
boolean isReferenceEntity); }
|
@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 resourceName = "baz"; when(defn.getResourceName()).thenReturn(resourceName); String entityId = "entityId"; PathConstants.TEMP_MAP.put(resourceName, resourceName); EmbeddedLink embeddedLink = ResourceUtil.getSelfLinkForEntity(uriInfo, entityId, defn); String href = embeddedLink.getHref(); assertTrue(href.contains(version + "/" + resourceName + "/" + entityId)); }
|
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 shouldExist = (Boolean) andCriteria.getValue(); Object actualValue = entity.get(fieldName); if (shouldExist && actualValue == null) { return false; } else if (!shouldExist && actualValue != null) { return false; } } else { String fieldValue = (String) entity.get(fieldName); if (fieldValue == null) { return false; } String expectedValue = (String) andCriteria.getValue(); int comparison = fieldValue.compareTo(expectedValue); if (NeutralCriteria.CRITERIA_LT.equals(operator)) { if (comparison >= 0) { return false; } } else if (NeutralCriteria.CRITERIA_LTE.equals(operator)) { if (comparison > 0) { return false; } } else if (NeutralCriteria.CRITERIA_GT.equals(operator)) { if (comparison <= 0) { return false; } } else if (NeutralCriteria.CRITERIA_GTE.equals(operator)) { if (comparison < 0) { return false; } } } } if (query.getOrQueries().size() > 0) { for (NeutralQuery orQuery : query.getOrQueries()) { if (entitySatisfiesDateQuery(entity, orQuery)) { return true; } } return false; } else { return true; } } boolean entitySatisfiesDateQuery(EntityBody entity, NeutralQuery query); }
|
@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", false, result); }
@Test public void shouldVerifyOrQueryReturnsFalse(){ EntityBody entity = new EntityBody(); entity.put("date", "2005"); NeutralQuery query = new NeutralQuery(); query.addOrQuery(createQuery(new NeutralCriteria("date",NeutralCriteria.CRITERIA_GT,"2007"))); boolean result = eval.entitySatisfiesDateQuery(entity, query); Assert.assertEquals("Should match", false, result); }
@Test public void shouldVerifyOrQueryReturnsTrue(){ EntityBody entity = new EntityBody(); entity.put("date", "2005"); NeutralQuery query = new NeutralQuery(); query.addOrQuery(createQuery(new NeutralCriteria("date",NeutralCriteria.CRITERIA_GT,"2007"))); query.addOrQuery(createQuery(new NeutralCriteria("date",NeutralCriteria.CRITERIA_GT,"2001"))); boolean result = eval.entitySatisfiesDateQuery(entity, query); Assert.assertEquals("Should match", true, result); }
|
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); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
|
@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.getContext().getAuthentication() .getPrincipal(); sessionDetails.put("user_id", principal.getId()); sessionDetails.put("full_name", principal.getName()); sessionDetails.put("granted_authorities", principal.getRoles()); sessionDetails.put("realm", principal.getRealm()); sessionDetails.put("edOrg", principal.getEdOrg()); sessionDetails.put("edOrgId", principal.getEdOrgId()); sessionDetails.put("sliRoles", principal.getRoles()); sessionDetails.put("tenantId", principal.getTenantId()); sessionDetails.put("external_id", principal.getExternalId()); sessionDetails.put("email", getUserEmail(principal)); sessionDetails.put("rights", SecurityContextHolder.getContext().getAuthentication().getAuthorities()); sessionDetails.put("selfRights", principal.getSelfRights()); sessionDetails.put("adminRealmAuthenticated", principal.isAdminRealmAuthenticated()); sessionDetails.put("isAdminUser", principal.isAdminUser()); sessionDetails.put("userType", principal.getEntity().getType()); sessionDetails.put("edOrgRoles", principal.getEdOrgRoles()); sessionDetails.put("edOrgRights", principal.getEdOrgRights()); if (principal.getFirstName() != null) { sessionDetails.put("first_name", principal.getFirstName()); } if (principal.getLastName() != null) { sessionDetails.put("last_name", principal.getLastName()); } if (principal.getVendor() != null) { sessionDetails.put("vendor", principal.getVendor()); } } else { sessionDetails.put("authenticated", false); sessionDetails.put("redirect_user", realmPage); } return sessionDetails; } @GET @Path("logout") Map<String, Object> logoutUser(@Context HttpHeaders headers, @Context UriInfo uriInfo); @GET @Path("debug") SecurityContext sessionDebug(); @GET @Path("check") Object sessionCheck(); }
|
@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>) resource.sessionCheck(); assertEquals("Organization@Organization.com", response.get("email")); buildWithEmailType(Arrays.asList("Organization", "Work", "Other")); response = (Map<String, Object>) resource.sessionCheck(); assertEquals("Work@Work.com", response.get("email")); buildWithEmailType(Arrays.asList("Organization", "Other")); response = (Map<String, Object>) resource.sessionCheck(); assertEquals("Organization@Organization.com", response.get("email")); EntityBody body = new EntityBody(); body.put("name", new ArrayList<String>()); Entity e = Mockito.mock(Entity.class); Mockito.when(e.getBody()).thenReturn(body); injector.setCustomContext("MerpTest", "Merp Test", "IL", Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR), e, "merpmerpmerp"); response = (Map<String, Object>) resource.sessionCheck(); assertNull(response.get("email")); }
|
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"); } EntityBody oldRealm = service.get(realmId); if (!canEditCurrentRealm(updatedRealm) || oldRealm.get(ED_ORG) != null && !oldRealm.get(ED_ORG).equals(SecurityUtil.getEdOrg())) { EntityBody body = new EntityBody(); body.put(RESPONSE, "You are not authorized to update this realm."); return Response.status(Status.FORBIDDEN).entity(body).build(); } Response validateUniqueness = validateUniqueId(realmId, (String) updatedRealm.get(UNIQUE_IDENTIFIER), (String) updatedRealm.get(NAME), getIdpId(updatedRealm)); if (validateUniqueness != null) { return validateUniqueness; } Map<String, Object> idp = (Map<String, Object>) updatedRealm.get(IDP); Response validateArtifactResolution = validateArtifactResolution((String) idp.get(ARTIFACT_RESOLUTION_ENDPOINT), (String) idp.get(SOURCE_ID)); if (validateArtifactResolution != null) { LOG.debug("Invalid artifact resolution information"); return validateArtifactResolution; } updatedRealm.put("tenantId", SecurityUtil.getTenantId()); updatedRealm.put(ED_ORG, SecurityUtil.getEdOrg()); if (service.update(realmId, updatedRealm, false)) { logSecurityEvent(uriInfo, oldRealm, updatedRealm); return Response.status(Status.NO_CONTENT).build(); } return Response.status(Status.BAD_REQUEST).build(); } @PostConstruct void init(); void setService(EntityService service); @PUT @Path("{realmId}") @Consumes("application/json") @RightsAllowed({ Right.CRUD_REALM }) Response updateRealm(@PathParam("realmId") String realmId, EntityBody updatedRealm,
@Context final UriInfo uriInfo); @DELETE @Path("{realmId}") @RightsAllowed({ Right.CRUD_REALM }) Response deleteRealm(@PathParam("realmId") String realmId, @Context final UriInfo uriInfo); @POST @RightsAllowed({ Right.CRUD_REALM }) Response createRealm(EntityBody newRealm, @Context final UriInfo uriInfo); @GET @Path("{realmId}") @RightsAllowed({ Right.ADMIN_ACCESS }) Response readRealm(@PathParam("realmId") String realmId); @GET @RightsAllowed({ Right.ADMIN_ACCESS }) Response getRealms(@QueryParam(REALM) @DefaultValue("") String realm, @Context UriInfo info); static final String REALM; static final String ED_ORG; static final String RESPONSE; static final String NAME; static final String UNIQUE_IDENTIFIER; static final String IDP_ID; static final String ARTIFACT_RESOLUTION_ENDPOINT; static final String SOURCE_ID; static final String IDP; }
|
@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.assertEquals(Status.BAD_REQUEST.getStatusCode(), res.getStatus()); idp.put(RealmResource.SOURCE_ID, "ccf4f3895f6e37896e7511ed1d991b1d96f04ac1"); res = resource.updateRealm("1234", mapping, uriInfo); Assert.assertEquals(204, res.getStatus()); idp.remove(RealmResource.SOURCE_ID); }
@Test public void testUpdateOtherEdOrgRealm() { EntityBody temp = new EntityBody(); temp.put("foo", "foo"); UriInfo uriInfo = null; Response res = resource.updateRealm("other-realm", temp, uriInfo); Assert.assertEquals(403, res.getStatus()); }
|
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 ((artifactResolutionEndpoint.isEmpty() && sourceId.isEmpty()) || (sourceId.length() == SOURCEID_LENGTH && !artifactResolutionEndpoint.isEmpty())) { return null; } else { res.put(RESPONSE, "Source id needs to be 40 characters long"); } } else { res.put(RESPONSE, "artifactResolutionEndpoint and sourceId need to be present together."); } return Response.status(Status.BAD_REQUEST).entity(res).build(); } @PostConstruct void init(); void setService(EntityService service); @PUT @Path("{realmId}") @Consumes("application/json") @RightsAllowed({ Right.CRUD_REALM }) Response updateRealm(@PathParam("realmId") String realmId, EntityBody updatedRealm,
@Context final UriInfo uriInfo); @DELETE @Path("{realmId}") @RightsAllowed({ Right.CRUD_REALM }) Response deleteRealm(@PathParam("realmId") String realmId, @Context final UriInfo uriInfo); @POST @RightsAllowed({ Right.CRUD_REALM }) Response createRealm(EntityBody newRealm, @Context final UriInfo uriInfo); @GET @Path("{realmId}") @RightsAllowed({ Right.ADMIN_ACCESS }) Response readRealm(@PathParam("realmId") String realmId); @GET @RightsAllowed({ Right.ADMIN_ACCESS }) Response getRealms(@QueryParam(REALM) @DefaultValue("") String realm, @Context UriInfo info); static final String REALM; static final String ED_ORG; static final String RESPONSE; static final String NAME; static final String UNIQUE_IDENTIFIER; static final String IDP_ID; static final String ARTIFACT_RESOLUTION_ENDPOINT; static final String SOURCE_ID; static final String IDP; }
|
@Test public void testvalidateArtifactResolution() { Response res = resource.validateArtifactResolution(null, null); Assert.assertNull(res); res = resource.validateArtifactResolution("", ""); Assert.assertNull(res); res = resource.validateArtifactResolution("testEndpoint", "ccf4f3895f6e37896e7511ed1d991b1d96f04ac1"); Assert.assertNull(res); res = resource.validateArtifactResolution("", "ccf4f3895f6e37896e7511ed1d991b1d96f04ac1"); Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), res.getStatus()); res = resource.validateArtifactResolution("testEndpoint", ""); Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), res.getStatus()); res = resource.validateArtifactResolution(null, "ccf4f3895f6e37896e7511ed1d991b1d96f04ac1"); Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), res.getStatus()); res = resource.validateArtifactResolution("tesetEndpoint", null); Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), res.getStatus()); res = resource.validateArtifactResolution("tesetEndpoint", "ccf4f3895f6e37896e7511ed1d991b1d96f"); Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), res.getStatus()); }
|
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}") @Consumes("application/json") @RightsAllowed({ Right.CRUD_REALM }) Response updateRealm(@PathParam("realmId") String realmId, EntityBody updatedRealm,
@Context final UriInfo uriInfo); @DELETE @Path("{realmId}") @RightsAllowed({ Right.CRUD_REALM }) Response deleteRealm(@PathParam("realmId") String realmId, @Context final UriInfo uriInfo); @POST @RightsAllowed({ Right.CRUD_REALM }) Response createRealm(EntityBody newRealm, @Context final UriInfo uriInfo); @GET @Path("{realmId}") @RightsAllowed({ Right.ADMIN_ACCESS }) Response readRealm(@PathParam("realmId") String realmId); @GET @RightsAllowed({ Right.ADMIN_ACCESS }) Response getRealms(@QueryParam(REALM) @DefaultValue("") String realm, @Context UriInfo info); static final String REALM; static final String ED_ORG; static final String RESPONSE; static final String NAME; static final String UNIQUE_IDENTIFIER; static final String IDP_ID; static final String ARTIFACT_RESOLUTION_ENDPOINT; static final String SOURCE_ID; static final String IDP; }
|
@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"); Assert.assertEquals(Response.Status.OK.getStatusCode(), res.getStatus()); Assert.assertNull(res.getEntity()); }
|
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("sso/post") Response processPostBinding(@FormParam("SAMLResponse") String postData, @Context UriInfo uriInfo); @GET @Path("sso/artifact") Response processArtifactBinding(@Context HttpServletRequest request, @Context UriInfo uriInfo); static SimpleDateFormat ft; }
|
@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 = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader((String) response.getEntity())); org.w3c.dom.Document doc = db.parse(is); DOMBuilder builder = new DOMBuilder(); org.jdom.Document jdomDocument = builder.build(doc); Iterator<org.jdom.Element> itr = jdomDocument.getDescendants(new ElementFilter()); while (itr.hasNext()) { org.jdom.Element el = itr.next(); if(el.getName().equals("X509Certificate")) { Assert.assertNotNull(el.getText()); } } } catch (ParserConfigurationException e) { exception = e; } catch (SAXException e) { exception = e; } catch (IOException e) { exception = e; } Assert.assertNull(exception); }
|
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("No artifact provided by the IdP"); } String artifactUrl = samlHelper.getArtifactUrl(realmId, artifact); ArtifactResolve artifactResolve = artifactBindingHelper.generateArtifactResolveRequest(artifact, dsPKEntry, artifactUrl); Envelope soapEnvelope = artifactBindingHelper.generateSOAPEnvelope(artifactResolve); XMLObject response = soapHelper.sendSOAPCommunication(soapEnvelope, artifactUrl, clientCertPKEntry); ArtifactResponse artifactResponse = (ArtifactResponse)((EnvelopeImpl) response).getBody().getUnknownXMLObjects().get(0); org.opensaml.saml2.core.Response samlResponse = (org.opensaml.saml2.core.Response) artifactResponse.getMessage(); return processSAMLResponse(samlResponse, uriInfo); } @GET @Path("metadata") @Produces({ "text/xml" }) Response getMetadata(); @POST @Path("sso/post") Response processPostBinding(@FormParam("SAMLResponse") String postData, @Context UriInfo uriInfo); @GET @Path("sso/artifact") Response processArtifactBinding(@Context HttpServletRequest request, @Context UriInfo uriInfo); static SimpleDateFormat ft; }
|
@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.processArtifactBinding(request, uriInfo); }
@Test public void processArtifactBindingInvalidCondition() throws URISyntaxException { setRealm(false); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); UriInfo uriInfo = Mockito.mock(UriInfo.class); URI uri = new URI(issuerString); Mockito.when(uriInfo.getRequestUri()).thenReturn(uri); Mockito.when(uriInfo.getAbsolutePath()).thenReturn(uri); Mockito.when(request.getParameter("SAMLart")).thenReturn("AAQAAjh3bwgbBZ+LiIx3/RVwDGy0aRUu+xxuNtTZVbFofgZZVCKJQwQNQ7Q="); Mockito.when(request.getParameter("RelayState")).thenReturn("My Realm"); List<Assertion> assertions = new ArrayList<Assertion>(); DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy"); DateTime datetime = DateTime.now(); datetime = datetime.plusMonths(2) ; Assertion assertion = createAssertion(datetime.toString(fmt), "01/10/2011", issuerString); assertions.add(assertion); Mockito.when(samlHelper.getAssertion(Mockito.any(org.opensaml.saml2.core.Response.class), Mockito.any(KeyStore.PrivateKeyEntry.class))).thenReturn(assertion); expectedException.expect(APIAccessDeniedException.class); expectedException.expectMessage("Authorization could not be verified."); resource.processArtifactBinding(request, uriInfo); Mockito.when(assertion.getSubject()).thenReturn(null); resource.processArtifactBinding(request, uriInfo); assertions.clear(); assertions.add(createAssertion("01/10/2011", datetime.toString(fmt), issuerString)); resource.processArtifactBinding(request, uriInfo); }
|
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 custom role rights validation failed.",realmId); return res; } res = validateUniqueRoles(newCustomRole); if (res != null) { auditSecEvent(uriInfo, "Failed to create custom role unique roles check failed.",realmId); return res; } res = validateValidRealm(newCustomRole); if (res != null) { auditSecEvent(uriInfo, "Failed to create custom role invalid realm specified.",realmId); return res; } NeutralQuery existingCustomRoleQuery = new NeutralQuery(); existingCustomRoleQuery.addCriteria(new NeutralCriteria("realmId", NeutralCriteria.OPERATOR_EQUAL, realmId)); Entity existingRoleDoc = repo.findOne(RESOURCE_NAME, existingCustomRoleQuery); if (existingRoleDoc != null) { auditSecEvent(uriInfo, "Failed to create custom role Already exists.",realmId); return buildBadRequest(ERROR_MULTIPLE_DOCS + ": Realm '" + realmId + "'"); } String id = service.create(newCustomRole); if (id != null) { String uri = uriToString(uriInfo) + "/" + id; auditSecEvent(uriInfo, "Created custom role with id: " + id,realmId); this.sessions.clear(); return Response.status(Status.CREATED).header("Location", uri).build(); } return Response.status(Status.BAD_REQUEST).build(); } @PostConstruct void init(); @GET @RightsAllowed({Right.CRUD_ROLE }) Response readAll(@Context final UriInfo uriInfo,
@DefaultValue("") @QueryParam("realmId") String realmId); @GET @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response read(@PathParam("id") String id, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.CRUD_ROLE }) Response createCustomRole(EntityBody newCustomRole, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response updateCustomRole(@PathParam("id") String id, EntityBody updated, @Context final UriInfo uriInfo); @DELETE @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response deleteCustomRole(@PathParam("id") String id, @Context final UriInfo uriInfo); static final String RESOURCE_NAME; }
|
@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 public void testCreateWithDuplicateRoles() { EntityBody body = getRoleDocWithDuplicateRole(); mockGetRealmId(); Mockito.when(service.create(body)).thenReturn("new-role-id"); Response res = resource.createCustomRole(body, uriInfo); Assert.assertEquals(400, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_DUPLICATE_ROLE + ": 'Role1'", res.getEntity()); }
@Test public void testCreateWithInvalidRight() { EntityBody body = getRoleDocWithInvalidRight(); mockGetRealmId(); Mockito.when(service.create(body)).thenReturn("new-role-id"); Response res = resource.createCustomRole(body, uriInfo); Assert.assertEquals(400, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_INVALID_RIGHT + ": 'RIGHT_TO_REMAIN_SILENT'", res.getEntity()); }
@Test public void testCreateWithInvalidRealmId() { EntityBody body = getRoleDocWithInvalidRealm(); mockGetRealmId(); Mockito.when(service.create(body)).thenReturn("new-role-id"); Response res = resource.createCustomRole(body, uriInfo); Assert.assertEquals(403, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_INVALID_REALM, res.getEntity()); }
@Test public void testCreateWithDuplicateRights() { EntityBody body = getRoleDocWithDuplicateRights(); mockGetRealmId(); Mockito.when(service.create(body)).thenReturn("new-role-id"); Response res = resource.createCustomRole(body, uriInfo); Assert.assertEquals(400, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_DUPLICATE_RIGHTS + ": 'WRITE_GENERAL'", res.getEntity()); }
@Test public void testCreateDuplicate() { setRealms(REALM_ID); NeutralQuery existingCustomRoleQuery = new NeutralQuery(); existingCustomRoleQuery.addCriteria(new NeutralCriteria("realmId", NeutralCriteria.OPERATOR_EQUAL, REALM_ID)); Entity mockEntity = Mockito.mock(Entity.class); Mockito.when(mockEntity.getEntityId()).thenReturn("fake-id"); Mockito.when(repo.findOne(CustomRoleResource.RESOURCE_NAME, existingCustomRoleQuery)).thenReturn(mockEntity); mockGetRealmId(); Response res = resource.createCustomRole(getValidRoleDoc(), uriInfo); Assert.assertEquals(400, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_MULTIPLE_DOCS + ": Realm '867-5309'", res.getEntity()); }
|
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 readFields(DataInput data); @Override void write(DataOutput data); @Override String toString(); @Override BSONObject toBSON(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(EmittableKey other); }
|
@Test public void 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 failed.",null); return res; } res = validateUniqueRoles(updated); if (res != null) { auditSecEvent(uriInfo, "Failed to create custom role unique roles check failed.",null); return res; } res = validateValidRealm(updated); if (res != null) { auditSecEvent(uriInfo, "Failed to create custom role invalid realm specified.",null); return res; } EntityBody oldRealm = service.get(id); String oldRealmId = (String) oldRealm.get("realmId"); String updatedRealmId = (String) updated.get("realmId"); if (!updatedRealmId.equals(oldRealmId)) { auditSecEvent(uriInfo, "Failed to update realmId { from: " + oldRealmId + ", to: " + updatedRealmId + " } for role with id:" + id, oldRealmId); return buildBadRequest(ERROR_CHANGING_REALM_ID + ": '" + oldRealmId + "' -> '" + updatedRealmId + "'"); } if (service.update(id, updated, false)) { auditSecEvent(uriInfo, "Updated role with id:" + id,oldRealmId); this.sessions.clear(); return Response.status(Status.NO_CONTENT).build(); } return Response.status(Status.BAD_REQUEST).build(); } @PostConstruct void init(); @GET @RightsAllowed({Right.CRUD_ROLE }) Response readAll(@Context final UriInfo uriInfo,
@DefaultValue("") @QueryParam("realmId") String realmId); @GET @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response read(@PathParam("id") String id, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.CRUD_ROLE }) Response createCustomRole(EntityBody newCustomRole, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response updateCustomRole(@PathParam("id") String id, EntityBody updated, @Context final UriInfo uriInfo); @DELETE @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response deleteCustomRole(@PathParam("id") String id, @Context final UriInfo uriInfo); static final String RESOURCE_NAME; }
|
@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)).thenReturn(true); Response res = resource.updateCustomRole(id, body, uriInfo); Assert.assertEquals(204, res.getStatus()); }
@Test public void testUpdateWithDuplicateRoles() { EntityBody body = getRoleDocWithDuplicateRole(); body.put("customRights", Arrays.asList(new String[] {"Something", "Else"})); mockGetRealmId(); String id = "old-id"; Mockito.when(service.get(id)).thenReturn((EntityBody) body.clone()); Mockito.when(service.update(id, body, false)).thenReturn(true); Response res = resource.updateCustomRole(id, body, uriInfo); Assert.assertEquals(400, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_DUPLICATE_ROLE + ": 'Role1'", res.getEntity()); }
@Test public void testUpdateWithInvalidRight() { EntityBody body = getRoleDocWithInvalidRight(); body.put("customRights", Arrays.asList(new String[] {"Something", "Else"})); mockGetRealmId(); String id = "old-id"; Mockito.when(service.get(id)).thenReturn((EntityBody) body.clone()); Mockito.when(service.update(id, body, false)).thenReturn(true); Response res = resource.updateCustomRole(id, body, uriInfo); Assert.assertEquals(400, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_INVALID_RIGHT + ": 'RIGHT_TO_REMAIN_SILENT'", res.getEntity()); }
@Test public void testUpdateWithInvalidRealmId() { EntityBody body = getRoleDocWithInvalidRealm(); body.put("customRights", Arrays.asList(new String[] {"Something", "Else"})); mockGetRealmId(); String id = "old-id"; Mockito.when(service.get(id)).thenReturn((EntityBody) body.clone()); Mockito.when(service.update(id, body, false)).thenReturn(true); Response res = resource.updateCustomRole(id, body, uriInfo); Assert.assertEquals(403, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_INVALID_REALM, res.getEntity()); }
@Test public void testUpdateWithDuplicateRights() { EntityBody body = getRoleDocWithDuplicateRights(); body.put("customRights", Arrays.asList(new String[] {"Something", "Else"})); mockGetRealmId(); String id = "old-id"; Mockito.when(service.get(id)).thenReturn((EntityBody) body.clone()); Mockito.when(service.update(id, body, false)).thenReturn(true); Response res = resource.updateCustomRole(id, body, uriInfo); Assert.assertEquals(400, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_DUPLICATE_RIGHTS + ": 'WRITE_GENERAL'", res.getEntity()); }
|
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 != null && Boolean.valueOf(defaultsOnly).booleanValue()) { return Response.ok(roleInitializer.getDefaultRoles()).build(); } } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); Set<String> myRealms = realmHelper.getAssociatedRealmIds(); Set<String> realmsToQuery = null; if (!realmId.isEmpty() && !myRealms.contains(realmId)) { return buildBadRequest(ERROR_INVALID_REALM_ID + ": '" + realmId + "'"); } else { if (realmId.isEmpty()) { realmsToQuery = myRealms; } else { realmsToQuery = new HashSet<String>(); realmsToQuery.add(realmId); } } NeutralQuery customRoleQuery = new NeutralQuery(); customRoleQuery.addCriteria(new NeutralCriteria("realmId", NeutralCriteria.CRITERIA_IN, realmsToQuery)); Iterable<String> customRoles = repo.findAllIds("customRole", customRoleQuery); for (String id : customRoles) { EntityBody result = service.get(id); results.add(result); } return Response.ok(results).build(); } @PostConstruct void init(); @GET @RightsAllowed({Right.CRUD_ROLE }) Response readAll(@Context final UriInfo uriInfo,
@DefaultValue("") @QueryParam("realmId") String realmId); @GET @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response read(@PathParam("id") String id, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.CRUD_ROLE }) Response createCustomRole(EntityBody newCustomRole, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response updateCustomRole(@PathParam("id") String id, EntityBody updated, @Context final UriInfo uriInfo); @DELETE @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response deleteCustomRole(@PathParam("id") String id, @Context final UriInfo uriInfo); static final String RESOURCE_NAME; }
|
@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.when(service.get("mock-id")).thenReturn(body); NeutralQuery customRoleQuery = new NeutralQuery(); customRoleQuery.addCriteria(new NeutralCriteria("realmId", NeutralCriteria.CRITERIA_IN, new HashSet<String>(Arrays.asList(REALM_ID)))); Mockito.when(repo.findAllIds("customRole", customRoleQuery)).thenReturn(Arrays.asList("mock-id")); Response res = resource.readAll(uriInfo, ""); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(Arrays.asList(body), res.getEntity()); }
@Test public void testReadAllWithBadRealmIdParam() { 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.when(service.get("mock-id")).thenReturn(body); NeutralQuery customRoleQuery = new NeutralQuery(); customRoleQuery.addCriteria(new NeutralCriteria("realmId", NeutralCriteria.OPERATOR_EQUAL, REALM_ID)); Mockito.when(repo.findAllIds("customRole", customRoleQuery)).thenReturn(Arrays.asList("mock-id")); Response res = resource.readAll(uriInfo, "BAD_REALM_ID"); Assert.assertEquals(400, res.getStatus()); }
@Test public void testReadAllWithMultipleRealmsAndNoRealmIdParam() { setRealms(REALM_ID, "REALM2"); 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.when(service.get("mock-id")).thenReturn(body); NeutralQuery customRoleQuery = new NeutralQuery(); customRoleQuery.addCriteria(new NeutralCriteria("realmId", NeutralCriteria.CRITERIA_IN, new HashSet<String>(Arrays.asList(REALM_ID, "REALM2")))); Mockito.when(repo.findAllIds("customRole", customRoleQuery)).thenReturn(Arrays.asList("mock-id")); Response res = resource.readAll(uriInfo, ""); Assert.assertEquals(200, res.getStatus()); }
@Test public void testReadAllWithMultipleRealmsAndValidRealmIdParam() { setRealms(REALM_ID, "REALM2"); 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.when(service.get("mock-id")).thenReturn(body); NeutralQuery customRoleQuery = new NeutralQuery(); customRoleQuery.addCriteria(new NeutralCriteria("realmId", NeutralCriteria.CRITERIA_IN, new HashSet<String>(Arrays.asList(REALM_ID)))); Mockito.when(repo.findAllIds("customRole", customRoleQuery)).thenReturn(Arrays.asList("mock-id")); Response res = resource.readAll(uriInfo, REALM_ID); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(Arrays.asList(body), res.getEntity()); }
|
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)) { auditSecEvent(uriInfo, "Failed to read custom role with id: " + id + " wrong tenant + realm combination.",realmId); return Response.status(Status.FORBIDDEN).entity(ERROR_FORBIDDEN).build(); } return Response.ok(customRole).build(); } @PostConstruct void init(); @GET @RightsAllowed({Right.CRUD_ROLE }) Response readAll(@Context final UriInfo uriInfo,
@DefaultValue("") @QueryParam("realmId") String realmId); @GET @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response read(@PathParam("id") String id, @Context final UriInfo uriInfo); @POST @RightsAllowed({Right.CRUD_ROLE }) Response createCustomRole(EntityBody newCustomRole, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response updateCustomRole(@PathParam("id") String id, EntityBody updated, @Context final UriInfo uriInfo); @DELETE @Path("{id}") @RightsAllowed({Right.CRUD_ROLE }) Response deleteCustomRole(@PathParam("id") String id, @Context final UriInfo uriInfo); static final String RESOURCE_NAME; }
|
@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, res.getEntity()); }
@Test public void testReadInaccessible() { String inaccessibleId = "inaccessible-id"; EntityBody body = getValidRoleDoc(); body.put("realmId", "BAD-REALM"); Mockito.when(service.get(inaccessibleId)).thenReturn(body); Response res = resource.read(inaccessibleId, uriInfo); Assert.assertEquals(403, res.getStatus()); Assert.assertEquals(CustomRoleResource.ERROR_FORBIDDEN, res.getEntity()); }
|
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); }
|
@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"); }
|
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; }
|
@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())); }
|
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; }
|
@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")); }
|
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; }
|
@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()); }
|
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); }
|
@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(); } @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; }
|
@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()); }
|
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(); body.put(MESSAGE, "Auto-generated attribute (id|client_secret|client_id) specified in POST. " + "Remove attribute and try again."); return Response.status(Status.BAD_REQUEST).entity(body).build(); } if (missingRequiredUrls(newApp)) { EntityBody body = new EntityBody(); body.put(MESSAGE, "Applications that are not marked as installed must have a application url and redirect url"); return Response.status(Status.BAD_REQUEST).entity(body).build(); } newApp.put(AUTHORIZED_ED_ORGS, new ArrayList<String>()); String clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); while (isDuplicateToken(clientId)) { clientId = TokenGenerator.generateToken(CLIENT_ID_LENGTH); } newApp.put(CLIENT_ID, clientId); SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); newApp.put(CREATED_BY, principal.getExternalId()); if (principal.getSandboxTenant() != null) { newApp.put(AUTHOR_SANDBOX_TENANT, principal.getSandboxTenant()); } if (principal.getFirstName() != null) { newApp.put(AUTHOR_FIRST_NAME, principal.getFirstName()); } if (principal.getLastName() != null) { newApp.put(AUTHOR_LAST_NAME, principal.getLastName()); } Map<String, Object> registration = new HashMap<String, Object>(); registration.put(STATUS, STATUS_PENDING); if (autoRegister) { registration.put(APPROVAL_DATE, System.currentTimeMillis()); registration.put(STATUS, STATUS_APPROVED); } registration.put(REQUEST_DATE, System.currentTimeMillis()); newApp.put(REGISTRATION, registration); String clientSecret = TokenGenerator.generateToken(CLIENT_SECRET_LENGTH); newApp.put(CLIENT_SECRET, clientSecret); for (String fieldName : PERMANENT_FIELDS) { newApp.remove(fieldName); } return super.post(newApp, 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; }
|
@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).toString().length() == 10); assertTrue("Client secret set", app.get(CLIENT_SECRET).toString().length() == 48); Map reg = (Map) app.get(REGISTRATION); assertEquals("Reg is pending", "PENDING", reg.get(STATUS)); assertTrue("request date set", reg.containsKey(REQUEST_DATE)); assertFalse("approval date not set", reg.containsKey(APPROVAL_DATE)); }
|
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; }
|
@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); 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; }
|
@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); }
|
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; } }
|
@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()); }
|
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; } }
|
@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()); }
|
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 == null) { Entity appEntity = repo.findOne("application", new NeutralQuery(new NeutralCriteria("_id", "=", appId))); if (appEntity == null || isAutoAuthorizedApp(appEntity)) { return Response.status(Status.NOT_FOUND).build(); } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", false); entity.put("edorgs", Collections.emptyList()); return Response.status(Status.OK).entity(entity).build(); } } else { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("appId", appId); entity.put("id", appId); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) appAuth.get("edorgs"); Map<String,Object> authorizingInfo = getAuthorizingInfo(edOrgs, myEdorgs); entity.put("authorized", ( authorizingInfo == null)?false:true); if(!isSEAAdmin()) { Set<String> inScopeEdOrgs = getChildEdorgs(myEdorgs); entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } return Response.status(Status.OK).entity(entity).build(); } } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
|
@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.put("applicationId", "someAppId"); auth.put("edorgs", getAuthList("someOtherEdorg")); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization("someAppId", null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertFalse((Boolean) ent.get("authorized")); }
@Test public void testGetAuthForNonExistingAppAndExistingAuth2() { Map<String, Object> auth = new HashMap<String, Object>(); auth.put("applicationId", "someAppId"); auth.put("edorgs", getAuthList(SecurityUtil.getEdOrgId())); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization("someAppId", null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertTrue((Boolean) ent.get("authorized")); }
@Test public void testGetAuthForExistingAppAndNonExistingAuth() { Map<String, Object> appBody = new HashMap<String, Object>(); Entity app = repo.create("application", appBody); ResponseImpl resp = (ResponseImpl) res.getAuthorization(app.getEntityId(), null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertFalse((Boolean) ent.get("authorized")); }
@Test public void testGetAuthForExistingAppAndExistingAuth() { 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.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization(app.getEntityId(), null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertTrue((Boolean) ent.get("authorized")); }
@Test public void testGetAuthForExistingAppAndExistingAuth2() { 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("someOtherEdorg")); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization(app.getEntityId(), null); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertFalse((Boolean) ent.get("authorized")); }
@Test public void testGetAuthForExistingAppAndExistingAuthAndEdorg() { 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("someOtherEdorg")); repo.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorization(app.getEntityId(), SecurityUtil.getEdOrgId()); Assert.assertEquals(200, resp.getStatus()); Map ent = (Map) resp.getEntity(); Assert.assertFalse((Boolean) ent.get("authorized")); }
|
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); }
|
@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) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Iterable<EntityBody> ents = null; if (principal.isAdminRealmAuthenticated()) { ents = service.list(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs))); } else { ents = filterOutAutoAuthorized(service.listBasedOnContextualRoles(new NeutralQuery(new NeutralCriteria("edorgs.authorizedEdorg", NeutralCriteria.CRITERIA_IN, inScopeEdOrgs)))); } Iterable<Entity> appQuery = repo.findAll("application", new NeutralQuery()); Map<String, Entity> allApps = new HashMap<String, Entity>(); for (Entity ent : appQuery) { if(!isAutoAuthorizedApp(ent)) { allApps.put(ent.getEntityId(), ent); } } List<Map> results = new ArrayList<Map>(); for (EntityBody body : ents) { HashMap<String, Object> entity = new HashMap<String, Object>(); String appId = (String) body.get("applicationId"); List<Map<String,Object>> edOrgs = (List<Map<String,Object>>) body.get("edorgs"); entity.put("id", appId); entity.put("appId", appId); entity.put("authorized", true); if(!isSEAAdmin()) { entity.put("edorgs", filter(edOrgs, inScopeEdOrgs)); } else { entity.put("edorgs", edOrgs); } results.add(entity); allApps.remove(appId); } for (Map.Entry<String, Entity> entry : allApps.entrySet()) { Boolean autoApprove = (Boolean) entry.getValue().getBody().get("allowed_for_all_edorgs"); List<String> approvedEdorgs = (List<String>) entry.getValue().getBody().get("authorized_ed_orgs"); if ((autoApprove != null && autoApprove) || isSEAAdmin() || (approvedEdorgs != null && CollectionUtils.containsAny(approvedEdorgs, inScopeEdOrgs))) { HashMap<String, Object> entity = new HashMap<String, Object>(); entity.put("id", entry.getKey()); entity.put("appId", entry.getKey()); entity.put("authorized", false); results.add(entity); } } return Response.status(Status.OK).entity(results).build(); } @PostConstruct void init(); @GET @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorization(@PathParam("appId") String appId, @QueryParam("edorg") String edorg); boolean isAutoAuthorizedApp(Entity appEntity); @PUT @Path("{appId}") @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response updateAuthorization(@PathParam("appId") String appId, EntityBody auth); static List<Map<String, Object>> enrichAuthorizedEdOrgsList(List<String> edOrgIds); @GET @RightsAllowed({Right.EDORG_APP_AUTHZ, Right.APP_AUTHORIZE}) Response getAuthorizations(@QueryParam("edorg") String edorg); static final String RESOURCE_NAME; static final String APP_ID; static final String EDORG_IDS; }
|
@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.create("applicationAuthorization", auth); ResponseImpl resp = (ResponseImpl) res.getAuthorizations(null); Assert.assertEquals(200, resp.getStatus()); List ents = (List) resp.getEntity(); Assert.assertEquals(1, ents.size()); }
|
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(Resource resource) { return resourceService.getEntities(resource, uriInfo.getRequestUri(), false); } }); } @Override @GET @RightsAllowed({ Right.SECURITY_EVENT_VIEW }) Response getAll(@Context final UriInfo uriInfo); @Override @GET @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response getWithId(@PathParam("id") final String idList, @Context final UriInfo uriInfo); @Override @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) CustomEntityResource getCustomResource(final String id, final UriInfo uriInfo); @Override @POST @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response post(final EntityBody entityBody, @Context final UriInfo uriInfo); @PUT @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response put(@PathParam("id") final String id, final EntityBody entityBody,
@Context final UriInfo uriInfo); @Override @DELETE @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response delete(@PathParam("id") final String id, @Context final UriInfo uriInfo); @Override @PATCH @Path("{id}") @RightsAllowed({ Right.SECURITY_EVENT_VIEW}) Response patch(@PathParam("id") final String id,
final EntityBody entityBody,
@Context final UriInfo uriInfo); @OPTIONS @RightsAllowed({Right.SECURITY_EVENT_VIEW}) Response options(); static final String RESOURCE_NAME; }
|
@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 (response.getEntity() instanceof EntityResponse) { EntityResponse resp = (EntityResponse) response.getEntity(); responseEntityObj = resp.getEntity(); } else { fail("Should always return EntityResponse: " + response); } if (responseEntityObj instanceof EntityBody) { assertNotNull(responseEntityObj); } else if (responseEntityObj instanceof List<?>) { @SuppressWarnings("unchecked") List<EntityBody> results = (List<EntityBody>) responseEntityObj; assertEquals("unexpected number of entities", 2, results.size()); } else { fail("Response entity not recognized: " + response); } }
@Test public void testSLCOperatorLimitGetSecurityEvents() throws URISyntaxException { injector.setOperatorContext(); URI mockUri = new URI("/rest/securityEvent?limit=2&offset=0"); when(uriInfo.getRequestUri()).thenReturn(mockUri); Response response = resource.getAll(uriInfo); Object responseEntityObj = null; if (response.getEntity() instanceof EntityResponse) { EntityResponse resp = (EntityResponse) response.getEntity(); responseEntityObj = resp.getEntity(); } else { fail("Should always return EntityResponse: " + response); } if (responseEntityObj instanceof EntityBody) { assertNotNull(responseEntityObj); } else if (responseEntityObj instanceof List<?>) { @SuppressWarnings("unchecked") List<EntityBody> results = (List<EntityBody>) responseEntityObj; assertEquals("unexpected number of entities", 2, results.size()); } else { fail("Response entity not recognized: " + response); } }
@Test public void testSLCOperatorOffsetLimitGetSecurityEvents() throws URISyntaxException { injector.setOperatorContext(); URI mockUri = new URI("/rest/securityEvent?limit=3&offset=1"); when(uriInfo.getRequestUri()).thenReturn(mockUri); Response response = resource.getAll(uriInfo); Object responseEntityObj = null; if (response.getEntity() instanceof EntityResponse) { EntityResponse resp = (EntityResponse) response.getEntity(); responseEntityObj = resp.getEntity(); } else { fail("Should always return EntityResponse: " + response); } if (responseEntityObj instanceof EntityBody) { assertNotNull(responseEntityObj); } else if (responseEntityObj instanceof List<?>) { @SuppressWarnings("unchecked") List<EntityBody> results = (List<EntityBody>) responseEntityObj; assertEquals("unexpected number of entities", 3, results.size()); } else { fail("Response entity not recognized: " + response); } }
@Test public void testSLCOperatorGetSecurityEvents() { injector.setOperatorContext(); Response response = resource.getAll(uriInfo); Object responseEntityObj = null; if (response.getEntity() instanceof EntityResponse) { EntityResponse resp = (EntityResponse) response.getEntity(); responseEntityObj = resp.getEntity(); } else { fail("Should always return EntityResponse: " + response); } if (responseEntityObj instanceof EntityBody) { assertNotNull(responseEntityObj); } else if (responseEntityObj instanceof List<?>) { @SuppressWarnings("unchecked") List<EntityBody> results = (List<EntityBody>) responseEntityObj; assertEquals("unexpected number of entities", 5, results.size()); } else { fail("Response entity not recognized: " + response); } }
|
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); }
|
@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 result; } newUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(newUser.getGroups()))); newUser.setStatus(User.Status.SUBMITTED); try { ldapService.createUser(realm, newUser); } catch (NameAlreadyBoundException e) { return Response.status(Status.CONFLICT).build(); } auditLogger.audit(createSecurityEvent("Created user " + newUser.getUid() + " with roles " + rolesToString(newUser), newUser.getTenant(), newUser.getEdorg())); return Response.status(Status.CREATED).build(); } @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); }
|
@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(RoleInitializer.SLC_OPERATOR)); newUser.setFullName("Eddard Stark"); newUser.setEmail("nedstark@winterfell.gov"); newUser.setUid("nedstark"); Response res = resource.create(newUser); Mockito.verify(ldap).createUser(REALM, newUser); Assert.assertNotNull(res); Assert.assertEquals(201, res.getStatus()); rights.remove(Right.CRUD_SLC_OPERATOR); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(403, res.getStatus()); Mockito.when(secUtil.getEdOrg()).thenReturn(EDORG1); newUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); newUser.setEdorg(EDORG1); newUser.setTenant(TENANT); res = resource.create(newUser); Mockito.verify(ldap, Mockito.times(2)).createUser(REALM, newUser); Assert.assertNotNull(res); Assert.assertEquals(201, res.getStatus()); rights.remove(Right.CRUD_SEA_ADMIN); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(403, res.getStatus()); Mockito.when(secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)).thenReturn(true); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); newUser.setEdorg(EDORG1); Mockito.when(adminService.getAllowedEdOrgs(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(String.class), Mockito.anyBoolean())).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(201, res.getStatus()); Mockito.verify(ldap, Mockito.times(3)).createUser(REALM, newUser); newUser.setEdorg(EDORG2); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(400, res.getStatus()); rights.remove(Right.CRUD_LEA_ADMIN); res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(403, res.getStatus()); }
@Test public void testCreateWithOrWithoutLEA() { 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.hasRight(Right.CRUD_SLC_OPERATOR)).thenReturn(true); Mockito.when(adminService.getAllowedEdOrgs(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(String.class), Mockito.anyBoolean())).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); Mockito.when(adminService.getAllowedEdOrgs(Mockito.anyString(), Mockito.anyString())).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.REALM_ADMINISTRATOR)); newUser.setFullName("Eddard Stark"); newUser.setEmail("nedstark@winterfell.gov"); newUser.setUid("nedstark"); newUser.setEdorg(EDORG1); newUser.setTenant(TENANT); Response res = resource.create(newUser); Assert.assertNotNull(res); Assert.assertEquals(400, res.getStatus()); User lea = new User(); lea.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); lea.setFullName("Eddard2 Stark"); lea.setEmail("nedstark2@winterfell.gov"); lea.setUid("nedstark2"); lea.setEdorg(EDORG1); lea.setTenant(TENANT); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyString(), Mockito.anyCollectionOf(String.class))).thenReturn(Arrays.asList(lea)); res = resource.create(newUser); Mockito.verify(ldap).createUser(REALM, newUser); Assert.assertNotNull(res); Assert.assertEquals(201, res.getStatus()); }
@Test public void testMailValidation() { 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 userWithNoMail = new User(); userWithNoMail.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); userWithNoMail.setEdorg(EDORG1); userWithNoMail.setTenant(TENANT); userWithNoMail.setFullName("Mance Rayder"); userWithNoMail.setUid("mrayder"); userWithNoMail.setPassword("fr33folk"); Response response = resource.create(userWithNoMail); assertEquals(400, response.getStatus()); assertEquals("No email address", response.getEntity()); }
@Test public void testNameValidation() { 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 userWithNoName = new User(); userWithNoName.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); userWithNoName.setEdorg(EDORG1); userWithNoName.setTenant(TENANT); userWithNoName.setUid("kindlyman"); userWithNoName.setPassword("k1ndlyman"); userWithNoName.setEmail("kindlyman@bravos.org"); assertEquals(400, resource.create(userWithNoName).getStatus()); }
@Test public void testNoLastName() { 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 userWithNoSurname = new User(); userWithNoSurname.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); userWithNoSurname.setEdorg(EDORG1); userWithNoSurname.setTenant(TENANT); userWithNoSurname.setFullName("Jon"); userWithNoSurname.setUid("jsnow"); userWithNoSurname.setPassword("jsn0w"); userWithNoSurname.setEmail("jsnown@thewall.org"); assertEquals(201, resource.create(userWithNoSurname).getStatus()); }
@Test public void testUidValidation() { 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 userWithNoId = new User(); userWithNoId.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); userWithNoId.setEdorg(EDORG1); userWithNoId.setTenant(TENANT); userWithNoId.setFullName("Arya Stark"); userWithNoId.setPassword("@ry@"); userWithNoId.setEmail("arya@winterfell.org"); assertEquals(400, resource.create(userWithNoId).getStatus()); }
@Test public void testBadData() { 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(RoleInitializer.SEA_ADMINISTRATOR)); Response res = resource.create(newUser); Assert.assertEquals(400, res.getStatus()); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); res = resource.create(newUser); Assert.assertEquals(400, res.getStatus()); newUser.setTenant(TENANT); newUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); res = resource.create(newUser); Assert.assertEquals(400, res.getStatus()); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); res = resource.create(newUser); Assert.assertEquals(400, res.getStatus()); }
|
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) { return result; } updateUser.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapRoleToGroups(updateUser.getGroups()))); ldapService.updateUser(realm, updateUser); auditLogger.audit(createSecurityEvent("Updated user " + updateUser.getUid() + " with roles " + rolesToString(updateUser), updateUser.getTenant(), updateUser.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @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); }
|
@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 newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.INGESTION_USER)); newUser.setUid(UUID2); newUser.setTenant(TENANT); newUser.setEdorg(EDORG1); newUser.setFullName("Robb Stark"); newUser.setEmail("robbstark@winterfell.gov"); User ldapUser = new User(); ldapUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); ldapUser.setUid(UUID2); ldapUser.setFullName("Robb Stark"); ldapUser.setEmail("robbstark@winterfell.gov"); ldapUser.setTenant(TENANT); ldapUser.setEdorg(EDORG1); ldapUser.setHomeDir("test_dir"); User ldapUser2 = new User(); ldapUser2.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); ldapUser2.setUid(UUID2 + "2"); ldapUser2.setFullName("Robb Stark"); ldapUser2.setEmail("robbstark@winterfell.gov"); ldapUser2.setTenant(TENANT); ldapUser2.setEdorg(EDORG1); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(ldapUser); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyString(), Mockito.anyCollectionOf(String.class))).thenReturn(Arrays.asList(ldapUser)); Response res = resource.update(ldapUser); Assert.assertNotNull(res); Assert.assertEquals(204, res.getStatus()); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyString(), Mockito.anyCollectionOf(String.class))).thenReturn(Arrays.asList(ldapUser, ldapUser2)); res = resource.update(newUser); Mockito.verify(ldap).updateUser(REALM, newUser); Assert.assertNotNull(res); Assert.assertEquals(204, res.getStatus()); Assert.assertEquals(newUser.getHomeDir(), ldapUser.getHomeDir()); }
@Test public void testModifySelf() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(adminService.getAllowedEdOrgs(TENANT, null)).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn(UUID2); Mockito.when(secUtil.getEdOrg()).thenReturn(EDORG1); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); newUser.setUid(UUID2); newUser.setTenant(TENANT); newUser.setEdorg(EDORG1); newUser.setFullName("Robb Stark"); newUser.setEmail("robbstark@winterfell.gov"); User ldapUser = new User(); ldapUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); ldapUser.setUid(UUID2); ldapUser.setFullName("Robb Stark"); ldapUser.setEmail("robbstark@winterfell.gov"); ldapUser.setTenant(TENANT); ldapUser.setEdorg(EDORG1); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(ldapUser); Response res = resource.update(newUser); Assert.assertNotNull(res); Assert.assertEquals(400, res.getStatus()); }
@Test public void testUpdateLastSEA() { Collection<GrantedAuthority> rights = new HashSet<GrantedAuthority>(); rights.addAll(Arrays.asList(Right.CRUD_SLC_OPERATOR, Right.CRUD_SEA_ADMIN, Right.CRUD_LEA_ADMIN)); Mockito.when(adminService.getAllowedEdOrgs(TENANT, null)).thenReturn( new HashSet<String>(Arrays.asList(EDORG1))); Mockito.when(secUtil.getAllRights()).thenReturn(rights); Mockito.when(secUtil.getUid()).thenReturn(UUID1); Mockito.when(secUtil.getEdOrg()).thenReturn(EDORG1); User newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.LEA_ADMINISTRATOR)); newUser.setUid(UUID2); newUser.setTenant(TENANT); newUser.setEdorg(EDORG1); newUser.setFullName("Robb Stark"); newUser.setEmail("robbstark@winterfell.gov"); User ldapUser = new User(); ldapUser.setGroups(Arrays.asList(RoleInitializer.SEA_ADMINISTRATOR)); ldapUser.setUid(UUID2); ldapUser.setFullName("Robb Stark"); ldapUser.setEmail("robbstark@winterfell.gov"); ldapUser.setTenant(TENANT); ldapUser.setEdorg(EDORG1); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(ldapUser); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyString(), Mockito.anyCollectionOf(String.class))).thenReturn(Arrays.asList(ldapUser)); Response res = resource.update(newUser); Assert.assertNotNull(res); Assert.assertEquals(400, res.getStatus()); }
|
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 (result != null) { return result; } User userToDelete = ldapService.getUser(realm, uid); ldapService.removeUser(realm, uid); auditLogger.audit(createSecurityEvent("Deleted user " + uid + " with roles " + rolesToString(userToDelete), userToDelete.getTenant(), userToDelete.getEdorg())); return Response.status(Status.NO_CONTENT).build(); } @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); }
|
@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 newUser = new User(); newUser.setGroups(Arrays.asList(RoleInitializer.SLC_OPERATOR)); newUser.setUid(UUID2); newUser.setTenant(""); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(newUser); Mockito.when(secUtil.hasRole(RoleInitializer.SLC_OPERATOR)).thenReturn(true); Response res = resource.delete(newUser.getUid()); Mockito.verify(ldap, Mockito.atLeastOnce()).getUser(REALM, newUser.getUid()); Mockito.verify(ldap).removeUser(REALM, newUser.getUid()); Assert.assertNotNull(res); Assert.assertEquals(204, res.getStatus()); Collection<GrantedAuthority> rights2 = new HashSet<GrantedAuthority>(); rights2.addAll(Arrays.asList(Right.CRUD_SANDBOX_ADMIN)); Mockito.when(secUtil.getAllRights()).thenReturn(rights2); Mockito.when(secUtil.getUid()).thenReturn(UUID1); Mockito.when(secUtil.getTenantId()).thenReturn(TENANT); User userToDelete = new User(); userToDelete.setGroups(Arrays.asList(RoleInitializer.SLC_OPERATOR)); userToDelete.setUid(UUID2); userToDelete.setTenant(TENANT1); Mockito.when(ldap.getUser(REALM, UUID2)).thenReturn(userToDelete); Mockito.when(secUtil.hasRole(RoleInitializer.SLC_OPERATOR)).thenReturn(false); Mockito.when(secUtil.hasRole(RoleInitializer.SANDBOX_SLC_OPERATOR)).thenReturn(false); res = resource.delete(newUser.getUid()); Assert.assertNotNull(res); Assert.assertEquals(403, res.getStatus()); }
|
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); }
|
@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); }
|
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.getAllRights(), tenant); if (result != null) { return result; } Collection<String> edorgs = null; if (secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)) { edorgs = new ArrayList<String>(); edorgs.addAll(adminService.getAllowedEdOrgs(tenant, edorg)); } Set<String> groupsToIgnore = new HashSet<String>(); if (isLeaAdmin()) { groupsToIgnore.add(RoleInitializer.SLC_OPERATOR); groupsToIgnore.add(RoleInitializer.SEA_ADMINISTRATOR); } Collection<User> users = ldapService.findUsersByGroups(realm, RightToGroupMapper.getInstance().getGroups(secUtil.getAllRights()), groupsToIgnore, secUtil.getTenantId(), edorgs); if (users != null && users.size() > 0) { for (User user : users) { user.setGroups((List<String>) (RoleToGroupMapper.getInstance().mapGroupToRoles(user.getGroups()))); } } return Response.status(Status.OK).entity(users).build(); } @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); }
|
@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()).thenReturn("myUid"); Mockito.when(secUtil.hasRole(RoleInitializer.LEA_ADMINISTRATOR)).thenReturn(false); List<User> users = Arrays.asList(new User(), new User()); Mockito.when( ldap.findUsersByGroups(Mockito.eq(REALM), Mockito.anyCollectionOf(String.class), Mockito.anyCollectionOf(String.class), Mockito.anyString(), (Collection<String>) Mockito.isNull())).thenReturn(users); Response res = resource.readAll(); Assert.assertEquals(200, res.getStatus()); Object entity = res.getEntity(); Assert.assertEquals(users, entity); }
|
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(), tenant); if (result != null) { return result; } if (tenant == null) { List<String> edorgs = new LinkedList<String>(); return Response.status(Status.OK).entity(edorgs).build(); } String restrictByEdOrg = this.isLeaAdmin() ? secUtil.getEdOrg() : null; ArrayList<String> edOrgs = new ArrayList<String>(adminService.getAllowedEdOrgs(tenant, restrictByEdOrg)); Collections.sort(edOrgs); return Response.status(Status.OK).entity(edOrgs).build(); } @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); }
|
@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_ADMINISTRATOR)).thenReturn(false); Response res = resource.getEdOrgs(); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(new LinkedList<String>(), res.getEntity()); Mockito.when(secUtil.getTenantId()).thenReturn(TENANT); rights.remove(Right.CRUD_SLC_OPERATOR); Mockito.when(adminService.getAllowedEdOrgs(TENANT, null)).thenReturn( new HashSet<String>(Arrays.asList(EDORG1, EDORG2))); res = resource.getEdOrgs(); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(Arrays.asList(EDORG1, EDORG2), res.getEntity()); rights.remove(Right.CRUD_SEA_ADMIN); Mockito.when(secUtil.getEdOrg()).thenReturn(EDORG1); Mockito.when(adminService.getAllowedEdOrgs(TENANT, EDORG1)).thenReturn( new HashSet<String>(Arrays.asList(EDORG1, EDORG2))); res = resource.getEdOrgs(); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals(Arrays.asList(EDORG1, EDORG2), res.getEntity()); }
|
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); }
|
@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)); }
|
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); }
|
@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 }))); }
|
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); }
|
@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); }
|
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); }
|
@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 deserialize(final InputStream body); }
|
@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 public void testLists() { final String xmlList = "<test xmlns:sli=\"urn:sli\"><l1 sli:member=\"true\">v1</l1><l1 sli:member=\"true\">v2</l1></test>"; EntityBody body = null; try { body = deserialize(xmlList); } catch (XMLStreamException e) { fail(e.getMessage()); } assertNotNull(body); assertTrue("Should be a list", body.get("l1") instanceof List); @SuppressWarnings("unchecked") final List<String> l1Values = (List<String>) body.get("l1"); assertTrue(l1Values.contains("v1")); assertTrue(l1Values.contains("v2")); }
@Test public void testMaps() { final String xmlMaps = "<test>" + "<key1>" + "<ek1>ev1</ek1>" + "<ek2>ev2</ek2>" + "</key1>" + "</test>"; EntityBody body = null; try { body = deserialize(xmlMaps); } catch (XMLStreamException e) { fail(e.getMessage()); } assertNotNull(body); assertTrue("Should be a map", body.get("key1") instanceof Map); @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) body.get("key1"); assertEquals("ev1", map.get("ek1")); assertEquals("ev2", map.get("ek2")); }
@Test public void testSomethingComplex() { final String complexXML = "<school xmlns:sli=\"urn:sli\">\n" + " <id>8cc0a1ac-ccb5-dffc-1d74-32964722179b</id>\n" + " <schoolCategories sli:member=\"true\">Middle School</schoolCategories>\n" + " <gradesOffered sli:member=\"true\">Sixth grade</gradesOffered>\n" + " <gradesOffered sli:member=\"true\">Eighth grade</gradesOffered>\n" + " <gradesOffered sli:member=\"true\">Seventh grade</gradesOffered>\n" + " <organizationCategories sli:member=\"true\">School</organizationCategories>\n" + " <address sli:member=\"true\">\n" + " <addressType>Physical</addressType>\n" + " <streetNumberName>456 Blah Street</streetNumberName>\n" + " <city>Las Vegas</city>\n" + " <stateAbbreviation>NV</stateAbbreviation>\n" + " <postalCode>66666</postalCode>\n" + " <nameOfCounty>Vegas County</nameOfCounty>\n" + " </address>\n" + " <address sli:member=\"true\">\n" + " <addressType>Physical</addressType>\n" + " <streetNumberName>123 Blah Street</streetNumberName>\n" + " <city>Durham</city>\n" + " <stateAbbreviation>NC</stateAbbreviation>\n" + " <postalCode>66666</postalCode>\n" + " <nameOfCounty>Durham</nameOfCounty>\n" + " </address>\n" + " <parentEducationAgencyReference>bd086bae-ee82-4cf2-baf9-221a9407ea07</parentEducationAgencyReference>\n" + " <stateOrganizationId>152901004</stateOrganizationId>\n" + " <entityType>school</entityType>\n" + " <telephone sli:member=\"true\">\n" + " <institutionTelephoneNumberType>Main</institutionTelephoneNumberType>\n" + " <telephoneNumber>(333) 344-7777</telephoneNumber>\n" + " </telephone>\n" + " <nameOfInstitution>Purple Middle School</nameOfInstitution>\n" + "</school>\n"; EntityBody body = null; try { body = deserialize(complexXML); } catch (XMLStreamException e) { fail(e.getMessage()); } assertNotNull(body); Object address = body.get("address"); assertTrue(address instanceof List); assertEquals(2, ((List) address).size()); Object telephone = body.get("telephone"); assertTrue(telephone instanceof List); assertEquals(1, ((List) telephone).size()); @SuppressWarnings("unchecked") Map<String, Object> telephoneHash = (Map<String, Object>) ((List) telephone).get(0); assertEquals("(333) 344-7777", telephoneHash.get("telephoneNumber").toString()); Object id = body.get("id"); assertTrue(id instanceof String); assertEquals("8cc0a1ac-ccb5-dffc-1d74-32964722179b", id.toString()); }
@Test(expected = XMLStreamException.class) public void testMissingEndTag() throws XMLStreamException { final String xmlValues = "<test><k1>v1</k1><k2>v2</k2>"; final EntityBody body = deserialize(xmlValues); }
@Test(expected = XMLStreamException.class) public void testMalformedXML() throws XMLStreamException { final String xmlValues = "<test><k1>v1</k1><k2>v2</k2></tset>"; final EntityBody body = deserialize(xmlValues); }
@Test public void testProcessingInstruction() { final String xmlValues = "<?xml version=\"1.0\" ?><test><k1>v1</k1><k2>v2</k2></test>"; EntityBody body = null; try { body = deserialize(xmlValues); } catch (XMLStreamException e) { fail(); } assertNotNull(body); }
|
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); }
|
@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()); } }
|
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); }
|
@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>")); }
|
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); }
|
@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 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); }
|
@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 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); }
|
@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()); }
|
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; }
|
@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 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); }
|
@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")); }
|
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); }
|
@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")); }
|
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); }
|
@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()); }
|
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); }
|
@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()) { 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); }
|
@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 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); }
|
@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"))); }
|
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); }
|
@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()); }
|
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); }
|
@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 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); }
|
@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()); }
|
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); }
|
@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); }
|
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); }
|
@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")); }
|
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); }
|
@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")); }
|
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); }
|
@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 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); }
|
@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()); }
|
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; } }
|
@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()); }
|
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; }
|
@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"); } }
|
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); }
|
@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.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); }
|
@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, 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); }
|
@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)); }
|
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); }
|
@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); }
|
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); }
|
@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")); }
|
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); }
|
@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")); }
|
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); }
|
@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); }
|
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); }
|
@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 @Path("email") Object getEmail(); }
|
@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)); }
|
OptionalView implements View { @Override public List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams) { if (factory == null) { return entities; } List<EntityBody> appendedEntities = entities; List<String> optionalFields = new ArrayList<String>(); if (queryParams.get(ParameterConstants.OPTIONAL_FIELDS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.OPTIONAL_FIELDS)); } if (queryParams.get(ParameterConstants.VIEWS) != null) { optionalFields.addAll(queryParams.get(ParameterConstants.VIEWS)); } if (!optionalFields.isEmpty()) { for (String type : optionalFields) { for (String appenderType : type.split(",")) { Map<String, String> values = extractOptionalFieldParams(appenderType); OptionalFieldAppender appender = factory.getOptionalFieldAppender(resource + "_" + values.get(OptionalFieldAppenderFactory.APPENDER_PREFIX)); if (appender != null) { appendedEntities = appender.applyOptionalField(entities, values.get(OptionalFieldAppenderFactory.PARAM_PREFIX)); } } } } return appendedEntities; } @Override List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams); }
|
@Test @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)); }
|
OptionalView implements View { protected Map<String, String> extractOptionalFieldParams(String optionalFieldValue) { Map<String, String> values = new HashMap<String, String>(); String appender = null, params = null; if (optionalFieldValue.contains(".")) { StringTokenizer st = new StringTokenizer(optionalFieldValue, "."); int index = 0; String token = null; while (st.hasMoreTokens()) { token = st.nextToken(); switch (index) { case 0: appender = token; break; case 1: params = token; break; } ++index; } } else { appender = optionalFieldValue; } values.put(OptionalFieldAppenderFactory.APPENDER_PREFIX, appender); values.put(OptionalFieldAppenderFactory.PARAM_PREFIX, params); return values; } @Override List<EntityBody> add(List<EntityBody> entities, final String resource, MultivaluedMap<String, String> queryParams); }
|
@Test public void 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)); }
|
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.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); }
|
OptionalFieldAppenderHelper { public EntityBody getEntityFromList(List<EntityBody> list, String field, String value) { if (list == null || field == null || value == null) { return null; } for (EntityBody e : list) { if (value.equals(e.get(field))) { return e; } } return null; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void 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); }
|
OptionalFieldAppenderHelper { public List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value) { List<EntityBody> results = new ArrayList<EntityBody>(); if (list == null || field == null || value == null) { return results; } for (EntityBody e : list) { if (value.equals(e.get(field))) { results.add(e); } } return results; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void 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()); }
|
OptionalFieldAppenderHelper { public List<String> getIdList(List<EntityBody> list, String field) { List<String> ids = new ArrayList<String>(); if (list == null || field == null) { return ids; } for (EntityBody e : list) { if (e.get(field) != null) { ids.add((String) e.get(field)); } } return ids; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void 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()); }
|
OptionalFieldAppenderHelper { public Set<String> getSectionIds(List<EntityBody> entities) { Set<String> sectionIds = new HashSet<String>(); for (EntityBody e : entities) { List<EntityBody> associations = (List<EntityBody>) e.get("studentSectionAssociation"); if (associations == null) { continue; } for (EntityBody association : associations) { sectionIds.add((String) association.get(ParameterConstants.SECTION_ID)); } } return sectionIds; } List<EntityBody> queryEntities(String resourceName, String key, List<String> values); List<EntityBody> queryEntities(String resourceName, NeutralQuery query); EntityBody getEntityFromList(List<EntityBody> list, String field, String value); List<EntityBody> getEntitySubList(List<EntityBody> list, String field, String value); List<String> getIdList(List<EntityBody> list, String field); Set<String> getSectionIds(List<EntityBody> entities); }
|
@Test public void 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()); }
|
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); }
|
@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")); }
|
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); }
|
@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()); }
|
StudentAssessmentOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentAssessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ASSESSMENTS, ParameterConstants.STUDENT_ID, studentIds); List<String> assessmentIds = optionalFieldAppenderHelper.getIdList(studentAssessments, ParameterConstants.ASSESSMENT_ID); List<EntityBody> assessments = optionalFieldAppenderHelper.queryEntities(ResourceNames.ASSESSMENTS, "_id", assessmentIds); for (EntityBody student : entities) { List<EntityBody> studentAssessmentsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAssessments, ParameterConstants.STUDENT_ID, (String) student.get("id")); for (EntityBody studentAssessment : studentAssessmentsForStudent) { EntityBody assessment = optionalFieldAppenderHelper.getEntityFromList(assessments, "id", (String) studentAssessment.get(ParameterConstants.ASSESSMENT_ID)); studentAssessment.put(PathConstants.ASSESSMENTS, assessment); } student.put(PathConstants.STUDENT_ASSESSMENTS, studentAssessmentsForStudent); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
@Test 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")); }
|
StudentTranscriptOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSectionAssociations = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_SECTION_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); List<String> sectionIds = optionalFieldAppenderHelper.getIdList(studentSectionAssociations, ParameterConstants.SECTION_ID); List<EntityBody> sections = optionalFieldAppenderHelper.queryEntities(ResourceNames.SECTIONS, "_id", sectionIds); List<EntityBody> studentAcademicRecords = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); List<String> studentAcademicRecordIds = optionalFieldAppenderHelper.getIdList(studentAcademicRecords, "id"); List<EntityBody> courseTranscripts = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_TRANSCRIPTS, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordIds); List<String> sessionIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.SESSION_ID); List<EntityBody> sessions = optionalFieldAppenderHelper .queryEntities(ResourceNames.SESSIONS, "_id", sessionIds); List<String> courseOfferingIds = optionalFieldAppenderHelper.getIdList(sections, ParameterConstants.COURSE_OFFERING_ID); List<EntityBody> courseOfferings = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSE_OFFERINGS, "_id", courseOfferingIds); List<String> courseIds = optionalFieldAppenderHelper.getIdList(courseOfferings, ParameterConstants.COURSE_ID); List<EntityBody> courses = optionalFieldAppenderHelper.queryEntities(ResourceNames.COURSES, "_id", courseIds); List<EntityBody> studentAcademicRecordsForStudents = optionalFieldAppenderHelper.queryEntities(ResourceNames.STUDENT_ACADEMIC_RECORDS, ParameterConstants.STUDENT_ID, studentIds); for (EntityBody student : entities) { String studentId = (String) student.get("id"); List<EntityBody> studentSectionAssociationsForStudent = optionalFieldAppenderHelper.getEntitySubList( studentSectionAssociations, ParameterConstants.STUDENT_ID, studentId); List<EntityBody> studentCourseTranscripts = new ArrayList<EntityBody>(); for (EntityBody studentSectionAssociationForStudent : studentSectionAssociationsForStudent) { String sectionId = (String) studentSectionAssociationForStudent.get(ParameterConstants.SECTION_ID); EntityBody sectionForStudent = optionalFieldAppenderHelper.getEntityFromList(sections, "id", sectionId); if (sectionForStudent == null) { continue; } EntityBody sessionForSection = optionalFieldAppenderHelper.getEntityFromList(sessions, "id", (String) sectionForStudent.get(ParameterConstants.SESSION_ID)); EntityBody courseOfferingForSection = optionalFieldAppenderHelper.getEntityFromList(courseOfferings, "id", (String) sectionForStudent.get(ParameterConstants.COURSE_OFFERING_ID)); if (courseOfferingForSection == null) { continue; } EntityBody courseForSection = optionalFieldAppenderHelper.getEntityFromList(courses, "id", (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); List<EntityBody> studentAcademicRecordsForStudent = optionalFieldAppenderHelper.getEntitySubList(studentAcademicRecordsForStudents, ParameterConstants.STUDENT_ID, studentId); List<String> studentAcademicRecordIdsForStudent = optionalFieldAppenderHelper.getIdList(studentAcademicRecordsForStudent, "id"); List<EntityBody> studentTranscriptsForStudent = new ArrayList<EntityBody>(); for (String studentAcademicRecordId : studentAcademicRecordIdsForStudent) { studentTranscriptsForStudent.addAll(optionalFieldAppenderHelper.getEntitySubList(courseTranscripts, ParameterConstants.STUDENT_ACADEMIC_RECORD_ID, studentAcademicRecordId)); } List<EntityBody> studentTranscriptsForStudentAndCourse = optionalFieldAppenderHelper.getEntitySubList( studentTranscriptsForStudent, ParameterConstants.COURSE_ID, (String) courseOfferingForSection.get(ParameterConstants.COURSE_ID)); studentCourseTranscripts.addAll(studentTranscriptsForStudentAndCourse); sectionForStudent.put(PathConstants.SESSIONS, sessionForSection); sectionForStudent.put(PathConstants.COURSES, courseForSection); studentSectionAssociationForStudent.put(PathConstants.SECTIONS, sectionForStudent); } EntityBody body = new EntityBody(); body.put(PathConstants.STUDENT_SECTION_ASSOCIATIONS, studentSectionAssociationsForStudent); body.put(PathConstants.COURSE_TRANSCRIPTS, studentCourseTranscripts); student.put(ParameterConstants.OPTIONAL_FIELD_TRANSCRIPT, body); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
@Test public void testApplyOptionalField() { List<EntityBody> entities = new ArrayList<EntityBody>(); EntityBody body = new EntityBody(); body.putAll(studentEntity.getBody()); body.put("id", studentEntity.getEntityId()); entities.add(body); entities = studentTranscriptOptionalFieldAppender.applyOptionalField(entities, null); assertEquals("Should match", 1, entities.size()); EntityBody transcripts = (EntityBody) entities.get(0).get("transcript"); assertNotNull("Should be not null", transcripts); List<EntityBody> studentSectionAssociations = (List<EntityBody>) transcripts.get("studentSectionAssociations"); assertNotNull("Should be not null", studentSectionAssociations); assertEquals("Should match", 2, studentSectionAssociations.size()); EntityBody section = (EntityBody) studentSectionAssociations.get(0).get("sections"); assertNotNull("Should not be null", section); assertNotNull("Should not be null", section.get("sessions")); assertEquals("Should match", "1999", ((EntityBody) section.get("sessions")).get("schoolYear")); assertEquals("Should match", section.get("sessionId"), ((EntityBody) section.get("sessions")).get("id")); assertNotNull("Should not be null", section.get("courses")); assertEquals("Should match", "Math", ((EntityBody) section.get("courses")).get("courseTitle")); assertEquals("Should match", "Math A", section.get("sectionname")); List<EntityBody> courseTranscripts = (List<EntityBody>) transcripts.get("courseTranscripts"); assertNotNull("Should not be null", courseTranscripts); assertEquals("Should match", 2, courseTranscripts.size()); assertEquals("Should match", "A", courseTranscripts.get(0).get("letterGradeEarned")); }
|
StudentGradeLevelOptionalFieldAppender implements OptionalFieldAppender { @Override public List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters) { List<String> studentIds = optionalFieldAppenderHelper.getIdList(entities, "id"); List<EntityBody> studentSchoolAssociationList = optionalFieldAppenderHelper.queryEntities( ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, ParameterConstants.STUDENT_ID, studentIds); if (studentSchoolAssociationList == null) { return entities; } Date currentDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (EntityBody student : entities) { String mostRecentGradeLevel = "Not Available"; String mostRecentSchool = ""; Date mostRecentEntry = null; try { for (EntityBody studentSchoolAssociation : studentSchoolAssociationList) { if (!studentSchoolAssociation.get(ParameterConstants.STUDENT_ID).equals(student.get("id"))) { continue; } if (studentSchoolAssociation.containsKey(EXIT_WITHDRAW_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(EXIT_WITHDRAW_DATE)); if (ssaDate.compareTo(currentDate) <= 0) { continue; } } if (studentSchoolAssociation.containsKey(ENTRY_DATE)) { Date ssaDate = sdf.parse((String) studentSchoolAssociation.get(ENTRY_DATE)); if (mostRecentEntry == null) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } else { if (ssaDate.compareTo(mostRecentEntry) > 0) { mostRecentEntry = ssaDate; mostRecentGradeLevel = (String) studentSchoolAssociation.get(ENTRY_GRADE_LEVEL); mostRecentSchool = (String) studentSchoolAssociation.get(SCHOOL_ID); } } } } } catch (Exception e) { String exceptionMessage = "Exception while retrieving current gradeLevel for student with id: " + student.get("id") + " Exception: " + e.getMessage(); LOG.debug(exceptionMessage); mostRecentGradeLevel = "Not Available"; } student.put(GRADE_LEVEL, mostRecentGradeLevel); student.put(SCHOOL_ID, mostRecentSchool); } return entities; } @Override List<EntityBody> applyOptionalField(List<EntityBody> entities, String parameters); }
|
@Test public void 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")); }
|
CustomEntityResource { @GET @Path("/") public Response read() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } EntityBody entityBody = entityDefinition.getService().getCustom(entityId); if (entityBody == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.status(Status.OK).entity(entityBody).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
@Test public void 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"); }
|
CustomEntityResource { @PUT @Path("/") public Response createOrUpdatePut(final EntityBody customEntity) { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().createOrUpdateCustom(entityId, customEntity); return Response.status(Status.NO_CONTENT).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
@Test public void 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 = ResourceUtil.getURI(uriInfo, resourceHelper.extractVersion(uriInfo.getPathSegments()), PathConstants.TEMP_MAP.get(entityDefinition.getResourceName()), entityId, PathConstants.CUSTOM_ENTITIES) .toString(); return Response.status(Status.CREATED).header("Location", uri).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
@Test public void 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); }
|
CustomEntityResource { @DELETE @Path("/") public Response delete() { if (entityDefinition == null) { return Response.status(Status.NOT_FOUND).build(); } entityDefinition.getService().deleteCustom(entityId); return Response.status(Status.NO_CONTENT).build(); } CustomEntityResource(final String entityId, final EntityDefinition entityDefinition,
final ResourceHelper resourceHelper); @GET @Path("/") Response read(); @PUT @Path("/") Response createOrUpdatePut(final EntityBody customEntity); @POST @Path("/") Response createOrUpdatePost(@Context final UriInfo uriInfo,
final EntityBody customEntity); @DELETE @Path("/") Response delete(); }
|
@Test public void 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("http: assertTrue("Should validate", validator.validate(new URI("http: }
|
QueryStringValidator implements URLValidator { @Override public boolean validate(URI url) { String queryString = url.getQuery(); if (queryString != null && !queryString.isEmpty()) { queryString = queryString.replaceAll(">", "").replaceAll("<", ""); for (AbstractBlacklistStrategy abstractBlacklistStrategy : validationStrategyList) { if (!abstractBlacklistStrategy.isValid("", queryString)) { return false; } } } return true; } @Override boolean validate(URI url); }
|
@Test public void 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")))); }
|
VersionFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest containerRequest) { List<PathSegment> segments = containerRequest.getPathSegments(); if (!segments.isEmpty()) { String version = segments.get(0).getPath(); boolean isBulkNonVersion = version.equals("bulk"); SortedSet<String> minorVersions = resourceEndPoint.getNameSpaceMappings().get(version); String newVersion = null; if(isBulkNonVersion || (segments.size() > 1 && segments.get(1).getPath().equals("bulk"))) { if (!isBulkNonVersion) { segments.remove(0); } else { version = ""; } newVersion = getLatestApiVersion(version); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } else if ((minorVersions != null) && !minorVersions.isEmpty()) { segments.remove(0); newVersion = version + "." + minorVersions.last(); updateContainerRequest(containerRequest, segments, newVersion); LOG.info("Version Rewrite: {} --> {}", new Object[] { version, newVersion }); } } return containerRequest; } @Override ContainerRequest filter(ContainerRequest containerRequest); String getLatestApiVersion(String requestedVersion); }
|
@Test public void 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"); }
|
DateSearchFilter implements ContainerRequestFilter { @Override public ContainerRequest filter(ContainerRequest request) { request.getProperties().put("startTime", System.currentTimeMillis()); List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null ){ validateNotVersionOneZero(request); validateDateSearchUri(request); validateNonTwoPartUri(request); } return request; } @Override ContainerRequest filter(ContainerRequest request); }
|
@Test(expected = QueryParseException.class) public void 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); }
|
SessionRangeCalculator { public SessionDateInfo findDateRange(String schoolYearRange) { Pair<String, String> years = parseDateRange(schoolYearRange); Set<String> edOrgIds = edOrgHelper.getDirectEdorgs(); Iterable<Entity> sessions = getSessions(years, edOrgIds); return findMinMaxDates(sessions); } SessionDateInfo findDateRange(String schoolYearRange); }
|
@Test public void 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()); }
|
DateFilterCriteriaGenerator { public void generate(ContainerRequest request) { List<String> schoolYears = request.getQueryParameters().get(ParameterConstants.SCHOOL_YEARS); if (schoolYears != null && schoolYears.size() > 0) { String schoolYearRange = schoolYears.get(0); SessionDateInfo sessionDateInfo = sessionRangeCalculator.findDateRange(schoolYearRange); EntityFilterInfo entityFilterInfo = entityIdentifier.findEntity(request.getPath()); GranularAccessFilter filter = new DateFilterCriteriaBuilder().forEntity(entityFilterInfo.getEntityName()) .connectedBy(entityFilterInfo.getConnectingEntityList()) .withDateAttributes(entityFilterInfo.getBeginDateAttribute(), entityFilterInfo.getEndDateAttribute()) .withSessionAttribute(entityFilterInfo.getSessionAttribute()) .startingFrom(sessionDateInfo.getStartDate()) .endingTo(sessionDateInfo.getEndDate()) .withSessionIds(sessionDateInfo.getSessionIds()) .build(); granularAccessFilterProvider.storeGranularAccessFilter(filter); } } void generate(ContainerRequest request); }
|
@Test public void 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); }
|
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); }
|
@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()); }
|
ApplicationInitializer { @PostConstruct public void init() { if (bootstrapProperties.isReadable()) { Properties sliProp; try { sliProp = PropertiesLoaderUtils.loadProperties(bootstrapProperties); processTemplates(sliProp); } catch (IOException e) { LOG.error("Could not load boostrap properties.", e); } } else { LOG.warn("Could not find bootstrap properties at {}.", bootstrapProperties); } } @PostConstruct void init(); }
|
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void 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()); }
|
RealmInitializer { @PostConstruct public void bootstrap() { Map<String, Object> bootstrapAdminRealmBody = createAdminRealmBody(); createOrUpdateRealm(ADMIN_REALM_ID, bootstrapAdminRealmBody); if (!isSandbox) { ensurePropertySet("bootstrap.developer.realm.name", devRealmName); ensurePropertySet("bootstrap.developer.realm.uniqueId", devUniqueId); ensurePropertySet("bootstrap.developer.realm.idpId", devIdpId); ensurePropertySet("bootstrap.developer.realm.redirectEndpoint", devRedirectEndpoint); Map<String, Object> bootstrapDeveloperRealmBody = createDeveloperRealmBody(); createOrUpdateRealm(devUniqueId, bootstrapDeveloperRealmBody); } } @PostConstruct void bootstrap(); static final String ADMIN_REALM_ID; }
|
@Test(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("roles", groups); rolesBody.put("customRights", new ArrayList<String>()); repository.create(ROLES, rolesBody); return groups.size(); } else { LOG.warn("Null realm id --> not building roles."); } return 0; } void dropAndBuildRoles(String realmId); void dropRoles(String realmId); int buildRoles(String realmId); List<Map<String, Object>> getDefaultRoles(); void setRepository(Repository<Entity> repository); static final String EDUCATOR; static final String TEACHER; static final String AGGREGATE_VIEWER; static final String SPECIALIST_CONSULTANT; static final String IT_ADMINISTRATOR; static final String SCHOOL_ADMIN; static final String LEA_ADMIN; static final String LEADER; static final String PRINCIPAL; static final String SUPERINTENDENT; static final String STUDENT; static final String PARENT; static final String ROLES; static final String LEA_ADMINISTRATOR; static final String SEA_ADMINISTRATOR; static final String APP_DEVELOPER; static final String SLC_OPERATOR; static final String REALM_ADMINISTRATOR; static final String INGESTION_USER; static final String SANDBOX_SLC_OPERATOR; static final String SANDBOX_ADMINISTRATOR; }
|
@Test public void testAllRolesCreated() throws Exception { assertTrue(roleInitializer.buildRoles("myRealmId") == 6); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.