method2testcases
stringlengths
118
6.63k
### Question: SemanticSelector extends HashMap<Type, List<SelectorElement>> implements SelectorQueryVisitable { @Override public String toString() { final StringBuilder builder = new StringBuilder(); for (final Map.Entry<Type, List<SelectorElement>> item : this.entrySet()) { final List<SelectorElement> elements = item.getValue(); builder.append("["); builder.append(StringUtils.join(elements, ',')); builder.append("]"); } return builder.toString(); } void addSelector(final Type type, final SelectorElement se); @Override SelectorQueryPlan accept(SelectorQueryVisitor selectorQueryVisitor); @Override String toString(); }### Answer: @Test public void testToString() { assertTrue(selector.toString().isEmpty()); }
### Question: SemanticSelector extends HashMap<Type, List<SelectorElement>> implements SelectorQueryVisitable { @Override public SelectorQueryPlan accept(SelectorQueryVisitor selectorQueryVisitor) { return selectorQueryVisitor.visit(this); } void addSelector(final Type type, final SelectorElement se); @Override SelectorQueryPlan accept(SelectorQueryVisitor selectorQueryVisitor); @Override String toString(); }### Answer: @Test public void testVisitor() { final SelectorQueryVisitor visitor = mock(SelectorQueryVisitor.class); selector.accept(visitor); verify(visitor).visit(selector); }
### Question: DefaultSelectorStore implements SelectorRepository { @Override public SemanticSelector getSelector(String type) { return defaultSelectors.containsKey(type) ? defaultSelectors.get(type) : getFallBackSelector(type); } @Override SemanticSelector getSelector(String type); static final String DEFAULT_SELECTOR_TYPE_KEY; static final String DEFAULT_SELECTOR_VALUE_KEY; static final String DEFAULT_SELECTOR_RESOURCE_FILENAME; static final Map<String, Object> FALLBACK_SELECTOR; }### Answer: @Test public void testSuccessfulLoadOfData() { final ClassType studentType = provider.getClassType("Student"); final ClassType studentSectionAssociationType = provider.getClassType("StudentSectionAssociation"); final ClassType sectionType = provider.getClassType("Section"); SemanticSelector sectionSelector = defaultSelectorRepository.getSelector("Section"); assertNotNull("Should not be null", sectionSelector); List<SelectorElement> elements = sectionSelector.get(sectionType); SelectorElement element = elements.get(0); assertTrue("Should be true", element instanceof BooleanSelectorElement); assertEquals("Should match", "sequenceOfCourse", element.getElementName()); SemanticSelector studentSelector = defaultSelectorRepository.getSelector("Student"); assertNotNull("Should not be null", studentSelector); elements = studentSelector.get(studentType); for (SelectorElement e : elements) { if (e instanceof IncludeXSDSelectorElement) { assertEquals("Should match", studentType, e.getLHS()); } else if (e instanceof BooleanSelectorElement) { assertEquals("Should match", studentSectionAssociationType, e.getLHS()); } else { fail("unknown type"); } } SemanticSelector studentSectionAssociationSelector = defaultSelectorRepository.getSelector("StudentSectionAssociation"); assertNotNull("Should not be null", studentSectionAssociationSelector); elements = studentSectionAssociationSelector.get(studentSectionAssociationType); element = elements.get(0); assertTrue("Should be true", element instanceof IncludeXSDSelectorElement); } @Test public void assertGracefulHandlingOfInvalidTypeDefaultSelector() { assertNull("Should be null", defaultSelectorRepository.getSelector("type1")); } @Test public void assertGracefulHandlingOfMissingDefaultSelector() { final ClassType schoolType = provider.getClassType("School"); SemanticSelector schoolSelector = defaultSelectorRepository.getSelector("School"); assertNotNull("Should not be null", schoolSelector); List<SelectorElement> elements = schoolSelector.get(schoolType); assertEquals("Should match", 1, elements.size()); SelectorElement element = elements.get(0); assertTrue("Should be true", element instanceof IncludeXSDSelectorElement); }
### Question: DefaultLogicalEntity implements LogicalEntity { @Override public List<EntityBody> getEntities(final ApiQuery apiQuery, final String resourceName) { if (apiQuery == null) { throw new IllegalArgumentException("apiQuery"); } if (apiQuery.getSelector() == null) { throw new UnsupportedSelectorException("No selector to parse"); } final EntityDefinition typeDef = resourceHelper.getEntityDefinition(resourceName); final ClassType entityType = provider.getClassType(StringUtils.capitalize(typeDef.getType())); if (UNSUPPORTED_RESOURCE_LIST.contains(resourceName)) { throw new UnsupportedSelectorException("Selector is not supported yet for this resource"); } final SemanticSelector semanticSelector = selectorSemanticModel.parse(apiQuery.getSelector(), entityType); final SelectorQuery selectorQuery = selectorQueryEngine.assembleQueryPlan(semanticSelector); return selectorDocument.aggregate(selectorQuery, apiQuery); } @Override List<EntityBody> getEntities(final ApiQuery apiQuery, final String resourceName); }### Answer: @Test public void testCreateEntities() { final EntityDefinition mockEntityDefinition = mock(EntityDefinition.class); when(mockEntityDefinition.getType()).thenReturn("TEST"); when(resourceHelper.getEntityDefinition(anyString())).thenReturn(mockEntityDefinition); @SuppressWarnings("unchecked") final SelectorQuery mockPlan = mock(SelectorQuery.class); when(selectorQueryEngine.assembleQueryPlan(any(SemanticSelector.class))).thenReturn(mockPlan); final ApiQuery apiQuery = mock(ApiQuery.class); when(apiQuery.getSelector()).thenReturn(new HashMap<String, Object>()); @SuppressWarnings("unchecked") final List<EntityBody> mockEntityList = mock(List.class); when(selectorDocument.aggregate(mockPlan, apiQuery)).thenReturn(mockEntityList); final List<EntityBody> entityList = logicalEntity.getEntities(apiQuery, "TEST"); assertEquals(mockEntityList, entityList); }
### Question: URITranslator { public void translate(ContainerRequest request) { String uri = request.getPath(); List<PathSegment> segments = request.getPathSegments(); String version = PathConstants.V1; if (!segments.isEmpty()) { version = segments.get(0).getPath(); } for (Map.Entry<String, URITranslation> entry : uriTranslationMap.entrySet()) { String key = entry.getKey(); if (uri.contains(key)) { String newPath = uriTranslationMap.get(key).translate(request.getPath()); if (!newPath.equals(uri)) { request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(newPath).build()); } } } } URITranslator(); void setRepository(PagingRepositoryDelegate<Entity> repository); void translate(ContainerRequest request); URITranslation getTranslator(String uri); }### Answer: @Test public void testTranslate() throws Exception { List<Entity> learningObjectiveList = new ArrayList<Entity>(); Entity loEntity = mock(Entity.class); Map<String, Object> body = new HashMap<String, Object>(); body.put("parentLearningObjective", "456"); when(loEntity.getEntityId()).thenReturn("123"); when(loEntity.getBody()).thenReturn(body); learningObjectiveList.add(loEntity); when(repository.findAll(anyString(), any(NeutralQuery.class))).thenReturn(learningObjectiveList); String newPath = translator.getTranslator("parentLearningObjective").translate("v1/learningObjectives/123/parentLearningObjectives"); assertTrue("Should match new uri", "learningObjectives/456".equals(newPath)); }
### Question: EntityBody extends HashMap<String, Object> { public List<String> getValues(String key) { List<String> valueList = new ArrayList<String>(); Object value = this.get(key); if (value instanceof String) { valueList.add((String) value); } else if (value instanceof List<?>) { for (Object subValues : (List<?>) value) { valueList.add(subValues.toString()); } } return valueList; } EntityBody(); EntityBody(Map<? extends String, ? extends Object> m); List<String> getValues(String key); }### Answer: @Test public void testGetId() { EntityBody entityBody = new EntityBody(createTestMap()); List<String> list1 = entityBody.getValues("key1"); assertNotNull("List should not be null", list1); assertEquals("List should have 1 value", list1.size(), 1); assertEquals("List value should be original id", list1.get(0), "stringValue1"); List<String> list2 = entityBody.getValues("key2"); assertNotNull("List should not be null", list2); assertEquals("List should have 1 value", list2.size(), 1); assertEquals("List value should be original id", list2.get(0), "stringValue2"); List<String> list3 = entityBody.getValues("key3"); assertNotNull("List should not be null", list3); assertEquals("List should have 2 values", list3.size(), 2); assertEquals("List value 1 should be original id", list3.get(0), "stringInList1"); assertEquals("List value 2 should be original id", list3.get(1), "stringInList2"); List<String> list4 = entityBody.getValues("key4"); assertNotNull("List should not be null", list4); assertEquals("List should have 0 values", list4.size(), 0); }
### Question: EntityResponse extends HashMap<String, Object> { public EntityResponse(String entityCollectionName, Object object) { super(); setEntityCollectionName(entityCollectionName); put(this.entityCollectionName, object); } EntityResponse(String entityCollectionName, Object object); Object getEntity(); final void setEntityCollectionName(String entityCollectionName); String getEntityCollectionName(); }### Answer: @Test public void testEntityResponse() { Map<String, String> map = new HashMap<String, String>(); map.put("testkey", "testvalue"); EntityResponse response = new EntityResponse("testcollection", map); assertNotNull("Should not be null", response.getEntity()); Map<String, String> testMap = (Map<String, String>) response.getEntity(); assertEquals("Should match", "testvalue", testMap.get("testkey")); }
### Question: EntityResponse extends HashMap<String, Object> { public Object getEntity() { return this.get(entityCollectionName); } EntityResponse(String entityCollectionName, Object object); Object getEntity(); final void setEntityCollectionName(String entityCollectionName); String getEntityCollectionName(); }### Answer: @Test public void testEntityResponseNullCollectionName() { EntityResponse response = new EntityResponse(null, new HashMap<String, String>()); assertNotNull("Should not be null", response.getEntity()); }
### Question: TenantIdToDbName { public static String convertTenantIdToDbName(String tenantId) { if (tenantId != null) { return TENANT_ID_CACHE.getUnchecked(tenantId); } else { return tenantId; } } static String convertTenantIdToDbName(String tenantId); }### Answer: @Test public void testConvertTenantIdToDbName() { Assert.assertEquals("7be07aaf460d593a323d0db33da05b64bfdcb3a5", TenantIdToDbName.convertTenantIdToDbName("ABCDE")); Assert.assertEquals("782a35eb5b9cd3e771047a60381e1274d76bc069", TenantIdToDbName.convertTenantIdToDbName("ABC.DE")); Assert.assertEquals("1072a2a56f16654387d030014968a48f04ca7488", TenantIdToDbName.convertTenantIdToDbName(" ABC DE ")); Assert.assertEquals("f89b39e01f5b1bb76655211472cd71274766070e", TenantIdToDbName.convertTenantIdToDbName("$ABCDE")); Assert.assertEquals("8e1cea182e0e0499fe1e0fe28e02d9ffb47ba098", TenantIdToDbName.convertTenantIdToDbName("ABC/DE")); }
### Question: DateHelper { public boolean isFieldExpired(Map<String, Object> body) { for (String key : Arrays.asList("endDate", "exitWithdrawDate")) { if (body.containsKey(key)) { return isFieldExpired(body, key, false); } } return false; } String getFilterDate(boolean useGracePeriod); DateTime getNowMinusGracePeriod(); boolean isFieldExpired(Map<String, Object> body); boolean isFieldExpired(Map<String, Object> body, String fieldName); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); DateTime getDate(Map<String, Object> body, String fieldName); boolean isLhsBeforeRhs(DateTime lhs, DateTime rhs); static DateTimeFormatter getDateTimeFormat(); static Criteria getExpiredCriteria(); static Criteria getExpiredCriteria(String endDateField); }### Answer: @Test public void testIsFieldExpired() { Map<String, Object> body = generateEntityBody(); Assert.assertTrue(dateHelper.isFieldExpired(body, "endDate", false)); body.put("exitWithdrawDate", "2070-10-25"); Assert.assertFalse(dateHelper.isFieldExpired(body, "exitWithdrawDate", false)); }
### Question: DateHelper { public DateTime getDate(Map<String, Object> body, String fieldName) { DateTime date = null; if (body.get(fieldName) != null) { date = DateTime.parse((String) body.get(fieldName), FMT); } return date; } String getFilterDate(boolean useGracePeriod); DateTime getNowMinusGracePeriod(); boolean isFieldExpired(Map<String, Object> body); boolean isFieldExpired(Map<String, Object> body, String fieldName); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); DateTime getDate(Map<String, Object> body, String fieldName); boolean isLhsBeforeRhs(DateTime lhs, DateTime rhs); static DateTimeFormatter getDateTimeFormat(); static Criteria getExpiredCriteria(); static Criteria getExpiredCriteria(String endDateField); }### Answer: @Test public void testGetDate() { Map<String, Object> body = generateEntityBody(); DateTime result = dateHelper.getDate(body, "endDate"); Assert.assertEquals(2010, result.getYear()); Assert.assertEquals(07, result.getMonthOfYear()); Assert.assertEquals(10, result.getDayOfMonth()); result = dateHelper.getDate(body, "expirationDate"); Assert.assertNull(result); }
### Question: SmooksEdFi2SLITransformer extends EdFi2SLITransformer { @Override public List<List<SimpleEntity>> handle(List<NeutralRecord> items, AbstractMessageReport report, ReportStats reportStats) { return null; } @Override List<SimpleEntity> transform(NeutralRecord item, AbstractMessageReport report, ReportStats reportStats); Map<String, Smooks> getSmooksConfigs(); void setSmooksConfigs(Map<String, Smooks> smooksConfigs); @Override List<List<SimpleEntity>> handle(List<NeutralRecord> items, AbstractMessageReport report, ReportStats reportStats); @Override String getStageName(); }### Answer: @SuppressWarnings("deprecation") @Test public void testCreateAssessmentEntity() { EntityConfigFactory entityConfigurations = new EntityConfigFactory(); MongoEntityRepository mockedEntityRepository = mock(MongoEntityRepository.class); NeutralRecord assessmentRC = createAssessmentNeutralRecord(true); entityConfigurations.setResourceLoader(new DefaultResourceLoader()); entityConfigurations.setSearchPath("classpath:smooksEdFi2SLI/"); transformer.setEntityRepository(mockedEntityRepository); transformer.setEntityConfigurations(entityConfigurations); DeterministicIdResolver mockDidResolver = Mockito.mock(DeterministicIdResolver.class); transformer.setDIdResolver(mockDidResolver); List<Entity> le = new ArrayList<Entity>(); le.add(createAssessmentEntity(true)); when( mockedEntityRepository.findByQuery(eq("assessment"), Mockito.any(Query.class), eq(0), eq(0))).thenReturn(le); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); List<SimpleEntity> res = transformer.handle(assessmentRC, errorReport, reportStats); verify(mockedEntityRepository).findByQuery(eq("assessment"), Mockito.any(Query.class), eq(0), eq(0)); Assert.assertNotNull(res); Assert.assertEquals(ASSESSMENT_TITLE, res.get(0).getBody().get("assessmentTitle")); Assert.assertEquals(TENANT_ID, res.get(0).getMetaData().get(TENANT_ID_FIELD)); Assert.assertEquals(STUDENT_ID, res.get(0).getMetaData().get(EXTERNAL_ID_FIELD)); }
### Question: DeterministicUUIDGeneratorStrategy implements UUIDGeneratorStrategy { protected static UUID generateUuid(byte[] data) { ByteBuffer byteBuffer = ByteBuffer.wrap(data); long msb = byteBuffer.getLong(0); long lsb = byteBuffer.getLong(8); UUID uuid = new UUID(msb, lsb); return uuid; } @Override String generateId(); @Override String generateId(NaturalKeyDescriptor naturalKeyDescriptor); static final String DIGEST_ALGORITHM; }### Answer: @Test public void testGenerateUuid() { byte[] testBytes = "abcdefghij1234567890".getBytes(); UUID uuid = DeterministicUUIDGeneratorStrategy.generateUuid(testBytes); assertNotNull("uuid must not be null", uuid); assertEquals("61626364-6566-6768-696a-313233343536", uuid.toString()); }
### Question: EntityPersistHandler extends AbstractIngestionHandler<SimpleEntity, Entity> implements InitializingBean { public void setEntityRepository(Repository<Entity> entityRepository) { this.entityRepository = entityRepository; } @Override void afterPropertiesSet(); void setEntityRepository(Repository<Entity> entityRepository); EntityConfigFactory getEntityConfigurations(); void setEntityConfigurations(EntityConfigFactory entityConfigurations); @Override String getStageName(); static final Logger LOG; }### Answer: @Test public void testCreateStudentEntity() { MongoEntityRepository entityRepository = mock(MongoEntityRepository.class); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria(METADATA_BLOCK + "." + REGION_ID_FIELD, NeutralCriteria.OPERATOR_EQUAL, REGION_ID, false)); query.addCriteria(new NeutralCriteria(METADATA_BLOCK + "." + EXTERNAL_ID_FIELD, NeutralCriteria.OPERATOR_EQUAL, STUDENT_ID, false)); SimpleEntity studentEntity = createStudentEntity(true); List<Entity> le = new ArrayList<Entity>(); le.add(studentEntity); when(entityRepository.findAll(eq("student"), any(NeutralQuery.class))).thenReturn(le); when(entityRepository.updateWithRetries(studentEntity.getType(), studentEntity, totalRetries)).thenReturn(true); entityPersistHandler.setEntityRepository(entityRepository); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); entityPersistHandler.handle(studentEntity, errorReport, reportStats); verify(entityRepository).updateWithRetries(studentEntity.getType(), studentEntity, totalRetries); le.clear(); SimpleEntity studentEntity2 = createStudentEntity(false); le.add(studentEntity2); entityPersistHandler.handle(studentEntity2, errorReport, reportStats); verify(entityRepository).createWithRetries(studentEntity.getType(), null, studentEntity.getBody(), studentEntity.getMetaData(), "student", totalRetries); Assert.assertFalse("Error report should not contain errors", reportStats.hasErrors()); } @Test public void testCreateAndDeleteStudentEntity() { MongoEntityRepository entityRepository = mock(MongoEntityRepository.class); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria(METADATA_BLOCK + "." + REGION_ID_FIELD, NeutralCriteria.OPERATOR_EQUAL, REGION_ID, false)); query.addCriteria(new NeutralCriteria(METADATA_BLOCK + "." + EXTERNAL_ID_FIELD, NeutralCriteria.OPERATOR_EQUAL, STUDENT_ID, false)); SimpleEntity studentEntity = createStudentEntity(true); List<Entity> le = new ArrayList<Entity>(); le.add(studentEntity); when(entityRepository.findAll(eq("student"), any(NeutralQuery.class))).thenReturn(le); when(entityRepository.updateWithRetries(studentEntity.getType(), studentEntity, totalRetries)).thenReturn(true); CascadeResult mockCascadeResult = new CascadeResult(); mockCascadeResult.setStatus(CascadeResult.Status.SUCCESS); when(entityRepository.safeDelete(eq(studentEntity), eq(studentEntity.getEntityId()), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(), anyInt(), any(AccessibilityCheck.class))).thenReturn(mockCascadeResult); entityPersistHandler.setEntityRepository(entityRepository); AbstractMessageReport errorReport = new DummyMessageReport(); ReportStats reportStats = new SimpleReportStats(); entityPersistHandler.handle(studentEntity, errorReport, reportStats); verify(entityRepository).updateWithRetries(studentEntity.getType(), studentEntity, totalRetries); studentEntity.setAction( ActionVerb.CASCADE_DELETE); studentEntity.setActionAttributes(ImmutableMap.of( "Force", "true", "LogViolations", "true" )); entityPersistHandler.handle( studentEntity, errorReport, reportStats); verify(entityRepository).safeDelete(studentEntity, studentEntity.getEntityId(), true, false, true, true, null, null); Assert.assertFalse("Error report should not contain errors", reportStats.hasErrors()); }
### Question: ShardType1UUIDGeneratorStrategy implements UUIDGeneratorStrategy { @Override public String generateId() { StringBuilder builder = new StringBuilder(); char c1 = (char) (r.nextInt(26) + 'a'); char c2 = (char) (r.nextInt(26) + 'a'); builder.append(new DateTime().getYear()); builder.append(c1); builder.append(c2); builder.append("-"); builder.append(generator.generate().toString()); String uuid = builder.toString(); return uuid; } @Override String generateId(); @Override String generateId(NaturalKeyDescriptor naturalKeyDescriptor); }### Answer: @Test public void testShardType1UUIDGenerator() { ShardType1UUIDGeneratorStrategy uuidGen = new ShardType1UUIDGeneratorStrategy(); String uuid = uuidGen.generateId(); assertNotNull(uuid); assertEquals('1', uuid.charAt(22)); assertEquals(43, uuid.length()); }
### Question: LdapServiceImpl implements LdapService { @SuppressWarnings("rawtypes") @Override public User getUser(String realm, String uid) { AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, userObjectClass)).and(new EqualsFilter(userSearchAttribute, uid)); DistinguishedName dn = new DistinguishedName("ou=" + realm); User user; try { List userList = ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] { "*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper()); if (userList == null || userList.size() == 0) { throw new EmptyResultDataAccessException(1); } else if (userList.size() > 1) { throw new IncorrectResultSizeDataAccessException("User must be unique", 1); } user = (User) userList.get(0); user.setUid(uid); user.setGroups(getGroupNames(getUserGroups(realm, uid))); } catch (EmptyResultDataAccessException e) { return null; } return user; } @SuppressWarnings("rawtypes") @Override User getUser(String realm, String uid); @SuppressWarnings("unchecked") @Override Collection<Group> getUserGroups(String realm, String uid); @Override void removeUser(String realm, String uid); @Override String createUser(String realm, User user); @Override boolean updateUser(String realm, User user); @Override Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames, final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant); @Override Collection<User> findUsersByAttributes(String realm, Collection<String> attributes); @Override Group getGroup(String realm, String groupName); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant, Collection<String> edorgs); @Override boolean addUserToGroup(String realm, Group group, User user); @Override boolean removeUserFromGroup(String realm, Group group, User user); @Override boolean updateGroup(String realm, Group group); @Override void setLdapTemplate(LdapTemplate ldapTemplate); static final String OBJECTCLASS; }### Answer: @Test public void testGetUser() { User slcoperator = ldapService.getUser("LocalNew", "slcoperator"); assertNotNull(slcoperator); assertTrue(slcoperator.getGroups().contains("SLC Operator")); assertTrue(slcoperator.getEmail().equals("[email protected]")); assertTrue(slcoperator.getUid().equals("slcoperator")); assertNotNull(slcoperator.getHomeDir()); assertNotNull(slcoperator.getGivenName()); assertNotNull(slcoperator.getSn()); assertNotNull(slcoperator.getFullName()); assertNull(slcoperator.getTenant()); assertNull(slcoperator.getEdorg()); assertNotNull(slcoperator.getCreateTime()); assertNotNull(slcoperator.getModifyTime()); }
### Question: LdapServiceImpl implements LdapService { @Override public Group getGroup(String realm, String groupName) { DistinguishedName dn = new DistinguishedName("ou=" + realm); AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, groupObjectClass)).and(new EqualsFilter("cn", groupName)); try { return (Group) ldapTemplate.searchForObject(dn, filter.toString(), new GroupContextMapper()); } catch (EmptyResultDataAccessException e) { return null; } } @SuppressWarnings("rawtypes") @Override User getUser(String realm, String uid); @SuppressWarnings("unchecked") @Override Collection<Group> getUserGroups(String realm, String uid); @Override void removeUser(String realm, String uid); @Override String createUser(String realm, User user); @Override boolean updateUser(String realm, User user); @Override Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames, final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant); @Override Collection<User> findUsersByAttributes(String realm, Collection<String> attributes); @Override Group getGroup(String realm, String groupName); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant, Collection<String> edorgs); @Override boolean addUserToGroup(String realm, Group group, User user); @Override boolean removeUserFromGroup(String realm, Group group, User user); @Override boolean updateGroup(String realm, Group group); @Override void setLdapTemplate(LdapTemplate ldapTemplate); static final String OBJECTCLASS; }### Answer: @Test public void testGetGroup() { Group slcoperatorGroup = ldapService.getGroup("LocalNew", "SLC Operator"); assertNotNull(slcoperatorGroup); assertEquals("SLC Operator", slcoperatorGroup.getGroupName()); assertTrue(slcoperatorGroup.getMemberUids().contains("slcoperator")); }
### Question: LdapServiceImpl implements LdapService { @SuppressWarnings("unchecked") @Override public Collection<Group> getUserGroups(String realm, String uid) { DistinguishedName dn = new DistinguishedName("ou=" + realm); AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, groupObjectClass)).and(new EqualsFilter(groupSearchAttribute, uid)); List<Group> groups = ldapTemplate.search(dn, filter.toString(), new GroupContextMapper()); return groups; } @SuppressWarnings("rawtypes") @Override User getUser(String realm, String uid); @SuppressWarnings("unchecked") @Override Collection<Group> getUserGroups(String realm, String uid); @Override void removeUser(String realm, String uid); @Override String createUser(String realm, User user); @Override boolean updateUser(String realm, User user); @Override Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames, final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant); @Override Collection<User> findUsersByAttributes(String realm, Collection<String> attributes); @Override Group getGroup(String realm, String groupName); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant, Collection<String> edorgs); @Override boolean addUserToGroup(String realm, Group group, User user); @Override boolean removeUserFromGroup(String realm, Group group, User user); @Override boolean updateGroup(String realm, Group group); @Override void setLdapTemplate(LdapTemplate ldapTemplate); static final String OBJECTCLASS; }### Answer: @Test public void testGetUserGroups() { Collection<Group> groups = ldapService.getUserGroups("LocalNew", "slcoperator"); assertNotNull(groups); Collection<String> groupNames = new ArrayList<String>(); for (Group group : groups) { groupNames.add(group.getGroupName()); } assertTrue(groupNames.contains("SLC Operator")); }
### Question: LdapServiceImpl implements LdapService { @Override public Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames, final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs) { Collection<String> allowed = allowedGroupNames; Collection<String> disallowed = disallowedGroupNames; if (allowed == null) { allowed = new LinkedList<String>(); } if (disallowed == null) { disallowed = new LinkedList<String>(); } Set<String> allowedUsers = new HashSet<String>(); Map<String, List<String>> uidToGroupsMap = new HashMap<String, List<String>>(); for (String groupName : allowed) { Group group = getGroup(realm, groupName); if (group != null) { List<String> memberUids = group.getMemberUids(); if (memberUids != null && memberUids.size() > 0) { for (String memberUid : memberUids) { if (uidToGroupsMap.containsKey(memberUid)) { uidToGroupsMap.get(memberUid).add(groupName); } else { List<String> uidGroupNames = new ArrayList<String>(); uidGroupNames.add(groupName); uidToGroupsMap.put(memberUid, uidGroupNames); } allowedUsers.add(memberUid); } } } } for (String groupName : disallowed) { Group group = getGroup(realm, groupName); if (group != null) { allowedUsers.removeAll(group.getMemberUids()); } } AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, userObjectClass)); OrFilter orFilter = new OrFilter(); for (String uid : allowedUsers) { orFilter.or(new EqualsFilter(userSearchAttribute, uid)); } filter.and(orFilter); DistinguishedName dn = new DistinguishedName("ou=" + realm); @SuppressWarnings("unchecked") Collection<User> users = (ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] { "*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper())); for (User user : users) { user.setGroups(uidToGroupsMap.get(user.getUid())); } if (tenant != null) { users = filterByTenant(users, tenant); } if (edorgs != null) { users = filterByEdorgs(users, edorgs); } return users; } @SuppressWarnings("rawtypes") @Override User getUser(String realm, String uid); @SuppressWarnings("unchecked") @Override Collection<Group> getUserGroups(String realm, String uid); @Override void removeUser(String realm, String uid); @Override String createUser(String realm, User user); @Override boolean updateUser(String realm, User user); @Override Collection<User> findUsersByGroups(String realm, final Collection<String> allowedGroupNames, final Collection<String> disallowedGroupNames, String tenant, Collection<String> edorgs); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant); @Override Collection<User> findUsersByAttributes(String realm, Collection<String> attributes); @Override Group getGroup(String realm, String groupName); @Override Collection<User> findUsersByGroups(String realm, Collection<String> groupNames, String tenant, Collection<String> edorgs); @Override boolean addUserToGroup(String realm, Group group, User user); @Override boolean removeUserFromGroup(String realm, Group group, User user); @Override boolean updateGroup(String realm, Group group); @Override void setLdapTemplate(LdapTemplate ldapTemplate); static final String OBJECTCLASS; }### Answer: @Test public void testFindUserByGroups() { String[] groups = new String[] { "SEA Administrator" }; Collection<User> users = ldapService.findUsersByGroups("LocalNew", Arrays.asList(groups)); assertNotNull(users); }
### Question: NaturalKeyDescriptor { public NaturalKeyDescriptor() { this(null, null, null, null); } NaturalKeyDescriptor(); NaturalKeyDescriptor(Map<String, String> naturalKeys); NaturalKeyDescriptor(Map<String, String> naturalKeys, String tenantId, String entityType, String parentId); @Override boolean equals(Object o); @Override int hashCode(); Map<String, String> getNaturalKeys(); void setNaturalKeys(Map<String, String> naturalKeys); String getTenantId(); void setTenantId(String tenantId); String getEntityType(); void setEntityType(String entityType); boolean isNaturalKeysNotNeeded(); void setNaturalKeysNotNeeded(boolean naturalKeysNotNeeded); String getParentId(); void setParentId(String parentId); }### Answer: @Test public void testNaturalKeyDescriptor() { NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(); Map<String, String> naturalKeys = naturalKeyDescriptor.getNaturalKeys(); assertNotNull("naturalKeys is not null", naturalKeys); assertEquals("naturalKeys has 0 natural keys", 0, naturalKeys.size()); assertEquals("tenantId is empty", "", naturalKeyDescriptor.getTenantId()); assertEquals("entityType is empty", "", naturalKeyDescriptor.getEntityType()); NaturalKeyDescriptor naturalKeyDescriptor2 = new NaturalKeyDescriptor(); assertTrue(naturalKeyDescriptor.equals(naturalKeyDescriptor2)); }
### Question: ContainerDocumentHolder { public ContainerDocument getContainerDocument(final String entityName) { return containerDocumentMap.get(entityName); } ContainerDocumentHolder(); ContainerDocumentHolder(final Map<String, ContainerDocument> containerDocumentMap); ContainerDocument getContainerDocument(final String entityName); boolean isContainerDocument(final String entityName); }### Answer: @Test public void testGetContainerDocument() { final Map<String, ContainerDocument> testContainer = createContainerMap(); testHolder = new ContainerDocumentHolder(testContainer); assertEquals(testContainer.get("test"), testHolder.getContainerDocument("test")); }
### Question: ContainerDocumentHolder { public boolean isContainerDocument(final String entityName) { return containerDocumentMap.containsKey(entityName); } ContainerDocumentHolder(); ContainerDocumentHolder(final Map<String, ContainerDocument> containerDocumentMap); ContainerDocument getContainerDocument(final String entityName); boolean isContainerDocument(final String entityName); }### Answer: @Test public void testIsContainerDocument() { final Map<String, ContainerDocument> testContainer = createContainerMap(); testHolder = new ContainerDocumentHolder(testContainer); assertFalse(testHolder.isContainerDocument("foo")); assertTrue(testHolder.isContainerDocument("test")); }
### Question: XmlSignatureHelper { public Document signSamlAssertion(Document document) throws TransformerException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { if (document != null) { PrivateKeyEntry entry = getPrivateKeyEntryFromKeystore(); PrivateKey privateKey = entry.getPrivateKey(); X509Certificate certificate = (X509Certificate) entry.getCertificate(); Element signedElement = signSamlAssertion(document, privateKey, certificate); return signedElement.getOwnerDocument(); } return null; } Document signSamlAssertion(Document document); Document convertDocumentToDocumentDom(org.jdom.Document doc); Element convertElementToElementDom(org.jdom.Element element); Element convertDocumentToElementDom(org.jdom.Document document); }### Answer: @Ignore @Test public void signSamlArtifactResolve() throws JDOMException, TransformerException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, KeyStoreException, CertificateException { Document unsignedDocument = getDocument("artifact-resolve-unsigned.xml"); Document signedDom = signatureHelper.signSamlAssertion(unsignedDocument); Assert.assertNotNull(signedDom); boolean foundSignedInfo = false; boolean foundSignatureValue = false; boolean foundKeyInfo = false; NodeList list = signedDom.getChildNodes(); if (list.item(0).getNodeName().equals("samlp:ArtifactResolve")) { NodeList sublist = list.item(0).getChildNodes(); for (int i = 0; i < sublist.getLength(); i++) { if (sublist.item(i).getNodeName().equals("Signature")) { NodeList signatureList = sublist.item(i).getChildNodes(); for (int j = 0; j < signatureList.getLength(); j++) { if (signatureList.item(j).getNodeName().equals("SignedInfo")) { foundSignedInfo = true; } else if (signatureList.item(j).getNodeName().equals("SignatureValue")) { foundSignatureValue = true; } else if (signatureList.item(j).getNodeName().equals("KeyInfo")) { foundKeyInfo = true; } } } } } Assert.assertTrue("Should be true if Signature contains SignedInfo tag", foundSignedInfo); Assert.assertTrue("Should be true if Signature contains SignatureValue tag", foundSignatureValue); Assert.assertTrue("Should be true if Signature contains KeyInfo tag", foundKeyInfo); Assert.assertTrue(validator.isDocumentTrusted(signedDom, "CN=*.slidev.org,OU=Domain Control Validated,O=*.slidev.org")); }
### Question: DefaultSAML2Validator implements SAML2Validator { @Override public boolean isSignatureValid(Document samlDocument) { try { return getSignature(samlDocument).getSignatureValue().validate(valContext); } catch (MarshalException e) { LOG.warn("Couldn't validate signature", e); } catch (XMLSignatureException e) { LOG.warn("Couldn't validate signature", e); } return false; } @Override boolean isSignatureTrusted(XMLSignature signature, String issuer); @Override boolean isDocumentTrustedAndValid(Document samlDocument, String issuer); @Override boolean isDocumentTrusted(Document samlDocument, String issuer); @Override boolean isDocumentTrusted(Element element, String issuer); @Override boolean isDocumentValid(Document samlDocument); @Override boolean isSignatureValid(Document samlDocument); @Override Document signDocumentWithSAMLSigner(Document samlDocument, SAML2Signer signer); }### Answer: @Test public void testIsSignatureValidWithValid() throws Exception { Document doc = getDocument("complete-valid2.xml"); Assert.assertTrue(validator.isSignatureValid(doc)); } @Test public void testIsSignatureValidWithInvalid() throws Exception { Document doc = getDocument("complete-invalid.xml"); Assert.assertTrue(!validator.isSignatureValid(doc)); }
### Question: DefaultSAML2Validator implements SAML2Validator { @Override public boolean isDocumentValid(Document samlDocument) { try { return getSignature(samlDocument).validate(valContext); } catch (MarshalException e) { LOG.warn("Couldn't validate Document", e); } catch (XMLSignatureException e) { LOG.warn("Couldn't extract XML Signature from Document", e); } return false; } @Override boolean isSignatureTrusted(XMLSignature signature, String issuer); @Override boolean isDocumentTrustedAndValid(Document samlDocument, String issuer); @Override boolean isDocumentTrusted(Document samlDocument, String issuer); @Override boolean isDocumentTrusted(Element element, String issuer); @Override boolean isDocumentValid(Document samlDocument); @Override boolean isSignatureValid(Document samlDocument); @Override Document signDocumentWithSAMLSigner(Document samlDocument, SAML2Signer signer); }### Answer: @Test public void testValidatingAValidDocument() throws Exception { Document doc = getDocument("complete-valid2.xml"); Assert.assertTrue(validator.isDocumentValid(doc)); } @Test public void testValidatingAnInvalidDocument() throws Exception { Document doc = getDocument("complete-invalid.xml"); Assert.assertTrue(!validator.isDocumentValid(doc)); }
### Question: DefaultSAML2Validator implements SAML2Validator { @Override public boolean isDocumentTrusted(Document samlDocument, String issuer) throws KeyStoreException, InvalidAlgorithmParameterException, CertificateException, NoSuchAlgorithmException, MarshalException { return isSignatureTrusted(getSignature(samlDocument), issuer); } @Override boolean isSignatureTrusted(XMLSignature signature, String issuer); @Override boolean isDocumentTrustedAndValid(Document samlDocument, String issuer); @Override boolean isDocumentTrusted(Document samlDocument, String issuer); @Override boolean isDocumentTrusted(Element element, String issuer); @Override boolean isDocumentValid(Document samlDocument); @Override boolean isSignatureValid(Document samlDocument); @Override Document signDocumentWithSAMLSigner(Document samlDocument, SAML2Signer signer); }### Answer: @Test public void testIsUntrustedAssertionTrusted() throws Exception { Document doc = getDocument("adfs-invalid.xml"); Assert.assertTrue(!validator.isDocumentTrusted(doc, "CN=*.slidev.org,OU=Domain Control Validated,O=*.slidev.org")); }
### Question: SliSchemaVersionValidator { @PostConstruct public void initMigration() { this.detectMigrations(); this.migrationStrategyMap = this.buildMigrationStrategyMap(); this.warnForEachMissingMigrationStrategyList(); } void insertVersionInformation(Entity entity); @PostConstruct void initMigration(); Entity migrate(String collectionName, Entity entity, ValidationWithoutNaturalKeys repo); Iterable<Entity> migrate(String collectionName, Iterable<Entity> entities, ValidationWithoutNaturalKeys repo); MongoTemplate getMongoTemplate(); void setMongoTemplate(MongoTemplate mongoTemplate); static final String SARJE; static final String DAL_SV; static final String ID; static final String MONGO_SV; static final String METADATA_COLLECTION; }### Answer: @Test public void testInitMigration() { initMockMigration(); Mockito.verify(mongoTemplate, Mockito.times(1)).updateFirst(Mockito.any(Query.class), Mockito.any(Update.class), Mockito.any(String.class)); Mockito.verify(mongoTemplate, Mockito.times(1)).insert(Mockito.any(Object.class), Mockito.any(String.class)); }
### Question: SliSchemaVersionValidator { protected boolean isMigrationNeeded(String entityType, Entity entity) { if (this.entityTypesBeingMigrated.containsKey(entityType)) { int entityVersionNumber = this.getEntityVersionNumber(entity); int newVersionNumber = this.entityTypesBeingMigrated.get(entityType); if (entityVersionNumber < newVersionNumber) { return true; } } return false; } void insertVersionInformation(Entity entity); @PostConstruct void initMigration(); Entity migrate(String collectionName, Entity entity, ValidationWithoutNaturalKeys repo); Iterable<Entity> migrate(String collectionName, Iterable<Entity> entities, ValidationWithoutNaturalKeys repo); MongoTemplate getMongoTemplate(); void setMongoTemplate(MongoTemplate mongoTemplate); static final String SARJE; static final String DAL_SV; static final String ID; static final String MONGO_SV; static final String METADATA_COLLECTION; }### Answer: @Test public void testIsMigrationNeeded() { String entityType = "student"; Entity entity = new MongoEntity("student", new HashMap<String, Object>()); initMockMigration(); assertTrue("Should be true", sliSchemaVersionValidator.isMigrationNeeded(entityType, entity)); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("version", 5); entity = new MongoEntity("student", "someId", new HashMap<String, Object>(), metaData); assertFalse("Should be false", sliSchemaVersionValidator.isMigrationNeeded(entityType, entity)); }
### Question: SliSchemaVersionValidator { protected Entity performMigration(String entityType, Entity entity, ValidationWithoutNaturalKeys repo, String collectionName, boolean doUpdate) { int newVersionNumber = this.entityTypesBeingMigrated.get(entityType); int entityVersionNumber = this.getEntityVersionNumber(entity); Entity localEntity = entity; for (MigrationStrategy migrationStrategy : this.getMigrationStrategies(entityType, entityVersionNumber, newVersionNumber)) { localEntity = (Entity) migrationStrategy.migrate(localEntity); } localEntity.getMetaData().put(VERSION_NUMBER_FIELD, newVersionNumber); if (doUpdate) { repo.updateWithoutValidatingNaturalKeys(collectionName, localEntity); } return localEntity; } void insertVersionInformation(Entity entity); @PostConstruct void initMigration(); Entity migrate(String collectionName, Entity entity, ValidationWithoutNaturalKeys repo); Iterable<Entity> migrate(String collectionName, Iterable<Entity> entities, ValidationWithoutNaturalKeys repo); MongoTemplate getMongoTemplate(); void setMongoTemplate(MongoTemplate mongoTemplate); static final String SARJE; static final String DAL_SV; static final String ID; static final String MONGO_SV; static final String METADATA_COLLECTION; }### Answer: @Test public void testPerformMigration() { String entityType = "student"; String collectionName = "student"; Entity entity = new MongoEntity("student", new HashMap<String, Object>()); ValidationWithoutNaturalKeys repo = mock(ValidationWithoutNaturalKeys.class); when(repo.updateWithoutValidatingNaturalKeys(anyString(), any(Entity.class))).thenReturn(true); initMockMigration(); sliSchemaVersionValidator.performMigration(entityType, entity, repo, collectionName, false); Mockito.verify(repo, never()).updateWithoutValidatingNaturalKeys(anyString(), any(Entity.class)); sliSchemaVersionValidator.performMigration(entityType, entity, repo, collectionName, true); Mockito.verify(repo, Mockito.times(1)).updateWithoutValidatingNaturalKeys(anyString(), any(Entity.class)); }
### Question: AggregationLoader { protected String loadJavascriptFile(InputStream in) { try { if (in == null) { return ""; } StringBuffer fileData = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String temp = br.readLine(); while (temp != null) { fileData.append(temp); fileData.append("\n"); temp = br.readLine(); } br.close(); fileData.append("\n"); return fileData.toString(); } catch (IOException ioe) { LOG.debug("Failed to load definition file"); return ""; } } void init(); }### Answer: @Test public void testLoadNonExistentFile() { String testFile = "nonExistent"; InputStream in = getClass().getResourceAsStream(testFile); String out = aggregationLoader.loadJavascriptFile(in); assertEquals("", out); }
### Question: TenantAwareMongoDbFactory extends SimpleMongoDbFactory { @Override public DB getDb() throws DataAccessException { String tenantId = TenantContext.getTenantId(); boolean isSystemCall = TenantContext.isSystemCall(); if (isSystemCall || tenantId == null) { return super.getDb(); } else { return super.getDb(getTenantDatabaseName(tenantId)); } } TenantAwareMongoDbFactory(Mongo mongo, String systemDatabaseName); @Override DB getDb(); static String getTenantDatabaseName(String tenantId); }### Answer: @Test public void testGetSystemConnection() { Mongo mongo = Mockito.mock(Mongo.class); DB db = Mockito.mock(DB.class); Mockito.when(db.getMongo()).thenReturn(mongo); Mockito.when(db.getName()).thenReturn("System"); Mockito.when(mongo.getDB(Mockito.anyString())).thenReturn(db); TenantAwareMongoDbFactory cm = new TenantAwareMongoDbFactory(mongo, "System"); Assert.assertNotNull(cm.getDb()); Assert.assertSame("System", cm.getDb().getName()); }
### Question: MongoQueryConverter { protected static String prefixKey(NeutralCriteria neutralCriteria) { LOG.debug(">>>MongoQueryConverter.prefixKey()"); String key = neutralCriteria.getKey(); if (key.equals(MONGO_ID)) { return key; } else if (neutralCriteria.canBePrefixed()) { return MONGO_BODY + key; } else { return key; } } MongoQueryConverter(); Query convert(String entityName, NeutralQuery neutralQuery); Query convert(String entityName, NeutralQuery neutralQuery, boolean allFields); List<Criteria> convertToCriteria(String entityName, NeutralQuery neutralQuery, NeutralSchema entitySchema); }### Answer: @Test public void testKeyPrefixing() { NeutralCriteria neutralCriteria1 = new NeutralCriteria("metadata.x", "=", "1"); NeutralCriteria neutralCriteria2 = new NeutralCriteria("metadata.x", "=", "1", false); NeutralCriteria neutralCriteria3 = new NeutralCriteria("_id", "=", "1"); NeutralCriteria neutralCriteria4 = new NeutralCriteria("metadata._id", "=", "1"); assertEquals(MongoQueryConverter.prefixKey(neutralCriteria1), "body.metadata.x"); assertEquals(MongoQueryConverter.prefixKey(neutralCriteria2), "metadata.x"); assertEquals(MongoQueryConverter.prefixKey(neutralCriteria3), "_id"); assertEquals(MongoQueryConverter.prefixKey(neutralCriteria4), "body.metadata._id"); }
### Question: MongoQueryConverter { protected List<Criteria> mergeCriteria(Map<String, List<NeutralCriteria>> criteriaForFields) { LOG.debug(">>>MongoQueryConverter.mergeCriteria()"); List<Criteria> criteriaList = new ArrayList<Criteria>(); if (criteriaForFields != null) { for (Map.Entry<String, List<NeutralCriteria>> e : criteriaForFields.entrySet()) { List<NeutralCriteria> list = e.getValue(); if (list != null) { Criteria fullCriteria = null; for (NeutralCriteria criteria : list) { fullCriteria = operatorImplementations.get( criteria.getOperator()).generateCriteria(criteria, fullCriteria); } criteriaList.add(fullCriteria); } } } return criteriaList; } MongoQueryConverter(); Query convert(String entityName, NeutralQuery neutralQuery); Query convert(String entityName, NeutralQuery neutralQuery, boolean allFields); List<Criteria> convertToCriteria(String entityName, NeutralQuery neutralQuery, NeutralSchema entitySchema); }### Answer: @Test public void testMergeCriteria() { NeutralCriteria neutralCriteria1 = new NeutralCriteria("eventDate", ">=", "2011-09-08"); NeutralCriteria neutralCriteria2 = new NeutralCriteria("eventDate", "<=", "2012-04-08"); List<NeutralCriteria> list = new ArrayList<NeutralCriteria>(); list.add(neutralCriteria1); list.add(neutralCriteria2); Map<String, List<NeutralCriteria>> map = new HashMap<String, List<NeutralCriteria>>(); map.put("eventDate", list); List<Criteria> criteriaMerged = mongoQueryConverter.mergeCriteria(map); assertNotNull("Should not be null", criteriaMerged); assertNotNull("Should not be null", criteriaMerged.get(0)); DBObject obj = criteriaMerged.get(0).getCriteriaObject(); assertTrue("Should not be null", obj.containsField("body.eventDate")); DBObject criteria = (DBObject) obj.get("body.eventDate"); assertNotNull("Should not be null", criteria.get("$gte")); assertNotNull("Should not be null", criteria.get("$lte")); } @Test public void testNullMergeCriteria() { List<Criteria> criteriaMerged = mongoQueryConverter.mergeCriteria(null); assertNotNull("Should not be null", criteriaMerged); assertEquals("Should match", 0, criteriaMerged.size()); }
### Question: NodeService { public List<String> getChildren(String cluster, String path) throws ShepherException { List<String> children = nodeDAO.getChildren(cluster, path); Collections.sort(children); return children; } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer: @Test public void testGetChildren() throws Exception { List<String> children = nodeService.getChildren("local_test", "/test"); Assert.assertNotNull(children); Assert.assertEquals(0, children.size()); }
### Question: ClusterAdminService { public List<Cluster> all() { return clusterAdminBiz.all(); } void create(String name, String config); void update(String name, String config); void delete(String name); List<Cluster> all(); }### Answer: @Test public void testAll() throws Exception { List<Cluster> clusters = clusterAdminService.all(); Assert.assertNotNull(clusters); Assert.assertEquals(1, clusters.size()); }
### Question: TeamService { @Transactional public boolean create(long userId, String teamName, String cluster, String path) throws ShepherException { long teamId = teamBiz.create(teamName, userId).getId(); userTeamBiz.create(userId, teamId, Role.MASTER, Status.AGREE); long permissionId = permissionBiz.createIfNotExists(cluster, path); permissionTeamBiz.create(permissionId, teamId, Status.PENDING); return true; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testCreate() throws Exception { long userId = 2; String teamName = "test_team"; String cluster = "local_test"; String path = "/test"; boolean createResult = teamService.create(userId, teamName, cluster, path); Assert.assertEquals(true, createResult); }
### Question: TeamService { public UserTeam addApply(long userId, long teamId, Role role) throws ShepherException { return userTeamBiz.create(userId, teamId, role, Status.PENDING); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testAddApplyForUserIdTeamIdRole() throws Exception { long userId = 2; long teamId = 5; Role role = Role.MEMBER; UserTeam userTeam = teamService.addApply(userId, teamId, role); Assert.assertNotNull(userTeam); Assert.assertNotEquals(1, userTeam.getId()); }
### Question: TeamService { @Transactional public void addMember(User member, long teamId, Role role, User creator) throws ShepherException { if (member == null || creator == null) { throw ShepherException.createIllegalParameterException(); } if (userTeamBiz.listUserByTeamId(teamId).contains(member.getName())) { throw ShepherException.createUserExistsException(); } userTeamBiz.create(member.getId(), teamId, role, Status.AGREE); Team team = this.get(teamId); if (team == null) { throw ShepherException.createNoSuchTeamException(); } Set<String> receivers = new HashSet<>(); receivers.add(member.getName()); mailSenderFactory.getMailSender().noticeJoinTeamHandled(receivers, creator.getName(), Status.AGREE, team.getName(), serverUrl + "/teams/" + teamId + "/members"); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testAddMember() throws Exception { }
### Question: TeamService { public List<UserTeam> listUserTeamsPending(Team team) throws ShepherException { if (team == null) { throw ShepherException.createIllegalParameterException(); } return userTeamBiz.listByTeam(team.getId(), Status.PENDING); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testListUserTeamsPending() throws Exception { long userId = 2; long teamId = 5; Role role = Role.MEMBER; Team team = teamService.get(teamId); teamService.addApply(userId, teamId, role); List<UserTeam> applies = teamService.listUserTeamsPending(team); Assert.assertNotNull(applies); Assert.assertEquals(1, applies.size()); }
### Question: TeamService { public List<UserTeam> listUserTeamsAgree(Team team) throws ShepherException { if (team == null) { throw ShepherException.createIllegalParameterException(); } return userTeamBiz.listByTeam(team.getId(), Status.AGREE); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testListUserTeamsAgree() throws Exception { long teamId = 1; Team team = teamService.get(teamId); List<UserTeam> applies = teamService.listUserTeamsAgree(team); Assert.assertNotNull(applies); Assert.assertEquals(3, applies.size()); }
### Question: TeamService { public List<UserTeam> listUserTeamsJoined(User user) throws ShepherException { if (user == null) { throw ShepherException.createIllegalParameterException(); } return userTeamBiz.listByUser(user.getId(), Status.AGREE); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testListUserTeamsJoined() throws Exception { long userId = 3; User user = new User(); user.setId(userId); List<UserTeam> joinedTeams = teamService.listUserTeamsJoined(user); Assert.assertNotNull(joinedTeams); Assert.assertEquals(2, joinedTeams.size()); }
### Question: TeamService { public List<Team> listTeamsToJoin(long userId, String cluster, String path) { return teamBiz.listTeamsByPathAndUser(userId, cluster, path, false); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testListTeamsToJoin() throws Exception { long userId = 4; String cluster = "local_test"; String path = "/test/sub1"; List<Team> teams = teamService.listTeamsToJoin(userId, cluster, path); Assert.assertNotNull(teams); Assert.assertEquals(1, teams.size()); }
### Question: TeamService { public List<Team> listTeamsJoined(long userId, String cluster, String path) { return teamBiz.listTeamsByPathAndUser(userId, cluster, path, true); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testListTeamsJoined() throws Exception { long userId = 3; String cluster = "local_test"; String path = "/test/sub1"; List<Team> teams = teamService.listTeamsJoined(userId, cluster, path); Assert.assertNotNull(teams); Assert.assertEquals(1, teams.size()); }
### Question: TeamService { public Team get(String teamName) throws ShepherException { return teamBiz.getByName(teamName); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testGetTeamName() throws Exception { String teamName = "admin"; Team team = teamService.get(teamName); Assert.assertNotNull(team); Assert.assertEquals(1, team.getId()); } @Test public void testGetTeamId() throws Exception { long teamId = 1; Team team = teamService.get(teamId); Assert.assertNotNull(team); Assert.assertEquals("admin", team.getName()); }
### Question: NodeService { public String getData(String cluster, String path) throws ShepherException { return nodeDAO.getData(cluster, path); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer: @Test public void testGetData() throws Exception { String data = nodeService.getData("local_test", "/test"); Assert.assertNull(data); }
### Question: TeamService { public int updateStatus(long id, Status status) throws ShepherException { return userTeamBiz.updateStatus(id, status); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testUpdateStatus() throws Exception { long id = 3; Status status = Status.DELETE; int updateResult = teamService.updateStatus(id, status); Assert.assertEquals(RESULT_OK, updateResult); }
### Question: TeamService { public int agreeJoin(User user, long id, long teamId) throws ShepherException { int result = this.updateStatus(id, Status.AGREE); this.noticeJoinTeamHandled(id, user, teamId, Status.AGREE); return result; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testAgreeJoin() throws Exception { }
### Question: TeamService { public int refuseJoin(User user, long id, long teamId) throws ShepherException { int result = this.updateStatus(id, Status.REFUSE); this.noticeJoinTeamHandled(id, user, teamId, Status.REFUSE); return result; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testRefuseJoin() throws Exception { }
### Question: TeamService { public int updateRole(long id, Role role) throws ShepherException { return userTeamBiz.updateRole(id, role); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testUpdateRole() throws Exception { long id = 3; Role role = Role.MEMBER; int updateResult = teamService.updateRole(id, role); Assert.assertEquals(RESULT_OK, updateResult); }
### Question: TeamService { public boolean hasApplied(long teamId, String cluster, String path) throws ShepherException { boolean accepted = permissionTeamBiz.get(teamId, cluster, path, Status.AGREE) != null; boolean pending = permissionTeamBiz.get(teamId, cluster, path, Status.PENDING) != null; return accepted || pending; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testHasApplied() throws Exception { long teamId = 5; String cluster = "local_test"; String path = "/test/sub1"; boolean hasApplied = teamService.hasApplied(teamId, cluster, path); Assert.assertEquals(true, hasApplied); }
### Question: TeamService { public boolean isMaster(long userId, long teamId) throws ShepherException { return userTeamBiz.getRoleValue(userId, teamId, Status.AGREE) == Role.MASTER.getValue(); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testIsMaster() throws Exception { long userId = 1; long teamId = 1; boolean isMaster = teamService.isMaster(userId, teamId); Assert.assertEquals(true, isMaster); }
### Question: TeamService { public boolean isOwner(long userId, long teamId) { Team team = teamBiz.getById(teamId); return team != null && team.getOwner() == userId; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testIsOwner() throws Exception { long userId = 1; long teamId = 1; boolean isOwner = teamService.isOwner(userId, teamId); Assert.assertEquals(true, isOwner); }
### Question: TeamService { public boolean isAdmin(long userId) throws ShepherException { Team team = teamBiz.getByName(ShepherConstants.ADMIN); return userTeamBiz.getRoleValue(userId, team.getId(), Status.AGREE) > ShepherConstants.DEFAULT_ROLEVALUE; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer: @Test public void testIsAdmin() throws Exception { long userId = 1; boolean isAdmin = teamService.isAdmin(userId); Assert.assertEquals(true, isAdmin); }
### Question: ReviewService { @Transactional public long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus) throws ShepherException { if (creator == null) { throw ShepherException.createIllegalParameterException(); } Stat stat = nodeDAO.getStat(cluster, path, true); long snapshotId = snapshotBiz.getOriginalId(path, cluster, ReviewUtil.DEFAULT_CREATOR, stat, action, true); long newSnapshotId = snapshotBiz.create(cluster, path, data, creator.getName(), action, ReviewUtil.DEFAULT_MTIME, ReviewStatus.NEW, stat.getVersion() + 1, ReviewUtil.DEFAULT_REVIEWER).getId(); Set<String> masters = teamBiz.listUserNamesByPathAndUser(creator.getId(), cluster, path, Role.MASTER); String reviewers = this.asStringReviewers(masters); long reviewId = reviewBiz.create(cluster, path, snapshotId, newSnapshotId, reviewStatus, creator.getName(), ReviewUtil.DEFAULT_REVIEWER, action).getId(); logger.info("Create review request, reviewId={}, creator={}, reviewers={}", reviewId, creator, reviewers); mailSenderFactory.getMailSender().noticeUpdate(masters, creator.getName(), path, cluster, serverUrl + "/reviews/" + reviewId); return reviewId; } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer: @Test public void testCreate() throws Exception { }
### Question: NodeService { public Stat getStat(String cluster, String path) throws ShepherException { return this.getStat(cluster, path, true); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer: @Test public void testGetStatForClusterPath() throws Exception { Stat stat = nodeService.getStat("local_test", "/test"); Assert.assertNotNull(stat); } @Test public void testGetStatForClusterPathReturnNullIfPathNotExists() throws Exception { Stat stat = nodeService.getStat("local_test", "/test", true); Assert.assertNotNull(stat); }
### Question: ReviewService { @Transactional public int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime) throws ShepherException { snapshotBiz.update(snapshotId, reviewStatus, reviewer, zkMtime); return reviewBiz.update(id, reviewStatus, reviewer); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer: @Test public void testUpdate() throws Exception { int result = reviewService.update(ReviewStatus.ACCEPTED, 1L, "reviewer", 0L, 0L); Assert.assertNotEquals(0, result); }
### Question: ReviewService { @Transactional public int accept(long id, String reviewer, ReviewRequest reviewRequest) throws ShepherException { if (reviewRequest == null) { throw ShepherException.createIllegalParameterException(); } if (!teamBiz.isAboveRole(reviewRequest.getCluster(), reviewRequest.getPath(), Role.MASTER, reviewer)) { throw ShepherException.createNoAuthorizationException(); } switch (Action.get(reviewRequest.getAction())) { case DELETE: nodeBiz.delete(reviewRequest.getCluster(), reviewRequest.getPath()); break; case ADD: logger.error("Add action doesn't need review, id:{}", id); break; case UPDATE: nodeBiz.update(reviewRequest.getCluster(), reviewRequest.getPath(), reviewRequest.getNewSnapshotContent(), reviewRequest.getNewSnapshot()); break; default: logger.error("Action value not corrected, id:{}", id); break; } Stat stat = nodeDAO.getStat(reviewRequest.getCluster(), reviewRequest.getPath(), true); logger.info("Accepted review request, reviewId={}, reviewer={}", id, reviewer); mailSenderFactory.getMailSender().noticeReview(reviewRequest.getCreator(), reviewer, reviewRequest.getPath(), reviewRequest.getCluster(), serverUrl + "/reviews/" + id, ReviewStatus.ACCEPTED.getDescription()); return this.update(ReviewStatus.ACCEPTED, id, reviewer, reviewRequest.getNewSnapshot(), stat == null ? ReviewUtil.DEFAULT_MTIME : stat.getMtime()); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer: @Test public void testAccept() throws Exception { int result = reviewService.accept(1L, "testuser", new ReviewRequest("local_test", "/test/sub1", 0, 0, ReviewStatus.ACCEPTED.getValue(), "testuser", "testuser", new Date(), Action.UPDATE.getValue())); Assert.assertNotEquals(0, result); }
### Question: ReviewService { @Transactional public int refuse(long id, String reviewer, ReviewRequest reviewRequest) throws ShepherException { if (reviewRequest == null) { throw ShepherException.createIllegalParameterException(); } if (!teamBiz.isAboveRole(reviewRequest.getCluster(), reviewRequest.getPath(), Role.MASTER, reviewer)) { throw ShepherException.createNoAuthorizationException(); } logger.info("Rejected review request, reviewId={}, reviewer={}", id, reviewer); mailSenderFactory.getMailSender().noticeReview(reviewRequest.getCreator(), reviewer, reviewRequest.getPath(), reviewRequest.getCluster(), serverUrl + "/reviews/" + id, ReviewStatus.REJECTED.getDescription()); return this.update(ReviewStatus.REJECTED, id, reviewer, reviewRequest.getNewSnapshot(), ReviewUtil.DEFAULT_MTIME); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer: @Test public void testRefuse() throws Exception { int result = reviewService.refuse(1L, "testuser", new ReviewRequest("local_test", "/test/sub1", 0, 0, ReviewStatus.ACCEPTED.getValue(), "testuser", "testuser", new Date(), Action.UPDATE.getValue())); Assert.assertNotEquals(0, result); }
### Question: ReviewService { public ReviewRequest get(long id) { return reviewBiz.get(id); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer: @Test public void testGet() throws Exception { ReviewRequest reviewRequest = reviewService.get(1); Assert.assertNotNull(reviewRequest); }
### Question: ReviewService { @Transactional public void rejectIfExpired(ReviewRequest reviewRequest) throws ShepherException { if (reviewRequest == null) { throw ShepherException.createIllegalParameterException(); } Snapshot snapshot = snapshotBiz.get(reviewRequest.getNewSnapshot()); if (snapshot != null && reviewRequest.getReviewStatus() == ReviewStatus.NEW.getValue()) { Stat stat = nodeDAO.getStat(snapshot.getCluster(), snapshot.getPath(), true); if (stat == null || stat.getVersion() >= snapshot.getZkVersion()) { this.update(ReviewStatus.REJECTED, reviewRequest.getId(), ReviewUtil.DEFAULT_CREATOR, reviewRequest.getNewSnapshot(), stat == null ? ReviewUtil.DEFAULT_MTIME : stat.getMtime()); reviewRequest.setReviewStatus(ReviewStatus.REJECTED.getValue()); } } } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer: @Test public void testRejectIfExpired() throws Exception { reviewService.rejectIfExpired(new ReviewRequest("local_test", "/test/sub1", 0, 0, ReviewStatus.ACCEPTED.getValue(), "testuser", "testuser", new Date(), Action.UPDATE.getValue())); }
### Question: ReviewService { public int delete(long id) throws ShepherException { return reviewBiz.delete(id); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer: @Test public void testDelete() throws Exception { int result = reviewService.delete(1); Assert.assertEquals(RESULT_OK, result); }
### Question: SnapshotService { public List<Snapshot> getByPath(String path, String cluster, int offset, int limit) throws ShepherException { return snapshotBiz.listByPath(path, cluster, offset, limit); } List<Snapshot> getByPath(String path, String cluster, int offset, int limit); Snapshot getById(long id); }### Answer: @Test public void testGetByPath() throws Exception { String path = "/test/test2"; String cluster = "local_test"; int offset = 0; int limit = 20; List<Snapshot> snapshots = snapshotService.getByPath(path, cluster, offset, limit); Assert.assertNotNull(snapshots); Assert.assertEquals(2, snapshots.size()); }
### Question: SnapshotService { public Snapshot getById(long id) { return snapshotBiz.get(id); } List<Snapshot> getByPath(String path, String cluster, int offset, int limit); Snapshot getById(long id); }### Answer: @Test public void testGetById() throws Exception { Snapshot snapshot = snapshotService.getById(1); Assert.assertNotNull(snapshot); }
### Question: UserService { public User get(long id) { return userBiz.getById(id); } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer: @Test public void testGetId() throws Exception { long id = 1; User user = userService.get(id); Assert.assertNotNull(user); Assert.assertEquals("banchuanyu", user.getName()); } @Test public void testGetName() throws Exception { String name = "banchuanyu"; User user = userService.get(name); Assert.assertNotNull(user); Assert.assertEquals(1, user.getId()); }
### Question: UserService { public User create(String name) throws ShepherException { return userBiz.create(name); } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer: @Test public void testCreate() throws Exception { String name = "test_user"; User user = userService.create(name); Assert.assertEquals(4, user.getId()); }
### Question: UserService { public User createIfNotExist(String name) throws ShepherException { User user = this.get(name); if (user == null) { user = this.create(name); } return user; } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer: @Test public void testCreateIfNotExist() throws Exception { String existedName = "banchuanyu"; User user = userService.createIfNotExist(existedName); Assert.assertEquals(1, user.getId()); String name = "test_user"; user = userService.createIfNotExist(name); Assert.assertNotNull(user); Assert.assertEquals(4, user.getId()); }
### Question: UserService { public List<User> listByTeams(Set<Long> teams, Status status, Role role) throws ShepherException { return userBiz.list(teams, status, role); } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer: @Test public void testListByTeams() throws Exception { Set<Long> teams = new HashSet<>(); teams.add(1L); teams.add(2L); List<User> users = userService.listByTeams(teams, Status.AGREE, Role.MEMBER); Assert.assertNotNull(users); Assert.assertEquals(3, users.size()); }
### Question: UserService { public Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role) throws ShepherException { return userBiz.listNames(teamIds, status, role); } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer: @Test public void testListNamesByTeams() throws Exception { Set<Long> teams = new HashSet<>(); teams.add(1L); teams.add(2L); Set<String> names = userService.listNamesByTeams(teams, Status.AGREE, Role.MEMBER); Assert.assertNotNull(names); Assert.assertEquals(3, names.size()); }
### Question: PermissionService { public PermissionTeam add(long permissionId, long teamId, Status status) throws ShepherException { return permissionTeamBiz.create(permissionId, teamId, status); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testAddForPermissionIdTeamIdStatus() throws Exception { long permissionId = 3; long teamId = 5; Status status = Status.AGREE; PermissionTeam permissionTeam = permissionService.add(permissionId, teamId, status); Assert.assertNotNull(permissionTeam); Assert.assertEquals(4, permissionTeam.getId()); } @Test public void testAddForTeamIdClusterPathStatus() throws Exception { long teamId = 5; Status status = Status.AGREE; String cluster = "local_test"; String path = "/test"; boolean addResult = permissionService.add(teamId, cluster, path, status); Assert.assertEquals(true, addResult); }
### Question: PermissionService { public boolean addPending(long teamId, String cluster, String path) throws ShepherException { return this.add(teamId, cluster, path, Status.PENDING); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testAddPending() throws Exception { long teamId = 5; String cluster = "local_test"; String path = "/test"; boolean addResult = permissionService.addPending(teamId, cluster, path); Assert.assertEquals(true, addResult); }
### Question: PermissionService { public boolean addAgree(long teamId, String cluster, String path) throws ShepherException { return this.add(teamId, cluster, path, Status.AGREE); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testAddAgree() throws Exception { long teamId = 5; String cluster = "local_test"; String path = "/test"; boolean addResult = permissionService.addAgree(teamId, cluster, path); Assert.assertEquals(true, addResult); }
### Question: PermissionService { public List<PermissionTeam> listPermissionTeamsAgree() throws ShepherException { return permissionTeamBiz.list(Status.AGREE); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testListPermissionTeamsAgree() throws Exception { List<PermissionTeam> permissionTeams = permissionService.listPermissionTeamsAgree(); Assert.assertNotNull(permissionTeams); Assert.assertEquals(1, permissionTeams.size()); }
### Question: PermissionService { public List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status) throws ShepherException { return permissionTeamBiz.listByTeam(teamId, status); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testListPermissionTeamsByTeam() throws Exception { long teamId = 5; List<PermissionTeam> permissionTeams = permissionService.listPermissionTeamsByTeam(teamId, Status.AGREE); Assert.assertNotNull(permissionTeams); Assert.assertEquals(1, permissionTeams.size()); }
### Question: NodeService { public void create(String cluster, String path, String data, String creator) throws ShepherException { nodeBiz.create(cluster, path, data); long zkCreationTime = nodeDAO.getCreationTime(cluster, path); snapshotBiz.create(cluster, path, data, creator, Action.ADD, zkCreationTime, ReviewStatus.ACCEPTED, ReviewUtil.NEW_CREATE_VERSION, ReviewUtil.DEFAULT_REVIEWER); logger.info("Create node, cluster={}, path={}, operator={}", cluster, path, creator); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer: @Test public void testCreate() throws Exception { nodeService.create("local_test", "/test", "data", "creator"); }
### Question: PermissionService { public List<PermissionTeam> listPermissionTeamsPending() throws ShepherException { return permissionTeamBiz.list(Status.PENDING); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testListPermissionTeamsPending() throws Exception { List<PermissionTeam> permissionTeams = permissionService.listPermissionTeamsPending(); Assert.assertNotNull(permissionTeams); Assert.assertEquals(1, permissionTeams.size()); }
### Question: PermissionService { public int updateStatus(long id, Status status) throws ShepherException { return permissionTeamBiz.update(id, status); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testUpdateStatus() throws Exception { int id = 3; Status status = Status.AGREE; int updateResult = permissionService.updateStatus(id, status); Assert.assertEquals(RESULT_OK, updateResult); }
### Question: PermissionService { public boolean isPathMember(long userId, String cluster, String path) throws ShepherException { if (ClusterUtil.isPublicCluster(cluster)) { return true; } return teamBiz.isAboveRole(cluster, path, Role.MEMBER, userId); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testIsPathMember() throws Exception { long userId = 3; String cluster = "local_test"; String path = "/test/sub1"; boolean isMember = permissionService.isPathMember(userId, cluster, path); Assert.assertEquals(true, isMember); }
### Question: PermissionService { public boolean isPathMaster(long userId, String cluster, String path) throws ShepherException { if (ClusterUtil.isPublicCluster(cluster)) { return true; } return teamBiz.isAboveRole(cluster, path, Role.MASTER, userId); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer: @Test public void testIsPathMasterForUserIdClusterPath() throws Exception { long userId = 3; String cluster = "local_test"; String path = "/test/sub1"; boolean isMaster = permissionService.isPathMaster(userId, cluster, path); Assert.assertEquals(true, isMaster); } @Test public void testIsPathMasterForUserNameClusterPath() throws Exception { String userName = "testuser"; String cluster = "local_test"; String path = "/test/sub1"; boolean isMaster = permissionService.isPathMaster(userName, cluster, path); Assert.assertEquals(true, isMaster); }
### Question: NodeService { public void update(String cluster, String path, String data, String creator) throws ShepherException { nodeBiz.update(cluster, path, data); Stat stat = nodeDAO.getStat(cluster, path, true); snapshotBiz.create(cluster, path, data, creator, Action.UPDATE, stat.getCtime(), ReviewStatus.ACCEPTED, stat.getVersion(), ReviewUtil.DEFAULT_REVIEWER); logger.info("Update node, cluster={}, path={}, operator={}", cluster, path, creator); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer: @Test public void testUpdate() throws Exception { nodeService.update("local_test", "/test", "", ""); }
### Question: NodeService { public void delete(String cluster, String path, String creator) throws ShepherException { nodeBiz.delete(cluster, path); long snapshotId = snapshotBiz.create(cluster, path, ReviewUtil.EMPTY_CONTENT, creator, Action.DELETE, ReviewUtil.DEFAULT_MTIME, ReviewStatus.DELETED, ReviewUtil.NEW_CREATE_VERSION, ReviewUtil.DEFAULT_REVIEWER).getId(); Set<String> masters = teamBiz.listUserNamesByPath(cluster, path, Role.MASTER); mailSenderFactory.getMailSender().noticeDelete(masters, creator, path, cluster, serverUrl + "/snapshots/" + snapshotId); logger.info("Delete node, cluster={}, path={}, operator={}", cluster, path, creator); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer: @Test public void testDelete() throws Exception { nodeService.delete("local_test", "/test", ""); }
### Question: ClusterAdminService { public void create(String name, String config) throws ShepherException { clusterAdminBiz.create(name, config); logger.info("Create cluster, config={}, name={}, operator={}", config, name, userHolder.getUser().getName()); } void create(String name, String config); void update(String name, String config); void delete(String name); List<Cluster> all(); }### Answer: @Test public void testCreate() throws Exception { clusterAdminService.create("name", "config"); List<Cluster> clusters = clusterAdminService.all(); Assert.assertNotNull(clusters); Assert.assertEquals(2, clusters.size()); thrown.expect(ShepherException.class); clusterAdminService.create(null, "config"); clusterAdminService.create("local_test", "config"); }
### Question: ClusterAdminService { public void update(String name, String config) throws ShepherException { clusterAdminBiz.update(name, config); logger.info("Update cluster, config={}, name={}, operator={}", config, name, userHolder.getUser().getName()); } void create(String name, String config); void update(String name, String config); void delete(String name); List<Cluster> all(); }### Answer: @Test public void testUpdate() throws Exception { clusterAdminService.update("local_test", "config"); List<Cluster> clusters = clusterAdminService.all(); Assert.assertNotNull(clusters); Assert.assertEquals(1, clusters.size()); Assert.assertEquals("config", clusters.get(0).getConfig()); thrown.expect(ShepherException.class); clusterAdminService.update(null, "config"); }
### Question: ClusterAdminService { public void delete(String name) throws ShepherException { clusterAdminBiz.delete(name); logger.info("Delete cluster, name={}, operator={}", name, userHolder.getUser().getName()); } void create(String name, String config); void update(String name, String config); void delete(String name); List<Cluster> all(); }### Answer: @Test public void testDelete() throws Exception { clusterAdminService.delete("local_test"); List<Cluster> clusters = clusterAdminService.all(); Assert.assertNotNull(clusters); Assert.assertEquals(0, clusters.size()); thrown.expect(ShepherException.class); clusterAdminService.delete(null); }
### Question: FsAccessOptions { public static BitField<FsAccessOption> of(FsAccessOption... options) { return 0 == options.length ? NONE : BitField.of(options[0], options); } private FsAccessOptions(); static BitField<FsAccessOption> of(FsAccessOption... options); static final BitField<FsAccessOption> NONE; static final BitField<FsAccessOption> ACCESS_PREFERENCES_MASK; }### Answer: @Test public void testOf() { for (final Object[] params : new Object[][] { { new FsAccessOption[0], NONE }, { new FsAccessOption[] { CACHE, CREATE_PARENTS, STORE, COMPRESS, GROW, ENCRYPT }, ACCESS_PREFERENCES_MASK }, }) { final FsAccessOption[] array = (FsAccessOption[]) params[0]; final BitField<?> bits = (BitField<?>) params[1]; assertEquals(FsAccessOptions.of(array), bits); } }
### Question: FsMountPoint implements Serializable, Comparable<FsMountPoint> { public URI toHierarchicalUri() { final URI hierarchical = this.hierarchical; return null != hierarchical ? hierarchical : (this.hierarchical = uri.isOpaque() ? path.toHierarchicalUri() : uri); } @ConstructorProperties("uri") FsMountPoint(URI uri); FsMountPoint(URI uri, FsUriModifier modifier); FsMountPoint(final FsScheme scheme, final FsNodePath path); static FsMountPoint create(URI uri); static FsMountPoint create(URI uri, FsUriModifier modifier); static FsMountPoint create(FsScheme scheme, FsNodePath path); URI getUri(); URI toHierarchicalUri(); FsScheme getScheme(); @Nullable FsNodePath getPath(); @Nullable FsMountPoint getParent(); FsNodePath resolve(FsNodeName name); @Override int compareTo(FsMountPoint that); @Override boolean equals(@CheckForNull Object that); @Override int hashCode(); @Override String toString(); static final String SEPARATOR; }### Answer: @Test public void testToHierarchicalUri() { for (final String[] params : new String[][] { { "foo:bar:baz:/x/bö%20m?plö%20k!/bä%20g?zö%20k!/", "baz:/x/bö%20m/bä%20g?zö%20k" }, { "foo:bar:baz:/x/bööm?plönk!/bäng?zönk!/", "baz:/x/bööm/bäng?zönk" }, { "foo:bar:baz:/boom?plonk!/bang?zonk!/", "baz:/boom/bang?zonk" }, { "foo:bar:baz:/boom!/bang!/", "baz:/boom/bang" }, { "foo:bar:/baz?boom!/", "bar:/baz?boom" }, { "foo:bar:/baz!/", "bar:/baz" }, { "foo:/bar/", "foo:/bar/" }, }) { final FsMountPoint mp = FsMountPoint.create(URI.create(params[0])); final URI hmp = mp.toHierarchicalUri(); final FsNodePath p = FsNodePath.create(URI.create(params[0])); final URI hp = p.toHierarchicalUri(); assertThat(hmp, equalTo(URI.create(params[1]))); assertThat(hmp, equalTo(hp)); } }
### Question: FileBufferPoolFactory extends IoBufferPoolFactory { @Override public int getPriority() { return -100; } @Override IoBufferPool get(); @Override int getPriority(); }### Answer: @Test public void testPriority() { assertTrue(new FileBufferPoolFactory().getPriority() < 0); }
### Question: UShort { public static boolean check( final int i, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= i && i <= MAX_VALUE) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(i) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); } private UShort(); static boolean check( final int i, final @CheckForNull String subject, final @CheckForNull String error); static boolean check(final int i); static final int MIN_VALUE; static final int MAX_VALUE; static final int SIZE; }### Answer: @Test public void testCheck() { try { UShort.check(UShort.MIN_VALUE - 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } UShort.check(UShort.MIN_VALUE); UShort.check(UShort.MAX_VALUE); try { UShort.check(UShort.MAX_VALUE + 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } }
### Question: ULong { public static boolean check( final long l, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= l) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(l) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); } private ULong(); static boolean check( final long l, final @CheckForNull String subject, final @CheckForNull String error); static boolean check(final long l); static final long MIN_VALUE; static final long MAX_VALUE; static final int SIZE; }### Answer: @Test public void testCheck() { try { ULong.check(ULong.MIN_VALUE - 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } ULong.check(ULong.MIN_VALUE); ULong.check(ULong.MAX_VALUE); }
### Question: ExtraField { static void register(final Class<? extends ExtraField> c) { final ExtraField ef; try { ef = c.getDeclaredConstructor().newInstance(); } catch (NullPointerException ex) { throw ex; } catch (Exception ex) { throw new IllegalArgumentException(ex); } final int headerId = ef.getHeaderId(); assert UShort.check(headerId); registry.put(headerId, c); } }### Answer: @Test public void testRegister() { try { ExtraField.register(null); fail(); } catch (NullPointerException expected) { } try { ExtraField.register(TooSmallHeaderIDExtraField.class); fail(); } catch (IllegalArgumentException expected) { } try { ExtraField.register(TooLargeHeaderIDExtraField.class); fail(); } catch (IllegalArgumentException expected) { } ExtraField.register(NullExtraField.class); }
### Question: ExtraField { static ExtraField create(final int headerId) { assert UShort.check(headerId); final Class<? extends ExtraField> c = registry.get(headerId); final ExtraField ef; try { ef = null != c ? c.getDeclaredConstructor().newInstance() : new DefaultExtraField(headerId); } catch (final Exception cannotHappen) { throw new AssertionError(cannotHappen); } assert headerId == ef.getHeaderId(); return ef; } }### Answer: @Test public void testCreate() { ExtraField ef; ExtraField.register(NullExtraField.class); ef = ExtraField.create(0x0000); assertTrue(ef instanceof NullExtraField); assertEquals(0x0000, ef.getHeaderId()); ef = ExtraField.create(0x0001); assertTrue(ef instanceof DefaultExtraField); assertEquals(0x0001, ef.getHeaderId()); ef = ExtraField.create(0x0002); assertTrue(ef instanceof DefaultExtraField); assertEquals(0x0002, ef.getHeaderId()); ef = ExtraField.create(UShort.MAX_VALUE); assertTrue(ef instanceof DefaultExtraField); assertEquals(UShort.MAX_VALUE, ef.getHeaderId()); try { ef = ExtraField.create(UShort.MIN_VALUE - 1); fail(); } catch (IllegalArgumentException expected) { } try { ef = ExtraField.create(UShort.MAX_VALUE + 1); fail(); } catch (IllegalArgumentException expected) { } }
### Question: UByte { public static boolean check( final int i, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= i && i <= MAX_VALUE) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(i) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); } private UByte(); static boolean check( final int i, final @CheckForNull String subject, final @CheckForNull String error); static boolean check(final int i); static final short MIN_VALUE; static final short MAX_VALUE; static final int SIZE; }### Answer: @Test public void testCheck() { try { UByte.check(UByte.MIN_VALUE - 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } UByte.check(UByte.MIN_VALUE); UByte.check(UByte.MAX_VALUE); try { UByte.check(UByte.MAX_VALUE + 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } }
### Question: UInt { public static boolean check( final long l, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= l && l <= MAX_VALUE) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(l) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); } private UInt(); static boolean check( final long l, final @CheckForNull String subject, final @CheckForNull String error); static boolean check(final long l); static final long MIN_VALUE; static final long MAX_VALUE; static final int SIZE; }### Answer: @Test public void testCheck() { try { UInt.check(UInt.MIN_VALUE - 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } UInt.check(UInt.MIN_VALUE); UInt.check(UInt.MAX_VALUE); try { UInt.check(UInt.MAX_VALUE + 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } }
### Question: ZipEntry implements Cloneable { @Override @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") public ZipEntry clone() { final ZipEntry entry; try { entry = (ZipEntry) super.clone(); } catch (CloneNotSupportedException ex) { throw new AssertionError(ex); } final ExtraFields fields = this.fields; entry.fields = fields == null ? null : fields.clone(); return entry; } ZipEntry(final String name); @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") protected ZipEntry(final String name, final ZipEntry template); @Override @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") ZipEntry clone(); final String getName(); final boolean isDirectory(); final int getPlatform(); final void setPlatform(final int platform); final boolean isEncrypted(); final void setEncrypted(boolean encrypted); final void clearEncryption(); final int getMethod(); final void setMethod(final int method); final long getTime(); final void setTime(final long jtime); final long getCrc(); final void setCrc(final long crc); final long getCompressedSize(); final void setCompressedSize(final long csize); final long getSize(); final void setSize(final long size); final long getExternalAttributes(); final void setExternalAttributes(final long eattr); final byte[] getExtra(); final void setExtra(final @CheckForNull byte[] buf); final @CheckForNull String getComment(); final void setComment(final @CheckForNull String comment); @Override String toString(); static final byte UNKNOWN; static final short PLATFORM_FAT; static final short PLATFORM_UNIX; static final int STORED; static final int DEFLATED; static final int BZIP2; static final long MIN_DOS_TIME; static final long MAX_DOS_TIME; }### Answer: @Test public void testClone() { ZipEntry clone = entry.clone(); assertNotSame(clone, entry); }
### Question: DefaultExtraField extends ExtraField { @Override int getDataSize() { final byte[] data = this.data; return null != data ? data.length : 0; } DefaultExtraField(final int headerId); }### Answer: @Test public void testGetDataSize() { assertEquals(0, field.getDataSize()); }
### Question: FsScheme implements Serializable, Comparable<FsScheme> { public static FsScheme create(String scheme) { try { return new FsScheme(scheme); } catch (URISyntaxException ex) { throw new IllegalArgumentException(ex); } } @ConstructorProperties("scheme") FsScheme(final String scheme); static FsScheme create(String scheme); @Deprecated String getScheme(); @Override boolean equals(Object that); @Override int compareTo(FsScheme that); @Override int hashCode(); @Override String toString(); }### Answer: @Test @SuppressWarnings("ResultOfObjectAllocationIgnored") public void testConstructorWithInvalidUri() throws URISyntaxException { try { FsScheme.create(null); fail(); } catch (NullPointerException expected) { } try { new FsScheme(null); fail(); } catch (NullPointerException expected) { } for (final String param : new String[] { "", "+", "-", ".", }) { try { FsScheme.create(param); fail(param); } catch (IllegalArgumentException expected) { } try { new FsScheme(param); fail(param); } catch (URISyntaxException expected) { } } }
### Question: TApplication { @SuppressWarnings("NoopMethodInAbstractClass") protected void setup() { } }### Answer: @Test public void testSetup() { instance.setup(); }
### Question: TApplication { protected abstract int work(String[] args) throws E; }### Answer: @Test public void testWork() { try { instance.work(null); } catch (NullPointerException expected) { } assertEquals(0, instance.work(new String[0])); }
### Question: FsSyncOptions { public static BitField<FsSyncOption> of(FsSyncOption... options) { return 0 == options.length ? NONE : BitField.of(options[0], options); } private FsSyncOptions(); static BitField<FsSyncOption> of(FsSyncOption... options); static final BitField<FsSyncOption> NONE; static final BitField<FsSyncOption> UMOUNT; static final BitField<FsSyncOption> SYNC; static final BitField<FsSyncOption> RESET; }### Answer: @Test public void testOf() { for (final Object[] params : new Object[][] { { new FsSyncOption[0], NONE }, { new FsSyncOption[] { ABORT_CHANGES }, RESET }, { new FsSyncOption[] { WAIT_CLOSE_IO }, SYNC }, { new FsSyncOption[] { FORCE_CLOSE_IO, CLEAR_CACHE }, UMOUNT }, }) { final FsSyncOption[] array = (FsSyncOption[]) params[0]; final BitField<?> bits = (BitField<?>) params[1]; assertEquals(bits, FsSyncOptions.of(array)); } }
### Question: FsNodeName implements Serializable, Comparable<FsNodeName> { public static FsNodeName create(URI uri) { return create(uri, NULL); } @ConstructorProperties("uri") FsNodeName(URI uri); FsNodeName(URI uri, final FsUriModifier modifier); FsNodeName( final FsNodeName parent, final FsNodeName member); static FsNodeName create(URI uri); static FsNodeName create(URI uri, FsUriModifier modifier); boolean isRoot(); URI getUri(); String getPath(); @CheckForNull String getQuery(); @Override int compareTo(FsNodeName that); @Override boolean equals(@CheckForNull Object that); @Override int hashCode(); @Override String toString(); static final String SEPARATOR; static final char SEPARATOR_CHAR; static final FsNodeName ROOT; }### Answer: @Test @SuppressWarnings("ResultOfObjectAllocationIgnored") public void testConstructorWithInvalidUri() { for (final String param : new String[] { "/../foo#boo", "/../foo#", "/../foo", "/./foo", " "/foo", "/foo/bar", "/foo/bar/", "/", "foo#fragmentDefined", "foo/", "foo "foo/.", "foo/./", "foo/..", "foo/../", "foo:bar", "foo:bar:", "foo:bar:/", "foo:bar:/baz", "foo:bar:/baz!", "foo:bar:/baz/", "foo:bar:/baz! "foo:bar:/baz!/#", "foo:bar:/baz!/#bang", "foo:bar:/baz!/.", "foo:bar:/baz!/./", "foo:bar:/baz!/..", "foo:bar:/baz!/../", "foo:bar:/baz!/bang/.", "foo:bar:/baz!/bang/./", "foo:bar:/baz!/bang/..", "foo:bar:/baz!/bang/../", "foo:bar:baz:/bang", "foo:bar:baz:/bang!", "foo:bar:baz:/bang/", "foo:bar:baz:/bang!/", "foo:bar:baz:/bang!/boom", "foo:bar:/baz/.!/", "foo:bar:/baz/./!/", "foo:bar:/baz/..!/", "foo:bar:/baz/../!/", "foo:bar:/baz/../!/bang/", "foo:bar:/baz/..!/bang/", "foo:bar:/baz/./!/bang/", "foo:bar:/baz/.!/bang/", "foo:bar:/../baz/!/bang/", "foo:bar:/./baz/!/bang/", "foo:bar: "foo:bar: "foo:bar:/!/bang/", "foo:bar:/baz/../!/bang", "foo:bar:/baz/..!/bang", "foo:bar:/baz/./!/bang", "foo:bar:/baz/.!/bang", "foo:bar:/../baz/!/bang", "foo:bar:/./baz/!/bang", "foo:bar: "foo:bar: "foo:bar:/!/bang", "foo:bar:/baz/!/", "foo:bar:/baz/?bang!/?plonk", "foo:bar:/baz "foo:bar:/baz/./!/", "foo:bar:/baz/..!/", "foo:bar:/baz/../!/", " }) { final URI uri = URI.create(param); try { FsNodeName.create(uri); fail(param); } catch (IllegalArgumentException ignored) { } try { new FsNodeName(uri); fail(param); } catch (URISyntaxException ignored) { } } }
### Question: FsNodeName implements Serializable, Comparable<FsNodeName> { public boolean isRoot() { final URI uri = getUri(); final String path = uri.getRawPath(); if (null != path && !path.isEmpty()) return false; final String query = uri.getRawQuery(); return null == query; } @ConstructorProperties("uri") FsNodeName(URI uri); FsNodeName(URI uri, final FsUriModifier modifier); FsNodeName( final FsNodeName parent, final FsNodeName member); static FsNodeName create(URI uri); static FsNodeName create(URI uri, FsUriModifier modifier); boolean isRoot(); URI getUri(); String getPath(); @CheckForNull String getQuery(); @Override int compareTo(FsNodeName that); @Override boolean equals(@CheckForNull Object that); @Override int hashCode(); @Override String toString(); static final String SEPARATOR; static final char SEPARATOR_CHAR; static final FsNodeName ROOT; }### Answer: @Test public void testIsRoot() { for (final Object params[] : new Object[][] { { "", true }, { "?", false, }, }) { assertThat(FsNodeName.create(URI.create(params[0].toString())).isRoot(), is(params[1])); } }