src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
|---|---|
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); }
|
@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)); }
|
NaturalKeyDescriptor { @Override public int hashCode() { int result = 42; if (this.getNaturalKeys() != null) { result = 37 * result + this.getNaturalKeys().hashCode(); } if (this.getTenantId() != null) { result = 37 * result + this.getTenantId().hashCode(); } if (this.getEntityType() != null) { result = 37 * result + this.getEntityType().hashCode(); } if (this.getParentId() != null) { result = 37 * result + this.getParentId().hashCode(); } return result; } 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); }
|
@Test public void hashCodeShouldMatchExpected() { Map<String, String> naturalKeysForConstructor = new HashMap<String, String>(); naturalKeysForConstructor.put("key1", "value1"); naturalKeysForConstructor.put("key2", "value2"); String testTenantId = "testTenantId"; String testEntityType = "testEntityType"; NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(naturalKeysForConstructor, testTenantId, testEntityType, null); int hashCode = naturalKeyDescriptor.hashCode(); assertEquals(1601434024, hashCode); Map<String, String> naturalKeysForConstructor2 = new HashMap<String, String>(); naturalKeysForConstructor2.put("key1", "value1"); NaturalKeyDescriptor naturalKeyDescriptor2 = new NaturalKeyDescriptor(naturalKeysForConstructor2, testTenantId, testEntityType, null); int hashCode2 = naturalKeyDescriptor2.hashCode(); assertEquals(-741620770, hashCode2); Map<String, String> naturalKeysForConstructor3 = new HashMap<String, String>(); naturalKeysForConstructor3.put("key1", "value1"); naturalKeysForConstructor3.put("key2", "value3"); NaturalKeyDescriptor naturalKeyDescriptor3 = new NaturalKeyDescriptor(naturalKeysForConstructor3, testTenantId, testEntityType, null); int hashCode3 = naturalKeyDescriptor3.hashCode(); assertEquals(1601383371, hashCode3); Map<String, String> naturalKeysForConstructor4 = new HashMap<String, String>(); naturalKeysForConstructor4.put("key1", "value1"); naturalKeysForConstructor4.put("key3", "value2"); NaturalKeyDescriptor naturalKeyDescriptor4 = new NaturalKeyDescriptor(naturalKeysForConstructor4, testTenantId, testEntityType, null); int hashCode4 = naturalKeyDescriptor4.hashCode(); assertEquals(1601585983, hashCode4); NaturalKeyDescriptor naturalKeyDescriptor5 = new NaturalKeyDescriptor(null, testTenantId, testEntityType, null); int hashCode5 = naturalKeyDescriptor5.hashCode(); assertEquals(1210291732, hashCode5); NaturalKeyDescriptor naturalKeyDescriptor6 = new NaturalKeyDescriptor(naturalKeysForConstructor, "testTenantId6", testEntityType, null); int hashCode6 = naturalKeyDescriptor6.hashCode(); assertEquals(326979664, hashCode6); NaturalKeyDescriptor naturalKeyDescriptor7 = new NaturalKeyDescriptor(naturalKeysForConstructor, null, testEntityType, null); int hashCode7 = naturalKeyDescriptor7.hashCode(); assertEquals(784924841, hashCode7); NaturalKeyDescriptor naturalKeyDescriptor8 = new NaturalKeyDescriptor(naturalKeysForConstructor, testTenantId, "testEntityType8", null); int hashCode8 = naturalKeyDescriptor8.hashCode(); assertEquals(-1831432182, hashCode8); NaturalKeyDescriptor naturalKeyDescriptor9 = new NaturalKeyDescriptor(naturalKeysForConstructor, testTenantId, null, null); int hashCode9 = naturalKeyDescriptor9.hashCode(); assertEquals(1286366237, hashCode9); NaturalKeyDescriptor naturalKeyDescriptor10 = new NaturalKeyDescriptor(naturalKeysForConstructor, testTenantId, null, "parentId1"); int hashCode10 = naturalKeyDescriptor10.hashCode(); assertEquals(-938294903, hashCode10); }
|
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); }
|
@Test public void testGetContainerDocument() { final Map<String, ContainerDocument> testContainer = createContainerMap(); testHolder = new ContainerDocumentHolder(testContainer); assertEquals(testContainer.get("test"), testHolder.getContainerDocument("test")); }
|
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); }
|
@Test public void testIsContainerDocument() { final Map<String, ContainerDocument> testContainer = createContainerMap(); testHolder = new ContainerDocumentHolder(testContainer); assertFalse(testHolder.isContainerDocument("foo")); assertTrue(testHolder.isContainerDocument("test")); }
|
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); }
|
@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")); }
|
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); }
|
@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)); }
|
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); }
|
@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)); }
|
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); }
|
@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")); }
|
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; }
|
@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)); }
|
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; }
|
@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)); }
|
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; }
|
@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)); }
|
SliSchemaVersionValidator { protected List<MigrationStrategy> getMigrationStrategies(String entityType, int entityVersionNumber, int newVersionNumber) { Map<String, List<MigrationStrategy>> entityMigrations = migrationStrategyMap.get(entityType); List<MigrationStrategy> allStrategies = new LinkedList<MigrationStrategy>(); if (entityMigrations != null) { for (Integer version = entityVersionNumber+1; version <= newVersionNumber; version++) { List<MigrationStrategy> strategies = entityMigrations.get(version.toString()); if (strategies != null) { allStrategies.addAll(strategies); } } if (!allStrategies.isEmpty()) { return allStrategies; } } return NO_STRATEGIES_DEFINED; } 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; }
|
@Test public void testGetMigrationStrategies() { initMockMigration(); Entity entity = new MongoEntity("staff", new HashMap<String, Object>()); List<MigrationStrategy> strategies = sliSchemaVersionValidator.getMigrationStrategies("staff", 0, 2); assertEquals("Should match", 1, strategies.size()); assertTrue("Should be true", strategies.get(0) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(0).migrate(entity), "somefield", "somevalue")); entity = new MongoEntity("staff", new HashMap<String, Object>()); strategies = sliSchemaVersionValidator.getMigrationStrategies("staff", 0, 3); assertEquals("Should match", 2, strategies.size()); assertTrue("Should be true", strategies.get(0) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(0).migrate(entity), "somefield", "somevalue")); assertTrue("Should be true", strategies.get(1) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(1).migrate(entity), "favoriteColor", "yellow")); entity = new MongoEntity("staff", new HashMap<String, Object>()); strategies = sliSchemaVersionValidator.getMigrationStrategies("staff", 0, 4); assertEquals("Should match", 3, strategies.size()); assertTrue("Should be true", strategies.get(0) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(0).migrate(entity), "somefield", "somevalue")); assertTrue("Should be true", strategies.get(1) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(1).migrate(entity), "favoriteColor", "yellow")); assertTrue("Should be true", strategies.get(2) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(2).migrate(entity), "mascot", "red")); entity = new MongoEntity("staff", new HashMap<String, Object>()); strategies = sliSchemaVersionValidator.getMigrationStrategies("staff", 3, 4); assertEquals("Should match", 1, strategies.size()); assertTrue("Should be true", strategies.get(0) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(0).migrate(entity), "mascot", "red")); strategies = sliSchemaVersionValidator.getMigrationStrategies("staff", 0, 1); assertEquals("Should match", 0, strategies.size()); entity = new MongoEntity("staff", new HashMap<String, Object>()); strategies = sliSchemaVersionValidator.getMigrationStrategies("staff", 2, 4); assertEquals("Should match", 2, strategies.size()); assertTrue("Should be true", strategies.get(0) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(0).migrate(entity), "favoriteColor", "yellow")); assertTrue("Should be true", strategies.get(1) instanceof AddStrategy); assertTrue("Should be true", checkEntity((Entity) strategies.get(1).migrate(entity), "mascot", "red")); strategies = sliSchemaVersionValidator.getMigrationStrategies("staff", 3, 1); assertEquals("Should match", 0, strategies.size()); }
|
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(); }
|
@Test public void testLoadNonExistentFile() { String testFile = "nonExistent"; InputStream in = getClass().getResourceAsStream(testFile); String out = aggregationLoader.loadJavascriptFile(in); assertEquals("", out); }
|
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); }
|
@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()); }
|
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); }
|
@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"); }
|
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); }
|
@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()); }
|
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); }
|
@Test public void testGetChildren() throws Exception { List<String> children = nodeService.getChildren("local_test", "/test"); Assert.assertNotNull(children); Assert.assertEquals(0, children.size()); }
|
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(); }
|
@Test public void testAll() throws Exception { List<Cluster> clusters = clusterAdminService.all(); Assert.assertNotNull(clusters); Assert.assertEquals(1, clusters.size()); }
|
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); }
|
@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); }
|
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); }
|
@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()); }
|
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); }
|
@Test public void testAddMember() throws Exception { }
|
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); }
|
@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()); }
|
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); }
|
@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()); }
|
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); }
|
@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()); }
|
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); }
|
@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()); }
|
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); }
|
@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()); }
|
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); }
|
@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()); }
|
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); }
|
@Test public void testGetData() throws Exception { String data = nodeService.getData("local_test", "/test"); Assert.assertNull(data); }
|
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); }
|
@Test public void testUpdateStatus() throws Exception { long id = 3; Status status = Status.DELETE; int updateResult = teamService.updateStatus(id, status); Assert.assertEquals(RESULT_OK, updateResult); }
|
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); }
|
@Test public void testAgreeJoin() throws Exception { }
|
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); }
|
@Test public void testRefuseJoin() throws Exception { }
|
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); }
|
@Test public void testUpdateRole() throws Exception { long id = 3; Role role = Role.MEMBER; int updateResult = teamService.updateRole(id, role); Assert.assertEquals(RESULT_OK, updateResult); }
|
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); }
|
@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); }
|
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); }
|
@Test public void testIsMaster() throws Exception { long userId = 1; long teamId = 1; boolean isMaster = teamService.isMaster(userId, teamId); Assert.assertEquals(true, isMaster); }
|
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); }
|
@Test public void testIsOwner() throws Exception { long userId = 1; long teamId = 1; boolean isOwner = teamService.isOwner(userId, teamId); Assert.assertEquals(true, isOwner); }
|
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); }
|
@Test public void testIsAdmin() throws Exception { long userId = 1; boolean isAdmin = teamService.isAdmin(userId); Assert.assertEquals(true, isAdmin); }
|
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); }
|
@Test public void testCreate() throws Exception { }
|
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); }
|
@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); }
|
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); }
|
@Test public void testUpdate() throws Exception { int result = reviewService.update(ReviewStatus.ACCEPTED, 1L, "reviewer", 0L, 0L); Assert.assertNotEquals(0, result); }
|
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); }
|
@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); }
|
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); }
|
@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); }
|
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); }
|
@Test public void testGet() throws Exception { ReviewRequest reviewRequest = reviewService.get(1); Assert.assertNotNull(reviewRequest); }
|
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); }
|
@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())); }
|
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); }
|
@Test public void testDelete() throws Exception { int result = reviewService.delete(1); Assert.assertEquals(RESULT_OK, result); }
|
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); }
|
@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()); }
|
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); }
|
@Test public void testGetById() throws Exception { Snapshot snapshot = snapshotService.getById(1); Assert.assertNotNull(snapshot); }
|
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); }
|
@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()); }
|
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); }
|
@Test public void testCreate() throws Exception { String name = "test_user"; User user = userService.create(name); Assert.assertEquals(4, user.getId()); }
|
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); }
|
@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()); }
|
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); }
|
@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()); }
|
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); }
|
@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()); }
|
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); }
|
@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); }
|
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); }
|
@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); }
|
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); }
|
@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); }
|
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); }
|
@Test public void testListPermissionTeamsAgree() throws Exception { List<PermissionTeam> permissionTeams = permissionService.listPermissionTeamsAgree(); Assert.assertNotNull(permissionTeams); Assert.assertEquals(1, permissionTeams.size()); }
|
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); }
|
@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()); }
|
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); }
|
@Test public void testCreate() throws Exception { nodeService.create("local_test", "/test", "data", "creator"); }
|
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); }
|
@Test public void testListPermissionTeamsPending() throws Exception { List<PermissionTeam> permissionTeams = permissionService.listPermissionTeamsPending(); Assert.assertNotNull(permissionTeams); Assert.assertEquals(1, permissionTeams.size()); }
|
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); }
|
@Test public void testUpdateStatus() throws Exception { int id = 3; Status status = Status.AGREE; int updateResult = permissionService.updateStatus(id, status); Assert.assertEquals(RESULT_OK, updateResult); }
|
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); }
|
@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); }
|
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); }
|
@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); }
|
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); }
|
@Test public void testUpdate() throws Exception { nodeService.update("local_test", "/test", "", ""); }
|
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); }
|
@Test public void testDelete() throws Exception { nodeService.delete("local_test", "/test", ""); }
|
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(); }
|
@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"); }
|
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(); }
|
@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"); }
|
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(); }
|
@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); }
|
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; }
|
@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); } }
|
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; }
|
@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)); } }
|
FileBufferPoolFactory extends IoBufferPoolFactory { @Override public int getPriority() { return -100; } @Override IoBufferPool get(); @Override int getPriority(); }
|
@Test public void testPriority() { assertTrue(new FileBufferPoolFactory().getPriority() < 0); }
|
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; }
|
@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) { } }
|
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; }
|
@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); }
|
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); } }
|
@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); }
|
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; } }
|
@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) { } }
|
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; }
|
@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) { } }
|
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; }
|
@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) { } }
|
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; }
|
@Test public void testClone() { ZipEntry clone = entry.clone(); assertNotSame(clone, entry); }
|
DefaultExtraField extends ExtraField { @Override int getDataSize() { final byte[] data = this.data; return null != data ? data.length : 0; } DefaultExtraField(final int headerId); }
|
@Test public void testGetDataSize() { assertEquals(0, field.getDataSize()); }
|
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(); }
|
@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) { } } }
|
TApplication { @SuppressWarnings("NoopMethodInAbstractClass") protected void setup() { } }
|
@Test public void testSetup() { instance.setup(); }
|
TApplication { protected abstract int work(String[] args) throws E; }
|
@Test public void testWork() { try { instance.work(null); } catch (NullPointerException expected) { } assertEquals(0, instance.work(new String[0])); }
|
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; }
|
@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)); } }
|
FsNodePath implements Serializable, Comparable<FsNodePath> { public static FsNodePath create(URI uri) { return create(uri, NULL); } FsNodePath(File file); @ConstructorProperties("uri") FsNodePath(URI uri); FsNodePath(URI uri, FsUriModifier modifier); FsNodePath(
final @CheckForNull FsMountPoint mountPoint,
final FsNodeName nodeName); static FsNodePath create(URI uri); static FsNodePath create(URI uri, FsUriModifier modifier); URI getUri(); URI toHierarchicalUri(); @Nullable FsMountPoint getMountPoint(); FsNodeName getNodeName(); FsNodePath resolve(final FsNodeName nodeName); @Override int compareTo(FsNodePath that); @Override boolean equals(@CheckForNull Object that); @Override int hashCode(); @Override String toString(); }
|
@Test @SuppressWarnings("ResultOfObjectAllocationIgnored") public void testConstructorWithInvalidUri() throws URISyntaxException { try { FsNodePath.create((URI) null); fail(); } catch (NullPointerException expected) { } try { new FsNodePath((URI) null); fail(); } catch (NullPointerException expected) { } try { FsNodePath.create((URI) null, NULL); fail(); } catch (NullPointerException expected) { } try { new FsNodePath((URI) null, NULL); fail(); } catch (NullPointerException expected) { } try { FsNodePath.create((URI) null, CANONICALIZE); fail(); } catch (NullPointerException expected) { } try { new FsNodePath((URI) null, CANONICALIZE); fail(); } catch (NullPointerException expected) { } try { new FsNodePath((FsMountPoint) null, null); fail(); } catch (NullPointerException expected) { } 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:", "foo:bar:/", "foo:bar:/baz", "foo:bar:/baz!", "foo:bar:/baz/", "foo:bar:/baz! "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 { FsNodePath.create(uri); fail(param); } catch (IllegalArgumentException expected) { } try { new FsNodePath(uri); fail(param); } catch (URISyntaxException expected) { } } }
@Test @SuppressWarnings("ResultOfObjectAllocationIgnored") public void testConstructorWithValidUri() { for (final String[] params : new String[][] { { "foo:bar:baz:/bä%20ng!/bö%20öm!/plö%20nk", "foo:bar:baz:/bä%20ng!/bö%20öm!/", "plö%20nk" }, { "foo:bar:baz:/bäng!/bööm!/plönk", "foo:bar:baz:/bäng!/bööm!/", "plönk" }, { "foo:bar:baz:/bang!/boom!/plonk", "foo:bar:baz:/bang!/boom!/", "plonk" }, { "foo:bar:baz:/bang!/boom!/", "foo:bar:baz:/bang!/boom!/", "" }, { "foo:bar:/baz!/bang/../", "foo:bar:/baz!/", "" }, { "foo:bar:/baz!/bang/..", "foo:bar:/baz!/", "" }, { "foo:bar:/baz!/bang", "foo:bar:/baz!/", "bang" }, { "foo:bar:/baz!/./", "foo:bar:/baz!/", "" }, { "foo:bar:/baz!/.", "foo:bar:/baz!/", "" }, { "foo:bar:/baz!/", "foo:bar:/baz!/", "" }, { "foo:bar:/baz?bang!/?plonk", "foo:bar:/baz?bang!/", "?plonk" }, { "foo:bar:/baz!/bang/..", "foo:bar:/baz!/", "" }, { "foo:bar:/baz!/bang/../", "foo:bar:/baz!/", "" }, { "", null, "", }, { "foo", null, "foo" }, { "foo/..", null, "" }, { "foo/../", null, "" }, { "foo/bar", null, "foo/bar" }, { "foo:/", "foo:/", "" }, { "foo:/bar", "foo:/", "bar" }, { "foo:/bar/", "foo:/", "bar" }, { "foo:/bar { "foo:/bar/.", "foo:/", "bar" }, { "foo:/bar/./", "foo:/", "bar" }, { "foo:/bar/..", "foo:/", "" }, { "foo:/bar/../", "foo:/", "" }, { "foo:/bar/baz", "foo:/bar/", "baz" }, { "foo:/bar/baz?bang", "foo:/bar/", "baz?bang" }, { "foo:/bar/baz/", "foo:/bar/", "baz" }, { "foo:/bar/baz/?bang", "foo:/bar/", "baz?bang" }, { "file: { "file: { "file: { "file:/foo/c%3A { "file: { "file:/c: { "file:/c%3A", "file:/", "c%3A" }, { "föö/", null, "föö" }, { "/föö", null, "föö" }, { " { " { "/föö/", null, "föö" }, { "/C%3A/", null, "C%3A" }, { "C%3A/", null, "C%3A" }, }) { FsNodePath path = FsNodePath.create(URI.create(params[0]), CANONICALIZE); final FsMountPoint mountPoint = null == params[1] ? null : FsMountPoint.create(URI.create(params[1])); final FsNodeName nodeName = FsNodeName.create(URI.create(params[2])); assertPath(path, mountPoint, nodeName); path = new FsNodePath(mountPoint, nodeName); assertPath(path, mountPoint, nodeName); } }
|
FsNodePath implements Serializable, Comparable<FsNodePath> { public URI toHierarchicalUri() { final URI hierarchical = this.hierarchical; if (null != hierarchical) return hierarchical; if (uri.isOpaque()) { final URI mpu = mountPoint.toHierarchicalUri(); final URI enu = nodeName.getUri(); try { return this.hierarchical = enu.toString().isEmpty() ? mpu : new UriBuilder(mpu, true) .path(mpu.getRawPath() + FsNodeName.SEPARATOR) .getUri() .resolve(enu); } catch (URISyntaxException ex) { throw new AssertionError(ex); } } else { return this.hierarchical = uri; } } FsNodePath(File file); @ConstructorProperties("uri") FsNodePath(URI uri); FsNodePath(URI uri, FsUriModifier modifier); FsNodePath(
final @CheckForNull FsMountPoint mountPoint,
final FsNodeName nodeName); static FsNodePath create(URI uri); static FsNodePath create(URI uri, FsUriModifier modifier); URI getUri(); URI toHierarchicalUri(); @Nullable FsMountPoint getMountPoint(); FsNodeName getNodeName(); FsNodePath resolve(final FsNodeName nodeName); @Override int compareTo(FsNodePath that); @Override boolean equals(@CheckForNull Object that); @Override int hashCode(); @Override String toString(); }
|
@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" }, { "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" }, { "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" }, { "bar:baz:/boom?plonk!/bang?zonk", "baz:/boom/bang?zonk" }, { "bar:baz:/boom?plonk!/?zonk", "baz:/boom/?zonk" }, { "bar:baz:/boom?plonk!/bang", "baz:/boom/bang" }, { "bar:baz:/boom?plonk!/", "baz:/boom?plonk" }, { "foo:bar:baz:/boom!/bang!/", "baz:/boom/bang" }, { "bar:baz:/boom!/bang", "baz:/boom/bang" }, { "foo:bar:/baz?boom!/", "bar:/baz?boom" }, { "bar:/baz?boom", "bar:/baz?boom" }, { "foo:bar:/baz!/", "bar:/baz" }, { "bar:/baz", "bar:/baz" }, { "foo:/bar/?boom", "foo:/bar/?boom" }, { "bar?boom", "bar?boom" }, { "foo:/bar/", "foo:/bar/" }, { "bar", "bar" }, }) { final FsNodePath path = FsNodePath.create(URI.create(params[0])); final URI hierarchical = path.toHierarchicalUri(); assertThat(hierarchical, equalTo(URI.create(params[1]))); } }
|
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; }
|
@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) { } } }
|
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; }
|
@Test public void testIsRoot() { for (final Object params[] : new Object[][] { { "", true }, { "?", false, }, }) { assertThat(FsNodeName.create(URI.create(params[0].toString())).isRoot(), is(params[1])); } }
|
FsMountPoint implements Serializable, Comparable<FsMountPoint> { public static FsMountPoint create(URI uri) { return create(uri, NULL); } @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; }
|
@Test @SuppressWarnings("ResultOfObjectAllocationIgnored") public void testConstructorWithInvalidUri() throws URISyntaxException { try { FsMountPoint.create((URI) null); fail(); } catch (NullPointerException expected) { } try { new FsMountPoint((URI) null); fail(); } catch (NullPointerException expected) { } try { FsMountPoint.create((URI) null, NULL); fail(); } catch (NullPointerException expected) { } try { new FsMountPoint((URI) null, NULL); fail(); } catch (NullPointerException expected) { } try { FsMountPoint.create((URI) null, CANONICALIZE); fail(); } catch (NullPointerException expected) { } try { new FsMountPoint((URI) null, CANONICALIZE); fail(); } catch (NullPointerException expected) { } try { FsMountPoint.create((FsScheme) null, null); fail(); } catch (NullPointerException expected) { } try { new FsMountPoint((FsScheme) null, null); fail(); } catch (NullPointerException expected) { } for (final String param : new String[] { "foo:/?queryDefined", "foo:bar:baz:/!/!/", "foo", "foo/bar", "foo/bar/", "/foo", "/foo/bar", "/foo/bar/", " "/../foo", "foo:/bar#baz", "foo:/bar/#baz", "foo:/bar", "foo:/bar?baz", "foo:/bar "foo:/bar/.", "foo:/bar/./", "foo:/bar/..", "foo:/bar/../", "foo:bar!/", "foo:bar:baz!/", "foo:bar:/baz! "foo:bar:/baz!/.", "foo:bar:/baz!/./", "foo:bar:/baz!/..", "foo:bar:/baz!/../", "foo:bar:/baz!/bang", "foo:bar:/baz!/#bang", "foo:bar:/baz/!/", "foo:bar:baz:/bang!/!/", }) { final URI uri = URI.create(param); try { FsMountPoint.create(uri); fail(param); } catch (IllegalArgumentException expected) { } try { new FsMountPoint(uri); fail(param); } catch (URISyntaxException expected) { } } for (final String[] params : new String[][] { { "foo", "bar:baz:/bang!/" }, { "foo", "bar:/baz/" }, }) { final FsScheme scheme = FsScheme.create(params[0]); final FsNodePath path = FsNodePath.create(URI.create(params[1])); try { new FsMountPoint(scheme, path); fail(params[0] + ":" + params[1] + "!/"); } catch (URISyntaxException expected) { } } }
|
FsMountPoint implements Serializable, Comparable<FsMountPoint> { public FsNodePath resolve(FsNodeName name) { return new FsNodePath(this, name); } @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; }
|
@Test public void testResolve() { for (final String[] params : new String[][] { { "foo:bar:/baz?plonk!/", "", "baz", "foo:bar:/baz?plonk!/" }, { "foo:bar:/bäz?bööm!/", "bäng?plönk", "bäz/bäng?plönk", "foo:bar:/bäz?bööm!/bäng?plönk" }, { "foo:bar:/baz!/", "bang?boom", "baz/bang?boom", "foo:bar:/baz!/bang?boom" }, { "foo:bar:/baz!/", "bang", "baz/bang", "foo:bar:/baz!/bang" }, { "foo:bar:/baz!/", "", "baz", "foo:bar:/baz!/" }, { "foo:bar:/baz?plonk!/", "bang?boom", "baz/bang?boom", "foo:bar:/baz?plonk!/bang?boom" }, { "foo:bar:/baz?plonk!/", "bang", "baz/bang", "foo:bar:/baz?plonk!/bang" }, { "foo:/bar/", "baz?bang", null, "foo:/bar/baz?bang" }, { "foo:/bar/", "baz", null, "foo:/bar/baz" }, { "foo:/bar/", "", null, "foo:/bar/" }, { "foo:/bar/", "baz", null, "foo:/bar/baz" }, }) { final FsMountPoint mountPoint = FsMountPoint.create(URI.create(params[0])); final FsNodeName entryName = FsNodeName.create(URI.create(params[1])); final FsNodeName parentEntryName = null == params[2] ? null : FsNodeName.create(URI.create(params[2])); final FsNodePath path = FsNodePath.create(URI.create(params[3])); if (null != parentEntryName) assertThat(mountPoint.getPath().resolve(entryName).getNodeName(), equalTo(parentEntryName)); assertThat(mountPoint.resolve(entryName), equalTo(path)); assertThat(mountPoint.resolve(entryName).getUri().isAbsolute(), is(true)); } }
|
User implements Serializable { public User(final String login, final String password) { this.login = login; this.password = password; } User(final String login, final String password); final void setLocale(final String locale); final Date getLastUpdate(); final void setLastUpdate(final Date lastUpdate); final void setDatePattern(final String datePattern); final String getLanguage(); final String getCountry(); final JsonObject getJSONObject(); }
|
@Test public void testUser() { String login = "carl"; String password = "mypassword"; String email = "mail@gmail.com"; User user = User.builder().login(login).password(password).email(email).build(); assertEquals(login, user.getLogin()); assertEquals(email, user.getEmail()); }
|
Portfolio { public final Optional<Account> getAccount(final String name) { return accounts == null ? Optional.empty() : accounts.stream().filter(account -> account.getName().equals(name)).findFirst(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetAccountByName() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getAccount(FIDELITY); assertTrue(actual.isPresent()); }
@Test public void testGetAccountById() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getAccount(2); assertTrue(actual.isPresent()); }
@Test public void testGetAccountByIdEmpty() { Optional<Account> actual = portfolio.getAccount(2); assertFalse(actual.isPresent()); }
|
Portfolio { public final Optional<Account> getFirstAccount() { return accounts == null ? Optional.empty() : accounts.stream().filter(account -> !account.getDel()).findFirst(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetFirstAccount() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getFirstAccount(); assertTrue(actual.isPresent()); }
|
Portfolio { protected Map<String, List<Equity>> getSectorByCompanies() { final Map<String, List<Equity>> map = new TreeMap<>(); List<Equity> companies; for (final Equity equity : getEquities()) { if (equity.getCompany().getFund()) { companies = map.getOrDefault(Constants.FUND, new ArrayList<>()); companies.add(equity); map.putIfAbsent(Constants.FUND, companies); } else { final String sector = equity.getCurrentSector(); if (StringUtils.isEmpty(sector)) { companies = map.getOrDefault(Constants.UNKNOWN, new ArrayList<>()); companies.add(equity); map.putIfAbsent(Constants.UNKNOWN, companies); } else { companies = map.getOrDefault(sector, new ArrayList<>()); companies.add(equity); map.putIfAbsent(sector, companies); } } } return map; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetSectorByCompanies() { portfolio.setEquities(createEquities()); Map<String, List<Equity>> actual = portfolio.getSectorByCompanies(); assertNotNull(actual); assertThat(actual.size(), is(3)); assertTrue(actual.containsKey(FUND)); assertTrue(actual.containsKey(UNKNOWN)); assertTrue(actual.containsKey(HIGH_TECH)); }
|
Portfolio { public final String getHTMLSectorByCompanies() { final Map<String, List<Equity>> map = getSectorByCompanies(); return extractHTMLfromMap(map); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetHTMLSectorByCompanies() { portfolio.setEquities(createEquities()); String actual = portfolio.getHTMLSectorByCompanies(); verifyHTML(actual); }
|
Portfolio { protected Map<String, List<Equity>> getGapByCompanies() { final Map<String, List<Equity>> map = new TreeMap<>(); List<Equity> companies; for (final Equity equity : getEquities()) { if (equity.getMarketCapitalizationType().getValue() == null || equity.getCompany().getFund()) { equity.setMarketCapitalizationType(MarketCapitalization.UNKNOWN); } companies = map.getOrDefault(equity.getMarketCapitalizationType().getValue(), new ArrayList<>()); companies.add(equity); map.put(equity.getMarketCapitalizationType().getValue(), companies); } return map; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetGapByCompanies() { portfolio.setEquities(createEquities()); Map<String, List<Equity>> actual = portfolio.getGapByCompanies(); assertNotNull(actual); assertThat(actual.size(), is(3)); assertTrue(actual.containsKey(LARGE_CAP.getValue())); assertTrue(actual.containsKey(MEGA_CAP.getValue())); assertTrue(actual.containsKey(UNKNOWN)); }
|
Portfolio { public final String getHTMLCapByCompanies() { final Map<String, List<Equity>> map = getGapByCompanies(); return extractHTMLfromMap(map); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetHTMLCapByCompanies() { portfolio.setEquities(createEquities()); String actual = portfolio.getHTMLCapByCompanies(); verifyHTML(actual); }
|
Portfolio { public final Double getTotalValue() { return totalValue + getLiquidity(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetTotalValue() { Double actual = portfolio.getTotalValue(); assertEquals(0d, actual, 0.1); }
@Test public void testGetTotalValueWithLiquidity() { portfolio.setLiquidity(1000d); Double actual = portfolio.getTotalValue(); assertEquals(1000d, actual, 0.1); }
|
Portfolio { public final void compute() { Double totalUnitCostPrice = 0d; Double totalAverageQuotePrice = 0d; Double totalOriginalValue = 0d; totalVariation = 0d; double totalValueStart = 0; totalGainToday = 0d; Date lastUpdate = null; if (equities != null) { for (final Equity equity : equities) { totalQuantity += equity.getQuantity(); totalUnitCostPrice += equity.getUnitCostPrice(); totalAverageQuotePrice += equity.getCompany().getQuote() * equity.getParity(); totalValue += equity.getValue(); totalOriginalValue += equity.getQuantity() * equity.getUnitCostPrice() * equity.getCurrentParity(); yieldYear += equity.getYieldYear(); totalGain += equity.getPlusMinusUnitCostPriceValue(); if (equity.getCompany().getRealTime()) { if (lastUpdate == null) { lastUpdate = equity.getCompany().getLastUpdate(); } else { if (equity.getCompany().getLastUpdate() != null && lastUpdate.after(equity.getCompany().getLastUpdate())) { lastUpdate = equity.getCompany().getLastUpdate(); } } } if (equity.getCompany().getChange() != null) { double valueStart = equity.getValue() / (equity.getCompany().getChange() / PERCENT + 1); totalValueStart += valueStart; totalGainToday += valueStart * equity.getCompany().getChange() / PERCENT; } } totalVariation = totalValueStart == 0 ? totalValueStart : ((totalValueStart + totalGainToday) / totalValueStart - 1) * PERCENT; averageUnitCostPrice = totalUnitCostPrice / equities.size(); averageQuotePrice = totalAverageQuotePrice / equities.size(); totalPlusMinusValue = ((totalValue - totalOriginalValue) / totalOriginalValue) * PERCENT; yieldYearPerc = yieldYear / getTotalValue() * PERCENT; setLastCompanyUpdate(lastUpdate); } } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testCompute() { portfolio.setEquities(createEquities()); portfolio.compute(); assertEquals(66d, portfolio.getTotalQuantity(), 0.1); assertEquals(30500d, portfolio.getTotalValue(), 0.1); assertEquals(0d, portfolio.getYieldYear(), 0.1); assertEquals(12700d, portfolio.getTotalGain(), 0.1); assertNotNull(portfolio.getLastCompanyUpdate()); }
|
Portfolio { protected final Map<String, Double> getChartSectorData() { if (chartSectorData == null) { final Map<String, Double> data = new HashMap<>(); for (final Equity equity : getEquities()) { if (equity.getCompany().getFund()) { addEquityValueToMap(data, Constants.FUND, equity); } else { final String sector = equity.getCurrentSector(); if (StringUtils.isEmpty(sector)) { addEquityValueToMap(data, Constants.UNKNOWN, equity); } else { addEquityValueToMap(data, sector, equity); } } } chartSectorData = new TreeMap<>(); chartSectorData.putAll(data); } return chartSectorData; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetChartSectorData() { portfolio.setEquities(createEquities()); Map<String, Double> actual = portfolio.getChartSectorData(); assertNotNull(actual); assertEquals(25500d, actual.get(FUND), 0.1); assertEquals(4000d, actual.get(HIGH_TECH), 0.1); assertEquals(1000d, actual.get(UNKNOWN), 0.1); }
|
Portfolio { protected final Map<Date, Double> getChartShareValueData() { Map<Date, Double> data = new HashMap<>(); List<ShareValue> shareValuess = getShareValues(); int max = shareValuess.size(); double base = shareValuess.get(max - 1).getShareValue(); for (int i = max - 1; i != -1; i--) { ShareValue temp = shareValuess.get(i); Double value = temp.getShareValue() * PERCENT / base; data.put(temp.getDate(), value); } chartShareValueData = new TreeMap<>(); chartShareValueData.putAll(data); return chartShareValueData; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetChartShareValueData() { portfolio.setShareValues(createShareValues()); Map<Date, Double> actual = portfolio.getChartShareValueData(); assertNotNull(actual); assertThat(actual.size(), is(2)); Iterator<Date> iterator = actual.keySet().iterator(); assertEquals(100d, actual.get(iterator.next()), 0.1); assertEquals(50d, actual.get(iterator.next()), 0.1); }
|
Portfolio { protected final Map<String, Double> getChartCapData() { if (chartCapData == null) { Map<String, Double> data = new HashMap<>(); for (Equity equity : getEquities()) { if (!equity.getCompany().getFund()) { MarketCapitalization marketCap = equity.getMarketCapitalizationType(); if (marketCap == null) { addEquityValueToMap(data, Constants.UNKNOWN, equity); } else { addEquityValueToMap(data, marketCap.getValue(), equity); } } else { addEquityValueToMap(data, Constants.UNKNOWN, equity); } } chartCapData = new TreeMap<>(); chartCapData.putAll(data); } return chartCapData; } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetChartCapData() { portfolio.setEquities(createEquities()); Map<String, Double> actual = portfolio.getChartCapData(); assertNotNull(actual); assertEquals(1000d, actual.get(MEGA_CAP.getValue()), 0.1); assertEquals(4000d, actual.get(LARGE_CAP.getValue()), 0.1); assertEquals(25500d, actual.get(UNKNOWN), 0.1); }
|
Portfolio { public final List<String> getCompaniesYahooIdRealTime() { return getEquities().stream() .filter(equity -> equity.getCompany().getRealTime()) .map(equity -> equity.getCompany().getYahooId()) .collect(Collectors.toList()); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }
|
@Test public void testGetCompaniesYahooIdRealTime() { portfolio.setEquities(createEquities()); List<String> actual = portfolio.getCompaniesYahooIdRealTime(); assertNotNull(actual); assertThat(actual, containsInAnyOrder(GOOGLE, APPLE)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.